blob: 42d7733caeeb0dd9df10a4136f86d1554f283ebf [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 {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000187 // If not blank, set to the version of the sdk to compile against.
Jaewoong Jung26342642021-03-17 15:56:23 -0700188 // Defaults to compiling against the current platform.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000189 // Values are of one of the following forms:
190 // 1) numerical API level or "current"
191 // 2) An SDK kind with an API level: "<sdk kind>_<API level>". See
192 // build/soong/android/sdk_version.go for the complete and up to date list of
193 // SDK kinds. If the SDK kind value is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700194 Sdk_version *string
195
196 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000197 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700198 Min_sdk_version *string
199
satayev0a420e72021-11-29 17:25:52 +0000200 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
201 // Defaults to empty string "". See sdk_version for possible values.
202 Max_sdk_version *string
203
Jaewoong Jung26342642021-03-17 15:56:23 -0700204 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Target_sdk_version *string
207
208 // Whether to compile against the platform APIs instead of an SDK.
209 // If true, then sdk_version must be empty. The value of this field
210 // is ignored when module's type isn't android_app.
211 Platform_apis *bool
212
213 Aidl struct {
214 // Top level directories to pass to aidl tool
215 Include_dirs []string
216
217 // Directories rooted at the Android.bp file to pass to aidl tool
218 Local_include_dirs []string
219
220 // directories that should be added as include directories for any aidl sources of modules
221 // that depend on this module, as well as to aidl for this module.
222 Export_include_dirs []string
223
224 // whether to generate traces (for systrace) for this interface
225 Generate_traces *bool
226
227 // whether to generate Binder#GetTransaction name method.
228 Generate_get_transaction_name *bool
229
230 // list of flags that will be passed to the AIDL compiler
231 Flags []string
232 }
233
234 // If true, export a copy of the module as a -hostdex module for host testing.
235 Hostdex *bool
236
237 Target struct {
238 Hostdex struct {
239 // Additional required dependencies to add to -hostdex modules.
240 Required []string
241 }
242 }
243
244 // When targeting 1.9 and above, override the modules to use with --system,
245 // otherwise provides defaults libraries to add to the bootclasspath.
246 System_modules *string
247
Jaewoong Jung26342642021-03-17 15:56:23 -0700248 IsSDKLibrary bool `blueprint:"mutated"`
249
250 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
251 // Defaults to false.
252 V4_signature *bool
253
254 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
255 // public stubs library.
256 SyspropPublicStub string `blueprint:"mutated"`
257}
258
Jooyung Han01d80d82022-01-08 12:16:32 +0900259// Device properties that can be overridden by overriding module (e.g. override_android_app)
260type OverridableDeviceProperties struct {
261 // set the name of the output. If not set, `name` is used.
262 // To override a module with this property set, overriding module might need to set this as well.
263 // Otherwise, both the overridden and the overriding modules will have the same output name, which
264 // can cause the duplicate output error.
265 Stem *string
266}
267
Jaewoong Jung26342642021-03-17 15:56:23 -0700268// Functionality common to Module and Import
269//
270// It is embedded in Module so its functionality can be used by methods in Module
271// but it is currently only initialized by Import and Library.
272type embeddableInModuleAndImport struct {
273
274 // Functionality related to this being used as a component of a java_sdk_library.
275 EmbeddableSdkLibraryComponent
276}
277
Paul Duffin71b33cc2021-06-23 11:39:47 +0100278func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
279 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700280}
281
282// Module/Import's DepIsInSameApex(...) delegates to this method.
283//
284// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
285// the one provided by ApexModuleBase.
286func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
287 // dependencies other than the static linkage are all considered crossing APEX boundary
288 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
289 return true
290 }
291 return false
292}
293
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100294// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
295// or an invalid path describing the reason it is invalid.
296//
297// It is unset if a dex jar isn't applicable, i.e. no build rule has been
298// requested to create one.
299//
300// If a dex jar has been requested to be built then it is set, and it may be
301// either a valid android.Path, or invalid with a reason message. The latter
302// happens if the source that should produce the dex file isn't able to.
303//
304// E.g. it is invalid with a reason message if there is a prebuilt APEX that
305// could produce the dex jar through a deapexer module, but the APEX isn't
306// installable so doing so wouldn't be safe.
307type OptionalDexJarPath struct {
308 isSet bool
309 path android.OptionalPath
310}
311
312// IsSet returns true if a path has been set, either invalid or valid.
313func (o OptionalDexJarPath) IsSet() bool {
314 return o.isSet
315}
316
317// Valid returns true if there is a path that is valid.
318func (o OptionalDexJarPath) Valid() bool {
319 return o.isSet && o.path.Valid()
320}
321
322// Path returns the valid path, or panics if it's either not set or is invalid.
323func (o OptionalDexJarPath) Path() android.Path {
324 if !o.isSet {
325 panic("path isn't set")
326 }
327 return o.path.Path()
328}
329
330// PathOrNil returns the path if it's set and valid, or else nil.
331func (o OptionalDexJarPath) PathOrNil() android.Path {
332 if o.Valid() {
333 return o.Path()
334 }
335 return nil
336}
337
338// InvalidReason returns the reason for an invalid path, which is never "". It
339// returns "" for an unset or valid path.
340func (o OptionalDexJarPath) InvalidReason() string {
341 if !o.isSet {
342 return ""
343 }
344 return o.path.InvalidReason()
345}
346
347func (o OptionalDexJarPath) String() string {
348 if !o.isSet {
349 return "<unset>"
350 }
351 return o.path.String()
352}
353
354// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
355func makeUnsetDexJarPath() OptionalDexJarPath {
356 return OptionalDexJarPath{isSet: false}
357}
358
359// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
360// the given OptionalPath, which may be valid or invalid.
361func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
362 return OptionalDexJarPath{isSet: true, path: path}
363}
364
365// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
366// valid given path. It returns an unset OptionalDexJarPath if the given path is
367// nil.
368func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
369 if path == nil {
370 return makeUnsetDexJarPath()
371 }
372 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
373}
374
Jaewoong Jung26342642021-03-17 15:56:23 -0700375// Module contains the properties and members used by all java module types
376type Module struct {
377 android.ModuleBase
378 android.DefaultableModuleBase
379 android.ApexModuleBase
380 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800381 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700382
383 // Functionality common to Module and Import.
384 embeddableInModuleAndImport
385
386 properties CommonProperties
387 protoProperties android.ProtoProperties
388 deviceProperties DeviceProperties
389
Jooyung Han01d80d82022-01-08 12:16:32 +0900390 overridableDeviceProperties OverridableDeviceProperties
391
Jaewoong Jung26342642021-03-17 15:56:23 -0700392 // jar file containing header classes including static library dependencies, suitable for
393 // inserting into the bootclasspath/classpath of another compile
394 headerJarFile android.Path
395
396 // jar file containing implementation classes including static library dependencies but no
397 // resources
398 implementationJarFile android.Path
399
400 // jar file containing only resources including from static library dependencies
401 resourceJar android.Path
402
403 // args and dependencies to package source files into a srcjar
404 srcJarArgs []string
405 srcJarDeps android.Paths
406
407 // jar file containing implementation classes and resources including static library
408 // dependencies
409 implementationAndResourcesJar android.Path
410
411 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100412 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700413
414 // output file containing uninstrumented classes that will be instrumented by jacoco
415 jacocoReportClassesFile android.Path
416
417 // output file of the module, which may be a classes jar or a dex jar
418 outputFile android.Path
419 extraOutputFiles android.Paths
420
421 exportAidlIncludeDirs android.Paths
422
423 logtagsSrcs android.Paths
424
425 // installed file for binary dependency
426 installFile android.Path
427
Colin Cross3108ce12021-11-10 14:38:50 -0800428 // installed file for hostdex copy
429 hostdexInstallFile android.InstallPath
430
Jaewoong Jung26342642021-03-17 15:56:23 -0700431 // list of .java files and srcjars that was passed to javac
432 compiledJavaSrcs android.Paths
433 compiledSrcJars android.Paths
434
435 // manifest file to use instead of properties.Manifest
436 overrideManifest android.OptionalPath
437
438 // map of SDK version to class loader context
439 classLoaderContexts dexpreopt.ClassLoaderContextMap
440
441 // list of plugins that this java module is exporting
442 exportedPluginJars android.Paths
443
444 // list of plugins that this java module is exporting
445 exportedPluginClasses []string
446
447 // if true, the exported plugins generate API and require disabling turbine.
448 exportedDisableTurbine bool
449
450 // list of source files, collected from srcFiles with unique java and all kt files,
451 // will be used by android.IDEInfo struct
452 expandIDEInfoCompiledSrcs []string
453
454 // expanded Jarjar_rules
455 expandJarjarRules android.Path
456
Jaewoong Jung26342642021-03-17 15:56:23 -0700457 // Extra files generated by the module type to be added as java resources.
458 extraResources android.Paths
459
460 hiddenAPI
461 dexer
462 dexpreopter
463 usesLibrary
464 linter
465
466 // list of the xref extraction files
467 kytheFiles android.Paths
468
469 // Collect the module directory for IDE info in java/jdeps.go.
470 modulePaths []string
471
472 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900473
474 sdkVersion android.SdkSpec
475 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000476 maxSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700477}
478
Jiyong Park92315372021-04-02 08:45:46 +0900479func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
480 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900481 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700482 return nil
483 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900484 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000485 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700486 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
487 } else {
488 // Treat stable core platform as stable.
489 return nil
490 }
491 } else {
492 return fmt.Errorf("non stable SDK %v", sdkVersion)
493 }
494}
495
496// checkSdkVersions enforces restrictions around SDK dependencies.
497func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
498 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900499 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900500 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700501 ctx.PropertyErrorf("sdk_version",
502 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
503 }
504 }
505 }
506
507 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
508 // See rank() for details.
509 ctx.VisitDirectDeps(func(module android.Module) {
510 tag := ctx.OtherModuleDependencyTag(module)
511 switch module.(type) {
512 // TODO(satayev): cover other types as well, e.g. imports
513 case *Library, *AndroidLibrary:
514 switch tag {
515 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
516 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
517 }
518 }
519 })
520}
521
522func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900523 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700524 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900525 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700526 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000527 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 -0700528 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000529 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 -0700530 }
531
532 }
533}
534
535func (j *Module) addHostProperties() {
536 j.AddProperties(
537 &j.properties,
538 &j.protoProperties,
539 &j.usesLibraryProperties,
540 )
541}
542
543func (j *Module) addHostAndDeviceProperties() {
544 j.addHostProperties()
545 j.AddProperties(
546 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900547 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700548 &j.dexer.dexProperties,
549 &j.dexpreoptProperties,
550 &j.linter.properties,
551 )
552}
553
554func (j *Module) OutputFiles(tag string) (android.Paths, error) {
555 switch tag {
556 case "":
557 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
558 case android.DefaultDistTag:
559 return android.Paths{j.outputFile}, nil
560 case ".jar":
561 return android.Paths{j.implementationAndResourcesJar}, nil
562 case ".proguard_map":
563 if j.dexer.proguardDictionary.Valid() {
564 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
565 }
566 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
567 default:
568 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
569 }
570}
571
572var _ android.OutputFileProducer = (*Module)(nil)
573
574func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
575 initJavaModule(module, hod, false)
576}
577
578func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
579 initJavaModule(module, hod, true)
580}
581
582func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
583 multilib := android.MultilibCommon
584 if multiTargets {
585 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
586 } else {
587 android.InitAndroidArchModule(module, hod, multilib)
588 }
589 android.InitDefaultableModule(module)
590}
591
592func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
593 return j.properties.Instrument &&
594 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
595 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
596}
597
598func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
599 return j.shouldInstrument(ctx) &&
600 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
601 ctx.Config().UnbundledBuild())
602}
603
604func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
605 // Force enable the instrumentation for java code that is built for APEXes ...
606 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
607 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
608 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
609 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
610 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
611 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
612 return true
613 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
614 return true
615 }
616 }
617 return false
618}
619
Jiyong Park92315372021-04-02 08:45:46 +0900620func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
621 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700622}
623
Jiyong Parkf1691d22021-03-29 20:11:58 +0900624func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700625 return proptools.String(j.deviceProperties.System_modules)
626}
627
Jiyong Park92315372021-04-02 08:45:46 +0900628func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700629 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900630 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700631 }
Jiyong Park92315372021-04-02 08:45:46 +0900632 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700633}
634
satayev0a420e72021-11-29 17:25:52 +0000635func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
636 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
637 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
638 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
639 return android.SdkSpecFrom(ctx, maxSdkVersion)
640}
641
Jiyong Parkf1691d22021-03-29 20:11:58 +0900642func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900643 return j.minSdkVersion.Raw
644}
645
646func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
647 if j.deviceProperties.Target_sdk_version != nil {
648 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
649 }
650 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700651}
652
653func (j *Module) AvailableFor(what string) bool {
654 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
655 // Exception: for hostdex: true libraries, the platform variant is created
656 // even if it's not marked as available to platform. In that case, the platform
657 // variant is used only for the hostdex and not installed to the device.
658 return true
659 }
660 return j.ApexModuleBase.AvailableFor(what)
661}
662
663func (j *Module) deps(ctx android.BottomUpMutatorContext) {
664 if ctx.Device() {
665 j.linter.deps(ctx)
666
Jiyong Parkf1691d22021-03-29 20:11:58 +0900667 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700668
669 if j.deviceProperties.SyspropPublicStub != "" {
670 // This is a sysprop implementation library that has a corresponding sysprop public
671 // stubs library, and a dependency on it so that dependencies on the implementation can
672 // be forwarded to the public stubs library when necessary.
673 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
674 }
675 }
676
677 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
678 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
679
680 // Add dependency on libraries that provide additional hidden api annotations.
681 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
682
683 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
684 // Require java_sdk_library at inter-partition java dependency to ensure stable
685 // interface between partitions. If inter-partition java_library dependency is detected,
686 // raise build error because java_library doesn't have a stable interface.
687 //
688 // Inputs:
689 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
690 // if true, enable enforcement
691 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
692 // exception list of java_library names to allow inter-partition dependency
693 for idx := range j.properties.Libs {
694 if libDeps[idx] == nil {
695 continue
696 }
697
698 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
699 // java_sdk_library is always allowed at inter-partition dependency.
700 // So, skip check.
701 if _, ok := javaDep.(*SdkLibrary); ok {
702 continue
703 }
704
705 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
706 }
707 }
708 }
709
710 // For library dependencies that are component libraries (like stubs), add the implementation
711 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
712 for _, dep := range libDeps {
713 if dep != nil {
714 if component, ok := dep.(SdkLibraryComponentDependency); ok {
715 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100716 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100717 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
718 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100719 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700720 }
721 }
722 }
723 }
724
725 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
726 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
727 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
728
729 android.ProtoDeps(ctx, &j.protoProperties)
730 if j.hasSrcExt(".proto") {
731 protoDeps(ctx, &j.protoProperties)
732 }
733
734 if j.hasSrcExt(".kt") {
735 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
736 // Kotlin files
737 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
738 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
739 if len(j.properties.Plugins) > 0 {
740 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
741 }
742 }
743
744 // Framework libraries need special handling in static coverage builds: they should not have
745 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
746 // the same jacoco classes coming from different bootclasspath jars.
747 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
748 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
749 j.properties.Instrument = true
750 }
751 } else if j.shouldInstrumentStatic(ctx) {
752 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
753 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700754
755 if j.useCompose() {
756 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
757 "androidx.compose.compiler_compiler-hosted")
758 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700759}
760
761func hasSrcExt(srcs []string, ext string) bool {
762 for _, src := range srcs {
763 if filepath.Ext(src) == ext {
764 return true
765 }
766 }
767
768 return false
769}
770
771func (j *Module) hasSrcExt(ext string) bool {
772 return hasSrcExt(j.properties.Srcs, ext)
773}
774
775func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
776 aidlIncludeDirs android.Paths) (string, android.Paths) {
777
778 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
779 aidlIncludes = append(aidlIncludes,
780 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
781 aidlIncludes = append(aidlIncludes,
782 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
783
784 var flags []string
785 var deps android.Paths
786
787 flags = append(flags, j.deviceProperties.Aidl.Flags...)
788
789 if aidlPreprocess.Valid() {
790 flags = append(flags, "-p"+aidlPreprocess.String())
791 deps = append(deps, aidlPreprocess.Path())
792 } else if len(aidlIncludeDirs) > 0 {
793 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
794 }
795
796 if len(j.exportAidlIncludeDirs) > 0 {
797 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
798 }
799
800 if len(aidlIncludes) > 0 {
801 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
802 }
803
804 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
805 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
806 flags = append(flags, "-I"+src.String())
807 }
808
809 if Bool(j.deviceProperties.Aidl.Generate_traces) {
810 flags = append(flags, "-t")
811 }
812
813 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
814 flags = append(flags, "--transaction_names")
815 }
816
Jooyung Han07f70c02021-11-06 07:08:45 +0900817 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
818 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
819
Jaewoong Jung26342642021-03-17 15:56:23 -0700820 return strings.Join(flags, " "), deps
821}
822
823func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
824
825 var flags javaBuilderFlags
826
827 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900828 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700829
Cole Faust2b1536e2021-06-18 12:25:54 -0700830 epEnabled := j.properties.Errorprone.Enabled
831 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700832 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
833 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
834 }
835
836 errorProneFlags := []string{
837 "-Xplugin:ErrorProne",
838 "${config.ErrorProneChecks}",
839 }
840 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
841
842 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
843 "'" + strings.Join(errorProneFlags, " ") + "'"
844 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
845 }
846
847 // classpath
848 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
849 flags.classpath = append(flags.classpath, deps.classpath...)
850 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
851 flags.processorPath = append(flags.processorPath, deps.processorPath...)
852 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
853
854 flags.processors = append(flags.processors, deps.processorClasses...)
855 flags.processors = android.FirstUniqueStrings(flags.processors)
856
857 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900858 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700859 // Give host-side tools a version of OpenJDK's standard libraries
860 // close to what they're targeting. As of Dec 2017, AOSP is only
861 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
862 //
863 // When building with OpenJDK 8, the following should have no
864 // effect since those jars would be available by default.
865 //
866 // When building with OpenJDK 9 but targeting a version < 1.8,
867 // putting them on the bootclasspath means that:
868 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
869 // b) references to existing APIs are not reinterpreted in an
870 // OpenJDK 9-specific way, eg. calls to subclasses of
871 // java.nio.Buffer as in http://b/70862583
872 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
873 flags.bootClasspath = append(flags.bootClasspath,
874 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
875 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
876 if Bool(j.properties.Use_tools_jar) {
877 flags.bootClasspath = append(flags.bootClasspath,
878 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
879 }
880 }
881
882 // systemModules
883 flags.systemModules = deps.systemModules
884
885 // aidl flags.
886 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
887
888 return flags
889}
890
891func (j *Module) collectJavacFlags(
892 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
893 // javac flags.
894 javacFlags := j.properties.Javacflags
895
896 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
897 // For non-host binaries, override the -g flag passed globally to remove
898 // local variable debug info to reduce disk and memory usage.
899 javacFlags = append(javacFlags, "-g:source,lines")
900 }
901 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
902
903 if flags.javaVersion.usesJavaModules() {
904 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
905
906 if j.properties.Patch_module != nil {
907 // Manually specify build directory in case it is not under the repo root.
908 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
909 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200910 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700911
912 // b/150878007
913 //
914 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
915 // execution root for --patch-module. If this javac command line is
916 // invoked within Bazel's execution root working directory, the top
917 // level directories (e.g. libcore/, tools/, frameworks/) are all
918 // symlinks. JDK9 javac does not traverse into symlinks, which causes
919 // --patch-module to fail source file lookups when invoked in the
920 // execution root.
921 //
922 // Short of patching javac or enumerating *all* directories as possible
923 // input dirs, manually add the top level dir of the source files to be
924 // compiled.
925 topLevelDirs := map[string]bool{}
926 for _, srcFilePath := range srcFiles {
927 srcFileParts := strings.Split(srcFilePath.String(), "/")
928 // Ignore source files that are already in the top level directory
929 // as well as generated files in the out directory. The out
930 // directory may be an absolute path, which means srcFileParts[0] is the
931 // empty string, so check that as well. Note that "out" in Bazel's execution
932 // root is *not* a symlink, which doesn't cause problems for --patch-modules
933 // anyway, so it's fine to not apply this workaround for generated
934 // source files.
935 if len(srcFileParts) > 1 &&
936 srcFileParts[0] != "" &&
937 srcFileParts[0] != "out" {
938 topLevelDirs[srcFileParts[0]] = true
939 }
940 }
941 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
942
943 classPath := flags.classpath.FormJavaClassPath("")
944 if classPath != "" {
945 patchPaths = append(patchPaths, classPath)
946 }
947 javacFlags = append(
948 javacFlags,
949 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
950 }
951 }
952
953 if len(javacFlags) > 0 {
954 // optimization.
955 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
956 flags.javacFlags = "$javacFlags"
957 }
958
959 return flags
960}
961
962func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
963 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
964
965 deps := j.collectDeps(ctx)
966 flags := j.collectBuilderFlags(ctx, deps)
967
968 if flags.javaVersion.usesJavaModules() {
969 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
970 }
Sorin Basca9347ae32021-12-20 11:51:24 +0000971
Jaewoong Jung26342642021-03-17 15:56:23 -0700972 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
973 if hasSrcExt(srcFiles.Strings(), ".proto") {
974 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
975 }
976
977 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
978 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
979 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
980 }
981
982 srcFiles = j.genSources(ctx, srcFiles, flags)
983
984 // Collect javac flags only after computing the full set of srcFiles to
985 // ensure that the --patch-module lookup paths are complete.
986 flags = j.collectJavacFlags(ctx, flags, srcFiles)
987
988 srcJars := srcFiles.FilterByExt(".srcjar")
989 srcJars = append(srcJars, deps.srcJars...)
990 if aaptSrcJar != nil {
991 srcJars = append(srcJars, aaptSrcJar)
992 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700993 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700994
995 if j.properties.Jarjar_rules != nil {
996 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
997 }
998
999 jarName := ctx.ModuleName() + ".jar"
1000
1001 javaSrcFiles := srcFiles.FilterByExt(".java")
1002 var uniqueSrcFiles android.Paths
1003 set := make(map[string]bool)
1004 for _, v := range javaSrcFiles {
1005 if _, found := set[v.String()]; !found {
1006 set[v.String()] = true
1007 uniqueSrcFiles = append(uniqueSrcFiles, v)
1008 }
1009 }
1010
1011 // Collect .java files for AIDEGen
1012 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1013
1014 var kotlinJars android.Paths
1015
1016 if srcFiles.HasExt(".kt") {
1017 // user defined kotlin flags.
1018 kotlincFlags := j.properties.Kotlincflags
1019 CheckKotlincFlags(ctx, kotlincFlags)
1020
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001021 // Workaround for KT-46512
1022 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001023
1024 // If there are kotlin files, compile them first but pass all the kotlin and java files
1025 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1026 // won't emit any classes for them.
1027 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1028 if ctx.Device() {
1029 kotlincFlags = append(kotlincFlags, "-no-jdk")
1030 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001031
1032 for _, plugin := range deps.kotlinPlugins {
1033 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1034 }
1035 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1036
Jaewoong Jung26342642021-03-17 15:56:23 -07001037 if len(kotlincFlags) > 0 {
1038 // optimization.
1039 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1040 flags.kotlincFlags += "$kotlincFlags"
1041 }
1042
1043 var kotlinSrcFiles android.Paths
1044 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1045 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1046
1047 // Collect .kt files for AIDEGen
1048 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1049 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1050
1051 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1052 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1053
1054 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1055 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1056
1057 if len(flags.processorPath) > 0 {
1058 // Use kapt for annotation processing
1059 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1060 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1061 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1062 srcJars = append(srcJars, kaptSrcJar)
1063 kotlinJars = append(kotlinJars, kaptResJar)
1064 // Disable annotation processing in javac, it's already been handled by kapt
1065 flags.processorPath = nil
1066 flags.processors = nil
1067 }
1068
1069 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
1070 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1071 if ctx.Failed() {
1072 return
1073 }
1074
1075 // Make javac rule depend on the kotlinc rule
1076 flags.classpath = append(flags.classpath, kotlinJar)
1077
1078 kotlinJars = append(kotlinJars, kotlinJar)
1079 // Jar kotlin classes into the final jar after javac
1080 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1081 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
1082 }
1083 }
1084
1085 jars := append(android.Paths(nil), kotlinJars...)
1086
1087 // Store the list of .java files that was passed to javac
1088 j.compiledJavaSrcs = uniqueSrcFiles
1089 j.compiledSrcJars = srcJars
1090
1091 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001092 var headerJarFileWithoutDepsOrJarjar android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001093 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
1094 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1095 enableSharding = true
1096 // Formerly, there was a check here that prevented annotation processors
1097 // from being used when sharding was enabled, as some annotation processors
1098 // do not function correctly in sharded environments. It was removed to
1099 // allow for the use of annotation processors that do function correctly
1100 // with sharding enabled. See: b/77284273.
1101 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001102 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Jaewoong Jung26342642021-03-17 15:56:23 -07001103 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
1104 if ctx.Failed() {
1105 return
1106 }
1107 }
1108 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1109 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001110 if Bool(j.properties.Errorprone.Enabled) {
1111 // If error-prone is enabled, enable errorprone flags on the regular
1112 // build.
1113 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001114 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001115 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1116 // a new jar file just for compiling with the errorprone compiler to.
1117 // This is because we don't want to cause the java files to get completely
1118 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1119 // We also don't want to run this if errorprone is enabled by default for
1120 // this module, or else we could have duplicated errorprone messages.
1121 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001122 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001123
1124 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1125 "errorprone", "errorprone")
1126
Jaewoong Jung26342642021-03-17 15:56:23 -07001127 extraJarDeps = append(extraJarDeps, errorprone)
1128 }
1129
1130 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001131 if headerJarFileWithoutDepsOrJarjar != nil {
1132 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1133 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001134 shardSize := int(*(j.properties.Javac_shard_size))
1135 var shardSrcs []android.Paths
1136 if len(uniqueSrcFiles) > 0 {
1137 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1138 for idx, shardSrc := range shardSrcs {
1139 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1140 nil, flags, extraJarDeps)
1141 jars = append(jars, classes)
1142 }
1143 }
1144 if len(srcJars) > 0 {
1145 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1146 nil, srcJars, flags, extraJarDeps)
1147 jars = append(jars, classes)
1148 }
1149 } else {
1150 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1151 jars = append(jars, classes)
1152 }
1153 if ctx.Failed() {
1154 return
1155 }
1156 }
1157
1158 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1159
1160 var includeSrcJar android.WritablePath
1161 if Bool(j.properties.Include_srcs) {
1162 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1163 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1164 }
1165
1166 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1167 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1168 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1169 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1170
1171 var resArgs []string
1172 var resDeps android.Paths
1173
1174 resArgs = append(resArgs, dirArgs...)
1175 resDeps = append(resDeps, dirDeps...)
1176
1177 resArgs = append(resArgs, fileArgs...)
1178 resDeps = append(resDeps, fileDeps...)
1179
1180 resArgs = append(resArgs, extraArgs...)
1181 resDeps = append(resDeps, extraDeps...)
1182
1183 if len(resArgs) > 0 {
1184 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1185 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1186 j.resourceJar = resourceJar
1187 if ctx.Failed() {
1188 return
1189 }
1190 }
1191
1192 var resourceJars android.Paths
1193 if j.resourceJar != nil {
1194 resourceJars = append(resourceJars, j.resourceJar)
1195 }
1196 if Bool(j.properties.Include_srcs) {
1197 resourceJars = append(resourceJars, includeSrcJar)
1198 }
1199 resourceJars = append(resourceJars, deps.staticResourceJars...)
1200
1201 if len(resourceJars) > 1 {
1202 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1203 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1204 false, nil, nil)
1205 j.resourceJar = combinedJar
1206 } else if len(resourceJars) == 1 {
1207 j.resourceJar = resourceJars[0]
1208 }
1209
1210 if len(deps.staticJars) > 0 {
1211 jars = append(jars, deps.staticJars...)
1212 }
1213
1214 manifest := j.overrideManifest
1215 if !manifest.Valid() && j.properties.Manifest != nil {
1216 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1217 }
1218
1219 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1220 if len(services) > 0 {
1221 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1222 var zipargs []string
1223 for _, file := range services {
1224 serviceFile := file.String()
1225 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1226 }
1227 rule := zip
1228 args := map[string]string{
1229 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1230 }
1231 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1232 rule = zipRE
1233 args["implicits"] = strings.Join(services.Strings(), ",")
1234 }
1235 ctx.Build(pctx, android.BuildParams{
1236 Rule: rule,
1237 Output: servicesJar,
1238 Implicits: services,
1239 Args: args,
1240 })
1241 jars = append(jars, servicesJar)
1242 }
1243
1244 // Combine the classes built from sources, any manifests, and any static libraries into
1245 // classes.jar. If there is only one input jar this step will be skipped.
1246 var outputFile android.OutputPath
1247
1248 if len(jars) == 1 && !manifest.Valid() {
1249 // Optimization: skip the combine step as there is nothing to do
1250 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1251 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1252 // any if len(jars) == 1.
1253
1254 // Transform the single path to the jar into an OutputPath as that is required by the following
1255 // code.
1256 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1257 // The path contains an embedded OutputPath so reuse that.
1258 outputFile = moduleOutPath.OutputPath
1259 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1260 // The path is an OutputPath so reuse it directly.
1261 outputFile = outputPath
1262 } else {
1263 // The file is not in the out directory so create an OutputPath into which it can be copied
1264 // and which the following code can use to refer to it.
1265 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1266 ctx.Build(pctx, android.BuildParams{
1267 Rule: android.Cp,
1268 Input: jars[0],
1269 Output: combinedJar,
1270 })
1271 outputFile = combinedJar.OutputPath
1272 }
1273 } else {
1274 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1275 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1276 false, nil, nil)
1277 outputFile = combinedJar.OutputPath
1278 }
1279
1280 // jarjar implementation jar if necessary
1281 if j.expandJarjarRules != nil {
1282 // Transform classes.jar into classes-jarjar.jar
1283 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1284 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1285 outputFile = jarjarFile
1286
1287 // jarjar resource jar if necessary
1288 if j.resourceJar != nil {
1289 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1290 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1291 j.resourceJar = resourceJarJarFile
1292 }
1293
1294 if ctx.Failed() {
1295 return
1296 }
1297 }
1298
1299 // Check package restrictions if necessary.
1300 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001301 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001302 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001303
1304 // Create a rule to copy the output jar to another path and add a validate dependency that
1305 // will check that the jar only contains the permitted packages. The new location will become
1306 // the output file of this module.
1307 inputFile := outputFile
1308 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1309 ctx.Build(pctx, android.BuildParams{
1310 Rule: android.Cp,
1311 Input: inputFile,
1312 Output: outputFile,
1313 // Make sure that any dependency on the output file will cause ninja to run the package check
1314 // rule.
1315 Validation: pkgckFile,
1316 })
1317
1318 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001319 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001320
1321 if ctx.Failed() {
1322 return
1323 }
1324 }
1325
1326 j.implementationJarFile = outputFile
1327 if j.headerJarFile == nil {
1328 j.headerJarFile = j.implementationJarFile
1329 }
1330
1331 if j.shouldInstrumentInApex(ctx) {
1332 j.properties.Instrument = true
1333 }
1334
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001335 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1336 specs := j.jacocoModuleToZipCommand(ctx)
1337 if ctx.Failed() {
1338 return
1339 }
1340
Jaewoong Jung26342642021-03-17 15:56:23 -07001341 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001342 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001343 }
1344
1345 // merge implementation jar with resources if necessary
1346 implementationAndResourcesJar := outputFile
1347 if j.resourceJar != nil {
1348 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1349 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1350 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1351 false, nil, nil)
1352 implementationAndResourcesJar = combinedJar
1353 }
1354
1355 j.implementationAndResourcesJar = implementationAndResourcesJar
1356
1357 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1358 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1359 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1360 if j.dexProperties.Compile_dex == nil {
1361 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1362 }
1363 if j.deviceProperties.Hostdex == nil {
1364 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1365 }
1366 }
1367
1368 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1369 if j.hasCode(ctx) {
1370 if j.shouldInstrumentStatic(ctx) {
1371 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1372 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1373 }
1374 // Dex compilation
1375 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001376 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001377 if ctx.Failed() {
1378 return
1379 }
1380
Jaewoong Jung26342642021-03-17 15:56:23 -07001381 // merge dex jar with resources if necessary
1382 if j.resourceJar != nil {
1383 jars := android.Paths{dexOutputFile, j.resourceJar}
1384 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1385 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1386 false, nil, nil)
1387 if *j.dexProperties.Uncompress_dex {
1388 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1389 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1390 dexOutputFile = combinedAlignedJar
1391 } else {
1392 dexOutputFile = combinedJar
1393 }
1394 }
1395
Paul Duffin4de94502021-05-16 05:21:16 +01001396 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001397
1398 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001399
1400 // Encode hidden API flags in dex file, if needed.
1401 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1402
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001403 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001404
1405 // Dexpreopting
1406 j.dexpreopt(ctx, dexOutputFile)
1407
1408 outputFile = dexOutputFile
1409 } else {
1410 // There is no code to compile into a dex jar, make sure the resources are propagated
1411 // to the APK if this is an app.
1412 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001413 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001414 }
1415
1416 if ctx.Failed() {
1417 return
1418 }
1419 } else {
1420 outputFile = implementationAndResourcesJar
1421 }
1422
1423 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001424 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001425 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001426 return v.String()
1427 } else {
1428 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1429 }
1430 }
1431
1432 j.linter.name = ctx.ModuleName()
1433 j.linter.srcs = srcFiles
1434 j.linter.srcJars = srcJars
1435 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1436 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001437 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1438 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1439 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001440 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001441 j.linter.javaLanguageLevel = flags.javaVersion.String()
1442 j.linter.kotlinLanguageLevel = "1.3"
1443 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1444 j.linter.buildModuleReportZip = true
1445 }
1446 j.linter.lint(ctx)
1447 }
1448
1449 ctx.CheckbuildFile(outputFile)
1450
1451 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1452 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1453 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1454 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1455 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1456 AidlIncludeDirs: j.exportAidlIncludeDirs,
1457 SrcJarArgs: j.srcJarArgs,
1458 SrcJarDeps: j.srcJarDeps,
1459 ExportedPlugins: j.exportedPluginJars,
1460 ExportedPluginClasses: j.exportedPluginClasses,
1461 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1462 JacocoReportClassesFile: j.jacocoReportClassesFile,
1463 })
1464
1465 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1466 j.outputFile = outputFile.WithoutRel()
1467}
1468
Colin Crossa1ff7c62021-09-17 14:11:52 -07001469func (j *Module) useCompose() bool {
1470 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1471}
1472
Cole Faust75fffb12021-06-13 15:23:16 -07001473// Returns a copy of the supplied flags, but with all the errorprone-related
1474// fields copied to the regular build's fields.
1475func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1476 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1477
1478 if len(flags.errorProneExtraJavacFlags) > 0 {
1479 if len(flags.javacFlags) > 0 {
1480 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1481 } else {
1482 flags.javacFlags = flags.errorProneExtraJavacFlags
1483 }
1484 }
1485 return flags
1486}
1487
Jaewoong Jung26342642021-03-17 15:56:23 -07001488func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1489 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1490
1491 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1492 if idx >= 0 {
1493 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1494 jarName += strconv.Itoa(idx)
1495 }
1496
1497 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1498 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1499
1500 if ctx.Config().EmitXrefRules() {
1501 extractionFile := android.PathForModuleOut(ctx, kzipName)
1502 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1503 j.kytheFiles = append(j.kytheFiles, extractionFile)
1504 }
1505
1506 return classes
1507}
1508
1509// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1510// since some of these flags may be used internally.
1511func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1512 for _, flag := range flags {
1513 flag = strings.TrimSpace(flag)
1514
1515 if !strings.HasPrefix(flag, "-") {
1516 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1517 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1518 ctx.PropertyErrorf("kotlincflags",
1519 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1520 } else if inList(flag, config.KotlincIllegalFlags) {
1521 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1522 } else if flag == "-include-runtime" {
1523 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1524 } else {
1525 args := strings.Split(flag, " ")
1526 if args[0] == "-kotlin-home" {
1527 ctx.PropertyErrorf("kotlincflags",
1528 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1529 }
1530 }
1531 }
1532}
1533
1534func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1535 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001536 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001537
1538 var jars android.Paths
1539 if len(srcFiles) > 0 || len(srcJars) > 0 {
1540 // Compile java sources into turbine.jar.
1541 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1542 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1543 if ctx.Failed() {
1544 return nil, nil
1545 }
1546 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001547 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001548 }
1549
1550 jars = append(jars, extraJars...)
1551
1552 // Combine any static header libraries into classes-header.jar. If there is only
1553 // one input jar this step will be skipped.
1554 jars = append(jars, deps.staticHeaderJars...)
1555
1556 // we cannot skip the combine step for now if there is only one jar
1557 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1558 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1559 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1560 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001561 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001562
1563 if j.expandJarjarRules != nil {
1564 // Transform classes.jar into classes-jarjar.jar
1565 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001566 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1567 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001568 if ctx.Failed() {
1569 return nil, nil
1570 }
1571 }
1572
Colin Cross3d56ed52021-11-18 22:23:12 -08001573 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001574}
1575
1576func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001577 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001578
1579 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1580 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1581
1582 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1583
1584 j.jacocoReportClassesFile = jacocoReportClassesFile
1585
1586 return instrumentedJar
1587}
1588
1589func (j *Module) HeaderJars() android.Paths {
1590 if j.headerJarFile == nil {
1591 return nil
1592 }
1593 return android.Paths{j.headerJarFile}
1594}
1595
1596func (j *Module) ImplementationJars() android.Paths {
1597 if j.implementationJarFile == nil {
1598 return nil
1599 }
1600 return android.Paths{j.implementationJarFile}
1601}
1602
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001603func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001604 return j.dexJarFile
1605}
1606
1607func (j *Module) DexJarInstallPath() android.Path {
1608 return j.installFile
1609}
1610
1611func (j *Module) ImplementationAndResourcesJars() android.Paths {
1612 if j.implementationAndResourcesJar == nil {
1613 return nil
1614 }
1615 return android.Paths{j.implementationAndResourcesJar}
1616}
1617
1618func (j *Module) AidlIncludeDirs() android.Paths {
1619 // exportAidlIncludeDirs is type android.Paths already
1620 return j.exportAidlIncludeDirs
1621}
1622
1623func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1624 return j.classLoaderContexts
1625}
1626
1627// Collect information for opening IDE project files in java/jdeps.go.
1628func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1629 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1630 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1631 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1632 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1633 if j.expandJarjarRules != nil {
1634 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1635 }
1636 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1637}
1638
1639func (j *Module) CompilerDeps() []string {
1640 jdeps := []string{}
1641 jdeps = append(jdeps, j.properties.Libs...)
1642 jdeps = append(jdeps, j.properties.Static_libs...)
1643 return jdeps
1644}
1645
1646func (j *Module) hasCode(ctx android.ModuleContext) bool {
1647 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1648 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1649}
1650
1651// Implements android.ApexModule
1652func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1653 return j.depIsInSameApex(ctx, dep)
1654}
1655
1656// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001657func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001658 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001659 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001660 return fmt.Errorf("min_sdk_version is not specified")
1661 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001662 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001663 return nil
1664 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001665 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1666 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001667 }
1668 return nil
1669}
1670
1671func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001672 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001673}
1674
Jaewoong Jung26342642021-03-17 15:56:23 -07001675func (j *Module) JacocoReportClassesFile() android.Path {
1676 return j.jacocoReportClassesFile
1677}
1678
1679func (j *Module) IsInstallable() bool {
1680 return Bool(j.properties.Installable)
1681}
1682
1683type sdkLinkType int
1684
1685const (
1686 // TODO(jiyong) rename these for better readability. Make the allowed
1687 // and disallowed link types explicit
1688 // order is important here. See rank()
1689 javaCore sdkLinkType = iota
1690 javaSdk
1691 javaSystem
1692 javaModule
1693 javaSystemServer
1694 javaPlatform
1695)
1696
1697func (lt sdkLinkType) String() string {
1698 switch lt {
1699 case javaCore:
1700 return "core Java API"
1701 case javaSdk:
1702 return "Android API"
1703 case javaSystem:
1704 return "system API"
1705 case javaModule:
1706 return "module API"
1707 case javaSystemServer:
1708 return "system server API"
1709 case javaPlatform:
1710 return "private API"
1711 default:
1712 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1713 }
1714}
1715
1716// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1717// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1718// can't statically depend on modules that use Platform API.
1719func (lt sdkLinkType) rank() int {
1720 return int(lt)
1721}
1722
1723type moduleWithSdkDep interface {
1724 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001725 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001726}
1727
Jiyong Park92315372021-04-02 08:45:46 +09001728func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001729 switch name {
1730 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1731 "stub-annotations", "private-stub-annotations-jar",
1732 "core-lambda-stubs", "core-generated-annotation-stubs":
1733 return javaCore, true
1734 case "android_stubs_current":
1735 return javaSdk, true
1736 case "android_system_stubs_current":
1737 return javaSystem, true
1738 case "android_module_lib_stubs_current":
1739 return javaModule, true
1740 case "android_system_server_stubs_current":
1741 return javaSystemServer, true
1742 case "android_test_stubs_current":
1743 return javaSystem, true
1744 }
1745
1746 if stub, linkType := moduleStubLinkType(name); stub {
1747 return linkType, true
1748 }
1749
Jiyong Park92315372021-04-02 08:45:46 +09001750 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001751 switch ver.Kind {
1752 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001753 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001754 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001755 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001756 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001757 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001758 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001759 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001760 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001761 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001762 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001763 return javaPlatform, false
1764 }
1765
Jiyong Parkf1691d22021-03-29 20:11:58 +09001766 if !ver.Valid() {
1767 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001768 }
1769 return javaSdk, false
1770}
1771
1772// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1773// this module's. See the comment on rank() for details and an example.
1774func (j *Module) checkSdkLinkType(
1775 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1776 if ctx.Host() {
1777 return
1778 }
1779
Jiyong Park92315372021-04-02 08:45:46 +09001780 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001781 if stubs {
1782 return
1783 }
Jiyong Park92315372021-04-02 08:45:46 +09001784 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001785
1786 if myLinkType.rank() < depLinkType.rank() {
1787 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1788 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1789 "property of the source or target module so that target module is built "+
1790 "with the same or smaller API set when compared to the source.",
1791 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1792 }
1793}
1794
1795func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1796 var deps deps
1797
1798 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001799 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001800 if sdkDep.invalidVersion {
1801 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1802 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1803 } else if sdkDep.useFiles {
1804 // sdkDep.jar is actually equivalent to turbine header.jar.
1805 deps.classpath = append(deps.classpath, sdkDep.jars...)
1806 deps.aidlPreprocess = sdkDep.aidl
1807 } else {
1808 deps.aidlPreprocess = sdkDep.aidl
1809 }
1810 }
1811
Jiyong Park92315372021-04-02 08:45:46 +09001812 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001813
1814 ctx.VisitDirectDeps(func(module android.Module) {
1815 otherName := ctx.OtherModuleName(module)
1816 tag := ctx.OtherModuleDependencyTag(module)
1817
1818 if IsJniDepTag(tag) {
1819 // Handled by AndroidApp.collectAppDeps
1820 return
1821 }
1822 if tag == certificateTag {
1823 // Handled by AndroidApp.collectAppDeps
1824 return
1825 }
1826
1827 if dep, ok := module.(SdkLibraryDependency); ok {
1828 switch tag {
1829 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001830 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001831 case staticLibTag:
1832 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1833 }
1834 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1835 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1836 if sdkLinkType != javaPlatform &&
1837 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1838 // dep is a sysprop implementation library, but this module is not linking against
1839 // the platform, so it gets the sysprop public stubs library instead. Replace
1840 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1841 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1842 dep = syspropDep.JavaInfo
1843 }
1844 switch tag {
1845 case bootClasspathTag:
1846 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1847 case libTag, instrumentationForTag:
1848 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1849 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1850 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1851 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1852 case java9LibTag:
1853 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1854 case staticLibTag:
1855 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1856 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1857 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1858 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1859 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1860 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1861 // Turbine doesn't run annotation processors, so any module that uses an
1862 // annotation processor that generates API is incompatible with the turbine
1863 // optimization.
1864 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1865 case pluginTag:
1866 if plugin, ok := module.(*Plugin); ok {
1867 if plugin.pluginProperties.Processor_class != nil {
1868 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1869 } else {
1870 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1871 }
1872 // Turbine doesn't run annotation processors, so any module that uses an
1873 // annotation processor that generates API is incompatible with the turbine
1874 // optimization.
1875 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1876 } else {
1877 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1878 }
1879 case errorpronePluginTag:
1880 if _, ok := module.(*Plugin); ok {
1881 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1882 } else {
1883 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1884 }
1885 case exportedPluginTag:
1886 if plugin, ok := module.(*Plugin); ok {
1887 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1888 if plugin.pluginProperties.Processor_class != nil {
1889 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1890 }
1891 // Turbine doesn't run annotation processors, so any module that uses an
1892 // annotation processor that generates API is incompatible with the turbine
1893 // optimization.
1894 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1895 } else {
1896 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1897 }
1898 case kotlinStdlibTag:
1899 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1900 case kotlinAnnotationsTag:
1901 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001902 case kotlinPluginTag:
1903 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001904 case syspropPublicStubDepTag:
1905 // This is a sysprop implementation library, forward the JavaInfoProvider from
1906 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1907 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1908 JavaInfo: dep,
1909 })
1910 }
1911 } else if dep, ok := module.(android.SourceFileProducer); ok {
1912 switch tag {
1913 case libTag:
1914 checkProducesJars(ctx, dep)
1915 deps.classpath = append(deps.classpath, dep.Srcs()...)
1916 case staticLibTag:
1917 checkProducesJars(ctx, dep)
1918 deps.classpath = append(deps.classpath, dep.Srcs()...)
1919 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1920 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1921 }
1922 } else {
1923 switch tag {
1924 case bootClasspathTag:
1925 // If a system modules dependency has been added to the bootclasspath
1926 // then add its libs to the bootclasspath.
1927 sm := module.(SystemModulesProvider)
1928 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1929
1930 case systemModulesTag:
1931 if deps.systemModules != nil {
1932 panic("Found two system module dependencies")
1933 }
1934 sm := module.(SystemModulesProvider)
1935 outputDir, outputDeps := sm.OutputDirAndDeps()
1936 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00001937
1938 case instrumentationForTag:
1939 ctx.PropertyErrorf("instrumentation_for", "dependency %q of type %q does not provide JavaInfo so is unsuitable for use with this property", ctx.OtherModuleName(module), ctx.OtherModuleType(module))
Jaewoong Jung26342642021-03-17 15:56:23 -07001940 }
1941 }
1942
1943 addCLCFromDep(ctx, module, j.classLoaderContexts)
1944 })
1945
1946 return deps
1947}
1948
1949func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1950 deps.processorPath = append(deps.processorPath, pluginJars...)
1951 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1952}
1953
1954// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1955// this interface.
1956type ProvidesUsesLib interface {
1957 ProvidesUsesLib() *string
1958}
1959
1960func (j *Module) ProvidesUsesLib() *string {
1961 return j.usesLibraryProperties.Provides_uses_lib
1962}
satayev1c564cc2021-05-25 19:50:30 +01001963
1964type ModuleWithStem interface {
1965 Stem() string
1966}
1967
1968var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08001969
1970func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1971 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00001972 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08001973 if lib, ok := ctx.Module().(*Library); ok {
1974 javaLibraryBp2Build(ctx, lib)
1975 }
1976 case "java_binary_host":
1977 if binary, ok := ctx.Module().(*Binary); ok {
1978 javaBinaryHostBp2Build(ctx, binary)
1979 }
1980 }
Wei Libafb6d62021-12-10 03:14:59 -08001981}