blob: bc8da9a775e5c140a56f29c84a340d7658b771be [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
Sorin Basca9347ae32021-12-20 11:51:24 +0000125 Openjdk11 struct {
126 // List of source files that should only be used when passing -source 1.9 or higher
127 Srcs []string `android:"path"`
128
129 // List of javac flags that should only be used when passing -source 1.9 or higher
130 Javacflags []string
131 }
132
Jaewoong Jung26342642021-03-17 15:56:23 -0700133 // When compiling language level 9+ .java code in packages that are part of
134 // a system module, patch_module names the module that your sources and
135 // dependencies should be patched into. The Android runtime currently
136 // doesn't implement the JEP 261 module system so this option is only
137 // supported at compile time. It should only be needed to compile tests in
138 // packages that exist in libcore and which are inconvenient to move
139 // elsewhere.
140 Patch_module *string `android:"arch_variant"`
141
142 Jacoco struct {
143 // List of classes to include for instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. If unset defaults to all
145 // classes.
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 Include_filter []string
150
151 // List of classes to exclude from instrumentation with jacoco to collect coverage
152 // information at runtime when building with coverage enabled. Overrides classes selected
153 // by the include_filter property.
154 // Supports '*' as the last character of an entry in the list as a wildcard match.
155 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
156 // it matches classes in the package that have the class name as a prefix.
157 Exclude_filter []string
158 }
159
160 Errorprone struct {
161 // List of javac flags that should only be used when running errorprone.
162 Javacflags []string
163
164 // List of java_plugin modules that provide extra errorprone checks.
165 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700166
Cole Faust2b1536e2021-06-18 12:25:54 -0700167 // This property can be in 3 states. When set to true, errorprone will
168 // be run during the regular build. When set to false, errorprone will
169 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
170 // environment variable is true. Setting this to false will improve build
171 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700172 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700173 }
174
175 Proto struct {
176 // List of extra options that will be passed to the proto generator.
177 Output_params []string
178 }
179
180 Instrument bool `blueprint:"mutated"`
181
182 // List of files to include in the META-INF/services folder of the resulting jar.
183 Services []string `android:"path,arch_variant"`
184
185 // If true, package the kotlin stdlib into the jar. Defaults to true.
186 Static_kotlin_stdlib *bool `android:"arch_variant"`
187
188 // A list of java_library instances that provide additional hiddenapi annotations for the library.
189 Hiddenapi_additional_annotations []string
190}
191
192// Properties that are specific to device modules. Host module factories should not add these when
193// constructing a new module.
194type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000195 // If not blank, set to the version of the sdk to compile against.
Jaewoong Jung26342642021-03-17 15:56:23 -0700196 // Defaults to compiling against the current platform.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000197 // Values are of one of the following forms:
198 // 1) numerical API level or "current"
199 // 2) An SDK kind with an API level: "<sdk kind>_<API level>". See
200 // build/soong/android/sdk_version.go for the complete and up to date list of
201 // SDK kinds. If the SDK kind value is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700202 Sdk_version *string
203
204 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Min_sdk_version *string
207
satayev0a420e72021-11-29 17:25:52 +0000208 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
209 // Defaults to empty string "". See sdk_version for possible values.
210 Max_sdk_version *string
211
Jaewoong Jung26342642021-03-17 15:56:23 -0700212 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000213 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700214 Target_sdk_version *string
215
216 // Whether to compile against the platform APIs instead of an SDK.
217 // If true, then sdk_version must be empty. The value of this field
218 // is ignored when module's type isn't android_app.
219 Platform_apis *bool
220
221 Aidl struct {
222 // Top level directories to pass to aidl tool
223 Include_dirs []string
224
225 // Directories rooted at the Android.bp file to pass to aidl tool
226 Local_include_dirs []string
227
228 // directories that should be added as include directories for any aidl sources of modules
229 // that depend on this module, as well as to aidl for this module.
230 Export_include_dirs []string
231
232 // whether to generate traces (for systrace) for this interface
233 Generate_traces *bool
234
235 // whether to generate Binder#GetTransaction name method.
236 Generate_get_transaction_name *bool
237
238 // list of flags that will be passed to the AIDL compiler
239 Flags []string
240 }
241
242 // If true, export a copy of the module as a -hostdex module for host testing.
243 Hostdex *bool
244
245 Target struct {
246 Hostdex struct {
247 // Additional required dependencies to add to -hostdex modules.
248 Required []string
249 }
250 }
251
252 // When targeting 1.9 and above, override the modules to use with --system,
253 // otherwise provides defaults libraries to add to the bootclasspath.
254 System_modules *string
255
Jaewoong Jung26342642021-03-17 15:56:23 -0700256 IsSDKLibrary bool `blueprint:"mutated"`
257
258 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
259 // Defaults to false.
260 V4_signature *bool
261
262 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
263 // public stubs library.
264 SyspropPublicStub string `blueprint:"mutated"`
265}
266
Jooyung Han01d80d82022-01-08 12:16:32 +0900267// Device properties that can be overridden by overriding module (e.g. override_android_app)
268type OverridableDeviceProperties struct {
269 // set the name of the output. If not set, `name` is used.
270 // To override a module with this property set, overriding module might need to set this as well.
271 // Otherwise, both the overridden and the overriding modules will have the same output name, which
272 // can cause the duplicate output error.
273 Stem *string
274}
275
Jaewoong Jung26342642021-03-17 15:56:23 -0700276// Functionality common to Module and Import
277//
278// It is embedded in Module so its functionality can be used by methods in Module
279// but it is currently only initialized by Import and Library.
280type embeddableInModuleAndImport struct {
281
282 // Functionality related to this being used as a component of a java_sdk_library.
283 EmbeddableSdkLibraryComponent
284}
285
Paul Duffin71b33cc2021-06-23 11:39:47 +0100286func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
287 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700288}
289
290// Module/Import's DepIsInSameApex(...) delegates to this method.
291//
292// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
293// the one provided by ApexModuleBase.
294func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
295 // dependencies other than the static linkage are all considered crossing APEX boundary
296 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
297 return true
298 }
299 return false
300}
301
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100302// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
303// or an invalid path describing the reason it is invalid.
304//
305// It is unset if a dex jar isn't applicable, i.e. no build rule has been
306// requested to create one.
307//
308// If a dex jar has been requested to be built then it is set, and it may be
309// either a valid android.Path, or invalid with a reason message. The latter
310// happens if the source that should produce the dex file isn't able to.
311//
312// E.g. it is invalid with a reason message if there is a prebuilt APEX that
313// could produce the dex jar through a deapexer module, but the APEX isn't
314// installable so doing so wouldn't be safe.
315type OptionalDexJarPath struct {
316 isSet bool
317 path android.OptionalPath
318}
319
320// IsSet returns true if a path has been set, either invalid or valid.
321func (o OptionalDexJarPath) IsSet() bool {
322 return o.isSet
323}
324
325// Valid returns true if there is a path that is valid.
326func (o OptionalDexJarPath) Valid() bool {
327 return o.isSet && o.path.Valid()
328}
329
330// Path returns the valid path, or panics if it's either not set or is invalid.
331func (o OptionalDexJarPath) Path() android.Path {
332 if !o.isSet {
333 panic("path isn't set")
334 }
335 return o.path.Path()
336}
337
338// PathOrNil returns the path if it's set and valid, or else nil.
339func (o OptionalDexJarPath) PathOrNil() android.Path {
340 if o.Valid() {
341 return o.Path()
342 }
343 return nil
344}
345
346// InvalidReason returns the reason for an invalid path, which is never "". It
347// returns "" for an unset or valid path.
348func (o OptionalDexJarPath) InvalidReason() string {
349 if !o.isSet {
350 return ""
351 }
352 return o.path.InvalidReason()
353}
354
355func (o OptionalDexJarPath) String() string {
356 if !o.isSet {
357 return "<unset>"
358 }
359 return o.path.String()
360}
361
362// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
363func makeUnsetDexJarPath() OptionalDexJarPath {
364 return OptionalDexJarPath{isSet: false}
365}
366
367// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
368// the given OptionalPath, which may be valid or invalid.
369func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
370 return OptionalDexJarPath{isSet: true, path: path}
371}
372
373// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
374// valid given path. It returns an unset OptionalDexJarPath if the given path is
375// nil.
376func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
377 if path == nil {
378 return makeUnsetDexJarPath()
379 }
380 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
381}
382
Jaewoong Jung26342642021-03-17 15:56:23 -0700383// Module contains the properties and members used by all java module types
384type Module struct {
385 android.ModuleBase
386 android.DefaultableModuleBase
387 android.ApexModuleBase
388 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800389 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700390
391 // Functionality common to Module and Import.
392 embeddableInModuleAndImport
393
394 properties CommonProperties
395 protoProperties android.ProtoProperties
396 deviceProperties DeviceProperties
397
Jooyung Han01d80d82022-01-08 12:16:32 +0900398 overridableDeviceProperties OverridableDeviceProperties
399
Jaewoong Jung26342642021-03-17 15:56:23 -0700400 // jar file containing header classes including static library dependencies, suitable for
401 // inserting into the bootclasspath/classpath of another compile
402 headerJarFile android.Path
403
404 // jar file containing implementation classes including static library dependencies but no
405 // resources
406 implementationJarFile android.Path
407
408 // jar file containing only resources including from static library dependencies
409 resourceJar android.Path
410
411 // args and dependencies to package source files into a srcjar
412 srcJarArgs []string
413 srcJarDeps android.Paths
414
415 // jar file containing implementation classes and resources including static library
416 // dependencies
417 implementationAndResourcesJar android.Path
418
419 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100420 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700421
422 // output file containing uninstrumented classes that will be instrumented by jacoco
423 jacocoReportClassesFile android.Path
424
425 // output file of the module, which may be a classes jar or a dex jar
426 outputFile android.Path
427 extraOutputFiles android.Paths
428
429 exportAidlIncludeDirs android.Paths
430
431 logtagsSrcs android.Paths
432
433 // installed file for binary dependency
434 installFile android.Path
435
Colin Cross3108ce12021-11-10 14:38:50 -0800436 // installed file for hostdex copy
437 hostdexInstallFile android.InstallPath
438
Jaewoong Jung26342642021-03-17 15:56:23 -0700439 // list of .java files and srcjars that was passed to javac
440 compiledJavaSrcs android.Paths
441 compiledSrcJars android.Paths
442
443 // manifest file to use instead of properties.Manifest
444 overrideManifest android.OptionalPath
445
446 // map of SDK version to class loader context
447 classLoaderContexts dexpreopt.ClassLoaderContextMap
448
449 // list of plugins that this java module is exporting
450 exportedPluginJars android.Paths
451
452 // list of plugins that this java module is exporting
453 exportedPluginClasses []string
454
455 // if true, the exported plugins generate API and require disabling turbine.
456 exportedDisableTurbine bool
457
458 // list of source files, collected from srcFiles with unique java and all kt files,
459 // will be used by android.IDEInfo struct
460 expandIDEInfoCompiledSrcs []string
461
462 // expanded Jarjar_rules
463 expandJarjarRules android.Path
464
Jaewoong Jung26342642021-03-17 15:56:23 -0700465 // Extra files generated by the module type to be added as java resources.
466 extraResources android.Paths
467
468 hiddenAPI
469 dexer
470 dexpreopter
471 usesLibrary
472 linter
473
474 // list of the xref extraction files
475 kytheFiles android.Paths
476
477 // Collect the module directory for IDE info in java/jdeps.go.
478 modulePaths []string
479
480 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900481
482 sdkVersion android.SdkSpec
483 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000484 maxSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700485}
486
Jiyong Park92315372021-04-02 08:45:46 +0900487func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
488 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900489 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700490 return nil
491 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900492 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000493 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700494 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
495 } else {
496 // Treat stable core platform as stable.
497 return nil
498 }
499 } else {
500 return fmt.Errorf("non stable SDK %v", sdkVersion)
501 }
502}
503
504// checkSdkVersions enforces restrictions around SDK dependencies.
505func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
506 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900507 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900508 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700509 ctx.PropertyErrorf("sdk_version",
510 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
511 }
512 }
513 }
514
515 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
516 // See rank() for details.
517 ctx.VisitDirectDeps(func(module android.Module) {
518 tag := ctx.OtherModuleDependencyTag(module)
519 switch module.(type) {
520 // TODO(satayev): cover other types as well, e.g. imports
521 case *Library, *AndroidLibrary:
522 switch tag {
523 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
524 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
525 }
526 }
527 })
528}
529
530func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900531 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700532 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900533 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700534 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000535 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 -0700536 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000537 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 -0700538 }
539
540 }
541}
542
543func (j *Module) addHostProperties() {
544 j.AddProperties(
545 &j.properties,
546 &j.protoProperties,
547 &j.usesLibraryProperties,
548 )
549}
550
551func (j *Module) addHostAndDeviceProperties() {
552 j.addHostProperties()
553 j.AddProperties(
554 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900555 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700556 &j.dexer.dexProperties,
557 &j.dexpreoptProperties,
558 &j.linter.properties,
559 )
560}
561
562func (j *Module) OutputFiles(tag string) (android.Paths, error) {
563 switch tag {
564 case "":
565 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
566 case android.DefaultDistTag:
567 return android.Paths{j.outputFile}, nil
568 case ".jar":
569 return android.Paths{j.implementationAndResourcesJar}, nil
570 case ".proguard_map":
571 if j.dexer.proguardDictionary.Valid() {
572 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
573 }
574 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
575 default:
576 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
577 }
578}
579
580var _ android.OutputFileProducer = (*Module)(nil)
581
582func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
583 initJavaModule(module, hod, false)
584}
585
586func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
587 initJavaModule(module, hod, true)
588}
589
590func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
591 multilib := android.MultilibCommon
592 if multiTargets {
593 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
594 } else {
595 android.InitAndroidArchModule(module, hod, multilib)
596 }
597 android.InitDefaultableModule(module)
598}
599
600func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
601 return j.properties.Instrument &&
602 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
603 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
604}
605
606func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
607 return j.shouldInstrument(ctx) &&
608 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
609 ctx.Config().UnbundledBuild())
610}
611
612func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
613 // Force enable the instrumentation for java code that is built for APEXes ...
614 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
615 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
616 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
617 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
618 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
619 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
620 return true
621 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
622 return true
623 }
624 }
625 return false
626}
627
Jiyong Park92315372021-04-02 08:45:46 +0900628func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
629 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700630}
631
Jiyong Parkf1691d22021-03-29 20:11:58 +0900632func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700633 return proptools.String(j.deviceProperties.System_modules)
634}
635
Jiyong Park92315372021-04-02 08:45:46 +0900636func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700637 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900638 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700639 }
Jiyong Park92315372021-04-02 08:45:46 +0900640 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700641}
642
satayev0a420e72021-11-29 17:25:52 +0000643func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
644 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
645 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
646 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
647 return android.SdkSpecFrom(ctx, maxSdkVersion)
648}
649
Jiyong Parkf1691d22021-03-29 20:11:58 +0900650func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900651 return j.minSdkVersion.Raw
652}
653
654func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
655 if j.deviceProperties.Target_sdk_version != nil {
656 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
657 }
658 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700659}
660
661func (j *Module) AvailableFor(what string) bool {
662 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
663 // Exception: for hostdex: true libraries, the platform variant is created
664 // even if it's not marked as available to platform. In that case, the platform
665 // variant is used only for the hostdex and not installed to the device.
666 return true
667 }
668 return j.ApexModuleBase.AvailableFor(what)
669}
670
671func (j *Module) deps(ctx android.BottomUpMutatorContext) {
672 if ctx.Device() {
673 j.linter.deps(ctx)
674
Jiyong Parkf1691d22021-03-29 20:11:58 +0900675 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700676
677 if j.deviceProperties.SyspropPublicStub != "" {
678 // This is a sysprop implementation library that has a corresponding sysprop public
679 // stubs library, and a dependency on it so that dependencies on the implementation can
680 // be forwarded to the public stubs library when necessary.
681 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
682 }
683 }
684
685 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
686 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
687
688 // Add dependency on libraries that provide additional hidden api annotations.
689 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
690
691 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
692 // Require java_sdk_library at inter-partition java dependency to ensure stable
693 // interface between partitions. If inter-partition java_library dependency is detected,
694 // raise build error because java_library doesn't have a stable interface.
695 //
696 // Inputs:
697 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
698 // if true, enable enforcement
699 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
700 // exception list of java_library names to allow inter-partition dependency
701 for idx := range j.properties.Libs {
702 if libDeps[idx] == nil {
703 continue
704 }
705
706 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
707 // java_sdk_library is always allowed at inter-partition dependency.
708 // So, skip check.
709 if _, ok := javaDep.(*SdkLibrary); ok {
710 continue
711 }
712
713 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
714 }
715 }
716 }
717
718 // For library dependencies that are component libraries (like stubs), add the implementation
719 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
720 for _, dep := range libDeps {
721 if dep != nil {
722 if component, ok := dep.(SdkLibraryComponentDependency); ok {
723 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100724 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100725 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
726 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100727 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700728 }
729 }
730 }
731 }
732
733 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
734 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
735 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
736
737 android.ProtoDeps(ctx, &j.protoProperties)
738 if j.hasSrcExt(".proto") {
739 protoDeps(ctx, &j.protoProperties)
740 }
741
742 if j.hasSrcExt(".kt") {
743 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
744 // Kotlin files
745 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
746 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
747 if len(j.properties.Plugins) > 0 {
748 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
749 }
750 }
751
752 // Framework libraries need special handling in static coverage builds: they should not have
753 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
754 // the same jacoco classes coming from different bootclasspath jars.
755 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
756 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
757 j.properties.Instrument = true
758 }
759 } else if j.shouldInstrumentStatic(ctx) {
760 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
761 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700762
763 if j.useCompose() {
764 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
765 "androidx.compose.compiler_compiler-hosted")
766 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700767}
768
769func hasSrcExt(srcs []string, ext string) bool {
770 for _, src := range srcs {
771 if filepath.Ext(src) == ext {
772 return true
773 }
774 }
775
776 return false
777}
778
779func (j *Module) hasSrcExt(ext string) bool {
780 return hasSrcExt(j.properties.Srcs, ext)
781}
782
783func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
784 aidlIncludeDirs android.Paths) (string, android.Paths) {
785
786 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
787 aidlIncludes = append(aidlIncludes,
788 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
789 aidlIncludes = append(aidlIncludes,
790 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
791
792 var flags []string
793 var deps android.Paths
794
795 flags = append(flags, j.deviceProperties.Aidl.Flags...)
796
797 if aidlPreprocess.Valid() {
798 flags = append(flags, "-p"+aidlPreprocess.String())
799 deps = append(deps, aidlPreprocess.Path())
800 } else if len(aidlIncludeDirs) > 0 {
801 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
802 }
803
804 if len(j.exportAidlIncludeDirs) > 0 {
805 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
806 }
807
808 if len(aidlIncludes) > 0 {
809 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
810 }
811
812 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
813 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
814 flags = append(flags, "-I"+src.String())
815 }
816
817 if Bool(j.deviceProperties.Aidl.Generate_traces) {
818 flags = append(flags, "-t")
819 }
820
821 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
822 flags = append(flags, "--transaction_names")
823 }
824
Jooyung Han07f70c02021-11-06 07:08:45 +0900825 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
826 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
827
Jaewoong Jung26342642021-03-17 15:56:23 -0700828 return strings.Join(flags, " "), deps
829}
830
831func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
832
833 var flags javaBuilderFlags
834
835 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900836 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700837
Cole Faust2b1536e2021-06-18 12:25:54 -0700838 epEnabled := j.properties.Errorprone.Enabled
839 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700840 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
841 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
842 }
843
844 errorProneFlags := []string{
845 "-Xplugin:ErrorProne",
846 "${config.ErrorProneChecks}",
847 }
848 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
849
850 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
851 "'" + strings.Join(errorProneFlags, " ") + "'"
852 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
853 }
854
855 // classpath
856 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
857 flags.classpath = append(flags.classpath, deps.classpath...)
858 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
859 flags.processorPath = append(flags.processorPath, deps.processorPath...)
860 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
861
862 flags.processors = append(flags.processors, deps.processorClasses...)
863 flags.processors = android.FirstUniqueStrings(flags.processors)
864
865 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900866 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700867 // Give host-side tools a version of OpenJDK's standard libraries
868 // close to what they're targeting. As of Dec 2017, AOSP is only
869 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
870 //
871 // When building with OpenJDK 8, the following should have no
872 // effect since those jars would be available by default.
873 //
874 // When building with OpenJDK 9 but targeting a version < 1.8,
875 // putting them on the bootclasspath means that:
876 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
877 // b) references to existing APIs are not reinterpreted in an
878 // OpenJDK 9-specific way, eg. calls to subclasses of
879 // java.nio.Buffer as in http://b/70862583
880 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
881 flags.bootClasspath = append(flags.bootClasspath,
882 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
883 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
884 if Bool(j.properties.Use_tools_jar) {
885 flags.bootClasspath = append(flags.bootClasspath,
886 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
887 }
888 }
889
890 // systemModules
891 flags.systemModules = deps.systemModules
892
893 // aidl flags.
894 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
895
896 return flags
897}
898
899func (j *Module) collectJavacFlags(
900 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
901 // javac flags.
902 javacFlags := j.properties.Javacflags
903
904 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
905 // For non-host binaries, override the -g flag passed globally to remove
906 // local variable debug info to reduce disk and memory usage.
907 javacFlags = append(javacFlags, "-g:source,lines")
908 }
909 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
910
911 if flags.javaVersion.usesJavaModules() {
912 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
913
914 if j.properties.Patch_module != nil {
915 // Manually specify build directory in case it is not under the repo root.
916 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
917 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200918 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700919
920 // b/150878007
921 //
922 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
923 // execution root for --patch-module. If this javac command line is
924 // invoked within Bazel's execution root working directory, the top
925 // level directories (e.g. libcore/, tools/, frameworks/) are all
926 // symlinks. JDK9 javac does not traverse into symlinks, which causes
927 // --patch-module to fail source file lookups when invoked in the
928 // execution root.
929 //
930 // Short of patching javac or enumerating *all* directories as possible
931 // input dirs, manually add the top level dir of the source files to be
932 // compiled.
933 topLevelDirs := map[string]bool{}
934 for _, srcFilePath := range srcFiles {
935 srcFileParts := strings.Split(srcFilePath.String(), "/")
936 // Ignore source files that are already in the top level directory
937 // as well as generated files in the out directory. The out
938 // directory may be an absolute path, which means srcFileParts[0] is the
939 // empty string, so check that as well. Note that "out" in Bazel's execution
940 // root is *not* a symlink, which doesn't cause problems for --patch-modules
941 // anyway, so it's fine to not apply this workaround for generated
942 // source files.
943 if len(srcFileParts) > 1 &&
944 srcFileParts[0] != "" &&
945 srcFileParts[0] != "out" {
946 topLevelDirs[srcFileParts[0]] = true
947 }
948 }
949 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
950
951 classPath := flags.classpath.FormJavaClassPath("")
952 if classPath != "" {
953 patchPaths = append(patchPaths, classPath)
954 }
955 javacFlags = append(
956 javacFlags,
957 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
958 }
959 }
960
961 if len(javacFlags) > 0 {
962 // optimization.
963 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
964 flags.javacFlags = "$javacFlags"
965 }
966
967 return flags
968}
969
970func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
971 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
972
973 deps := j.collectDeps(ctx)
974 flags := j.collectBuilderFlags(ctx, deps)
975
976 if flags.javaVersion.usesJavaModules() {
977 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
978 }
Sorin Basca9347ae32021-12-20 11:51:24 +0000979 if ctx.Config().TargetsJava11() {
980 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk11.Srcs...)
981 }
982
Jaewoong Jung26342642021-03-17 15:56:23 -0700983 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
984 if hasSrcExt(srcFiles.Strings(), ".proto") {
985 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
986 }
987
988 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
989 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
990 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
991 }
992
993 srcFiles = j.genSources(ctx, srcFiles, flags)
994
995 // Collect javac flags only after computing the full set of srcFiles to
996 // ensure that the --patch-module lookup paths are complete.
997 flags = j.collectJavacFlags(ctx, flags, srcFiles)
998
999 srcJars := srcFiles.FilterByExt(".srcjar")
1000 srcJars = append(srcJars, deps.srcJars...)
1001 if aaptSrcJar != nil {
1002 srcJars = append(srcJars, aaptSrcJar)
1003 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001004 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001005
1006 if j.properties.Jarjar_rules != nil {
1007 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1008 }
1009
1010 jarName := ctx.ModuleName() + ".jar"
1011
1012 javaSrcFiles := srcFiles.FilterByExt(".java")
1013 var uniqueSrcFiles android.Paths
1014 set := make(map[string]bool)
1015 for _, v := range javaSrcFiles {
1016 if _, found := set[v.String()]; !found {
1017 set[v.String()] = true
1018 uniqueSrcFiles = append(uniqueSrcFiles, v)
1019 }
1020 }
1021
1022 // Collect .java files for AIDEGen
1023 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1024
1025 var kotlinJars android.Paths
1026
1027 if srcFiles.HasExt(".kt") {
1028 // user defined kotlin flags.
1029 kotlincFlags := j.properties.Kotlincflags
1030 CheckKotlincFlags(ctx, kotlincFlags)
1031
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001032 // Workaround for KT-46512
1033 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001034
1035 // If there are kotlin files, compile them first but pass all the kotlin and java files
1036 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1037 // won't emit any classes for them.
1038 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1039 if ctx.Device() {
1040 kotlincFlags = append(kotlincFlags, "-no-jdk")
1041 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001042
1043 for _, plugin := range deps.kotlinPlugins {
1044 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1045 }
1046 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1047
Jaewoong Jung26342642021-03-17 15:56:23 -07001048 if len(kotlincFlags) > 0 {
1049 // optimization.
1050 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1051 flags.kotlincFlags += "$kotlincFlags"
1052 }
1053
1054 var kotlinSrcFiles android.Paths
1055 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1056 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1057
1058 // Collect .kt files for AIDEGen
1059 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1060 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1061
1062 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1063 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1064
1065 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1066 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1067
1068 if len(flags.processorPath) > 0 {
1069 // Use kapt for annotation processing
1070 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1071 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1072 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1073 srcJars = append(srcJars, kaptSrcJar)
1074 kotlinJars = append(kotlinJars, kaptResJar)
1075 // Disable annotation processing in javac, it's already been handled by kapt
1076 flags.processorPath = nil
1077 flags.processors = nil
1078 }
1079
1080 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
1081 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1082 if ctx.Failed() {
1083 return
1084 }
1085
1086 // Make javac rule depend on the kotlinc rule
1087 flags.classpath = append(flags.classpath, kotlinJar)
1088
1089 kotlinJars = append(kotlinJars, kotlinJar)
1090 // Jar kotlin classes into the final jar after javac
1091 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1092 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
1093 }
1094 }
1095
1096 jars := append(android.Paths(nil), kotlinJars...)
1097
1098 // Store the list of .java files that was passed to javac
1099 j.compiledJavaSrcs = uniqueSrcFiles
1100 j.compiledSrcJars = srcJars
1101
1102 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001103 var headerJarFileWithoutDepsOrJarjar android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001104 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
1105 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1106 enableSharding = true
1107 // Formerly, there was a check here that prevented annotation processors
1108 // from being used when sharding was enabled, as some annotation processors
1109 // do not function correctly in sharded environments. It was removed to
1110 // allow for the use of annotation processors that do function correctly
1111 // with sharding enabled. See: b/77284273.
1112 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001113 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Jaewoong Jung26342642021-03-17 15:56:23 -07001114 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
1115 if ctx.Failed() {
1116 return
1117 }
1118 }
1119 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1120 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001121 if Bool(j.properties.Errorprone.Enabled) {
1122 // If error-prone is enabled, enable errorprone flags on the regular
1123 // build.
1124 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001125 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001126 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1127 // a new jar file just for compiling with the errorprone compiler to.
1128 // This is because we don't want to cause the java files to get completely
1129 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1130 // We also don't want to run this if errorprone is enabled by default for
1131 // this module, or else we could have duplicated errorprone messages.
1132 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001133 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001134
1135 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1136 "errorprone", "errorprone")
1137
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 extraJarDeps = append(extraJarDeps, errorprone)
1139 }
1140
1141 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001142 if headerJarFileWithoutDepsOrJarjar != nil {
1143 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1144 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001145 shardSize := int(*(j.properties.Javac_shard_size))
1146 var shardSrcs []android.Paths
1147 if len(uniqueSrcFiles) > 0 {
1148 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1149 for idx, shardSrc := range shardSrcs {
1150 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1151 nil, flags, extraJarDeps)
1152 jars = append(jars, classes)
1153 }
1154 }
1155 if len(srcJars) > 0 {
1156 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1157 nil, srcJars, flags, extraJarDeps)
1158 jars = append(jars, classes)
1159 }
1160 } else {
1161 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1162 jars = append(jars, classes)
1163 }
1164 if ctx.Failed() {
1165 return
1166 }
1167 }
1168
1169 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1170
1171 var includeSrcJar android.WritablePath
1172 if Bool(j.properties.Include_srcs) {
1173 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1174 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1175 }
1176
1177 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1178 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1179 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1180 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1181
1182 var resArgs []string
1183 var resDeps android.Paths
1184
1185 resArgs = append(resArgs, dirArgs...)
1186 resDeps = append(resDeps, dirDeps...)
1187
1188 resArgs = append(resArgs, fileArgs...)
1189 resDeps = append(resDeps, fileDeps...)
1190
1191 resArgs = append(resArgs, extraArgs...)
1192 resDeps = append(resDeps, extraDeps...)
1193
1194 if len(resArgs) > 0 {
1195 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1196 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1197 j.resourceJar = resourceJar
1198 if ctx.Failed() {
1199 return
1200 }
1201 }
1202
1203 var resourceJars android.Paths
1204 if j.resourceJar != nil {
1205 resourceJars = append(resourceJars, j.resourceJar)
1206 }
1207 if Bool(j.properties.Include_srcs) {
1208 resourceJars = append(resourceJars, includeSrcJar)
1209 }
1210 resourceJars = append(resourceJars, deps.staticResourceJars...)
1211
1212 if len(resourceJars) > 1 {
1213 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1214 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1215 false, nil, nil)
1216 j.resourceJar = combinedJar
1217 } else if len(resourceJars) == 1 {
1218 j.resourceJar = resourceJars[0]
1219 }
1220
1221 if len(deps.staticJars) > 0 {
1222 jars = append(jars, deps.staticJars...)
1223 }
1224
1225 manifest := j.overrideManifest
1226 if !manifest.Valid() && j.properties.Manifest != nil {
1227 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1228 }
1229
1230 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1231 if len(services) > 0 {
1232 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1233 var zipargs []string
1234 for _, file := range services {
1235 serviceFile := file.String()
1236 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1237 }
1238 rule := zip
1239 args := map[string]string{
1240 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1241 }
1242 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1243 rule = zipRE
1244 args["implicits"] = strings.Join(services.Strings(), ",")
1245 }
1246 ctx.Build(pctx, android.BuildParams{
1247 Rule: rule,
1248 Output: servicesJar,
1249 Implicits: services,
1250 Args: args,
1251 })
1252 jars = append(jars, servicesJar)
1253 }
1254
1255 // Combine the classes built from sources, any manifests, and any static libraries into
1256 // classes.jar. If there is only one input jar this step will be skipped.
1257 var outputFile android.OutputPath
1258
1259 if len(jars) == 1 && !manifest.Valid() {
1260 // Optimization: skip the combine step as there is nothing to do
1261 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1262 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1263 // any if len(jars) == 1.
1264
1265 // Transform the single path to the jar into an OutputPath as that is required by the following
1266 // code.
1267 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1268 // The path contains an embedded OutputPath so reuse that.
1269 outputFile = moduleOutPath.OutputPath
1270 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1271 // The path is an OutputPath so reuse it directly.
1272 outputFile = outputPath
1273 } else {
1274 // The file is not in the out directory so create an OutputPath into which it can be copied
1275 // and which the following code can use to refer to it.
1276 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1277 ctx.Build(pctx, android.BuildParams{
1278 Rule: android.Cp,
1279 Input: jars[0],
1280 Output: combinedJar,
1281 })
1282 outputFile = combinedJar.OutputPath
1283 }
1284 } else {
1285 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1286 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1287 false, nil, nil)
1288 outputFile = combinedJar.OutputPath
1289 }
1290
1291 // jarjar implementation jar if necessary
1292 if j.expandJarjarRules != nil {
1293 // Transform classes.jar into classes-jarjar.jar
1294 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1295 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1296 outputFile = jarjarFile
1297
1298 // jarjar resource jar if necessary
1299 if j.resourceJar != nil {
1300 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1301 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1302 j.resourceJar = resourceJarJarFile
1303 }
1304
1305 if ctx.Failed() {
1306 return
1307 }
1308 }
1309
1310 // Check package restrictions if necessary.
1311 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001312 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001313 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001314
1315 // Create a rule to copy the output jar to another path and add a validate dependency that
1316 // will check that the jar only contains the permitted packages. The new location will become
1317 // the output file of this module.
1318 inputFile := outputFile
1319 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1320 ctx.Build(pctx, android.BuildParams{
1321 Rule: android.Cp,
1322 Input: inputFile,
1323 Output: outputFile,
1324 // Make sure that any dependency on the output file will cause ninja to run the package check
1325 // rule.
1326 Validation: pkgckFile,
1327 })
1328
1329 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001330 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001331
1332 if ctx.Failed() {
1333 return
1334 }
1335 }
1336
1337 j.implementationJarFile = outputFile
1338 if j.headerJarFile == nil {
1339 j.headerJarFile = j.implementationJarFile
1340 }
1341
1342 if j.shouldInstrumentInApex(ctx) {
1343 j.properties.Instrument = true
1344 }
1345
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001346 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1347 specs := j.jacocoModuleToZipCommand(ctx)
1348 if ctx.Failed() {
1349 return
1350 }
1351
Jaewoong Jung26342642021-03-17 15:56:23 -07001352 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001353 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001354 }
1355
1356 // merge implementation jar with resources if necessary
1357 implementationAndResourcesJar := outputFile
1358 if j.resourceJar != nil {
1359 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1360 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1361 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1362 false, nil, nil)
1363 implementationAndResourcesJar = combinedJar
1364 }
1365
1366 j.implementationAndResourcesJar = implementationAndResourcesJar
1367
1368 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1369 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1370 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1371 if j.dexProperties.Compile_dex == nil {
1372 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1373 }
1374 if j.deviceProperties.Hostdex == nil {
1375 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1376 }
1377 }
1378
1379 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1380 if j.hasCode(ctx) {
1381 if j.shouldInstrumentStatic(ctx) {
1382 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1383 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1384 }
1385 // Dex compilation
1386 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001387 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001388 if ctx.Failed() {
1389 return
1390 }
1391
Jaewoong Jung26342642021-03-17 15:56:23 -07001392 // merge dex jar with resources if necessary
1393 if j.resourceJar != nil {
1394 jars := android.Paths{dexOutputFile, j.resourceJar}
1395 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1396 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1397 false, nil, nil)
1398 if *j.dexProperties.Uncompress_dex {
1399 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1400 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1401 dexOutputFile = combinedAlignedJar
1402 } else {
1403 dexOutputFile = combinedJar
1404 }
1405 }
1406
Paul Duffin4de94502021-05-16 05:21:16 +01001407 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001408
1409 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001410
1411 // Encode hidden API flags in dex file, if needed.
1412 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1413
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001414 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001415
1416 // Dexpreopting
1417 j.dexpreopt(ctx, dexOutputFile)
1418
1419 outputFile = dexOutputFile
1420 } else {
1421 // There is no code to compile into a dex jar, make sure the resources are propagated
1422 // to the APK if this is an app.
1423 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001424 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001425 }
1426
1427 if ctx.Failed() {
1428 return
1429 }
1430 } else {
1431 outputFile = implementationAndResourcesJar
1432 }
1433
1434 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001435 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001436 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001437 return v.String()
1438 } else {
1439 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1440 }
1441 }
1442
1443 j.linter.name = ctx.ModuleName()
1444 j.linter.srcs = srcFiles
1445 j.linter.srcJars = srcJars
1446 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1447 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001448 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1449 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1450 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001451 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001452 j.linter.javaLanguageLevel = flags.javaVersion.String()
1453 j.linter.kotlinLanguageLevel = "1.3"
1454 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1455 j.linter.buildModuleReportZip = true
1456 }
1457 j.linter.lint(ctx)
1458 }
1459
1460 ctx.CheckbuildFile(outputFile)
1461
1462 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1463 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1464 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1465 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1466 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1467 AidlIncludeDirs: j.exportAidlIncludeDirs,
1468 SrcJarArgs: j.srcJarArgs,
1469 SrcJarDeps: j.srcJarDeps,
1470 ExportedPlugins: j.exportedPluginJars,
1471 ExportedPluginClasses: j.exportedPluginClasses,
1472 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1473 JacocoReportClassesFile: j.jacocoReportClassesFile,
1474 })
1475
1476 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1477 j.outputFile = outputFile.WithoutRel()
1478}
1479
Colin Crossa1ff7c62021-09-17 14:11:52 -07001480func (j *Module) useCompose() bool {
1481 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1482}
1483
Cole Faust75fffb12021-06-13 15:23:16 -07001484// Returns a copy of the supplied flags, but with all the errorprone-related
1485// fields copied to the regular build's fields.
1486func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1487 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1488
1489 if len(flags.errorProneExtraJavacFlags) > 0 {
1490 if len(flags.javacFlags) > 0 {
1491 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1492 } else {
1493 flags.javacFlags = flags.errorProneExtraJavacFlags
1494 }
1495 }
1496 return flags
1497}
1498
Jaewoong Jung26342642021-03-17 15:56:23 -07001499func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1500 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1501
1502 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1503 if idx >= 0 {
1504 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1505 jarName += strconv.Itoa(idx)
1506 }
1507
1508 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1509 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1510
1511 if ctx.Config().EmitXrefRules() {
1512 extractionFile := android.PathForModuleOut(ctx, kzipName)
1513 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1514 j.kytheFiles = append(j.kytheFiles, extractionFile)
1515 }
1516
1517 return classes
1518}
1519
1520// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1521// since some of these flags may be used internally.
1522func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1523 for _, flag := range flags {
1524 flag = strings.TrimSpace(flag)
1525
1526 if !strings.HasPrefix(flag, "-") {
1527 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1528 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1529 ctx.PropertyErrorf("kotlincflags",
1530 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1531 } else if inList(flag, config.KotlincIllegalFlags) {
1532 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1533 } else if flag == "-include-runtime" {
1534 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1535 } else {
1536 args := strings.Split(flag, " ")
1537 if args[0] == "-kotlin-home" {
1538 ctx.PropertyErrorf("kotlincflags",
1539 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1540 }
1541 }
1542 }
1543}
1544
1545func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1546 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001547 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001548
1549 var jars android.Paths
1550 if len(srcFiles) > 0 || len(srcJars) > 0 {
1551 // Compile java sources into turbine.jar.
1552 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1553 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1554 if ctx.Failed() {
1555 return nil, nil
1556 }
1557 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001558 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001559 }
1560
1561 jars = append(jars, extraJars...)
1562
1563 // Combine any static header libraries into classes-header.jar. If there is only
1564 // one input jar this step will be skipped.
1565 jars = append(jars, deps.staticHeaderJars...)
1566
1567 // we cannot skip the combine step for now if there is only one jar
1568 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1569 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1570 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1571 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001572 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001573
1574 if j.expandJarjarRules != nil {
1575 // Transform classes.jar into classes-jarjar.jar
1576 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001577 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1578 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001579 if ctx.Failed() {
1580 return nil, nil
1581 }
1582 }
1583
Colin Cross3d56ed52021-11-18 22:23:12 -08001584 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001585}
1586
1587func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001588 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001589
1590 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1591 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1592
1593 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1594
1595 j.jacocoReportClassesFile = jacocoReportClassesFile
1596
1597 return instrumentedJar
1598}
1599
1600func (j *Module) HeaderJars() android.Paths {
1601 if j.headerJarFile == nil {
1602 return nil
1603 }
1604 return android.Paths{j.headerJarFile}
1605}
1606
1607func (j *Module) ImplementationJars() android.Paths {
1608 if j.implementationJarFile == nil {
1609 return nil
1610 }
1611 return android.Paths{j.implementationJarFile}
1612}
1613
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001614func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001615 return j.dexJarFile
1616}
1617
1618func (j *Module) DexJarInstallPath() android.Path {
1619 return j.installFile
1620}
1621
1622func (j *Module) ImplementationAndResourcesJars() android.Paths {
1623 if j.implementationAndResourcesJar == nil {
1624 return nil
1625 }
1626 return android.Paths{j.implementationAndResourcesJar}
1627}
1628
1629func (j *Module) AidlIncludeDirs() android.Paths {
1630 // exportAidlIncludeDirs is type android.Paths already
1631 return j.exportAidlIncludeDirs
1632}
1633
1634func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1635 return j.classLoaderContexts
1636}
1637
1638// Collect information for opening IDE project files in java/jdeps.go.
1639func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1640 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1641 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1642 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1643 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1644 if j.expandJarjarRules != nil {
1645 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1646 }
1647 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1648}
1649
1650func (j *Module) CompilerDeps() []string {
1651 jdeps := []string{}
1652 jdeps = append(jdeps, j.properties.Libs...)
1653 jdeps = append(jdeps, j.properties.Static_libs...)
1654 return jdeps
1655}
1656
1657func (j *Module) hasCode(ctx android.ModuleContext) bool {
1658 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1659 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1660}
1661
1662// Implements android.ApexModule
1663func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1664 return j.depIsInSameApex(ctx, dep)
1665}
1666
1667// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001668func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001669 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001670 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001671 return fmt.Errorf("min_sdk_version is not specified")
1672 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001673 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001674 return nil
1675 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001676 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1677 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001678 }
1679 return nil
1680}
1681
1682func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001683 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001684}
1685
Jaewoong Jung26342642021-03-17 15:56:23 -07001686func (j *Module) JacocoReportClassesFile() android.Path {
1687 return j.jacocoReportClassesFile
1688}
1689
1690func (j *Module) IsInstallable() bool {
1691 return Bool(j.properties.Installable)
1692}
1693
1694type sdkLinkType int
1695
1696const (
1697 // TODO(jiyong) rename these for better readability. Make the allowed
1698 // and disallowed link types explicit
1699 // order is important here. See rank()
1700 javaCore sdkLinkType = iota
1701 javaSdk
1702 javaSystem
1703 javaModule
1704 javaSystemServer
1705 javaPlatform
1706)
1707
1708func (lt sdkLinkType) String() string {
1709 switch lt {
1710 case javaCore:
1711 return "core Java API"
1712 case javaSdk:
1713 return "Android API"
1714 case javaSystem:
1715 return "system API"
1716 case javaModule:
1717 return "module API"
1718 case javaSystemServer:
1719 return "system server API"
1720 case javaPlatform:
1721 return "private API"
1722 default:
1723 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1724 }
1725}
1726
1727// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1728// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1729// can't statically depend on modules that use Platform API.
1730func (lt sdkLinkType) rank() int {
1731 return int(lt)
1732}
1733
1734type moduleWithSdkDep interface {
1735 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001736 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001737}
1738
Jiyong Park92315372021-04-02 08:45:46 +09001739func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001740 switch name {
1741 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1742 "stub-annotations", "private-stub-annotations-jar",
1743 "core-lambda-stubs", "core-generated-annotation-stubs":
1744 return javaCore, true
1745 case "android_stubs_current":
1746 return javaSdk, true
1747 case "android_system_stubs_current":
1748 return javaSystem, true
1749 case "android_module_lib_stubs_current":
1750 return javaModule, true
1751 case "android_system_server_stubs_current":
1752 return javaSystemServer, true
1753 case "android_test_stubs_current":
1754 return javaSystem, true
1755 }
1756
1757 if stub, linkType := moduleStubLinkType(name); stub {
1758 return linkType, true
1759 }
1760
Jiyong Park92315372021-04-02 08:45:46 +09001761 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001762 switch ver.Kind {
1763 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001764 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001765 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001766 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001767 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001768 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001769 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001770 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001771 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001772 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001773 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001774 return javaPlatform, false
1775 }
1776
Jiyong Parkf1691d22021-03-29 20:11:58 +09001777 if !ver.Valid() {
1778 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001779 }
1780 return javaSdk, false
1781}
1782
1783// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1784// this module's. See the comment on rank() for details and an example.
1785func (j *Module) checkSdkLinkType(
1786 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1787 if ctx.Host() {
1788 return
1789 }
1790
Jiyong Park92315372021-04-02 08:45:46 +09001791 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001792 if stubs {
1793 return
1794 }
Jiyong Park92315372021-04-02 08:45:46 +09001795 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001796
1797 if myLinkType.rank() < depLinkType.rank() {
1798 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1799 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1800 "property of the source or target module so that target module is built "+
1801 "with the same or smaller API set when compared to the source.",
1802 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1803 }
1804}
1805
1806func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1807 var deps deps
1808
1809 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001810 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001811 if sdkDep.invalidVersion {
1812 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1813 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1814 } else if sdkDep.useFiles {
1815 // sdkDep.jar is actually equivalent to turbine header.jar.
1816 deps.classpath = append(deps.classpath, sdkDep.jars...)
1817 deps.aidlPreprocess = sdkDep.aidl
1818 } else {
1819 deps.aidlPreprocess = sdkDep.aidl
1820 }
1821 }
1822
Jiyong Park92315372021-04-02 08:45:46 +09001823 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001824
1825 ctx.VisitDirectDeps(func(module android.Module) {
1826 otherName := ctx.OtherModuleName(module)
1827 tag := ctx.OtherModuleDependencyTag(module)
1828
1829 if IsJniDepTag(tag) {
1830 // Handled by AndroidApp.collectAppDeps
1831 return
1832 }
1833 if tag == certificateTag {
1834 // Handled by AndroidApp.collectAppDeps
1835 return
1836 }
1837
1838 if dep, ok := module.(SdkLibraryDependency); ok {
1839 switch tag {
1840 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001841 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001842 case staticLibTag:
1843 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1844 }
1845 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1846 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1847 if sdkLinkType != javaPlatform &&
1848 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1849 // dep is a sysprop implementation library, but this module is not linking against
1850 // the platform, so it gets the sysprop public stubs library instead. Replace
1851 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1852 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1853 dep = syspropDep.JavaInfo
1854 }
1855 switch tag {
1856 case bootClasspathTag:
1857 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1858 case libTag, instrumentationForTag:
1859 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1860 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1861 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1862 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1863 case java9LibTag:
1864 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1865 case staticLibTag:
1866 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1867 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1868 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1869 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1870 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1871 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1872 // Turbine doesn't run annotation processors, so any module that uses an
1873 // annotation processor that generates API is incompatible with the turbine
1874 // optimization.
1875 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1876 case pluginTag:
1877 if plugin, ok := module.(*Plugin); ok {
1878 if plugin.pluginProperties.Processor_class != nil {
1879 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1880 } else {
1881 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1882 }
1883 // Turbine doesn't run annotation processors, so any module that uses an
1884 // annotation processor that generates API is incompatible with the turbine
1885 // optimization.
1886 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1887 } else {
1888 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1889 }
1890 case errorpronePluginTag:
1891 if _, ok := module.(*Plugin); ok {
1892 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1893 } else {
1894 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1895 }
1896 case exportedPluginTag:
1897 if plugin, ok := module.(*Plugin); ok {
1898 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1899 if plugin.pluginProperties.Processor_class != nil {
1900 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1901 }
1902 // Turbine doesn't run annotation processors, so any module that uses an
1903 // annotation processor that generates API is incompatible with the turbine
1904 // optimization.
1905 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1906 } else {
1907 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1908 }
1909 case kotlinStdlibTag:
1910 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1911 case kotlinAnnotationsTag:
1912 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001913 case kotlinPluginTag:
1914 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001915 case syspropPublicStubDepTag:
1916 // This is a sysprop implementation library, forward the JavaInfoProvider from
1917 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1918 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1919 JavaInfo: dep,
1920 })
1921 }
1922 } else if dep, ok := module.(android.SourceFileProducer); ok {
1923 switch tag {
1924 case libTag:
1925 checkProducesJars(ctx, dep)
1926 deps.classpath = append(deps.classpath, dep.Srcs()...)
1927 case staticLibTag:
1928 checkProducesJars(ctx, dep)
1929 deps.classpath = append(deps.classpath, dep.Srcs()...)
1930 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1931 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1932 }
1933 } else {
1934 switch tag {
1935 case bootClasspathTag:
1936 // If a system modules dependency has been added to the bootclasspath
1937 // then add its libs to the bootclasspath.
1938 sm := module.(SystemModulesProvider)
1939 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1940
1941 case systemModulesTag:
1942 if deps.systemModules != nil {
1943 panic("Found two system module dependencies")
1944 }
1945 sm := module.(SystemModulesProvider)
1946 outputDir, outputDeps := sm.OutputDirAndDeps()
1947 deps.systemModules = &systemModules{outputDir, outputDeps}
1948 }
1949 }
1950
1951 addCLCFromDep(ctx, module, j.classLoaderContexts)
1952 })
1953
1954 return deps
1955}
1956
1957func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1958 deps.processorPath = append(deps.processorPath, pluginJars...)
1959 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1960}
1961
1962// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1963// this interface.
1964type ProvidesUsesLib interface {
1965 ProvidesUsesLib() *string
1966}
1967
1968func (j *Module) ProvidesUsesLib() *string {
1969 return j.usesLibraryProperties.Provides_uses_lib
1970}
satayev1c564cc2021-05-25 19:50:30 +01001971
1972type ModuleWithStem interface {
1973 Stem() string
1974}
1975
1976var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08001977
1978func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1979 switch ctx.ModuleType() {
1980 case "java_library", "java_library_host":
1981 if lib, ok := ctx.Module().(*Library); ok {
1982 javaLibraryBp2Build(ctx, lib)
1983 }
1984 case "java_binary_host":
1985 if binary, ok := ctx.Module().(*Binary); ok {
1986 javaBinaryHostBp2Build(ctx, binary)
1987 }
1988 }
1989
1990}