blob: efc6a748be57a1ae8e3e1a4beac68b4a8a4c1e9a [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
Cole Faust65cb40a2024-10-21 15:41:42 -070074 // Same as java_resources, but modules added here will use the device variant. Can be useful
75 // for making a host test that tests the contents of a device built app.
76 Device_common_java_resources []string `android:"path_device_common"`
77
78 // Same as java_resources, but modules added here will use the device's os variant and the
79 // device's first architecture variant. Can be useful for making a host test that tests the
80 // contents of a native device built app.
81 Device_first_java_resources []string `android:"path_device_first"`
82
Jaewoong Jung26342642021-03-17 15:56:23 -070083 // list of module-specific flags that will be used for javac compiles
84 Javacflags []string `android:"arch_variant"`
85
86 // list of module-specific flags that will be used for kotlinc compiles
87 Kotlincflags []string `android:"arch_variant"`
88
89 // list of java libraries that will be in the classpath
90 Libs []string `android:"arch_variant"`
91
92 // list of java libraries that will be compiled into the resulting jar
Cole Faustb7493472024-08-28 11:55:52 -070093 Static_libs proptools.Configurable[[]string] `android:"arch_variant"`
Jaewoong Jung26342642021-03-17 15:56:23 -070094
95 // manifest file to be included in resulting jar
96 Manifest *string `android:"path"`
97
98 // if not blank, run jarjar using the specified rules file
99 Jarjar_rules *string `android:"path,arch_variant"`
100
Joe Onoratoa5d17172024-07-20 17:39:56 -0700101 // java class names to rename with jarjar when a reverse dependency has a jarjar_prefix
102 // property.
103 Jarjar_rename []string
104
Joe Onorato349ae8d2024-02-05 22:46:00 +0000105 // if not blank, used as prefix to generate repackage rule
106 Jarjar_prefix *string
107
Jaewoong Jung26342642021-03-17 15:56:23 -0700108 // If not blank, set the java version passed to javac as -source and -target
109 Java_version *string
110
111 // If set to true, allow this module to be dexed and installed on devices. Has no
112 // effect on host modules, which are always considered installable.
113 Installable *bool
114
115 // If set to true, include sources used to compile the module in to the final jar
116 Include_srcs *bool
117
118 // If not empty, classes are restricted to the specified packages and their sub-packages.
119 // This restriction is checked after applying jarjar rules and including static libs.
120 Permitted_packages []string
121
122 // List of modules to use as annotation processors
123 Plugins []string
124
125 // List of modules to export to libraries that directly depend on this library as annotation
126 // processors. Note that if the plugins set generates_api: true this will disable the turbine
127 // optimization on modules that depend on this module, which will reduce parallelism and cause
128 // more recompilation.
129 Exported_plugins []string
130
131 // The number of Java source entries each Javac instance can process
132 Javac_shard_size *int64
133
134 // Add host jdk tools.jar to bootclasspath
135 Use_tools_jar *bool
136
137 Openjdk9 struct {
138 // List of source files that should only be used when passing -source 1.9 or higher
139 Srcs []string `android:"path"`
140
141 // List of javac flags that should only be used when passing -source 1.9 or higher
142 Javacflags []string
143 }
144
145 // When compiling language level 9+ .java code in packages that are part of
146 // a system module, patch_module names the module that your sources and
147 // dependencies should be patched into. The Android runtime currently
148 // doesn't implement the JEP 261 module system so this option is only
149 // supported at compile time. It should only be needed to compile tests in
150 // packages that exist in libcore and which are inconvenient to move
151 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400152 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700153
154 Jacoco struct {
155 // List of classes to include for instrumentation with jacoco to collect coverage
156 // information at runtime when building with coverage enabled. If unset defaults to all
157 // classes.
158 // Supports '*' as the last character of an entry in the list as a wildcard match.
159 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
160 // it matches classes in the package that have the class name as a prefix.
161 Include_filter []string
162
163 // List of classes to exclude from instrumentation with jacoco to collect coverage
164 // information at runtime when building with coverage enabled. Overrides classes selected
165 // by the include_filter property.
166 // Supports '*' as the last character of an entry in the list as a wildcard match.
167 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
168 // it matches classes in the package that have the class name as a prefix.
169 Exclude_filter []string
170 }
171
172 Errorprone struct {
173 // List of javac flags that should only be used when running errorprone.
174 Javacflags []string
175
176 // List of java_plugin modules that provide extra errorprone checks.
177 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700178
Cole Faust2b1536e2021-06-18 12:25:54 -0700179 // This property can be in 3 states. When set to true, errorprone will
180 // be run during the regular build. When set to false, errorprone will
181 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
182 // environment variable is true. Setting this to false will improve build
183 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700184 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700185 }
186
187 Proto struct {
188 // List of extra options that will be passed to the proto generator.
189 Output_params []string
190 }
191
Sam Delmericoc7593722022-08-31 15:57:52 -0400192 // If true, then jacocoagent is automatically added as a libs dependency so that
193 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700194 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000195 // If true, then the module supports statically including the jacocoagent
196 // into the library.
197 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700198
199 // List of files to include in the META-INF/services folder of the resulting jar.
200 Services []string `android:"path,arch_variant"`
201
202 // If true, package the kotlin stdlib into the jar. Defaults to true.
203 Static_kotlin_stdlib *bool `android:"arch_variant"`
204
205 // A list of java_library instances that provide additional hiddenapi annotations for the library.
206 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700207
208 // Additional srcJars tacked in by GeneratedJavaLibraryModule
209 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000210
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000211 // intermediate aconfig cache file tacked in by GeneratedJavaLibraryModule
212 Aconfig_Cache_files []android.Path `android:"mutated"`
213
Mark Whitea15790a2023-08-22 21:28:11 +0000214 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400215 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800216
217 // A list of files or dependencies to make available to the build sandbox. This is
218 // useful if source files are symlinks, the targets of the symlinks must be listed here.
219 // Note that currently not all actions implemented by android_apps are sandboxed, so you
220 // may only see this being necessary in lint builds.
221 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000222
223 // Property signifying whether the module compiles stubs or not.
224 // Should be set to true when srcs of this module are stub files.
225 // This property does not need to be set to true when the module depends on
226 // the stubs via libs, but should be set to true when the module depends on
227 // the stubs via static libs.
228 Is_stubs_module *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700229
Makoto Onuki7ded3822024-03-28 14:42:20 -0700230 Ravenizer struct {
John Wu989ee842024-10-04 00:21:43 +0000231 // If true, enable the "Ravenizer" tool on the output jar.
232 // "Ravenizer" is a tool for Ravenwood tests, but it can also be enabled on other kinds
233 // of java targets.
Makoto Onuki7ded3822024-03-28 14:42:20 -0700234 Enabled *bool
John Wu989ee842024-10-04 00:21:43 +0000235
236 // If true, the "Ravenizer" tool will remove all Mockito and DexMaker
237 // classes from the output jar.
238 Strip_mockito *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700239 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +0000240
241 // Contributing api surface of the stub module. Is not visible to bp modules, and should
242 // only be set for stub submodules generated by the java_sdk_library
243 Stub_contributing_api *string `blueprint:"mutated"`
Yihan Dong8be09c22024-08-29 15:32:13 +0800244
245 // If true, enable the "ApiMapper" tool on the output jar. "ApiMapper" is a tool to inject
246 // bytecode to log API calls.
247 ApiMapper bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700248}
249
250// Properties that are specific to device modules. Host module factories should not add these when
251// constructing a new module.
252type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000253 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000254 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000255 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000256 // 1) numerical API level, "current", "none", or "core_platform"
257 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
258 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
259 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700260 Sdk_version *string
261
satayev0a420e72021-11-29 17:25:52 +0000262 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
263 // Defaults to empty string "". See sdk_version for possible values.
264 Max_sdk_version *string
265
William Loh5a082f92022-05-17 20:21:50 +0000266 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
267 // Defaults to empty string "". See sdk_version for possible values.
268 Replace_max_sdk_version_placeholder *string
269
Jaewoong Jung26342642021-03-17 15:56:23 -0700270 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000271 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700272 Target_sdk_version *string
273
274 // Whether to compile against the platform APIs instead of an SDK.
275 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000276 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700277 Platform_apis *bool
278
279 Aidl struct {
280 // Top level directories to pass to aidl tool
281 Include_dirs []string
282
283 // Directories rooted at the Android.bp file to pass to aidl tool
284 Local_include_dirs []string
285
286 // directories that should be added as include directories for any aidl sources of modules
287 // that depend on this module, as well as to aidl for this module.
288 Export_include_dirs []string
289
290 // whether to generate traces (for systrace) for this interface
291 Generate_traces *bool
292
293 // whether to generate Binder#GetTransaction name method.
294 Generate_get_transaction_name *bool
295
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100296 // whether all interfaces should be annotated with required permissions.
297 Enforce_permissions *bool
298
299 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
300 Enforce_permissions_exceptions []string `android:"path"`
301
Jaewoong Jung26342642021-03-17 15:56:23 -0700302 // list of flags that will be passed to the AIDL compiler
303 Flags []string
304 }
305
306 // If true, export a copy of the module as a -hostdex module for host testing.
307 Hostdex *bool
308
309 Target struct {
310 Hostdex struct {
311 // Additional required dependencies to add to -hostdex modules.
312 Required []string
313 }
314 }
315
316 // When targeting 1.9 and above, override the modules to use with --system,
317 // otherwise provides defaults libraries to add to the bootclasspath.
318 System_modules *string
319
Jaewoong Jung26342642021-03-17 15:56:23 -0700320 IsSDKLibrary bool `blueprint:"mutated"`
321
322 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
323 // Defaults to false.
324 V4_signature *bool
325
326 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
327 // public stubs library.
328 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000329
330 HiddenAPIPackageProperties
331 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700332}
333
yangbill2af0b6e2024-03-15 09:29:29 +0000334// Properties that can be overridden by overriding module (e.g. override_android_app)
335type OverridableProperties struct {
Jooyung Han01d80d82022-01-08 12:16:32 +0900336 // set the name of the output. If not set, `name` is used.
337 // To override a module with this property set, overriding module might need to set this as well.
338 // Otherwise, both the overridden and the overriding modules will have the same output name, which
339 // can cause the duplicate output error.
340 Stem *string
Spandan Dasb9c58352024-05-13 18:29:45 +0000341
342 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
343 // Defaults to sdk_version if not set. See sdk_version for possible values.
344 Min_sdk_version *string
Jooyung Han01d80d82022-01-08 12:16:32 +0900345}
346
Jaewoong Jung26342642021-03-17 15:56:23 -0700347// Functionality common to Module and Import
348//
349// It is embedded in Module so its functionality can be used by methods in Module
350// but it is currently only initialized by Import and Library.
351type embeddableInModuleAndImport struct {
352
353 // Functionality related to this being used as a component of a java_sdk_library.
354 EmbeddableSdkLibraryComponent
355}
356
Paul Duffin71b33cc2021-06-23 11:39:47 +0100357func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
358 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700359}
360
361// Module/Import's DepIsInSameApex(...) delegates to this method.
362//
363// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
364// the one provided by ApexModuleBase.
365func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
366 // dependencies other than the static linkage are all considered crossing APEX boundary
367 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
368 return true
369 }
370 return false
371}
372
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100373// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
374// or an invalid path describing the reason it is invalid.
375//
376// It is unset if a dex jar isn't applicable, i.e. no build rule has been
377// requested to create one.
378//
379// If a dex jar has been requested to be built then it is set, and it may be
380// either a valid android.Path, or invalid with a reason message. The latter
381// happens if the source that should produce the dex file isn't able to.
382//
383// E.g. it is invalid with a reason message if there is a prebuilt APEX that
384// could produce the dex jar through a deapexer module, but the APEX isn't
385// installable so doing so wouldn't be safe.
386type OptionalDexJarPath struct {
387 isSet bool
388 path android.OptionalPath
389}
390
391// IsSet returns true if a path has been set, either invalid or valid.
392func (o OptionalDexJarPath) IsSet() bool {
393 return o.isSet
394}
395
396// Valid returns true if there is a path that is valid.
397func (o OptionalDexJarPath) Valid() bool {
398 return o.isSet && o.path.Valid()
399}
400
401// Path returns the valid path, or panics if it's either not set or is invalid.
402func (o OptionalDexJarPath) Path() android.Path {
403 if !o.isSet {
404 panic("path isn't set")
405 }
406 return o.path.Path()
407}
408
409// PathOrNil returns the path if it's set and valid, or else nil.
410func (o OptionalDexJarPath) PathOrNil() android.Path {
411 if o.Valid() {
412 return o.Path()
413 }
414 return nil
415}
416
417// InvalidReason returns the reason for an invalid path, which is never "". It
418// returns "" for an unset or valid path.
419func (o OptionalDexJarPath) InvalidReason() string {
420 if !o.isSet {
421 return ""
422 }
423 return o.path.InvalidReason()
424}
425
426func (o OptionalDexJarPath) String() string {
427 if !o.isSet {
428 return "<unset>"
429 }
430 return o.path.String()
431}
432
433// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
434func makeUnsetDexJarPath() OptionalDexJarPath {
435 return OptionalDexJarPath{isSet: false}
436}
437
438// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
439// the given OptionalPath, which may be valid or invalid.
440func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
441 return OptionalDexJarPath{isSet: true, path: path}
442}
443
444// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
445// valid given path. It returns an unset OptionalDexJarPath if the given path is
446// nil.
447func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
448 if path == nil {
449 return makeUnsetDexJarPath()
450 }
451 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
452}
453
Jaewoong Jung26342642021-03-17 15:56:23 -0700454// Module contains the properties and members used by all java module types
455type Module struct {
456 android.ModuleBase
457 android.DefaultableModuleBase
458 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700459
460 // Functionality common to Module and Import.
461 embeddableInModuleAndImport
462
463 properties CommonProperties
464 protoProperties android.ProtoProperties
465 deviceProperties DeviceProperties
466
yangbill2af0b6e2024-03-15 09:29:29 +0000467 overridableProperties OverridableProperties
Ronald Braunsteincdc66f42024-04-12 11:23:19 -0700468 sourceProperties android.SourceProperties
Jooyung Han01d80d82022-01-08 12:16:32 +0900469
Jaewoong Jung26342642021-03-17 15:56:23 -0700470 // jar file containing header classes including static library dependencies, suitable for
471 // inserting into the bootclasspath/classpath of another compile
472 headerJarFile android.Path
473
474 // jar file containing implementation classes including static library dependencies but no
475 // resources
476 implementationJarFile android.Path
477
Jaewoong Jung26342642021-03-17 15:56:23 -0700478 // args and dependencies to package source files into a srcjar
479 srcJarArgs []string
480 srcJarDeps android.Paths
481
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000482 // the source files of this module and all its static dependencies
483 transitiveSrcFiles *android.DepSet[android.Path]
484
Jaewoong Jung26342642021-03-17 15:56:23 -0700485 // jar file containing implementation classes and resources including static library
486 // dependencies
487 implementationAndResourcesJar android.Path
488
489 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100490 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700491
492 // output file containing uninstrumented classes that will be instrumented by jacoco
493 jacocoReportClassesFile android.Path
494
495 // output file of the module, which may be a classes jar or a dex jar
496 outputFile android.Path
497 extraOutputFiles android.Paths
498
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100499 exportAidlIncludeDirs android.Paths
500 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700501
502 logtagsSrcs android.Paths
503
504 // installed file for binary dependency
505 installFile android.Path
506
Colin Cross3108ce12021-11-10 14:38:50 -0800507 // installed file for hostdex copy
508 hostdexInstallFile android.InstallPath
509
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800510 // list of unique .java and .kt source files
511 uniqueSrcFiles android.Paths
512
513 // list of srcjars that was passed to javac
514 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700515
516 // manifest file to use instead of properties.Manifest
517 overrideManifest android.OptionalPath
518
Jaewoong Jung26342642021-03-17 15:56:23 -0700519 // list of plugins that this java module is exporting
520 exportedPluginJars android.Paths
521
522 // list of plugins that this java module is exporting
523 exportedPluginClasses []string
524
525 // if true, the exported plugins generate API and require disabling turbine.
526 exportedDisableTurbine bool
527
528 // list of source files, collected from srcFiles with unique java and all kt files,
529 // will be used by android.IDEInfo struct
530 expandIDEInfoCompiledSrcs []string
531
532 // expanded Jarjar_rules
533 expandJarjarRules android.Path
534
Joe Onorato349ae8d2024-02-05 22:46:00 +0000535 // jarjar rule for inherited jarjar rules
536 repackageJarjarRules android.Path
537
Jaewoong Jung26342642021-03-17 15:56:23 -0700538 // Extra files generated by the module type to be added as java resources.
539 extraResources android.Paths
540
541 hiddenAPI
542 dexer
543 dexpreopter
544 usesLibrary
545 linter
546
547 // list of the xref extraction files
Spandan Das1028d5a2024-08-19 21:45:48 +0000548 kytheFiles android.Paths
549 kytheKotlinFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700550
Jaewoong Jung26342642021-03-17 15:56:23 -0700551 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900552
553 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000554 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000555 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400556
557 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000558
559 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000560
561 // output file name based on Stem property.
562 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
563 // or the module should override Stem().
564 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700565
Joe Onorato349ae8d2024-02-05 22:46:00 +0000566 // Values that will be set in the JarJarProvider data for jarjar repackaging,
567 // and merged with our dependencies' rules.
568 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000569
570 stubsLinkType StubsLinkType
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000571
572 // Paths to the aconfig intermediate cache files that are provided by the
573 // java_aconfig_library or java_library modules that are statically linked
574 // to this module. Does not contain cache files from all transitive dependencies.
575 aconfigCacheFiles android.Paths
Spandan Das8aac9932024-07-18 23:14:13 +0000576
577 // List of soong module dependencies required to compile the current module.
578 // This information is printed out to `Dependencies` field in module_bp_java_deps.json
579 compileDepNames []string
Makoto Onuki7ded3822024-03-28 14:42:20 -0700580
581 ravenizer struct {
582 enabled bool
583 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700584}
585
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000586var _ android.InstallableModule = (*Module)(nil)
587
588// To satisfy the InstallableModule interface
Jihoon Kang224ea082024-08-12 22:38:16 +0000589func (j *Module) StaticDependencyTags() []blueprint.DependencyTag {
590 return []blueprint.DependencyTag{staticLibTag}
591}
592
593// To satisfy the InstallableModule interface
594func (j *Module) DynamicDependencyTags() []blueprint.DependencyTag {
595 return []blueprint.DependencyTag{libTag, sdkLibTag, bootClasspathTag, systemModulesTag,
596 instrumentationForTag, java9LibTag}
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000597}
598
599// Overrides android.ModuleBase.InstallInProduct()
600func (j *Module) InstallInProduct() bool {
601 return j.ProductSpecific()
602}
603
Jihoon Kang85bc1932024-07-01 17:04:46 +0000604var _ android.StubsAvailableModule = (*Module)(nil)
605
606// To safisfy the StubsAvailableModule interface
607func (j *Module) IsStubsModule() bool {
608 return proptools.Bool(j.properties.Is_stubs_module)
609}
610
Jiyong Park92315372021-04-02 08:45:46 +0900611func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
612 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900613 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700614 return nil
615 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900616 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000617 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700618 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
619 } else {
620 // Treat stable core platform as stable.
621 return nil
622 }
623 } else {
624 return fmt.Errorf("non stable SDK %v", sdkVersion)
625 }
626}
627
628// checkSdkVersions enforces restrictions around SDK dependencies.
629func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
630 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900631 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900632 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700633 ctx.PropertyErrorf("sdk_version",
634 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
635 }
636 }
637 }
638
639 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
640 // See rank() for details.
641 ctx.VisitDirectDeps(func(module android.Module) {
642 tag := ctx.OtherModuleDependencyTag(module)
643 switch module.(type) {
644 // TODO(satayev): cover other types as well, e.g. imports
645 case *Library, *AndroidLibrary:
646 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400647 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700648 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
649 }
650 }
651 })
652}
653
654func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900655 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700656 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900657 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700658 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000659 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 -0700660 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000661 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 -0700662 }
663
664 }
665}
666
Mark Whitea15790a2023-08-22 21:28:11 +0000667func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
668 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400669 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000670 installable := proptools.Bool(j.properties.Installable)
671
672 if headersOnly && installable {
673 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.")
674 }
675 }
676}
677
Jaewoong Jung26342642021-03-17 15:56:23 -0700678func (j *Module) addHostProperties() {
679 j.AddProperties(
680 &j.properties,
yangbill2af0b6e2024-03-15 09:29:29 +0000681 &j.overridableProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700682 &j.protoProperties,
683 &j.usesLibraryProperties,
684 )
685}
686
687func (j *Module) addHostAndDeviceProperties() {
688 j.addHostProperties()
689 j.AddProperties(
690 &j.deviceProperties,
691 &j.dexer.dexProperties,
692 &j.dexpreoptProperties,
693 &j.linter.properties,
694 )
695}
696
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000697// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
698// makes it available through the hiddenAPIPropertyInfoProvider.
699func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
700 hiddenAPIInfo := newHiddenAPIPropertyInfo()
701
702 // Populate with flag file paths from the properties.
703 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
704
705 // Populate with package rules from the properties.
706 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
707
Colin Cross40213022023-12-13 15:19:49 -0800708 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000709}
710
mrziwang9f7b9f42024-07-10 12:18:06 -0700711// helper method for java modules to set OutputFilesProvider
712func setOutputFiles(ctx android.ModuleContext, m Module) {
713 ctx.SetOutputFiles(append(android.Paths{m.outputFile}, m.extraOutputFiles...), "")
714 ctx.SetOutputFiles(android.Paths{m.outputFile}, android.DefaultDistTag)
715 ctx.SetOutputFiles(android.Paths{m.implementationAndResourcesJar}, ".jar")
716 ctx.SetOutputFiles(android.Paths{m.headerJarFile}, ".hjar")
717 if m.dexer.proguardDictionary.Valid() {
718 ctx.SetOutputFiles(android.Paths{m.dexer.proguardDictionary.Path()}, ".proguard_map")
719 }
720 ctx.SetOutputFiles(m.properties.Generated_srcjars, ".generated_srcjars")
Jaewoong Jung26342642021-03-17 15:56:23 -0700721}
722
Jaewoong Jung26342642021-03-17 15:56:23 -0700723func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
724 initJavaModule(module, hod, false)
725}
726
727func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
728 initJavaModule(module, hod, true)
729}
730
731func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
732 multilib := android.MultilibCommon
733 if multiTargets {
734 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
735 } else {
736 android.InitAndroidArchModule(module, hod, multilib)
737 }
738 android.InitDefaultableModule(module)
739}
740
741func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
742 return j.properties.Instrument &&
743 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
744 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
745}
746
Yihan Dong8be09c22024-08-29 15:32:13 +0800747func (j *Module) shouldApiMapper() bool {
748 return j.properties.ApiMapper
749}
750
Jaewoong Jung26342642021-03-17 15:56:23 -0700751func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000752 return j.properties.Supports_static_instrumentation &&
753 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700754 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
755 ctx.Config().UnbundledBuild())
756}
757
758func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
759 // Force enable the instrumentation for java code that is built for APEXes ...
760 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
761 // 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 -0800762 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700763 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
Jihoon Kang690df2e2024-05-22 04:27:38 +0000764
Jihoon Kang46d66de2024-05-22 22:42:39 +0000765 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700766 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
767 return true
768 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
769 return true
770 }
771 }
772 return false
773}
774
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400775func (j *Module) setInstrument(value bool) {
776 j.properties.Instrument = value
777}
778
Yihan Dong8be09c22024-08-29 15:32:13 +0800779func (j *Module) setApiMapper(value bool) {
780 j.properties.ApiMapper = value
781}
782
Jiyong Park92315372021-04-02 08:45:46 +0900783func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
784 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700785}
786
Jiyong Parkf1691d22021-03-29 20:11:58 +0900787func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700788 return proptools.String(j.deviceProperties.System_modules)
789}
790
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000791func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Spandan Dasb9c58352024-05-13 18:29:45 +0000792 if j.overridableProperties.Min_sdk_version != nil {
793 return android.ApiLevelFrom(ctx, *j.overridableProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700794 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000795 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700796}
797
Yu Liuf2b94012023-09-19 15:09:10 -0700798func (j *Module) GetDeviceProperties() *DeviceProperties {
799 return &j.deviceProperties
800}
801
Spandan Dasa26eda72023-03-02 00:56:06 +0000802func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
803 if j.deviceProperties.Max_sdk_version != nil {
804 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
805 }
806 // Default is PrivateApiLevel
807 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000808}
809
Spandan Dasa26eda72023-03-02 00:56:06 +0000810func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
811 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
812 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
813 }
814 // Default is PrivateApiLevel
815 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000816}
817
Jiyong Parkf1691d22021-03-29 20:11:58 +0900818func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000819 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900820}
821
Spandan Dasca70fc42023-03-01 23:38:49 +0000822func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900823 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000824 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900825 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000826 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700827}
828
829func (j *Module) AvailableFor(what string) bool {
830 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
831 // Exception: for hostdex: true libraries, the platform variant is created
832 // even if it's not marked as available to platform. In that case, the platform
833 // variant is used only for the hostdex and not installed to the device.
834 return true
835 }
836 return j.ApexModuleBase.AvailableFor(what)
837}
838
Cole Faustb7493472024-08-28 11:55:52 -0700839func (j *Module) staticLibs(ctx android.BaseModuleContext) []string {
Jihoon Kang8bce3812024-09-30 18:46:51 +0000840 return j.properties.Static_libs.GetOrDefault(ctx, nil)
Cole Faustb7493472024-08-28 11:55:52 -0700841}
842
Jaewoong Jung26342642021-03-17 15:56:23 -0700843func (j *Module) deps(ctx android.BottomUpMutatorContext) {
844 if ctx.Device() {
845 j.linter.deps(ctx)
846
Jiyong Parkf1691d22021-03-29 20:11:58 +0900847 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700848
849 if j.deviceProperties.SyspropPublicStub != "" {
850 // This is a sysprop implementation library that has a corresponding sysprop public
851 // stubs library, and a dependency on it so that dependencies on the implementation can
852 // be forwarded to the public stubs library when necessary.
853 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
854 }
855 }
856
857 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000858
Cole Faustb7493472024-08-28 11:55:52 -0700859 ctx.AddVariationDependencies(nil, staticLibTag, j.staticLibs(ctx)...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700860
861 // Add dependency on libraries that provide additional hidden api annotations.
862 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
863
Jaewoong Jung26342642021-03-17 15:56:23 -0700864 // For library dependencies that are component libraries (like stubs), add the implementation
865 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
866 for _, dep := range libDeps {
867 if dep != nil {
868 if component, ok := dep.(SdkLibraryComponentDependency); ok {
869 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +0000870 // Add library as optional if it's one of the optional compatibility libs or it's
871 // explicitly listed in the optional_uses_libs property.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100872 tag := usesLibReqTag
Jiakai Zhangf98da192024-04-15 11:15:41 +0000873 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) ||
874 android.InList(*lib, j.usesLibrary.usesLibraryProperties.Optional_uses_libs) {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100875 tag = usesLibOptTag
876 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100877 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700878 }
879 }
880 }
881 }
882
883 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
884 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
885 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
886
887 android.ProtoDeps(ctx, &j.protoProperties)
888 if j.hasSrcExt(".proto") {
889 protoDeps(ctx, &j.protoProperties)
890 }
891
892 if j.hasSrcExt(".kt") {
893 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
894 // Kotlin files
Colin Cross882d6002024-08-14 10:24:06 -0700895 tag := staticLibTag
896 if !BoolDefault(j.properties.Static_kotlin_stdlib, true) {
897 tag = libTag
898 }
899 ctx.AddVariationDependencies(nil, tag,
900 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700901 }
902
903 // Framework libraries need special handling in static coverage builds: they should not have
904 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
905 // the same jacoco classes coming from different bootclasspath jars.
906 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
907 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
908 j.properties.Instrument = true
909 }
910 } else if j.shouldInstrumentStatic(ctx) {
911 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
912 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700913
Cole Faustb7493472024-08-28 11:55:52 -0700914 if j.useCompose(ctx) {
Colin Crossa1ff7c62021-09-17 14:11:52 -0700915 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
916 "androidx.compose.compiler_compiler-hosted")
917 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700918}
919
920func hasSrcExt(srcs []string, ext string) bool {
921 for _, src := range srcs {
922 if filepath.Ext(src) == ext {
923 return true
924 }
925 }
926
927 return false
928}
929
930func (j *Module) hasSrcExt(ext string) bool {
931 return hasSrcExt(j.properties.Srcs, ext)
932}
933
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100934func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
935 var flags string
936
937 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
938 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
939 flags = "-Wmissing-permission-annotation -Werror"
940 }
941 }
942 return flags
943}
944
Jaewoong Jung26342642021-03-17 15:56:23 -0700945func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000946 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700947
948 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
949 aidlIncludes = append(aidlIncludes,
950 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
951 aidlIncludes = append(aidlIncludes,
952 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
953
954 var flags []string
955 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000956 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700957
958 flags = append(flags, j.deviceProperties.Aidl.Flags...)
959
960 if aidlPreprocess.Valid() {
961 flags = append(flags, "-p"+aidlPreprocess.String())
962 deps = append(deps, aidlPreprocess.Path())
963 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000964 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700965 }
966
967 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000968 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700969 }
970
971 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000972 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700973 }
974
Sam Delmerico2351eac2022-05-24 17:10:02 +0000975 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700976 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000977 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700978 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000979 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
980 // add flags for dirs containing AIDL srcs that haven't been specified yet
981 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700982
Zim8774ae12022-08-17 11:46:34 +0100983 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000984 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100985 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700986 flags = append(flags, "-t")
987 }
988
989 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
990 flags = append(flags, "--transaction_names")
991 }
992
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100993 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
994 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
995 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
996 }
997
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000998 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900999 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
1000
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 return strings.Join(flags, " "), deps
1002}
1003
1004func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
1005
1006 var flags javaBuilderFlags
1007
1008 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +09001009 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001010
Cole Faust2b1536e2021-06-18 12:25:54 -07001011 epEnabled := j.properties.Errorprone.Enabled
1012 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +01001013 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001014 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
1015 }
1016
1017 errorProneFlags := []string{
1018 "-Xplugin:ErrorProne",
1019 "${config.ErrorProneChecks}",
1020 }
1021 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
1022
Colin Cross8bf6cad2022-02-28 13:07:03 -08001023 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -07001024 "'" + strings.Join(errorProneFlags, " ") + "'"
1025 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
1026 }
1027
1028 // classpath
1029 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
1030 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001031 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001032 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
1033 flags.processorPath = append(flags.processorPath, deps.processorPath...)
1034 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
1035
1036 flags.processors = append(flags.processors, deps.processorClasses...)
1037 flags.processors = android.FirstUniqueStrings(flags.processors)
1038
1039 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001040 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001041 // Give host-side tools a version of OpenJDK's standard libraries
1042 // close to what they're targeting. As of Dec 2017, AOSP is only
1043 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1044 //
1045 // When building with OpenJDK 8, the following should have no
1046 // effect since those jars would be available by default.
1047 //
1048 // When building with OpenJDK 9 but targeting a version < 1.8,
1049 // putting them on the bootclasspath means that:
1050 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1051 // b) references to existing APIs are not reinterpreted in an
1052 // OpenJDK 9-specific way, eg. calls to subclasses of
1053 // java.nio.Buffer as in http://b/70862583
1054 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1055 flags.bootClasspath = append(flags.bootClasspath,
1056 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1057 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1058 if Bool(j.properties.Use_tools_jar) {
1059 flags.bootClasspath = append(flags.bootClasspath,
1060 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1061 }
1062 }
1063
1064 // systemModules
1065 flags.systemModules = deps.systemModules
1066
Jaewoong Jung26342642021-03-17 15:56:23 -07001067 return flags
1068}
1069
1070func (j *Module) collectJavacFlags(
1071 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1072 // javac flags.
1073 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001074 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001075
Mythri Alle4b9f6182023-10-25 15:17:11 +00001076 needsDebugInfo = false
1077 for _, flag := range javacFlags {
1078 if strings.HasPrefix(flag, "-g") {
1079 needsDebugInfo = true
1080 }
1081 }
1082
1083 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001084 // For non-host binaries, override the -g flag passed globally to remove
1085 // local variable debug info to reduce disk and memory usage.
1086 javacFlags = append(javacFlags, "-g:source,lines")
1087 }
1088 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1089
1090 if flags.javaVersion.usesJavaModules() {
1091 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001092 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1093 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1094 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1095 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001096
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001097 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001098 if j.properties.Patch_module != nil {
1099 // Manually specify build directory in case it is not under the repo root.
1100 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1101 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001102 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001103
Jaewoong Jung26342642021-03-17 15:56:23 -07001104 classPath := flags.classpath.FormJavaClassPath("")
1105 if classPath != "" {
1106 patchPaths = append(patchPaths, classPath)
1107 }
1108 javacFlags = append(
1109 javacFlags,
1110 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1111 }
1112 }
1113
1114 if len(javacFlags) > 0 {
1115 // optimization.
1116 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1117 flags.javacFlags = "$javacFlags"
1118 }
1119
1120 return flags
1121}
1122
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001123func (j *Module) AddJSONData(d *map[string]interface{}) {
1124 (&j.ModuleBase).AddJSONData(d)
1125 (*d)["Java"] = map[string]interface{}{
1126 "SourceExtensions": j.sourceExtensions,
1127 }
1128
1129}
1130
usta0391ca42023-09-19 15:51:59 -04001131func (j *Module) addGeneratedSrcJars(path android.Path) {
1132 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001133}
1134
Colin Crossfdaa6722024-08-23 11:58:08 -07001135func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars, extraDepCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001136 // Auto-propagating jarjar rules
1137 jarjarProviderData := j.collectJarJarRules(ctx)
1138 if jarjarProviderData != nil {
1139 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
Zi Wangddb2ee52024-04-02 16:44:02 +00001140 text := getJarJarRuleText(jarjarProviderData)
1141 if text != "" {
1142 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1143 android.WriteFileRule(ctx, ruleTextFile, text)
1144 j.repackageJarjarRules = ruleTextFile
Joe Onorato349ae8d2024-02-05 22:46:00 +00001145 }
1146 }
1147
Jaewoong Jung26342642021-03-17 15:56:23 -07001148 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1149
John Wu989ee842024-10-04 00:21:43 +00001150 // Only override the original value if explicitly set
1151 if j.properties.Ravenizer.Enabled != nil {
1152 j.ravenizer.enabled = *j.properties.Ravenizer.Enabled
Makoto Onuki7ded3822024-03-28 14:42:20 -07001153 }
1154
Jaewoong Jung26342642021-03-17 15:56:23 -07001155 deps := j.collectDeps(ctx)
1156 flags := j.collectBuilderFlags(ctx, deps)
1157
1158 if flags.javaVersion.usesJavaModules() {
1159 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001160 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1161 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1162 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001164
Jaewoong Jung26342642021-03-17 15:56:23 -07001165 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001166 j.sourceExtensions = []string{}
1167 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1168 if hasSrcExt(srcFiles.Strings(), ext) {
1169 j.sourceExtensions = append(j.sourceExtensions, ext)
1170 }
1171 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001172 if hasSrcExt(srcFiles.Strings(), ".proto") {
1173 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1174 }
1175
1176 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1177 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1178 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1179 }
1180
Sam Delmerico2351eac2022-05-24 17:10:02 +00001181 aidlSrcs := srcFiles.FilterByExt(".aidl")
1182 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1183
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001184 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001185 srcFiles = j.genSources(ctx, srcFiles, flags)
1186
1187 // Collect javac flags only after computing the full set of srcFiles to
1188 // ensure that the --patch-module lookup paths are complete.
1189 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1190
1191 srcJars := srcFiles.FilterByExt(".srcjar")
1192 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001193 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001194 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001195 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001196
1197 if j.properties.Jarjar_rules != nil {
1198 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1199 }
1200
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001201 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001202
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001203 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001204 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001205 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001206 if _, found := set[v.String()]; !found {
1207 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001208 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001209 }
1210 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001211 var uniqueKtFiles android.Paths
1212 for _, v := range srcFiles.FilterByExt(".kt") {
1213 if _, found := set[v.String()]; !found {
1214 set[v.String()] = true
1215 uniqueKtFiles = append(uniqueKtFiles, v)
1216 }
1217 }
1218
1219 var uniqueSrcFiles android.Paths
1220 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1221 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1222 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001223 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001224
Colin Crossb5db4012022-03-28 17:12:39 -07001225 // We don't currently run annotation processors in turbine, which means we can't use turbine
1226 // generated header jars when an annotation processor that generates API is enabled. One
1227 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1228 // is used to run all of the annotation processors.
1229 disableTurbine := deps.disableTurbine
1230
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001231 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1233
Colin Cross220a9a12022-03-28 17:08:01 -07001234 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001235
Colin Cross4eae06d2023-06-20 22:40:02 -07001236 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1237 // any dependencies so that it can override any non-final R classes from dependencies with the
1238 // final R classes from the app.
1239 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1240
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001241 j.aconfigCacheFiles = append(deps.aconfigProtoFiles, j.properties.Aconfig_Cache_files...)
1242
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001243 var localImplementationJars android.Paths
1244
Mark Whitea15790a2023-08-22 21:28:11 +00001245 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001246 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001247 if srcFiles.HasExt(".kt") {
1248 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1249 }
1250 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1251 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1252 }
1253
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001254 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1255
1256 localHeaderJars, combinedHeaderJarFile := j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
Colin Crossedec77c2024-07-26 15:25:40 -07001257 extraCombinedJars)
1258
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001259 combinedHeaderJarFile, jarjared := j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1260 if jarjared {
1261 localHeaderJars = android.Paths{combinedHeaderJarFile}
1262 transitiveStaticLibsHeaderJars = nil
1263 }
1264 combinedHeaderJarFile, repackaged := j.repackageFlagsIfNecessary(ctx, combinedHeaderJarFile, jarName, "repackage-turbine")
1265 if repackaged {
1266 localHeaderJars = android.Paths{combinedHeaderJarFile}
1267 transitiveStaticLibsHeaderJars = nil
1268 }
Mark Whitea15790a2023-08-22 21:28:11 +00001269 if ctx.Failed() {
1270 return
1271 }
Colin Crossedec77c2024-07-26 15:25:40 -07001272 j.headerJarFile = combinedHeaderJarFile
Mark Whitea15790a2023-08-22 21:28:11 +00001273
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001274 if ctx.Config().UseTransitiveJarsInClasspath() {
1275 if len(localHeaderJars) > 0 {
1276 ctx.CheckbuildFile(localHeaderJars...)
1277 } else {
1278 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1279 ctx.UncheckedModule()
1280 }
1281 } else {
1282 ctx.CheckbuildFile(j.headerJarFile)
1283 }
Colin Crossa6182ab2024-08-21 10:47:44 -07001284
Colin Cross7727c7f2024-07-18 15:36:32 -07001285 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Jihoon Kang705e63e2024-03-13 01:21:16 +00001286 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001287 LocalHeaderJars: localHeaderJars,
1288 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
Colin Cross9ffaf282024-08-12 13:50:09 -07001289 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1290 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001291 AidlIncludeDirs: j.exportAidlIncludeDirs,
1292 ExportedPlugins: j.exportedPluginJars,
1293 ExportedPluginClasses: j.exportedPluginClasses,
1294 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1295 StubsLinkType: j.stubsLinkType,
1296 AconfigIntermediateCacheOutputPaths: deps.aconfigProtoFiles,
Mark Whitea15790a2023-08-22 21:28:11 +00001297 })
1298
1299 j.outputFile = j.headerJarFile
1300 return
1301 }
1302
Jaewoong Jung26342642021-03-17 15:56:23 -07001303 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001304 // When using kotlin sources turbine is used to generate annotation processor sources,
1305 // including for annotation processors that generate API, so we can use turbine for
1306 // java sources too.
1307 disableTurbine = false
1308
Jaewoong Jung26342642021-03-17 15:56:23 -07001309 // user defined kotlin flags.
1310 kotlincFlags := j.properties.Kotlincflags
1311 CheckKotlincFlags(ctx, kotlincFlags)
1312
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001313 // Workaround for KT-46512
1314 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001315
1316 // If there are kotlin files, compile them first but pass all the kotlin and java files
1317 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1318 // won't emit any classes for them.
1319 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1320 if ctx.Device() {
1321 kotlincFlags = append(kotlincFlags, "-no-jdk")
1322 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001323
1324 for _, plugin := range deps.kotlinPlugins {
1325 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1326 }
1327 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1328
Jaewoong Jung26342642021-03-17 15:56:23 -07001329 if len(kotlincFlags) > 0 {
1330 // optimization.
1331 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1332 flags.kotlincFlags += "$kotlincFlags"
1333 }
1334
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001335 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001336 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1337
Jaewoong Jung26342642021-03-17 15:56:23 -07001338 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1339 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1340
Isaac Chioua23d9942022-04-06 06:14:38 +00001341 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001342 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001343 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1344 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001345 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001346 srcJars = append(srcJars, kaptSrcJar)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001347 localImplementationJars = append(localImplementationJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001348 // Disable annotation processing in javac, it's already been handled by kapt
1349 flags.processorPath = nil
1350 flags.processors = nil
1351 }
1352
1353 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001354 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Spandan Das1028d5a2024-08-19 21:45:48 +00001355 j.kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001356 if ctx.Failed() {
1357 return
1358 }
1359
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001360 kotlinJarPath, _ := j.repackageFlagsIfNecessary(ctx, kotlinJar, jarName, "kotlinc")
Zi Wangddb2ee52024-04-02 16:44:02 +00001361
Isaac Chioua23d9942022-04-06 06:14:38 +00001362 // Make javac rule depend on the kotlinc rule
1363 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1364
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001365 localImplementationJars = append(localImplementationJars, kotlinJarPath)
1366
Colin Cross220a9a12022-03-28 17:08:01 -07001367 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001368 }
1369
Jaewoong Jung26342642021-03-17 15:56:23 -07001370 j.compiledSrcJars = srcJars
1371
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001372 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1373
Jaewoong Jung26342642021-03-17 15:56:23 -07001374 enableSharding := false
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001375 var localHeaderJars android.Paths
1376 var shardingHeaderJars android.Paths
1377 var repackagedHeaderJarFile android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001378 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001379 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1380 enableSharding = true
1381 // Formerly, there was a check here that prevented annotation processors
1382 // from being used when sharding was enabled, as some annotation processors
1383 // do not function correctly in sharded environments. It was removed to
1384 // allow for the use of annotation processors that do function correctly
1385 // with sharding enabled. See: b/77284273.
1386 }
Colin Crossd1d8f172024-07-29 11:30:29 -07001387 extraJars := slices.Clone(kotlinHeaderJars)
Colin Crossd1d8f172024-07-29 11:30:29 -07001388 extraJars = append(extraJars, extraCombinedJars...)
Colin Crossedec77c2024-07-26 15:25:40 -07001389 var combinedHeaderJarFile android.Path
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001390 localHeaderJars, combinedHeaderJarFile = j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
1391 shardingHeaderJars = localHeaderJars
Colin Crossedec77c2024-07-26 15:25:40 -07001392
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001393 var jarjared bool
1394 j.headerJarFile, jarjared = j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1395 if jarjared {
1396 // jarjar modifies transitive static dependencies, use the combined header jar and drop the transitive
1397 // static libs header jars.
1398 localHeaderJars = android.Paths{j.headerJarFile}
1399 transitiveStaticLibsHeaderJars = nil
1400 }
1401 var repackaged bool
1402 repackagedHeaderJarFile, repackaged = j.repackageFlagsIfNecessary(ctx, j.headerJarFile, jarName, "turbine")
1403 if repackaged {
1404 // repackage modifies transitive static dependencies, use the combined header jar and drop the transitive
1405 // static libs header jars.
1406 // TODO(b/356688296): this shouldn't export both the unmodified and repackaged header jars
1407 localHeaderJars = android.Paths{j.headerJarFile, repackagedHeaderJarFile}
1408 transitiveStaticLibsHeaderJars = nil
1409 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001410 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001411 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001412 hasErrorproneableFiles := false
1413 for _, ext := range j.sourceExtensions {
1414 if ext != ".proto" && ext != ".aidl" {
1415 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1416 // compile, and it's not useful to have warnings on these generated sources.
1417 hasErrorproneableFiles = true
1418 break
1419 }
1420 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001421 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001422 if Bool(j.properties.Errorprone.Enabled) {
1423 // If error-prone is enabled, enable errorprone flags on the regular
1424 // build.
1425 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001426 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001427 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1428 // a new jar file just for compiling with the errorprone compiler to.
1429 // This is because we don't want to cause the java files to get completely
1430 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1431 // We also don't want to run this if errorprone is enabled by default for
1432 // this module, or else we could have duplicated errorprone messages.
1433 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001434 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001435 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001436
Vadim Spivak3c496f02023-06-08 06:14:59 +00001437 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001438 "errorprone", "errorprone")
1439
Jaewoong Jung26342642021-03-17 15:56:23 -07001440 extraJarDeps = append(extraJarDeps, errorprone)
1441 }
1442
1443 if enableSharding {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001444 if len(shardingHeaderJars) > 0 {
1445 flags.classpath = append(classpath(slices.Clone(shardingHeaderJars)), flags.classpath...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001446 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001447 shardSize := int(*(j.properties.Javac_shard_size))
1448 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001449 if len(uniqueJavaFiles) > 0 {
1450 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001451 for idx, shardSrc := range shardSrcs {
1452 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1453 nil, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001454 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(idx))
1455 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 }
1457 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001458 // Assume approximately 5 sources per srcjar.
1459 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1460 // 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 -07001461 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001462 startIdx := len(shardSrcs)
1463 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1464 for idx, shardSrcJars := range shardSrcJarsList {
1465 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1466 nil, shardSrcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001467 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(startIdx+idx))
1468 localImplementationJars = append(localImplementationJars, classes)
Colin Crossa052ddb2023-09-25 21:46:58 -07001469 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001470 }
1471 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001472 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001473 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac")
1474 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001475 }
1476 if ctx.Failed() {
1477 return
1478 }
1479 }
1480
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001481 localImplementationJars = append(localImplementationJars, extraCombinedJars...)
Colin Crossfd620b22024-02-23 10:05:21 -08001482
Jaewoong Jung26342642021-03-17 15:56:23 -07001483 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1484
1485 var includeSrcJar android.WritablePath
1486 if Bool(j.properties.Include_srcs) {
1487 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1488 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1489 }
1490
1491 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1492 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1493 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
Cole Faust65cb40a2024-10-21 15:41:42 -07001494 fileArgs2, fileDeps2 := ResourceFilesToJarArgs(ctx, j.properties.Device_common_java_resources, nil)
1495 fileArgs3, fileDeps3 := ResourceFilesToJarArgs(ctx, j.properties.Device_first_java_resources, nil)
1496 fileArgs = slices.Concat(fileArgs, fileArgs2, fileArgs3)
1497 fileDeps = slices.Concat(fileDeps, fileDeps2, fileDeps3)
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1499
1500 var resArgs []string
1501 var resDeps android.Paths
1502
1503 resArgs = append(resArgs, dirArgs...)
1504 resDeps = append(resDeps, dirDeps...)
1505
1506 resArgs = append(resArgs, fileArgs...)
1507 resDeps = append(resDeps, fileDeps...)
1508
1509 resArgs = append(resArgs, extraArgs...)
1510 resDeps = append(resDeps, extraDeps...)
1511
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001512 var localResourceJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 if len(resArgs) > 0 {
1514 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1515 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001516 if ctx.Failed() {
1517 return
1518 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001519 localResourceJars = append(localResourceJars, resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001520 }
1521
Jaewoong Jung26342642021-03-17 15:56:23 -07001522 if Bool(j.properties.Include_srcs) {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001523 localResourceJars = append(localResourceJars, includeSrcJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001524 }
1525
1526 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1527 if len(services) > 0 {
1528 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1529 var zipargs []string
1530 for _, file := range services {
1531 serviceFile := file.String()
1532 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1533 }
1534 rule := zip
1535 args := map[string]string{
1536 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1537 }
1538 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1539 rule = zipRE
1540 args["implicits"] = strings.Join(services.Strings(), ",")
1541 }
1542 ctx.Build(pctx, android.BuildParams{
1543 Rule: rule,
1544 Output: servicesJar,
1545 Implicits: services,
1546 Args: args,
1547 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001548 localResourceJars = append(localResourceJars, servicesJar)
1549 }
1550
1551 completeStaticLibsResourceJars := android.NewDepSet(android.PREORDER, localResourceJars, deps.transitiveStaticLibsResourceJars)
1552
1553 var combinedResourceJar android.Path
1554 var resourceJars android.Paths
1555 if ctx.Config().UseTransitiveJarsInClasspath() {
1556 resourceJars = completeStaticLibsResourceJars.ToList()
1557 } else {
1558 resourceJars = append(slices.Clone(localResourceJars), deps.staticResourceJars...)
1559 }
1560 if len(resourceJars) == 1 {
1561 combinedResourceJar = resourceJars[0]
1562 } else if len(resourceJars) > 0 {
1563 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1564 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1565 false, nil, nil)
1566 combinedResourceJar = combinedJar
1567 }
1568
1569 manifest := j.overrideManifest
1570 if !manifest.Valid() && j.properties.Manifest != nil {
1571 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
Jaewoong Jung26342642021-03-17 15:56:23 -07001572 }
1573
1574 // Combine the classes built from sources, any manifests, and any static libraries into
1575 // classes.jar. If there is only one input jar this step will be skipped.
Colin Cross7707b242024-07-26 12:02:36 -07001576 var outputFile android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001577
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001578 completeStaticLibsImplementationJars := android.NewDepSet(android.PREORDER, localImplementationJars, deps.transitiveStaticLibsImplementationJars)
1579
1580 var jars android.Paths
1581 if ctx.Config().UseTransitiveJarsInClasspath() {
1582 jars = completeStaticLibsImplementationJars.ToList()
1583 } else {
1584 jars = append(slices.Clone(localImplementationJars), deps.staticJars...)
1585 }
1586
1587 jars = append(jars, extraDepCombinedJars...)
1588
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 if len(jars) == 1 && !manifest.Valid() {
1590 // Optimization: skip the combine step as there is nothing to do
1591 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1592 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001593 // any if len(extraJars) == 0.
Jaewoong Jung26342642021-03-17 15:56:23 -07001594
Jihoon Kang1147b312023-06-08 23:25:57 +00001595 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1596 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1597 // either with .from-source or .from-text suffix.
1598 // outputFile should be agnostic to the build configuration,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001599 // thus copy the single input static lib in order to prevent the static lib from being exposed
Jihoon Kang1147b312023-06-08 23:25:57 +00001600 // to the copy rules.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001601 if stub, _ := moduleStubLinkType(j); stub {
1602 copiedJar := android.PathForModuleOut(ctx, "combined", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 ctx.Build(pctx, android.BuildParams{
1604 Rule: android.Cp,
1605 Input: jars[0],
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001606 Output: copiedJar,
Jaewoong Jung26342642021-03-17 15:56:23 -07001607 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001608 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, android.Paths{copiedJar}, nil)
1609 outputFile = copiedJar
Colin Cross7707b242024-07-26 12:02:36 -07001610 } else {
1611 outputFile = jars[0]
Jaewoong Jung26342642021-03-17 15:56:23 -07001612 }
1613 } else {
1614 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1615 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1616 false, nil, nil)
Colin Cross7707b242024-07-26 12:02:36 -07001617 outputFile = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001618 }
1619
1620 // jarjar implementation jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001621 jarjarFile, jarjarred := j.jarjarIfNecessary(ctx, outputFile, jarName, "")
1622 if jarjarred {
1623 localImplementationJars = android.Paths{jarjarFile}
1624 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
1625 }
Colin Crossedec77c2024-07-26 15:25:40 -07001626 outputFile = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001627
Colin Crossedec77c2024-07-26 15:25:40 -07001628 // jarjar resource jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001629 if combinedResourceJar != nil {
1630 resourceJarJarFile, jarjarred := j.jarjarIfNecessary(ctx, combinedResourceJar, jarName, "resource")
1631 combinedResourceJar = resourceJarJarFile
1632 if jarjarred {
1633 localResourceJars = android.Paths{resourceJarJarFile}
1634 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1635 }
Colin Crossedec77c2024-07-26 15:25:40 -07001636 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001637
Colin Crossedec77c2024-07-26 15:25:40 -07001638 if ctx.Failed() {
1639 return
Jaewoong Jung26342642021-03-17 15:56:23 -07001640 }
1641
Makoto Onuki7ded3822024-03-28 14:42:20 -07001642 if j.ravenizer.enabled {
1643 ravenizerInput := outputFile
John Wub67040d2024-10-07 18:39:06 +00001644 ravenizerOutput := android.PathForModuleOut(ctx, "ravenizer", "", jarName)
John Wu989ee842024-10-04 00:21:43 +00001645 ravenizerArgs := ""
1646 if proptools.Bool(j.properties.Ravenizer.Strip_mockito) {
1647 ravenizerArgs = "--strip-mockito"
1648 }
1649 TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
Makoto Onuki7ded3822024-03-28 14:42:20 -07001650 outputFile = ravenizerOutput
Colin Cross7e863852024-09-06 14:42:38 -07001651 localImplementationJars = android.Paths{ravenizerOutput}
1652 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
John Wub67040d2024-10-07 18:39:06 +00001653 if combinedResourceJar != nil {
1654 ravenizerInput = combinedResourceJar
1655 ravenizerOutput = android.PathForModuleOut(ctx, "ravenizer", "resources", jarName)
1656 TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
1657 combinedResourceJar = ravenizerOutput
1658 localResourceJars = android.Paths{ravenizerOutput}
1659 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1660 }
Makoto Onuki7ded3822024-03-28 14:42:20 -07001661 }
1662
Yihan Dong8be09c22024-08-29 15:32:13 +08001663 if j.shouldApiMapper() {
1664 inputFile := outputFile
1665 apiMapperFile := android.PathForModuleOut(ctx, "apimapper", jarName)
1666 ctx.Build(pctx, android.BuildParams{
1667 Rule: apimapper,
1668 Description: "apimapper",
1669 Input: inputFile,
1670 Output: apiMapperFile,
1671 })
1672 outputFile = apiMapperFile
Colin Cross7e863852024-09-06 14:42:38 -07001673 localImplementationJars = android.Paths{apiMapperFile}
1674 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Yihan Dong8be09c22024-08-29 15:32:13 +08001675 }
1676
Jaewoong Jung26342642021-03-17 15:56:23 -07001677 // Check package restrictions if necessary.
1678 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001679 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001680 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001681
1682 // Create a rule to copy the output jar to another path and add a validate dependency that
1683 // will check that the jar only contains the permitted packages. The new location will become
1684 // the output file of this module.
1685 inputFile := outputFile
Colin Cross7707b242024-07-26 12:02:36 -07001686 packageCheckOutputFile := android.PathForModuleOut(ctx, "package-check", jarName)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001687 ctx.Build(pctx, android.BuildParams{
1688 Rule: android.Cp,
1689 Input: inputFile,
Colin Cross7707b242024-07-26 12:02:36 -07001690 Output: packageCheckOutputFile,
Paul Duffin08a18bf2021-10-01 13:19:58 +01001691 // Make sure that any dependency on the output file will cause ninja to run the package check
1692 // rule.
1693 Validation: pkgckFile,
1694 })
Colin Cross7707b242024-07-26 12:02:36 -07001695 outputFile = packageCheckOutputFile
Colin Cross7e863852024-09-06 14:42:38 -07001696 localImplementationJars = android.Paths{packageCheckOutputFile}
1697 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001698
1699 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001700 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001701
1702 if ctx.Failed() {
1703 return
1704 }
1705 }
1706
1707 j.implementationJarFile = outputFile
1708 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001709 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1710 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1711 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1712 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1713 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1714 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1715 j.headerJarFile = headerJarFile
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001716 if len(localImplementationJars) == 1 && ctx.Config().UseTransitiveJarsInClasspath() {
1717 localHeaderJarFile := android.PathForModuleOut(ctx, "local-javac-header", jarName)
1718 convertImplementationJarToHeaderJar(ctx, localImplementationJars[0], localHeaderJarFile)
1719 localHeaderJars = append(localHeaderJars, localHeaderJarFile)
1720 } else {
1721 localHeaderJars = append(localHeaderJars, headerJarFile)
1722 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001723 }
1724
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001725 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1726 specs := j.jacocoModuleToZipCommand(ctx)
1727 if ctx.Failed() {
1728 return
1729 }
1730
Colin Crossb323c912024-09-24 15:21:00 -07001731 completeStaticLibsImplementationJarsToCombine := completeStaticLibsImplementationJars
1732
Jaewoong Jung26342642021-03-17 15:56:23 -07001733 if j.shouldInstrument(ctx) {
Colin Crossb323c912024-09-24 15:21:00 -07001734 instrumentedOutputFile := j.instrument(ctx, flags, outputFile, jarName, specs)
1735 completeStaticLibsImplementationJarsToCombine = android.NewDepSet(android.PREORDER, android.Paths{instrumentedOutputFile}, nil)
1736 outputFile = instrumentedOutputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001737 }
1738
1739 // merge implementation jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001740 var implementationAndResourcesJarsToCombine android.Paths
1741 if ctx.Config().UseTransitiveJarsInClasspath() {
1742 resourceJars := completeStaticLibsResourceJars.ToList()
1743 if len(resourceJars) > 0 {
Colin Crossb323c912024-09-24 15:21:00 -07001744 implementationAndResourcesJarsToCombine = append(resourceJars, completeStaticLibsImplementationJarsToCombine.ToList()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001745 implementationAndResourcesJarsToCombine = append(implementationAndResourcesJarsToCombine, extraDepCombinedJars...)
1746 }
1747 } else {
1748 if combinedResourceJar != nil {
1749 implementationAndResourcesJarsToCombine = android.Paths{combinedResourceJar, outputFile}
1750 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001751 }
1752
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001753 if len(implementationAndResourcesJarsToCombine) > 0 {
1754 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
1755 TransformJarsToJar(ctx, combinedJar, "for resources", implementationAndResourcesJarsToCombine, manifest,
1756 false, nil, nil)
1757 outputFile = combinedJar
1758 }
1759
1760 j.implementationAndResourcesJar = outputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001761
1762 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001763 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001764 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001765 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001766 if compileDex == nil {
1767 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001768 }
1769 if j.deviceProperties.Hostdex == nil {
1770 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1771 }
1772 }
1773
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001774 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001775 if j.hasCode(ctx) {
1776 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001777 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001778 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1779 }
1780 // Dex compilation
Colin Cross7707b242024-07-26 12:02:36 -07001781 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00001782 params := &compileDexParams{
1783 flags: flags,
1784 sdkVersion: j.SdkVersion(ctx),
1785 minSdkVersion: j.MinSdkVersion(ctx),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001786 classesJar: outputFile,
Spandan Dasc404cc72023-02-23 18:05:05 +00001787 jarName: jarName,
1788 }
Cole Fausteb032462024-09-19 11:12:54 -07001789 if j.GetProfileGuided(ctx) && j.optimizeOrObfuscateEnabled() && !j.EnableProfileRewriting(ctx) {
Spandan Das15a67112024-05-30 00:07:40 +00001790 ctx.PropertyErrorf("enable_profile_rewriting",
1791 "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.",
1792 )
1793 }
Cole Fausteb032462024-09-19 11:12:54 -07001794 if j.EnableProfileRewriting(ctx) {
1795 profile := j.GetProfile(ctx)
1796 if profile == "" || !j.GetProfileGuided(ctx) {
Spandan Das3dbda182024-05-20 22:23:10 +00001797 ctx.PropertyErrorf("enable_profile_rewriting", "Profile and Profile_guided must be set when enable_profile_rewriting is true")
1798 }
1799 params.artProfileInput = &profile
1800 }
1801 dexOutputFile, dexArtProfileOutput := j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001802 if ctx.Failed() {
1803 return
1804 }
1805
Spandan Das3dbda182024-05-20 22:23:10 +00001806 // If r8/d8 provides a profile that matches the optimized dex, use that for dexpreopt.
1807 if dexArtProfileOutput != nil {
Colin Cross7707b242024-07-26 12:02:36 -07001808 j.dexpreopter.SetRewrittenProfile(dexArtProfileOutput)
Spandan Das3dbda182024-05-20 22:23:10 +00001809 }
1810
Jaewoong Jung26342642021-03-17 15:56:23 -07001811 // merge dex jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001812 var dexAndResourceJarsToCombine android.Paths
1813 if ctx.Config().UseTransitiveJarsInClasspath() {
1814 resourceJars := completeStaticLibsResourceJars.ToList()
1815 if len(resourceJars) > 0 {
1816 dexAndResourceJarsToCombine = append(android.Paths{dexOutputFile}, resourceJars...)
1817 }
1818 } else {
1819 if combinedResourceJar != nil {
1820 dexAndResourceJarsToCombine = android.Paths{dexOutputFile, combinedResourceJar}
1821 }
1822 }
1823 if len(dexAndResourceJarsToCombine) > 0 {
Colin Cross7707b242024-07-26 12:02:36 -07001824 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001825 TransformJarsToJar(ctx, combinedJar, "for dex resources", dexAndResourceJarsToCombine, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07001826 false, nil, nil)
1827 if *j.dexProperties.Uncompress_dex {
Colin Cross7707b242024-07-26 12:02:36 -07001828 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName)
Cole Faust51d7bfd2023-09-07 05:31:32 +00001829 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001830 dexOutputFile = combinedAlignedJar
1831 } else {
1832 dexOutputFile = combinedJar
1833 }
1834 }
1835
Paul Duffin4de94502021-05-16 05:21:16 +01001836 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001837
1838 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001839
1840 // Encode hidden API flags in dex file, if needed.
1841 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1842
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001843 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001844
1845 // Dexpreopting
Jihoon Kanga3a05462024-04-05 00:36:44 +00001846 libName := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())
1847 if j.SdkLibraryName() != nil && strings.HasSuffix(ctx.ModuleName(), ".impl") {
1848 libName = strings.TrimSuffix(libName, ".impl")
1849 }
1850 j.dexpreopt(ctx, libName, dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001851
1852 outputFile = dexOutputFile
Colin Crossa6182ab2024-08-21 10:47:44 -07001853
1854 ctx.CheckbuildFile(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001855 } else {
1856 // There is no code to compile into a dex jar, make sure the resources are propagated
1857 // to the APK if this is an app.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001858 j.dexJarFile = makeDexJarPathFromPath(combinedResourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001859 }
1860
1861 if ctx.Failed() {
1862 return
1863 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001864 }
1865
1866 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001867 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001868 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001869 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001870 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001871 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001872 }
1873 }
1874
1875 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001876 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1877 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001878 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1879 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001880 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001881 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001882 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001883 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001884 j.linter.javaLanguageLevel = flags.javaVersion.String()
1885 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001886 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1888 j.linter.buildModuleReportZip = true
1889 }
1890 j.linter.lint(ctx)
1891 }
1892
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001893 j.collectTransitiveSrcFiles(ctx, srcFiles)
1894
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001895 if ctx.Config().UseTransitiveJarsInClasspath() {
1896 if len(localImplementationJars) > 0 || len(localResourceJars) > 0 || len(localHeaderJars) > 0 {
1897 ctx.CheckbuildFile(localImplementationJars...)
1898 ctx.CheckbuildFile(localResourceJars...)
1899 ctx.CheckbuildFile(localHeaderJars...)
1900 } else {
1901 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1902 ctx.UncheckedModule()
1903 }
1904 } else {
1905 ctx.CheckbuildFile(j.implementationJarFile)
1906 ctx.CheckbuildFile(j.headerJarFile)
1907 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001908
Colin Cross7727c7f2024-07-18 15:36:32 -07001909 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001910 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1911 RepackagedHeaderJars: android.PathsIfNonNil(repackagedHeaderJarFile),
1912
1913 LocalHeaderJars: localHeaderJars,
1914 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
1915 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
1916 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
1917
Colin Cross9ffaf282024-08-12 13:50:09 -07001918 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1919 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001920 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1921 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001922 ResourceJars: android.PathsIfNonNil(combinedResourceJar),
Jihoon Kang705e63e2024-03-13 01:21:16 +00001923 AidlIncludeDirs: j.exportAidlIncludeDirs,
1924 SrcJarArgs: j.srcJarArgs,
1925 SrcJarDeps: j.srcJarDeps,
1926 TransitiveSrcFiles: j.transitiveSrcFiles,
1927 ExportedPlugins: j.exportedPluginJars,
1928 ExportedPluginClasses: j.exportedPluginClasses,
1929 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1930 JacocoReportClassesFile: j.jacocoReportClassesFile,
1931 StubsLinkType: j.stubsLinkType,
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001932 AconfigIntermediateCacheOutputPaths: j.aconfigCacheFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001933 })
1934
1935 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1936 j.outputFile = outputFile.WithoutRel()
1937}
1938
Cole Faustb7493472024-08-28 11:55:52 -07001939func (j *Module) useCompose(ctx android.BaseModuleContext) bool {
1940 return android.InList("androidx.compose.runtime_runtime", j.staticLibs(ctx))
Colin Crossa1ff7c62021-09-17 14:11:52 -07001941}
1942
Colin Crosscde55342024-03-27 14:11:51 -07001943func collectDepProguardSpecInfo(ctx android.ModuleContext) (transitiveProguardFlags, transitiveUnconditionalExportedFlags []*android.DepSet[android.Path]) {
Sam Delmerico95d70942023-08-02 18:00:35 -04001944 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001945 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001946 depTag := ctx.OtherModuleDependencyTag(m)
1947
1948 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1949 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1950 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1951 }
1952
1953 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1954 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1955 }
1956 })
1957
Colin Crosscde55342024-03-27 14:11:51 -07001958 return transitiveProguardFlags, transitiveUnconditionalExportedFlags
1959}
1960
1961func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1962 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
1963
Sam Delmerico95d70942023-08-02 18:00:35 -04001964 directUnconditionalExportedFlags := android.Paths{}
1965 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1966 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1967 if exportUnconditionally {
1968 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1969 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1970 directUnconditionalExportedFlags = proguardFlagsForThisModule
1971 }
1972
1973 return ProguardSpecInfo{
1974 Export_proguard_flags_files: exportUnconditionally,
1975 ProguardFlagsFiles: android.NewDepSet[android.Path](
1976 android.POSTORDER,
1977 proguardFlagsForThisModule,
1978 transitiveProguardFlags,
1979 ),
1980 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1981 android.POSTORDER,
1982 directUnconditionalExportedFlags,
1983 transitiveUnconditionalExportedFlags,
1984 ),
1985 }
1986
1987}
1988
Cole Faust75fffb12021-06-13 15:23:16 -07001989// Returns a copy of the supplied flags, but with all the errorprone-related
1990// fields copied to the regular build's fields.
1991func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1992 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1993
1994 if len(flags.errorProneExtraJavacFlags) > 0 {
1995 if len(flags.javacFlags) > 0 {
1996 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1997 } else {
1998 flags.javacFlags = flags.errorProneExtraJavacFlags
1999 }
2000 }
2001 return flags
2002}
2003
Jaewoong Jung26342642021-03-17 15:56:23 -07002004func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
Colin Cross7707b242024-07-26 12:02:36 -07002005 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07002006
2007 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00002008 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07002009 if idx >= 0 {
2010 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00002011 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07002012 jarName += strconv.Itoa(idx)
2013 }
2014
Colin Cross7707b242024-07-26 12:02:36 -07002015 classes := android.PathForModuleOut(ctx, "javac", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002016 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07002017
Cole Faust9decf832024-06-11 11:45:53 -07002018 if ctx.Config().EmitXrefRules() && ctx.Module() == ctx.PrimaryModule() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002019 extractionFile := android.PathForModuleOut(ctx, kzipName)
2020 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
2021 j.kytheFiles = append(j.kytheFiles, extractionFile)
2022 }
2023
Vadim Spivak3c496f02023-06-08 06:14:59 +00002024 if len(flags.processorPath) > 0 {
2025 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
2026 }
2027
Jaewoong Jung26342642021-03-17 15:56:23 -07002028 return classes
2029}
2030
2031// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
2032// since some of these flags may be used internally.
2033func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
2034 for _, flag := range flags {
2035 flag = strings.TrimSpace(flag)
2036
2037 if !strings.HasPrefix(flag, "-") {
2038 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
2039 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
2040 ctx.PropertyErrorf("kotlincflags",
2041 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
2042 } else if inList(flag, config.KotlincIllegalFlags) {
2043 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
2044 } else if flag == "-include-runtime" {
2045 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
2046 } else {
2047 args := strings.Split(flag, " ")
2048 if args[0] == "-kotlin-home" {
2049 ctx.PropertyErrorf("kotlincflags",
2050 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
2051 }
2052 }
2053 }
2054}
2055
2056func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
2057 deps deps, flags javaBuilderFlags, jarName string,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002058 extraJars android.Paths) (localHeaderJars android.Paths, combinedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002059
Jaewoong Jung26342642021-03-17 15:56:23 -07002060 if len(srcFiles) > 0 || len(srcJars) > 0 {
2061 // Compile java sources into turbine.jar.
2062 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
2063 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002064 localHeaderJars = append(localHeaderJars, turbineJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07002065 }
2066
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002067 localHeaderJars = append(localHeaderJars, extraJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002068
2069 // Combine any static header libraries into classes-header.jar. If there is only
2070 // one input jar this step will be skipped.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002071 var jars android.Paths
2072 if ctx.Config().UseTransitiveJarsInClasspath() {
2073 depSet := android.NewDepSet(android.PREORDER, localHeaderJars, deps.transitiveStaticLibsHeaderJars)
2074 jars = depSet.ToList()
2075 } else {
2076 jars = append(slices.Clone(localHeaderJars), deps.staticHeaderJars...)
2077 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002078
2079 // we cannot skip the combine step for now if there is only one jar
2080 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
Colin Crossedec77c2024-07-26 15:25:40 -07002081 combinedHeaderJarOutputPath := android.PathForModuleOut(ctx, "turbine-combined", jarName)
2082 TransformJarsToJar(ctx, combinedHeaderJarOutputPath, "for turbine", jars, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07002083 false, nil, []string{"META-INF/TRANSITIVE"})
Jaewoong Jung26342642021-03-17 15:56:23 -07002084
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002085 return localHeaderJars, combinedHeaderJarOutputPath
Jaewoong Jung26342642021-03-17 15:56:23 -07002086}
2087
2088func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Colin Cross7707b242024-07-26 12:02:36 -07002089 classesJar android.Path, jarName string, specs string) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07002090
2091 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
Colin Cross7707b242024-07-26 12:02:36 -07002092 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07002093
2094 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
2095
2096 j.jacocoReportClassesFile = jacocoReportClassesFile
2097
2098 return instrumentedJar
2099}
2100
Colin Cross9ffaf282024-08-12 13:50:09 -07002101type providesTransitiveHeaderJarsForR8 struct {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002102 // set of header jars for all transitive libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002103 transitiveLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002104 // set of header jars for all transitive static libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002105 transitiveStaticLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002106}
2107
Colin Cross9ffaf282024-08-12 13:50:09 -07002108// collectTransitiveHeaderJarsForR8 visits direct dependencies and collects all transitive libs and static_libs
2109// header jars. The semantics of the collected jars are odd (it collects combined jars that contain the static
2110// libs, but also the static libs, and it collects transitive libs dependencies of static_libs), so these
2111// are only used to expand the --lib arguments to R8.
2112func (j *providesTransitiveHeaderJarsForR8) collectTransitiveHeaderJarsForR8(ctx android.ModuleContext) {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002113 directLibs := android.Paths{}
2114 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07002115 transitiveLibs := []*android.DepSet[android.Path]{}
2116 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002117 ctx.VisitDirectDeps(func(module android.Module) {
2118 // don't add deps of the prebuilt version of the same library
2119 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
2120 return
2121 }
2122
Colin Cross7727c7f2024-07-18 15:36:32 -07002123 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2124 tag := ctx.OtherModuleDependencyTag(module)
2125 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
2126 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
2127 directLibs = append(directLibs, dep.HeaderJars...)
2128 } else if tag == staticLibTag {
2129 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
2130 } else {
2131 // Don't propagate transitive libs for other kinds of dependencies.
2132 return
2133 }
Jared Dukeefb6d602023-10-27 18:47:10 +00002134
Colin Cross9ffaf282024-08-12 13:50:09 -07002135 if dep.TransitiveLibsHeaderJarsForR8 != nil {
2136 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002137 }
Colin Cross9ffaf282024-08-12 13:50:09 -07002138 if dep.TransitiveStaticLibsHeaderJarsForR8 != nil {
2139 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002140 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002141
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002142 }
2143 })
Colin Cross9ffaf282024-08-12 13:50:09 -07002144 j.transitiveLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
2145 j.transitiveStaticLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002146}
2147
Jaewoong Jung26342642021-03-17 15:56:23 -07002148func (j *Module) HeaderJars() android.Paths {
2149 if j.headerJarFile == nil {
2150 return nil
2151 }
2152 return android.Paths{j.headerJarFile}
2153}
2154
2155func (j *Module) ImplementationJars() android.Paths {
2156 if j.implementationJarFile == nil {
2157 return nil
2158 }
2159 return android.Paths{j.implementationJarFile}
2160}
2161
Spandan Das59a4a2b2024-01-09 21:35:56 +00002162func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07002163 return j.dexJarFile
2164}
2165
2166func (j *Module) DexJarInstallPath() android.Path {
2167 return j.installFile
2168}
2169
2170func (j *Module) ImplementationAndResourcesJars() android.Paths {
2171 if j.implementationAndResourcesJar == nil {
2172 return nil
2173 }
2174 return android.Paths{j.implementationAndResourcesJar}
2175}
2176
2177func (j *Module) AidlIncludeDirs() android.Paths {
2178 // exportAidlIncludeDirs is type android.Paths already
2179 return j.exportAidlIncludeDirs
2180}
2181
2182func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2183 return j.classLoaderContexts
2184}
2185
2186// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -07002187func (j *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002188 if j.expandJarjarRules != nil {
2189 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
Spandan Das096b8d62024-10-08 22:41:26 +00002190 // Add the header jar so that the rdeps can be resolved to the repackaged classes.
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002191 dpInfo.Jars = append(dpInfo.Jars, j.headerJarFile.String())
Jaewoong Jung26342642021-03-17 15:56:23 -07002192 }
Spandan Das096b8d62024-10-08 22:41:26 +00002193 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2194 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2195 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002196 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2197 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
Cole Faustb7493472024-08-28 11:55:52 -07002198 dpInfo.Static_libs = append(dpInfo.Static_libs, j.staticLibs(ctx)...)
Yikef6282022022-04-13 20:41:01 +08002199 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002200}
2201
2202func (j *Module) CompilerDeps() []string {
Spandan Das8aac9932024-07-18 23:14:13 +00002203 return j.compileDepNames
Jaewoong Jung26342642021-03-17 15:56:23 -07002204}
2205
2206func (j *Module) hasCode(ctx android.ModuleContext) bool {
2207 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2208 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2209}
2210
2211// Implements android.ApexModule
2212func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2213 return j.depIsInSameApex(ctx, dep)
2214}
2215
2216// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002217func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002218 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002219 minSdkVersion := j.MinSdkVersion(ctx)
2220 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002221 return fmt.Errorf("min_sdk_version is not specified")
2222 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002223 // If the module is compiling against core (via sdk_version), skip comparison check.
2224 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002225 return nil
2226 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002227 if minSdkVersion.GreaterThan(sdkVersion) {
2228 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002229 }
2230 return nil
2231}
2232
2233func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002234 if j.stem == "" {
2235 panic("Stem() called before stem property was set")
2236 }
2237 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002238}
2239
Jaewoong Jung26342642021-03-17 15:56:23 -07002240func (j *Module) JacocoReportClassesFile() android.Path {
2241 return j.jacocoReportClassesFile
2242}
2243
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002244func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2245 var fromDeps []*android.DepSet[android.Path]
2246 ctx.VisitDirectDeps(func(module android.Module) {
2247 tag := ctx.OtherModuleDependencyTag(module)
2248 if tag == staticLibTag {
Colin Cross7727c7f2024-07-18 15:36:32 -07002249 if depInfo, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2250 if depInfo.TransitiveSrcFiles != nil {
2251 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2252 }
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002253 }
2254 }
2255 })
2256
2257 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2258}
2259
Jaewoong Jung26342642021-03-17 15:56:23 -07002260func (j *Module) IsInstallable() bool {
2261 return Bool(j.properties.Installable)
2262}
2263
2264type sdkLinkType int
2265
2266const (
2267 // TODO(jiyong) rename these for better readability. Make the allowed
2268 // and disallowed link types explicit
2269 // order is important here. See rank()
2270 javaCore sdkLinkType = iota
2271 javaSdk
2272 javaSystem
2273 javaModule
2274 javaSystemServer
2275 javaPlatform
2276)
2277
2278func (lt sdkLinkType) String() string {
2279 switch lt {
2280 case javaCore:
2281 return "core Java API"
2282 case javaSdk:
2283 return "Android API"
2284 case javaSystem:
2285 return "system API"
2286 case javaModule:
2287 return "module API"
2288 case javaSystemServer:
2289 return "system server API"
2290 case javaPlatform:
2291 return "private API"
2292 default:
2293 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2294 }
2295}
2296
2297// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2298// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2299// can't statically depend on modules that use Platform API.
2300func (lt sdkLinkType) rank() int {
2301 return int(lt)
2302}
2303
2304type moduleWithSdkDep interface {
2305 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002306 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002307}
2308
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002309func sdkLinkTypeFromSdkKind(k android.SdkKind) sdkLinkType {
2310 switch k {
2311 case android.SdkCore:
2312 return javaCore
2313 case android.SdkSystem:
2314 return javaSystem
2315 case android.SdkPublic:
2316 return javaSdk
2317 case android.SdkModule:
2318 return javaModule
2319 case android.SdkSystemServer:
2320 return javaSystemServer
2321 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
2322 return javaPlatform
2323 default:
2324 return javaSdk
2325 }
2326}
2327
Jiyong Park92315372021-04-02 08:45:46 +09002328func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002329 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002330 case android.SdkCore.DefaultJavaLibraryName(),
2331 "legacy.core.platform.api.stubs",
2332 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002333 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002334 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002335 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002336 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002337 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002338 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002339 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002340 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002341 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002342 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002343 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002344 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002345 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002346 return javaSystem, true
2347 }
2348
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002349 if stub, linkType := moduleStubLinkType(m); stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07002350 return linkType, true
2351 }
2352
Jiyong Park92315372021-04-02 08:45:46 +09002353 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002354 if !ver.Valid() {
2355 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002356 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002357
2358 return sdkLinkTypeFromSdkKind(ver.Kind), false
Jaewoong Jung26342642021-03-17 15:56:23 -07002359}
2360
2361// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2362// this module's. See the comment on rank() for details and an example.
2363func (j *Module) checkSdkLinkType(
2364 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2365 if ctx.Host() {
2366 return
2367 }
2368
Jiyong Park92315372021-04-02 08:45:46 +09002369 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002370 if stubs {
2371 return
2372 }
Jiyong Park92315372021-04-02 08:45:46 +09002373 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002374
2375 if myLinkType.rank() < depLinkType.rank() {
2376 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2377 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2378 "property of the source or target module so that target module is built "+
2379 "with the same or smaller API set when compared to the source.",
2380 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2381 }
2382}
2383
2384func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2385 var deps deps
2386
Jiyong Park92315372021-04-02 08:45:46 +09002387 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002388
Colin Cross9ffaf282024-08-12 13:50:09 -07002389 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002390
2391 var transitiveBootClasspathHeaderJars []*android.DepSet[android.Path]
2392 var transitiveClasspathHeaderJars []*android.DepSet[android.Path]
2393 var transitiveJava9ClasspathHeaderJars []*android.DepSet[android.Path]
2394 var transitiveStaticJarsHeaderLibs []*android.DepSet[android.Path]
2395 var transitiveStaticJarsImplementationLibs []*android.DepSet[android.Path]
2396 var transitiveStaticJarsResourceLibs []*android.DepSet[android.Path]
2397
Jaewoong Jung26342642021-03-17 15:56:23 -07002398 ctx.VisitDirectDeps(func(module android.Module) {
2399 otherName := ctx.OtherModuleName(module)
2400 tag := ctx.OtherModuleDependencyTag(module)
2401
2402 if IsJniDepTag(tag) {
2403 // Handled by AndroidApp.collectAppDeps
2404 return
2405 }
2406 if tag == certificateTag {
2407 // Handled by AndroidApp.collectAppDeps
2408 return
2409 }
2410
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002411 if sdkInfo, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -07002412 switch tag {
Jihoon Kang28c96572024-09-11 23:44:44 +00002413 case sdkLibTag, libTag, staticLibTag:
Jihoon Kang28c96572024-09-11 23:44:44 +00002414 generatingLibsString := android.PrettyConcat(
2415 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
2416 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 -07002417 }
Colin Cross313aa542023-12-13 13:47:44 -08002418 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2419 if sdkLinkType != javaPlatform {
2420 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2421 // dep is a sysprop implementation library, but this module is not linking against
2422 // the platform, so it gets the sysprop public stubs library instead. Replace
2423 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2424 dep = syspropDep.JavaInfo
2425 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002426 }
2427 switch tag {
2428 case bootClasspathTag:
2429 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002430 if dep.TransitiveStaticLibsHeaderJars != nil {
2431 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2432 }
Liz Kammeref28a4c2022-09-23 16:50:56 -04002433 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002434 if _, ok := module.(*Plugin); ok {
2435 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2436 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002437 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002438 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002439 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2440 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2441 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2442 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002443 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2444 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2445 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002446
2447 if dep.TransitiveStaticLibsHeaderJars != nil {
2448 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2449 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002450 case java9LibTag:
2451 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002452 if dep.TransitiveStaticLibsHeaderJars != nil {
2453 transitiveJava9ClasspathHeaderJars = append(transitiveJava9ClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2454 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002455 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002456 if _, ok := module.(*Plugin); ok {
2457 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2458 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002459 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2460 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2461 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2462 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2463 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2464 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2465 // Turbine doesn't run annotation processors, so any module that uses an
2466 // annotation processor that generates API is incompatible with the turbine
2467 // optimization.
2468 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Jihoon Kang705e63e2024-03-13 01:21:16 +00002469 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.AconfigIntermediateCacheOutputPaths...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002470
2471 if dep.TransitiveStaticLibsHeaderJars != nil {
2472 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2473 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, dep.TransitiveStaticLibsHeaderJars)
2474 }
2475 if dep.TransitiveStaticLibsImplementationJars != nil {
2476 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, dep.TransitiveStaticLibsImplementationJars)
2477 }
2478 if dep.TransitiveStaticLibsResourceJars != nil {
2479 transitiveStaticJarsResourceLibs = append(transitiveStaticJarsResourceLibs, dep.TransitiveStaticLibsResourceJars)
2480 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002481 case pluginTag:
2482 if plugin, ok := module.(*Plugin); ok {
2483 if plugin.pluginProperties.Processor_class != nil {
2484 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2485 } else {
2486 addPlugins(&deps, dep.ImplementationAndResourcesJars)
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 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2492 } else {
2493 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2494 }
2495 case errorpronePluginTag:
2496 if _, ok := module.(*Plugin); ok {
2497 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2498 } else {
2499 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2500 }
2501 case exportedPluginTag:
2502 if plugin, ok := module.(*Plugin); ok {
2503 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2504 if plugin.pluginProperties.Processor_class != nil {
2505 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2506 }
2507 // Turbine doesn't run annotation processors, so any module that uses an
2508 // annotation processor that generates API is incompatible with the turbine
2509 // optimization.
2510 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2511 } else {
2512 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2513 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07002514 case kotlinPluginTag:
2515 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002516 case syspropPublicStubDepTag:
2517 // This is a sysprop implementation library, forward the JavaInfoProvider from
2518 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002519 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002520 JavaInfo: dep,
2521 })
2522 }
2523 } else if dep, ok := module.(android.SourceFileProducer); ok {
2524 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002525 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002526 checkProducesJars(ctx, dep)
2527 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002528 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002529 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars,
2530 android.NewDepSet(android.PREORDER, dep.Srcs(), nil))
Jaewoong Jung26342642021-03-17 15:56:23 -07002531 case staticLibTag:
2532 checkProducesJars(ctx, dep)
2533 deps.classpath = append(deps.classpath, dep.Srcs()...)
2534 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2535 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002536
2537 depHeaderJars := android.NewDepSet(android.PREORDER, dep.Srcs(), nil)
2538 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, depHeaderJars)
2539 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, depHeaderJars)
2540 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, depHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07002541 }
Jihoon Kang705e63e2024-03-13 01:21:16 +00002542 } else if dep, ok := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider); ok {
Jihoon Kang3921f0b2024-03-12 23:51:37 +00002543 switch tag {
2544 case staticLibTag:
2545 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.IntermediateCacheOutputPaths...)
2546 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002547 } else {
2548 switch tag {
2549 case bootClasspathTag:
2550 // If a system modules dependency has been added to the bootclasspath
2551 // then add its libs to the bootclasspath.
Colin Crossb61c2262024-08-08 14:04:42 -07002552 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002553 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars...)
2554 if sm.TransitiveStaticLibsHeaderJars != nil {
2555 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars,
2556 sm.TransitiveStaticLibsHeaderJars)
2557 }
Colin Crossb61c2262024-08-08 14:04:42 -07002558 } else {
2559 ctx.PropertyErrorf("boot classpath dependency %q does not provide SystemModulesProvider",
2560 ctx.OtherModuleName(module))
2561 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002562
2563 case systemModulesTag:
2564 if deps.systemModules != nil {
2565 panic("Found two system module dependencies")
2566 }
Colin Crossb61c2262024-08-08 14:04:42 -07002567 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
2568 deps.systemModules = &systemModules{sm.OutputDir, sm.OutputDirDeps}
2569 } else {
2570 ctx.PropertyErrorf("system modules dependency %q does not provide SystemModulesProvider",
2571 ctx.OtherModuleName(module))
2572 }
Paul Duffin53a70a42022-01-11 14:35:55 +00002573
2574 case instrumentationForTag:
2575 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 -07002576 }
2577 }
2578
Spandan Das8aac9932024-07-18 23:14:13 +00002579 if android.InList(tag, compileDependencyTags) {
2580 // Add the dependency name to compileDepNames so that it can be recorded in module_bp_java_deps.json
2581 j.compileDepNames = append(j.compileDepNames, otherName)
2582 }
2583
Jaewoong Jung26342642021-03-17 15:56:23 -07002584 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiakai Zhang36937082024-04-15 11:15:50 +00002585 addMissingOptionalUsesLibsFromDep(ctx, module, &j.usesLibrary)
Jaewoong Jung26342642021-03-17 15:56:23 -07002586 })
2587
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002588 deps.transitiveStaticLibsHeaderJars = transitiveStaticJarsHeaderLibs
2589 deps.transitiveStaticLibsImplementationJars = transitiveStaticJarsImplementationLibs
2590 deps.transitiveStaticLibsResourceJars = transitiveStaticJarsResourceLibs
2591
2592 if ctx.Config().UseTransitiveJarsInClasspath() {
2593 depSet := android.NewDepSet(android.PREORDER, nil, transitiveClasspathHeaderJars)
2594 deps.classpath = depSet.ToList()
2595 depSet = android.NewDepSet(android.PREORDER, nil, transitiveBootClasspathHeaderJars)
2596 deps.bootClasspath = depSet.ToList()
2597 depSet = android.NewDepSet(android.PREORDER, nil, transitiveJava9ClasspathHeaderJars)
2598 deps.java9Classpath = depSet.ToList()
2599 }
2600
2601 if ctx.Device() {
2602 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
2603 if sdkDep.invalidVersion {
2604 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2605 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2606 } else if sdkDep.useFiles {
2607 // sdkDep.jar is actually equivalent to turbine header.jar.
2608 deps.classpath = append(slices.Clone(classpath(sdkDep.jars)), deps.classpath...)
2609 deps.dexClasspath = append(slices.Clone(classpath(sdkDep.jars)), deps.dexClasspath...)
2610 deps.aidlPreprocess = sdkDep.aidl
2611 // Add the sdk module dependency to `compileDepNames`.
2612 // This ensures that the dependency is reported in `module_bp_java_deps.json`
2613 // TODO (b/358608607): Move this to decodeSdkDep
2614 sdkSpec := android.SdkContext(j).SdkVersion(ctx)
2615 j.compileDepNames = append(j.compileDepNames, fmt.Sprintf("sdk_%s_%s_android", sdkSpec.Kind.String(), sdkSpec.ApiLevel.String()))
2616 } else {
2617 deps.aidlPreprocess = sdkDep.aidl
2618 }
2619 }
2620
Jaewoong Jung26342642021-03-17 15:56:23 -07002621 return deps
2622}
2623
Joe Onorato349ae8d2024-02-05 22:46:00 +00002624// Provider for jarjar renaming rules.
2625//
2626// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2627// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2628// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2629// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2630// be renamed from that module.
2631// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002632type DependencyUse int
2633
2634const (
2635 RenameUseInvalid DependencyUse = iota
2636 RenameUseInclude
2637 RenameUseExclude
2638)
2639
2640type RenameUseElement struct {
2641 DepName string
2642 RenameUse DependencyUse
2643 Why string // token for determining where in the logic the decision was made.
2644}
2645
Joe Onorato349ae8d2024-02-05 22:46:00 +00002646type JarJarProviderData struct {
2647 // Mapping of class names: original --> renamed. If the value is "", the class will be
2648 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2649 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002650 Rename map[string]string
2651 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002652}
2653
2654func (this JarJarProviderData) GetDebugString() string {
2655 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002656 for _, k := range android.SortedKeys(this.Rename) {
2657 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002658 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2659 result += k + "--&gt;" + v + ";"
2660 }
2661 }
2662 return result
2663}
2664
2665var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2666
2667var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2668
2669func init() {
2670 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
Yu Liu26a716d2024-08-30 23:40:32 +00002671
2672 gob.Register(BaseJarJarProviderData{})
Joe Onorato349ae8d2024-02-05 22:46:00 +00002673}
2674
2675// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2676// whether they are java modules or not.
2677type BaseJarJarProviderData struct {
2678 JarJarProviderData JarJarProviderData
2679}
2680
2681func (this BaseJarJarProviderData) GetDebugString() string {
2682 return this.JarJarProviderData.GetDebugString()
2683}
2684
2685var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2686
2687// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2688// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2689// either JarJarProvider or BaseJarJarProvider.
2690func mergeJarJarPrefixes(ctx android.ModuleContext) {
2691 mod := ctx.Module()
2692 // Explicitly avoid propagating into some module types.
2693 switch reflect.TypeOf(mod).String() {
2694 case "*java.Droidstubs":
2695 return
2696 }
2697 jarJarData := collectDirectDepsProviders(ctx)
2698 if jarJarData != nil {
2699 providerData := BaseJarJarProviderData{
2700 JarJarProviderData: *jarJarData,
2701 }
2702 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2703 }
2704
2705}
2706
2707// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2708func (module *Module) addJarJarRenameRule(original string, renamed string) {
2709 if module.jarjarRenameRules == nil {
2710 module.jarjarRenameRules = make(map[string]string)
2711 }
2712 module.jarjarRenameRules[original] = renamed
2713}
2714
2715func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2716 // Gather repackage information from deps
2717 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002718
2719 module := ctx.Module()
2720 moduleName := module.Name()
2721
Colin Cross648daea2024-09-12 14:35:29 -07002722 ctx.VisitDirectDeps(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002723 tag := ctx.OtherModuleDependencyTag(m)
2724 // This logic mirrors that in (*Module).collectDeps above. There are several places
2725 // where we explicitly return RenameUseExclude, even though it is the default, to
2726 // indicate that it has been verified to be the case.
2727 //
2728 // Note well: there are probably cases that are getting to the unconditional return
2729 // and are therefore wrong.
2730 shouldIncludeRenames := func() (DependencyUse, string) {
2731 if moduleName == m.Name() {
2732 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2733 }
2734 if sc, ok := module.(android.SdkContext); ok {
2735 if ctx.Device() {
2736 sdkDep := decodeSdkDep(ctx, sc)
2737 if !sdkDep.invalidVersion && sdkDep.useFiles {
2738 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002739 }
2740 }
LaMont Jones63683e42024-02-08 14:30:45 -08002741 }
2742 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2743 return RenameUseExclude, "tags"
2744 }
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002745 if _, ok := android.OtherModuleProvider(ctx, m, SdkLibraryInfoProvider); ok {
LaMont Jones63683e42024-02-08 14:30:45 -08002746 switch tag {
2747 case sdkLibTag, libTag:
2748 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2749 }
2750 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2751 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2752 switch ji.StubsLinkType {
2753 case Stubs:
2754 return RenameUseExclude, "info"
2755 case Implementation:
2756 return RenameUseInclude, "info"
2757 default:
LaMont Jones09721862024-06-11 10:30:50 -07002758 //fmt.Printf("collectDirectDepsProviders: %v -> %v StubsLinkType unknown\n", module, m)
LaMont Jones63683e42024-02-08 14:30:45 -08002759 // Fall through to the heuristic logic.
2760 }
2761 switch reflect.TypeOf(m).String() {
2762 case "*java.GeneratedJavaLibraryModule":
2763 // Probably a java_aconfig_library module.
2764 // TODO: make this check better.
2765 return RenameUseInclude, "reflect"
2766 }
2767 switch tag {
2768 case bootClasspathTag:
2769 return RenameUseExclude, "tagswitch"
2770 case sdkLibTag, libTag, instrumentationForTag:
2771 return RenameUseInclude, "tagswitch"
2772 case java9LibTag:
2773 return RenameUseExclude, "tagswitch"
2774 case staticLibTag:
2775 return RenameUseInclude, "tagswitch"
2776 case pluginTag:
2777 return RenameUseInclude, "tagswitch"
2778 case errorpronePluginTag:
2779 return RenameUseInclude, "tagswitch"
2780 case exportedPluginTag:
2781 return RenameUseInclude, "tagswitch"
LaMont Jones63683e42024-02-08 14:30:45 -08002782 case kotlinPluginTag:
2783 return RenameUseInclude, "tagswitch"
2784 default:
2785 return RenameUseExclude, "tagswitch"
2786 }
2787 } else if _, ok := m.(android.SourceFileProducer); ok {
2788 switch tag {
2789 case sdkLibTag, libTag, staticLibTag:
2790 return RenameUseInclude, "srcfile"
2791 default:
2792 return RenameUseExclude, "srcfile"
2793 }
Yu Liu67a28422024-03-05 00:36:31 +00002794 } else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
Jihoon Kang03d014f2024-02-16 22:22:18 +00002795 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002796 } else {
2797 switch tag {
2798 case bootClasspathTag:
2799 return RenameUseExclude, "else"
2800 case systemModulesTag:
2801 return RenameUseInclude, "else"
2802 }
2803 }
2804 // If we got here, choose the safer option, which may lead to a build failure, rather
2805 // than runtime failures on the device.
2806 return RenameUseExclude, "end"
2807 }
2808
2809 if result == nil {
2810 result = &JarJarProviderData{
2811 Rename: make(map[string]string),
2812 RenameUse: make([]RenameUseElement, 0),
2813 }
2814 }
2815 how, why := shouldIncludeRenames()
2816 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2817 if how != RenameUseInclude {
2818 // Nothing to merge.
2819 return
2820 }
2821
2822 merge := func(theirs *JarJarProviderData) {
2823 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002824 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2825 result.Rename[orig] = renamed
2826 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2827 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2828 result.Rename[orig] = renamed
2829 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2830 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2831 continue
2832 }
2833 }
2834 }
2835 }
2836 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2837 merge(&theirs)
2838 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2839 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2840 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2841 // to java.Module.
2842 merge(&theirs.JarJarProviderData)
2843 }
2844 })
2845 return
2846}
2847
2848func (this Module) GetDebugString() string {
2849 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2850}
2851
2852// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2853// us, and if it's been set, apply the jarjar_prefix property to rename them.
2854func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2855 // Gather repackage information from deps
2856 result := collectDirectDepsProviders(ctx)
2857
Joe Onoratoa5d17172024-07-20 17:39:56 -07002858 add := func(orig string, renamed string) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002859 if result == nil {
2860 result = &JarJarProviderData{
2861 Rename: make(map[string]string),
2862 }
2863 }
2864 if renamed != "" {
2865 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2866 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
Joe Onoratoa5d17172024-07-20 17:39:56 -07002867 return
Joe Onorato349ae8d2024-02-05 22:46:00 +00002868 }
2869 }
2870 (*result).Rename[orig] = renamed
2871 }
2872
Joe Onoratoa5d17172024-07-20 17:39:56 -07002873 // Update that with entries we've stored for ourself
2874 for orig, renamed := range module.jarjarRenameRules {
2875 add(orig, renamed)
2876 }
2877
2878 // Update that with entries given in the jarjar_rename property.
2879 for _, orig := range module.properties.Jarjar_rename {
2880 add(orig, "")
2881 }
2882
Joe Onorato349ae8d2024-02-05 22:46:00 +00002883 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2884 if result == nil {
2885 return nil
2886 }
2887
2888 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2889 // that have not yet been renamed.
2890 prefix := proptools.String(module.properties.Jarjar_prefix)
2891 if prefix != "" {
2892 if prefix[0] == '.' {
2893 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2894 return nil
2895 }
2896 if prefix[len(prefix)-1] == '.' {
2897 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2898 return nil
2899 }
2900
2901 var updated map[string]string
2902 for orig, renamed := range (*result).Rename {
2903 if renamed == "" {
2904 if updated == nil {
2905 updated = make(map[string]string)
2906 }
2907 updated[orig] = prefix + "." + orig
2908 }
2909 }
2910 for orig, renamed := range updated {
2911 (*result).Rename[orig] = renamed
2912 }
2913 }
2914
2915 return result
2916}
2917
2918// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2919// to "" won't be in this list because they shouldn't be renamed yet.
2920func getJarJarRuleText(provider *JarJarProviderData) string {
2921 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002922 for _, orig := range android.SortedKeys(provider.Rename) {
2923 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002924 if renamed != "" {
2925 result += "rule " + orig + " " + renamed + "\n"
2926 }
2927 }
2928 return result
2929}
2930
Zi Wangddb2ee52024-04-02 16:44:02 +00002931// Repackage the flags if the jarjar rule txt for the flags is generated
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002932func (j *Module) repackageFlagsIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Zi Wangddb2ee52024-04-02 16:44:02 +00002933 if j.repackageJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002934 return infile, false
Zi Wangddb2ee52024-04-02 16:44:02 +00002935 }
Colin Crossedec77c2024-07-26 15:25:40 -07002936 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", info, jarName)
Zi Wangddb2ee52024-04-02 16:44:02 +00002937 TransformJarJar(ctx, repackagedJarjarFile, infile, j.repackageJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002938 return repackagedJarjarFile, true
Zi Wangddb2ee52024-04-02 16:44:02 +00002939}
2940
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002941func (j *Module) jarjarIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Colin Crossedec77c2024-07-26 15:25:40 -07002942 if j.expandJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002943 return infile, false
Colin Crossedec77c2024-07-26 15:25:40 -07002944 }
2945 jarjarFile := android.PathForModuleOut(ctx, "jarjar", info, jarName)
2946 TransformJarJar(ctx, jarjarFile, infile, j.expandJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002947 return jarjarFile, true
Colin Crossedec77c2024-07-26 15:25:40 -07002948
2949}
2950
Jaewoong Jung26342642021-03-17 15:56:23 -07002951func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2952 deps.processorPath = append(deps.processorPath, pluginJars...)
2953 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2954}
2955
2956// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2957// this interface.
2958type ProvidesUsesLib interface {
2959 ProvidesUsesLib() *string
2960}
2961
2962func (j *Module) ProvidesUsesLib() *string {
2963 return j.usesLibraryProperties.Provides_uses_lib
2964}
satayev1c564cc2021-05-25 19:50:30 +01002965
2966type ModuleWithStem interface {
2967 Stem() string
2968}
2969
2970var _ ModuleWithStem = (*Module)(nil)
Jiakai Zhangf98da192024-04-15 11:15:41 +00002971
2972type ModuleWithUsesLibrary interface {
2973 UsesLibrary() *usesLibrary
2974}
2975
2976func (j *Module) UsesLibrary() *usesLibrary {
2977 return &j.usesLibrary
2978}
2979
2980var _ ModuleWithUsesLibrary = (*Module)(nil)