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