blob: 32bfc17f9929685d628105dea50af3f1b698d4a1 [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 (
Yu Liu26a716d2024-08-30 23:40:32 +000018 "encoding/gob"
Jaewoong Jung26342642021-03-17 15:56:23 -070019 "fmt"
20 "path/filepath"
Joe Onorato349ae8d2024-02-05 22:46:00 +000021 "reflect"
22 "slices"
Jaewoong Jung26342642021-03-17 15:56:23 -070023 "strconv"
24 "strings"
25
Colin Crossd788b3e2023-11-28 13:14:56 -080026 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070027 "github.com/google/blueprint/pathtools"
28 "github.com/google/blueprint/proptools"
29
30 "android/soong/android"
31 "android/soong/dexpreopt"
32 "android/soong/java/config"
33)
34
35// This file contains the definition and the implementation of the base module that most
36// source-based Java module structs embed.
37
38// TODO:
39// Autogenerated files:
40// Renderscript
41// Post-jar passes:
42// Proguard
43// Rmtypedefs
44// DroidDoc
45// Findbugs
46
47// Properties that are common to most Java modules, i.e. whether it's a host or device module.
48type CommonProperties struct {
49 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
50 // or .aidl files.
51 Srcs []string `android:"path,arch_variant"`
52
53 // list Kotlin of source files containing Kotlin code that should be treated as common code in
54 // a codebase that supports Kotlin multiplatform. See
55 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
56 Common_srcs []string `android:"path,arch_variant"`
57
58 // list of source files that should not be used to build the Java module.
59 // This is most useful in the arch/multilib variants to remove non-common files
60 Exclude_srcs []string `android:"path,arch_variant"`
61
62 // list of directories containing Java resources
63 Java_resource_dirs []string `android:"arch_variant"`
64
65 // list of directories that should be excluded from java_resource_dirs
66 Exclude_java_resource_dirs []string `android:"arch_variant"`
67
68 // list of files to use as Java resources
69 Java_resources []string `android:"path,arch_variant"`
70
71 // list of files that should be excluded from java_resources and java_resource_dirs
72 Exclude_java_resources []string `android:"path,arch_variant"`
73
74 // list of module-specific flags that will be used for javac compiles
75 Javacflags []string `android:"arch_variant"`
76
77 // list of module-specific flags that will be used for kotlinc compiles
78 Kotlincflags []string `android:"arch_variant"`
79
80 // list of java libraries that will be in the classpath
81 Libs []string `android:"arch_variant"`
82
83 // list of java libraries that will be compiled into the resulting jar
Cole Faustb7493472024-08-28 11:55:52 -070084 Static_libs proptools.Configurable[[]string] `android:"arch_variant"`
Jaewoong Jung26342642021-03-17 15:56:23 -070085
86 // manifest file to be included in resulting jar
87 Manifest *string `android:"path"`
88
89 // if not blank, run jarjar using the specified rules file
90 Jarjar_rules *string `android:"path,arch_variant"`
91
Joe Onoratoa5d17172024-07-20 17:39:56 -070092 // java class names to rename with jarjar when a reverse dependency has a jarjar_prefix
93 // property.
94 Jarjar_rename []string
95
Joe Onorato349ae8d2024-02-05 22:46:00 +000096 // if not blank, used as prefix to generate repackage rule
97 Jarjar_prefix *string
98
Jaewoong Jung26342642021-03-17 15:56:23 -070099 // If not blank, set the java version passed to javac as -source and -target
100 Java_version *string
101
102 // If set to true, allow this module to be dexed and installed on devices. Has no
103 // effect on host modules, which are always considered installable.
104 Installable *bool
105
106 // If set to true, include sources used to compile the module in to the final jar
107 Include_srcs *bool
108
109 // If not empty, classes are restricted to the specified packages and their sub-packages.
110 // This restriction is checked after applying jarjar rules and including static libs.
111 Permitted_packages []string
112
113 // List of modules to use as annotation processors
114 Plugins []string
115
116 // List of modules to export to libraries that directly depend on this library as annotation
117 // processors. Note that if the plugins set generates_api: true this will disable the turbine
118 // optimization on modules that depend on this module, which will reduce parallelism and cause
119 // more recompilation.
120 Exported_plugins []string
121
122 // The number of Java source entries each Javac instance can process
123 Javac_shard_size *int64
124
125 // Add host jdk tools.jar to bootclasspath
126 Use_tools_jar *bool
127
128 Openjdk9 struct {
129 // List of source files that should only be used when passing -source 1.9 or higher
130 Srcs []string `android:"path"`
131
132 // List of javac flags that should only be used when passing -source 1.9 or higher
133 Javacflags []string
134 }
135
136 // When compiling language level 9+ .java code in packages that are part of
137 // a system module, patch_module names the module that your sources and
138 // dependencies should be patched into. The Android runtime currently
139 // doesn't implement the JEP 261 module system so this option is only
140 // supported at compile time. It should only be needed to compile tests in
141 // packages that exist in libcore and which are inconvenient to move
142 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400143 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700144
145 Jacoco struct {
146 // List of classes to include for instrumentation with jacoco to collect coverage
147 // information at runtime when building with coverage enabled. If unset defaults to all
148 // classes.
149 // Supports '*' as the last character of an entry in the list as a wildcard match.
150 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
151 // it matches classes in the package that have the class name as a prefix.
152 Include_filter []string
153
154 // List of classes to exclude from instrumentation with jacoco to collect coverage
155 // information at runtime when building with coverage enabled. Overrides classes selected
156 // by the include_filter property.
157 // Supports '*' as the last character of an entry in the list as a wildcard match.
158 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
159 // it matches classes in the package that have the class name as a prefix.
160 Exclude_filter []string
161 }
162
163 Errorprone struct {
164 // List of javac flags that should only be used when running errorprone.
165 Javacflags []string
166
167 // List of java_plugin modules that provide extra errorprone checks.
168 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700169
Cole Faust2b1536e2021-06-18 12:25:54 -0700170 // This property can be in 3 states. When set to true, errorprone will
171 // be run during the regular build. When set to false, errorprone will
172 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
173 // environment variable is true. Setting this to false will improve build
174 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700175 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700176 }
177
178 Proto struct {
179 // List of extra options that will be passed to the proto generator.
180 Output_params []string
181 }
182
Sam Delmericoc7593722022-08-31 15:57:52 -0400183 // If true, then jacocoagent is automatically added as a libs dependency so that
184 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700185 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000186 // If true, then the module supports statically including the jacocoagent
187 // into the library.
188 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700189
190 // List of files to include in the META-INF/services folder of the resulting jar.
191 Services []string `android:"path,arch_variant"`
192
193 // If true, package the kotlin stdlib into the jar. Defaults to true.
194 Static_kotlin_stdlib *bool `android:"arch_variant"`
195
196 // A list of java_library instances that provide additional hiddenapi annotations for the library.
197 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700198
199 // Additional srcJars tacked in by GeneratedJavaLibraryModule
200 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000201
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000202 // intermediate aconfig cache file tacked in by GeneratedJavaLibraryModule
203 Aconfig_Cache_files []android.Path `android:"mutated"`
204
Mark Whitea15790a2023-08-22 21:28:11 +0000205 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400206 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800207
208 // A list of files or dependencies to make available to the build sandbox. This is
209 // useful if source files are symlinks, the targets of the symlinks must be listed here.
210 // Note that currently not all actions implemented by android_apps are sandboxed, so you
211 // may only see this being necessary in lint builds.
212 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000213
214 // Property signifying whether the module compiles stubs or not.
215 // Should be set to true when srcs of this module are stub files.
216 // This property does not need to be set to true when the module depends on
217 // the stubs via libs, but should be set to true when the module depends on
218 // the stubs via static libs.
219 Is_stubs_module *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700220
221 // If true, enable the "Ravenizer" tool on the output jar.
222 // "Ravenizer" is a tool for Ravenwood tests, but it can also be enabled on other kinds
223 // of java targets.
224 Ravenizer struct {
225 Enabled *bool
226 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +0000227
228 // Contributing api surface of the stub module. Is not visible to bp modules, and should
229 // only be set for stub submodules generated by the java_sdk_library
230 Stub_contributing_api *string `blueprint:"mutated"`
Yihan Dong8be09c22024-08-29 15:32:13 +0800231
232 // If true, enable the "ApiMapper" tool on the output jar. "ApiMapper" is a tool to inject
233 // bytecode to log API calls.
234 ApiMapper bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700235}
236
237// Properties that are specific to device modules. Host module factories should not add these when
238// constructing a new module.
239type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000240 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000241 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000242 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000243 // 1) numerical API level, "current", "none", or "core_platform"
244 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
245 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
246 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700247 Sdk_version *string
248
satayev0a420e72021-11-29 17:25:52 +0000249 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
250 // Defaults to empty string "". See sdk_version for possible values.
251 Max_sdk_version *string
252
William Loh5a082f92022-05-17 20:21:50 +0000253 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
254 // Defaults to empty string "". See sdk_version for possible values.
255 Replace_max_sdk_version_placeholder *string
256
Jaewoong Jung26342642021-03-17 15:56:23 -0700257 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000258 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700259 Target_sdk_version *string
260
261 // Whether to compile against the platform APIs instead of an SDK.
262 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000263 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700264 Platform_apis *bool
265
266 Aidl struct {
267 // Top level directories to pass to aidl tool
268 Include_dirs []string
269
270 // Directories rooted at the Android.bp file to pass to aidl tool
271 Local_include_dirs []string
272
273 // directories that should be added as include directories for any aidl sources of modules
274 // that depend on this module, as well as to aidl for this module.
275 Export_include_dirs []string
276
277 // whether to generate traces (for systrace) for this interface
278 Generate_traces *bool
279
280 // whether to generate Binder#GetTransaction name method.
281 Generate_get_transaction_name *bool
282
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100283 // whether all interfaces should be annotated with required permissions.
284 Enforce_permissions *bool
285
286 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
287 Enforce_permissions_exceptions []string `android:"path"`
288
Jaewoong Jung26342642021-03-17 15:56:23 -0700289 // list of flags that will be passed to the AIDL compiler
290 Flags []string
291 }
292
293 // If true, export a copy of the module as a -hostdex module for host testing.
294 Hostdex *bool
295
296 Target struct {
297 Hostdex struct {
298 // Additional required dependencies to add to -hostdex modules.
299 Required []string
300 }
301 }
302
303 // When targeting 1.9 and above, override the modules to use with --system,
304 // otherwise provides defaults libraries to add to the bootclasspath.
305 System_modules *string
306
Jaewoong Jung26342642021-03-17 15:56:23 -0700307 IsSDKLibrary bool `blueprint:"mutated"`
308
309 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
310 // Defaults to false.
311 V4_signature *bool
312
313 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
314 // public stubs library.
315 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000316
317 HiddenAPIPackageProperties
318 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700319}
320
yangbill2af0b6e2024-03-15 09:29:29 +0000321// Properties that can be overridden by overriding module (e.g. override_android_app)
322type OverridableProperties struct {
Jooyung Han01d80d82022-01-08 12:16:32 +0900323 // set the name of the output. If not set, `name` is used.
324 // To override a module with this property set, overriding module might need to set this as well.
325 // Otherwise, both the overridden and the overriding modules will have the same output name, which
326 // can cause the duplicate output error.
327 Stem *string
Spandan Dasb9c58352024-05-13 18:29:45 +0000328
329 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
330 // Defaults to sdk_version if not set. See sdk_version for possible values.
331 Min_sdk_version *string
Jooyung Han01d80d82022-01-08 12:16:32 +0900332}
333
Jaewoong Jung26342642021-03-17 15:56:23 -0700334// Functionality common to Module and Import
335//
336// It is embedded in Module so its functionality can be used by methods in Module
337// but it is currently only initialized by Import and Library.
338type embeddableInModuleAndImport struct {
339
340 // Functionality related to this being used as a component of a java_sdk_library.
341 EmbeddableSdkLibraryComponent
342}
343
Paul Duffin71b33cc2021-06-23 11:39:47 +0100344func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
345 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700346}
347
348// Module/Import's DepIsInSameApex(...) delegates to this method.
349//
350// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
351// the one provided by ApexModuleBase.
352func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
353 // dependencies other than the static linkage are all considered crossing APEX boundary
354 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
355 return true
356 }
357 return false
358}
359
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100360// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
361// or an invalid path describing the reason it is invalid.
362//
363// It is unset if a dex jar isn't applicable, i.e. no build rule has been
364// requested to create one.
365//
366// If a dex jar has been requested to be built then it is set, and it may be
367// either a valid android.Path, or invalid with a reason message. The latter
368// happens if the source that should produce the dex file isn't able to.
369//
370// E.g. it is invalid with a reason message if there is a prebuilt APEX that
371// could produce the dex jar through a deapexer module, but the APEX isn't
372// installable so doing so wouldn't be safe.
373type OptionalDexJarPath struct {
374 isSet bool
375 path android.OptionalPath
376}
377
378// IsSet returns true if a path has been set, either invalid or valid.
379func (o OptionalDexJarPath) IsSet() bool {
380 return o.isSet
381}
382
383// Valid returns true if there is a path that is valid.
384func (o OptionalDexJarPath) Valid() bool {
385 return o.isSet && o.path.Valid()
386}
387
388// Path returns the valid path, or panics if it's either not set or is invalid.
389func (o OptionalDexJarPath) Path() android.Path {
390 if !o.isSet {
391 panic("path isn't set")
392 }
393 return o.path.Path()
394}
395
396// PathOrNil returns the path if it's set and valid, or else nil.
397func (o OptionalDexJarPath) PathOrNil() android.Path {
398 if o.Valid() {
399 return o.Path()
400 }
401 return nil
402}
403
404// InvalidReason returns the reason for an invalid path, which is never "". It
405// returns "" for an unset or valid path.
406func (o OptionalDexJarPath) InvalidReason() string {
407 if !o.isSet {
408 return ""
409 }
410 return o.path.InvalidReason()
411}
412
413func (o OptionalDexJarPath) String() string {
414 if !o.isSet {
415 return "<unset>"
416 }
417 return o.path.String()
418}
419
420// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
421func makeUnsetDexJarPath() OptionalDexJarPath {
422 return OptionalDexJarPath{isSet: false}
423}
424
425// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
426// the given OptionalPath, which may be valid or invalid.
427func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
428 return OptionalDexJarPath{isSet: true, path: path}
429}
430
431// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
432// valid given path. It returns an unset OptionalDexJarPath if the given path is
433// nil.
434func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
435 if path == nil {
436 return makeUnsetDexJarPath()
437 }
438 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
439}
440
Jaewoong Jung26342642021-03-17 15:56:23 -0700441// Module contains the properties and members used by all java module types
442type Module struct {
443 android.ModuleBase
444 android.DefaultableModuleBase
445 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700446
447 // Functionality common to Module and Import.
448 embeddableInModuleAndImport
449
450 properties CommonProperties
451 protoProperties android.ProtoProperties
452 deviceProperties DeviceProperties
453
yangbill2af0b6e2024-03-15 09:29:29 +0000454 overridableProperties OverridableProperties
Ronald Braunsteincdc66f42024-04-12 11:23:19 -0700455 sourceProperties android.SourceProperties
Jooyung Han01d80d82022-01-08 12:16:32 +0900456
Jaewoong Jung26342642021-03-17 15:56:23 -0700457 // jar file containing header classes including static library dependencies, suitable for
458 // inserting into the bootclasspath/classpath of another compile
459 headerJarFile android.Path
460
461 // jar file containing implementation classes including static library dependencies but no
462 // resources
463 implementationJarFile android.Path
464
Jaewoong Jung26342642021-03-17 15:56:23 -0700465 // args and dependencies to package source files into a srcjar
466 srcJarArgs []string
467 srcJarDeps android.Paths
468
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000469 // the source files of this module and all its static dependencies
470 transitiveSrcFiles *android.DepSet[android.Path]
471
Jaewoong Jung26342642021-03-17 15:56:23 -0700472 // jar file containing implementation classes and resources including static library
473 // dependencies
474 implementationAndResourcesJar android.Path
475
476 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100477 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700478
479 // output file containing uninstrumented classes that will be instrumented by jacoco
480 jacocoReportClassesFile android.Path
481
482 // output file of the module, which may be a classes jar or a dex jar
483 outputFile android.Path
484 extraOutputFiles android.Paths
485
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100486 exportAidlIncludeDirs android.Paths
487 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700488
489 logtagsSrcs android.Paths
490
491 // installed file for binary dependency
492 installFile android.Path
493
Colin Cross3108ce12021-11-10 14:38:50 -0800494 // installed file for hostdex copy
495 hostdexInstallFile android.InstallPath
496
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800497 // list of unique .java and .kt source files
498 uniqueSrcFiles android.Paths
499
500 // list of srcjars that was passed to javac
501 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700502
503 // manifest file to use instead of properties.Manifest
504 overrideManifest android.OptionalPath
505
Jaewoong Jung26342642021-03-17 15:56:23 -0700506 // list of plugins that this java module is exporting
507 exportedPluginJars android.Paths
508
509 // list of plugins that this java module is exporting
510 exportedPluginClasses []string
511
512 // if true, the exported plugins generate API and require disabling turbine.
513 exportedDisableTurbine bool
514
515 // list of source files, collected from srcFiles with unique java and all kt files,
516 // will be used by android.IDEInfo struct
517 expandIDEInfoCompiledSrcs []string
518
519 // expanded Jarjar_rules
520 expandJarjarRules android.Path
521
Joe Onorato349ae8d2024-02-05 22:46:00 +0000522 // jarjar rule for inherited jarjar rules
523 repackageJarjarRules android.Path
524
Jaewoong Jung26342642021-03-17 15:56:23 -0700525 // Extra files generated by the module type to be added as java resources.
526 extraResources android.Paths
527
528 hiddenAPI
529 dexer
530 dexpreopter
531 usesLibrary
532 linter
533
534 // list of the xref extraction files
Spandan Das1028d5a2024-08-19 21:45:48 +0000535 kytheFiles android.Paths
536 kytheKotlinFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700537
Jaewoong Jung26342642021-03-17 15:56:23 -0700538 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900539
540 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000541 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000542 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400543
544 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000545
546 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000547
548 // output file name based on Stem property.
549 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
550 // or the module should override Stem().
551 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700552
Joe Onorato349ae8d2024-02-05 22:46:00 +0000553 // Values that will be set in the JarJarProvider data for jarjar repackaging,
554 // and merged with our dependencies' rules.
555 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000556
557 stubsLinkType StubsLinkType
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000558
559 // Paths to the aconfig intermediate cache files that are provided by the
560 // java_aconfig_library or java_library modules that are statically linked
561 // to this module. Does not contain cache files from all transitive dependencies.
562 aconfigCacheFiles android.Paths
Spandan Das8aac9932024-07-18 23:14:13 +0000563
564 // List of soong module dependencies required to compile the current module.
565 // This information is printed out to `Dependencies` field in module_bp_java_deps.json
566 compileDepNames []string
Makoto Onuki7ded3822024-03-28 14:42:20 -0700567
568 ravenizer struct {
569 enabled bool
570 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700571}
572
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000573var _ android.InstallableModule = (*Module)(nil)
574
575// To satisfy the InstallableModule interface
Jihoon Kang224ea082024-08-12 22:38:16 +0000576func (j *Module) StaticDependencyTags() []blueprint.DependencyTag {
577 return []blueprint.DependencyTag{staticLibTag}
578}
579
580// To satisfy the InstallableModule interface
581func (j *Module) DynamicDependencyTags() []blueprint.DependencyTag {
582 return []blueprint.DependencyTag{libTag, sdkLibTag, bootClasspathTag, systemModulesTag,
583 instrumentationForTag, java9LibTag}
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000584}
585
586// Overrides android.ModuleBase.InstallInProduct()
587func (j *Module) InstallInProduct() bool {
588 return j.ProductSpecific()
589}
590
Jihoon Kang85bc1932024-07-01 17:04:46 +0000591var _ android.StubsAvailableModule = (*Module)(nil)
592
593// To safisfy the StubsAvailableModule interface
594func (j *Module) IsStubsModule() bool {
595 return proptools.Bool(j.properties.Is_stubs_module)
596}
597
Jiyong Park92315372021-04-02 08:45:46 +0900598func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
599 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900600 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700601 return nil
602 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900603 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000604 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700605 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
606 } else {
607 // Treat stable core platform as stable.
608 return nil
609 }
610 } else {
611 return fmt.Errorf("non stable SDK %v", sdkVersion)
612 }
613}
614
615// checkSdkVersions enforces restrictions around SDK dependencies.
616func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
617 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900618 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900619 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700620 ctx.PropertyErrorf("sdk_version",
621 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
622 }
623 }
624 }
625
626 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
627 // See rank() for details.
628 ctx.VisitDirectDeps(func(module android.Module) {
629 tag := ctx.OtherModuleDependencyTag(module)
630 switch module.(type) {
631 // TODO(satayev): cover other types as well, e.g. imports
632 case *Library, *AndroidLibrary:
633 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400634 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700635 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
636 }
637 }
638 })
639}
640
641func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900642 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700643 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900644 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700645 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000646 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 -0700647 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000648 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 -0700649 }
650
651 }
652}
653
Mark Whitea15790a2023-08-22 21:28:11 +0000654func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
655 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400656 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000657 installable := proptools.Bool(j.properties.Installable)
658
659 if headersOnly && installable {
660 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.")
661 }
662 }
663}
664
Jaewoong Jung26342642021-03-17 15:56:23 -0700665func (j *Module) addHostProperties() {
666 j.AddProperties(
667 &j.properties,
yangbill2af0b6e2024-03-15 09:29:29 +0000668 &j.overridableProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700669 &j.protoProperties,
670 &j.usesLibraryProperties,
671 )
672}
673
674func (j *Module) addHostAndDeviceProperties() {
675 j.addHostProperties()
676 j.AddProperties(
677 &j.deviceProperties,
678 &j.dexer.dexProperties,
679 &j.dexpreoptProperties,
680 &j.linter.properties,
681 )
682}
683
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000684// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
685// makes it available through the hiddenAPIPropertyInfoProvider.
686func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
687 hiddenAPIInfo := newHiddenAPIPropertyInfo()
688
689 // Populate with flag file paths from the properties.
690 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
691
692 // Populate with package rules from the properties.
693 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
694
Colin Cross40213022023-12-13 15:19:49 -0800695 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000696}
697
mrziwang9f7b9f42024-07-10 12:18:06 -0700698// helper method for java modules to set OutputFilesProvider
699func setOutputFiles(ctx android.ModuleContext, m Module) {
700 ctx.SetOutputFiles(append(android.Paths{m.outputFile}, m.extraOutputFiles...), "")
701 ctx.SetOutputFiles(android.Paths{m.outputFile}, android.DefaultDistTag)
702 ctx.SetOutputFiles(android.Paths{m.implementationAndResourcesJar}, ".jar")
703 ctx.SetOutputFiles(android.Paths{m.headerJarFile}, ".hjar")
704 if m.dexer.proguardDictionary.Valid() {
705 ctx.SetOutputFiles(android.Paths{m.dexer.proguardDictionary.Path()}, ".proguard_map")
706 }
707 ctx.SetOutputFiles(m.properties.Generated_srcjars, ".generated_srcjars")
Jaewoong Jung26342642021-03-17 15:56:23 -0700708}
709
Jaewoong Jung26342642021-03-17 15:56:23 -0700710func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
711 initJavaModule(module, hod, false)
712}
713
714func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
715 initJavaModule(module, hod, true)
716}
717
718func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
719 multilib := android.MultilibCommon
720 if multiTargets {
721 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
722 } else {
723 android.InitAndroidArchModule(module, hod, multilib)
724 }
725 android.InitDefaultableModule(module)
726}
727
728func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
729 return j.properties.Instrument &&
730 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
731 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
732}
733
Yihan Dong8be09c22024-08-29 15:32:13 +0800734func (j *Module) shouldApiMapper() bool {
735 return j.properties.ApiMapper
736}
737
Jaewoong Jung26342642021-03-17 15:56:23 -0700738func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000739 return j.properties.Supports_static_instrumentation &&
740 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700741 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
742 ctx.Config().UnbundledBuild())
743}
744
745func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
746 // Force enable the instrumentation for java code that is built for APEXes ...
747 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
748 // 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 -0800749 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700750 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
Jihoon Kang690df2e2024-05-22 04:27:38 +0000751
Jihoon Kang46d66de2024-05-22 22:42:39 +0000752 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700753 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
754 return true
755 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
756 return true
757 }
758 }
759 return false
760}
761
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400762func (j *Module) setInstrument(value bool) {
763 j.properties.Instrument = value
764}
765
Yihan Dong8be09c22024-08-29 15:32:13 +0800766func (j *Module) setApiMapper(value bool) {
767 j.properties.ApiMapper = value
768}
769
Jiyong Park92315372021-04-02 08:45:46 +0900770func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
771 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700772}
773
Jiyong Parkf1691d22021-03-29 20:11:58 +0900774func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700775 return proptools.String(j.deviceProperties.System_modules)
776}
777
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000778func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Spandan Dasb9c58352024-05-13 18:29:45 +0000779 if j.overridableProperties.Min_sdk_version != nil {
780 return android.ApiLevelFrom(ctx, *j.overridableProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700781 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000782 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700783}
784
Yu Liuf2b94012023-09-19 15:09:10 -0700785func (j *Module) GetDeviceProperties() *DeviceProperties {
786 return &j.deviceProperties
787}
788
Spandan Dasa26eda72023-03-02 00:56:06 +0000789func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
790 if j.deviceProperties.Max_sdk_version != nil {
791 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
792 }
793 // Default is PrivateApiLevel
794 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000795}
796
Spandan Dasa26eda72023-03-02 00:56:06 +0000797func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
798 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
799 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
800 }
801 // Default is PrivateApiLevel
802 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000803}
804
Jiyong Parkf1691d22021-03-29 20:11:58 +0900805func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000806 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900807}
808
Spandan Dasca70fc42023-03-01 23:38:49 +0000809func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900810 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000811 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900812 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000813 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700814}
815
816func (j *Module) AvailableFor(what string) bool {
817 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
818 // Exception: for hostdex: true libraries, the platform variant is created
819 // even if it's not marked as available to platform. In that case, the platform
820 // variant is used only for the hostdex and not installed to the device.
821 return true
822 }
823 return j.ApexModuleBase.AvailableFor(what)
824}
825
Cole Faustb7493472024-08-28 11:55:52 -0700826func (j *Module) staticLibs(ctx android.BaseModuleContext) []string {
Jihoon Kang8bce3812024-09-30 18:46:51 +0000827 return j.properties.Static_libs.GetOrDefault(ctx, nil)
Cole Faustb7493472024-08-28 11:55:52 -0700828}
829
Jaewoong Jung26342642021-03-17 15:56:23 -0700830func (j *Module) deps(ctx android.BottomUpMutatorContext) {
831 if ctx.Device() {
832 j.linter.deps(ctx)
833
Jiyong Parkf1691d22021-03-29 20:11:58 +0900834 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700835
836 if j.deviceProperties.SyspropPublicStub != "" {
837 // This is a sysprop implementation library that has a corresponding sysprop public
838 // stubs library, and a dependency on it so that dependencies on the implementation can
839 // be forwarded to the public stubs library when necessary.
840 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
841 }
842 }
843
844 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000845
Cole Faustb7493472024-08-28 11:55:52 -0700846 ctx.AddVariationDependencies(nil, staticLibTag, j.staticLibs(ctx)...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700847
848 // Add dependency on libraries that provide additional hidden api annotations.
849 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
850
Jaewoong Jung26342642021-03-17 15:56:23 -0700851 // For library dependencies that are component libraries (like stubs), add the implementation
852 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
853 for _, dep := range libDeps {
854 if dep != nil {
855 if component, ok := dep.(SdkLibraryComponentDependency); ok {
856 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +0000857 // Add library as optional if it's one of the optional compatibility libs or it's
858 // explicitly listed in the optional_uses_libs property.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100859 tag := usesLibReqTag
Jiakai Zhangf98da192024-04-15 11:15:41 +0000860 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) ||
861 android.InList(*lib, j.usesLibrary.usesLibraryProperties.Optional_uses_libs) {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100862 tag = usesLibOptTag
863 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100864 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700865 }
866 }
867 }
868 }
869
870 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
871 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
872 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
873
874 android.ProtoDeps(ctx, &j.protoProperties)
875 if j.hasSrcExt(".proto") {
876 protoDeps(ctx, &j.protoProperties)
877 }
878
879 if j.hasSrcExt(".kt") {
880 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
881 // Kotlin files
Colin Cross882d6002024-08-14 10:24:06 -0700882 tag := staticLibTag
883 if !BoolDefault(j.properties.Static_kotlin_stdlib, true) {
884 tag = libTag
885 }
886 ctx.AddVariationDependencies(nil, tag,
887 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700888 }
889
890 // Framework libraries need special handling in static coverage builds: they should not have
891 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
892 // the same jacoco classes coming from different bootclasspath jars.
893 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
894 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
895 j.properties.Instrument = true
896 }
897 } else if j.shouldInstrumentStatic(ctx) {
898 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
899 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700900
Cole Faustb7493472024-08-28 11:55:52 -0700901 if j.useCompose(ctx) {
Colin Crossa1ff7c62021-09-17 14:11:52 -0700902 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
903 "androidx.compose.compiler_compiler-hosted")
904 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700905}
906
907func hasSrcExt(srcs []string, ext string) bool {
908 for _, src := range srcs {
909 if filepath.Ext(src) == ext {
910 return true
911 }
912 }
913
914 return false
915}
916
917func (j *Module) hasSrcExt(ext string) bool {
918 return hasSrcExt(j.properties.Srcs, ext)
919}
920
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100921func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
922 var flags string
923
924 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
925 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
926 flags = "-Wmissing-permission-annotation -Werror"
927 }
928 }
929 return flags
930}
931
Jaewoong Jung26342642021-03-17 15:56:23 -0700932func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000933 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700934
935 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
936 aidlIncludes = append(aidlIncludes,
937 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
938 aidlIncludes = append(aidlIncludes,
939 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
940
941 var flags []string
942 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000943 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700944
945 flags = append(flags, j.deviceProperties.Aidl.Flags...)
946
947 if aidlPreprocess.Valid() {
948 flags = append(flags, "-p"+aidlPreprocess.String())
949 deps = append(deps, aidlPreprocess.Path())
950 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000951 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700952 }
953
954 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000955 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700956 }
957
958 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000959 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700960 }
961
Sam Delmerico2351eac2022-05-24 17:10:02 +0000962 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700963 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000964 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700965 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000966 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
967 // add flags for dirs containing AIDL srcs that haven't been specified yet
968 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700969
Zim8774ae12022-08-17 11:46:34 +0100970 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000971 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100972 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700973 flags = append(flags, "-t")
974 }
975
976 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
977 flags = append(flags, "--transaction_names")
978 }
979
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100980 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
981 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
982 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
983 }
984
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000985 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900986 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
987
Jaewoong Jung26342642021-03-17 15:56:23 -0700988 return strings.Join(flags, " "), deps
989}
990
991func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
992
993 var flags javaBuilderFlags
994
995 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900996 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700997
Cole Faust2b1536e2021-06-18 12:25:54 -0700998 epEnabled := j.properties.Errorprone.Enabled
999 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +01001000 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
1002 }
1003
1004 errorProneFlags := []string{
1005 "-Xplugin:ErrorProne",
1006 "${config.ErrorProneChecks}",
1007 }
1008 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
1009
Colin Cross8bf6cad2022-02-28 13:07:03 -08001010 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -07001011 "'" + strings.Join(errorProneFlags, " ") + "'"
1012 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
1013 }
1014
1015 // classpath
1016 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
1017 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001018 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001019 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
1020 flags.processorPath = append(flags.processorPath, deps.processorPath...)
1021 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
1022
1023 flags.processors = append(flags.processors, deps.processorClasses...)
1024 flags.processors = android.FirstUniqueStrings(flags.processors)
1025
1026 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001027 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001028 // Give host-side tools a version of OpenJDK's standard libraries
1029 // close to what they're targeting. As of Dec 2017, AOSP is only
1030 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1031 //
1032 // When building with OpenJDK 8, the following should have no
1033 // effect since those jars would be available by default.
1034 //
1035 // When building with OpenJDK 9 but targeting a version < 1.8,
1036 // putting them on the bootclasspath means that:
1037 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1038 // b) references to existing APIs are not reinterpreted in an
1039 // OpenJDK 9-specific way, eg. calls to subclasses of
1040 // java.nio.Buffer as in http://b/70862583
1041 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1042 flags.bootClasspath = append(flags.bootClasspath,
1043 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1044 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1045 if Bool(j.properties.Use_tools_jar) {
1046 flags.bootClasspath = append(flags.bootClasspath,
1047 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1048 }
1049 }
1050
1051 // systemModules
1052 flags.systemModules = deps.systemModules
1053
Jaewoong Jung26342642021-03-17 15:56:23 -07001054 return flags
1055}
1056
1057func (j *Module) collectJavacFlags(
1058 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1059 // javac flags.
1060 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001061 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001062
Mythri Alle4b9f6182023-10-25 15:17:11 +00001063 needsDebugInfo = false
1064 for _, flag := range javacFlags {
1065 if strings.HasPrefix(flag, "-g") {
1066 needsDebugInfo = true
1067 }
1068 }
1069
1070 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001071 // For non-host binaries, override the -g flag passed globally to remove
1072 // local variable debug info to reduce disk and memory usage.
1073 javacFlags = append(javacFlags, "-g:source,lines")
1074 }
1075 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1076
1077 if flags.javaVersion.usesJavaModules() {
1078 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001079 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1080 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1081 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1082 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001083
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001084 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 if j.properties.Patch_module != nil {
1086 // Manually specify build directory in case it is not under the repo root.
1087 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1088 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001089 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001090
Jaewoong Jung26342642021-03-17 15:56:23 -07001091 classPath := flags.classpath.FormJavaClassPath("")
1092 if classPath != "" {
1093 patchPaths = append(patchPaths, classPath)
1094 }
1095 javacFlags = append(
1096 javacFlags,
1097 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1098 }
1099 }
1100
1101 if len(javacFlags) > 0 {
1102 // optimization.
1103 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1104 flags.javacFlags = "$javacFlags"
1105 }
1106
1107 return flags
1108}
1109
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001110func (j *Module) AddJSONData(d *map[string]interface{}) {
1111 (&j.ModuleBase).AddJSONData(d)
1112 (*d)["Java"] = map[string]interface{}{
1113 "SourceExtensions": j.sourceExtensions,
1114 }
1115
1116}
1117
usta0391ca42023-09-19 15:51:59 -04001118func (j *Module) addGeneratedSrcJars(path android.Path) {
1119 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001120}
1121
Colin Crossfdaa6722024-08-23 11:58:08 -07001122func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars, extraDepCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001123 // Auto-propagating jarjar rules
1124 jarjarProviderData := j.collectJarJarRules(ctx)
1125 if jarjarProviderData != nil {
1126 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
Zi Wangddb2ee52024-04-02 16:44:02 +00001127 text := getJarJarRuleText(jarjarProviderData)
1128 if text != "" {
1129 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1130 android.WriteFileRule(ctx, ruleTextFile, text)
1131 j.repackageJarjarRules = ruleTextFile
Joe Onorato349ae8d2024-02-05 22:46:00 +00001132 }
1133 }
1134
Jaewoong Jung26342642021-03-17 15:56:23 -07001135 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1136
Makoto Onuki7ded3822024-03-28 14:42:20 -07001137 if re := proptools.Bool(j.properties.Ravenizer.Enabled); re {
1138 j.ravenizer.enabled = re
1139 }
1140
Jaewoong Jung26342642021-03-17 15:56:23 -07001141 deps := j.collectDeps(ctx)
1142 flags := j.collectBuilderFlags(ctx, deps)
1143
1144 if flags.javaVersion.usesJavaModules() {
1145 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001146 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1147 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1148 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001149 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001150
Jaewoong Jung26342642021-03-17 15:56:23 -07001151 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001152 j.sourceExtensions = []string{}
1153 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1154 if hasSrcExt(srcFiles.Strings(), ext) {
1155 j.sourceExtensions = append(j.sourceExtensions, ext)
1156 }
1157 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001158 if hasSrcExt(srcFiles.Strings(), ".proto") {
1159 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1160 }
1161
1162 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1163 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1164 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1165 }
1166
Sam Delmerico2351eac2022-05-24 17:10:02 +00001167 aidlSrcs := srcFiles.FilterByExt(".aidl")
1168 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1169
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001170 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001171 srcFiles = j.genSources(ctx, srcFiles, flags)
1172
1173 // Collect javac flags only after computing the full set of srcFiles to
1174 // ensure that the --patch-module lookup paths are complete.
1175 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1176
1177 srcJars := srcFiles.FilterByExt(".srcjar")
1178 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001179 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001180 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001181 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001182
1183 if j.properties.Jarjar_rules != nil {
1184 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1185 }
1186
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001187 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001188
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001189 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001190 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001191 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001192 if _, found := set[v.String()]; !found {
1193 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001194 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001195 }
1196 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001197 var uniqueKtFiles android.Paths
1198 for _, v := range srcFiles.FilterByExt(".kt") {
1199 if _, found := set[v.String()]; !found {
1200 set[v.String()] = true
1201 uniqueKtFiles = append(uniqueKtFiles, v)
1202 }
1203 }
1204
1205 var uniqueSrcFiles android.Paths
1206 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1207 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1208 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001209 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001210
Colin Crossb5db4012022-03-28 17:12:39 -07001211 // We don't currently run annotation processors in turbine, which means we can't use turbine
1212 // generated header jars when an annotation processor that generates API is enabled. One
1213 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1214 // is used to run all of the annotation processors.
1215 disableTurbine := deps.disableTurbine
1216
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001217 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001218 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1219
Colin Cross220a9a12022-03-28 17:08:01 -07001220 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001221
Colin Cross4eae06d2023-06-20 22:40:02 -07001222 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1223 // any dependencies so that it can override any non-final R classes from dependencies with the
1224 // final R classes from the app.
1225 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1226
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001227 j.aconfigCacheFiles = append(deps.aconfigProtoFiles, j.properties.Aconfig_Cache_files...)
1228
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001229 var localImplementationJars android.Paths
1230
Mark Whitea15790a2023-08-22 21:28:11 +00001231 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001232 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001233 if srcFiles.HasExt(".kt") {
1234 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1235 }
1236 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1237 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1238 }
1239
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001240 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1241
1242 localHeaderJars, combinedHeaderJarFile := j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
Colin Crossedec77c2024-07-26 15:25:40 -07001243 extraCombinedJars)
1244
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001245 combinedHeaderJarFile, jarjared := j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1246 if jarjared {
1247 localHeaderJars = android.Paths{combinedHeaderJarFile}
1248 transitiveStaticLibsHeaderJars = nil
1249 }
1250 combinedHeaderJarFile, repackaged := j.repackageFlagsIfNecessary(ctx, combinedHeaderJarFile, jarName, "repackage-turbine")
1251 if repackaged {
1252 localHeaderJars = android.Paths{combinedHeaderJarFile}
1253 transitiveStaticLibsHeaderJars = nil
1254 }
Mark Whitea15790a2023-08-22 21:28:11 +00001255 if ctx.Failed() {
1256 return
1257 }
Colin Crossedec77c2024-07-26 15:25:40 -07001258 j.headerJarFile = combinedHeaderJarFile
Mark Whitea15790a2023-08-22 21:28:11 +00001259
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001260 if ctx.Config().UseTransitiveJarsInClasspath() {
1261 if len(localHeaderJars) > 0 {
1262 ctx.CheckbuildFile(localHeaderJars...)
1263 } else {
1264 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1265 ctx.UncheckedModule()
1266 }
1267 } else {
1268 ctx.CheckbuildFile(j.headerJarFile)
1269 }
Colin Crossa6182ab2024-08-21 10:47:44 -07001270
Colin Cross7727c7f2024-07-18 15:36:32 -07001271 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Jihoon Kang705e63e2024-03-13 01:21:16 +00001272 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001273 LocalHeaderJars: localHeaderJars,
1274 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
Colin Cross9ffaf282024-08-12 13:50:09 -07001275 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1276 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001277 AidlIncludeDirs: j.exportAidlIncludeDirs,
1278 ExportedPlugins: j.exportedPluginJars,
1279 ExportedPluginClasses: j.exportedPluginClasses,
1280 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1281 StubsLinkType: j.stubsLinkType,
1282 AconfigIntermediateCacheOutputPaths: deps.aconfigProtoFiles,
Mark Whitea15790a2023-08-22 21:28:11 +00001283 })
1284
1285 j.outputFile = j.headerJarFile
1286 return
1287 }
1288
Jaewoong Jung26342642021-03-17 15:56:23 -07001289 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001290 // When using kotlin sources turbine is used to generate annotation processor sources,
1291 // including for annotation processors that generate API, so we can use turbine for
1292 // java sources too.
1293 disableTurbine = false
1294
Jaewoong Jung26342642021-03-17 15:56:23 -07001295 // user defined kotlin flags.
1296 kotlincFlags := j.properties.Kotlincflags
1297 CheckKotlincFlags(ctx, kotlincFlags)
1298
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001299 // Workaround for KT-46512
1300 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001301
1302 // If there are kotlin files, compile them first but pass all the kotlin and java files
1303 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1304 // won't emit any classes for them.
1305 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1306 if ctx.Device() {
1307 kotlincFlags = append(kotlincFlags, "-no-jdk")
1308 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001309
1310 for _, plugin := range deps.kotlinPlugins {
1311 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1312 }
1313 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1314
Jaewoong Jung26342642021-03-17 15:56:23 -07001315 if len(kotlincFlags) > 0 {
1316 // optimization.
1317 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1318 flags.kotlincFlags += "$kotlincFlags"
1319 }
1320
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001321 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001322 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1323
Jaewoong Jung26342642021-03-17 15:56:23 -07001324 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1325 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1326
Isaac Chioua23d9942022-04-06 06:14:38 +00001327 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001328 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001329 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1330 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001331 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001332 srcJars = append(srcJars, kaptSrcJar)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001333 localImplementationJars = append(localImplementationJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001334 // Disable annotation processing in javac, it's already been handled by kapt
1335 flags.processorPath = nil
1336 flags.processors = nil
1337 }
1338
1339 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001340 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Spandan Das1028d5a2024-08-19 21:45:48 +00001341 j.kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001342 if ctx.Failed() {
1343 return
1344 }
1345
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001346 kotlinJarPath, _ := j.repackageFlagsIfNecessary(ctx, kotlinJar, jarName, "kotlinc")
Zi Wangddb2ee52024-04-02 16:44:02 +00001347
Isaac Chioua23d9942022-04-06 06:14:38 +00001348 // Make javac rule depend on the kotlinc rule
1349 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1350
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001351 localImplementationJars = append(localImplementationJars, kotlinJarPath)
1352
Colin Cross220a9a12022-03-28 17:08:01 -07001353 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001354 }
1355
Jaewoong Jung26342642021-03-17 15:56:23 -07001356 j.compiledSrcJars = srcJars
1357
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001358 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1359
Jaewoong Jung26342642021-03-17 15:56:23 -07001360 enableSharding := false
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001361 var localHeaderJars android.Paths
1362 var shardingHeaderJars android.Paths
1363 var repackagedHeaderJarFile android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001364 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001365 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1366 enableSharding = true
1367 // Formerly, there was a check here that prevented annotation processors
1368 // from being used when sharding was enabled, as some annotation processors
1369 // do not function correctly in sharded environments. It was removed to
1370 // allow for the use of annotation processors that do function correctly
1371 // with sharding enabled. See: b/77284273.
1372 }
Colin Crossd1d8f172024-07-29 11:30:29 -07001373 extraJars := slices.Clone(kotlinHeaderJars)
Colin Crossd1d8f172024-07-29 11:30:29 -07001374 extraJars = append(extraJars, extraCombinedJars...)
Colin Crossedec77c2024-07-26 15:25:40 -07001375 var combinedHeaderJarFile android.Path
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001376 localHeaderJars, combinedHeaderJarFile = j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
1377 shardingHeaderJars = localHeaderJars
Colin Crossedec77c2024-07-26 15:25:40 -07001378
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001379 var jarjared bool
1380 j.headerJarFile, jarjared = j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1381 if jarjared {
1382 // jarjar modifies transitive static dependencies, use the combined header jar and drop the transitive
1383 // static libs header jars.
1384 localHeaderJars = android.Paths{j.headerJarFile}
1385 transitiveStaticLibsHeaderJars = nil
1386 }
1387 var repackaged bool
1388 repackagedHeaderJarFile, repackaged = j.repackageFlagsIfNecessary(ctx, j.headerJarFile, jarName, "turbine")
1389 if repackaged {
1390 // repackage modifies transitive static dependencies, use the combined header jar and drop the transitive
1391 // static libs header jars.
1392 // TODO(b/356688296): this shouldn't export both the unmodified and repackaged header jars
1393 localHeaderJars = android.Paths{j.headerJarFile, repackagedHeaderJarFile}
1394 transitiveStaticLibsHeaderJars = nil
1395 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001396 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001397 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001398 hasErrorproneableFiles := false
1399 for _, ext := range j.sourceExtensions {
1400 if ext != ".proto" && ext != ".aidl" {
1401 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1402 // compile, and it's not useful to have warnings on these generated sources.
1403 hasErrorproneableFiles = true
1404 break
1405 }
1406 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001407 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001408 if Bool(j.properties.Errorprone.Enabled) {
1409 // If error-prone is enabled, enable errorprone flags on the regular
1410 // build.
1411 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001412 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001413 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1414 // a new jar file just for compiling with the errorprone compiler to.
1415 // This is because we don't want to cause the java files to get completely
1416 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1417 // We also don't want to run this if errorprone is enabled by default for
1418 // this module, or else we could have duplicated errorprone messages.
1419 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001420 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001421 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001422
Vadim Spivak3c496f02023-06-08 06:14:59 +00001423 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001424 "errorprone", "errorprone")
1425
Jaewoong Jung26342642021-03-17 15:56:23 -07001426 extraJarDeps = append(extraJarDeps, errorprone)
1427 }
1428
1429 if enableSharding {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001430 if len(shardingHeaderJars) > 0 {
1431 flags.classpath = append(classpath(slices.Clone(shardingHeaderJars)), flags.classpath...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001432 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001433 shardSize := int(*(j.properties.Javac_shard_size))
1434 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001435 if len(uniqueJavaFiles) > 0 {
1436 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001437 for idx, shardSrc := range shardSrcs {
1438 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1439 nil, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001440 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(idx))
1441 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001442 }
1443 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001444 // Assume approximately 5 sources per srcjar.
1445 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1446 // 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 -07001447 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001448 startIdx := len(shardSrcs)
1449 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1450 for idx, shardSrcJars := range shardSrcJarsList {
1451 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1452 nil, shardSrcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001453 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(startIdx+idx))
1454 localImplementationJars = append(localImplementationJars, classes)
Colin Crossa052ddb2023-09-25 21:46:58 -07001455 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 }
1457 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001458 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001459 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac")
1460 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001461 }
1462 if ctx.Failed() {
1463 return
1464 }
1465 }
1466
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001467 localImplementationJars = append(localImplementationJars, extraCombinedJars...)
Colin Crossfd620b22024-02-23 10:05:21 -08001468
Jaewoong Jung26342642021-03-17 15:56:23 -07001469 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1470
1471 var includeSrcJar android.WritablePath
1472 if Bool(j.properties.Include_srcs) {
1473 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1474 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1475 }
1476
1477 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1478 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1479 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1480 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1481
1482 var resArgs []string
1483 var resDeps android.Paths
1484
1485 resArgs = append(resArgs, dirArgs...)
1486 resDeps = append(resDeps, dirDeps...)
1487
1488 resArgs = append(resArgs, fileArgs...)
1489 resDeps = append(resDeps, fileDeps...)
1490
1491 resArgs = append(resArgs, extraArgs...)
1492 resDeps = append(resDeps, extraDeps...)
1493
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001494 var localResourceJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001495 if len(resArgs) > 0 {
1496 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1497 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 if ctx.Failed() {
1499 return
1500 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001501 localResourceJars = append(localResourceJars, resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001502 }
1503
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 if Bool(j.properties.Include_srcs) {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001505 localResourceJars = append(localResourceJars, includeSrcJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001506 }
1507
1508 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1509 if len(services) > 0 {
1510 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1511 var zipargs []string
1512 for _, file := range services {
1513 serviceFile := file.String()
1514 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1515 }
1516 rule := zip
1517 args := map[string]string{
1518 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1519 }
1520 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1521 rule = zipRE
1522 args["implicits"] = strings.Join(services.Strings(), ",")
1523 }
1524 ctx.Build(pctx, android.BuildParams{
1525 Rule: rule,
1526 Output: servicesJar,
1527 Implicits: services,
1528 Args: args,
1529 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001530 localResourceJars = append(localResourceJars, servicesJar)
1531 }
1532
1533 completeStaticLibsResourceJars := android.NewDepSet(android.PREORDER, localResourceJars, deps.transitiveStaticLibsResourceJars)
1534
1535 var combinedResourceJar android.Path
1536 var resourceJars android.Paths
1537 if ctx.Config().UseTransitiveJarsInClasspath() {
1538 resourceJars = completeStaticLibsResourceJars.ToList()
1539 } else {
1540 resourceJars = append(slices.Clone(localResourceJars), deps.staticResourceJars...)
1541 }
1542 if len(resourceJars) == 1 {
1543 combinedResourceJar = resourceJars[0]
1544 } else if len(resourceJars) > 0 {
1545 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1546 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1547 false, nil, nil)
1548 combinedResourceJar = combinedJar
1549 }
1550
1551 manifest := j.overrideManifest
1552 if !manifest.Valid() && j.properties.Manifest != nil {
1553 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
Jaewoong Jung26342642021-03-17 15:56:23 -07001554 }
1555
1556 // Combine the classes built from sources, any manifests, and any static libraries into
1557 // classes.jar. If there is only one input jar this step will be skipped.
Colin Cross7707b242024-07-26 12:02:36 -07001558 var outputFile android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001559
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001560 completeStaticLibsImplementationJars := android.NewDepSet(android.PREORDER, localImplementationJars, deps.transitiveStaticLibsImplementationJars)
1561
1562 var jars android.Paths
1563 if ctx.Config().UseTransitiveJarsInClasspath() {
1564 jars = completeStaticLibsImplementationJars.ToList()
1565 } else {
1566 jars = append(slices.Clone(localImplementationJars), deps.staticJars...)
1567 }
1568
1569 jars = append(jars, extraDepCombinedJars...)
1570
Jaewoong Jung26342642021-03-17 15:56:23 -07001571 if len(jars) == 1 && !manifest.Valid() {
1572 // Optimization: skip the combine step as there is nothing to do
1573 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1574 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001575 // any if len(extraJars) == 0.
Jaewoong Jung26342642021-03-17 15:56:23 -07001576
Jihoon Kang1147b312023-06-08 23:25:57 +00001577 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1578 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1579 // either with .from-source or .from-text suffix.
1580 // outputFile should be agnostic to the build configuration,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001581 // thus copy the single input static lib in order to prevent the static lib from being exposed
Jihoon Kang1147b312023-06-08 23:25:57 +00001582 // to the copy rules.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001583 if stub, _ := moduleStubLinkType(j); stub {
1584 copiedJar := android.PathForModuleOut(ctx, "combined", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001585 ctx.Build(pctx, android.BuildParams{
1586 Rule: android.Cp,
1587 Input: jars[0],
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001588 Output: copiedJar,
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001590 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, android.Paths{copiedJar}, nil)
1591 outputFile = copiedJar
Colin Cross7707b242024-07-26 12:02:36 -07001592 } else {
1593 outputFile = jars[0]
Jaewoong Jung26342642021-03-17 15:56:23 -07001594 }
1595 } else {
1596 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1597 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1598 false, nil, nil)
Colin Cross7707b242024-07-26 12:02:36 -07001599 outputFile = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001600 }
1601
1602 // jarjar implementation jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001603 jarjarFile, jarjarred := j.jarjarIfNecessary(ctx, outputFile, jarName, "")
1604 if jarjarred {
1605 localImplementationJars = android.Paths{jarjarFile}
1606 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
1607 }
Colin Crossedec77c2024-07-26 15:25:40 -07001608 outputFile = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001609
Colin Crossedec77c2024-07-26 15:25:40 -07001610 // jarjar resource jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001611 if combinedResourceJar != nil {
1612 resourceJarJarFile, jarjarred := j.jarjarIfNecessary(ctx, combinedResourceJar, jarName, "resource")
1613 combinedResourceJar = resourceJarJarFile
1614 if jarjarred {
1615 localResourceJars = android.Paths{resourceJarJarFile}
1616 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1617 }
Colin Crossedec77c2024-07-26 15:25:40 -07001618 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001619
Colin Crossedec77c2024-07-26 15:25:40 -07001620 if ctx.Failed() {
1621 return
Jaewoong Jung26342642021-03-17 15:56:23 -07001622 }
1623
Makoto Onuki7ded3822024-03-28 14:42:20 -07001624 if j.ravenizer.enabled {
1625 ravenizerInput := outputFile
1626 ravenizerOutput := android.PathForModuleOut(ctx, "ravenizer", jarName)
1627 ctx.Build(pctx, android.BuildParams{
1628 Rule: ravenizer,
1629 Description: "ravenizer",
1630 Input: ravenizerInput,
1631 Output: ravenizerOutput,
1632 })
1633 outputFile = ravenizerOutput
Colin Cross7e863852024-09-06 14:42:38 -07001634 localImplementationJars = android.Paths{ravenizerOutput}
1635 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Makoto Onuki7ded3822024-03-28 14:42:20 -07001636 }
1637
Yihan Dong8be09c22024-08-29 15:32:13 +08001638 if j.shouldApiMapper() {
1639 inputFile := outputFile
1640 apiMapperFile := android.PathForModuleOut(ctx, "apimapper", jarName)
1641 ctx.Build(pctx, android.BuildParams{
1642 Rule: apimapper,
1643 Description: "apimapper",
1644 Input: inputFile,
1645 Output: apiMapperFile,
1646 })
1647 outputFile = apiMapperFile
Colin Cross7e863852024-09-06 14:42:38 -07001648 localImplementationJars = android.Paths{apiMapperFile}
1649 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Yihan Dong8be09c22024-08-29 15:32:13 +08001650 }
1651
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 // Check package restrictions if necessary.
1653 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001654 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001655 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001656
1657 // Create a rule to copy the output jar to another path and add a validate dependency that
1658 // will check that the jar only contains the permitted packages. The new location will become
1659 // the output file of this module.
1660 inputFile := outputFile
Colin Cross7707b242024-07-26 12:02:36 -07001661 packageCheckOutputFile := android.PathForModuleOut(ctx, "package-check", jarName)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001662 ctx.Build(pctx, android.BuildParams{
1663 Rule: android.Cp,
1664 Input: inputFile,
Colin Cross7707b242024-07-26 12:02:36 -07001665 Output: packageCheckOutputFile,
Paul Duffin08a18bf2021-10-01 13:19:58 +01001666 // Make sure that any dependency on the output file will cause ninja to run the package check
1667 // rule.
1668 Validation: pkgckFile,
1669 })
Colin Cross7707b242024-07-26 12:02:36 -07001670 outputFile = packageCheckOutputFile
Colin Cross7e863852024-09-06 14:42:38 -07001671 localImplementationJars = android.Paths{packageCheckOutputFile}
1672 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001673
1674 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001675 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001676
1677 if ctx.Failed() {
1678 return
1679 }
1680 }
1681
1682 j.implementationJarFile = outputFile
1683 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001684 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1685 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1686 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1687 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1688 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1689 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1690 j.headerJarFile = headerJarFile
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001691 if len(localImplementationJars) == 1 && ctx.Config().UseTransitiveJarsInClasspath() {
1692 localHeaderJarFile := android.PathForModuleOut(ctx, "local-javac-header", jarName)
1693 convertImplementationJarToHeaderJar(ctx, localImplementationJars[0], localHeaderJarFile)
1694 localHeaderJars = append(localHeaderJars, localHeaderJarFile)
1695 } else {
1696 localHeaderJars = append(localHeaderJars, headerJarFile)
1697 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001698 }
1699
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001700 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1701 specs := j.jacocoModuleToZipCommand(ctx)
1702 if ctx.Failed() {
1703 return
1704 }
1705
Colin Crossb323c912024-09-24 15:21:00 -07001706 completeStaticLibsImplementationJarsToCombine := completeStaticLibsImplementationJars
1707
Jaewoong Jung26342642021-03-17 15:56:23 -07001708 if j.shouldInstrument(ctx) {
Colin Crossb323c912024-09-24 15:21:00 -07001709 instrumentedOutputFile := j.instrument(ctx, flags, outputFile, jarName, specs)
1710 completeStaticLibsImplementationJarsToCombine = android.NewDepSet(android.PREORDER, android.Paths{instrumentedOutputFile}, nil)
1711 outputFile = instrumentedOutputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001712 }
1713
1714 // merge implementation jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001715 var implementationAndResourcesJarsToCombine android.Paths
1716 if ctx.Config().UseTransitiveJarsInClasspath() {
1717 resourceJars := completeStaticLibsResourceJars.ToList()
1718 if len(resourceJars) > 0 {
Colin Crossb323c912024-09-24 15:21:00 -07001719 implementationAndResourcesJarsToCombine = append(resourceJars, completeStaticLibsImplementationJarsToCombine.ToList()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001720 implementationAndResourcesJarsToCombine = append(implementationAndResourcesJarsToCombine, extraDepCombinedJars...)
1721 }
1722 } else {
1723 if combinedResourceJar != nil {
1724 implementationAndResourcesJarsToCombine = android.Paths{combinedResourceJar, outputFile}
1725 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001726 }
1727
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001728 if len(implementationAndResourcesJarsToCombine) > 0 {
1729 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
1730 TransformJarsToJar(ctx, combinedJar, "for resources", implementationAndResourcesJarsToCombine, manifest,
1731 false, nil, nil)
1732 outputFile = combinedJar
1733 }
1734
1735 j.implementationAndResourcesJar = outputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001736
1737 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001738 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001739 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001740 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001741 if compileDex == nil {
1742 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001743 }
1744 if j.deviceProperties.Hostdex == nil {
1745 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1746 }
1747 }
1748
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001749 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001750 if j.hasCode(ctx) {
1751 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001752 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001753 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1754 }
1755 // Dex compilation
Colin Cross7707b242024-07-26 12:02:36 -07001756 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00001757 params := &compileDexParams{
1758 flags: flags,
1759 sdkVersion: j.SdkVersion(ctx),
1760 minSdkVersion: j.MinSdkVersion(ctx),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001761 classesJar: outputFile,
Spandan Dasc404cc72023-02-23 18:05:05 +00001762 jarName: jarName,
1763 }
Cole Fausteb032462024-09-19 11:12:54 -07001764 if j.GetProfileGuided(ctx) && j.optimizeOrObfuscateEnabled() && !j.EnableProfileRewriting(ctx) {
Spandan Das15a67112024-05-30 00:07:40 +00001765 ctx.PropertyErrorf("enable_profile_rewriting",
1766 "Enable_profile_rewriting must be true when profile_guided dexpreopt and R8 optimization/obfuscation is turned on. The attached profile should be sourced from an unoptimized/unobfuscated APK.",
1767 )
1768 }
Cole Fausteb032462024-09-19 11:12:54 -07001769 if j.EnableProfileRewriting(ctx) {
1770 profile := j.GetProfile(ctx)
1771 if profile == "" || !j.GetProfileGuided(ctx) {
Spandan Das3dbda182024-05-20 22:23:10 +00001772 ctx.PropertyErrorf("enable_profile_rewriting", "Profile and Profile_guided must be set when enable_profile_rewriting is true")
1773 }
1774 params.artProfileInput = &profile
1775 }
1776 dexOutputFile, dexArtProfileOutput := j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001777 if ctx.Failed() {
1778 return
1779 }
1780
Spandan Das3dbda182024-05-20 22:23:10 +00001781 // If r8/d8 provides a profile that matches the optimized dex, use that for dexpreopt.
1782 if dexArtProfileOutput != nil {
Colin Cross7707b242024-07-26 12:02:36 -07001783 j.dexpreopter.SetRewrittenProfile(dexArtProfileOutput)
Spandan Das3dbda182024-05-20 22:23:10 +00001784 }
1785
Jaewoong Jung26342642021-03-17 15:56:23 -07001786 // merge dex jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001787 var dexAndResourceJarsToCombine android.Paths
1788 if ctx.Config().UseTransitiveJarsInClasspath() {
1789 resourceJars := completeStaticLibsResourceJars.ToList()
1790 if len(resourceJars) > 0 {
1791 dexAndResourceJarsToCombine = append(android.Paths{dexOutputFile}, resourceJars...)
1792 }
1793 } else {
1794 if combinedResourceJar != nil {
1795 dexAndResourceJarsToCombine = android.Paths{dexOutputFile, combinedResourceJar}
1796 }
1797 }
1798 if len(dexAndResourceJarsToCombine) > 0 {
Colin Cross7707b242024-07-26 12:02:36 -07001799 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001800 TransformJarsToJar(ctx, combinedJar, "for dex resources", dexAndResourceJarsToCombine, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07001801 false, nil, nil)
1802 if *j.dexProperties.Uncompress_dex {
Colin Cross7707b242024-07-26 12:02:36 -07001803 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName)
Cole Faust51d7bfd2023-09-07 05:31:32 +00001804 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001805 dexOutputFile = combinedAlignedJar
1806 } else {
1807 dexOutputFile = combinedJar
1808 }
1809 }
1810
Paul Duffin4de94502021-05-16 05:21:16 +01001811 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001812
1813 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001814
1815 // Encode hidden API flags in dex file, if needed.
1816 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1817
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001818 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001819
1820 // Dexpreopting
Jihoon Kanga3a05462024-04-05 00:36:44 +00001821 libName := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())
1822 if j.SdkLibraryName() != nil && strings.HasSuffix(ctx.ModuleName(), ".impl") {
1823 libName = strings.TrimSuffix(libName, ".impl")
1824 }
1825 j.dexpreopt(ctx, libName, dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001826
1827 outputFile = dexOutputFile
Colin Crossa6182ab2024-08-21 10:47:44 -07001828
1829 ctx.CheckbuildFile(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001830 } else {
1831 // There is no code to compile into a dex jar, make sure the resources are propagated
1832 // to the APK if this is an app.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001833 j.dexJarFile = makeDexJarPathFromPath(combinedResourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001834 }
1835
1836 if ctx.Failed() {
1837 return
1838 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001839 }
1840
1841 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001842 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001843 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001844 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001845 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001846 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001847 }
1848 }
1849
1850 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001851 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1852 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001853 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1854 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001855 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001856 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001857 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001858 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001859 j.linter.javaLanguageLevel = flags.javaVersion.String()
1860 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001861 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001862 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1863 j.linter.buildModuleReportZip = true
1864 }
1865 j.linter.lint(ctx)
1866 }
1867
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001868 j.collectTransitiveSrcFiles(ctx, srcFiles)
1869
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001870 if ctx.Config().UseTransitiveJarsInClasspath() {
1871 if len(localImplementationJars) > 0 || len(localResourceJars) > 0 || len(localHeaderJars) > 0 {
1872 ctx.CheckbuildFile(localImplementationJars...)
1873 ctx.CheckbuildFile(localResourceJars...)
1874 ctx.CheckbuildFile(localHeaderJars...)
1875 } else {
1876 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1877 ctx.UncheckedModule()
1878 }
1879 } else {
1880 ctx.CheckbuildFile(j.implementationJarFile)
1881 ctx.CheckbuildFile(j.headerJarFile)
1882 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001883
Colin Cross7727c7f2024-07-18 15:36:32 -07001884 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001885 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1886 RepackagedHeaderJars: android.PathsIfNonNil(repackagedHeaderJarFile),
1887
1888 LocalHeaderJars: localHeaderJars,
1889 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
1890 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
1891 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
1892
Colin Cross9ffaf282024-08-12 13:50:09 -07001893 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1894 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001895 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1896 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001897 ResourceJars: android.PathsIfNonNil(combinedResourceJar),
Jihoon Kang705e63e2024-03-13 01:21:16 +00001898 AidlIncludeDirs: j.exportAidlIncludeDirs,
1899 SrcJarArgs: j.srcJarArgs,
1900 SrcJarDeps: j.srcJarDeps,
1901 TransitiveSrcFiles: j.transitiveSrcFiles,
1902 ExportedPlugins: j.exportedPluginJars,
1903 ExportedPluginClasses: j.exportedPluginClasses,
1904 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1905 JacocoReportClassesFile: j.jacocoReportClassesFile,
1906 StubsLinkType: j.stubsLinkType,
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001907 AconfigIntermediateCacheOutputPaths: j.aconfigCacheFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001908 })
1909
1910 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1911 j.outputFile = outputFile.WithoutRel()
1912}
1913
Cole Faustb7493472024-08-28 11:55:52 -07001914func (j *Module) useCompose(ctx android.BaseModuleContext) bool {
1915 return android.InList("androidx.compose.runtime_runtime", j.staticLibs(ctx))
Colin Crossa1ff7c62021-09-17 14:11:52 -07001916}
1917
Colin Crosscde55342024-03-27 14:11:51 -07001918func collectDepProguardSpecInfo(ctx android.ModuleContext) (transitiveProguardFlags, transitiveUnconditionalExportedFlags []*android.DepSet[android.Path]) {
Sam Delmerico95d70942023-08-02 18:00:35 -04001919 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001920 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001921 depTag := ctx.OtherModuleDependencyTag(m)
1922
1923 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1924 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1925 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1926 }
1927
1928 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1929 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1930 }
1931 })
1932
Colin Crosscde55342024-03-27 14:11:51 -07001933 return transitiveProguardFlags, transitiveUnconditionalExportedFlags
1934}
1935
1936func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1937 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
1938
Sam Delmerico95d70942023-08-02 18:00:35 -04001939 directUnconditionalExportedFlags := android.Paths{}
1940 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1941 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1942 if exportUnconditionally {
1943 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1944 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1945 directUnconditionalExportedFlags = proguardFlagsForThisModule
1946 }
1947
1948 return ProguardSpecInfo{
1949 Export_proguard_flags_files: exportUnconditionally,
1950 ProguardFlagsFiles: android.NewDepSet[android.Path](
1951 android.POSTORDER,
1952 proguardFlagsForThisModule,
1953 transitiveProguardFlags,
1954 ),
1955 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1956 android.POSTORDER,
1957 directUnconditionalExportedFlags,
1958 transitiveUnconditionalExportedFlags,
1959 ),
1960 }
1961
1962}
1963
Cole Faust75fffb12021-06-13 15:23:16 -07001964// Returns a copy of the supplied flags, but with all the errorprone-related
1965// fields copied to the regular build's fields.
1966func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1967 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1968
1969 if len(flags.errorProneExtraJavacFlags) > 0 {
1970 if len(flags.javacFlags) > 0 {
1971 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1972 } else {
1973 flags.javacFlags = flags.errorProneExtraJavacFlags
1974 }
1975 }
1976 return flags
1977}
1978
Jaewoong Jung26342642021-03-17 15:56:23 -07001979func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
Colin Cross7707b242024-07-26 12:02:36 -07001980 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07001981
1982 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001983 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001984 if idx >= 0 {
1985 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001986 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001987 jarName += strconv.Itoa(idx)
1988 }
1989
Colin Cross7707b242024-07-26 12:02:36 -07001990 classes := android.PathForModuleOut(ctx, "javac", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001991 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001992
Cole Faust9decf832024-06-11 11:45:53 -07001993 if ctx.Config().EmitXrefRules() && ctx.Module() == ctx.PrimaryModule() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001994 extractionFile := android.PathForModuleOut(ctx, kzipName)
1995 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1996 j.kytheFiles = append(j.kytheFiles, extractionFile)
1997 }
1998
Vadim Spivak3c496f02023-06-08 06:14:59 +00001999 if len(flags.processorPath) > 0 {
2000 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
2001 }
2002
Jaewoong Jung26342642021-03-17 15:56:23 -07002003 return classes
2004}
2005
2006// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
2007// since some of these flags may be used internally.
2008func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
2009 for _, flag := range flags {
2010 flag = strings.TrimSpace(flag)
2011
2012 if !strings.HasPrefix(flag, "-") {
2013 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
2014 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
2015 ctx.PropertyErrorf("kotlincflags",
2016 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
2017 } else if inList(flag, config.KotlincIllegalFlags) {
2018 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
2019 } else if flag == "-include-runtime" {
2020 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
2021 } else {
2022 args := strings.Split(flag, " ")
2023 if args[0] == "-kotlin-home" {
2024 ctx.PropertyErrorf("kotlincflags",
2025 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
2026 }
2027 }
2028 }
2029}
2030
2031func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
2032 deps deps, flags javaBuilderFlags, jarName string,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002033 extraJars android.Paths) (localHeaderJars android.Paths, combinedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002034
Jaewoong Jung26342642021-03-17 15:56:23 -07002035 if len(srcFiles) > 0 || len(srcJars) > 0 {
2036 // Compile java sources into turbine.jar.
2037 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
2038 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002039 localHeaderJars = append(localHeaderJars, turbineJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07002040 }
2041
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002042 localHeaderJars = append(localHeaderJars, extraJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002043
2044 // Combine any static header libraries into classes-header.jar. If there is only
2045 // one input jar this step will be skipped.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002046 var jars android.Paths
2047 if ctx.Config().UseTransitiveJarsInClasspath() {
2048 depSet := android.NewDepSet(android.PREORDER, localHeaderJars, deps.transitiveStaticLibsHeaderJars)
2049 jars = depSet.ToList()
2050 } else {
2051 jars = append(slices.Clone(localHeaderJars), deps.staticHeaderJars...)
2052 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002053
2054 // we cannot skip the combine step for now if there is only one jar
2055 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
Colin Crossedec77c2024-07-26 15:25:40 -07002056 combinedHeaderJarOutputPath := android.PathForModuleOut(ctx, "turbine-combined", jarName)
2057 TransformJarsToJar(ctx, combinedHeaderJarOutputPath, "for turbine", jars, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07002058 false, nil, []string{"META-INF/TRANSITIVE"})
Jaewoong Jung26342642021-03-17 15:56:23 -07002059
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002060 return localHeaderJars, combinedHeaderJarOutputPath
Jaewoong Jung26342642021-03-17 15:56:23 -07002061}
2062
2063func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Colin Cross7707b242024-07-26 12:02:36 -07002064 classesJar android.Path, jarName string, specs string) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07002065
2066 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
Colin Cross7707b242024-07-26 12:02:36 -07002067 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07002068
2069 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
2070
2071 j.jacocoReportClassesFile = jacocoReportClassesFile
2072
2073 return instrumentedJar
2074}
2075
Colin Cross9ffaf282024-08-12 13:50:09 -07002076type providesTransitiveHeaderJarsForR8 struct {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002077 // set of header jars for all transitive libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002078 transitiveLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002079 // set of header jars for all transitive static libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002080 transitiveStaticLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002081}
2082
Colin Cross9ffaf282024-08-12 13:50:09 -07002083// collectTransitiveHeaderJarsForR8 visits direct dependencies and collects all transitive libs and static_libs
2084// header jars. The semantics of the collected jars are odd (it collects combined jars that contain the static
2085// libs, but also the static libs, and it collects transitive libs dependencies of static_libs), so these
2086// are only used to expand the --lib arguments to R8.
2087func (j *providesTransitiveHeaderJarsForR8) collectTransitiveHeaderJarsForR8(ctx android.ModuleContext) {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002088 directLibs := android.Paths{}
2089 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07002090 transitiveLibs := []*android.DepSet[android.Path]{}
2091 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002092 ctx.VisitDirectDeps(func(module android.Module) {
2093 // don't add deps of the prebuilt version of the same library
2094 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
2095 return
2096 }
2097
Colin Cross7727c7f2024-07-18 15:36:32 -07002098 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2099 tag := ctx.OtherModuleDependencyTag(module)
2100 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
2101 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
2102 directLibs = append(directLibs, dep.HeaderJars...)
2103 } else if tag == staticLibTag {
2104 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
2105 } else {
2106 // Don't propagate transitive libs for other kinds of dependencies.
2107 return
2108 }
Jared Dukeefb6d602023-10-27 18:47:10 +00002109
Colin Cross9ffaf282024-08-12 13:50:09 -07002110 if dep.TransitiveLibsHeaderJarsForR8 != nil {
2111 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002112 }
Colin Cross9ffaf282024-08-12 13:50:09 -07002113 if dep.TransitiveStaticLibsHeaderJarsForR8 != nil {
2114 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002115 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002116
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002117 }
2118 })
Colin Cross9ffaf282024-08-12 13:50:09 -07002119 j.transitiveLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
2120 j.transitiveStaticLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002121}
2122
Jaewoong Jung26342642021-03-17 15:56:23 -07002123func (j *Module) HeaderJars() android.Paths {
2124 if j.headerJarFile == nil {
2125 return nil
2126 }
2127 return android.Paths{j.headerJarFile}
2128}
2129
2130func (j *Module) ImplementationJars() android.Paths {
2131 if j.implementationJarFile == nil {
2132 return nil
2133 }
2134 return android.Paths{j.implementationJarFile}
2135}
2136
Spandan Das59a4a2b2024-01-09 21:35:56 +00002137func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07002138 return j.dexJarFile
2139}
2140
2141func (j *Module) DexJarInstallPath() android.Path {
2142 return j.installFile
2143}
2144
2145func (j *Module) ImplementationAndResourcesJars() android.Paths {
2146 if j.implementationAndResourcesJar == nil {
2147 return nil
2148 }
2149 return android.Paths{j.implementationAndResourcesJar}
2150}
2151
2152func (j *Module) AidlIncludeDirs() android.Paths {
2153 // exportAidlIncludeDirs is type android.Paths already
2154 return j.exportAidlIncludeDirs
2155}
2156
2157func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2158 return j.classLoaderContexts
2159}
2160
2161// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -07002162func (j *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002163 // jarjar rules will repackage the sources. To prevent misleading results, IdeInfo should contain the
2164 // repackaged jar instead of the input sources.
Jaewoong Jung26342642021-03-17 15:56:23 -07002165 if j.expandJarjarRules != nil {
2166 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002167 dpInfo.Jars = append(dpInfo.Jars, j.headerJarFile.String())
2168 } else {
2169 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2170 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2171 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002172 }
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002173 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2174 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
Cole Faustb7493472024-08-28 11:55:52 -07002175 dpInfo.Static_libs = append(dpInfo.Static_libs, j.staticLibs(ctx)...)
Yikef6282022022-04-13 20:41:01 +08002176 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002177}
2178
2179func (j *Module) CompilerDeps() []string {
Spandan Das8aac9932024-07-18 23:14:13 +00002180 return j.compileDepNames
Jaewoong Jung26342642021-03-17 15:56:23 -07002181}
2182
2183func (j *Module) hasCode(ctx android.ModuleContext) bool {
2184 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2185 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2186}
2187
2188// Implements android.ApexModule
2189func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2190 return j.depIsInSameApex(ctx, dep)
2191}
2192
2193// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002194func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002195 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002196 minSdkVersion := j.MinSdkVersion(ctx)
2197 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002198 return fmt.Errorf("min_sdk_version is not specified")
2199 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002200 // If the module is compiling against core (via sdk_version), skip comparison check.
2201 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002202 return nil
2203 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002204 if minSdkVersion.GreaterThan(sdkVersion) {
2205 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002206 }
2207 return nil
2208}
2209
2210func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002211 if j.stem == "" {
2212 panic("Stem() called before stem property was set")
2213 }
2214 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002215}
2216
Jaewoong Jung26342642021-03-17 15:56:23 -07002217func (j *Module) JacocoReportClassesFile() android.Path {
2218 return j.jacocoReportClassesFile
2219}
2220
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002221func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2222 var fromDeps []*android.DepSet[android.Path]
2223 ctx.VisitDirectDeps(func(module android.Module) {
2224 tag := ctx.OtherModuleDependencyTag(module)
2225 if tag == staticLibTag {
Colin Cross7727c7f2024-07-18 15:36:32 -07002226 if depInfo, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2227 if depInfo.TransitiveSrcFiles != nil {
2228 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2229 }
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002230 }
2231 }
2232 })
2233
2234 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2235}
2236
Jaewoong Jung26342642021-03-17 15:56:23 -07002237func (j *Module) IsInstallable() bool {
2238 return Bool(j.properties.Installable)
2239}
2240
2241type sdkLinkType int
2242
2243const (
2244 // TODO(jiyong) rename these for better readability. Make the allowed
2245 // and disallowed link types explicit
2246 // order is important here. See rank()
2247 javaCore sdkLinkType = iota
2248 javaSdk
2249 javaSystem
2250 javaModule
2251 javaSystemServer
2252 javaPlatform
2253)
2254
2255func (lt sdkLinkType) String() string {
2256 switch lt {
2257 case javaCore:
2258 return "core Java API"
2259 case javaSdk:
2260 return "Android API"
2261 case javaSystem:
2262 return "system API"
2263 case javaModule:
2264 return "module API"
2265 case javaSystemServer:
2266 return "system server API"
2267 case javaPlatform:
2268 return "private API"
2269 default:
2270 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2271 }
2272}
2273
2274// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2275// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2276// can't statically depend on modules that use Platform API.
2277func (lt sdkLinkType) rank() int {
2278 return int(lt)
2279}
2280
2281type moduleWithSdkDep interface {
2282 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002283 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002284}
2285
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002286func sdkLinkTypeFromSdkKind(k android.SdkKind) sdkLinkType {
2287 switch k {
2288 case android.SdkCore:
2289 return javaCore
2290 case android.SdkSystem:
2291 return javaSystem
2292 case android.SdkPublic:
2293 return javaSdk
2294 case android.SdkModule:
2295 return javaModule
2296 case android.SdkSystemServer:
2297 return javaSystemServer
2298 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
2299 return javaPlatform
2300 default:
2301 return javaSdk
2302 }
2303}
2304
Jiyong Park92315372021-04-02 08:45:46 +09002305func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002306 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002307 case android.SdkCore.DefaultJavaLibraryName(),
2308 "legacy.core.platform.api.stubs",
2309 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002310 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002311 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002312 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002313 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002314 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002315 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002316 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002317 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002318 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002319 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002320 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002321 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002322 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002323 return javaSystem, true
2324 }
2325
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002326 if stub, linkType := moduleStubLinkType(m); stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07002327 return linkType, true
2328 }
2329
Jiyong Park92315372021-04-02 08:45:46 +09002330 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002331 if !ver.Valid() {
2332 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002333 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002334
2335 return sdkLinkTypeFromSdkKind(ver.Kind), false
Jaewoong Jung26342642021-03-17 15:56:23 -07002336}
2337
2338// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2339// this module's. See the comment on rank() for details and an example.
2340func (j *Module) checkSdkLinkType(
2341 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2342 if ctx.Host() {
2343 return
2344 }
2345
Jiyong Park92315372021-04-02 08:45:46 +09002346 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002347 if stubs {
2348 return
2349 }
Jiyong Park92315372021-04-02 08:45:46 +09002350 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002351
2352 if myLinkType.rank() < depLinkType.rank() {
2353 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2354 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2355 "property of the source or target module so that target module is built "+
2356 "with the same or smaller API set when compared to the source.",
2357 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2358 }
2359}
2360
2361func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2362 var deps deps
2363
Jiyong Park92315372021-04-02 08:45:46 +09002364 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002365
Colin Cross9ffaf282024-08-12 13:50:09 -07002366 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002367
2368 var transitiveBootClasspathHeaderJars []*android.DepSet[android.Path]
2369 var transitiveClasspathHeaderJars []*android.DepSet[android.Path]
2370 var transitiveJava9ClasspathHeaderJars []*android.DepSet[android.Path]
2371 var transitiveStaticJarsHeaderLibs []*android.DepSet[android.Path]
2372 var transitiveStaticJarsImplementationLibs []*android.DepSet[android.Path]
2373 var transitiveStaticJarsResourceLibs []*android.DepSet[android.Path]
2374
Jaewoong Jung26342642021-03-17 15:56:23 -07002375 ctx.VisitDirectDeps(func(module android.Module) {
2376 otherName := ctx.OtherModuleName(module)
2377 tag := ctx.OtherModuleDependencyTag(module)
2378
2379 if IsJniDepTag(tag) {
2380 // Handled by AndroidApp.collectAppDeps
2381 return
2382 }
2383 if tag == certificateTag {
2384 // Handled by AndroidApp.collectAppDeps
2385 return
2386 }
2387
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002388 if sdkInfo, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -07002389 switch tag {
Jihoon Kang28c96572024-09-11 23:44:44 +00002390 case sdkLibTag, libTag, staticLibTag:
Jihoon Kang28c96572024-09-11 23:44:44 +00002391 generatingLibsString := android.PrettyConcat(
2392 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
2393 ctx.ModuleErrorf("cannot depend directly on java_sdk_library %q; try depending on %s instead", module.Name(), generatingLibsString)
Jaewoong Jung26342642021-03-17 15:56:23 -07002394 }
Colin Cross313aa542023-12-13 13:47:44 -08002395 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2396 if sdkLinkType != javaPlatform {
2397 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2398 // dep is a sysprop implementation library, but this module is not linking against
2399 // the platform, so it gets the sysprop public stubs library instead. Replace
2400 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2401 dep = syspropDep.JavaInfo
2402 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002403 }
2404 switch tag {
2405 case bootClasspathTag:
2406 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002407 if dep.TransitiveStaticLibsHeaderJars != nil {
2408 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2409 }
Liz Kammeref28a4c2022-09-23 16:50:56 -04002410 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002411 if _, ok := module.(*Plugin); ok {
2412 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2413 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002414 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002415 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002416 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2417 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2418 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2419 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002420 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2421 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2422 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002423
2424 if dep.TransitiveStaticLibsHeaderJars != nil {
2425 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2426 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002427 case java9LibTag:
2428 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002429 if dep.TransitiveStaticLibsHeaderJars != nil {
2430 transitiveJava9ClasspathHeaderJars = append(transitiveJava9ClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2431 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002432 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002433 if _, ok := module.(*Plugin); ok {
2434 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2435 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002436 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2437 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2438 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2439 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2440 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2441 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2442 // Turbine doesn't run annotation processors, so any module that uses an
2443 // annotation processor that generates API is incompatible with the turbine
2444 // optimization.
2445 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Jihoon Kang705e63e2024-03-13 01:21:16 +00002446 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.AconfigIntermediateCacheOutputPaths...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002447
2448 if dep.TransitiveStaticLibsHeaderJars != nil {
2449 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2450 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, dep.TransitiveStaticLibsHeaderJars)
2451 }
2452 if dep.TransitiveStaticLibsImplementationJars != nil {
2453 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, dep.TransitiveStaticLibsImplementationJars)
2454 }
2455 if dep.TransitiveStaticLibsResourceJars != nil {
2456 transitiveStaticJarsResourceLibs = append(transitiveStaticJarsResourceLibs, dep.TransitiveStaticLibsResourceJars)
2457 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002458 case pluginTag:
2459 if plugin, ok := module.(*Plugin); ok {
2460 if plugin.pluginProperties.Processor_class != nil {
2461 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2462 } else {
2463 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2464 }
2465 // Turbine doesn't run annotation processors, so any module that uses an
2466 // annotation processor that generates API is incompatible with the turbine
2467 // optimization.
2468 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2469 } else {
2470 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2471 }
2472 case errorpronePluginTag:
2473 if _, ok := module.(*Plugin); ok {
2474 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2475 } else {
2476 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2477 }
2478 case exportedPluginTag:
2479 if plugin, ok := module.(*Plugin); ok {
2480 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2481 if plugin.pluginProperties.Processor_class != nil {
2482 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2483 }
2484 // Turbine doesn't run annotation processors, so any module that uses an
2485 // annotation processor that generates API is incompatible with the turbine
2486 // optimization.
2487 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2488 } else {
2489 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2490 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07002491 case kotlinPluginTag:
2492 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002493 case syspropPublicStubDepTag:
2494 // This is a sysprop implementation library, forward the JavaInfoProvider from
2495 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002496 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002497 JavaInfo: dep,
2498 })
2499 }
2500 } else if dep, ok := module.(android.SourceFileProducer); ok {
2501 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002502 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002503 checkProducesJars(ctx, dep)
2504 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002505 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002506 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars,
2507 android.NewDepSet(android.PREORDER, dep.Srcs(), nil))
Jaewoong Jung26342642021-03-17 15:56:23 -07002508 case staticLibTag:
2509 checkProducesJars(ctx, dep)
2510 deps.classpath = append(deps.classpath, dep.Srcs()...)
2511 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2512 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002513
2514 depHeaderJars := android.NewDepSet(android.PREORDER, dep.Srcs(), nil)
2515 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, depHeaderJars)
2516 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, depHeaderJars)
2517 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, depHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07002518 }
Jihoon Kang705e63e2024-03-13 01:21:16 +00002519 } else if dep, ok := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider); ok {
Jihoon Kang3921f0b2024-03-12 23:51:37 +00002520 switch tag {
2521 case staticLibTag:
2522 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.IntermediateCacheOutputPaths...)
2523 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002524 } else {
2525 switch tag {
2526 case bootClasspathTag:
2527 // If a system modules dependency has been added to the bootclasspath
2528 // then add its libs to the bootclasspath.
Colin Crossb61c2262024-08-08 14:04:42 -07002529 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002530 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars...)
2531 if sm.TransitiveStaticLibsHeaderJars != nil {
2532 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars,
2533 sm.TransitiveStaticLibsHeaderJars)
2534 }
Colin Crossb61c2262024-08-08 14:04:42 -07002535 } else {
2536 ctx.PropertyErrorf("boot classpath dependency %q does not provide SystemModulesProvider",
2537 ctx.OtherModuleName(module))
2538 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002539
2540 case systemModulesTag:
2541 if deps.systemModules != nil {
2542 panic("Found two system module dependencies")
2543 }
Colin Crossb61c2262024-08-08 14:04:42 -07002544 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
2545 deps.systemModules = &systemModules{sm.OutputDir, sm.OutputDirDeps}
2546 } else {
2547 ctx.PropertyErrorf("system modules dependency %q does not provide SystemModulesProvider",
2548 ctx.OtherModuleName(module))
2549 }
Paul Duffin53a70a42022-01-11 14:35:55 +00002550
2551 case instrumentationForTag:
2552 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 -07002553 }
2554 }
2555
Spandan Das8aac9932024-07-18 23:14:13 +00002556 if android.InList(tag, compileDependencyTags) {
2557 // Add the dependency name to compileDepNames so that it can be recorded in module_bp_java_deps.json
2558 j.compileDepNames = append(j.compileDepNames, otherName)
2559 }
2560
Jaewoong Jung26342642021-03-17 15:56:23 -07002561 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiakai Zhang36937082024-04-15 11:15:50 +00002562 addMissingOptionalUsesLibsFromDep(ctx, module, &j.usesLibrary)
Jaewoong Jung26342642021-03-17 15:56:23 -07002563 })
2564
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002565 deps.transitiveStaticLibsHeaderJars = transitiveStaticJarsHeaderLibs
2566 deps.transitiveStaticLibsImplementationJars = transitiveStaticJarsImplementationLibs
2567 deps.transitiveStaticLibsResourceJars = transitiveStaticJarsResourceLibs
2568
2569 if ctx.Config().UseTransitiveJarsInClasspath() {
2570 depSet := android.NewDepSet(android.PREORDER, nil, transitiveClasspathHeaderJars)
2571 deps.classpath = depSet.ToList()
2572 depSet = android.NewDepSet(android.PREORDER, nil, transitiveBootClasspathHeaderJars)
2573 deps.bootClasspath = depSet.ToList()
2574 depSet = android.NewDepSet(android.PREORDER, nil, transitiveJava9ClasspathHeaderJars)
2575 deps.java9Classpath = depSet.ToList()
2576 }
2577
2578 if ctx.Device() {
2579 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
2580 if sdkDep.invalidVersion {
2581 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2582 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2583 } else if sdkDep.useFiles {
2584 // sdkDep.jar is actually equivalent to turbine header.jar.
2585 deps.classpath = append(slices.Clone(classpath(sdkDep.jars)), deps.classpath...)
2586 deps.dexClasspath = append(slices.Clone(classpath(sdkDep.jars)), deps.dexClasspath...)
2587 deps.aidlPreprocess = sdkDep.aidl
2588 // Add the sdk module dependency to `compileDepNames`.
2589 // This ensures that the dependency is reported in `module_bp_java_deps.json`
2590 // TODO (b/358608607): Move this to decodeSdkDep
2591 sdkSpec := android.SdkContext(j).SdkVersion(ctx)
2592 j.compileDepNames = append(j.compileDepNames, fmt.Sprintf("sdk_%s_%s_android", sdkSpec.Kind.String(), sdkSpec.ApiLevel.String()))
2593 } else {
2594 deps.aidlPreprocess = sdkDep.aidl
2595 }
2596 }
2597
Jaewoong Jung26342642021-03-17 15:56:23 -07002598 return deps
2599}
2600
Joe Onorato349ae8d2024-02-05 22:46:00 +00002601// Provider for jarjar renaming rules.
2602//
2603// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2604// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2605// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2606// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2607// be renamed from that module.
2608// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002609type DependencyUse int
2610
2611const (
2612 RenameUseInvalid DependencyUse = iota
2613 RenameUseInclude
2614 RenameUseExclude
2615)
2616
2617type RenameUseElement struct {
2618 DepName string
2619 RenameUse DependencyUse
2620 Why string // token for determining where in the logic the decision was made.
2621}
2622
Joe Onorato349ae8d2024-02-05 22:46:00 +00002623type JarJarProviderData struct {
2624 // Mapping of class names: original --> renamed. If the value is "", the class will be
2625 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2626 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002627 Rename map[string]string
2628 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002629}
2630
2631func (this JarJarProviderData) GetDebugString() string {
2632 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002633 for _, k := range android.SortedKeys(this.Rename) {
2634 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002635 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2636 result += k + "--&gt;" + v + ";"
2637 }
2638 }
2639 return result
2640}
2641
2642var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2643
2644var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2645
2646func init() {
2647 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
Yu Liu26a716d2024-08-30 23:40:32 +00002648
2649 gob.Register(BaseJarJarProviderData{})
Joe Onorato349ae8d2024-02-05 22:46:00 +00002650}
2651
2652// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2653// whether they are java modules or not.
2654type BaseJarJarProviderData struct {
2655 JarJarProviderData JarJarProviderData
2656}
2657
2658func (this BaseJarJarProviderData) GetDebugString() string {
2659 return this.JarJarProviderData.GetDebugString()
2660}
2661
2662var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2663
2664// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2665// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2666// either JarJarProvider or BaseJarJarProvider.
2667func mergeJarJarPrefixes(ctx android.ModuleContext) {
2668 mod := ctx.Module()
2669 // Explicitly avoid propagating into some module types.
2670 switch reflect.TypeOf(mod).String() {
2671 case "*java.Droidstubs":
2672 return
2673 }
2674 jarJarData := collectDirectDepsProviders(ctx)
2675 if jarJarData != nil {
2676 providerData := BaseJarJarProviderData{
2677 JarJarProviderData: *jarJarData,
2678 }
2679 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2680 }
2681
2682}
2683
2684// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2685func (module *Module) addJarJarRenameRule(original string, renamed string) {
2686 if module.jarjarRenameRules == nil {
2687 module.jarjarRenameRules = make(map[string]string)
2688 }
2689 module.jarjarRenameRules[original] = renamed
2690}
2691
2692func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2693 // Gather repackage information from deps
2694 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002695
2696 module := ctx.Module()
2697 moduleName := module.Name()
2698
Colin Cross648daea2024-09-12 14:35:29 -07002699 ctx.VisitDirectDeps(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002700 tag := ctx.OtherModuleDependencyTag(m)
2701 // This logic mirrors that in (*Module).collectDeps above. There are several places
2702 // where we explicitly return RenameUseExclude, even though it is the default, to
2703 // indicate that it has been verified to be the case.
2704 //
2705 // Note well: there are probably cases that are getting to the unconditional return
2706 // and are therefore wrong.
2707 shouldIncludeRenames := func() (DependencyUse, string) {
2708 if moduleName == m.Name() {
2709 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2710 }
2711 if sc, ok := module.(android.SdkContext); ok {
2712 if ctx.Device() {
2713 sdkDep := decodeSdkDep(ctx, sc)
2714 if !sdkDep.invalidVersion && sdkDep.useFiles {
2715 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002716 }
2717 }
LaMont Jones63683e42024-02-08 14:30:45 -08002718 }
2719 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2720 return RenameUseExclude, "tags"
2721 }
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002722 if _, ok := android.OtherModuleProvider(ctx, m, SdkLibraryInfoProvider); ok {
LaMont Jones63683e42024-02-08 14:30:45 -08002723 switch tag {
2724 case sdkLibTag, libTag:
2725 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2726 }
2727 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2728 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2729 switch ji.StubsLinkType {
2730 case Stubs:
2731 return RenameUseExclude, "info"
2732 case Implementation:
2733 return RenameUseInclude, "info"
2734 default:
LaMont Jones09721862024-06-11 10:30:50 -07002735 //fmt.Printf("collectDirectDepsProviders: %v -> %v StubsLinkType unknown\n", module, m)
LaMont Jones63683e42024-02-08 14:30:45 -08002736 // Fall through to the heuristic logic.
2737 }
2738 switch reflect.TypeOf(m).String() {
2739 case "*java.GeneratedJavaLibraryModule":
2740 // Probably a java_aconfig_library module.
2741 // TODO: make this check better.
2742 return RenameUseInclude, "reflect"
2743 }
2744 switch tag {
2745 case bootClasspathTag:
2746 return RenameUseExclude, "tagswitch"
2747 case sdkLibTag, libTag, instrumentationForTag:
2748 return RenameUseInclude, "tagswitch"
2749 case java9LibTag:
2750 return RenameUseExclude, "tagswitch"
2751 case staticLibTag:
2752 return RenameUseInclude, "tagswitch"
2753 case pluginTag:
2754 return RenameUseInclude, "tagswitch"
2755 case errorpronePluginTag:
2756 return RenameUseInclude, "tagswitch"
2757 case exportedPluginTag:
2758 return RenameUseInclude, "tagswitch"
LaMont Jones63683e42024-02-08 14:30:45 -08002759 case kotlinPluginTag:
2760 return RenameUseInclude, "tagswitch"
2761 default:
2762 return RenameUseExclude, "tagswitch"
2763 }
2764 } else if _, ok := m.(android.SourceFileProducer); ok {
2765 switch tag {
2766 case sdkLibTag, libTag, staticLibTag:
2767 return RenameUseInclude, "srcfile"
2768 default:
2769 return RenameUseExclude, "srcfile"
2770 }
Yu Liu67a28422024-03-05 00:36:31 +00002771 } else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
Jihoon Kang03d014f2024-02-16 22:22:18 +00002772 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002773 } else {
2774 switch tag {
2775 case bootClasspathTag:
2776 return RenameUseExclude, "else"
2777 case systemModulesTag:
2778 return RenameUseInclude, "else"
2779 }
2780 }
2781 // If we got here, choose the safer option, which may lead to a build failure, rather
2782 // than runtime failures on the device.
2783 return RenameUseExclude, "end"
2784 }
2785
2786 if result == nil {
2787 result = &JarJarProviderData{
2788 Rename: make(map[string]string),
2789 RenameUse: make([]RenameUseElement, 0),
2790 }
2791 }
2792 how, why := shouldIncludeRenames()
2793 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2794 if how != RenameUseInclude {
2795 // Nothing to merge.
2796 return
2797 }
2798
2799 merge := func(theirs *JarJarProviderData) {
2800 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002801 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2802 result.Rename[orig] = renamed
2803 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2804 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2805 result.Rename[orig] = renamed
2806 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2807 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2808 continue
2809 }
2810 }
2811 }
2812 }
2813 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2814 merge(&theirs)
2815 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2816 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2817 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2818 // to java.Module.
2819 merge(&theirs.JarJarProviderData)
2820 }
2821 })
2822 return
2823}
2824
2825func (this Module) GetDebugString() string {
2826 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2827}
2828
2829// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2830// us, and if it's been set, apply the jarjar_prefix property to rename them.
2831func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2832 // Gather repackage information from deps
2833 result := collectDirectDepsProviders(ctx)
2834
Joe Onoratoa5d17172024-07-20 17:39:56 -07002835 add := func(orig string, renamed string) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002836 if result == nil {
2837 result = &JarJarProviderData{
2838 Rename: make(map[string]string),
2839 }
2840 }
2841 if renamed != "" {
2842 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2843 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
Joe Onoratoa5d17172024-07-20 17:39:56 -07002844 return
Joe Onorato349ae8d2024-02-05 22:46:00 +00002845 }
2846 }
2847 (*result).Rename[orig] = renamed
2848 }
2849
Joe Onoratoa5d17172024-07-20 17:39:56 -07002850 // Update that with entries we've stored for ourself
2851 for orig, renamed := range module.jarjarRenameRules {
2852 add(orig, renamed)
2853 }
2854
2855 // Update that with entries given in the jarjar_rename property.
2856 for _, orig := range module.properties.Jarjar_rename {
2857 add(orig, "")
2858 }
2859
Joe Onorato349ae8d2024-02-05 22:46:00 +00002860 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2861 if result == nil {
2862 return nil
2863 }
2864
2865 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2866 // that have not yet been renamed.
2867 prefix := proptools.String(module.properties.Jarjar_prefix)
2868 if prefix != "" {
2869 if prefix[0] == '.' {
2870 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2871 return nil
2872 }
2873 if prefix[len(prefix)-1] == '.' {
2874 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2875 return nil
2876 }
2877
2878 var updated map[string]string
2879 for orig, renamed := range (*result).Rename {
2880 if renamed == "" {
2881 if updated == nil {
2882 updated = make(map[string]string)
2883 }
2884 updated[orig] = prefix + "." + orig
2885 }
2886 }
2887 for orig, renamed := range updated {
2888 (*result).Rename[orig] = renamed
2889 }
2890 }
2891
2892 return result
2893}
2894
2895// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2896// to "" won't be in this list because they shouldn't be renamed yet.
2897func getJarJarRuleText(provider *JarJarProviderData) string {
2898 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002899 for _, orig := range android.SortedKeys(provider.Rename) {
2900 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002901 if renamed != "" {
2902 result += "rule " + orig + " " + renamed + "\n"
2903 }
2904 }
2905 return result
2906}
2907
Zi Wangddb2ee52024-04-02 16:44:02 +00002908// Repackage the flags if the jarjar rule txt for the flags is generated
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002909func (j *Module) repackageFlagsIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Zi Wangddb2ee52024-04-02 16:44:02 +00002910 if j.repackageJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002911 return infile, false
Zi Wangddb2ee52024-04-02 16:44:02 +00002912 }
Colin Crossedec77c2024-07-26 15:25:40 -07002913 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", info, jarName)
Zi Wangddb2ee52024-04-02 16:44:02 +00002914 TransformJarJar(ctx, repackagedJarjarFile, infile, j.repackageJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002915 return repackagedJarjarFile, true
Zi Wangddb2ee52024-04-02 16:44:02 +00002916}
2917
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002918func (j *Module) jarjarIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Colin Crossedec77c2024-07-26 15:25:40 -07002919 if j.expandJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002920 return infile, false
Colin Crossedec77c2024-07-26 15:25:40 -07002921 }
2922 jarjarFile := android.PathForModuleOut(ctx, "jarjar", info, jarName)
2923 TransformJarJar(ctx, jarjarFile, infile, j.expandJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002924 return jarjarFile, true
Colin Crossedec77c2024-07-26 15:25:40 -07002925
2926}
2927
Jaewoong Jung26342642021-03-17 15:56:23 -07002928func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2929 deps.processorPath = append(deps.processorPath, pluginJars...)
2930 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2931}
2932
2933// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2934// this interface.
2935type ProvidesUsesLib interface {
2936 ProvidesUsesLib() *string
2937}
2938
2939func (j *Module) ProvidesUsesLib() *string {
2940 return j.usesLibraryProperties.Provides_uses_lib
2941}
satayev1c564cc2021-05-25 19:50:30 +01002942
2943type ModuleWithStem interface {
2944 Stem() string
2945}
2946
2947var _ ModuleWithStem = (*Module)(nil)
Jiakai Zhangf98da192024-04-15 11:15:41 +00002948
2949type ModuleWithUsesLibrary interface {
2950 UsesLibrary() *usesLibrary
2951}
2952
2953func (j *Module) UsesLibrary() *usesLibrary {
2954 return &j.usesLibrary
2955}
2956
2957var _ ModuleWithUsesLibrary = (*Module)(nil)