blob: c0da215235d01cfe3bb81b9e3ba9fb6198b6457b [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 // set the name of the output
249 Stem *string
250
251 IsSDKLibrary bool `blueprint:"mutated"`
252
253 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
254 // Defaults to false.
255 V4_signature *bool
256
257 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
258 // public stubs library.
259 SyspropPublicStub string `blueprint:"mutated"`
260}
261
262// Functionality common to Module and Import
263//
264// It is embedded in Module so its functionality can be used by methods in Module
265// but it is currently only initialized by Import and Library.
266type embeddableInModuleAndImport struct {
267
268 // Functionality related to this being used as a component of a java_sdk_library.
269 EmbeddableSdkLibraryComponent
270}
271
Paul Duffin71b33cc2021-06-23 11:39:47 +0100272func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
273 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700274}
275
276// Module/Import's DepIsInSameApex(...) delegates to this method.
277//
278// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
279// the one provided by ApexModuleBase.
280func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
281 // dependencies other than the static linkage are all considered crossing APEX boundary
282 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
283 return true
284 }
285 return false
286}
287
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100288// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
289// or an invalid path describing the reason it is invalid.
290//
291// It is unset if a dex jar isn't applicable, i.e. no build rule has been
292// requested to create one.
293//
294// If a dex jar has been requested to be built then it is set, and it may be
295// either a valid android.Path, or invalid with a reason message. The latter
296// happens if the source that should produce the dex file isn't able to.
297//
298// E.g. it is invalid with a reason message if there is a prebuilt APEX that
299// could produce the dex jar through a deapexer module, but the APEX isn't
300// installable so doing so wouldn't be safe.
301type OptionalDexJarPath struct {
302 isSet bool
303 path android.OptionalPath
304}
305
306// IsSet returns true if a path has been set, either invalid or valid.
307func (o OptionalDexJarPath) IsSet() bool {
308 return o.isSet
309}
310
311// Valid returns true if there is a path that is valid.
312func (o OptionalDexJarPath) Valid() bool {
313 return o.isSet && o.path.Valid()
314}
315
316// Path returns the valid path, or panics if it's either not set or is invalid.
317func (o OptionalDexJarPath) Path() android.Path {
318 if !o.isSet {
319 panic("path isn't set")
320 }
321 return o.path.Path()
322}
323
324// PathOrNil returns the path if it's set and valid, or else nil.
325func (o OptionalDexJarPath) PathOrNil() android.Path {
326 if o.Valid() {
327 return o.Path()
328 }
329 return nil
330}
331
332// InvalidReason returns the reason for an invalid path, which is never "". It
333// returns "" for an unset or valid path.
334func (o OptionalDexJarPath) InvalidReason() string {
335 if !o.isSet {
336 return ""
337 }
338 return o.path.InvalidReason()
339}
340
341func (o OptionalDexJarPath) String() string {
342 if !o.isSet {
343 return "<unset>"
344 }
345 return o.path.String()
346}
347
348// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
349func makeUnsetDexJarPath() OptionalDexJarPath {
350 return OptionalDexJarPath{isSet: false}
351}
352
353// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
354// the given OptionalPath, which may be valid or invalid.
355func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
356 return OptionalDexJarPath{isSet: true, path: path}
357}
358
359// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
360// valid given path. It returns an unset OptionalDexJarPath if the given path is
361// nil.
362func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
363 if path == nil {
364 return makeUnsetDexJarPath()
365 }
366 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
367}
368
Jaewoong Jung26342642021-03-17 15:56:23 -0700369// Module contains the properties and members used by all java module types
370type Module struct {
371 android.ModuleBase
372 android.DefaultableModuleBase
373 android.ApexModuleBase
374 android.SdkBase
375
376 // Functionality common to Module and Import.
377 embeddableInModuleAndImport
378
379 properties CommonProperties
380 protoProperties android.ProtoProperties
381 deviceProperties DeviceProperties
382
383 // jar file containing header classes including static library dependencies, suitable for
384 // inserting into the bootclasspath/classpath of another compile
385 headerJarFile android.Path
386
387 // jar file containing implementation classes including static library dependencies but no
388 // resources
389 implementationJarFile android.Path
390
391 // jar file containing only resources including from static library dependencies
392 resourceJar android.Path
393
394 // args and dependencies to package source files into a srcjar
395 srcJarArgs []string
396 srcJarDeps android.Paths
397
398 // jar file containing implementation classes and resources including static library
399 // dependencies
400 implementationAndResourcesJar android.Path
401
402 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100403 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700404
405 // output file containing uninstrumented classes that will be instrumented by jacoco
406 jacocoReportClassesFile android.Path
407
408 // output file of the module, which may be a classes jar or a dex jar
409 outputFile android.Path
410 extraOutputFiles android.Paths
411
412 exportAidlIncludeDirs android.Paths
413
414 logtagsSrcs android.Paths
415
416 // installed file for binary dependency
417 installFile android.Path
418
Colin Cross3108ce12021-11-10 14:38:50 -0800419 // installed file for hostdex copy
420 hostdexInstallFile android.InstallPath
421
Jaewoong Jung26342642021-03-17 15:56:23 -0700422 // list of .java files and srcjars that was passed to javac
423 compiledJavaSrcs android.Paths
424 compiledSrcJars android.Paths
425
426 // manifest file to use instead of properties.Manifest
427 overrideManifest android.OptionalPath
428
429 // map of SDK version to class loader context
430 classLoaderContexts dexpreopt.ClassLoaderContextMap
431
432 // list of plugins that this java module is exporting
433 exportedPluginJars android.Paths
434
435 // list of plugins that this java module is exporting
436 exportedPluginClasses []string
437
438 // if true, the exported plugins generate API and require disabling turbine.
439 exportedDisableTurbine bool
440
441 // list of source files, collected from srcFiles with unique java and all kt files,
442 // will be used by android.IDEInfo struct
443 expandIDEInfoCompiledSrcs []string
444
445 // expanded Jarjar_rules
446 expandJarjarRules android.Path
447
Jaewoong Jung26342642021-03-17 15:56:23 -0700448 // Extra files generated by the module type to be added as java resources.
449 extraResources android.Paths
450
451 hiddenAPI
452 dexer
453 dexpreopter
454 usesLibrary
455 linter
456
457 // list of the xref extraction files
458 kytheFiles android.Paths
459
460 // Collect the module directory for IDE info in java/jdeps.go.
461 modulePaths []string
462
463 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900464
465 sdkVersion android.SdkSpec
466 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000467 maxSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700468}
469
Jiyong Park92315372021-04-02 08:45:46 +0900470func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
471 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900472 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700473 return nil
474 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900475 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000476 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700477 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
478 } else {
479 // Treat stable core platform as stable.
480 return nil
481 }
482 } else {
483 return fmt.Errorf("non stable SDK %v", sdkVersion)
484 }
485}
486
487// checkSdkVersions enforces restrictions around SDK dependencies.
488func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
489 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900490 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900491 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700492 ctx.PropertyErrorf("sdk_version",
493 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
494 }
495 }
496 }
497
498 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
499 // See rank() for details.
500 ctx.VisitDirectDeps(func(module android.Module) {
501 tag := ctx.OtherModuleDependencyTag(module)
502 switch module.(type) {
503 // TODO(satayev): cover other types as well, e.g. imports
504 case *Library, *AndroidLibrary:
505 switch tag {
506 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
507 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
508 }
509 }
510 })
511}
512
513func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900514 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700515 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900516 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700517 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000518 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 -0700519 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000520 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 -0700521 }
522
523 }
524}
525
526func (j *Module) addHostProperties() {
527 j.AddProperties(
528 &j.properties,
529 &j.protoProperties,
530 &j.usesLibraryProperties,
531 )
532}
533
534func (j *Module) addHostAndDeviceProperties() {
535 j.addHostProperties()
536 j.AddProperties(
537 &j.deviceProperties,
538 &j.dexer.dexProperties,
539 &j.dexpreoptProperties,
540 &j.linter.properties,
541 )
542}
543
544func (j *Module) OutputFiles(tag string) (android.Paths, error) {
545 switch tag {
546 case "":
547 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
548 case android.DefaultDistTag:
549 return android.Paths{j.outputFile}, nil
550 case ".jar":
551 return android.Paths{j.implementationAndResourcesJar}, nil
552 case ".proguard_map":
553 if j.dexer.proguardDictionary.Valid() {
554 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
555 }
556 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
557 default:
558 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
559 }
560}
561
562var _ android.OutputFileProducer = (*Module)(nil)
563
564func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
565 initJavaModule(module, hod, false)
566}
567
568func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
569 initJavaModule(module, hod, true)
570}
571
572func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
573 multilib := android.MultilibCommon
574 if multiTargets {
575 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
576 } else {
577 android.InitAndroidArchModule(module, hod, multilib)
578 }
579 android.InitDefaultableModule(module)
580}
581
582func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
583 return j.properties.Instrument &&
584 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
585 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
586}
587
588func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
589 return j.shouldInstrument(ctx) &&
590 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
591 ctx.Config().UnbundledBuild())
592}
593
594func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
595 // Force enable the instrumentation for java code that is built for APEXes ...
596 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
597 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
598 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
599 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
600 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
601 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
602 return true
603 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
604 return true
605 }
606 }
607 return false
608}
609
Jiyong Park92315372021-04-02 08:45:46 +0900610func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
611 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700612}
613
Jiyong Parkf1691d22021-03-29 20:11:58 +0900614func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700615 return proptools.String(j.deviceProperties.System_modules)
616}
617
Jiyong Park92315372021-04-02 08:45:46 +0900618func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700619 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900620 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700621 }
Jiyong Park92315372021-04-02 08:45:46 +0900622 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700623}
624
satayev0a420e72021-11-29 17:25:52 +0000625func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
626 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
627 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
628 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
629 return android.SdkSpecFrom(ctx, maxSdkVersion)
630}
631
Jiyong Parkf1691d22021-03-29 20:11:58 +0900632func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900633 return j.minSdkVersion.Raw
634}
635
636func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
637 if j.deviceProperties.Target_sdk_version != nil {
638 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
639 }
640 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700641}
642
643func (j *Module) AvailableFor(what string) bool {
644 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
645 // Exception: for hostdex: true libraries, the platform variant is created
646 // even if it's not marked as available to platform. In that case, the platform
647 // variant is used only for the hostdex and not installed to the device.
648 return true
649 }
650 return j.ApexModuleBase.AvailableFor(what)
651}
652
653func (j *Module) deps(ctx android.BottomUpMutatorContext) {
654 if ctx.Device() {
655 j.linter.deps(ctx)
656
Jiyong Parkf1691d22021-03-29 20:11:58 +0900657 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700658
659 if j.deviceProperties.SyspropPublicStub != "" {
660 // This is a sysprop implementation library that has a corresponding sysprop public
661 // stubs library, and a dependency on it so that dependencies on the implementation can
662 // be forwarded to the public stubs library when necessary.
663 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
664 }
665 }
666
667 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
668 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
669
670 // Add dependency on libraries that provide additional hidden api annotations.
671 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
672
673 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
674 // Require java_sdk_library at inter-partition java dependency to ensure stable
675 // interface between partitions. If inter-partition java_library dependency is detected,
676 // raise build error because java_library doesn't have a stable interface.
677 //
678 // Inputs:
679 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
680 // if true, enable enforcement
681 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
682 // exception list of java_library names to allow inter-partition dependency
683 for idx := range j.properties.Libs {
684 if libDeps[idx] == nil {
685 continue
686 }
687
688 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
689 // java_sdk_library is always allowed at inter-partition dependency.
690 // So, skip check.
691 if _, ok := javaDep.(*SdkLibrary); ok {
692 continue
693 }
694
695 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
696 }
697 }
698 }
699
700 // For library dependencies that are component libraries (like stubs), add the implementation
701 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
702 for _, dep := range libDeps {
703 if dep != nil {
704 if component, ok := dep.(SdkLibraryComponentDependency); ok {
705 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100706 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100707 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
708 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100709 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700710 }
711 }
712 }
713 }
714
715 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
716 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
717 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
718
719 android.ProtoDeps(ctx, &j.protoProperties)
720 if j.hasSrcExt(".proto") {
721 protoDeps(ctx, &j.protoProperties)
722 }
723
724 if j.hasSrcExt(".kt") {
725 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
726 // Kotlin files
727 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
728 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
729 if len(j.properties.Plugins) > 0 {
730 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
731 }
732 }
733
734 // Framework libraries need special handling in static coverage builds: they should not have
735 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
736 // the same jacoco classes coming from different bootclasspath jars.
737 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
738 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
739 j.properties.Instrument = true
740 }
741 } else if j.shouldInstrumentStatic(ctx) {
742 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
743 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700744
745 if j.useCompose() {
746 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
747 "androidx.compose.compiler_compiler-hosted")
748 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700749}
750
751func hasSrcExt(srcs []string, ext string) bool {
752 for _, src := range srcs {
753 if filepath.Ext(src) == ext {
754 return true
755 }
756 }
757
758 return false
759}
760
761func (j *Module) hasSrcExt(ext string) bool {
762 return hasSrcExt(j.properties.Srcs, ext)
763}
764
765func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
766 aidlIncludeDirs android.Paths) (string, android.Paths) {
767
768 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
769 aidlIncludes = append(aidlIncludes,
770 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
771 aidlIncludes = append(aidlIncludes,
772 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
773
774 var flags []string
775 var deps android.Paths
776
777 flags = append(flags, j.deviceProperties.Aidl.Flags...)
778
779 if aidlPreprocess.Valid() {
780 flags = append(flags, "-p"+aidlPreprocess.String())
781 deps = append(deps, aidlPreprocess.Path())
782 } else if len(aidlIncludeDirs) > 0 {
783 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
784 }
785
786 if len(j.exportAidlIncludeDirs) > 0 {
787 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
788 }
789
790 if len(aidlIncludes) > 0 {
791 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
792 }
793
794 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
795 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
796 flags = append(flags, "-I"+src.String())
797 }
798
799 if Bool(j.deviceProperties.Aidl.Generate_traces) {
800 flags = append(flags, "-t")
801 }
802
803 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
804 flags = append(flags, "--transaction_names")
805 }
806
Jooyung Han07f70c02021-11-06 07:08:45 +0900807 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
808 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
809
Jaewoong Jung26342642021-03-17 15:56:23 -0700810 return strings.Join(flags, " "), deps
811}
812
813func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
814
815 var flags javaBuilderFlags
816
817 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900818 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700819
Cole Faust2b1536e2021-06-18 12:25:54 -0700820 epEnabled := j.properties.Errorprone.Enabled
821 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700822 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
823 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
824 }
825
826 errorProneFlags := []string{
827 "-Xplugin:ErrorProne",
828 "${config.ErrorProneChecks}",
829 }
830 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
831
832 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
833 "'" + strings.Join(errorProneFlags, " ") + "'"
834 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
835 }
836
837 // classpath
838 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
839 flags.classpath = append(flags.classpath, deps.classpath...)
840 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
841 flags.processorPath = append(flags.processorPath, deps.processorPath...)
842 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
843
844 flags.processors = append(flags.processors, deps.processorClasses...)
845 flags.processors = android.FirstUniqueStrings(flags.processors)
846
847 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900848 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700849 // Give host-side tools a version of OpenJDK's standard libraries
850 // close to what they're targeting. As of Dec 2017, AOSP is only
851 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
852 //
853 // When building with OpenJDK 8, the following should have no
854 // effect since those jars would be available by default.
855 //
856 // When building with OpenJDK 9 but targeting a version < 1.8,
857 // putting them on the bootclasspath means that:
858 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
859 // b) references to existing APIs are not reinterpreted in an
860 // OpenJDK 9-specific way, eg. calls to subclasses of
861 // java.nio.Buffer as in http://b/70862583
862 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
863 flags.bootClasspath = append(flags.bootClasspath,
864 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
865 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
866 if Bool(j.properties.Use_tools_jar) {
867 flags.bootClasspath = append(flags.bootClasspath,
868 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
869 }
870 }
871
872 // systemModules
873 flags.systemModules = deps.systemModules
874
875 // aidl flags.
876 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
877
878 return flags
879}
880
881func (j *Module) collectJavacFlags(
882 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
883 // javac flags.
884 javacFlags := j.properties.Javacflags
885
886 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
887 // For non-host binaries, override the -g flag passed globally to remove
888 // local variable debug info to reduce disk and memory usage.
889 javacFlags = append(javacFlags, "-g:source,lines")
890 }
891 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
892
893 if flags.javaVersion.usesJavaModules() {
894 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
895
896 if j.properties.Patch_module != nil {
897 // Manually specify build directory in case it is not under the repo root.
898 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
899 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200900 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700901
902 // b/150878007
903 //
904 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
905 // execution root for --patch-module. If this javac command line is
906 // invoked within Bazel's execution root working directory, the top
907 // level directories (e.g. libcore/, tools/, frameworks/) are all
908 // symlinks. JDK9 javac does not traverse into symlinks, which causes
909 // --patch-module to fail source file lookups when invoked in the
910 // execution root.
911 //
912 // Short of patching javac or enumerating *all* directories as possible
913 // input dirs, manually add the top level dir of the source files to be
914 // compiled.
915 topLevelDirs := map[string]bool{}
916 for _, srcFilePath := range srcFiles {
917 srcFileParts := strings.Split(srcFilePath.String(), "/")
918 // Ignore source files that are already in the top level directory
919 // as well as generated files in the out directory. The out
920 // directory may be an absolute path, which means srcFileParts[0] is the
921 // empty string, so check that as well. Note that "out" in Bazel's execution
922 // root is *not* a symlink, which doesn't cause problems for --patch-modules
923 // anyway, so it's fine to not apply this workaround for generated
924 // source files.
925 if len(srcFileParts) > 1 &&
926 srcFileParts[0] != "" &&
927 srcFileParts[0] != "out" {
928 topLevelDirs[srcFileParts[0]] = true
929 }
930 }
931 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
932
933 classPath := flags.classpath.FormJavaClassPath("")
934 if classPath != "" {
935 patchPaths = append(patchPaths, classPath)
936 }
937 javacFlags = append(
938 javacFlags,
939 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
940 }
941 }
942
943 if len(javacFlags) > 0 {
944 // optimization.
945 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
946 flags.javacFlags = "$javacFlags"
947 }
948
949 return flags
950}
951
952func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
953 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
954
955 deps := j.collectDeps(ctx)
956 flags := j.collectBuilderFlags(ctx, deps)
957
958 if flags.javaVersion.usesJavaModules() {
959 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
960 }
961 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
962 if hasSrcExt(srcFiles.Strings(), ".proto") {
963 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
964 }
965
966 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
967 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
968 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
969 }
970
971 srcFiles = j.genSources(ctx, srcFiles, flags)
972
973 // Collect javac flags only after computing the full set of srcFiles to
974 // ensure that the --patch-module lookup paths are complete.
975 flags = j.collectJavacFlags(ctx, flags, srcFiles)
976
977 srcJars := srcFiles.FilterByExt(".srcjar")
978 srcJars = append(srcJars, deps.srcJars...)
979 if aaptSrcJar != nil {
980 srcJars = append(srcJars, aaptSrcJar)
981 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700982 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700983
984 if j.properties.Jarjar_rules != nil {
985 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
986 }
987
988 jarName := ctx.ModuleName() + ".jar"
989
990 javaSrcFiles := srcFiles.FilterByExt(".java")
991 var uniqueSrcFiles android.Paths
992 set := make(map[string]bool)
993 for _, v := range javaSrcFiles {
994 if _, found := set[v.String()]; !found {
995 set[v.String()] = true
996 uniqueSrcFiles = append(uniqueSrcFiles, v)
997 }
998 }
999
1000 // Collect .java files for AIDEGen
1001 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1002
1003 var kotlinJars android.Paths
1004
1005 if srcFiles.HasExt(".kt") {
1006 // user defined kotlin flags.
1007 kotlincFlags := j.properties.Kotlincflags
1008 CheckKotlincFlags(ctx, kotlincFlags)
1009
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001010 // Workaround for KT-46512
1011 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001012
1013 // If there are kotlin files, compile them first but pass all the kotlin and java files
1014 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1015 // won't emit any classes for them.
1016 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1017 if ctx.Device() {
1018 kotlincFlags = append(kotlincFlags, "-no-jdk")
1019 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001020
1021 for _, plugin := range deps.kotlinPlugins {
1022 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1023 }
1024 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1025
Jaewoong Jung26342642021-03-17 15:56:23 -07001026 if len(kotlincFlags) > 0 {
1027 // optimization.
1028 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1029 flags.kotlincFlags += "$kotlincFlags"
1030 }
1031
1032 var kotlinSrcFiles android.Paths
1033 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1034 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1035
1036 // Collect .kt files for AIDEGen
1037 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1038 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1039
1040 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1041 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1042
1043 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1044 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1045
1046 if len(flags.processorPath) > 0 {
1047 // Use kapt for annotation processing
1048 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1049 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1050 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1051 srcJars = append(srcJars, kaptSrcJar)
1052 kotlinJars = append(kotlinJars, kaptResJar)
1053 // Disable annotation processing in javac, it's already been handled by kapt
1054 flags.processorPath = nil
1055 flags.processors = nil
1056 }
1057
1058 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
1059 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1060 if ctx.Failed() {
1061 return
1062 }
1063
1064 // Make javac rule depend on the kotlinc rule
1065 flags.classpath = append(flags.classpath, kotlinJar)
1066
1067 kotlinJars = append(kotlinJars, kotlinJar)
1068 // Jar kotlin classes into the final jar after javac
1069 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1070 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
1071 }
1072 }
1073
1074 jars := append(android.Paths(nil), kotlinJars...)
1075
1076 // Store the list of .java files that was passed to javac
1077 j.compiledJavaSrcs = uniqueSrcFiles
1078 j.compiledSrcJars = srcJars
1079
1080 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001081 var headerJarFileWithoutDepsOrJarjar android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001082 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
1083 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1084 enableSharding = true
1085 // Formerly, there was a check here that prevented annotation processors
1086 // from being used when sharding was enabled, as some annotation processors
1087 // do not function correctly in sharded environments. It was removed to
1088 // allow for the use of annotation processors that do function correctly
1089 // with sharding enabled. See: b/77284273.
1090 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001091 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Jaewoong Jung26342642021-03-17 15:56:23 -07001092 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
1093 if ctx.Failed() {
1094 return
1095 }
1096 }
1097 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1098 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001099 if Bool(j.properties.Errorprone.Enabled) {
1100 // If error-prone is enabled, enable errorprone flags on the regular
1101 // build.
1102 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001103 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001104 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1105 // a new jar file just for compiling with the errorprone compiler to.
1106 // This is because we don't want to cause the java files to get completely
1107 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1108 // We also don't want to run this if errorprone is enabled by default for
1109 // this module, or else we could have duplicated errorprone messages.
1110 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001111 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001112
1113 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1114 "errorprone", "errorprone")
1115
Jaewoong Jung26342642021-03-17 15:56:23 -07001116 extraJarDeps = append(extraJarDeps, errorprone)
1117 }
1118
1119 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001120 if headerJarFileWithoutDepsOrJarjar != nil {
1121 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1122 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001123 shardSize := int(*(j.properties.Javac_shard_size))
1124 var shardSrcs []android.Paths
1125 if len(uniqueSrcFiles) > 0 {
1126 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1127 for idx, shardSrc := range shardSrcs {
1128 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1129 nil, flags, extraJarDeps)
1130 jars = append(jars, classes)
1131 }
1132 }
1133 if len(srcJars) > 0 {
1134 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1135 nil, srcJars, flags, extraJarDeps)
1136 jars = append(jars, classes)
1137 }
1138 } else {
1139 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1140 jars = append(jars, classes)
1141 }
1142 if ctx.Failed() {
1143 return
1144 }
1145 }
1146
1147 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1148
1149 var includeSrcJar android.WritablePath
1150 if Bool(j.properties.Include_srcs) {
1151 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1152 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1153 }
1154
1155 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1156 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1157 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1158 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1159
1160 var resArgs []string
1161 var resDeps android.Paths
1162
1163 resArgs = append(resArgs, dirArgs...)
1164 resDeps = append(resDeps, dirDeps...)
1165
1166 resArgs = append(resArgs, fileArgs...)
1167 resDeps = append(resDeps, fileDeps...)
1168
1169 resArgs = append(resArgs, extraArgs...)
1170 resDeps = append(resDeps, extraDeps...)
1171
1172 if len(resArgs) > 0 {
1173 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1174 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1175 j.resourceJar = resourceJar
1176 if ctx.Failed() {
1177 return
1178 }
1179 }
1180
1181 var resourceJars android.Paths
1182 if j.resourceJar != nil {
1183 resourceJars = append(resourceJars, j.resourceJar)
1184 }
1185 if Bool(j.properties.Include_srcs) {
1186 resourceJars = append(resourceJars, includeSrcJar)
1187 }
1188 resourceJars = append(resourceJars, deps.staticResourceJars...)
1189
1190 if len(resourceJars) > 1 {
1191 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1192 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1193 false, nil, nil)
1194 j.resourceJar = combinedJar
1195 } else if len(resourceJars) == 1 {
1196 j.resourceJar = resourceJars[0]
1197 }
1198
1199 if len(deps.staticJars) > 0 {
1200 jars = append(jars, deps.staticJars...)
1201 }
1202
1203 manifest := j.overrideManifest
1204 if !manifest.Valid() && j.properties.Manifest != nil {
1205 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1206 }
1207
1208 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1209 if len(services) > 0 {
1210 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1211 var zipargs []string
1212 for _, file := range services {
1213 serviceFile := file.String()
1214 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1215 }
1216 rule := zip
1217 args := map[string]string{
1218 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1219 }
1220 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1221 rule = zipRE
1222 args["implicits"] = strings.Join(services.Strings(), ",")
1223 }
1224 ctx.Build(pctx, android.BuildParams{
1225 Rule: rule,
1226 Output: servicesJar,
1227 Implicits: services,
1228 Args: args,
1229 })
1230 jars = append(jars, servicesJar)
1231 }
1232
1233 // Combine the classes built from sources, any manifests, and any static libraries into
1234 // classes.jar. If there is only one input jar this step will be skipped.
1235 var outputFile android.OutputPath
1236
1237 if len(jars) == 1 && !manifest.Valid() {
1238 // Optimization: skip the combine step as there is nothing to do
1239 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1240 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1241 // any if len(jars) == 1.
1242
1243 // Transform the single path to the jar into an OutputPath as that is required by the following
1244 // code.
1245 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1246 // The path contains an embedded OutputPath so reuse that.
1247 outputFile = moduleOutPath.OutputPath
1248 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1249 // The path is an OutputPath so reuse it directly.
1250 outputFile = outputPath
1251 } else {
1252 // The file is not in the out directory so create an OutputPath into which it can be copied
1253 // and which the following code can use to refer to it.
1254 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1255 ctx.Build(pctx, android.BuildParams{
1256 Rule: android.Cp,
1257 Input: jars[0],
1258 Output: combinedJar,
1259 })
1260 outputFile = combinedJar.OutputPath
1261 }
1262 } else {
1263 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1264 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1265 false, nil, nil)
1266 outputFile = combinedJar.OutputPath
1267 }
1268
1269 // jarjar implementation jar if necessary
1270 if j.expandJarjarRules != nil {
1271 // Transform classes.jar into classes-jarjar.jar
1272 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1273 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1274 outputFile = jarjarFile
1275
1276 // jarjar resource jar if necessary
1277 if j.resourceJar != nil {
1278 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1279 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1280 j.resourceJar = resourceJarJarFile
1281 }
1282
1283 if ctx.Failed() {
1284 return
1285 }
1286 }
1287
1288 // Check package restrictions if necessary.
1289 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001290 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001291 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001292
1293 // Create a rule to copy the output jar to another path and add a validate dependency that
1294 // will check that the jar only contains the permitted packages. The new location will become
1295 // the output file of this module.
1296 inputFile := outputFile
1297 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1298 ctx.Build(pctx, android.BuildParams{
1299 Rule: android.Cp,
1300 Input: inputFile,
1301 Output: outputFile,
1302 // Make sure that any dependency on the output file will cause ninja to run the package check
1303 // rule.
1304 Validation: pkgckFile,
1305 })
1306
1307 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001308 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001309
1310 if ctx.Failed() {
1311 return
1312 }
1313 }
1314
1315 j.implementationJarFile = outputFile
1316 if j.headerJarFile == nil {
1317 j.headerJarFile = j.implementationJarFile
1318 }
1319
1320 if j.shouldInstrumentInApex(ctx) {
1321 j.properties.Instrument = true
1322 }
1323
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001324 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1325 specs := j.jacocoModuleToZipCommand(ctx)
1326 if ctx.Failed() {
1327 return
1328 }
1329
Jaewoong Jung26342642021-03-17 15:56:23 -07001330 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001331 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001332 }
1333
1334 // merge implementation jar with resources if necessary
1335 implementationAndResourcesJar := outputFile
1336 if j.resourceJar != nil {
1337 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1338 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1339 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1340 false, nil, nil)
1341 implementationAndResourcesJar = combinedJar
1342 }
1343
1344 j.implementationAndResourcesJar = implementationAndResourcesJar
1345
1346 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1347 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1348 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1349 if j.dexProperties.Compile_dex == nil {
1350 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1351 }
1352 if j.deviceProperties.Hostdex == nil {
1353 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1354 }
1355 }
1356
1357 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1358 if j.hasCode(ctx) {
1359 if j.shouldInstrumentStatic(ctx) {
1360 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1361 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1362 }
1363 // Dex compilation
1364 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001365 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001366 if ctx.Failed() {
1367 return
1368 }
1369
Jaewoong Jung26342642021-03-17 15:56:23 -07001370 // merge dex jar with resources if necessary
1371 if j.resourceJar != nil {
1372 jars := android.Paths{dexOutputFile, j.resourceJar}
1373 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1374 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1375 false, nil, nil)
1376 if *j.dexProperties.Uncompress_dex {
1377 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1378 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1379 dexOutputFile = combinedAlignedJar
1380 } else {
1381 dexOutputFile = combinedJar
1382 }
1383 }
1384
Paul Duffin4de94502021-05-16 05:21:16 +01001385 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001386
1387 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001388
1389 // Encode hidden API flags in dex file, if needed.
1390 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1391
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001392 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001393
1394 // Dexpreopting
1395 j.dexpreopt(ctx, dexOutputFile)
1396
1397 outputFile = dexOutputFile
1398 } else {
1399 // There is no code to compile into a dex jar, make sure the resources are propagated
1400 // to the APK if this is an app.
1401 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001402 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001403 }
1404
1405 if ctx.Failed() {
1406 return
1407 }
1408 } else {
1409 outputFile = implementationAndResourcesJar
1410 }
1411
1412 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001413 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001414 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001415 return v.String()
1416 } else {
1417 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1418 }
1419 }
1420
1421 j.linter.name = ctx.ModuleName()
1422 j.linter.srcs = srcFiles
1423 j.linter.srcJars = srcJars
1424 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1425 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001426 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1427 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1428 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001429 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001430 j.linter.javaLanguageLevel = flags.javaVersion.String()
1431 j.linter.kotlinLanguageLevel = "1.3"
1432 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1433 j.linter.buildModuleReportZip = true
1434 }
1435 j.linter.lint(ctx)
1436 }
1437
1438 ctx.CheckbuildFile(outputFile)
1439
1440 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1441 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1442 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1443 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1444 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1445 AidlIncludeDirs: j.exportAidlIncludeDirs,
1446 SrcJarArgs: j.srcJarArgs,
1447 SrcJarDeps: j.srcJarDeps,
1448 ExportedPlugins: j.exportedPluginJars,
1449 ExportedPluginClasses: j.exportedPluginClasses,
1450 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1451 JacocoReportClassesFile: j.jacocoReportClassesFile,
1452 })
1453
1454 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1455 j.outputFile = outputFile.WithoutRel()
1456}
1457
Colin Crossa1ff7c62021-09-17 14:11:52 -07001458func (j *Module) useCompose() bool {
1459 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1460}
1461
Cole Faust75fffb12021-06-13 15:23:16 -07001462// Returns a copy of the supplied flags, but with all the errorprone-related
1463// fields copied to the regular build's fields.
1464func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1465 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1466
1467 if len(flags.errorProneExtraJavacFlags) > 0 {
1468 if len(flags.javacFlags) > 0 {
1469 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1470 } else {
1471 flags.javacFlags = flags.errorProneExtraJavacFlags
1472 }
1473 }
1474 return flags
1475}
1476
Jaewoong Jung26342642021-03-17 15:56:23 -07001477func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1478 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1479
1480 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1481 if idx >= 0 {
1482 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1483 jarName += strconv.Itoa(idx)
1484 }
1485
1486 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1487 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1488
1489 if ctx.Config().EmitXrefRules() {
1490 extractionFile := android.PathForModuleOut(ctx, kzipName)
1491 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1492 j.kytheFiles = append(j.kytheFiles, extractionFile)
1493 }
1494
1495 return classes
1496}
1497
1498// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1499// since some of these flags may be used internally.
1500func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1501 for _, flag := range flags {
1502 flag = strings.TrimSpace(flag)
1503
1504 if !strings.HasPrefix(flag, "-") {
1505 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1506 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1507 ctx.PropertyErrorf("kotlincflags",
1508 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1509 } else if inList(flag, config.KotlincIllegalFlags) {
1510 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1511 } else if flag == "-include-runtime" {
1512 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1513 } else {
1514 args := strings.Split(flag, " ")
1515 if args[0] == "-kotlin-home" {
1516 ctx.PropertyErrorf("kotlincflags",
1517 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1518 }
1519 }
1520 }
1521}
1522
1523func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1524 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001525 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001526
1527 var jars android.Paths
1528 if len(srcFiles) > 0 || len(srcJars) > 0 {
1529 // Compile java sources into turbine.jar.
1530 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1531 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1532 if ctx.Failed() {
1533 return nil, nil
1534 }
1535 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001536 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001537 }
1538
1539 jars = append(jars, extraJars...)
1540
1541 // Combine any static header libraries into classes-header.jar. If there is only
1542 // one input jar this step will be skipped.
1543 jars = append(jars, deps.staticHeaderJars...)
1544
1545 // we cannot skip the combine step for now if there is only one jar
1546 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1547 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1548 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1549 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001550 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001551
1552 if j.expandJarjarRules != nil {
1553 // Transform classes.jar into classes-jarjar.jar
1554 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001555 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1556 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001557 if ctx.Failed() {
1558 return nil, nil
1559 }
1560 }
1561
Colin Cross3d56ed52021-11-18 22:23:12 -08001562 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001563}
1564
1565func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001566 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001567
1568 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1569 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1570
1571 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1572
1573 j.jacocoReportClassesFile = jacocoReportClassesFile
1574
1575 return instrumentedJar
1576}
1577
1578func (j *Module) HeaderJars() android.Paths {
1579 if j.headerJarFile == nil {
1580 return nil
1581 }
1582 return android.Paths{j.headerJarFile}
1583}
1584
1585func (j *Module) ImplementationJars() android.Paths {
1586 if j.implementationJarFile == nil {
1587 return nil
1588 }
1589 return android.Paths{j.implementationJarFile}
1590}
1591
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001592func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001593 return j.dexJarFile
1594}
1595
1596func (j *Module) DexJarInstallPath() android.Path {
1597 return j.installFile
1598}
1599
1600func (j *Module) ImplementationAndResourcesJars() android.Paths {
1601 if j.implementationAndResourcesJar == nil {
1602 return nil
1603 }
1604 return android.Paths{j.implementationAndResourcesJar}
1605}
1606
1607func (j *Module) AidlIncludeDirs() android.Paths {
1608 // exportAidlIncludeDirs is type android.Paths already
1609 return j.exportAidlIncludeDirs
1610}
1611
1612func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1613 return j.classLoaderContexts
1614}
1615
1616// Collect information for opening IDE project files in java/jdeps.go.
1617func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1618 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1619 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1620 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1621 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1622 if j.expandJarjarRules != nil {
1623 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1624 }
1625 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1626}
1627
1628func (j *Module) CompilerDeps() []string {
1629 jdeps := []string{}
1630 jdeps = append(jdeps, j.properties.Libs...)
1631 jdeps = append(jdeps, j.properties.Static_libs...)
1632 return jdeps
1633}
1634
1635func (j *Module) hasCode(ctx android.ModuleContext) bool {
1636 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1637 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1638}
1639
1640// Implements android.ApexModule
1641func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1642 return j.depIsInSameApex(ctx, dep)
1643}
1644
1645// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001646func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001647 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001648 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001649 return fmt.Errorf("min_sdk_version is not specified")
1650 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001651 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 return nil
1653 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001654 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1655 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001656 }
1657 return nil
1658}
1659
1660func (j *Module) Stem() string {
1661 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1662}
1663
Jaewoong Jung26342642021-03-17 15:56:23 -07001664func (j *Module) JacocoReportClassesFile() android.Path {
1665 return j.jacocoReportClassesFile
1666}
1667
1668func (j *Module) IsInstallable() bool {
1669 return Bool(j.properties.Installable)
1670}
1671
1672type sdkLinkType int
1673
1674const (
1675 // TODO(jiyong) rename these for better readability. Make the allowed
1676 // and disallowed link types explicit
1677 // order is important here. See rank()
1678 javaCore sdkLinkType = iota
1679 javaSdk
1680 javaSystem
1681 javaModule
1682 javaSystemServer
1683 javaPlatform
1684)
1685
1686func (lt sdkLinkType) String() string {
1687 switch lt {
1688 case javaCore:
1689 return "core Java API"
1690 case javaSdk:
1691 return "Android API"
1692 case javaSystem:
1693 return "system API"
1694 case javaModule:
1695 return "module API"
1696 case javaSystemServer:
1697 return "system server API"
1698 case javaPlatform:
1699 return "private API"
1700 default:
1701 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1702 }
1703}
1704
1705// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1706// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1707// can't statically depend on modules that use Platform API.
1708func (lt sdkLinkType) rank() int {
1709 return int(lt)
1710}
1711
1712type moduleWithSdkDep interface {
1713 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001714 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001715}
1716
Jiyong Park92315372021-04-02 08:45:46 +09001717func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001718 switch name {
1719 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1720 "stub-annotations", "private-stub-annotations-jar",
1721 "core-lambda-stubs", "core-generated-annotation-stubs":
1722 return javaCore, true
1723 case "android_stubs_current":
1724 return javaSdk, true
1725 case "android_system_stubs_current":
1726 return javaSystem, true
1727 case "android_module_lib_stubs_current":
1728 return javaModule, true
1729 case "android_system_server_stubs_current":
1730 return javaSystemServer, true
1731 case "android_test_stubs_current":
1732 return javaSystem, true
1733 }
1734
1735 if stub, linkType := moduleStubLinkType(name); stub {
1736 return linkType, true
1737 }
1738
Jiyong Park92315372021-04-02 08:45:46 +09001739 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001740 switch ver.Kind {
1741 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001742 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001743 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001744 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001745 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001746 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001747 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001748 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001749 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001750 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001751 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001752 return javaPlatform, false
1753 }
1754
Jiyong Parkf1691d22021-03-29 20:11:58 +09001755 if !ver.Valid() {
1756 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001757 }
1758 return javaSdk, false
1759}
1760
1761// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1762// this module's. See the comment on rank() for details and an example.
1763func (j *Module) checkSdkLinkType(
1764 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1765 if ctx.Host() {
1766 return
1767 }
1768
Jiyong Park92315372021-04-02 08:45:46 +09001769 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001770 if stubs {
1771 return
1772 }
Jiyong Park92315372021-04-02 08:45:46 +09001773 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001774
1775 if myLinkType.rank() < depLinkType.rank() {
1776 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1777 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1778 "property of the source or target module so that target module is built "+
1779 "with the same or smaller API set when compared to the source.",
1780 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1781 }
1782}
1783
1784func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1785 var deps deps
1786
1787 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001788 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001789 if sdkDep.invalidVersion {
1790 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1791 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1792 } else if sdkDep.useFiles {
1793 // sdkDep.jar is actually equivalent to turbine header.jar.
1794 deps.classpath = append(deps.classpath, sdkDep.jars...)
1795 deps.aidlPreprocess = sdkDep.aidl
1796 } else {
1797 deps.aidlPreprocess = sdkDep.aidl
1798 }
1799 }
1800
Jiyong Park92315372021-04-02 08:45:46 +09001801 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001802
1803 ctx.VisitDirectDeps(func(module android.Module) {
1804 otherName := ctx.OtherModuleName(module)
1805 tag := ctx.OtherModuleDependencyTag(module)
1806
1807 if IsJniDepTag(tag) {
1808 // Handled by AndroidApp.collectAppDeps
1809 return
1810 }
1811 if tag == certificateTag {
1812 // Handled by AndroidApp.collectAppDeps
1813 return
1814 }
1815
1816 if dep, ok := module.(SdkLibraryDependency); ok {
1817 switch tag {
1818 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001819 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001820 case staticLibTag:
1821 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1822 }
1823 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1824 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1825 if sdkLinkType != javaPlatform &&
1826 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1827 // dep is a sysprop implementation library, but this module is not linking against
1828 // the platform, so it gets the sysprop public stubs library instead. Replace
1829 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1830 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1831 dep = syspropDep.JavaInfo
1832 }
1833 switch tag {
1834 case bootClasspathTag:
1835 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1836 case libTag, instrumentationForTag:
1837 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1838 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1839 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1840 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1841 case java9LibTag:
1842 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1843 case staticLibTag:
1844 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1845 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1846 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1847 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1848 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1849 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1850 // Turbine doesn't run annotation processors, so any module that uses an
1851 // annotation processor that generates API is incompatible with the turbine
1852 // optimization.
1853 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1854 case pluginTag:
1855 if plugin, ok := module.(*Plugin); ok {
1856 if plugin.pluginProperties.Processor_class != nil {
1857 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1858 } else {
1859 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1860 }
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 || Bool(plugin.pluginProperties.Generates_api)
1865 } else {
1866 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1867 }
1868 case errorpronePluginTag:
1869 if _, ok := module.(*Plugin); ok {
1870 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1871 } else {
1872 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1873 }
1874 case exportedPluginTag:
1875 if plugin, ok := module.(*Plugin); ok {
1876 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1877 if plugin.pluginProperties.Processor_class != nil {
1878 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1879 }
1880 // Turbine doesn't run annotation processors, so any module that uses an
1881 // annotation processor that generates API is incompatible with the turbine
1882 // optimization.
1883 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1884 } else {
1885 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1886 }
1887 case kotlinStdlibTag:
1888 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1889 case kotlinAnnotationsTag:
1890 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001891 case kotlinPluginTag:
1892 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001893 case syspropPublicStubDepTag:
1894 // This is a sysprop implementation library, forward the JavaInfoProvider from
1895 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1896 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1897 JavaInfo: dep,
1898 })
1899 }
1900 } else if dep, ok := module.(android.SourceFileProducer); ok {
1901 switch tag {
1902 case libTag:
1903 checkProducesJars(ctx, dep)
1904 deps.classpath = append(deps.classpath, dep.Srcs()...)
1905 case staticLibTag:
1906 checkProducesJars(ctx, dep)
1907 deps.classpath = append(deps.classpath, dep.Srcs()...)
1908 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1909 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1910 }
1911 } else {
1912 switch tag {
1913 case bootClasspathTag:
1914 // If a system modules dependency has been added to the bootclasspath
1915 // then add its libs to the bootclasspath.
1916 sm := module.(SystemModulesProvider)
1917 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1918
1919 case systemModulesTag:
1920 if deps.systemModules != nil {
1921 panic("Found two system module dependencies")
1922 }
1923 sm := module.(SystemModulesProvider)
1924 outputDir, outputDeps := sm.OutputDirAndDeps()
1925 deps.systemModules = &systemModules{outputDir, outputDeps}
1926 }
1927 }
1928
1929 addCLCFromDep(ctx, module, j.classLoaderContexts)
1930 })
1931
1932 return deps
1933}
1934
1935func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1936 deps.processorPath = append(deps.processorPath, pluginJars...)
1937 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1938}
1939
1940// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1941// this interface.
1942type ProvidesUsesLib interface {
1943 ProvidesUsesLib() *string
1944}
1945
1946func (j *Module) ProvidesUsesLib() *string {
1947 return j.usesLibraryProperties.Provides_uses_lib
1948}
satayev1c564cc2021-05-25 19:50:30 +01001949
1950type ModuleWithStem interface {
1951 Stem() string
1952}
1953
1954var _ ModuleWithStem = (*Module)(nil)