blob: 0d05505614969cb52290ca03393f937b2c4fa6ce [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
Jihoon Kang381c2fa2023-06-01 22:17:32 +000086 // list of java libraries that should not be used to build this module
87 Exclude_static_libs []string `android:"arch_variant"`
88
Jaewoong Jung26342642021-03-17 15:56:23 -070089 // manifest file to be included in resulting jar
90 Manifest *string `android:"path"`
91
92 // if not blank, run jarjar using the specified rules file
93 Jarjar_rules *string `android:"path,arch_variant"`
94
Joe Onoratoa5d17172024-07-20 17:39:56 -070095 // java class names to rename with jarjar when a reverse dependency has a jarjar_prefix
96 // property.
97 Jarjar_rename []string
98
Joe Onorato349ae8d2024-02-05 22:46:00 +000099 // if not blank, used as prefix to generate repackage rule
100 Jarjar_prefix *string
101
Jaewoong Jung26342642021-03-17 15:56:23 -0700102 // If not blank, set the java version passed to javac as -source and -target
103 Java_version *string
104
105 // If set to true, allow this module to be dexed and installed on devices. Has no
106 // effect on host modules, which are always considered installable.
107 Installable *bool
108
109 // If set to true, include sources used to compile the module in to the final jar
110 Include_srcs *bool
111
112 // If not empty, classes are restricted to the specified packages and their sub-packages.
113 // This restriction is checked after applying jarjar rules and including static libs.
114 Permitted_packages []string
115
116 // List of modules to use as annotation processors
117 Plugins []string
118
119 // List of modules to export to libraries that directly depend on this library as annotation
120 // processors. Note that if the plugins set generates_api: true this will disable the turbine
121 // optimization on modules that depend on this module, which will reduce parallelism and cause
122 // more recompilation.
123 Exported_plugins []string
124
125 // The number of Java source entries each Javac instance can process
126 Javac_shard_size *int64
127
128 // Add host jdk tools.jar to bootclasspath
129 Use_tools_jar *bool
130
131 Openjdk9 struct {
132 // List of source files that should only be used when passing -source 1.9 or higher
133 Srcs []string `android:"path"`
134
135 // List of javac flags that should only be used when passing -source 1.9 or higher
136 Javacflags []string
137 }
138
139 // When compiling language level 9+ .java code in packages that are part of
140 // a system module, patch_module names the module that your sources and
141 // dependencies should be patched into. The Android runtime currently
142 // doesn't implement the JEP 261 module system so this option is only
143 // supported at compile time. It should only be needed to compile tests in
144 // packages that exist in libcore and which are inconvenient to move
145 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400146 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700147
148 Jacoco struct {
149 // List of classes to include for instrumentation with jacoco to collect coverage
150 // information at runtime when building with coverage enabled. If unset defaults to all
151 // classes.
152 // Supports '*' as the last character of an entry in the list as a wildcard match.
153 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
154 // it matches classes in the package that have the class name as a prefix.
155 Include_filter []string
156
157 // List of classes to exclude from instrumentation with jacoco to collect coverage
158 // information at runtime when building with coverage enabled. Overrides classes selected
159 // by the include_filter property.
160 // Supports '*' as the last character of an entry in the list as a wildcard match.
161 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
162 // it matches classes in the package that have the class name as a prefix.
163 Exclude_filter []string
164 }
165
166 Errorprone struct {
167 // List of javac flags that should only be used when running errorprone.
168 Javacflags []string
169
170 // List of java_plugin modules that provide extra errorprone checks.
171 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700172
Cole Faust2b1536e2021-06-18 12:25:54 -0700173 // This property can be in 3 states. When set to true, errorprone will
174 // be run during the regular build. When set to false, errorprone will
175 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
176 // environment variable is true. Setting this to false will improve build
177 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700178 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 }
180
181 Proto struct {
182 // List of extra options that will be passed to the proto generator.
183 Output_params []string
184 }
185
Sam Delmericoc7593722022-08-31 15:57:52 -0400186 // If true, then jacocoagent is automatically added as a libs dependency so that
187 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700188 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000189 // If true, then the module supports statically including the jacocoagent
190 // into the library.
191 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700192
193 // List of files to include in the META-INF/services folder of the resulting jar.
194 Services []string `android:"path,arch_variant"`
195
196 // If true, package the kotlin stdlib into the jar. Defaults to true.
197 Static_kotlin_stdlib *bool `android:"arch_variant"`
198
199 // A list of java_library instances that provide additional hiddenapi annotations for the library.
200 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700201
202 // Additional srcJars tacked in by GeneratedJavaLibraryModule
203 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000204
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000205 // intermediate aconfig cache file tacked in by GeneratedJavaLibraryModule
206 Aconfig_Cache_files []android.Path `android:"mutated"`
207
Mark Whitea15790a2023-08-22 21:28:11 +0000208 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400209 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800210
211 // A list of files or dependencies to make available to the build sandbox. This is
212 // useful if source files are symlinks, the targets of the symlinks must be listed here.
213 // Note that currently not all actions implemented by android_apps are sandboxed, so you
214 // may only see this being necessary in lint builds.
215 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000216
217 // Property signifying whether the module compiles stubs or not.
218 // Should be set to true when srcs of this module are stub files.
219 // This property does not need to be set to true when the module depends on
220 // the stubs via libs, but should be set to true when the module depends on
221 // the stubs via static libs.
222 Is_stubs_module *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700223
224 // If true, enable the "Ravenizer" tool on the output jar.
225 // "Ravenizer" is a tool for Ravenwood tests, but it can also be enabled on other kinds
226 // of java targets.
227 Ravenizer struct {
228 Enabled *bool
229 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +0000230
231 // Contributing api surface of the stub module. Is not visible to bp modules, and should
232 // only be set for stub submodules generated by the java_sdk_library
233 Stub_contributing_api *string `blueprint:"mutated"`
Yihan Dong8be09c22024-08-29 15:32:13 +0800234
235 // If true, enable the "ApiMapper" tool on the output jar. "ApiMapper" is a tool to inject
236 // bytecode to log API calls.
237 ApiMapper bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700238}
239
240// Properties that are specific to device modules. Host module factories should not add these when
241// constructing a new module.
242type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000243 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000244 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000245 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000246 // 1) numerical API level, "current", "none", or "core_platform"
247 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
248 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
249 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700250 Sdk_version *string
251
satayev0a420e72021-11-29 17:25:52 +0000252 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
253 // Defaults to empty string "". See sdk_version for possible values.
254 Max_sdk_version *string
255
William Loh5a082f92022-05-17 20:21:50 +0000256 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
257 // Defaults to empty string "". See sdk_version for possible values.
258 Replace_max_sdk_version_placeholder *string
259
Jaewoong Jung26342642021-03-17 15:56:23 -0700260 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000261 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700262 Target_sdk_version *string
263
264 // Whether to compile against the platform APIs instead of an SDK.
265 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000266 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700267 Platform_apis *bool
268
269 Aidl struct {
270 // Top level directories to pass to aidl tool
271 Include_dirs []string
272
273 // Directories rooted at the Android.bp file to pass to aidl tool
274 Local_include_dirs []string
275
276 // directories that should be added as include directories for any aidl sources of modules
277 // that depend on this module, as well as to aidl for this module.
278 Export_include_dirs []string
279
280 // whether to generate traces (for systrace) for this interface
281 Generate_traces *bool
282
283 // whether to generate Binder#GetTransaction name method.
284 Generate_get_transaction_name *bool
285
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100286 // whether all interfaces should be annotated with required permissions.
287 Enforce_permissions *bool
288
289 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
290 Enforce_permissions_exceptions []string `android:"path"`
291
Jaewoong Jung26342642021-03-17 15:56:23 -0700292 // list of flags that will be passed to the AIDL compiler
293 Flags []string
294 }
295
296 // If true, export a copy of the module as a -hostdex module for host testing.
297 Hostdex *bool
298
299 Target struct {
300 Hostdex struct {
301 // Additional required dependencies to add to -hostdex modules.
302 Required []string
303 }
304 }
305
306 // When targeting 1.9 and above, override the modules to use with --system,
307 // otherwise provides defaults libraries to add to the bootclasspath.
308 System_modules *string
309
Jaewoong Jung26342642021-03-17 15:56:23 -0700310 IsSDKLibrary bool `blueprint:"mutated"`
311
312 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
313 // Defaults to false.
314 V4_signature *bool
315
316 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
317 // public stubs library.
318 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000319
320 HiddenAPIPackageProperties
321 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700322}
323
yangbill2af0b6e2024-03-15 09:29:29 +0000324// Properties that can be overridden by overriding module (e.g. override_android_app)
325type OverridableProperties struct {
Jooyung Han01d80d82022-01-08 12:16:32 +0900326 // set the name of the output. If not set, `name` is used.
327 // To override a module with this property set, overriding module might need to set this as well.
328 // Otherwise, both the overridden and the overriding modules will have the same output name, which
329 // can cause the duplicate output error.
330 Stem *string
Spandan Dasb9c58352024-05-13 18:29:45 +0000331
332 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
333 // Defaults to sdk_version if not set. See sdk_version for possible values.
334 Min_sdk_version *string
Jooyung Han01d80d82022-01-08 12:16:32 +0900335}
336
Jaewoong Jung26342642021-03-17 15:56:23 -0700337// Functionality common to Module and Import
338//
339// It is embedded in Module so its functionality can be used by methods in Module
340// but it is currently only initialized by Import and Library.
341type embeddableInModuleAndImport struct {
342
343 // Functionality related to this being used as a component of a java_sdk_library.
344 EmbeddableSdkLibraryComponent
345}
346
Paul Duffin71b33cc2021-06-23 11:39:47 +0100347func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
348 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700349}
350
351// Module/Import's DepIsInSameApex(...) delegates to this method.
352//
353// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
354// the one provided by ApexModuleBase.
355func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
356 // dependencies other than the static linkage are all considered crossing APEX boundary
357 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
358 return true
359 }
360 return false
361}
362
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100363// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
364// or an invalid path describing the reason it is invalid.
365//
366// It is unset if a dex jar isn't applicable, i.e. no build rule has been
367// requested to create one.
368//
369// If a dex jar has been requested to be built then it is set, and it may be
370// either a valid android.Path, or invalid with a reason message. The latter
371// happens if the source that should produce the dex file isn't able to.
372//
373// E.g. it is invalid with a reason message if there is a prebuilt APEX that
374// could produce the dex jar through a deapexer module, but the APEX isn't
375// installable so doing so wouldn't be safe.
376type OptionalDexJarPath struct {
377 isSet bool
378 path android.OptionalPath
379}
380
381// IsSet returns true if a path has been set, either invalid or valid.
382func (o OptionalDexJarPath) IsSet() bool {
383 return o.isSet
384}
385
386// Valid returns true if there is a path that is valid.
387func (o OptionalDexJarPath) Valid() bool {
388 return o.isSet && o.path.Valid()
389}
390
391// Path returns the valid path, or panics if it's either not set or is invalid.
392func (o OptionalDexJarPath) Path() android.Path {
393 if !o.isSet {
394 panic("path isn't set")
395 }
396 return o.path.Path()
397}
398
399// PathOrNil returns the path if it's set and valid, or else nil.
400func (o OptionalDexJarPath) PathOrNil() android.Path {
401 if o.Valid() {
402 return o.Path()
403 }
404 return nil
405}
406
407// InvalidReason returns the reason for an invalid path, which is never "". It
408// returns "" for an unset or valid path.
409func (o OptionalDexJarPath) InvalidReason() string {
410 if !o.isSet {
411 return ""
412 }
413 return o.path.InvalidReason()
414}
415
416func (o OptionalDexJarPath) String() string {
417 if !o.isSet {
418 return "<unset>"
419 }
420 return o.path.String()
421}
422
423// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
424func makeUnsetDexJarPath() OptionalDexJarPath {
425 return OptionalDexJarPath{isSet: false}
426}
427
428// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
429// the given OptionalPath, which may be valid or invalid.
430func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
431 return OptionalDexJarPath{isSet: true, path: path}
432}
433
434// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
435// valid given path. It returns an unset OptionalDexJarPath if the given path is
436// nil.
437func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
438 if path == nil {
439 return makeUnsetDexJarPath()
440 }
441 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
442}
443
Jaewoong Jung26342642021-03-17 15:56:23 -0700444// Module contains the properties and members used by all java module types
445type Module struct {
446 android.ModuleBase
447 android.DefaultableModuleBase
448 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700449
450 // Functionality common to Module and Import.
451 embeddableInModuleAndImport
452
453 properties CommonProperties
454 protoProperties android.ProtoProperties
455 deviceProperties DeviceProperties
456
yangbill2af0b6e2024-03-15 09:29:29 +0000457 overridableProperties OverridableProperties
Ronald Braunsteincdc66f42024-04-12 11:23:19 -0700458 sourceProperties android.SourceProperties
Jooyung Han01d80d82022-01-08 12:16:32 +0900459
Jaewoong Jung26342642021-03-17 15:56:23 -0700460 // jar file containing header classes including static library dependencies, suitable for
461 // inserting into the bootclasspath/classpath of another compile
462 headerJarFile android.Path
463
464 // jar file containing implementation classes including static library dependencies but no
465 // resources
466 implementationJarFile android.Path
467
Jaewoong Jung26342642021-03-17 15:56:23 -0700468 // args and dependencies to package source files into a srcjar
469 srcJarArgs []string
470 srcJarDeps android.Paths
471
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000472 // the source files of this module and all its static dependencies
473 transitiveSrcFiles *android.DepSet[android.Path]
474
Jaewoong Jung26342642021-03-17 15:56:23 -0700475 // jar file containing implementation classes and resources including static library
476 // dependencies
477 implementationAndResourcesJar android.Path
478
479 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100480 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700481
482 // output file containing uninstrumented classes that will be instrumented by jacoco
483 jacocoReportClassesFile android.Path
484
485 // output file of the module, which may be a classes jar or a dex jar
486 outputFile android.Path
487 extraOutputFiles android.Paths
488
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100489 exportAidlIncludeDirs android.Paths
490 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700491
492 logtagsSrcs android.Paths
493
494 // installed file for binary dependency
495 installFile android.Path
496
Colin Cross3108ce12021-11-10 14:38:50 -0800497 // installed file for hostdex copy
498 hostdexInstallFile android.InstallPath
499
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800500 // list of unique .java and .kt source files
501 uniqueSrcFiles android.Paths
502
503 // list of srcjars that was passed to javac
504 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700505
506 // manifest file to use instead of properties.Manifest
507 overrideManifest android.OptionalPath
508
Jaewoong Jung26342642021-03-17 15:56:23 -0700509 // list of plugins that this java module is exporting
510 exportedPluginJars android.Paths
511
512 // list of plugins that this java module is exporting
513 exportedPluginClasses []string
514
515 // if true, the exported plugins generate API and require disabling turbine.
516 exportedDisableTurbine bool
517
518 // list of source files, collected from srcFiles with unique java and all kt files,
519 // will be used by android.IDEInfo struct
520 expandIDEInfoCompiledSrcs []string
521
522 // expanded Jarjar_rules
523 expandJarjarRules android.Path
524
Joe Onorato349ae8d2024-02-05 22:46:00 +0000525 // jarjar rule for inherited jarjar rules
526 repackageJarjarRules android.Path
527
Jaewoong Jung26342642021-03-17 15:56:23 -0700528 // Extra files generated by the module type to be added as java resources.
529 extraResources android.Paths
530
531 hiddenAPI
532 dexer
533 dexpreopter
534 usesLibrary
535 linter
536
537 // list of the xref extraction files
Spandan Das1028d5a2024-08-19 21:45:48 +0000538 kytheFiles android.Paths
539 kytheKotlinFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700540
Jaewoong Jung26342642021-03-17 15:56:23 -0700541 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900542
543 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000544 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000545 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400546
547 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000548
549 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000550
551 // output file name based on Stem property.
552 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
553 // or the module should override Stem().
554 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700555
Joe Onorato349ae8d2024-02-05 22:46:00 +0000556 // Values that will be set in the JarJarProvider data for jarjar repackaging,
557 // and merged with our dependencies' rules.
558 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000559
560 stubsLinkType StubsLinkType
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000561
562 // Paths to the aconfig intermediate cache files that are provided by the
563 // java_aconfig_library or java_library modules that are statically linked
564 // to this module. Does not contain cache files from all transitive dependencies.
565 aconfigCacheFiles android.Paths
Spandan Das8aac9932024-07-18 23:14:13 +0000566
567 // List of soong module dependencies required to compile the current module.
568 // This information is printed out to `Dependencies` field in module_bp_java_deps.json
569 compileDepNames []string
Makoto Onuki7ded3822024-03-28 14:42:20 -0700570
571 ravenizer struct {
572 enabled bool
573 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700574}
575
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000576var _ android.InstallableModule = (*Module)(nil)
577
578// To satisfy the InstallableModule interface
Jihoon Kang224ea082024-08-12 22:38:16 +0000579func (j *Module) StaticDependencyTags() []blueprint.DependencyTag {
580 return []blueprint.DependencyTag{staticLibTag}
581}
582
583// To satisfy the InstallableModule interface
584func (j *Module) DynamicDependencyTags() []blueprint.DependencyTag {
585 return []blueprint.DependencyTag{libTag, sdkLibTag, bootClasspathTag, systemModulesTag,
586 instrumentationForTag, java9LibTag}
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000587}
588
589// Overrides android.ModuleBase.InstallInProduct()
590func (j *Module) InstallInProduct() bool {
591 return j.ProductSpecific()
592}
593
Jihoon Kang85bc1932024-07-01 17:04:46 +0000594var _ android.StubsAvailableModule = (*Module)(nil)
595
596// To safisfy the StubsAvailableModule interface
597func (j *Module) IsStubsModule() bool {
598 return proptools.Bool(j.properties.Is_stubs_module)
599}
600
Jiyong Park92315372021-04-02 08:45:46 +0900601func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
602 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900603 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700604 return nil
605 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900606 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000607 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700608 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
609 } else {
610 // Treat stable core platform as stable.
611 return nil
612 }
613 } else {
614 return fmt.Errorf("non stable SDK %v", sdkVersion)
615 }
616}
617
618// checkSdkVersions enforces restrictions around SDK dependencies.
619func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
620 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900621 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900622 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700623 ctx.PropertyErrorf("sdk_version",
624 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
625 }
626 }
627 }
628
629 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
630 // See rank() for details.
631 ctx.VisitDirectDeps(func(module android.Module) {
632 tag := ctx.OtherModuleDependencyTag(module)
633 switch module.(type) {
634 // TODO(satayev): cover other types as well, e.g. imports
635 case *Library, *AndroidLibrary:
636 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400637 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700638 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
639 }
640 }
641 })
642}
643
644func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900645 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700646 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900647 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700648 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000649 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 -0700650 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000651 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 -0700652 }
653
654 }
655}
656
Mark Whitea15790a2023-08-22 21:28:11 +0000657func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
658 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400659 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000660 installable := proptools.Bool(j.properties.Installable)
661
662 if headersOnly && installable {
663 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.")
664 }
665 }
666}
667
Jaewoong Jung26342642021-03-17 15:56:23 -0700668func (j *Module) addHostProperties() {
669 j.AddProperties(
670 &j.properties,
yangbill2af0b6e2024-03-15 09:29:29 +0000671 &j.overridableProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700672 &j.protoProperties,
673 &j.usesLibraryProperties,
674 )
675}
676
677func (j *Module) addHostAndDeviceProperties() {
678 j.addHostProperties()
679 j.AddProperties(
680 &j.deviceProperties,
681 &j.dexer.dexProperties,
682 &j.dexpreoptProperties,
683 &j.linter.properties,
684 )
685}
686
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000687// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
688// makes it available through the hiddenAPIPropertyInfoProvider.
689func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
690 hiddenAPIInfo := newHiddenAPIPropertyInfo()
691
692 // Populate with flag file paths from the properties.
693 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
694
695 // Populate with package rules from the properties.
696 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
697
Colin Cross40213022023-12-13 15:19:49 -0800698 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000699}
700
mrziwang9f7b9f42024-07-10 12:18:06 -0700701// helper method for java modules to set OutputFilesProvider
702func setOutputFiles(ctx android.ModuleContext, m Module) {
703 ctx.SetOutputFiles(append(android.Paths{m.outputFile}, m.extraOutputFiles...), "")
704 ctx.SetOutputFiles(android.Paths{m.outputFile}, android.DefaultDistTag)
705 ctx.SetOutputFiles(android.Paths{m.implementationAndResourcesJar}, ".jar")
706 ctx.SetOutputFiles(android.Paths{m.headerJarFile}, ".hjar")
707 if m.dexer.proguardDictionary.Valid() {
708 ctx.SetOutputFiles(android.Paths{m.dexer.proguardDictionary.Path()}, ".proguard_map")
709 }
710 ctx.SetOutputFiles(m.properties.Generated_srcjars, ".generated_srcjars")
Jaewoong Jung26342642021-03-17 15:56:23 -0700711}
712
Jaewoong Jung26342642021-03-17 15:56:23 -0700713func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
714 initJavaModule(module, hod, false)
715}
716
717func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
718 initJavaModule(module, hod, true)
719}
720
721func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
722 multilib := android.MultilibCommon
723 if multiTargets {
724 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
725 } else {
726 android.InitAndroidArchModule(module, hod, multilib)
727 }
728 android.InitDefaultableModule(module)
729}
730
731func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
732 return j.properties.Instrument &&
733 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
734 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
735}
736
Yihan Dong8be09c22024-08-29 15:32:13 +0800737func (j *Module) shouldApiMapper() bool {
738 return j.properties.ApiMapper
739}
740
Jaewoong Jung26342642021-03-17 15:56:23 -0700741func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000742 return j.properties.Supports_static_instrumentation &&
743 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700744 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
745 ctx.Config().UnbundledBuild())
746}
747
748func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
749 // Force enable the instrumentation for java code that is built for APEXes ...
750 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
751 // 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 -0800752 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700753 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
Jihoon Kang690df2e2024-05-22 04:27:38 +0000754
Jihoon Kang46d66de2024-05-22 22:42:39 +0000755 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700756 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
757 return true
758 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
759 return true
760 }
761 }
762 return false
763}
764
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400765func (j *Module) setInstrument(value bool) {
766 j.properties.Instrument = value
767}
768
Yihan Dong8be09c22024-08-29 15:32:13 +0800769func (j *Module) setApiMapper(value bool) {
770 j.properties.ApiMapper = value
771}
772
Jiyong Park92315372021-04-02 08:45:46 +0900773func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
774 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700775}
776
Jiyong Parkf1691d22021-03-29 20:11:58 +0900777func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700778 return proptools.String(j.deviceProperties.System_modules)
779}
780
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000781func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Spandan Dasb9c58352024-05-13 18:29:45 +0000782 if j.overridableProperties.Min_sdk_version != nil {
783 return android.ApiLevelFrom(ctx, *j.overridableProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700784 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000785 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700786}
787
Yu Liuf2b94012023-09-19 15:09:10 -0700788func (j *Module) GetDeviceProperties() *DeviceProperties {
789 return &j.deviceProperties
790}
791
Spandan Dasa26eda72023-03-02 00:56:06 +0000792func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
793 if j.deviceProperties.Max_sdk_version != nil {
794 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
795 }
796 // Default is PrivateApiLevel
797 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000798}
799
Spandan Dasa26eda72023-03-02 00:56:06 +0000800func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
801 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
802 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
803 }
804 // Default is PrivateApiLevel
805 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000806}
807
Jiyong Parkf1691d22021-03-29 20:11:58 +0900808func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000809 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900810}
811
Spandan Dasca70fc42023-03-01 23:38:49 +0000812func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900813 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000814 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900815 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000816 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700817}
818
819func (j *Module) AvailableFor(what string) bool {
820 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
821 // Exception: for hostdex: true libraries, the platform variant is created
822 // even if it's not marked as available to platform. In that case, the platform
823 // variant is used only for the hostdex and not installed to the device.
824 return true
825 }
826 return j.ApexModuleBase.AvailableFor(what)
827}
828
Cole Faustb7493472024-08-28 11:55:52 -0700829func (j *Module) staticLibs(ctx android.BaseModuleContext) []string {
830 return android.RemoveListFromList(j.properties.Static_libs.GetOrDefault(ctx, nil), j.properties.Exclude_static_libs)
831}
832
Jaewoong Jung26342642021-03-17 15:56:23 -0700833func (j *Module) deps(ctx android.BottomUpMutatorContext) {
834 if ctx.Device() {
835 j.linter.deps(ctx)
836
Jiyong Parkf1691d22021-03-29 20:11:58 +0900837 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700838
839 if j.deviceProperties.SyspropPublicStub != "" {
840 // This is a sysprop implementation library that has a corresponding sysprop public
841 // stubs library, and a dependency on it so that dependencies on the implementation can
842 // be forwarded to the public stubs library when necessary.
843 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
844 }
845 }
846
847 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000848
Cole Faustb7493472024-08-28 11:55:52 -0700849 ctx.AddVariationDependencies(nil, staticLibTag, j.staticLibs(ctx)...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700850
851 // Add dependency on libraries that provide additional hidden api annotations.
852 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
853
Jaewoong Jung26342642021-03-17 15:56:23 -0700854 // For library dependencies that are component libraries (like stubs), add the implementation
855 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
856 for _, dep := range libDeps {
857 if dep != nil {
858 if component, ok := dep.(SdkLibraryComponentDependency); ok {
859 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +0000860 // Add library as optional if it's one of the optional compatibility libs or it's
861 // explicitly listed in the optional_uses_libs property.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100862 tag := usesLibReqTag
Jiakai Zhangf98da192024-04-15 11:15:41 +0000863 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) ||
864 android.InList(*lib, j.usesLibrary.usesLibraryProperties.Optional_uses_libs) {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100865 tag = usesLibOptTag
866 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100867 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700868 }
869 }
870 }
871 }
872
873 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
874 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
875 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
876
877 android.ProtoDeps(ctx, &j.protoProperties)
878 if j.hasSrcExt(".proto") {
879 protoDeps(ctx, &j.protoProperties)
880 }
881
882 if j.hasSrcExt(".kt") {
883 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
884 // Kotlin files
Colin Cross882d6002024-08-14 10:24:06 -0700885 tag := staticLibTag
886 if !BoolDefault(j.properties.Static_kotlin_stdlib, true) {
887 tag = libTag
888 }
889 ctx.AddVariationDependencies(nil, tag,
890 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700891 }
892
893 // Framework libraries need special handling in static coverage builds: they should not have
894 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
895 // the same jacoco classes coming from different bootclasspath jars.
896 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
897 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
898 j.properties.Instrument = true
899 }
900 } else if j.shouldInstrumentStatic(ctx) {
901 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
902 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700903
Cole Faustb7493472024-08-28 11:55:52 -0700904 if j.useCompose(ctx) {
Colin Crossa1ff7c62021-09-17 14:11:52 -0700905 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
906 "androidx.compose.compiler_compiler-hosted")
907 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700908}
909
910func hasSrcExt(srcs []string, ext string) bool {
911 for _, src := range srcs {
912 if filepath.Ext(src) == ext {
913 return true
914 }
915 }
916
917 return false
918}
919
920func (j *Module) hasSrcExt(ext string) bool {
921 return hasSrcExt(j.properties.Srcs, ext)
922}
923
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100924func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
925 var flags string
926
927 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
928 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
929 flags = "-Wmissing-permission-annotation -Werror"
930 }
931 }
932 return flags
933}
934
Jaewoong Jung26342642021-03-17 15:56:23 -0700935func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000936 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700937
938 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
939 aidlIncludes = append(aidlIncludes,
940 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
941 aidlIncludes = append(aidlIncludes,
942 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
943
944 var flags []string
945 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000946 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700947
948 flags = append(flags, j.deviceProperties.Aidl.Flags...)
949
950 if aidlPreprocess.Valid() {
951 flags = append(flags, "-p"+aidlPreprocess.String())
952 deps = append(deps, aidlPreprocess.Path())
953 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000954 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700955 }
956
957 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000958 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700959 }
960
961 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000962 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700963 }
964
Sam Delmerico2351eac2022-05-24 17:10:02 +0000965 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700966 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000967 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700968 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000969 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
970 // add flags for dirs containing AIDL srcs that haven't been specified yet
971 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700972
Zim8774ae12022-08-17 11:46:34 +0100973 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000974 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100975 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700976 flags = append(flags, "-t")
977 }
978
979 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
980 flags = append(flags, "--transaction_names")
981 }
982
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100983 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
984 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
985 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
986 }
987
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000988 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900989 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
990
Jaewoong Jung26342642021-03-17 15:56:23 -0700991 return strings.Join(flags, " "), deps
992}
993
994func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
995
996 var flags javaBuilderFlags
997
998 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900999 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001000
Cole Faust2b1536e2021-06-18 12:25:54 -07001001 epEnabled := j.properties.Errorprone.Enabled
1002 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +01001003 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001004 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
1005 }
1006
1007 errorProneFlags := []string{
1008 "-Xplugin:ErrorProne",
1009 "${config.ErrorProneChecks}",
1010 }
1011 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
1012
Colin Cross8bf6cad2022-02-28 13:07:03 -08001013 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -07001014 "'" + strings.Join(errorProneFlags, " ") + "'"
1015 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
1016 }
1017
1018 // classpath
1019 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
1020 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001021 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001022 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
1023 flags.processorPath = append(flags.processorPath, deps.processorPath...)
1024 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
1025
1026 flags.processors = append(flags.processors, deps.processorClasses...)
1027 flags.processors = android.FirstUniqueStrings(flags.processors)
1028
1029 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001030 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001031 // Give host-side tools a version of OpenJDK's standard libraries
1032 // close to what they're targeting. As of Dec 2017, AOSP is only
1033 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1034 //
1035 // When building with OpenJDK 8, the following should have no
1036 // effect since those jars would be available by default.
1037 //
1038 // When building with OpenJDK 9 but targeting a version < 1.8,
1039 // putting them on the bootclasspath means that:
1040 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1041 // b) references to existing APIs are not reinterpreted in an
1042 // OpenJDK 9-specific way, eg. calls to subclasses of
1043 // java.nio.Buffer as in http://b/70862583
1044 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1045 flags.bootClasspath = append(flags.bootClasspath,
1046 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1047 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1048 if Bool(j.properties.Use_tools_jar) {
1049 flags.bootClasspath = append(flags.bootClasspath,
1050 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1051 }
1052 }
1053
1054 // systemModules
1055 flags.systemModules = deps.systemModules
1056
Jaewoong Jung26342642021-03-17 15:56:23 -07001057 return flags
1058}
1059
1060func (j *Module) collectJavacFlags(
1061 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1062 // javac flags.
1063 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001064 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001065
Mythri Alle4b9f6182023-10-25 15:17:11 +00001066 needsDebugInfo = false
1067 for _, flag := range javacFlags {
1068 if strings.HasPrefix(flag, "-g") {
1069 needsDebugInfo = true
1070 }
1071 }
1072
1073 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001074 // For non-host binaries, override the -g flag passed globally to remove
1075 // local variable debug info to reduce disk and memory usage.
1076 javacFlags = append(javacFlags, "-g:source,lines")
1077 }
1078 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1079
1080 if flags.javaVersion.usesJavaModules() {
1081 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001082 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1083 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1084 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1085 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001086
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001087 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001088 if j.properties.Patch_module != nil {
1089 // Manually specify build directory in case it is not under the repo root.
1090 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1091 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001092 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001093
Jaewoong Jung26342642021-03-17 15:56:23 -07001094 classPath := flags.classpath.FormJavaClassPath("")
1095 if classPath != "" {
1096 patchPaths = append(patchPaths, classPath)
1097 }
1098 javacFlags = append(
1099 javacFlags,
1100 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1101 }
1102 }
1103
1104 if len(javacFlags) > 0 {
1105 // optimization.
1106 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1107 flags.javacFlags = "$javacFlags"
1108 }
1109
1110 return flags
1111}
1112
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001113func (j *Module) AddJSONData(d *map[string]interface{}) {
1114 (&j.ModuleBase).AddJSONData(d)
1115 (*d)["Java"] = map[string]interface{}{
1116 "SourceExtensions": j.sourceExtensions,
1117 }
1118
1119}
1120
usta0391ca42023-09-19 15:51:59 -04001121func (j *Module) addGeneratedSrcJars(path android.Path) {
1122 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001123}
1124
Colin Crossfdaa6722024-08-23 11:58:08 -07001125func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars, extraDepCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001126 // Auto-propagating jarjar rules
1127 jarjarProviderData := j.collectJarJarRules(ctx)
1128 if jarjarProviderData != nil {
1129 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
Zi Wangddb2ee52024-04-02 16:44:02 +00001130 text := getJarJarRuleText(jarjarProviderData)
1131 if text != "" {
1132 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1133 android.WriteFileRule(ctx, ruleTextFile, text)
1134 j.repackageJarjarRules = ruleTextFile
Joe Onorato349ae8d2024-02-05 22:46:00 +00001135 }
1136 }
1137
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1139
Makoto Onuki7ded3822024-03-28 14:42:20 -07001140 if re := proptools.Bool(j.properties.Ravenizer.Enabled); re {
1141 j.ravenizer.enabled = re
1142 }
1143
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 deps := j.collectDeps(ctx)
1145 flags := j.collectBuilderFlags(ctx, deps)
1146
1147 if flags.javaVersion.usesJavaModules() {
1148 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001149 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1150 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1151 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001153
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001155 j.sourceExtensions = []string{}
1156 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1157 if hasSrcExt(srcFiles.Strings(), ext) {
1158 j.sourceExtensions = append(j.sourceExtensions, ext)
1159 }
1160 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001161 if hasSrcExt(srcFiles.Strings(), ".proto") {
1162 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1163 }
1164
1165 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1166 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1167 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1168 }
1169
Sam Delmerico2351eac2022-05-24 17:10:02 +00001170 aidlSrcs := srcFiles.FilterByExt(".aidl")
1171 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1172
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001173 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001174 srcFiles = j.genSources(ctx, srcFiles, flags)
1175
1176 // Collect javac flags only after computing the full set of srcFiles to
1177 // ensure that the --patch-module lookup paths are complete.
1178 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1179
1180 srcJars := srcFiles.FilterByExt(".srcjar")
1181 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001182 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001183 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001184 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001185
1186 if j.properties.Jarjar_rules != nil {
1187 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1188 }
1189
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001190 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001191
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001192 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001194 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001195 if _, found := set[v.String()]; !found {
1196 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001197 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001198 }
1199 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001200 var uniqueKtFiles android.Paths
1201 for _, v := range srcFiles.FilterByExt(".kt") {
1202 if _, found := set[v.String()]; !found {
1203 set[v.String()] = true
1204 uniqueKtFiles = append(uniqueKtFiles, v)
1205 }
1206 }
1207
1208 var uniqueSrcFiles android.Paths
1209 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1210 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1211 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001212 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001213
Colin Crossb5db4012022-03-28 17:12:39 -07001214 // We don't currently run annotation processors in turbine, which means we can't use turbine
1215 // generated header jars when an annotation processor that generates API is enabled. One
1216 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1217 // is used to run all of the annotation processors.
1218 disableTurbine := deps.disableTurbine
1219
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001220 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001221 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1222
Colin Cross220a9a12022-03-28 17:08:01 -07001223 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001224
Colin Cross4eae06d2023-06-20 22:40:02 -07001225 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1226 // any dependencies so that it can override any non-final R classes from dependencies with the
1227 // final R classes from the app.
1228 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1229
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001230 j.aconfigCacheFiles = append(deps.aconfigProtoFiles, j.properties.Aconfig_Cache_files...)
1231
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001232 var localImplementationJars android.Paths
1233
Mark Whitea15790a2023-08-22 21:28:11 +00001234 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001235 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001236 if srcFiles.HasExt(".kt") {
1237 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1238 }
1239 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1240 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1241 }
1242
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001243 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1244
1245 localHeaderJars, combinedHeaderJarFile := j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
Colin Crossedec77c2024-07-26 15:25:40 -07001246 extraCombinedJars)
1247
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001248 combinedHeaderJarFile, jarjared := j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1249 if jarjared {
1250 localHeaderJars = android.Paths{combinedHeaderJarFile}
1251 transitiveStaticLibsHeaderJars = nil
1252 }
1253 combinedHeaderJarFile, repackaged := j.repackageFlagsIfNecessary(ctx, combinedHeaderJarFile, jarName, "repackage-turbine")
1254 if repackaged {
1255 localHeaderJars = android.Paths{combinedHeaderJarFile}
1256 transitiveStaticLibsHeaderJars = nil
1257 }
Mark Whitea15790a2023-08-22 21:28:11 +00001258 if ctx.Failed() {
1259 return
1260 }
Colin Crossedec77c2024-07-26 15:25:40 -07001261 j.headerJarFile = combinedHeaderJarFile
Mark Whitea15790a2023-08-22 21:28:11 +00001262
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001263 if ctx.Config().UseTransitiveJarsInClasspath() {
1264 if len(localHeaderJars) > 0 {
1265 ctx.CheckbuildFile(localHeaderJars...)
1266 } else {
1267 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1268 ctx.UncheckedModule()
1269 }
1270 } else {
1271 ctx.CheckbuildFile(j.headerJarFile)
1272 }
Colin Crossa6182ab2024-08-21 10:47:44 -07001273
Colin Cross7727c7f2024-07-18 15:36:32 -07001274 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Jihoon Kang705e63e2024-03-13 01:21:16 +00001275 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001276 LocalHeaderJars: localHeaderJars,
1277 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
Colin Cross9ffaf282024-08-12 13:50:09 -07001278 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1279 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001280 AidlIncludeDirs: j.exportAidlIncludeDirs,
1281 ExportedPlugins: j.exportedPluginJars,
1282 ExportedPluginClasses: j.exportedPluginClasses,
1283 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1284 StubsLinkType: j.stubsLinkType,
1285 AconfigIntermediateCacheOutputPaths: deps.aconfigProtoFiles,
Mark Whitea15790a2023-08-22 21:28:11 +00001286 })
1287
1288 j.outputFile = j.headerJarFile
1289 return
1290 }
1291
Jaewoong Jung26342642021-03-17 15:56:23 -07001292 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001293 // When using kotlin sources turbine is used to generate annotation processor sources,
1294 // including for annotation processors that generate API, so we can use turbine for
1295 // java sources too.
1296 disableTurbine = false
1297
Jaewoong Jung26342642021-03-17 15:56:23 -07001298 // user defined kotlin flags.
1299 kotlincFlags := j.properties.Kotlincflags
1300 CheckKotlincFlags(ctx, kotlincFlags)
1301
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001302 // Workaround for KT-46512
1303 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001304
1305 // If there are kotlin files, compile them first but pass all the kotlin and java files
1306 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1307 // won't emit any classes for them.
1308 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1309 if ctx.Device() {
1310 kotlincFlags = append(kotlincFlags, "-no-jdk")
1311 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001312
1313 for _, plugin := range deps.kotlinPlugins {
1314 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1315 }
1316 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1317
Jaewoong Jung26342642021-03-17 15:56:23 -07001318 if len(kotlincFlags) > 0 {
1319 // optimization.
1320 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1321 flags.kotlincFlags += "$kotlincFlags"
1322 }
1323
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001324 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001325 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1326
Jaewoong Jung26342642021-03-17 15:56:23 -07001327 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1328 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1329
Isaac Chioua23d9942022-04-06 06:14:38 +00001330 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001331 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001332 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1333 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001334 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001335 srcJars = append(srcJars, kaptSrcJar)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001336 localImplementationJars = append(localImplementationJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001337 // Disable annotation processing in javac, it's already been handled by kapt
1338 flags.processorPath = nil
1339 flags.processors = nil
1340 }
1341
1342 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001343 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Spandan Das1028d5a2024-08-19 21:45:48 +00001344 j.kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001345 if ctx.Failed() {
1346 return
1347 }
1348
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001349 kotlinJarPath, _ := j.repackageFlagsIfNecessary(ctx, kotlinJar, jarName, "kotlinc")
Zi Wangddb2ee52024-04-02 16:44:02 +00001350
Isaac Chioua23d9942022-04-06 06:14:38 +00001351 // Make javac rule depend on the kotlinc rule
1352 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1353
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001354 localImplementationJars = append(localImplementationJars, kotlinJarPath)
1355
Colin Cross220a9a12022-03-28 17:08:01 -07001356 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001357 }
1358
Jaewoong Jung26342642021-03-17 15:56:23 -07001359 j.compiledSrcJars = srcJars
1360
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001361 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1362
Jaewoong Jung26342642021-03-17 15:56:23 -07001363 enableSharding := false
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001364 var localHeaderJars android.Paths
1365 var shardingHeaderJars android.Paths
1366 var repackagedHeaderJarFile android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001367 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001368 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1369 enableSharding = true
1370 // Formerly, there was a check here that prevented annotation processors
1371 // from being used when sharding was enabled, as some annotation processors
1372 // do not function correctly in sharded environments. It was removed to
1373 // allow for the use of annotation processors that do function correctly
1374 // with sharding enabled. See: b/77284273.
1375 }
Colin Crossd1d8f172024-07-29 11:30:29 -07001376 extraJars := slices.Clone(kotlinHeaderJars)
Colin Crossd1d8f172024-07-29 11:30:29 -07001377 extraJars = append(extraJars, extraCombinedJars...)
Colin Crossedec77c2024-07-26 15:25:40 -07001378 var combinedHeaderJarFile android.Path
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001379 localHeaderJars, combinedHeaderJarFile = j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
1380 shardingHeaderJars = localHeaderJars
Colin Crossedec77c2024-07-26 15:25:40 -07001381
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001382 var jarjared bool
1383 j.headerJarFile, jarjared = j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1384 if jarjared {
1385 // jarjar modifies transitive static dependencies, use the combined header jar and drop the transitive
1386 // static libs header jars.
1387 localHeaderJars = android.Paths{j.headerJarFile}
1388 transitiveStaticLibsHeaderJars = nil
1389 }
1390 var repackaged bool
1391 repackagedHeaderJarFile, repackaged = j.repackageFlagsIfNecessary(ctx, j.headerJarFile, jarName, "turbine")
1392 if repackaged {
1393 // repackage modifies transitive static dependencies, use the combined header jar and drop the transitive
1394 // static libs header jars.
1395 // TODO(b/356688296): this shouldn't export both the unmodified and repackaged header jars
1396 localHeaderJars = android.Paths{j.headerJarFile, repackagedHeaderJarFile}
1397 transitiveStaticLibsHeaderJars = nil
1398 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001399 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001400 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001401 hasErrorproneableFiles := false
1402 for _, ext := range j.sourceExtensions {
1403 if ext != ".proto" && ext != ".aidl" {
1404 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1405 // compile, and it's not useful to have warnings on these generated sources.
1406 hasErrorproneableFiles = true
1407 break
1408 }
1409 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001410 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001411 if Bool(j.properties.Errorprone.Enabled) {
1412 // If error-prone is enabled, enable errorprone flags on the regular
1413 // build.
1414 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001415 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001416 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1417 // a new jar file just for compiling with the errorprone compiler to.
1418 // This is because we don't want to cause the java files to get completely
1419 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1420 // We also don't want to run this if errorprone is enabled by default for
1421 // this module, or else we could have duplicated errorprone messages.
1422 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001423 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001424 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001425
Vadim Spivak3c496f02023-06-08 06:14:59 +00001426 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001427 "errorprone", "errorprone")
1428
Jaewoong Jung26342642021-03-17 15:56:23 -07001429 extraJarDeps = append(extraJarDeps, errorprone)
1430 }
1431
1432 if enableSharding {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001433 if len(shardingHeaderJars) > 0 {
1434 flags.classpath = append(classpath(slices.Clone(shardingHeaderJars)), flags.classpath...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001435 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001436 shardSize := int(*(j.properties.Javac_shard_size))
1437 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001438 if len(uniqueJavaFiles) > 0 {
1439 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001440 for idx, shardSrc := range shardSrcs {
1441 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1442 nil, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001443 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(idx))
1444 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001445 }
1446 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001447 // Assume approximately 5 sources per srcjar.
1448 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1449 // 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 -07001450 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001451 startIdx := len(shardSrcs)
1452 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1453 for idx, shardSrcJars := range shardSrcJarsList {
1454 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1455 nil, shardSrcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001456 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(startIdx+idx))
1457 localImplementationJars = append(localImplementationJars, classes)
Colin Crossa052ddb2023-09-25 21:46:58 -07001458 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001459 }
1460 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001461 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001462 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac")
1463 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001464 }
1465 if ctx.Failed() {
1466 return
1467 }
1468 }
1469
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001470 localImplementationJars = append(localImplementationJars, extraCombinedJars...)
Colin Crossfd620b22024-02-23 10:05:21 -08001471
Jaewoong Jung26342642021-03-17 15:56:23 -07001472 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1473
1474 var includeSrcJar android.WritablePath
1475 if Bool(j.properties.Include_srcs) {
1476 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1477 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1478 }
1479
1480 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1481 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1482 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1483 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1484
1485 var resArgs []string
1486 var resDeps android.Paths
1487
1488 resArgs = append(resArgs, dirArgs...)
1489 resDeps = append(resDeps, dirDeps...)
1490
1491 resArgs = append(resArgs, fileArgs...)
1492 resDeps = append(resDeps, fileDeps...)
1493
1494 resArgs = append(resArgs, extraArgs...)
1495 resDeps = append(resDeps, extraDeps...)
1496
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001497 var localResourceJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 if len(resArgs) > 0 {
1499 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1500 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 if ctx.Failed() {
1502 return
1503 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001504 localResourceJars = append(localResourceJars, resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001505 }
1506
Jaewoong Jung26342642021-03-17 15:56:23 -07001507 if Bool(j.properties.Include_srcs) {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001508 localResourceJars = append(localResourceJars, includeSrcJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001509 }
1510
1511 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1512 if len(services) > 0 {
1513 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1514 var zipargs []string
1515 for _, file := range services {
1516 serviceFile := file.String()
1517 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1518 }
1519 rule := zip
1520 args := map[string]string{
1521 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1522 }
1523 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1524 rule = zipRE
1525 args["implicits"] = strings.Join(services.Strings(), ",")
1526 }
1527 ctx.Build(pctx, android.BuildParams{
1528 Rule: rule,
1529 Output: servicesJar,
1530 Implicits: services,
1531 Args: args,
1532 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001533 localResourceJars = append(localResourceJars, servicesJar)
1534 }
1535
1536 completeStaticLibsResourceJars := android.NewDepSet(android.PREORDER, localResourceJars, deps.transitiveStaticLibsResourceJars)
1537
1538 var combinedResourceJar android.Path
1539 var resourceJars android.Paths
1540 if ctx.Config().UseTransitiveJarsInClasspath() {
1541 resourceJars = completeStaticLibsResourceJars.ToList()
1542 } else {
1543 resourceJars = append(slices.Clone(localResourceJars), deps.staticResourceJars...)
1544 }
1545 if len(resourceJars) == 1 {
1546 combinedResourceJar = resourceJars[0]
1547 } else if len(resourceJars) > 0 {
1548 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1549 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1550 false, nil, nil)
1551 combinedResourceJar = combinedJar
1552 }
1553
1554 manifest := j.overrideManifest
1555 if !manifest.Valid() && j.properties.Manifest != nil {
1556 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
Jaewoong Jung26342642021-03-17 15:56:23 -07001557 }
1558
1559 // Combine the classes built from sources, any manifests, and any static libraries into
1560 // classes.jar. If there is only one input jar this step will be skipped.
Colin Cross7707b242024-07-26 12:02:36 -07001561 var outputFile android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001562
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001563 completeStaticLibsImplementationJars := android.NewDepSet(android.PREORDER, localImplementationJars, deps.transitiveStaticLibsImplementationJars)
1564
1565 var jars android.Paths
1566 if ctx.Config().UseTransitiveJarsInClasspath() {
1567 jars = completeStaticLibsImplementationJars.ToList()
1568 } else {
1569 jars = append(slices.Clone(localImplementationJars), deps.staticJars...)
1570 }
1571
1572 jars = append(jars, extraDepCombinedJars...)
1573
Jaewoong Jung26342642021-03-17 15:56:23 -07001574 if len(jars) == 1 && !manifest.Valid() {
1575 // Optimization: skip the combine step as there is nothing to do
1576 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1577 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001578 // any if len(extraJars) == 0.
Jaewoong Jung26342642021-03-17 15:56:23 -07001579
Jihoon Kang1147b312023-06-08 23:25:57 +00001580 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1581 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1582 // either with .from-source or .from-text suffix.
1583 // outputFile should be agnostic to the build configuration,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001584 // thus copy the single input static lib in order to prevent the static lib from being exposed
Jihoon Kang1147b312023-06-08 23:25:57 +00001585 // to the copy rules.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001586 if stub, _ := moduleStubLinkType(j); stub {
1587 copiedJar := android.PathForModuleOut(ctx, "combined", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001588 ctx.Build(pctx, android.BuildParams{
1589 Rule: android.Cp,
1590 Input: jars[0],
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001591 Output: copiedJar,
Jaewoong Jung26342642021-03-17 15:56:23 -07001592 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001593 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, android.Paths{copiedJar}, nil)
1594 outputFile = copiedJar
Colin Cross7707b242024-07-26 12:02:36 -07001595 } else {
1596 outputFile = jars[0]
Jaewoong Jung26342642021-03-17 15:56:23 -07001597 }
1598 } else {
1599 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1600 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1601 false, nil, nil)
Colin Cross7707b242024-07-26 12:02:36 -07001602 outputFile = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 }
1604
1605 // jarjar implementation jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001606 jarjarFile, jarjarred := j.jarjarIfNecessary(ctx, outputFile, jarName, "")
1607 if jarjarred {
1608 localImplementationJars = android.Paths{jarjarFile}
1609 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
1610 }
Colin Crossedec77c2024-07-26 15:25:40 -07001611 outputFile = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001612
Colin Crossedec77c2024-07-26 15:25:40 -07001613 // jarjar resource jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001614 if combinedResourceJar != nil {
1615 resourceJarJarFile, jarjarred := j.jarjarIfNecessary(ctx, combinedResourceJar, jarName, "resource")
1616 combinedResourceJar = resourceJarJarFile
1617 if jarjarred {
1618 localResourceJars = android.Paths{resourceJarJarFile}
1619 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1620 }
Colin Crossedec77c2024-07-26 15:25:40 -07001621 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001622
Colin Crossedec77c2024-07-26 15:25:40 -07001623 if ctx.Failed() {
1624 return
Jaewoong Jung26342642021-03-17 15:56:23 -07001625 }
1626
Makoto Onuki7ded3822024-03-28 14:42:20 -07001627 if j.ravenizer.enabled {
1628 ravenizerInput := outputFile
1629 ravenizerOutput := android.PathForModuleOut(ctx, "ravenizer", jarName)
1630 ctx.Build(pctx, android.BuildParams{
1631 Rule: ravenizer,
1632 Description: "ravenizer",
1633 Input: ravenizerInput,
1634 Output: ravenizerOutput,
1635 })
1636 outputFile = ravenizerOutput
Colin Cross7e863852024-09-06 14:42:38 -07001637 localImplementationJars = android.Paths{ravenizerOutput}
1638 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Makoto Onuki7ded3822024-03-28 14:42:20 -07001639 }
1640
Yihan Dong8be09c22024-08-29 15:32:13 +08001641 if j.shouldApiMapper() {
1642 inputFile := outputFile
1643 apiMapperFile := android.PathForModuleOut(ctx, "apimapper", jarName)
1644 ctx.Build(pctx, android.BuildParams{
1645 Rule: apimapper,
1646 Description: "apimapper",
1647 Input: inputFile,
1648 Output: apiMapperFile,
1649 })
1650 outputFile = apiMapperFile
Colin Cross7e863852024-09-06 14:42:38 -07001651 localImplementationJars = android.Paths{apiMapperFile}
1652 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Yihan Dong8be09c22024-08-29 15:32:13 +08001653 }
1654
Jaewoong Jung26342642021-03-17 15:56:23 -07001655 // Check package restrictions if necessary.
1656 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001657 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001658 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001659
1660 // Create a rule to copy the output jar to another path and add a validate dependency that
1661 // will check that the jar only contains the permitted packages. The new location will become
1662 // the output file of this module.
1663 inputFile := outputFile
Colin Cross7707b242024-07-26 12:02:36 -07001664 packageCheckOutputFile := android.PathForModuleOut(ctx, "package-check", jarName)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001665 ctx.Build(pctx, android.BuildParams{
1666 Rule: android.Cp,
1667 Input: inputFile,
Colin Cross7707b242024-07-26 12:02:36 -07001668 Output: packageCheckOutputFile,
Paul Duffin08a18bf2021-10-01 13:19:58 +01001669 // Make sure that any dependency on the output file will cause ninja to run the package check
1670 // rule.
1671 Validation: pkgckFile,
1672 })
Colin Cross7707b242024-07-26 12:02:36 -07001673 outputFile = packageCheckOutputFile
Colin Cross7e863852024-09-06 14:42:38 -07001674 localImplementationJars = android.Paths{packageCheckOutputFile}
1675 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001676
1677 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001678 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001679
1680 if ctx.Failed() {
1681 return
1682 }
1683 }
1684
1685 j.implementationJarFile = outputFile
1686 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001687 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1688 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1689 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1690 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1691 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1692 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1693 j.headerJarFile = headerJarFile
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001694 if len(localImplementationJars) == 1 && ctx.Config().UseTransitiveJarsInClasspath() {
1695 localHeaderJarFile := android.PathForModuleOut(ctx, "local-javac-header", jarName)
1696 convertImplementationJarToHeaderJar(ctx, localImplementationJars[0], localHeaderJarFile)
1697 localHeaderJars = append(localHeaderJars, localHeaderJarFile)
1698 } else {
1699 localHeaderJars = append(localHeaderJars, headerJarFile)
1700 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001701 }
1702
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001703 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1704 specs := j.jacocoModuleToZipCommand(ctx)
1705 if ctx.Failed() {
1706 return
1707 }
1708
Colin Crossb323c912024-09-24 15:21:00 -07001709 completeStaticLibsImplementationJarsToCombine := completeStaticLibsImplementationJars
1710
Jaewoong Jung26342642021-03-17 15:56:23 -07001711 if j.shouldInstrument(ctx) {
Colin Crossb323c912024-09-24 15:21:00 -07001712 instrumentedOutputFile := j.instrument(ctx, flags, outputFile, jarName, specs)
1713 completeStaticLibsImplementationJarsToCombine = android.NewDepSet(android.PREORDER, android.Paths{instrumentedOutputFile}, nil)
1714 outputFile = instrumentedOutputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001715 }
1716
1717 // merge implementation jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001718 var implementationAndResourcesJarsToCombine android.Paths
1719 if ctx.Config().UseTransitiveJarsInClasspath() {
1720 resourceJars := completeStaticLibsResourceJars.ToList()
1721 if len(resourceJars) > 0 {
Colin Crossb323c912024-09-24 15:21:00 -07001722 implementationAndResourcesJarsToCombine = append(resourceJars, completeStaticLibsImplementationJarsToCombine.ToList()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001723 implementationAndResourcesJarsToCombine = append(implementationAndResourcesJarsToCombine, extraDepCombinedJars...)
1724 }
1725 } else {
1726 if combinedResourceJar != nil {
1727 implementationAndResourcesJarsToCombine = android.Paths{combinedResourceJar, outputFile}
1728 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001729 }
1730
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001731 if len(implementationAndResourcesJarsToCombine) > 0 {
1732 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
1733 TransformJarsToJar(ctx, combinedJar, "for resources", implementationAndResourcesJarsToCombine, manifest,
1734 false, nil, nil)
1735 outputFile = combinedJar
1736 }
1737
1738 j.implementationAndResourcesJar = outputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001739
1740 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001741 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001742 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001743 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001744 if compileDex == nil {
1745 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001746 }
1747 if j.deviceProperties.Hostdex == nil {
1748 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1749 }
1750 }
1751
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001752 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001753 if j.hasCode(ctx) {
1754 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001755 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001756 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1757 }
1758 // Dex compilation
Colin Cross7707b242024-07-26 12:02:36 -07001759 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00001760 params := &compileDexParams{
1761 flags: flags,
1762 sdkVersion: j.SdkVersion(ctx),
1763 minSdkVersion: j.MinSdkVersion(ctx),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001764 classesJar: outputFile,
Spandan Dasc404cc72023-02-23 18:05:05 +00001765 jarName: jarName,
1766 }
Cole Fausteb032462024-09-19 11:12:54 -07001767 if j.GetProfileGuided(ctx) && j.optimizeOrObfuscateEnabled() && !j.EnableProfileRewriting(ctx) {
Spandan Das15a67112024-05-30 00:07:40 +00001768 ctx.PropertyErrorf("enable_profile_rewriting",
1769 "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.",
1770 )
1771 }
Cole Fausteb032462024-09-19 11:12:54 -07001772 if j.EnableProfileRewriting(ctx) {
1773 profile := j.GetProfile(ctx)
1774 if profile == "" || !j.GetProfileGuided(ctx) {
Spandan Das3dbda182024-05-20 22:23:10 +00001775 ctx.PropertyErrorf("enable_profile_rewriting", "Profile and Profile_guided must be set when enable_profile_rewriting is true")
1776 }
1777 params.artProfileInput = &profile
1778 }
1779 dexOutputFile, dexArtProfileOutput := j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001780 if ctx.Failed() {
1781 return
1782 }
1783
Spandan Das3dbda182024-05-20 22:23:10 +00001784 // If r8/d8 provides a profile that matches the optimized dex, use that for dexpreopt.
1785 if dexArtProfileOutput != nil {
Colin Cross7707b242024-07-26 12:02:36 -07001786 j.dexpreopter.SetRewrittenProfile(dexArtProfileOutput)
Spandan Das3dbda182024-05-20 22:23:10 +00001787 }
1788
Jaewoong Jung26342642021-03-17 15:56:23 -07001789 // merge dex jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001790 var dexAndResourceJarsToCombine android.Paths
1791 if ctx.Config().UseTransitiveJarsInClasspath() {
1792 resourceJars := completeStaticLibsResourceJars.ToList()
1793 if len(resourceJars) > 0 {
1794 dexAndResourceJarsToCombine = append(android.Paths{dexOutputFile}, resourceJars...)
1795 }
1796 } else {
1797 if combinedResourceJar != nil {
1798 dexAndResourceJarsToCombine = android.Paths{dexOutputFile, combinedResourceJar}
1799 }
1800 }
1801 if len(dexAndResourceJarsToCombine) > 0 {
Colin Cross7707b242024-07-26 12:02:36 -07001802 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001803 TransformJarsToJar(ctx, combinedJar, "for dex resources", dexAndResourceJarsToCombine, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07001804 false, nil, nil)
1805 if *j.dexProperties.Uncompress_dex {
Colin Cross7707b242024-07-26 12:02:36 -07001806 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName)
Cole Faust51d7bfd2023-09-07 05:31:32 +00001807 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001808 dexOutputFile = combinedAlignedJar
1809 } else {
1810 dexOutputFile = combinedJar
1811 }
1812 }
1813
Paul Duffin4de94502021-05-16 05:21:16 +01001814 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001815
1816 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001817
1818 // Encode hidden API flags in dex file, if needed.
1819 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1820
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001821 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001822
1823 // Dexpreopting
Jihoon Kanga3a05462024-04-05 00:36:44 +00001824 libName := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())
1825 if j.SdkLibraryName() != nil && strings.HasSuffix(ctx.ModuleName(), ".impl") {
1826 libName = strings.TrimSuffix(libName, ".impl")
1827 }
1828 j.dexpreopt(ctx, libName, dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001829
1830 outputFile = dexOutputFile
Colin Crossa6182ab2024-08-21 10:47:44 -07001831
1832 ctx.CheckbuildFile(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001833 } else {
1834 // There is no code to compile into a dex jar, make sure the resources are propagated
1835 // to the APK if this is an app.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001836 j.dexJarFile = makeDexJarPathFromPath(combinedResourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001837 }
1838
1839 if ctx.Failed() {
1840 return
1841 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001842 }
1843
1844 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001845 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001846 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001847 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001848 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001849 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001850 }
1851 }
1852
1853 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001854 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1855 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001856 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1857 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001858 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001859 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001860 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001861 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001862 j.linter.javaLanguageLevel = flags.javaVersion.String()
1863 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001864 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001865 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1866 j.linter.buildModuleReportZip = true
1867 }
1868 j.linter.lint(ctx)
1869 }
1870
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001871 j.collectTransitiveSrcFiles(ctx, srcFiles)
1872
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001873 if ctx.Config().UseTransitiveJarsInClasspath() {
1874 if len(localImplementationJars) > 0 || len(localResourceJars) > 0 || len(localHeaderJars) > 0 {
1875 ctx.CheckbuildFile(localImplementationJars...)
1876 ctx.CheckbuildFile(localResourceJars...)
1877 ctx.CheckbuildFile(localHeaderJars...)
1878 } else {
1879 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1880 ctx.UncheckedModule()
1881 }
1882 } else {
1883 ctx.CheckbuildFile(j.implementationJarFile)
1884 ctx.CheckbuildFile(j.headerJarFile)
1885 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001886
Colin Cross7727c7f2024-07-18 15:36:32 -07001887 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001888 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1889 RepackagedHeaderJars: android.PathsIfNonNil(repackagedHeaderJarFile),
1890
1891 LocalHeaderJars: localHeaderJars,
1892 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
1893 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
1894 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
1895
Colin Cross9ffaf282024-08-12 13:50:09 -07001896 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1897 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001898 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1899 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001900 ResourceJars: android.PathsIfNonNil(combinedResourceJar),
Jihoon Kang705e63e2024-03-13 01:21:16 +00001901 AidlIncludeDirs: j.exportAidlIncludeDirs,
1902 SrcJarArgs: j.srcJarArgs,
1903 SrcJarDeps: j.srcJarDeps,
1904 TransitiveSrcFiles: j.transitiveSrcFiles,
1905 ExportedPlugins: j.exportedPluginJars,
1906 ExportedPluginClasses: j.exportedPluginClasses,
1907 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1908 JacocoReportClassesFile: j.jacocoReportClassesFile,
1909 StubsLinkType: j.stubsLinkType,
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001910 AconfigIntermediateCacheOutputPaths: j.aconfigCacheFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001911 })
1912
1913 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1914 j.outputFile = outputFile.WithoutRel()
1915}
1916
Cole Faustb7493472024-08-28 11:55:52 -07001917func (j *Module) useCompose(ctx android.BaseModuleContext) bool {
1918 return android.InList("androidx.compose.runtime_runtime", j.staticLibs(ctx))
Colin Crossa1ff7c62021-09-17 14:11:52 -07001919}
1920
Colin Crosscde55342024-03-27 14:11:51 -07001921func collectDepProguardSpecInfo(ctx android.ModuleContext) (transitiveProguardFlags, transitiveUnconditionalExportedFlags []*android.DepSet[android.Path]) {
Sam Delmerico95d70942023-08-02 18:00:35 -04001922 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001923 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001924 depTag := ctx.OtherModuleDependencyTag(m)
1925
1926 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1927 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1928 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1929 }
1930
1931 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1932 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1933 }
1934 })
1935
Colin Crosscde55342024-03-27 14:11:51 -07001936 return transitiveProguardFlags, transitiveUnconditionalExportedFlags
1937}
1938
1939func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1940 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
1941
Sam Delmerico95d70942023-08-02 18:00:35 -04001942 directUnconditionalExportedFlags := android.Paths{}
1943 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1944 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1945 if exportUnconditionally {
1946 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1947 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1948 directUnconditionalExportedFlags = proguardFlagsForThisModule
1949 }
1950
1951 return ProguardSpecInfo{
1952 Export_proguard_flags_files: exportUnconditionally,
1953 ProguardFlagsFiles: android.NewDepSet[android.Path](
1954 android.POSTORDER,
1955 proguardFlagsForThisModule,
1956 transitiveProguardFlags,
1957 ),
1958 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1959 android.POSTORDER,
1960 directUnconditionalExportedFlags,
1961 transitiveUnconditionalExportedFlags,
1962 ),
1963 }
1964
1965}
1966
Cole Faust75fffb12021-06-13 15:23:16 -07001967// Returns a copy of the supplied flags, but with all the errorprone-related
1968// fields copied to the regular build's fields.
1969func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1970 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1971
1972 if len(flags.errorProneExtraJavacFlags) > 0 {
1973 if len(flags.javacFlags) > 0 {
1974 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1975 } else {
1976 flags.javacFlags = flags.errorProneExtraJavacFlags
1977 }
1978 }
1979 return flags
1980}
1981
Jaewoong Jung26342642021-03-17 15:56:23 -07001982func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
Colin Cross7707b242024-07-26 12:02:36 -07001983 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07001984
1985 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001986 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001987 if idx >= 0 {
1988 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001989 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001990 jarName += strconv.Itoa(idx)
1991 }
1992
Colin Cross7707b242024-07-26 12:02:36 -07001993 classes := android.PathForModuleOut(ctx, "javac", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001994 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001995
Cole Faust9decf832024-06-11 11:45:53 -07001996 if ctx.Config().EmitXrefRules() && ctx.Module() == ctx.PrimaryModule() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001997 extractionFile := android.PathForModuleOut(ctx, kzipName)
1998 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1999 j.kytheFiles = append(j.kytheFiles, extractionFile)
2000 }
2001
Vadim Spivak3c496f02023-06-08 06:14:59 +00002002 if len(flags.processorPath) > 0 {
2003 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
2004 }
2005
Jaewoong Jung26342642021-03-17 15:56:23 -07002006 return classes
2007}
2008
2009// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
2010// since some of these flags may be used internally.
2011func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
2012 for _, flag := range flags {
2013 flag = strings.TrimSpace(flag)
2014
2015 if !strings.HasPrefix(flag, "-") {
2016 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
2017 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
2018 ctx.PropertyErrorf("kotlincflags",
2019 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
2020 } else if inList(flag, config.KotlincIllegalFlags) {
2021 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
2022 } else if flag == "-include-runtime" {
2023 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
2024 } else {
2025 args := strings.Split(flag, " ")
2026 if args[0] == "-kotlin-home" {
2027 ctx.PropertyErrorf("kotlincflags",
2028 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
2029 }
2030 }
2031 }
2032}
2033
2034func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
2035 deps deps, flags javaBuilderFlags, jarName string,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002036 extraJars android.Paths) (localHeaderJars android.Paths, combinedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002037
Jaewoong Jung26342642021-03-17 15:56:23 -07002038 if len(srcFiles) > 0 || len(srcJars) > 0 {
2039 // Compile java sources into turbine.jar.
2040 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
2041 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002042 localHeaderJars = append(localHeaderJars, turbineJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07002043 }
2044
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002045 localHeaderJars = append(localHeaderJars, extraJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002046
2047 // Combine any static header libraries into classes-header.jar. If there is only
2048 // one input jar this step will be skipped.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002049 var jars android.Paths
2050 if ctx.Config().UseTransitiveJarsInClasspath() {
2051 depSet := android.NewDepSet(android.PREORDER, localHeaderJars, deps.transitiveStaticLibsHeaderJars)
2052 jars = depSet.ToList()
2053 } else {
2054 jars = append(slices.Clone(localHeaderJars), deps.staticHeaderJars...)
2055 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002056
2057 // we cannot skip the combine step for now if there is only one jar
2058 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
Colin Crossedec77c2024-07-26 15:25:40 -07002059 combinedHeaderJarOutputPath := android.PathForModuleOut(ctx, "turbine-combined", jarName)
2060 TransformJarsToJar(ctx, combinedHeaderJarOutputPath, "for turbine", jars, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07002061 false, nil, []string{"META-INF/TRANSITIVE"})
Jaewoong Jung26342642021-03-17 15:56:23 -07002062
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002063 return localHeaderJars, combinedHeaderJarOutputPath
Jaewoong Jung26342642021-03-17 15:56:23 -07002064}
2065
2066func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Colin Cross7707b242024-07-26 12:02:36 -07002067 classesJar android.Path, jarName string, specs string) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07002068
2069 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
Colin Cross7707b242024-07-26 12:02:36 -07002070 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07002071
2072 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
2073
2074 j.jacocoReportClassesFile = jacocoReportClassesFile
2075
2076 return instrumentedJar
2077}
2078
Colin Cross9ffaf282024-08-12 13:50:09 -07002079type providesTransitiveHeaderJarsForR8 struct {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002080 // set of header jars for all transitive libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002081 transitiveLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002082 // set of header jars for all transitive static libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002083 transitiveStaticLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002084}
2085
Colin Cross9ffaf282024-08-12 13:50:09 -07002086// collectTransitiveHeaderJarsForR8 visits direct dependencies and collects all transitive libs and static_libs
2087// header jars. The semantics of the collected jars are odd (it collects combined jars that contain the static
2088// libs, but also the static libs, and it collects transitive libs dependencies of static_libs), so these
2089// are only used to expand the --lib arguments to R8.
2090func (j *providesTransitiveHeaderJarsForR8) collectTransitiveHeaderJarsForR8(ctx android.ModuleContext) {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002091 directLibs := android.Paths{}
2092 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07002093 transitiveLibs := []*android.DepSet[android.Path]{}
2094 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002095 ctx.VisitDirectDeps(func(module android.Module) {
2096 // don't add deps of the prebuilt version of the same library
2097 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
2098 return
2099 }
2100
Colin Cross7727c7f2024-07-18 15:36:32 -07002101 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2102 tag := ctx.OtherModuleDependencyTag(module)
2103 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
2104 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
2105 directLibs = append(directLibs, dep.HeaderJars...)
2106 } else if tag == staticLibTag {
2107 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
2108 } else {
2109 // Don't propagate transitive libs for other kinds of dependencies.
2110 return
2111 }
Jared Dukeefb6d602023-10-27 18:47:10 +00002112
Colin Cross9ffaf282024-08-12 13:50:09 -07002113 if dep.TransitiveLibsHeaderJarsForR8 != nil {
2114 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002115 }
Colin Cross9ffaf282024-08-12 13:50:09 -07002116 if dep.TransitiveStaticLibsHeaderJarsForR8 != nil {
2117 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002118 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002119
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002120 }
2121 })
Colin Cross9ffaf282024-08-12 13:50:09 -07002122 j.transitiveLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
2123 j.transitiveStaticLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002124}
2125
Jaewoong Jung26342642021-03-17 15:56:23 -07002126func (j *Module) HeaderJars() android.Paths {
2127 if j.headerJarFile == nil {
2128 return nil
2129 }
2130 return android.Paths{j.headerJarFile}
2131}
2132
2133func (j *Module) ImplementationJars() android.Paths {
2134 if j.implementationJarFile == nil {
2135 return nil
2136 }
2137 return android.Paths{j.implementationJarFile}
2138}
2139
Spandan Das59a4a2b2024-01-09 21:35:56 +00002140func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07002141 return j.dexJarFile
2142}
2143
2144func (j *Module) DexJarInstallPath() android.Path {
2145 return j.installFile
2146}
2147
2148func (j *Module) ImplementationAndResourcesJars() android.Paths {
2149 if j.implementationAndResourcesJar == nil {
2150 return nil
2151 }
2152 return android.Paths{j.implementationAndResourcesJar}
2153}
2154
2155func (j *Module) AidlIncludeDirs() android.Paths {
2156 // exportAidlIncludeDirs is type android.Paths already
2157 return j.exportAidlIncludeDirs
2158}
2159
2160func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2161 return j.classLoaderContexts
2162}
2163
2164// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -07002165func (j *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002166 // jarjar rules will repackage the sources. To prevent misleading results, IdeInfo should contain the
2167 // repackaged jar instead of the input sources.
Jaewoong Jung26342642021-03-17 15:56:23 -07002168 if j.expandJarjarRules != nil {
2169 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002170 dpInfo.Jars = append(dpInfo.Jars, j.headerJarFile.String())
2171 } else {
2172 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2173 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2174 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002175 }
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002176 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2177 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
Cole Faustb7493472024-08-28 11:55:52 -07002178 dpInfo.Static_libs = append(dpInfo.Static_libs, j.staticLibs(ctx)...)
Yikef6282022022-04-13 20:41:01 +08002179 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002180}
2181
2182func (j *Module) CompilerDeps() []string {
Spandan Das8aac9932024-07-18 23:14:13 +00002183 return j.compileDepNames
Jaewoong Jung26342642021-03-17 15:56:23 -07002184}
2185
2186func (j *Module) hasCode(ctx android.ModuleContext) bool {
2187 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2188 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2189}
2190
2191// Implements android.ApexModule
2192func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2193 return j.depIsInSameApex(ctx, dep)
2194}
2195
2196// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002197func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002198 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002199 minSdkVersion := j.MinSdkVersion(ctx)
2200 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002201 return fmt.Errorf("min_sdk_version is not specified")
2202 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002203 // If the module is compiling against core (via sdk_version), skip comparison check.
2204 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002205 return nil
2206 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002207 if minSdkVersion.GreaterThan(sdkVersion) {
2208 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002209 }
2210 return nil
2211}
2212
2213func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002214 if j.stem == "" {
2215 panic("Stem() called before stem property was set")
2216 }
2217 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002218}
2219
Jaewoong Jung26342642021-03-17 15:56:23 -07002220func (j *Module) JacocoReportClassesFile() android.Path {
2221 return j.jacocoReportClassesFile
2222}
2223
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002224func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2225 var fromDeps []*android.DepSet[android.Path]
2226 ctx.VisitDirectDeps(func(module android.Module) {
2227 tag := ctx.OtherModuleDependencyTag(module)
2228 if tag == staticLibTag {
Colin Cross7727c7f2024-07-18 15:36:32 -07002229 if depInfo, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2230 if depInfo.TransitiveSrcFiles != nil {
2231 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2232 }
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002233 }
2234 }
2235 })
2236
2237 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2238}
2239
Jaewoong Jung26342642021-03-17 15:56:23 -07002240func (j *Module) IsInstallable() bool {
2241 return Bool(j.properties.Installable)
2242}
2243
2244type sdkLinkType int
2245
2246const (
2247 // TODO(jiyong) rename these for better readability. Make the allowed
2248 // and disallowed link types explicit
2249 // order is important here. See rank()
2250 javaCore sdkLinkType = iota
2251 javaSdk
2252 javaSystem
2253 javaModule
2254 javaSystemServer
2255 javaPlatform
2256)
2257
2258func (lt sdkLinkType) String() string {
2259 switch lt {
2260 case javaCore:
2261 return "core Java API"
2262 case javaSdk:
2263 return "Android API"
2264 case javaSystem:
2265 return "system API"
2266 case javaModule:
2267 return "module API"
2268 case javaSystemServer:
2269 return "system server API"
2270 case javaPlatform:
2271 return "private API"
2272 default:
2273 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2274 }
2275}
2276
2277// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2278// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2279// can't statically depend on modules that use Platform API.
2280func (lt sdkLinkType) rank() int {
2281 return int(lt)
2282}
2283
2284type moduleWithSdkDep interface {
2285 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002286 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002287}
2288
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002289func sdkLinkTypeFromSdkKind(k android.SdkKind) sdkLinkType {
2290 switch k {
2291 case android.SdkCore:
2292 return javaCore
2293 case android.SdkSystem:
2294 return javaSystem
2295 case android.SdkPublic:
2296 return javaSdk
2297 case android.SdkModule:
2298 return javaModule
2299 case android.SdkSystemServer:
2300 return javaSystemServer
2301 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
2302 return javaPlatform
2303 default:
2304 return javaSdk
2305 }
2306}
2307
Jiyong Park92315372021-04-02 08:45:46 +09002308func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002309 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002310 case android.SdkCore.DefaultJavaLibraryName(),
2311 "legacy.core.platform.api.stubs",
2312 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002313 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002314 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002315 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002316 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002317 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002318 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002319 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002320 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002321 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002322 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002323 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002324 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002325 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002326 return javaSystem, true
2327 }
2328
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002329 if stub, linkType := moduleStubLinkType(m); stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07002330 return linkType, true
2331 }
2332
Jiyong Park92315372021-04-02 08:45:46 +09002333 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002334 if !ver.Valid() {
2335 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002336 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002337
2338 return sdkLinkTypeFromSdkKind(ver.Kind), false
Jaewoong Jung26342642021-03-17 15:56:23 -07002339}
2340
2341// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2342// this module's. See the comment on rank() for details and an example.
2343func (j *Module) checkSdkLinkType(
2344 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2345 if ctx.Host() {
2346 return
2347 }
2348
Jiyong Park92315372021-04-02 08:45:46 +09002349 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002350 if stubs {
2351 return
2352 }
Jiyong Park92315372021-04-02 08:45:46 +09002353 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002354
2355 if myLinkType.rank() < depLinkType.rank() {
2356 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2357 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2358 "property of the source or target module so that target module is built "+
2359 "with the same or smaller API set when compared to the source.",
2360 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2361 }
2362}
2363
2364func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2365 var deps deps
2366
Jiyong Park92315372021-04-02 08:45:46 +09002367 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002368
Colin Cross9ffaf282024-08-12 13:50:09 -07002369 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002370
2371 var transitiveBootClasspathHeaderJars []*android.DepSet[android.Path]
2372 var transitiveClasspathHeaderJars []*android.DepSet[android.Path]
2373 var transitiveJava9ClasspathHeaderJars []*android.DepSet[android.Path]
2374 var transitiveStaticJarsHeaderLibs []*android.DepSet[android.Path]
2375 var transitiveStaticJarsImplementationLibs []*android.DepSet[android.Path]
2376 var transitiveStaticJarsResourceLibs []*android.DepSet[android.Path]
2377
Jaewoong Jung26342642021-03-17 15:56:23 -07002378 ctx.VisitDirectDeps(func(module android.Module) {
2379 otherName := ctx.OtherModuleName(module)
2380 tag := ctx.OtherModuleDependencyTag(module)
2381
2382 if IsJniDepTag(tag) {
2383 // Handled by AndroidApp.collectAppDeps
2384 return
2385 }
2386 if tag == certificateTag {
2387 // Handled by AndroidApp.collectAppDeps
2388 return
2389 }
2390
Jihoon Kang28c96572024-09-11 23:44:44 +00002391 if _, ok := module.(SdkLibraryDependency); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -07002392 switch tag {
Jihoon Kang28c96572024-09-11 23:44:44 +00002393 case sdkLibTag, libTag, staticLibTag:
2394 sdkInfo, _ := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider)
2395 generatingLibsString := android.PrettyConcat(
2396 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
2397 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 -07002398 }
Colin Cross313aa542023-12-13 13:47:44 -08002399 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2400 if sdkLinkType != javaPlatform {
2401 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2402 // dep is a sysprop implementation library, but this module is not linking against
2403 // the platform, so it gets the sysprop public stubs library instead. Replace
2404 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2405 dep = syspropDep.JavaInfo
2406 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002407 }
2408 switch tag {
2409 case bootClasspathTag:
2410 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002411 if dep.TransitiveStaticLibsHeaderJars != nil {
2412 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2413 }
Liz Kammeref28a4c2022-09-23 16:50:56 -04002414 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002415 if _, ok := module.(*Plugin); ok {
2416 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2417 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002418 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002419 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002420 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2421 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2422 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2423 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002424 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2425 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2426 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002427
2428 if dep.TransitiveStaticLibsHeaderJars != nil {
2429 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2430 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002431 case java9LibTag:
2432 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002433 if dep.TransitiveStaticLibsHeaderJars != nil {
2434 transitiveJava9ClasspathHeaderJars = append(transitiveJava9ClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2435 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002436 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002437 if _, ok := module.(*Plugin); ok {
2438 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2439 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002440 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2441 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2442 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2443 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2444 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2445 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2446 // Turbine doesn't run annotation processors, so any module that uses an
2447 // annotation processor that generates API is incompatible with the turbine
2448 // optimization.
2449 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Jihoon Kang705e63e2024-03-13 01:21:16 +00002450 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.AconfigIntermediateCacheOutputPaths...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002451
2452 if dep.TransitiveStaticLibsHeaderJars != nil {
2453 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2454 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, dep.TransitiveStaticLibsHeaderJars)
2455 }
2456 if dep.TransitiveStaticLibsImplementationJars != nil {
2457 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, dep.TransitiveStaticLibsImplementationJars)
2458 }
2459 if dep.TransitiveStaticLibsResourceJars != nil {
2460 transitiveStaticJarsResourceLibs = append(transitiveStaticJarsResourceLibs, dep.TransitiveStaticLibsResourceJars)
2461 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002462 case pluginTag:
2463 if plugin, ok := module.(*Plugin); ok {
2464 if plugin.pluginProperties.Processor_class != nil {
2465 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2466 } else {
2467 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2468 }
2469 // Turbine doesn't run annotation processors, so any module that uses an
2470 // annotation processor that generates API is incompatible with the turbine
2471 // optimization.
2472 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2473 } else {
2474 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2475 }
2476 case errorpronePluginTag:
2477 if _, ok := module.(*Plugin); ok {
2478 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2479 } else {
2480 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2481 }
2482 case exportedPluginTag:
2483 if plugin, ok := module.(*Plugin); ok {
2484 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2485 if plugin.pluginProperties.Processor_class != nil {
2486 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2487 }
2488 // Turbine doesn't run annotation processors, so any module that uses an
2489 // annotation processor that generates API is incompatible with the turbine
2490 // optimization.
2491 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2492 } else {
2493 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2494 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07002495 case kotlinPluginTag:
2496 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002497 case syspropPublicStubDepTag:
2498 // This is a sysprop implementation library, forward the JavaInfoProvider from
2499 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002500 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002501 JavaInfo: dep,
2502 })
2503 }
2504 } else if dep, ok := module.(android.SourceFileProducer); ok {
2505 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002506 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002507 checkProducesJars(ctx, dep)
2508 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002509 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002510 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars,
2511 android.NewDepSet(android.PREORDER, dep.Srcs(), nil))
Jaewoong Jung26342642021-03-17 15:56:23 -07002512 case staticLibTag:
2513 checkProducesJars(ctx, dep)
2514 deps.classpath = append(deps.classpath, dep.Srcs()...)
2515 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2516 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002517
2518 depHeaderJars := android.NewDepSet(android.PREORDER, dep.Srcs(), nil)
2519 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, depHeaderJars)
2520 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, depHeaderJars)
2521 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, depHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07002522 }
Jihoon Kang705e63e2024-03-13 01:21:16 +00002523 } else if dep, ok := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider); ok {
Jihoon Kang3921f0b2024-03-12 23:51:37 +00002524 switch tag {
2525 case staticLibTag:
2526 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.IntermediateCacheOutputPaths...)
2527 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002528 } else {
2529 switch tag {
2530 case bootClasspathTag:
2531 // If a system modules dependency has been added to the bootclasspath
2532 // then add its libs to the bootclasspath.
Colin Crossb61c2262024-08-08 14:04:42 -07002533 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002534 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars...)
2535 if sm.TransitiveStaticLibsHeaderJars != nil {
2536 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars,
2537 sm.TransitiveStaticLibsHeaderJars)
2538 }
Colin Crossb61c2262024-08-08 14:04:42 -07002539 } else {
2540 ctx.PropertyErrorf("boot classpath dependency %q does not provide SystemModulesProvider",
2541 ctx.OtherModuleName(module))
2542 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002543
2544 case systemModulesTag:
2545 if deps.systemModules != nil {
2546 panic("Found two system module dependencies")
2547 }
Colin Crossb61c2262024-08-08 14:04:42 -07002548 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
2549 deps.systemModules = &systemModules{sm.OutputDir, sm.OutputDirDeps}
2550 } else {
2551 ctx.PropertyErrorf("system modules dependency %q does not provide SystemModulesProvider",
2552 ctx.OtherModuleName(module))
2553 }
Paul Duffin53a70a42022-01-11 14:35:55 +00002554
2555 case instrumentationForTag:
2556 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 -07002557 }
2558 }
2559
Spandan Das8aac9932024-07-18 23:14:13 +00002560 if android.InList(tag, compileDependencyTags) {
2561 // Add the dependency name to compileDepNames so that it can be recorded in module_bp_java_deps.json
2562 j.compileDepNames = append(j.compileDepNames, otherName)
2563 }
2564
Jaewoong Jung26342642021-03-17 15:56:23 -07002565 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiakai Zhang36937082024-04-15 11:15:50 +00002566 addMissingOptionalUsesLibsFromDep(ctx, module, &j.usesLibrary)
Jaewoong Jung26342642021-03-17 15:56:23 -07002567 })
2568
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002569 deps.transitiveStaticLibsHeaderJars = transitiveStaticJarsHeaderLibs
2570 deps.transitiveStaticLibsImplementationJars = transitiveStaticJarsImplementationLibs
2571 deps.transitiveStaticLibsResourceJars = transitiveStaticJarsResourceLibs
2572
2573 if ctx.Config().UseTransitiveJarsInClasspath() {
2574 depSet := android.NewDepSet(android.PREORDER, nil, transitiveClasspathHeaderJars)
2575 deps.classpath = depSet.ToList()
2576 depSet = android.NewDepSet(android.PREORDER, nil, transitiveBootClasspathHeaderJars)
2577 deps.bootClasspath = depSet.ToList()
2578 depSet = android.NewDepSet(android.PREORDER, nil, transitiveJava9ClasspathHeaderJars)
2579 deps.java9Classpath = depSet.ToList()
2580 }
2581
2582 if ctx.Device() {
2583 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
2584 if sdkDep.invalidVersion {
2585 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2586 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2587 } else if sdkDep.useFiles {
2588 // sdkDep.jar is actually equivalent to turbine header.jar.
2589 deps.classpath = append(slices.Clone(classpath(sdkDep.jars)), deps.classpath...)
2590 deps.dexClasspath = append(slices.Clone(classpath(sdkDep.jars)), deps.dexClasspath...)
2591 deps.aidlPreprocess = sdkDep.aidl
2592 // Add the sdk module dependency to `compileDepNames`.
2593 // This ensures that the dependency is reported in `module_bp_java_deps.json`
2594 // TODO (b/358608607): Move this to decodeSdkDep
2595 sdkSpec := android.SdkContext(j).SdkVersion(ctx)
2596 j.compileDepNames = append(j.compileDepNames, fmt.Sprintf("sdk_%s_%s_android", sdkSpec.Kind.String(), sdkSpec.ApiLevel.String()))
2597 } else {
2598 deps.aidlPreprocess = sdkDep.aidl
2599 }
2600 }
2601
Jaewoong Jung26342642021-03-17 15:56:23 -07002602 return deps
2603}
2604
Joe Onorato349ae8d2024-02-05 22:46:00 +00002605// Provider for jarjar renaming rules.
2606//
2607// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2608// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2609// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2610// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2611// be renamed from that module.
2612// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002613type DependencyUse int
2614
2615const (
2616 RenameUseInvalid DependencyUse = iota
2617 RenameUseInclude
2618 RenameUseExclude
2619)
2620
2621type RenameUseElement struct {
2622 DepName string
2623 RenameUse DependencyUse
2624 Why string // token for determining where in the logic the decision was made.
2625}
2626
Joe Onorato349ae8d2024-02-05 22:46:00 +00002627type JarJarProviderData struct {
2628 // Mapping of class names: original --> renamed. If the value is "", the class will be
2629 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2630 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002631 Rename map[string]string
2632 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002633}
2634
2635func (this JarJarProviderData) GetDebugString() string {
2636 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002637 for _, k := range android.SortedKeys(this.Rename) {
2638 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002639 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2640 result += k + "--&gt;" + v + ";"
2641 }
2642 }
2643 return result
2644}
2645
2646var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2647
2648var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2649
2650func init() {
2651 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
Yu Liu26a716d2024-08-30 23:40:32 +00002652
2653 gob.Register(BaseJarJarProviderData{})
Joe Onorato349ae8d2024-02-05 22:46:00 +00002654}
2655
2656// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2657// whether they are java modules or not.
2658type BaseJarJarProviderData struct {
2659 JarJarProviderData JarJarProviderData
2660}
2661
2662func (this BaseJarJarProviderData) GetDebugString() string {
2663 return this.JarJarProviderData.GetDebugString()
2664}
2665
2666var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2667
2668// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2669// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2670// either JarJarProvider or BaseJarJarProvider.
2671func mergeJarJarPrefixes(ctx android.ModuleContext) {
2672 mod := ctx.Module()
2673 // Explicitly avoid propagating into some module types.
2674 switch reflect.TypeOf(mod).String() {
2675 case "*java.Droidstubs":
2676 return
2677 }
2678 jarJarData := collectDirectDepsProviders(ctx)
2679 if jarJarData != nil {
2680 providerData := BaseJarJarProviderData{
2681 JarJarProviderData: *jarJarData,
2682 }
2683 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2684 }
2685
2686}
2687
2688// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2689func (module *Module) addJarJarRenameRule(original string, renamed string) {
2690 if module.jarjarRenameRules == nil {
2691 module.jarjarRenameRules = make(map[string]string)
2692 }
2693 module.jarjarRenameRules[original] = renamed
2694}
2695
2696func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2697 // Gather repackage information from deps
2698 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002699
2700 module := ctx.Module()
2701 moduleName := module.Name()
2702
Colin Cross648daea2024-09-12 14:35:29 -07002703 ctx.VisitDirectDeps(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002704 tag := ctx.OtherModuleDependencyTag(m)
2705 // This logic mirrors that in (*Module).collectDeps above. There are several places
2706 // where we explicitly return RenameUseExclude, even though it is the default, to
2707 // indicate that it has been verified to be the case.
2708 //
2709 // Note well: there are probably cases that are getting to the unconditional return
2710 // and are therefore wrong.
2711 shouldIncludeRenames := func() (DependencyUse, string) {
2712 if moduleName == m.Name() {
2713 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2714 }
2715 if sc, ok := module.(android.SdkContext); ok {
2716 if ctx.Device() {
2717 sdkDep := decodeSdkDep(ctx, sc)
2718 if !sdkDep.invalidVersion && sdkDep.useFiles {
2719 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002720 }
2721 }
LaMont Jones63683e42024-02-08 14:30:45 -08002722 }
2723 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2724 return RenameUseExclude, "tags"
2725 }
2726 if _, ok := m.(SdkLibraryDependency); ok {
2727 switch tag {
2728 case sdkLibTag, libTag:
2729 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2730 }
2731 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2732 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2733 switch ji.StubsLinkType {
2734 case Stubs:
2735 return RenameUseExclude, "info"
2736 case Implementation:
2737 return RenameUseInclude, "info"
2738 default:
LaMont Jones09721862024-06-11 10:30:50 -07002739 //fmt.Printf("collectDirectDepsProviders: %v -> %v StubsLinkType unknown\n", module, m)
LaMont Jones63683e42024-02-08 14:30:45 -08002740 // Fall through to the heuristic logic.
2741 }
2742 switch reflect.TypeOf(m).String() {
2743 case "*java.GeneratedJavaLibraryModule":
2744 // Probably a java_aconfig_library module.
2745 // TODO: make this check better.
2746 return RenameUseInclude, "reflect"
2747 }
2748 switch tag {
2749 case bootClasspathTag:
2750 return RenameUseExclude, "tagswitch"
2751 case sdkLibTag, libTag, instrumentationForTag:
2752 return RenameUseInclude, "tagswitch"
2753 case java9LibTag:
2754 return RenameUseExclude, "tagswitch"
2755 case staticLibTag:
2756 return RenameUseInclude, "tagswitch"
2757 case pluginTag:
2758 return RenameUseInclude, "tagswitch"
2759 case errorpronePluginTag:
2760 return RenameUseInclude, "tagswitch"
2761 case exportedPluginTag:
2762 return RenameUseInclude, "tagswitch"
LaMont Jones63683e42024-02-08 14:30:45 -08002763 case kotlinPluginTag:
2764 return RenameUseInclude, "tagswitch"
2765 default:
2766 return RenameUseExclude, "tagswitch"
2767 }
2768 } else if _, ok := m.(android.SourceFileProducer); ok {
2769 switch tag {
2770 case sdkLibTag, libTag, staticLibTag:
2771 return RenameUseInclude, "srcfile"
2772 default:
2773 return RenameUseExclude, "srcfile"
2774 }
Yu Liu67a28422024-03-05 00:36:31 +00002775 } else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
Jihoon Kang03d014f2024-02-16 22:22:18 +00002776 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002777 } else {
2778 switch tag {
2779 case bootClasspathTag:
2780 return RenameUseExclude, "else"
2781 case systemModulesTag:
2782 return RenameUseInclude, "else"
2783 }
2784 }
2785 // If we got here, choose the safer option, which may lead to a build failure, rather
2786 // than runtime failures on the device.
2787 return RenameUseExclude, "end"
2788 }
2789
2790 if result == nil {
2791 result = &JarJarProviderData{
2792 Rename: make(map[string]string),
2793 RenameUse: make([]RenameUseElement, 0),
2794 }
2795 }
2796 how, why := shouldIncludeRenames()
2797 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2798 if how != RenameUseInclude {
2799 // Nothing to merge.
2800 return
2801 }
2802
2803 merge := func(theirs *JarJarProviderData) {
2804 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002805 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2806 result.Rename[orig] = renamed
2807 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2808 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2809 result.Rename[orig] = renamed
2810 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2811 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2812 continue
2813 }
2814 }
2815 }
2816 }
2817 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2818 merge(&theirs)
2819 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2820 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2821 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2822 // to java.Module.
2823 merge(&theirs.JarJarProviderData)
2824 }
2825 })
2826 return
2827}
2828
2829func (this Module) GetDebugString() string {
2830 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2831}
2832
2833// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2834// us, and if it's been set, apply the jarjar_prefix property to rename them.
2835func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2836 // Gather repackage information from deps
2837 result := collectDirectDepsProviders(ctx)
2838
Joe Onoratoa5d17172024-07-20 17:39:56 -07002839 add := func(orig string, renamed string) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002840 if result == nil {
2841 result = &JarJarProviderData{
2842 Rename: make(map[string]string),
2843 }
2844 }
2845 if renamed != "" {
2846 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2847 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
Joe Onoratoa5d17172024-07-20 17:39:56 -07002848 return
Joe Onorato349ae8d2024-02-05 22:46:00 +00002849 }
2850 }
2851 (*result).Rename[orig] = renamed
2852 }
2853
Joe Onoratoa5d17172024-07-20 17:39:56 -07002854 // Update that with entries we've stored for ourself
2855 for orig, renamed := range module.jarjarRenameRules {
2856 add(orig, renamed)
2857 }
2858
2859 // Update that with entries given in the jarjar_rename property.
2860 for _, orig := range module.properties.Jarjar_rename {
2861 add(orig, "")
2862 }
2863
Joe Onorato349ae8d2024-02-05 22:46:00 +00002864 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2865 if result == nil {
2866 return nil
2867 }
2868
2869 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2870 // that have not yet been renamed.
2871 prefix := proptools.String(module.properties.Jarjar_prefix)
2872 if prefix != "" {
2873 if prefix[0] == '.' {
2874 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2875 return nil
2876 }
2877 if prefix[len(prefix)-1] == '.' {
2878 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2879 return nil
2880 }
2881
2882 var updated map[string]string
2883 for orig, renamed := range (*result).Rename {
2884 if renamed == "" {
2885 if updated == nil {
2886 updated = make(map[string]string)
2887 }
2888 updated[orig] = prefix + "." + orig
2889 }
2890 }
2891 for orig, renamed := range updated {
2892 (*result).Rename[orig] = renamed
2893 }
2894 }
2895
2896 return result
2897}
2898
2899// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2900// to "" won't be in this list because they shouldn't be renamed yet.
2901func getJarJarRuleText(provider *JarJarProviderData) string {
2902 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002903 for _, orig := range android.SortedKeys(provider.Rename) {
2904 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002905 if renamed != "" {
2906 result += "rule " + orig + " " + renamed + "\n"
2907 }
2908 }
2909 return result
2910}
2911
Zi Wangddb2ee52024-04-02 16:44:02 +00002912// Repackage the flags if the jarjar rule txt for the flags is generated
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002913func (j *Module) repackageFlagsIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Zi Wangddb2ee52024-04-02 16:44:02 +00002914 if j.repackageJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002915 return infile, false
Zi Wangddb2ee52024-04-02 16:44:02 +00002916 }
Colin Crossedec77c2024-07-26 15:25:40 -07002917 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", info, jarName)
Zi Wangddb2ee52024-04-02 16:44:02 +00002918 TransformJarJar(ctx, repackagedJarjarFile, infile, j.repackageJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002919 return repackagedJarjarFile, true
Zi Wangddb2ee52024-04-02 16:44:02 +00002920}
2921
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002922func (j *Module) jarjarIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Colin Crossedec77c2024-07-26 15:25:40 -07002923 if j.expandJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002924 return infile, false
Colin Crossedec77c2024-07-26 15:25:40 -07002925 }
2926 jarjarFile := android.PathForModuleOut(ctx, "jarjar", info, jarName)
2927 TransformJarJar(ctx, jarjarFile, infile, j.expandJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002928 return jarjarFile, true
Colin Crossedec77c2024-07-26 15:25:40 -07002929
2930}
2931
Jaewoong Jung26342642021-03-17 15:56:23 -07002932func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2933 deps.processorPath = append(deps.processorPath, pluginJars...)
2934 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2935}
2936
2937// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2938// this interface.
2939type ProvidesUsesLib interface {
2940 ProvidesUsesLib() *string
2941}
2942
2943func (j *Module) ProvidesUsesLib() *string {
2944 return j.usesLibraryProperties.Provides_uses_lib
2945}
satayev1c564cc2021-05-25 19:50:30 +01002946
2947type ModuleWithStem interface {
2948 Stem() string
2949}
2950
2951var _ ModuleWithStem = (*Module)(nil)
Jiakai Zhangf98da192024-04-15 11:15:41 +00002952
2953type ModuleWithUsesLibrary interface {
2954 UsesLibrary() *usesLibrary
2955}
2956
2957func (j *Module) UsesLibrary() *usesLibrary {
2958 return &j.usesLibrary
2959}
2960
2961var _ ModuleWithUsesLibrary = (*Module)(nil)