blob: c5f22d21435deac139972046a8b8be3860a0e0c4 [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"
Joe Onorato349ae8d2024-02-05 22:46:00 +000020 "reflect"
21 "slices"
Jaewoong Jung26342642021-03-17 15:56:23 -070022 "strconv"
23 "strings"
24
Colin Crossd788b3e2023-11-28 13:14:56 -080025 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070026 "github.com/google/blueprint/pathtools"
27 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
30 "android/soong/dexpreopt"
31 "android/soong/java/config"
32)
33
34// This file contains the definition and the implementation of the base module that most
35// source-based Java module structs embed.
36
37// TODO:
38// Autogenerated files:
39// Renderscript
40// Post-jar passes:
41// Proguard
42// Rmtypedefs
43// DroidDoc
44// Findbugs
45
46// Properties that are common to most Java modules, i.e. whether it's a host or device module.
47type CommonProperties struct {
48 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
49 // or .aidl files.
50 Srcs []string `android:"path,arch_variant"`
51
52 // list Kotlin of source files containing Kotlin code that should be treated as common code in
53 // a codebase that supports Kotlin multiplatform. See
54 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
55 Common_srcs []string `android:"path,arch_variant"`
56
57 // list of source files that should not be used to build the Java module.
58 // This is most useful in the arch/multilib variants to remove non-common files
59 Exclude_srcs []string `android:"path,arch_variant"`
60
61 // list of directories containing Java resources
62 Java_resource_dirs []string `android:"arch_variant"`
63
64 // list of directories that should be excluded from java_resource_dirs
65 Exclude_java_resource_dirs []string `android:"arch_variant"`
66
67 // list of files to use as Java resources
68 Java_resources []string `android:"path,arch_variant"`
69
70 // list of files that should be excluded from java_resources and java_resource_dirs
71 Exclude_java_resources []string `android:"path,arch_variant"`
72
73 // list of module-specific flags that will be used for javac compiles
74 Javacflags []string `android:"arch_variant"`
75
76 // list of module-specific flags that will be used for kotlinc compiles
77 Kotlincflags []string `android:"arch_variant"`
78
79 // list of java libraries that will be in the classpath
80 Libs []string `android:"arch_variant"`
81
82 // list of java libraries that will be compiled into the resulting jar
83 Static_libs []string `android:"arch_variant"`
84
Jihoon Kang381c2fa2023-06-01 22:17:32 +000085 // list of java libraries that should not be used to build this module
86 Exclude_static_libs []string `android:"arch_variant"`
87
Jaewoong Jung26342642021-03-17 15:56:23 -070088 // manifest file to be included in resulting jar
89 Manifest *string `android:"path"`
90
91 // if not blank, run jarjar using the specified rules file
92 Jarjar_rules *string `android:"path,arch_variant"`
93
Joe Onorato349ae8d2024-02-05 22:46:00 +000094 // if not blank, used as prefix to generate repackage rule
95 Jarjar_prefix *string
96
Jaewoong Jung26342642021-03-17 15:56:23 -070097 // If not blank, set the java version passed to javac as -source and -target
98 Java_version *string
99
100 // If set to true, allow this module to be dexed and installed on devices. Has no
101 // effect on host modules, which are always considered installable.
102 Installable *bool
103
104 // If set to true, include sources used to compile the module in to the final jar
105 Include_srcs *bool
106
107 // If not empty, classes are restricted to the specified packages and their sub-packages.
108 // This restriction is checked after applying jarjar rules and including static libs.
109 Permitted_packages []string
110
111 // List of modules to use as annotation processors
112 Plugins []string
113
114 // List of modules to export to libraries that directly depend on this library as annotation
115 // processors. Note that if the plugins set generates_api: true this will disable the turbine
116 // optimization on modules that depend on this module, which will reduce parallelism and cause
117 // more recompilation.
118 Exported_plugins []string
119
120 // The number of Java source entries each Javac instance can process
121 Javac_shard_size *int64
122
123 // Add host jdk tools.jar to bootclasspath
124 Use_tools_jar *bool
125
126 Openjdk9 struct {
127 // List of source files that should only be used when passing -source 1.9 or higher
128 Srcs []string `android:"path"`
129
130 // List of javac flags that should only be used when passing -source 1.9 or higher
131 Javacflags []string
132 }
133
134 // When compiling language level 9+ .java code in packages that are part of
135 // a system module, patch_module names the module that your sources and
136 // dependencies should be patched into. The Android runtime currently
137 // doesn't implement the JEP 261 module system so this option is only
138 // supported at compile time. It should only be needed to compile tests in
139 // packages that exist in libcore and which are inconvenient to move
140 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400141 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700142
143 Jacoco struct {
144 // List of classes to include for instrumentation with jacoco to collect coverage
145 // information at runtime when building with coverage enabled. If unset defaults to all
146 // classes.
147 // Supports '*' as the last character of an entry in the list as a wildcard match.
148 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
149 // it matches classes in the package that have the class name as a prefix.
150 Include_filter []string
151
152 // List of classes to exclude from instrumentation with jacoco to collect coverage
153 // information at runtime when building with coverage enabled. Overrides classes selected
154 // by the include_filter property.
155 // Supports '*' as the last character of an entry in the list as a wildcard match.
156 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
157 // it matches classes in the package that have the class name as a prefix.
158 Exclude_filter []string
159 }
160
161 Errorprone struct {
162 // List of javac flags that should only be used when running errorprone.
163 Javacflags []string
164
165 // List of java_plugin modules that provide extra errorprone checks.
166 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700167
Cole Faust2b1536e2021-06-18 12:25:54 -0700168 // This property can be in 3 states. When set to true, errorprone will
169 // be run during the regular build. When set to false, errorprone will
170 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
171 // environment variable is true. Setting this to false will improve build
172 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700173 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700174 }
175
176 Proto struct {
177 // List of extra options that will be passed to the proto generator.
178 Output_params []string
179 }
180
Sam Delmericoc7593722022-08-31 15:57:52 -0400181 // If true, then jacocoagent is automatically added as a libs dependency so that
182 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700183 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000184 // If true, then the module supports statically including the jacocoagent
185 // into the library.
186 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700187
188 // List of files to include in the META-INF/services folder of the resulting jar.
189 Services []string `android:"path,arch_variant"`
190
191 // If true, package the kotlin stdlib into the jar. Defaults to true.
192 Static_kotlin_stdlib *bool `android:"arch_variant"`
193
194 // A list of java_library instances that provide additional hiddenapi annotations for the library.
195 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700196
197 // Additional srcJars tacked in by GeneratedJavaLibraryModule
198 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000199
200 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400201 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800202
203 // A list of files or dependencies to make available to the build sandbox. This is
204 // useful if source files are symlinks, the targets of the symlinks must be listed here.
205 // Note that currently not all actions implemented by android_apps are sandboxed, so you
206 // may only see this being necessary in lint builds.
207 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000208
209 // Property signifying whether the module compiles stubs or not.
210 // Should be set to true when srcs of this module are stub files.
211 // This property does not need to be set to true when the module depends on
212 // the stubs via libs, but should be set to true when the module depends on
213 // the stubs via static libs.
214 Is_stubs_module *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700215}
216
217// Properties that are specific to device modules. Host module factories should not add these when
218// constructing a new module.
219type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000220 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000221 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000222 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000223 // 1) numerical API level, "current", "none", or "core_platform"
224 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
225 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
226 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700227 Sdk_version *string
228
229 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000230 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700231 Min_sdk_version *string
232
satayev0a420e72021-11-29 17:25:52 +0000233 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
234 // Defaults to empty string "". See sdk_version for possible values.
235 Max_sdk_version *string
236
William Loh5a082f92022-05-17 20:21:50 +0000237 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
238 // Defaults to empty string "". See sdk_version for possible values.
239 Replace_max_sdk_version_placeholder *string
240
Jaewoong Jung26342642021-03-17 15:56:23 -0700241 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000242 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700243 Target_sdk_version *string
244
245 // Whether to compile against the platform APIs instead of an SDK.
246 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000247 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700248 Platform_apis *bool
249
250 Aidl struct {
251 // Top level directories to pass to aidl tool
252 Include_dirs []string
253
254 // Directories rooted at the Android.bp file to pass to aidl tool
255 Local_include_dirs []string
256
257 // directories that should be added as include directories for any aidl sources of modules
258 // that depend on this module, as well as to aidl for this module.
259 Export_include_dirs []string
260
261 // whether to generate traces (for systrace) for this interface
262 Generate_traces *bool
263
264 // whether to generate Binder#GetTransaction name method.
265 Generate_get_transaction_name *bool
266
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100267 // whether all interfaces should be annotated with required permissions.
268 Enforce_permissions *bool
269
270 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
271 Enforce_permissions_exceptions []string `android:"path"`
272
Jaewoong Jung26342642021-03-17 15:56:23 -0700273 // list of flags that will be passed to the AIDL compiler
274 Flags []string
275 }
276
277 // If true, export a copy of the module as a -hostdex module for host testing.
278 Hostdex *bool
279
280 Target struct {
281 Hostdex struct {
282 // Additional required dependencies to add to -hostdex modules.
283 Required []string
284 }
285 }
286
287 // When targeting 1.9 and above, override the modules to use with --system,
288 // otherwise provides defaults libraries to add to the bootclasspath.
289 System_modules *string
290
Jaewoong Jung26342642021-03-17 15:56:23 -0700291 IsSDKLibrary bool `blueprint:"mutated"`
292
293 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
294 // Defaults to false.
295 V4_signature *bool
296
297 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
298 // public stubs library.
299 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000300
301 HiddenAPIPackageProperties
302 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700303}
304
Jooyung Han01d80d82022-01-08 12:16:32 +0900305// Device properties that can be overridden by overriding module (e.g. override_android_app)
306type OverridableDeviceProperties struct {
307 // set the name of the output. If not set, `name` is used.
308 // To override a module with this property set, overriding module might need to set this as well.
309 // Otherwise, both the overridden and the overriding modules will have the same output name, which
310 // can cause the duplicate output error.
311 Stem *string
312}
313
Jaewoong Jung26342642021-03-17 15:56:23 -0700314// Functionality common to Module and Import
315//
316// It is embedded in Module so its functionality can be used by methods in Module
317// but it is currently only initialized by Import and Library.
318type embeddableInModuleAndImport struct {
319
320 // Functionality related to this being used as a component of a java_sdk_library.
321 EmbeddableSdkLibraryComponent
322}
323
Paul Duffin71b33cc2021-06-23 11:39:47 +0100324func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
325 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700326}
327
328// Module/Import's DepIsInSameApex(...) delegates to this method.
329//
330// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
331// the one provided by ApexModuleBase.
332func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
333 // dependencies other than the static linkage are all considered crossing APEX boundary
334 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
335 return true
336 }
337 return false
338}
339
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100340// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
341// or an invalid path describing the reason it is invalid.
342//
343// It is unset if a dex jar isn't applicable, i.e. no build rule has been
344// requested to create one.
345//
346// If a dex jar has been requested to be built then it is set, and it may be
347// either a valid android.Path, or invalid with a reason message. The latter
348// happens if the source that should produce the dex file isn't able to.
349//
350// E.g. it is invalid with a reason message if there is a prebuilt APEX that
351// could produce the dex jar through a deapexer module, but the APEX isn't
352// installable so doing so wouldn't be safe.
353type OptionalDexJarPath struct {
354 isSet bool
355 path android.OptionalPath
356}
357
358// IsSet returns true if a path has been set, either invalid or valid.
359func (o OptionalDexJarPath) IsSet() bool {
360 return o.isSet
361}
362
363// Valid returns true if there is a path that is valid.
364func (o OptionalDexJarPath) Valid() bool {
365 return o.isSet && o.path.Valid()
366}
367
368// Path returns the valid path, or panics if it's either not set or is invalid.
369func (o OptionalDexJarPath) Path() android.Path {
370 if !o.isSet {
371 panic("path isn't set")
372 }
373 return o.path.Path()
374}
375
376// PathOrNil returns the path if it's set and valid, or else nil.
377func (o OptionalDexJarPath) PathOrNil() android.Path {
378 if o.Valid() {
379 return o.Path()
380 }
381 return nil
382}
383
384// InvalidReason returns the reason for an invalid path, which is never "". It
385// returns "" for an unset or valid path.
386func (o OptionalDexJarPath) InvalidReason() string {
387 if !o.isSet {
388 return ""
389 }
390 return o.path.InvalidReason()
391}
392
393func (o OptionalDexJarPath) String() string {
394 if !o.isSet {
395 return "<unset>"
396 }
397 return o.path.String()
398}
399
400// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
401func makeUnsetDexJarPath() OptionalDexJarPath {
402 return OptionalDexJarPath{isSet: false}
403}
404
405// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
406// the given OptionalPath, which may be valid or invalid.
407func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
408 return OptionalDexJarPath{isSet: true, path: path}
409}
410
411// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
412// valid given path. It returns an unset OptionalDexJarPath if the given path is
413// nil.
414func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
415 if path == nil {
416 return makeUnsetDexJarPath()
417 }
418 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
419}
420
Jaewoong Jung26342642021-03-17 15:56:23 -0700421// Module contains the properties and members used by all java module types
422type Module struct {
423 android.ModuleBase
424 android.DefaultableModuleBase
425 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700426
427 // Functionality common to Module and Import.
428 embeddableInModuleAndImport
429
430 properties CommonProperties
431 protoProperties android.ProtoProperties
432 deviceProperties DeviceProperties
433
Jooyung Han01d80d82022-01-08 12:16:32 +0900434 overridableDeviceProperties OverridableDeviceProperties
435
Jaewoong Jung26342642021-03-17 15:56:23 -0700436 // jar file containing header classes including static library dependencies, suitable for
437 // inserting into the bootclasspath/classpath of another compile
438 headerJarFile android.Path
439
Joe Onorato349ae8d2024-02-05 22:46:00 +0000440 repackagedHeaderJarFile android.Path
441
Jaewoong Jung26342642021-03-17 15:56:23 -0700442 // jar file containing implementation classes including static library dependencies but no
443 // resources
444 implementationJarFile android.Path
445
446 // jar file containing only resources including from static library dependencies
447 resourceJar android.Path
448
449 // args and dependencies to package source files into a srcjar
450 srcJarArgs []string
451 srcJarDeps android.Paths
452
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000453 // the source files of this module and all its static dependencies
454 transitiveSrcFiles *android.DepSet[android.Path]
455
Jaewoong Jung26342642021-03-17 15:56:23 -0700456 // jar file containing implementation classes and resources including static library
457 // dependencies
458 implementationAndResourcesJar android.Path
459
460 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100461 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700462
463 // output file containing uninstrumented classes that will be instrumented by jacoco
464 jacocoReportClassesFile android.Path
465
466 // output file of the module, which may be a classes jar or a dex jar
467 outputFile android.Path
468 extraOutputFiles android.Paths
469
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100470 exportAidlIncludeDirs android.Paths
471 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700472
473 logtagsSrcs android.Paths
474
475 // installed file for binary dependency
476 installFile android.Path
477
Colin Cross3108ce12021-11-10 14:38:50 -0800478 // installed file for hostdex copy
479 hostdexInstallFile android.InstallPath
480
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800481 // list of unique .java and .kt source files
482 uniqueSrcFiles android.Paths
483
484 // list of srcjars that was passed to javac
485 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700486
487 // manifest file to use instead of properties.Manifest
488 overrideManifest android.OptionalPath
489
Jaewoong Jung26342642021-03-17 15:56:23 -0700490 // list of plugins that this java module is exporting
491 exportedPluginJars android.Paths
492
493 // list of plugins that this java module is exporting
494 exportedPluginClasses []string
495
496 // if true, the exported plugins generate API and require disabling turbine.
497 exportedDisableTurbine bool
498
499 // list of source files, collected from srcFiles with unique java and all kt files,
500 // will be used by android.IDEInfo struct
501 expandIDEInfoCompiledSrcs []string
502
503 // expanded Jarjar_rules
504 expandJarjarRules android.Path
505
Joe Onorato349ae8d2024-02-05 22:46:00 +0000506 // jarjar rule for inherited jarjar rules
507 repackageJarjarRules android.Path
508
Jaewoong Jung26342642021-03-17 15:56:23 -0700509 // Extra files generated by the module type to be added as java resources.
510 extraResources android.Paths
511
512 hiddenAPI
513 dexer
514 dexpreopter
515 usesLibrary
516 linter
517
518 // list of the xref extraction files
519 kytheFiles android.Paths
520
Jaewoong Jung26342642021-03-17 15:56:23 -0700521 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900522
523 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000524 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000525 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400526
527 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000528
529 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000530
531 // output file name based on Stem property.
532 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
533 // or the module should override Stem().
534 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700535
Colin Crossd788b3e2023-11-28 13:14:56 -0800536 // Single aconfig "cache file" merged from this module and all dependencies.
537 mergedAconfigFiles map[string]android.Paths
Joe Onorato349ae8d2024-02-05 22:46:00 +0000538
539 // Values that will be set in the JarJarProvider data for jarjar repackaging,
540 // and merged with our dependencies' rules.
541 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000542
543 stubsLinkType StubsLinkType
Jaewoong Jung26342642021-03-17 15:56:23 -0700544}
545
Jiyong Park92315372021-04-02 08:45:46 +0900546func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
547 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900548 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700549 return nil
550 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900551 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000552 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700553 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
554 } else {
555 // Treat stable core platform as stable.
556 return nil
557 }
558 } else {
559 return fmt.Errorf("non stable SDK %v", sdkVersion)
560 }
561}
562
563// checkSdkVersions enforces restrictions around SDK dependencies.
564func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
565 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900566 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900567 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700568 ctx.PropertyErrorf("sdk_version",
569 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
570 }
571 }
572 }
573
574 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
575 // See rank() for details.
576 ctx.VisitDirectDeps(func(module android.Module) {
577 tag := ctx.OtherModuleDependencyTag(module)
578 switch module.(type) {
579 // TODO(satayev): cover other types as well, e.g. imports
580 case *Library, *AndroidLibrary:
581 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400582 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700583 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
584 }
585 }
586 })
587}
588
589func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900590 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700591 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900592 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700593 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000594 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 -0700595 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000596 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 -0700597 }
598
599 }
600}
601
Mark Whitea15790a2023-08-22 21:28:11 +0000602func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
603 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400604 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000605 installable := proptools.Bool(j.properties.Installable)
606
607 if headersOnly && installable {
608 ctx.PropertyErrorf("headers_only", "This module has conflicting settings. headers_only is true which, which means this module doesn't generate an implementation jar. However installable is set to true.")
609 }
610 }
611}
612
Jaewoong Jung26342642021-03-17 15:56:23 -0700613func (j *Module) addHostProperties() {
614 j.AddProperties(
615 &j.properties,
616 &j.protoProperties,
617 &j.usesLibraryProperties,
618 )
619}
620
621func (j *Module) addHostAndDeviceProperties() {
622 j.addHostProperties()
623 j.AddProperties(
624 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900625 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700626 &j.dexer.dexProperties,
627 &j.dexpreoptProperties,
628 &j.linter.properties,
629 )
630}
631
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000632// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
633// makes it available through the hiddenAPIPropertyInfoProvider.
634func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
635 hiddenAPIInfo := newHiddenAPIPropertyInfo()
636
637 // Populate with flag file paths from the properties.
638 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
639
640 // Populate with package rules from the properties.
641 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
642
Colin Cross40213022023-12-13 15:19:49 -0800643 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000644}
645
Jaewoong Jung26342642021-03-17 15:56:23 -0700646func (j *Module) OutputFiles(tag string) (android.Paths, error) {
647 switch tag {
648 case "":
649 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
650 case android.DefaultDistTag:
651 return android.Paths{j.outputFile}, nil
652 case ".jar":
653 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700654 case ".hjar":
655 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700656 case ".proguard_map":
657 if j.dexer.proguardDictionary.Valid() {
658 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
659 }
660 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700661 case ".generated_srcjars":
662 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000663 case ".lint":
664 if j.linter.outputs.xml != nil {
665 return android.Paths{j.linter.outputs.xml}, nil
666 }
667 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700668 default:
669 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
670 }
671}
672
673var _ android.OutputFileProducer = (*Module)(nil)
674
675func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
676 initJavaModule(module, hod, false)
677}
678
679func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
680 initJavaModule(module, hod, true)
681}
682
683func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
684 multilib := android.MultilibCommon
685 if multiTargets {
686 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
687 } else {
688 android.InitAndroidArchModule(module, hod, multilib)
689 }
690 android.InitDefaultableModule(module)
691}
692
693func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
694 return j.properties.Instrument &&
695 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
696 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
697}
698
699func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000700 return j.properties.Supports_static_instrumentation &&
701 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700702 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
703 ctx.Config().UnbundledBuild())
704}
705
706func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
707 // Force enable the instrumentation for java code that is built for APEXes ...
708 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
709 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
Colin Crossff694a82023-12-13 15:54:49 -0800710 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700711 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
712 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
713 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
714 return true
715 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
716 return true
717 }
718 }
719 return false
720}
721
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400722func (j *Module) setInstrument(value bool) {
723 j.properties.Instrument = value
724}
725
Jiyong Park92315372021-04-02 08:45:46 +0900726func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
727 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700728}
729
Jiyong Parkf1691d22021-03-29 20:11:58 +0900730func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700731 return proptools.String(j.deviceProperties.System_modules)
732}
733
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000734func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700735 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000736 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700737 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000738 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700739}
740
Yu Liuf2b94012023-09-19 15:09:10 -0700741func (j *Module) GetDeviceProperties() *DeviceProperties {
742 return &j.deviceProperties
743}
744
Spandan Dasa26eda72023-03-02 00:56:06 +0000745func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
746 if j.deviceProperties.Max_sdk_version != nil {
747 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
748 }
749 // Default is PrivateApiLevel
750 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000751}
752
Spandan Dasa26eda72023-03-02 00:56:06 +0000753func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
754 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
755 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
756 }
757 // Default is PrivateApiLevel
758 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000759}
760
Jiyong Parkf1691d22021-03-29 20:11:58 +0900761func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000762 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900763}
764
Spandan Dasca70fc42023-03-01 23:38:49 +0000765func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900766 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000767 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900768 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000769 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700770}
771
772func (j *Module) AvailableFor(what string) bool {
773 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
774 // Exception: for hostdex: true libraries, the platform variant is created
775 // even if it's not marked as available to platform. In that case, the platform
776 // variant is used only for the hostdex and not installed to the device.
777 return true
778 }
779 return j.ApexModuleBase.AvailableFor(what)
780}
781
782func (j *Module) deps(ctx android.BottomUpMutatorContext) {
783 if ctx.Device() {
784 j.linter.deps(ctx)
785
Jiyong Parkf1691d22021-03-29 20:11:58 +0900786 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700787
788 if j.deviceProperties.SyspropPublicStub != "" {
789 // This is a sysprop implementation library that has a corresponding sysprop public
790 // stubs library, and a dependency on it so that dependencies on the implementation can
791 // be forwarded to the public stubs library when necessary.
792 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
793 }
794 }
795
796 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000797
798 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700799 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
800
801 // Add dependency on libraries that provide additional hidden api annotations.
802 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
803
804 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
805 // Require java_sdk_library at inter-partition java dependency to ensure stable
806 // interface between partitions. If inter-partition java_library dependency is detected,
807 // raise build error because java_library doesn't have a stable interface.
808 //
809 // Inputs:
810 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
811 // if true, enable enforcement
812 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
813 // exception list of java_library names to allow inter-partition dependency
814 for idx := range j.properties.Libs {
815 if libDeps[idx] == nil {
816 continue
817 }
818
819 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
820 // java_sdk_library is always allowed at inter-partition dependency.
821 // So, skip check.
822 if _, ok := javaDep.(*SdkLibrary); ok {
823 continue
824 }
825
826 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
827 }
828 }
829 }
830
831 // For library dependencies that are component libraries (like stubs), add the implementation
832 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
833 for _, dep := range libDeps {
834 if dep != nil {
835 if component, ok := dep.(SdkLibraryComponentDependency); ok {
836 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100837 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100838 tag := usesLibReqTag
839 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
840 tag = usesLibOptTag
841 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100842 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700843 }
844 }
845 }
846 }
847
848 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
849 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
850 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
851
852 android.ProtoDeps(ctx, &j.protoProperties)
853 if j.hasSrcExt(".proto") {
854 protoDeps(ctx, &j.protoProperties)
855 }
856
857 if j.hasSrcExt(".kt") {
858 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
859 // Kotlin files
860 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
861 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700862 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700863 }
864
865 // Framework libraries need special handling in static coverage builds: they should not have
866 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
867 // the same jacoco classes coming from different bootclasspath jars.
868 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
869 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
870 j.properties.Instrument = true
871 }
872 } else if j.shouldInstrumentStatic(ctx) {
873 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
874 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700875
876 if j.useCompose() {
877 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
878 "androidx.compose.compiler_compiler-hosted")
879 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700880}
881
882func hasSrcExt(srcs []string, ext string) bool {
883 for _, src := range srcs {
884 if filepath.Ext(src) == ext {
885 return true
886 }
887 }
888
889 return false
890}
891
892func (j *Module) hasSrcExt(ext string) bool {
893 return hasSrcExt(j.properties.Srcs, ext)
894}
895
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100896func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
897 var flags string
898
899 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
900 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
901 flags = "-Wmissing-permission-annotation -Werror"
902 }
903 }
904 return flags
905}
906
Jaewoong Jung26342642021-03-17 15:56:23 -0700907func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000908 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700909
910 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
911 aidlIncludes = append(aidlIncludes,
912 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
913 aidlIncludes = append(aidlIncludes,
914 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
915
916 var flags []string
917 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000918 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700919
920 flags = append(flags, j.deviceProperties.Aidl.Flags...)
921
922 if aidlPreprocess.Valid() {
923 flags = append(flags, "-p"+aidlPreprocess.String())
924 deps = append(deps, aidlPreprocess.Path())
925 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000926 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700927 }
928
929 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000930 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700931 }
932
933 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000934 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700935 }
936
Sam Delmerico2351eac2022-05-24 17:10:02 +0000937 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700938 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000939 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700940 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000941 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
942 // add flags for dirs containing AIDL srcs that haven't been specified yet
943 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700944
Zim8774ae12022-08-17 11:46:34 +0100945 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000946 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100947 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700948 flags = append(flags, "-t")
949 }
950
951 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
952 flags = append(flags, "--transaction_names")
953 }
954
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100955 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
956 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
957 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
958 }
959
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000960 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900961 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
962
Jaewoong Jung26342642021-03-17 15:56:23 -0700963 return strings.Join(flags, " "), deps
964}
965
966func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
967
968 var flags javaBuilderFlags
969
970 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900971 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700972
Cole Faust2b1536e2021-06-18 12:25:54 -0700973 epEnabled := j.properties.Errorprone.Enabled
974 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100975 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700976 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
977 }
978
979 errorProneFlags := []string{
980 "-Xplugin:ErrorProne",
981 "${config.ErrorProneChecks}",
982 }
983 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
984
Colin Cross8bf6cad2022-02-28 13:07:03 -0800985 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700986 "'" + strings.Join(errorProneFlags, " ") + "'"
987 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
988 }
989
990 // classpath
991 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
992 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700993 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700994 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
995 flags.processorPath = append(flags.processorPath, deps.processorPath...)
996 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
997
998 flags.processors = append(flags.processors, deps.processorClasses...)
999 flags.processors = android.FirstUniqueStrings(flags.processors)
1000
1001 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001002 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001003 // Give host-side tools a version of OpenJDK's standard libraries
1004 // close to what they're targeting. As of Dec 2017, AOSP is only
1005 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1006 //
1007 // When building with OpenJDK 8, the following should have no
1008 // effect since those jars would be available by default.
1009 //
1010 // When building with OpenJDK 9 but targeting a version < 1.8,
1011 // putting them on the bootclasspath means that:
1012 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1013 // b) references to existing APIs are not reinterpreted in an
1014 // OpenJDK 9-specific way, eg. calls to subclasses of
1015 // java.nio.Buffer as in http://b/70862583
1016 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1017 flags.bootClasspath = append(flags.bootClasspath,
1018 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1019 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1020 if Bool(j.properties.Use_tools_jar) {
1021 flags.bootClasspath = append(flags.bootClasspath,
1022 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1023 }
1024 }
1025
1026 // systemModules
1027 flags.systemModules = deps.systemModules
1028
Jaewoong Jung26342642021-03-17 15:56:23 -07001029 return flags
1030}
1031
1032func (j *Module) collectJavacFlags(
1033 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1034 // javac flags.
1035 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001036 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001037
Mythri Alle4b9f6182023-10-25 15:17:11 +00001038 needsDebugInfo = false
1039 for _, flag := range javacFlags {
1040 if strings.HasPrefix(flag, "-g") {
1041 needsDebugInfo = true
1042 }
1043 }
1044
1045 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001046 // For non-host binaries, override the -g flag passed globally to remove
1047 // local variable debug info to reduce disk and memory usage.
1048 javacFlags = append(javacFlags, "-g:source,lines")
1049 }
1050 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1051
1052 if flags.javaVersion.usesJavaModules() {
1053 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001054 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1055 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1056 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1057 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001058
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001059 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001060 if j.properties.Patch_module != nil {
1061 // Manually specify build directory in case it is not under the repo root.
1062 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1063 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001064 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001065
Jaewoong Jung26342642021-03-17 15:56:23 -07001066 classPath := flags.classpath.FormJavaClassPath("")
1067 if classPath != "" {
1068 patchPaths = append(patchPaths, classPath)
1069 }
1070 javacFlags = append(
1071 javacFlags,
1072 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1073 }
1074 }
1075
1076 if len(javacFlags) > 0 {
1077 // optimization.
1078 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1079 flags.javacFlags = "$javacFlags"
1080 }
1081
1082 return flags
1083}
1084
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001085func (j *Module) AddJSONData(d *map[string]interface{}) {
1086 (&j.ModuleBase).AddJSONData(d)
1087 (*d)["Java"] = map[string]interface{}{
1088 "SourceExtensions": j.sourceExtensions,
1089 }
1090
1091}
1092
usta0391ca42023-09-19 15:51:59 -04001093func (j *Module) addGeneratedSrcJars(path android.Path) {
1094 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001095}
1096
Colin Cross4eae06d2023-06-20 22:40:02 -07001097func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001098
1099 // Auto-propagating jarjar rules
1100 jarjarProviderData := j.collectJarJarRules(ctx)
1101 if jarjarProviderData != nil {
1102 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
1103 text := getJarJarRuleText(jarjarProviderData)
1104 if text != "" {
1105 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1106 android.WriteFileRule(ctx, ruleTextFile, text)
1107 j.repackageJarjarRules = ruleTextFile
1108 }
1109 }
1110
Jaewoong Jung26342642021-03-17 15:56:23 -07001111 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1112
1113 deps := j.collectDeps(ctx)
1114 flags := j.collectBuilderFlags(ctx, deps)
1115
1116 if flags.javaVersion.usesJavaModules() {
1117 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001118 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1119 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1120 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001121 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001122
Jaewoong Jung26342642021-03-17 15:56:23 -07001123 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001124 j.sourceExtensions = []string{}
1125 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1126 if hasSrcExt(srcFiles.Strings(), ext) {
1127 j.sourceExtensions = append(j.sourceExtensions, ext)
1128 }
1129 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001130 if hasSrcExt(srcFiles.Strings(), ".proto") {
1131 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1132 }
1133
1134 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1135 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1136 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1137 }
1138
Sam Delmerico2351eac2022-05-24 17:10:02 +00001139 aidlSrcs := srcFiles.FilterByExt(".aidl")
1140 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1141
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001142 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001143 srcFiles = j.genSources(ctx, srcFiles, flags)
1144
1145 // Collect javac flags only after computing the full set of srcFiles to
1146 // ensure that the --patch-module lookup paths are complete.
1147 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1148
1149 srcJars := srcFiles.FilterByExt(".srcjar")
1150 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001151 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001152 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001153 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001154
1155 if j.properties.Jarjar_rules != nil {
1156 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1157 }
1158
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001159 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001160
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001161 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001162 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001163 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001164 if _, found := set[v.String()]; !found {
1165 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001166 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001167 }
1168 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001169 var uniqueKtFiles android.Paths
1170 for _, v := range srcFiles.FilterByExt(".kt") {
1171 if _, found := set[v.String()]; !found {
1172 set[v.String()] = true
1173 uniqueKtFiles = append(uniqueKtFiles, v)
1174 }
1175 }
1176
1177 var uniqueSrcFiles android.Paths
1178 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1179 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1180 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001181 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001182
Colin Crossb5db4012022-03-28 17:12:39 -07001183 // We don't currently run annotation processors in turbine, which means we can't use turbine
1184 // generated header jars when an annotation processor that generates API is enabled. One
1185 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1186 // is used to run all of the annotation processors.
1187 disableTurbine := deps.disableTurbine
1188
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001189 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001190 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1191
1192 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001193 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001194
Colin Cross4eae06d2023-06-20 22:40:02 -07001195 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1196 // any dependencies so that it can override any non-final R classes from dependencies with the
1197 // final R classes from the app.
1198 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1199
Mark Whitea15790a2023-08-22 21:28:11 +00001200 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001201 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001202 if srcFiles.HasExt(".kt") {
1203 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1204 }
1205 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1206 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1207 }
1208
Joe Onorato349ae8d2024-02-05 22:46:00 +00001209 _, j.headerJarFile, _ =
Mark Whitea15790a2023-08-22 21:28:11 +00001210 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1211 extraCombinedJars)
1212 if ctx.Failed() {
1213 return
1214 }
1215
Colin Cross40213022023-12-13 15:19:49 -08001216 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Mark Whitea15790a2023-08-22 21:28:11 +00001217 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1218 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1219 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1220 AidlIncludeDirs: j.exportAidlIncludeDirs,
1221 ExportedPlugins: j.exportedPluginJars,
1222 ExportedPluginClasses: j.exportedPluginClasses,
1223 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
Jihoon Kangfe914ed2024-02-12 22:49:21 +00001224 StubsLinkType: j.stubsLinkType,
Mark Whitea15790a2023-08-22 21:28:11 +00001225 })
1226
1227 j.outputFile = j.headerJarFile
1228 return
1229 }
1230
Jaewoong Jung26342642021-03-17 15:56:23 -07001231 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001232 // When using kotlin sources turbine is used to generate annotation processor sources,
1233 // including for annotation processors that generate API, so we can use turbine for
1234 // java sources too.
1235 disableTurbine = false
1236
Jaewoong Jung26342642021-03-17 15:56:23 -07001237 // user defined kotlin flags.
1238 kotlincFlags := j.properties.Kotlincflags
1239 CheckKotlincFlags(ctx, kotlincFlags)
1240
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001241 // Workaround for KT-46512
1242 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001243
1244 // If there are kotlin files, compile them first but pass all the kotlin and java files
1245 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1246 // won't emit any classes for them.
1247 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1248 if ctx.Device() {
1249 kotlincFlags = append(kotlincFlags, "-no-jdk")
1250 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001251
1252 for _, plugin := range deps.kotlinPlugins {
1253 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1254 }
1255 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1256
Jaewoong Jung26342642021-03-17 15:56:23 -07001257 if len(kotlincFlags) > 0 {
1258 // optimization.
1259 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1260 flags.kotlincFlags += "$kotlincFlags"
1261 }
1262
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001263 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1265
1266 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1267 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1268
1269 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1270 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1271
Isaac Chioua23d9942022-04-06 06:14:38 +00001272 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001273 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001274 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1275 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001276 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001277 srcJars = append(srcJars, kaptSrcJar)
1278 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001279 // Disable annotation processing in javac, it's already been handled by kapt
1280 flags.processorPath = nil
1281 flags.processors = nil
1282 }
1283
1284 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001285 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001286 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001287 if ctx.Failed() {
1288 return
1289 }
1290
Isaac Chioua23d9942022-04-06 06:14:38 +00001291 // Make javac rule depend on the kotlinc rule
1292 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1293
Jaewoong Jung26342642021-03-17 15:56:23 -07001294 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001295 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1296
Jaewoong Jung26342642021-03-17 15:56:23 -07001297 // Jar kotlin classes into the final jar after javac
1298 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1299 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001300 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001301 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001302 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001303 } else {
1304 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001305 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001306 }
1307 }
1308
Colin Crossfd620b22024-02-23 10:05:21 -08001309 jars := slices.Clone(kotlinJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001310
Jaewoong Jung26342642021-03-17 15:56:23 -07001311 j.compiledSrcJars = srcJars
1312
1313 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001314 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001315 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001316 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1317 enableSharding = true
1318 // Formerly, there was a check here that prevented annotation processors
1319 // from being used when sharding was enabled, as some annotation processors
1320 // do not function correctly in sharded environments. It was removed to
1321 // allow for the use of annotation processors that do function correctly
1322 // with sharding enabled. See: b/77284273.
1323 }
Colin Crossfd620b22024-02-23 10:05:21 -08001324 extraJars := append(slices.Clone(kotlinHeaderJars), extraCombinedJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00001325 headerJarFileWithoutDepsOrJarjar, j.headerJarFile, j.repackagedHeaderJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001326 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001327 if ctx.Failed() {
1328 return
1329 }
1330 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001331 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001332 hasErrorproneableFiles := false
1333 for _, ext := range j.sourceExtensions {
1334 if ext != ".proto" && ext != ".aidl" {
1335 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1336 // compile, and it's not useful to have warnings on these generated sources.
1337 hasErrorproneableFiles = true
1338 break
1339 }
1340 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001341 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001342 if Bool(j.properties.Errorprone.Enabled) {
1343 // If error-prone is enabled, enable errorprone flags on the regular
1344 // build.
1345 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001346 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001347 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1348 // a new jar file just for compiling with the errorprone compiler to.
1349 // This is because we don't want to cause the java files to get completely
1350 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1351 // We also don't want to run this if errorprone is enabled by default for
1352 // this module, or else we could have duplicated errorprone messages.
1353 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001354 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001355 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001356
Vadim Spivak3c496f02023-06-08 06:14:59 +00001357 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001358 "errorprone", "errorprone")
1359
Jaewoong Jung26342642021-03-17 15:56:23 -07001360 extraJarDeps = append(extraJarDeps, errorprone)
1361 }
1362
1363 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001364 if headerJarFileWithoutDepsOrJarjar != nil {
1365 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1366 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001367 shardSize := int(*(j.properties.Javac_shard_size))
1368 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001369 if len(uniqueJavaFiles) > 0 {
1370 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001371 for idx, shardSrc := range shardSrcs {
1372 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1373 nil, flags, extraJarDeps)
1374 jars = append(jars, classes)
1375 }
1376 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001377 // Assume approximately 5 sources per srcjar.
1378 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1379 // of 5.8 sources per srcjar, but a median of 1, a standard deviation of 10, and a max of 48 source files.
Jaewoong Jung26342642021-03-17 15:56:23 -07001380 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001381 startIdx := len(shardSrcs)
1382 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1383 for idx, shardSrcJars := range shardSrcJarsList {
1384 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1385 nil, shardSrcJars, flags, extraJarDeps)
1386 jars = append(jars, classes)
1387 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001388 }
1389 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001390 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001391 jars = append(jars, classes)
1392 }
1393 if ctx.Failed() {
1394 return
1395 }
1396 }
1397
Colin Crossfd620b22024-02-23 10:05:21 -08001398 jars = append(jars, extraCombinedJars...)
1399
Jaewoong Jung26342642021-03-17 15:56:23 -07001400 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1401
1402 var includeSrcJar android.WritablePath
1403 if Bool(j.properties.Include_srcs) {
1404 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1405 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1406 }
1407
1408 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1409 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1410 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1411 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1412
1413 var resArgs []string
1414 var resDeps android.Paths
1415
1416 resArgs = append(resArgs, dirArgs...)
1417 resDeps = append(resDeps, dirDeps...)
1418
1419 resArgs = append(resArgs, fileArgs...)
1420 resDeps = append(resDeps, fileDeps...)
1421
1422 resArgs = append(resArgs, extraArgs...)
1423 resDeps = append(resDeps, extraDeps...)
1424
1425 if len(resArgs) > 0 {
1426 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1427 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1428 j.resourceJar = resourceJar
1429 if ctx.Failed() {
1430 return
1431 }
1432 }
1433
1434 var resourceJars android.Paths
1435 if j.resourceJar != nil {
1436 resourceJars = append(resourceJars, j.resourceJar)
1437 }
1438 if Bool(j.properties.Include_srcs) {
1439 resourceJars = append(resourceJars, includeSrcJar)
1440 }
1441 resourceJars = append(resourceJars, deps.staticResourceJars...)
1442
1443 if len(resourceJars) > 1 {
1444 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1445 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1446 false, nil, nil)
1447 j.resourceJar = combinedJar
1448 } else if len(resourceJars) == 1 {
1449 j.resourceJar = resourceJars[0]
1450 }
1451
1452 if len(deps.staticJars) > 0 {
1453 jars = append(jars, deps.staticJars...)
1454 }
1455
1456 manifest := j.overrideManifest
1457 if !manifest.Valid() && j.properties.Manifest != nil {
1458 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1459 }
1460
1461 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1462 if len(services) > 0 {
1463 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1464 var zipargs []string
1465 for _, file := range services {
1466 serviceFile := file.String()
1467 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1468 }
1469 rule := zip
1470 args := map[string]string{
1471 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1472 }
1473 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1474 rule = zipRE
1475 args["implicits"] = strings.Join(services.Strings(), ",")
1476 }
1477 ctx.Build(pctx, android.BuildParams{
1478 Rule: rule,
1479 Output: servicesJar,
1480 Implicits: services,
1481 Args: args,
1482 })
1483 jars = append(jars, servicesJar)
1484 }
1485
1486 // Combine the classes built from sources, any manifests, and any static libraries into
1487 // classes.jar. If there is only one input jar this step will be skipped.
1488 var outputFile android.OutputPath
1489
1490 if len(jars) == 1 && !manifest.Valid() {
1491 // Optimization: skip the combine step as there is nothing to do
1492 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1493 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1494 // any if len(jars) == 1.
1495
Jihoon Kang1147b312023-06-08 23:25:57 +00001496 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1497 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1498 // either with .from-source or .from-text suffix.
1499 // outputFile should be agnostic to the build configuration,
1500 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1501 // to the copy rules.
1502 stub, _ := moduleStubLinkType(ctx.ModuleName())
1503
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 // Transform the single path to the jar into an OutputPath as that is required by the following
1505 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001506 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001507 // The path contains an embedded OutputPath so reuse that.
1508 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001509 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001510 // The path is an OutputPath so reuse it directly.
1511 outputFile = outputPath
1512 } else {
1513 // The file is not in the out directory so create an OutputPath into which it can be copied
1514 // and which the following code can use to refer to it.
1515 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1516 ctx.Build(pctx, android.BuildParams{
1517 Rule: android.Cp,
1518 Input: jars[0],
1519 Output: combinedJar,
1520 })
1521 outputFile = combinedJar.OutputPath
1522 }
1523 } else {
1524 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1525 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1526 false, nil, nil)
1527 outputFile = combinedJar.OutputPath
1528 }
1529
1530 // jarjar implementation jar if necessary
1531 if j.expandJarjarRules != nil {
1532 // Transform classes.jar into classes-jarjar.jar
1533 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1534 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1535 outputFile = jarjarFile
1536
1537 // jarjar resource jar if necessary
1538 if j.resourceJar != nil {
1539 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1540 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1541 j.resourceJar = resourceJarJarFile
1542 }
1543
1544 if ctx.Failed() {
1545 return
1546 }
1547 }
1548
Joe Onorato349ae8d2024-02-05 22:46:00 +00001549 // Automatic jarjar rules propagation
1550 if j.repackageJarjarRules != nil {
1551 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", jarName).OutputPath
1552 TransformJarJar(ctx, repackagedJarjarFile, outputFile, j.repackageJarjarRules)
1553 outputFile = repackagedJarjarFile
1554 if ctx.Failed() {
1555 return
1556 }
1557 }
1558
Jaewoong Jung26342642021-03-17 15:56:23 -07001559 // Check package restrictions if necessary.
1560 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001561 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001562 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001563
1564 // Create a rule to copy the output jar to another path and add a validate dependency that
1565 // will check that the jar only contains the permitted packages. The new location will become
1566 // the output file of this module.
1567 inputFile := outputFile
1568 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1569 ctx.Build(pctx, android.BuildParams{
1570 Rule: android.Cp,
1571 Input: inputFile,
1572 Output: outputFile,
1573 // Make sure that any dependency on the output file will cause ninja to run the package check
1574 // rule.
1575 Validation: pkgckFile,
1576 })
1577
1578 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001579 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001580
1581 if ctx.Failed() {
1582 return
1583 }
1584 }
1585
1586 j.implementationJarFile = outputFile
1587 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001588 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1589 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1590 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1591 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1592 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1593 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1594 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001595 }
1596
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001597 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1598 specs := j.jacocoModuleToZipCommand(ctx)
1599 if ctx.Failed() {
1600 return
1601 }
1602
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001604 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001605 }
1606
1607 // merge implementation jar with resources if necessary
1608 implementationAndResourcesJar := outputFile
1609 if j.resourceJar != nil {
1610 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1611 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1612 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1613 false, nil, nil)
1614 implementationAndResourcesJar = combinedJar
1615 }
1616
1617 j.implementationAndResourcesJar = implementationAndResourcesJar
1618
1619 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001620 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001621 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001622 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001623 if compileDex == nil {
1624 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001625 }
1626 if j.deviceProperties.Hostdex == nil {
1627 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1628 }
1629 }
1630
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001631 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001632 if j.hasCode(ctx) {
1633 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001634 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001635 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1636 }
1637 // Dex compilation
1638 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001639 params := &compileDexParams{
1640 flags: flags,
1641 sdkVersion: j.SdkVersion(ctx),
1642 minSdkVersion: j.MinSdkVersion(ctx),
1643 classesJar: implementationAndResourcesJar,
1644 jarName: jarName,
1645 }
1646 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001647 if ctx.Failed() {
1648 return
1649 }
1650
Jaewoong Jung26342642021-03-17 15:56:23 -07001651 // merge dex jar with resources if necessary
1652 if j.resourceJar != nil {
1653 jars := android.Paths{dexOutputFile, j.resourceJar}
1654 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1655 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1656 false, nil, nil)
1657 if *j.dexProperties.Uncompress_dex {
1658 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001659 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001660 dexOutputFile = combinedAlignedJar
1661 } else {
1662 dexOutputFile = combinedJar
1663 }
1664 }
1665
Paul Duffin4de94502021-05-16 05:21:16 +01001666 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001667
1668 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001669
1670 // Encode hidden API flags in dex file, if needed.
1671 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1672
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001673 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001674
1675 // Dexpreopting
Spandan Dase21a8d42024-01-23 23:56:29 +00001676 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001677
1678 outputFile = dexOutputFile
1679 } else {
1680 // There is no code to compile into a dex jar, make sure the resources are propagated
1681 // to the APK if this is an app.
1682 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001683 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001684 }
1685
1686 if ctx.Failed() {
1687 return
1688 }
1689 } else {
1690 outputFile = implementationAndResourcesJar
1691 }
1692
1693 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001694 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001695 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001696 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001697 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001698 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001699 }
1700 }
1701
1702 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001703 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1704 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001705 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1706 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001707 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001708 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001709 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001710 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001711 j.linter.javaLanguageLevel = flags.javaVersion.String()
1712 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001713 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001714 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1715 j.linter.buildModuleReportZip = true
1716 }
1717 j.linter.lint(ctx)
1718 }
1719
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001720 j.collectTransitiveSrcFiles(ctx, srcFiles)
1721
Jaewoong Jung26342642021-03-17 15:56:23 -07001722 ctx.CheckbuildFile(outputFile)
1723
LaMont Jonesaa005ae2023-12-19 19:01:57 +00001724 android.CollectDependencyAconfigFiles(ctx, &j.mergedAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001725
Colin Cross40213022023-12-13 15:19:49 -08001726 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07001727 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Joe Onorato349ae8d2024-02-05 22:46:00 +00001728 RepackagedHeaderJars: android.PathsIfNonNil(j.repackagedHeaderJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001729 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1730 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001731 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1732 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1733 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1734 AidlIncludeDirs: j.exportAidlIncludeDirs,
1735 SrcJarArgs: j.srcJarArgs,
1736 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001737 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001738 ExportedPlugins: j.exportedPluginJars,
1739 ExportedPluginClasses: j.exportedPluginClasses,
1740 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1741 JacocoReportClassesFile: j.jacocoReportClassesFile,
Jihoon Kangfe914ed2024-02-12 22:49:21 +00001742 StubsLinkType: j.stubsLinkType,
Jaewoong Jung26342642021-03-17 15:56:23 -07001743 })
1744
1745 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1746 j.outputFile = outputFile.WithoutRel()
1747}
1748
Colin Crossa1ff7c62021-09-17 14:11:52 -07001749func (j *Module) useCompose() bool {
1750 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1751}
1752
Sam Delmerico95d70942023-08-02 18:00:35 -04001753func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1754 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1755 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1756
1757 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001758 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001759 depTag := ctx.OtherModuleDependencyTag(m)
1760
1761 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1762 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1763 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1764 }
1765
1766 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1767 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1768 }
1769 })
1770
1771 directUnconditionalExportedFlags := android.Paths{}
1772 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1773 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1774 if exportUnconditionally {
1775 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1776 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1777 directUnconditionalExportedFlags = proguardFlagsForThisModule
1778 }
1779
1780 return ProguardSpecInfo{
1781 Export_proguard_flags_files: exportUnconditionally,
1782 ProguardFlagsFiles: android.NewDepSet[android.Path](
1783 android.POSTORDER,
1784 proguardFlagsForThisModule,
1785 transitiveProguardFlags,
1786 ),
1787 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1788 android.POSTORDER,
1789 directUnconditionalExportedFlags,
1790 transitiveUnconditionalExportedFlags,
1791 ),
1792 }
1793
1794}
1795
Cole Faust75fffb12021-06-13 15:23:16 -07001796// Returns a copy of the supplied flags, but with all the errorprone-related
1797// fields copied to the regular build's fields.
1798func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1799 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1800
1801 if len(flags.errorProneExtraJavacFlags) > 0 {
1802 if len(flags.javacFlags) > 0 {
1803 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1804 } else {
1805 flags.javacFlags = flags.errorProneExtraJavacFlags
1806 }
1807 }
1808 return flags
1809}
1810
Jaewoong Jung26342642021-03-17 15:56:23 -07001811func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1812 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1813
1814 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001815 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001816 if idx >= 0 {
1817 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001818 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001819 jarName += strconv.Itoa(idx)
1820 }
1821
1822 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001823 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001824
1825 if ctx.Config().EmitXrefRules() {
1826 extractionFile := android.PathForModuleOut(ctx, kzipName)
1827 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1828 j.kytheFiles = append(j.kytheFiles, extractionFile)
1829 }
1830
Vadim Spivak3c496f02023-06-08 06:14:59 +00001831 if len(flags.processorPath) > 0 {
1832 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1833 }
1834
Jaewoong Jung26342642021-03-17 15:56:23 -07001835 return classes
1836}
1837
1838// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1839// since some of these flags may be used internally.
1840func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1841 for _, flag := range flags {
1842 flag = strings.TrimSpace(flag)
1843
1844 if !strings.HasPrefix(flag, "-") {
1845 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1846 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1847 ctx.PropertyErrorf("kotlincflags",
1848 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1849 } else if inList(flag, config.KotlincIllegalFlags) {
1850 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1851 } else if flag == "-include-runtime" {
1852 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1853 } else {
1854 args := strings.Split(flag, " ")
1855 if args[0] == "-kotlin-home" {
1856 ctx.PropertyErrorf("kotlincflags",
1857 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1858 }
1859 }
1860 }
1861}
1862
1863func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1864 deps deps, flags javaBuilderFlags, jarName string,
Joe Onorato349ae8d2024-02-05 22:46:00 +00001865 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar, jarjarAndDepsRepackagedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001866
1867 var jars android.Paths
1868 if len(srcFiles) > 0 || len(srcJars) > 0 {
1869 // Compile java sources into turbine.jar.
1870 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1871 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1872 if ctx.Failed() {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001873 return nil, nil, nil
Jaewoong Jung26342642021-03-17 15:56:23 -07001874 }
1875 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001876 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001877 }
1878
1879 jars = append(jars, extraJars...)
1880
1881 // Combine any static header libraries into classes-header.jar. If there is only
1882 // one input jar this step will be skipped.
1883 jars = append(jars, deps.staticHeaderJars...)
1884
1885 // we cannot skip the combine step for now if there is only one jar
1886 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1887 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1888 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1889 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001890 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001891
1892 if j.expandJarjarRules != nil {
1893 // Transform classes.jar into classes-jarjar.jar
1894 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001895 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1896 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001897 if ctx.Failed() {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001898 return nil, nil, nil
Jaewoong Jung26342642021-03-17 15:56:23 -07001899 }
1900 }
1901
Joe Onorato349ae8d2024-02-05 22:46:00 +00001902 if j.repackageJarjarRules != nil {
1903 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-turbine-jarjar", jarName)
1904 TransformJarJar(ctx, repackagedJarjarFile, jarjarAndDepsHeaderJar, j.repackageJarjarRules)
1905 jarjarAndDepsRepackagedHeaderJar = repackagedJarjarFile
1906 if ctx.Failed() {
1907 return nil, nil, nil
1908 }
1909 } else {
1910 jarjarAndDepsRepackagedHeaderJar = jarjarAndDepsHeaderJar
1911 }
1912
1913 return headerJar, jarjarAndDepsHeaderJar, jarjarAndDepsRepackagedHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001914}
1915
1916func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001917 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001918
1919 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1920 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1921
1922 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1923
1924 j.jacocoReportClassesFile = jacocoReportClassesFile
1925
1926 return instrumentedJar
1927}
1928
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001929type providesTransitiveHeaderJars struct {
1930 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001931 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001932 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001933 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001934}
1935
Colin Crossc85750b2022-04-21 12:50:51 -07001936func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001937 return j.transitiveLibsHeaderJars
1938}
1939
Colin Crossc85750b2022-04-21 12:50:51 -07001940func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001941 return j.transitiveStaticLibsHeaderJars
1942}
1943
1944func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1945 directLibs := android.Paths{}
1946 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001947 transitiveLibs := []*android.DepSet[android.Path]{}
1948 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001949 ctx.VisitDirectDeps(func(module android.Module) {
1950 // don't add deps of the prebuilt version of the same library
1951 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1952 return
1953 }
1954
Colin Cross313aa542023-12-13 13:47:44 -08001955 dep, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001956 tag := ctx.OtherModuleDependencyTag(module)
1957 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1958 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1959 directLibs = append(directLibs, dep.HeaderJars...)
1960 } else if tag == staticLibTag {
1961 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001962 } else {
1963 // Don't propagate transitive libs for other kinds of dependencies.
1964 return
1965 }
1966
1967 if dep.TransitiveLibsHeaderJars != nil {
1968 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1969 }
1970 if dep.TransitiveStaticLibsHeaderJars != nil {
1971 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001972 }
1973 })
1974 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1975 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1976}
1977
Jaewoong Jung26342642021-03-17 15:56:23 -07001978func (j *Module) HeaderJars() android.Paths {
1979 if j.headerJarFile == nil {
1980 return nil
1981 }
1982 return android.Paths{j.headerJarFile}
1983}
1984
1985func (j *Module) ImplementationJars() android.Paths {
1986 if j.implementationJarFile == nil {
1987 return nil
1988 }
1989 return android.Paths{j.implementationJarFile}
1990}
1991
Spandan Das59a4a2b2024-01-09 21:35:56 +00001992func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001993 return j.dexJarFile
1994}
1995
1996func (j *Module) DexJarInstallPath() android.Path {
1997 return j.installFile
1998}
1999
2000func (j *Module) ImplementationAndResourcesJars() android.Paths {
2001 if j.implementationAndResourcesJar == nil {
2002 return nil
2003 }
2004 return android.Paths{j.implementationAndResourcesJar}
2005}
2006
2007func (j *Module) AidlIncludeDirs() android.Paths {
2008 // exportAidlIncludeDirs is type android.Paths already
2009 return j.exportAidlIncludeDirs
2010}
2011
2012func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2013 return j.classLoaderContexts
2014}
2015
2016// Collect information for opening IDE project files in java/jdeps.go.
2017func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
2018 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2019 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2020 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2021 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
2022 if j.expandJarjarRules != nil {
2023 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
2024 }
Yikef6282022022-04-13 20:41:01 +08002025 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2026 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002027 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002028}
2029
2030func (j *Module) CompilerDeps() []string {
2031 jdeps := []string{}
2032 jdeps = append(jdeps, j.properties.Libs...)
2033 jdeps = append(jdeps, j.properties.Static_libs...)
2034 return jdeps
2035}
2036
2037func (j *Module) hasCode(ctx android.ModuleContext) bool {
2038 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2039 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2040}
2041
2042// Implements android.ApexModule
2043func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2044 return j.depIsInSameApex(ctx, dep)
2045}
2046
2047// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002048func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002049 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002050 minSdkVersion := j.MinSdkVersion(ctx)
2051 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002052 return fmt.Errorf("min_sdk_version is not specified")
2053 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002054 // If the module is compiling against core (via sdk_version), skip comparison check.
2055 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002056 return nil
2057 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002058 if minSdkVersion.GreaterThan(sdkVersion) {
2059 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002060 }
2061 return nil
2062}
2063
2064func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002065 if j.stem == "" {
2066 panic("Stem() called before stem property was set")
2067 }
2068 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002069}
2070
Jaewoong Jung26342642021-03-17 15:56:23 -07002071func (j *Module) JacocoReportClassesFile() android.Path {
2072 return j.jacocoReportClassesFile
2073}
2074
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002075func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2076 var fromDeps []*android.DepSet[android.Path]
2077 ctx.VisitDirectDeps(func(module android.Module) {
2078 tag := ctx.OtherModuleDependencyTag(module)
2079 if tag == staticLibTag {
Colin Cross313aa542023-12-13 13:47:44 -08002080 depInfo, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002081 if depInfo.TransitiveSrcFiles != nil {
2082 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2083 }
2084 }
2085 })
2086
2087 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2088}
2089
Jaewoong Jung26342642021-03-17 15:56:23 -07002090func (j *Module) IsInstallable() bool {
2091 return Bool(j.properties.Installable)
2092}
2093
2094type sdkLinkType int
2095
2096const (
2097 // TODO(jiyong) rename these for better readability. Make the allowed
2098 // and disallowed link types explicit
2099 // order is important here. See rank()
2100 javaCore sdkLinkType = iota
2101 javaSdk
2102 javaSystem
2103 javaModule
2104 javaSystemServer
2105 javaPlatform
2106)
2107
2108func (lt sdkLinkType) String() string {
2109 switch lt {
2110 case javaCore:
2111 return "core Java API"
2112 case javaSdk:
2113 return "Android API"
2114 case javaSystem:
2115 return "system API"
2116 case javaModule:
2117 return "module API"
2118 case javaSystemServer:
2119 return "system server API"
2120 case javaPlatform:
2121 return "private API"
2122 default:
2123 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2124 }
2125}
2126
2127// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2128// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2129// can't statically depend on modules that use Platform API.
2130func (lt sdkLinkType) rank() int {
2131 return int(lt)
2132}
2133
2134type moduleWithSdkDep interface {
2135 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002136 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002137}
2138
Jiyong Park92315372021-04-02 08:45:46 +09002139func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002140 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002141 case android.SdkCore.DefaultJavaLibraryName(),
2142 "legacy.core.platform.api.stubs",
2143 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002144 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002145 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002146 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002147 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002148 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002149 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002150 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002151 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002152 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002153 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002154 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002155 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002156 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002157 return javaSystem, true
2158 }
2159
2160 if stub, linkType := moduleStubLinkType(name); stub {
2161 return linkType, true
2162 }
2163
Jiyong Park92315372021-04-02 08:45:46 +09002164 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002165 switch ver.Kind {
2166 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002167 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002168 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002169 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002170 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002171 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002172 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002173 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002174 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002175 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002176 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002177 return javaPlatform, false
2178 }
2179
Jiyong Parkf1691d22021-03-29 20:11:58 +09002180 if !ver.Valid() {
2181 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002182 }
2183 return javaSdk, false
2184}
2185
2186// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2187// this module's. See the comment on rank() for details and an example.
2188func (j *Module) checkSdkLinkType(
2189 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2190 if ctx.Host() {
2191 return
2192 }
2193
Jiyong Park92315372021-04-02 08:45:46 +09002194 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002195 if stubs {
2196 return
2197 }
Jiyong Park92315372021-04-02 08:45:46 +09002198 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002199
2200 if myLinkType.rank() < depLinkType.rank() {
2201 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2202 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2203 "property of the source or target module so that target module is built "+
2204 "with the same or smaller API set when compared to the source.",
2205 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2206 }
2207}
2208
2209func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2210 var deps deps
2211
2212 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002213 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002214 if sdkDep.invalidVersion {
2215 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2216 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2217 } else if sdkDep.useFiles {
2218 // sdkDep.jar is actually equivalent to turbine header.jar.
2219 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002220 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002221 deps.aidlPreprocess = sdkDep.aidl
2222 } else {
2223 deps.aidlPreprocess = sdkDep.aidl
2224 }
2225 }
2226
Jiyong Park92315372021-04-02 08:45:46 +09002227 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002228
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002229 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002230 ctx.VisitDirectDeps(func(module android.Module) {
2231 otherName := ctx.OtherModuleName(module)
2232 tag := ctx.OtherModuleDependencyTag(module)
2233
2234 if IsJniDepTag(tag) {
2235 // Handled by AndroidApp.collectAppDeps
2236 return
2237 }
2238 if tag == certificateTag {
2239 // Handled by AndroidApp.collectAppDeps
2240 return
2241 }
2242
2243 if dep, ok := module.(SdkLibraryDependency); ok {
2244 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002245 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002246 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2247 deps.classpath = append(deps.classpath, depHeaderJars...)
2248 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002249 case staticLibTag:
2250 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2251 }
Colin Cross313aa542023-12-13 13:47:44 -08002252 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2253 if sdkLinkType != javaPlatform {
2254 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2255 // dep is a sysprop implementation library, but this module is not linking against
2256 // the platform, so it gets the sysprop public stubs library instead. Replace
2257 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2258 dep = syspropDep.JavaInfo
2259 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002260 }
2261 switch tag {
2262 case bootClasspathTag:
2263 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002264 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002265 if _, ok := module.(*Plugin); ok {
2266 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2267 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002268 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002269 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002270 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2271 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2272 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2273 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002274 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2275 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2276 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2277 case java9LibTag:
2278 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2279 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002280 if _, ok := module.(*Plugin); ok {
2281 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2282 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002283 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2284 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2285 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2286 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2287 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2288 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2289 // Turbine doesn't run annotation processors, so any module that uses an
2290 // annotation processor that generates API is incompatible with the turbine
2291 // optimization.
2292 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2293 case pluginTag:
2294 if plugin, ok := module.(*Plugin); ok {
2295 if plugin.pluginProperties.Processor_class != nil {
2296 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2297 } else {
2298 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2299 }
2300 // Turbine doesn't run annotation processors, so any module that uses an
2301 // annotation processor that generates API is incompatible with the turbine
2302 // optimization.
2303 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2304 } else {
2305 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2306 }
2307 case errorpronePluginTag:
2308 if _, ok := module.(*Plugin); ok {
2309 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2310 } else {
2311 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2312 }
2313 case exportedPluginTag:
2314 if plugin, ok := module.(*Plugin); ok {
2315 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2316 if plugin.pluginProperties.Processor_class != nil {
2317 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2318 }
2319 // Turbine doesn't run annotation processors, so any module that uses an
2320 // annotation processor that generates API is incompatible with the turbine
2321 // optimization.
2322 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2323 } else {
2324 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2325 }
2326 case kotlinStdlibTag:
2327 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2328 case kotlinAnnotationsTag:
2329 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002330 case kotlinPluginTag:
2331 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002332 case syspropPublicStubDepTag:
2333 // This is a sysprop implementation library, forward the JavaInfoProvider from
2334 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002335 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002336 JavaInfo: dep,
2337 })
2338 }
2339 } else if dep, ok := module.(android.SourceFileProducer); ok {
2340 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002341 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002342 checkProducesJars(ctx, dep)
2343 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002344 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002345 case staticLibTag:
2346 checkProducesJars(ctx, dep)
2347 deps.classpath = append(deps.classpath, dep.Srcs()...)
2348 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2349 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2350 }
2351 } else {
2352 switch tag {
2353 case bootClasspathTag:
2354 // If a system modules dependency has been added to the bootclasspath
2355 // then add its libs to the bootclasspath.
2356 sm := module.(SystemModulesProvider)
2357 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2358
2359 case systemModulesTag:
2360 if deps.systemModules != nil {
2361 panic("Found two system module dependencies")
2362 }
2363 sm := module.(SystemModulesProvider)
2364 outputDir, outputDeps := sm.OutputDirAndDeps()
2365 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002366
2367 case instrumentationForTag:
2368 ctx.PropertyErrorf("instrumentation_for", "dependency %q of type %q does not provide JavaInfo so is unsuitable for use with this property", ctx.OtherModuleName(module), ctx.OtherModuleType(module))
Jaewoong Jung26342642021-03-17 15:56:23 -07002369 }
2370 }
2371
2372 addCLCFromDep(ctx, module, j.classLoaderContexts)
2373 })
2374
2375 return deps
2376}
2377
Joe Onorato349ae8d2024-02-05 22:46:00 +00002378// Provider for jarjar renaming rules.
2379//
2380// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2381// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2382// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2383// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2384// be renamed from that module.
2385// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002386type DependencyUse int
2387
2388const (
2389 RenameUseInvalid DependencyUse = iota
2390 RenameUseInclude
2391 RenameUseExclude
2392)
2393
2394type RenameUseElement struct {
2395 DepName string
2396 RenameUse DependencyUse
2397 Why string // token for determining where in the logic the decision was made.
2398}
2399
Joe Onorato349ae8d2024-02-05 22:46:00 +00002400type JarJarProviderData struct {
2401 // Mapping of class names: original --> renamed. If the value is "", the class will be
2402 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2403 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002404 Rename map[string]string
2405 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002406}
2407
2408func (this JarJarProviderData) GetDebugString() string {
2409 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002410 for _, k := range android.SortedKeys(this.Rename) {
2411 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002412 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2413 result += k + "--&gt;" + v + ";"
2414 }
2415 }
2416 return result
2417}
2418
2419var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2420
2421var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2422
2423func init() {
2424 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
2425}
2426
2427// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2428// whether they are java modules or not.
2429type BaseJarJarProviderData struct {
2430 JarJarProviderData JarJarProviderData
2431}
2432
2433func (this BaseJarJarProviderData) GetDebugString() string {
2434 return this.JarJarProviderData.GetDebugString()
2435}
2436
2437var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2438
2439// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2440// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2441// either JarJarProvider or BaseJarJarProvider.
2442func mergeJarJarPrefixes(ctx android.ModuleContext) {
2443 mod := ctx.Module()
2444 // Explicitly avoid propagating into some module types.
2445 switch reflect.TypeOf(mod).String() {
2446 case "*java.Droidstubs":
2447 return
2448 }
2449 jarJarData := collectDirectDepsProviders(ctx)
2450 if jarJarData != nil {
2451 providerData := BaseJarJarProviderData{
2452 JarJarProviderData: *jarJarData,
2453 }
2454 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2455 }
2456
2457}
2458
2459// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2460func (module *Module) addJarJarRenameRule(original string, renamed string) {
2461 if module.jarjarRenameRules == nil {
2462 module.jarjarRenameRules = make(map[string]string)
2463 }
2464 module.jarjarRenameRules[original] = renamed
2465}
2466
2467func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2468 // Gather repackage information from deps
2469 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002470
2471 module := ctx.Module()
2472 moduleName := module.Name()
2473
Joe Onorato349ae8d2024-02-05 22:46:00 +00002474 ctx.VisitDirectDepsIgnoreBlueprint(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002475 tag := ctx.OtherModuleDependencyTag(m)
2476 // This logic mirrors that in (*Module).collectDeps above. There are several places
2477 // where we explicitly return RenameUseExclude, even though it is the default, to
2478 // indicate that it has been verified to be the case.
2479 //
2480 // Note well: there are probably cases that are getting to the unconditional return
2481 // and are therefore wrong.
2482 shouldIncludeRenames := func() (DependencyUse, string) {
2483 if moduleName == m.Name() {
2484 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2485 }
2486 if sc, ok := module.(android.SdkContext); ok {
2487 if ctx.Device() {
2488 sdkDep := decodeSdkDep(ctx, sc)
2489 if !sdkDep.invalidVersion && sdkDep.useFiles {
2490 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002491 }
2492 }
LaMont Jones63683e42024-02-08 14:30:45 -08002493 }
2494 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2495 return RenameUseExclude, "tags"
2496 }
2497 if _, ok := m.(SdkLibraryDependency); ok {
2498 switch tag {
2499 case sdkLibTag, libTag:
2500 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2501 }
2502 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2503 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2504 switch ji.StubsLinkType {
2505 case Stubs:
2506 return RenameUseExclude, "info"
2507 case Implementation:
2508 return RenameUseInclude, "info"
2509 default:
2510 //fmt.Printf("LJ: %v -> %v StubsLinkType unknown\n", module, m)
2511 // Fall through to the heuristic logic.
2512 }
2513 switch reflect.TypeOf(m).String() {
2514 case "*java.GeneratedJavaLibraryModule":
2515 // Probably a java_aconfig_library module.
2516 // TODO: make this check better.
2517 return RenameUseInclude, "reflect"
2518 }
2519 switch tag {
2520 case bootClasspathTag:
2521 return RenameUseExclude, "tagswitch"
2522 case sdkLibTag, libTag, instrumentationForTag:
2523 return RenameUseInclude, "tagswitch"
2524 case java9LibTag:
2525 return RenameUseExclude, "tagswitch"
2526 case staticLibTag:
2527 return RenameUseInclude, "tagswitch"
2528 case pluginTag:
2529 return RenameUseInclude, "tagswitch"
2530 case errorpronePluginTag:
2531 return RenameUseInclude, "tagswitch"
2532 case exportedPluginTag:
2533 return RenameUseInclude, "tagswitch"
2534 case kotlinStdlibTag, kotlinAnnotationsTag:
2535 return RenameUseExclude, "tagswitch"
2536 case kotlinPluginTag:
2537 return RenameUseInclude, "tagswitch"
2538 default:
2539 return RenameUseExclude, "tagswitch"
2540 }
2541 } else if _, ok := m.(android.SourceFileProducer); ok {
2542 switch tag {
2543 case sdkLibTag, libTag, staticLibTag:
2544 return RenameUseInclude, "srcfile"
2545 default:
2546 return RenameUseExclude, "srcfile"
2547 }
Yu Liu67a28422024-03-05 00:36:31 +00002548 } else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
Jihoon Kang03d014f2024-02-16 22:22:18 +00002549 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002550 } else {
2551 switch tag {
2552 case bootClasspathTag:
2553 return RenameUseExclude, "else"
2554 case systemModulesTag:
2555 return RenameUseInclude, "else"
2556 }
2557 }
2558 // If we got here, choose the safer option, which may lead to a build failure, rather
2559 // than runtime failures on the device.
2560 return RenameUseExclude, "end"
2561 }
2562
2563 if result == nil {
2564 result = &JarJarProviderData{
2565 Rename: make(map[string]string),
2566 RenameUse: make([]RenameUseElement, 0),
2567 }
2568 }
2569 how, why := shouldIncludeRenames()
2570 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2571 if how != RenameUseInclude {
2572 // Nothing to merge.
2573 return
2574 }
2575
2576 merge := func(theirs *JarJarProviderData) {
2577 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002578 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2579 result.Rename[orig] = renamed
2580 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2581 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2582 result.Rename[orig] = renamed
2583 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2584 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2585 continue
2586 }
2587 }
2588 }
2589 }
2590 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2591 merge(&theirs)
2592 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2593 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2594 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2595 // to java.Module.
2596 merge(&theirs.JarJarProviderData)
2597 }
2598 })
2599 return
2600}
2601
2602func (this Module) GetDebugString() string {
2603 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2604}
2605
2606// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2607// us, and if it's been set, apply the jarjar_prefix property to rename them.
2608func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2609 // Gather repackage information from deps
2610 result := collectDirectDepsProviders(ctx)
2611
2612 // Update that with entries we've stored for ourself
2613 for orig, renamed := range module.jarjarRenameRules {
2614 if result == nil {
2615 result = &JarJarProviderData{
2616 Rename: make(map[string]string),
2617 }
2618 }
2619 if renamed != "" {
2620 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2621 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
2622 continue
2623 }
2624 }
2625 (*result).Rename[orig] = renamed
2626 }
2627
2628 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2629 if result == nil {
2630 return nil
2631 }
2632
2633 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2634 // that have not yet been renamed.
2635 prefix := proptools.String(module.properties.Jarjar_prefix)
2636 if prefix != "" {
2637 if prefix[0] == '.' {
2638 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2639 return nil
2640 }
2641 if prefix[len(prefix)-1] == '.' {
2642 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2643 return nil
2644 }
2645
2646 var updated map[string]string
2647 for orig, renamed := range (*result).Rename {
2648 if renamed == "" {
2649 if updated == nil {
2650 updated = make(map[string]string)
2651 }
2652 updated[orig] = prefix + "." + orig
2653 }
2654 }
2655 for orig, renamed := range updated {
2656 (*result).Rename[orig] = renamed
2657 }
2658 }
2659
2660 return result
2661}
2662
2663// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2664// to "" won't be in this list because they shouldn't be renamed yet.
2665func getJarJarRuleText(provider *JarJarProviderData) string {
2666 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002667 for _, orig := range android.SortedKeys(provider.Rename) {
2668 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002669 if renamed != "" {
2670 result += "rule " + orig + " " + renamed + "\n"
2671 }
2672 }
2673 return result
2674}
2675
Jaewoong Jung26342642021-03-17 15:56:23 -07002676func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2677 deps.processorPath = append(deps.processorPath, pluginJars...)
2678 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2679}
2680
2681// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2682// this interface.
2683type ProvidesUsesLib interface {
2684 ProvidesUsesLib() *string
2685}
2686
2687func (j *Module) ProvidesUsesLib() *string {
2688 return j.usesLibraryProperties.Provides_uses_lib
2689}
satayev1c564cc2021-05-25 19:50:30 +01002690
2691type ModuleWithStem interface {
2692 Stem() string
2693}
2694
2695var _ ModuleWithStem = (*Module)(nil)