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