blob: 19f6c5d095ff2fce0da79e0bfe09690a972b9728 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
Yu Liu26a716d2024-08-30 23:40:32 +000018 "encoding/gob"
Jaewoong Jung26342642021-03-17 15:56:23 -070019 "fmt"
20 "path/filepath"
Joe Onorato349ae8d2024-02-05 22:46:00 +000021 "reflect"
22 "slices"
Jaewoong Jung26342642021-03-17 15:56:23 -070023 "strconv"
24 "strings"
25
Colin Crossd788b3e2023-11-28 13:14:56 -080026 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070027 "github.com/google/blueprint/pathtools"
28 "github.com/google/blueprint/proptools"
29
30 "android/soong/android"
31 "android/soong/dexpreopt"
32 "android/soong/java/config"
33)
34
35// This file contains the definition and the implementation of the base module that most
36// source-based Java module structs embed.
37
38// TODO:
39// Autogenerated files:
40// Renderscript
41// Post-jar passes:
42// Proguard
43// Rmtypedefs
44// DroidDoc
45// Findbugs
46
47// Properties that are common to most Java modules, i.e. whether it's a host or device module.
48type CommonProperties struct {
49 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
50 // or .aidl files.
51 Srcs []string `android:"path,arch_variant"`
52
53 // list Kotlin of source files containing Kotlin code that should be treated as common code in
54 // a codebase that supports Kotlin multiplatform. See
55 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
56 Common_srcs []string `android:"path,arch_variant"`
57
58 // list of source files that should not be used to build the Java module.
59 // This is most useful in the arch/multilib variants to remove non-common files
60 Exclude_srcs []string `android:"path,arch_variant"`
61
62 // list of directories containing Java resources
63 Java_resource_dirs []string `android:"arch_variant"`
64
65 // list of directories that should be excluded from java_resource_dirs
66 Exclude_java_resource_dirs []string `android:"arch_variant"`
67
68 // list of files to use as Java resources
69 Java_resources []string `android:"path,arch_variant"`
70
71 // list of files that should be excluded from java_resources and java_resource_dirs
72 Exclude_java_resources []string `android:"path,arch_variant"`
73
74 // list of module-specific flags that will be used for javac compiles
75 Javacflags []string `android:"arch_variant"`
76
77 // list of module-specific flags that will be used for kotlinc compiles
78 Kotlincflags []string `android:"arch_variant"`
79
80 // list of java libraries that will be in the classpath
81 Libs []string `android:"arch_variant"`
82
83 // list of java libraries that will be compiled into the resulting jar
Cole Faustb7493472024-08-28 11:55:52 -070084 Static_libs proptools.Configurable[[]string] `android:"arch_variant"`
Jaewoong Jung26342642021-03-17 15:56:23 -070085
86 // manifest file to be included in resulting jar
87 Manifest *string `android:"path"`
88
89 // if not blank, run jarjar using the specified rules file
90 Jarjar_rules *string `android:"path,arch_variant"`
91
Joe Onoratoa5d17172024-07-20 17:39:56 -070092 // java class names to rename with jarjar when a reverse dependency has a jarjar_prefix
93 // property.
94 Jarjar_rename []string
95
Joe Onorato349ae8d2024-02-05 22:46:00 +000096 // if not blank, used as prefix to generate repackage rule
97 Jarjar_prefix *string
98
Jaewoong Jung26342642021-03-17 15:56:23 -070099 // If not blank, set the java version passed to javac as -source and -target
100 Java_version *string
101
102 // If set to true, allow this module to be dexed and installed on devices. Has no
103 // effect on host modules, which are always considered installable.
104 Installable *bool
105
106 // If set to true, include sources used to compile the module in to the final jar
107 Include_srcs *bool
108
109 // If not empty, classes are restricted to the specified packages and their sub-packages.
110 // This restriction is checked after applying jarjar rules and including static libs.
111 Permitted_packages []string
112
113 // List of modules to use as annotation processors
114 Plugins []string
115
Luca Stefani50098f72024-10-12 17:55:31 +0200116 // List of modules to use as kotlin plugin
117 Kotlin_plugins []string
118
Jaewoong Jung26342642021-03-17 15:56:23 -0700119 // List of modules to export to libraries that directly depend on this library as annotation
120 // processors. Note that if the plugins set generates_api: true this will disable the turbine
121 // optimization on modules that depend on this module, which will reduce parallelism and cause
122 // more recompilation.
123 Exported_plugins []string
124
125 // The number of Java source entries each Javac instance can process
126 Javac_shard_size *int64
127
128 // Add host jdk tools.jar to bootclasspath
129 Use_tools_jar *bool
130
131 Openjdk9 struct {
132 // List of source files that should only be used when passing -source 1.9 or higher
133 Srcs []string `android:"path"`
134
135 // List of javac flags that should only be used when passing -source 1.9 or higher
136 Javacflags []string
137 }
138
139 // When compiling language level 9+ .java code in packages that are part of
140 // a system module, patch_module names the module that your sources and
141 // dependencies should be patched into. The Android runtime currently
142 // doesn't implement the JEP 261 module system so this option is only
143 // supported at compile time. It should only be needed to compile tests in
144 // packages that exist in libcore and which are inconvenient to move
145 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400146 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700147
148 Jacoco struct {
149 // List of classes to include for instrumentation with jacoco to collect coverage
150 // information at runtime when building with coverage enabled. If unset defaults to all
151 // classes.
152 // Supports '*' as the last character of an entry in the list as a wildcard match.
153 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
154 // it matches classes in the package that have the class name as a prefix.
155 Include_filter []string
156
157 // List of classes to exclude from instrumentation with jacoco to collect coverage
158 // information at runtime when building with coverage enabled. Overrides classes selected
159 // by the include_filter property.
160 // Supports '*' as the last character of an entry in the list as a wildcard match.
161 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
162 // it matches classes in the package that have the class name as a prefix.
163 Exclude_filter []string
164 }
165
166 Errorprone struct {
167 // List of javac flags that should only be used when running errorprone.
168 Javacflags []string
169
170 // List of java_plugin modules that provide extra errorprone checks.
171 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700172
Cole Faust2b1536e2021-06-18 12:25:54 -0700173 // This property can be in 3 states. When set to true, errorprone will
174 // be run during the regular build. When set to false, errorprone will
175 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
176 // environment variable is true. Setting this to false will improve build
177 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700178 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 }
180
181 Proto struct {
182 // List of extra options that will be passed to the proto generator.
183 Output_params []string
184 }
185
Sam Delmericoc7593722022-08-31 15:57:52 -0400186 // If true, then jacocoagent is automatically added as a libs dependency so that
187 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700188 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000189 // If true, then the module supports statically including the jacocoagent
190 // into the library.
191 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700192
193 // List of files to include in the META-INF/services folder of the resulting jar.
194 Services []string `android:"path,arch_variant"`
195
196 // If true, package the kotlin stdlib into the jar. Defaults to true.
197 Static_kotlin_stdlib *bool `android:"arch_variant"`
198
199 // A list of java_library instances that provide additional hiddenapi annotations for the library.
200 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700201
202 // Additional srcJars tacked in by GeneratedJavaLibraryModule
203 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000204
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000205 // intermediate aconfig cache file tacked in by GeneratedJavaLibraryModule
206 Aconfig_Cache_files []android.Path `android:"mutated"`
207
Mark Whitea15790a2023-08-22 21:28:11 +0000208 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400209 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800210
211 // A list of files or dependencies to make available to the build sandbox. This is
212 // useful if source files are symlinks, the targets of the symlinks must be listed here.
213 // Note that currently not all actions implemented by android_apps are sandboxed, so you
214 // may only see this being necessary in lint builds.
215 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000216
217 // Property signifying whether the module compiles stubs or not.
218 // Should be set to true when srcs of this module are stub files.
219 // This property does not need to be set to true when the module depends on
220 // the stubs via libs, but should be set to true when the module depends on
221 // the stubs via static libs.
222 Is_stubs_module *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700223
Makoto Onuki7ded3822024-03-28 14:42:20 -0700224 Ravenizer struct {
John Wu989ee842024-10-04 00:21:43 +0000225 // If true, enable the "Ravenizer" tool on the output jar.
226 // "Ravenizer" is a tool for Ravenwood tests, but it can also be enabled on other kinds
227 // of java targets.
Makoto Onuki7ded3822024-03-28 14:42:20 -0700228 Enabled *bool
John Wu989ee842024-10-04 00:21:43 +0000229
230 // If true, the "Ravenizer" tool will remove all Mockito and DexMaker
231 // classes from the output jar.
232 Strip_mockito *bool
Makoto Onuki7ded3822024-03-28 14:42:20 -0700233 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +0000234
235 // Contributing api surface of the stub module. Is not visible to bp modules, and should
236 // only be set for stub submodules generated by the java_sdk_library
237 Stub_contributing_api *string `blueprint:"mutated"`
Yihan Dong8be09c22024-08-29 15:32:13 +0800238
239 // If true, enable the "ApiMapper" tool on the output jar. "ApiMapper" is a tool to inject
240 // bytecode to log API calls.
241 ApiMapper bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700242}
243
244// Properties that are specific to device modules. Host module factories should not add these when
245// constructing a new module.
246type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000247 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000248 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000249 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000250 // 1) numerical API level, "current", "none", or "core_platform"
251 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
252 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
253 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700254 Sdk_version *string
255
satayev0a420e72021-11-29 17:25:52 +0000256 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
257 // Defaults to empty string "". See sdk_version for possible values.
258 Max_sdk_version *string
259
William Loh5a082f92022-05-17 20:21:50 +0000260 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
261 // Defaults to empty string "". See sdk_version for possible values.
262 Replace_max_sdk_version_placeholder *string
263
Jaewoong Jung26342642021-03-17 15:56:23 -0700264 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000265 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700266 Target_sdk_version *string
267
268 // Whether to compile against the platform APIs instead of an SDK.
269 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000270 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700271 Platform_apis *bool
272
273 Aidl struct {
274 // Top level directories to pass to aidl tool
275 Include_dirs []string
276
277 // Directories rooted at the Android.bp file to pass to aidl tool
278 Local_include_dirs []string
279
280 // directories that should be added as include directories for any aidl sources of modules
281 // that depend on this module, as well as to aidl for this module.
282 Export_include_dirs []string
283
284 // whether to generate traces (for systrace) for this interface
285 Generate_traces *bool
286
287 // whether to generate Binder#GetTransaction name method.
288 Generate_get_transaction_name *bool
289
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100290 // whether all interfaces should be annotated with required permissions.
291 Enforce_permissions *bool
292
293 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
294 Enforce_permissions_exceptions []string `android:"path"`
295
Jaewoong Jung26342642021-03-17 15:56:23 -0700296 // list of flags that will be passed to the AIDL compiler
297 Flags []string
298 }
299
300 // If true, export a copy of the module as a -hostdex module for host testing.
301 Hostdex *bool
302
303 Target struct {
304 Hostdex struct {
305 // Additional required dependencies to add to -hostdex modules.
306 Required []string
307 }
308 }
309
310 // When targeting 1.9 and above, override the modules to use with --system,
311 // otherwise provides defaults libraries to add to the bootclasspath.
312 System_modules *string
313
Jaewoong Jung26342642021-03-17 15:56:23 -0700314 IsSDKLibrary bool `blueprint:"mutated"`
315
316 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
317 // Defaults to false.
318 V4_signature *bool
319
320 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
321 // public stubs library.
322 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000323
324 HiddenAPIPackageProperties
325 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700326}
327
yangbill2af0b6e2024-03-15 09:29:29 +0000328// Properties that can be overridden by overriding module (e.g. override_android_app)
329type OverridableProperties struct {
Jooyung Han01d80d82022-01-08 12:16:32 +0900330 // set the name of the output. If not set, `name` is used.
331 // To override a module with this property set, overriding module might need to set this as well.
332 // Otherwise, both the overridden and the overriding modules will have the same output name, which
333 // can cause the duplicate output error.
334 Stem *string
Spandan Dasb9c58352024-05-13 18:29:45 +0000335
336 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
337 // Defaults to sdk_version if not set. See sdk_version for possible values.
338 Min_sdk_version *string
Jooyung Han01d80d82022-01-08 12:16:32 +0900339}
340
Jaewoong Jung26342642021-03-17 15:56:23 -0700341// Functionality common to Module and Import
342//
343// It is embedded in Module so its functionality can be used by methods in Module
344// but it is currently only initialized by Import and Library.
345type embeddableInModuleAndImport struct {
346
347 // Functionality related to this being used as a component of a java_sdk_library.
348 EmbeddableSdkLibraryComponent
349}
350
Paul Duffin71b33cc2021-06-23 11:39:47 +0100351func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
352 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700353}
354
355// Module/Import's DepIsInSameApex(...) delegates to this method.
356//
357// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
358// the one provided by ApexModuleBase.
359func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
360 // dependencies other than the static linkage are all considered crossing APEX boundary
361 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
362 return true
363 }
364 return false
365}
366
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100367// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
368// or an invalid path describing the reason it is invalid.
369//
370// It is unset if a dex jar isn't applicable, i.e. no build rule has been
371// requested to create one.
372//
373// If a dex jar has been requested to be built then it is set, and it may be
374// either a valid android.Path, or invalid with a reason message. The latter
375// happens if the source that should produce the dex file isn't able to.
376//
377// E.g. it is invalid with a reason message if there is a prebuilt APEX that
378// could produce the dex jar through a deapexer module, but the APEX isn't
379// installable so doing so wouldn't be safe.
380type OptionalDexJarPath struct {
381 isSet bool
382 path android.OptionalPath
383}
384
385// IsSet returns true if a path has been set, either invalid or valid.
386func (o OptionalDexJarPath) IsSet() bool {
387 return o.isSet
388}
389
390// Valid returns true if there is a path that is valid.
391func (o OptionalDexJarPath) Valid() bool {
392 return o.isSet && o.path.Valid()
393}
394
395// Path returns the valid path, or panics if it's either not set or is invalid.
396func (o OptionalDexJarPath) Path() android.Path {
397 if !o.isSet {
398 panic("path isn't set")
399 }
400 return o.path.Path()
401}
402
403// PathOrNil returns the path if it's set and valid, or else nil.
404func (o OptionalDexJarPath) PathOrNil() android.Path {
405 if o.Valid() {
406 return o.Path()
407 }
408 return nil
409}
410
411// InvalidReason returns the reason for an invalid path, which is never "". It
412// returns "" for an unset or valid path.
413func (o OptionalDexJarPath) InvalidReason() string {
414 if !o.isSet {
415 return ""
416 }
417 return o.path.InvalidReason()
418}
419
420func (o OptionalDexJarPath) String() string {
421 if !o.isSet {
422 return "<unset>"
423 }
424 return o.path.String()
425}
426
427// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
428func makeUnsetDexJarPath() OptionalDexJarPath {
429 return OptionalDexJarPath{isSet: false}
430}
431
432// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
433// the given OptionalPath, which may be valid or invalid.
434func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
435 return OptionalDexJarPath{isSet: true, path: path}
436}
437
438// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
439// valid given path. It returns an unset OptionalDexJarPath if the given path is
440// nil.
441func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
442 if path == nil {
443 return makeUnsetDexJarPath()
444 }
445 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
446}
447
Jaewoong Jung26342642021-03-17 15:56:23 -0700448// Module contains the properties and members used by all java module types
449type Module struct {
450 android.ModuleBase
451 android.DefaultableModuleBase
452 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700453
454 // Functionality common to Module and Import.
455 embeddableInModuleAndImport
456
457 properties CommonProperties
458 protoProperties android.ProtoProperties
459 deviceProperties DeviceProperties
460
yangbill2af0b6e2024-03-15 09:29:29 +0000461 overridableProperties OverridableProperties
Ronald Braunsteincdc66f42024-04-12 11:23:19 -0700462 sourceProperties android.SourceProperties
Jooyung Han01d80d82022-01-08 12:16:32 +0900463
Jaewoong Jung26342642021-03-17 15:56:23 -0700464 // jar file containing header classes including static library dependencies, suitable for
465 // inserting into the bootclasspath/classpath of another compile
466 headerJarFile android.Path
467
468 // jar file containing implementation classes including static library dependencies but no
469 // resources
470 implementationJarFile android.Path
471
Jaewoong Jung26342642021-03-17 15:56:23 -0700472 // args and dependencies to package source files into a srcjar
473 srcJarArgs []string
474 srcJarDeps android.Paths
475
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000476 // the source files of this module and all its static dependencies
477 transitiveSrcFiles *android.DepSet[android.Path]
478
Jaewoong Jung26342642021-03-17 15:56:23 -0700479 // jar file containing implementation classes and resources including static library
480 // dependencies
481 implementationAndResourcesJar android.Path
482
483 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100484 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700485
486 // output file containing uninstrumented classes that will be instrumented by jacoco
487 jacocoReportClassesFile android.Path
488
489 // output file of the module, which may be a classes jar or a dex jar
490 outputFile android.Path
491 extraOutputFiles android.Paths
492
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100493 exportAidlIncludeDirs android.Paths
494 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700495
496 logtagsSrcs android.Paths
497
498 // installed file for binary dependency
499 installFile android.Path
500
Colin Cross3108ce12021-11-10 14:38:50 -0800501 // installed file for hostdex copy
502 hostdexInstallFile android.InstallPath
503
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800504 // list of unique .java and .kt source files
505 uniqueSrcFiles android.Paths
506
507 // list of srcjars that was passed to javac
508 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700509
510 // manifest file to use instead of properties.Manifest
511 overrideManifest android.OptionalPath
512
Jaewoong Jung26342642021-03-17 15:56:23 -0700513 // list of plugins that this java module is exporting
514 exportedPluginJars android.Paths
515
516 // list of plugins that this java module is exporting
517 exportedPluginClasses []string
518
519 // if true, the exported plugins generate API and require disabling turbine.
520 exportedDisableTurbine bool
521
522 // list of source files, collected from srcFiles with unique java and all kt files,
523 // will be used by android.IDEInfo struct
524 expandIDEInfoCompiledSrcs []string
525
526 // expanded Jarjar_rules
527 expandJarjarRules android.Path
528
Joe Onorato349ae8d2024-02-05 22:46:00 +0000529 // jarjar rule for inherited jarjar rules
530 repackageJarjarRules android.Path
531
Jaewoong Jung26342642021-03-17 15:56:23 -0700532 // Extra files generated by the module type to be added as java resources.
533 extraResources android.Paths
534
535 hiddenAPI
536 dexer
537 dexpreopter
538 usesLibrary
539 linter
540
541 // list of the xref extraction files
Spandan Das1028d5a2024-08-19 21:45:48 +0000542 kytheFiles android.Paths
543 kytheKotlinFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700544
Jaewoong Jung26342642021-03-17 15:56:23 -0700545 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900546
547 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000548 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000549 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400550
551 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000552
553 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000554
555 // output file name based on Stem property.
556 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
557 // or the module should override Stem().
558 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700559
Joe Onorato349ae8d2024-02-05 22:46:00 +0000560 // Values that will be set in the JarJarProvider data for jarjar repackaging,
561 // and merged with our dependencies' rules.
562 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000563
564 stubsLinkType StubsLinkType
Jihoon Kang3921f0b2024-03-12 23:51:37 +0000565
566 // Paths to the aconfig intermediate cache files that are provided by the
567 // java_aconfig_library or java_library modules that are statically linked
568 // to this module. Does not contain cache files from all transitive dependencies.
569 aconfigCacheFiles android.Paths
Spandan Das8aac9932024-07-18 23:14:13 +0000570
571 // List of soong module dependencies required to compile the current module.
572 // This information is printed out to `Dependencies` field in module_bp_java_deps.json
573 compileDepNames []string
Makoto Onuki7ded3822024-03-28 14:42:20 -0700574
575 ravenizer struct {
576 enabled bool
577 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700578}
579
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000580var _ android.InstallableModule = (*Module)(nil)
581
582// To satisfy the InstallableModule interface
Jihoon Kang224ea082024-08-12 22:38:16 +0000583func (j *Module) StaticDependencyTags() []blueprint.DependencyTag {
584 return []blueprint.DependencyTag{staticLibTag}
585}
586
587// To satisfy the InstallableModule interface
588func (j *Module) DynamicDependencyTags() []blueprint.DependencyTag {
589 return []blueprint.DependencyTag{libTag, sdkLibTag, bootClasspathTag, systemModulesTag,
590 instrumentationForTag, java9LibTag}
Jihoon Kangf86fe9a2024-06-26 22:18:10 +0000591}
592
593// Overrides android.ModuleBase.InstallInProduct()
594func (j *Module) InstallInProduct() bool {
595 return j.ProductSpecific()
596}
597
Jihoon Kang85bc1932024-07-01 17:04:46 +0000598var _ android.StubsAvailableModule = (*Module)(nil)
599
600// To safisfy the StubsAvailableModule interface
601func (j *Module) IsStubsModule() bool {
602 return proptools.Bool(j.properties.Is_stubs_module)
603}
604
Jiyong Park92315372021-04-02 08:45:46 +0900605func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
606 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900607 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700608 return nil
609 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900610 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000611 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700612 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
613 } else {
614 // Treat stable core platform as stable.
615 return nil
616 }
617 } else {
618 return fmt.Errorf("non stable SDK %v", sdkVersion)
619 }
620}
621
622// checkSdkVersions enforces restrictions around SDK dependencies.
623func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
624 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900625 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900626 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700627 ctx.PropertyErrorf("sdk_version",
628 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
629 }
630 }
631 }
632
633 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
634 // See rank() for details.
635 ctx.VisitDirectDeps(func(module android.Module) {
636 tag := ctx.OtherModuleDependencyTag(module)
637 switch module.(type) {
638 // TODO(satayev): cover other types as well, e.g. imports
639 case *Library, *AndroidLibrary:
640 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400641 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700642 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
643 }
644 }
645 })
646}
647
648func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900649 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700650 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900651 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700652 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000653 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 -0700654 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000655 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 -0700656 }
657
658 }
659}
660
Mark Whitea15790a2023-08-22 21:28:11 +0000661func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
662 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400663 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000664 installable := proptools.Bool(j.properties.Installable)
665
666 if headersOnly && installable {
667 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.")
668 }
669 }
670}
671
Jaewoong Jung26342642021-03-17 15:56:23 -0700672func (j *Module) addHostProperties() {
673 j.AddProperties(
674 &j.properties,
yangbill2af0b6e2024-03-15 09:29:29 +0000675 &j.overridableProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700676 &j.protoProperties,
677 &j.usesLibraryProperties,
678 )
679}
680
681func (j *Module) addHostAndDeviceProperties() {
682 j.addHostProperties()
683 j.AddProperties(
684 &j.deviceProperties,
685 &j.dexer.dexProperties,
686 &j.dexpreoptProperties,
687 &j.linter.properties,
688 )
689}
690
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000691// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
692// makes it available through the hiddenAPIPropertyInfoProvider.
693func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
694 hiddenAPIInfo := newHiddenAPIPropertyInfo()
695
696 // Populate with flag file paths from the properties.
697 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
698
699 // Populate with package rules from the properties.
700 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
701
Colin Cross40213022023-12-13 15:19:49 -0800702 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000703}
704
mrziwang9f7b9f42024-07-10 12:18:06 -0700705// helper method for java modules to set OutputFilesProvider
706func setOutputFiles(ctx android.ModuleContext, m Module) {
707 ctx.SetOutputFiles(append(android.Paths{m.outputFile}, m.extraOutputFiles...), "")
708 ctx.SetOutputFiles(android.Paths{m.outputFile}, android.DefaultDistTag)
709 ctx.SetOutputFiles(android.Paths{m.implementationAndResourcesJar}, ".jar")
710 ctx.SetOutputFiles(android.Paths{m.headerJarFile}, ".hjar")
711 if m.dexer.proguardDictionary.Valid() {
712 ctx.SetOutputFiles(android.Paths{m.dexer.proguardDictionary.Path()}, ".proguard_map")
713 }
714 ctx.SetOutputFiles(m.properties.Generated_srcjars, ".generated_srcjars")
Jaewoong Jung26342642021-03-17 15:56:23 -0700715}
716
Jaewoong Jung26342642021-03-17 15:56:23 -0700717func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
718 initJavaModule(module, hod, false)
719}
720
721func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
722 initJavaModule(module, hod, true)
723}
724
725func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
726 multilib := android.MultilibCommon
727 if multiTargets {
728 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
729 } else {
730 android.InitAndroidArchModule(module, hod, multilib)
731 }
732 android.InitDefaultableModule(module)
733}
734
735func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
736 return j.properties.Instrument &&
737 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
738 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
739}
740
Yihan Dong8be09c22024-08-29 15:32:13 +0800741func (j *Module) shouldApiMapper() bool {
742 return j.properties.ApiMapper
743}
744
Jaewoong Jung26342642021-03-17 15:56:23 -0700745func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000746 return j.properties.Supports_static_instrumentation &&
747 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700748 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
749 ctx.Config().UnbundledBuild())
750}
751
752func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
753 // Force enable the instrumentation for java code that is built for APEXes ...
754 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
755 // 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 -0800756 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700757 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
Jihoon Kang690df2e2024-05-22 04:27:38 +0000758
Jihoon Kang46d66de2024-05-22 22:42:39 +0000759 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700760 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
761 return true
762 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
763 return true
764 }
765 }
766 return false
767}
768
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400769func (j *Module) setInstrument(value bool) {
770 j.properties.Instrument = value
771}
772
Yihan Dong8be09c22024-08-29 15:32:13 +0800773func (j *Module) setApiMapper(value bool) {
774 j.properties.ApiMapper = value
775}
776
Jiyong Park92315372021-04-02 08:45:46 +0900777func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
778 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700779}
780
Jiyong Parkf1691d22021-03-29 20:11:58 +0900781func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700782 return proptools.String(j.deviceProperties.System_modules)
783}
784
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000785func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Spandan Dasb9c58352024-05-13 18:29:45 +0000786 if j.overridableProperties.Min_sdk_version != nil {
787 return android.ApiLevelFrom(ctx, *j.overridableProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700788 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000789 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700790}
791
Yu Liuf2b94012023-09-19 15:09:10 -0700792func (j *Module) GetDeviceProperties() *DeviceProperties {
793 return &j.deviceProperties
794}
795
Spandan Dasa26eda72023-03-02 00:56:06 +0000796func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
797 if j.deviceProperties.Max_sdk_version != nil {
798 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
799 }
800 // Default is PrivateApiLevel
801 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000802}
803
Spandan Dasa26eda72023-03-02 00:56:06 +0000804func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
805 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
806 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
807 }
808 // Default is PrivateApiLevel
809 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000810}
811
Jiyong Parkf1691d22021-03-29 20:11:58 +0900812func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000813 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900814}
815
Spandan Dasca70fc42023-03-01 23:38:49 +0000816func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900817 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000818 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900819 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000820 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700821}
822
823func (j *Module) AvailableFor(what string) bool {
824 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
825 // Exception: for hostdex: true libraries, the platform variant is created
826 // even if it's not marked as available to platform. In that case, the platform
827 // variant is used only for the hostdex and not installed to the device.
828 return true
829 }
830 return j.ApexModuleBase.AvailableFor(what)
831}
832
Cole Faustb7493472024-08-28 11:55:52 -0700833func (j *Module) staticLibs(ctx android.BaseModuleContext) []string {
Jihoon Kang8bce3812024-09-30 18:46:51 +0000834 return j.properties.Static_libs.GetOrDefault(ctx, nil)
Cole Faustb7493472024-08-28 11:55:52 -0700835}
836
Jaewoong Jung26342642021-03-17 15:56:23 -0700837func (j *Module) deps(ctx android.BottomUpMutatorContext) {
838 if ctx.Device() {
839 j.linter.deps(ctx)
840
Jiyong Parkf1691d22021-03-29 20:11:58 +0900841 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700842
843 if j.deviceProperties.SyspropPublicStub != "" {
844 // This is a sysprop implementation library that has a corresponding sysprop public
845 // stubs library, and a dependency on it so that dependencies on the implementation can
846 // be forwarded to the public stubs library when necessary.
847 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
848 }
849 }
850
851 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000852
Cole Faustb7493472024-08-28 11:55:52 -0700853 ctx.AddVariationDependencies(nil, staticLibTag, j.staticLibs(ctx)...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700854
855 // Add dependency on libraries that provide additional hidden api annotations.
856 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
857
Jaewoong Jung26342642021-03-17 15:56:23 -0700858 // For library dependencies that are component libraries (like stubs), add the implementation
859 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
860 for _, dep := range libDeps {
861 if dep != nil {
862 if component, ok := dep.(SdkLibraryComponentDependency); ok {
863 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +0000864 // Add library as optional if it's one of the optional compatibility libs or it's
865 // explicitly listed in the optional_uses_libs property.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100866 tag := usesLibReqTag
Jiakai Zhangf98da192024-04-15 11:15:41 +0000867 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) ||
868 android.InList(*lib, j.usesLibrary.usesLibraryProperties.Optional_uses_libs) {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100869 tag = usesLibOptTag
870 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100871 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 }
873 }
874 }
875 }
876
877 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
Luca Stefani50098f72024-10-12 17:55:31 +0200878 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag, j.properties.Kotlin_plugins...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700879 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
880 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
881
882 android.ProtoDeps(ctx, &j.protoProperties)
883 if j.hasSrcExt(".proto") {
884 protoDeps(ctx, &j.protoProperties)
885 }
886
887 if j.hasSrcExt(".kt") {
888 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
889 // Kotlin files
Colin Cross882d6002024-08-14 10:24:06 -0700890 tag := staticLibTag
891 if !BoolDefault(j.properties.Static_kotlin_stdlib, true) {
892 tag = libTag
893 }
894 ctx.AddVariationDependencies(nil, tag,
895 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8", "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700896 }
897
898 // Framework libraries need special handling in static coverage builds: they should not have
899 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
900 // the same jacoco classes coming from different bootclasspath jars.
901 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
902 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
903 j.properties.Instrument = true
904 }
905 } else if j.shouldInstrumentStatic(ctx) {
906 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
907 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700908
Cole Faustb7493472024-08-28 11:55:52 -0700909 if j.useCompose(ctx) {
Colin Crossa1ff7c62021-09-17 14:11:52 -0700910 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
Luca Stefani50098f72024-10-12 17:55:31 +0200911 "androidx.compose.compiler_compiler-hosted-plugin")
Colin Crossa1ff7c62021-09-17 14:11:52 -0700912 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700913}
914
915func hasSrcExt(srcs []string, ext string) bool {
916 for _, src := range srcs {
917 if filepath.Ext(src) == ext {
918 return true
919 }
920 }
921
922 return false
923}
924
925func (j *Module) hasSrcExt(ext string) bool {
926 return hasSrcExt(j.properties.Srcs, ext)
927}
928
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100929func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
930 var flags string
931
932 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
933 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
934 flags = "-Wmissing-permission-annotation -Werror"
935 }
936 }
937 return flags
938}
939
Jaewoong Jung26342642021-03-17 15:56:23 -0700940func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000941 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700942
943 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
944 aidlIncludes = append(aidlIncludes,
945 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
946 aidlIncludes = append(aidlIncludes,
947 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
948
949 var flags []string
950 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000951 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700952
953 flags = append(flags, j.deviceProperties.Aidl.Flags...)
954
955 if aidlPreprocess.Valid() {
956 flags = append(flags, "-p"+aidlPreprocess.String())
957 deps = append(deps, aidlPreprocess.Path())
958 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000959 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700960 }
961
962 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000963 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700964 }
965
966 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000967 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700968 }
969
Sam Delmerico2351eac2022-05-24 17:10:02 +0000970 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700971 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000972 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700973 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000974 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
975 // add flags for dirs containing AIDL srcs that haven't been specified yet
976 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700977
Zim8774ae12022-08-17 11:46:34 +0100978 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000979 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100980 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700981 flags = append(flags, "-t")
982 }
983
984 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
985 flags = append(flags, "--transaction_names")
986 }
987
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100988 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
989 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
990 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
991 }
992
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000993 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900994 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
995
Jaewoong Jung26342642021-03-17 15:56:23 -0700996 return strings.Join(flags, " "), deps
997}
998
999func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
1000
1001 var flags javaBuilderFlags
1002
1003 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +09001004 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001005
Cole Faust2b1536e2021-06-18 12:25:54 -07001006 epEnabled := j.properties.Errorprone.Enabled
1007 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +01001008 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001009 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
1010 }
1011
1012 errorProneFlags := []string{
1013 "-Xplugin:ErrorProne",
1014 "${config.ErrorProneChecks}",
1015 }
1016 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
1017
Colin Cross8bf6cad2022-02-28 13:07:03 -08001018 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -07001019 "'" + strings.Join(errorProneFlags, " ") + "'"
1020 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
1021 }
1022
1023 // classpath
1024 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
1025 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001026 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001027 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
1028 flags.processorPath = append(flags.processorPath, deps.processorPath...)
1029 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
1030
1031 flags.processors = append(flags.processors, deps.processorClasses...)
1032 flags.processors = android.FirstUniqueStrings(flags.processors)
1033
1034 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001035 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001036 // Give host-side tools a version of OpenJDK's standard libraries
1037 // close to what they're targeting. As of Dec 2017, AOSP is only
1038 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1039 //
1040 // When building with OpenJDK 8, the following should have no
1041 // effect since those jars would be available by default.
1042 //
1043 // When building with OpenJDK 9 but targeting a version < 1.8,
1044 // putting them on the bootclasspath means that:
1045 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1046 // b) references to existing APIs are not reinterpreted in an
1047 // OpenJDK 9-specific way, eg. calls to subclasses of
1048 // java.nio.Buffer as in http://b/70862583
1049 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1050 flags.bootClasspath = append(flags.bootClasspath,
1051 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1052 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1053 if Bool(j.properties.Use_tools_jar) {
1054 flags.bootClasspath = append(flags.bootClasspath,
1055 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1056 }
1057 }
1058
1059 // systemModules
1060 flags.systemModules = deps.systemModules
1061
Jaewoong Jung26342642021-03-17 15:56:23 -07001062 return flags
1063}
1064
1065func (j *Module) collectJavacFlags(
1066 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1067 // javac flags.
1068 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001069 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001070
Mythri Alle4b9f6182023-10-25 15:17:11 +00001071 needsDebugInfo = false
1072 for _, flag := range javacFlags {
1073 if strings.HasPrefix(flag, "-g") {
1074 needsDebugInfo = true
1075 }
1076 }
1077
1078 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001079 // For non-host binaries, override the -g flag passed globally to remove
1080 // local variable debug info to reduce disk and memory usage.
1081 javacFlags = append(javacFlags, "-g:source,lines")
1082 }
1083 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1084
1085 if flags.javaVersion.usesJavaModules() {
1086 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001087 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1088 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1089 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1090 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001091
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001092 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001093 if j.properties.Patch_module != nil {
1094 // Manually specify build directory in case it is not under the repo root.
1095 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1096 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001097 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001098
Jaewoong Jung26342642021-03-17 15:56:23 -07001099 classPath := flags.classpath.FormJavaClassPath("")
1100 if classPath != "" {
1101 patchPaths = append(patchPaths, classPath)
1102 }
1103 javacFlags = append(
1104 javacFlags,
1105 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1106 }
1107 }
1108
1109 if len(javacFlags) > 0 {
1110 // optimization.
1111 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1112 flags.javacFlags = "$javacFlags"
1113 }
1114
1115 return flags
1116}
1117
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001118func (j *Module) AddJSONData(d *map[string]interface{}) {
1119 (&j.ModuleBase).AddJSONData(d)
1120 (*d)["Java"] = map[string]interface{}{
1121 "SourceExtensions": j.sourceExtensions,
1122 }
1123
1124}
1125
usta0391ca42023-09-19 15:51:59 -04001126func (j *Module) addGeneratedSrcJars(path android.Path) {
1127 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001128}
1129
Colin Crossfdaa6722024-08-23 11:58:08 -07001130func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars, extraDepCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001131 // Auto-propagating jarjar rules
1132 jarjarProviderData := j.collectJarJarRules(ctx)
1133 if jarjarProviderData != nil {
1134 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
Zi Wangddb2ee52024-04-02 16:44:02 +00001135 text := getJarJarRuleText(jarjarProviderData)
1136 if text != "" {
1137 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1138 android.WriteFileRule(ctx, ruleTextFile, text)
1139 j.repackageJarjarRules = ruleTextFile
Joe Onorato349ae8d2024-02-05 22:46:00 +00001140 }
1141 }
1142
Jaewoong Jung26342642021-03-17 15:56:23 -07001143 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1144
John Wu989ee842024-10-04 00:21:43 +00001145 // Only override the original value if explicitly set
1146 if j.properties.Ravenizer.Enabled != nil {
1147 j.ravenizer.enabled = *j.properties.Ravenizer.Enabled
Makoto Onuki7ded3822024-03-28 14:42:20 -07001148 }
1149
Jaewoong Jung26342642021-03-17 15:56:23 -07001150 deps := j.collectDeps(ctx)
1151 flags := j.collectBuilderFlags(ctx, deps)
1152
1153 if flags.javaVersion.usesJavaModules() {
1154 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001155 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1156 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1157 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001158 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001159
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001161 j.sourceExtensions = []string{}
1162 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1163 if hasSrcExt(srcFiles.Strings(), ext) {
1164 j.sourceExtensions = append(j.sourceExtensions, ext)
1165 }
1166 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001167 if hasSrcExt(srcFiles.Strings(), ".proto") {
1168 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1169 }
1170
1171 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1172 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1173 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1174 }
1175
Sam Delmerico2351eac2022-05-24 17:10:02 +00001176 aidlSrcs := srcFiles.FilterByExt(".aidl")
1177 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1178
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001179 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001180 srcFiles = j.genSources(ctx, srcFiles, flags)
1181
1182 // Collect javac flags only after computing the full set of srcFiles to
1183 // ensure that the --patch-module lookup paths are complete.
1184 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1185
1186 srcJars := srcFiles.FilterByExt(".srcjar")
1187 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001188 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001189 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001190 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001191
1192 if j.properties.Jarjar_rules != nil {
1193 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1194 }
1195
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001196 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001197
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001198 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001199 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001200 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001201 if _, found := set[v.String()]; !found {
1202 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001203 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001204 }
1205 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001206 var uniqueKtFiles android.Paths
1207 for _, v := range srcFiles.FilterByExt(".kt") {
1208 if _, found := set[v.String()]; !found {
1209 set[v.String()] = true
1210 uniqueKtFiles = append(uniqueKtFiles, v)
1211 }
1212 }
1213
1214 var uniqueSrcFiles android.Paths
1215 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1216 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1217 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001218 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001219
Colin Crossb5db4012022-03-28 17:12:39 -07001220 // We don't currently run annotation processors in turbine, which means we can't use turbine
1221 // generated header jars when an annotation processor that generates API is enabled. One
1222 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1223 // is used to run all of the annotation processors.
1224 disableTurbine := deps.disableTurbine
1225
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001226 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001227 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1228
Colin Cross220a9a12022-03-28 17:08:01 -07001229 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001230
Colin Cross4eae06d2023-06-20 22:40:02 -07001231 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1232 // any dependencies so that it can override any non-final R classes from dependencies with the
1233 // final R classes from the app.
1234 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1235
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001236 j.aconfigCacheFiles = append(deps.aconfigProtoFiles, j.properties.Aconfig_Cache_files...)
1237
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001238 var localImplementationJars android.Paths
1239
Mark Whitea15790a2023-08-22 21:28:11 +00001240 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001241 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001242 if srcFiles.HasExt(".kt") {
1243 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1244 }
1245 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1246 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1247 }
1248
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001249 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1250
1251 localHeaderJars, combinedHeaderJarFile := j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
Colin Crossedec77c2024-07-26 15:25:40 -07001252 extraCombinedJars)
1253
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001254 combinedHeaderJarFile, jarjared := j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1255 if jarjared {
1256 localHeaderJars = android.Paths{combinedHeaderJarFile}
1257 transitiveStaticLibsHeaderJars = nil
1258 }
1259 combinedHeaderJarFile, repackaged := j.repackageFlagsIfNecessary(ctx, combinedHeaderJarFile, jarName, "repackage-turbine")
1260 if repackaged {
1261 localHeaderJars = android.Paths{combinedHeaderJarFile}
1262 transitiveStaticLibsHeaderJars = nil
1263 }
Mark Whitea15790a2023-08-22 21:28:11 +00001264 if ctx.Failed() {
1265 return
1266 }
Colin Crossedec77c2024-07-26 15:25:40 -07001267 j.headerJarFile = combinedHeaderJarFile
Mark Whitea15790a2023-08-22 21:28:11 +00001268
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001269 if ctx.Config().UseTransitiveJarsInClasspath() {
1270 if len(localHeaderJars) > 0 {
1271 ctx.CheckbuildFile(localHeaderJars...)
1272 } else {
1273 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1274 ctx.UncheckedModule()
1275 }
1276 } else {
1277 ctx.CheckbuildFile(j.headerJarFile)
1278 }
Colin Crossa6182ab2024-08-21 10:47:44 -07001279
Colin Cross7727c7f2024-07-18 15:36:32 -07001280 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Jihoon Kang705e63e2024-03-13 01:21:16 +00001281 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001282 LocalHeaderJars: localHeaderJars,
1283 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
Colin Cross9ffaf282024-08-12 13:50:09 -07001284 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1285 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001286 AidlIncludeDirs: j.exportAidlIncludeDirs,
1287 ExportedPlugins: j.exportedPluginJars,
1288 ExportedPluginClasses: j.exportedPluginClasses,
1289 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1290 StubsLinkType: j.stubsLinkType,
1291 AconfigIntermediateCacheOutputPaths: deps.aconfigProtoFiles,
Mark Whitea15790a2023-08-22 21:28:11 +00001292 })
1293
1294 j.outputFile = j.headerJarFile
1295 return
1296 }
1297
Jaewoong Jung26342642021-03-17 15:56:23 -07001298 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001299 // When using kotlin sources turbine is used to generate annotation processor sources,
1300 // including for annotation processors that generate API, so we can use turbine for
1301 // java sources too.
1302 disableTurbine = false
1303
Jaewoong Jung26342642021-03-17 15:56:23 -07001304 // user defined kotlin flags.
1305 kotlincFlags := j.properties.Kotlincflags
1306 CheckKotlincFlags(ctx, kotlincFlags)
1307
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001308 // Workaround for KT-46512
1309 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001310
1311 // If there are kotlin files, compile them first but pass all the kotlin and java files
1312 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1313 // won't emit any classes for them.
1314 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1315 if ctx.Device() {
1316 kotlincFlags = append(kotlincFlags, "-no-jdk")
1317 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001318
1319 for _, plugin := range deps.kotlinPlugins {
1320 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1321 }
1322 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1323
Jaewoong Jung26342642021-03-17 15:56:23 -07001324 if len(kotlincFlags) > 0 {
1325 // optimization.
1326 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1327 flags.kotlincFlags += "$kotlincFlags"
1328 }
1329
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001330 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001331 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1332
Jaewoong Jung26342642021-03-17 15:56:23 -07001333 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1334 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1335
Isaac Chioua23d9942022-04-06 06:14:38 +00001336 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001337 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001338 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1339 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001340 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001341 srcJars = append(srcJars, kaptSrcJar)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001342 localImplementationJars = append(localImplementationJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001343 // Disable annotation processing in javac, it's already been handled by kapt
1344 flags.processorPath = nil
1345 flags.processors = nil
1346 }
1347
1348 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001349 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Spandan Das1028d5a2024-08-19 21:45:48 +00001350 j.kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001351 if ctx.Failed() {
1352 return
1353 }
1354
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001355 kotlinJarPath, _ := j.repackageFlagsIfNecessary(ctx, kotlinJar, jarName, "kotlinc")
Zi Wangddb2ee52024-04-02 16:44:02 +00001356
Isaac Chioua23d9942022-04-06 06:14:38 +00001357 // Make javac rule depend on the kotlinc rule
1358 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1359
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001360 localImplementationJars = append(localImplementationJars, kotlinJarPath)
1361
Colin Cross220a9a12022-03-28 17:08:01 -07001362 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001363 }
1364
Jaewoong Jung26342642021-03-17 15:56:23 -07001365 j.compiledSrcJars = srcJars
1366
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001367 transitiveStaticLibsHeaderJars := deps.transitiveStaticLibsHeaderJars
1368
Jaewoong Jung26342642021-03-17 15:56:23 -07001369 enableSharding := false
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001370 var localHeaderJars android.Paths
1371 var shardingHeaderJars android.Paths
1372 var repackagedHeaderJarFile android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001373 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001374 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1375 enableSharding = true
1376 // Formerly, there was a check here that prevented annotation processors
1377 // from being used when sharding was enabled, as some annotation processors
1378 // do not function correctly in sharded environments. It was removed to
1379 // allow for the use of annotation processors that do function correctly
1380 // with sharding enabled. See: b/77284273.
1381 }
Colin Crossd1d8f172024-07-29 11:30:29 -07001382 extraJars := slices.Clone(kotlinHeaderJars)
Colin Crossd1d8f172024-07-29 11:30:29 -07001383 extraJars = append(extraJars, extraCombinedJars...)
Colin Crossedec77c2024-07-26 15:25:40 -07001384 var combinedHeaderJarFile android.Path
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001385 localHeaderJars, combinedHeaderJarFile = j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
1386 shardingHeaderJars = localHeaderJars
Colin Crossedec77c2024-07-26 15:25:40 -07001387
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001388 var jarjared bool
1389 j.headerJarFile, jarjared = j.jarjarIfNecessary(ctx, combinedHeaderJarFile, jarName, "turbine")
1390 if jarjared {
1391 // jarjar modifies transitive static dependencies, use the combined header jar and drop the transitive
1392 // static libs header jars.
1393 localHeaderJars = android.Paths{j.headerJarFile}
1394 transitiveStaticLibsHeaderJars = nil
1395 }
1396 var repackaged bool
1397 repackagedHeaderJarFile, repackaged = j.repackageFlagsIfNecessary(ctx, j.headerJarFile, jarName, "turbine")
1398 if repackaged {
1399 // repackage modifies transitive static dependencies, use the combined header jar and drop the transitive
1400 // static libs header jars.
1401 // TODO(b/356688296): this shouldn't export both the unmodified and repackaged header jars
1402 localHeaderJars = android.Paths{j.headerJarFile, repackagedHeaderJarFile}
1403 transitiveStaticLibsHeaderJars = nil
1404 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001405 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001406 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001407 hasErrorproneableFiles := false
1408 for _, ext := range j.sourceExtensions {
1409 if ext != ".proto" && ext != ".aidl" {
1410 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1411 // compile, and it's not useful to have warnings on these generated sources.
1412 hasErrorproneableFiles = true
1413 break
1414 }
1415 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001416 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001417 if Bool(j.properties.Errorprone.Enabled) {
1418 // If error-prone is enabled, enable errorprone flags on the regular
1419 // build.
1420 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001421 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001422 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1423 // a new jar file just for compiling with the errorprone compiler to.
1424 // This is because we don't want to cause the java files to get completely
1425 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1426 // We also don't want to run this if errorprone is enabled by default for
1427 // this module, or else we could have duplicated errorprone messages.
1428 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001429 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001430 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001431
Vadim Spivak3c496f02023-06-08 06:14:59 +00001432 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001433 "errorprone", "errorprone")
1434
Jaewoong Jung26342642021-03-17 15:56:23 -07001435 extraJarDeps = append(extraJarDeps, errorprone)
1436 }
1437
1438 if enableSharding {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001439 if len(shardingHeaderJars) > 0 {
1440 flags.classpath = append(classpath(slices.Clone(shardingHeaderJars)), flags.classpath...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001441 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001442 shardSize := int(*(j.properties.Javac_shard_size))
1443 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001444 if len(uniqueJavaFiles) > 0 {
1445 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001446 for idx, shardSrc := range shardSrcs {
1447 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1448 nil, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001449 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(idx))
1450 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001451 }
1452 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001453 // Assume approximately 5 sources per srcjar.
1454 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1455 // 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 -07001456 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001457 startIdx := len(shardSrcs)
1458 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1459 for idx, shardSrcJars := range shardSrcJarsList {
1460 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1461 nil, shardSrcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001462 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac-"+strconv.Itoa(startIdx+idx))
1463 localImplementationJars = append(localImplementationJars, classes)
Colin Crossa052ddb2023-09-25 21:46:58 -07001464 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 }
1466 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001467 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001468 classes, _ = j.repackageFlagsIfNecessary(ctx, classes, jarName, "javac")
1469 localImplementationJars = append(localImplementationJars, classes)
Jaewoong Jung26342642021-03-17 15:56:23 -07001470 }
1471 if ctx.Failed() {
1472 return
1473 }
1474 }
1475
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001476 localImplementationJars = append(localImplementationJars, extraCombinedJars...)
Colin Crossfd620b22024-02-23 10:05:21 -08001477
Jaewoong Jung26342642021-03-17 15:56:23 -07001478 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1479
1480 var includeSrcJar android.WritablePath
1481 if Bool(j.properties.Include_srcs) {
1482 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1483 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1484 }
1485
1486 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1487 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1488 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1489 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1490
1491 var resArgs []string
1492 var resDeps android.Paths
1493
1494 resArgs = append(resArgs, dirArgs...)
1495 resDeps = append(resDeps, dirDeps...)
1496
1497 resArgs = append(resArgs, fileArgs...)
1498 resDeps = append(resDeps, fileDeps...)
1499
1500 resArgs = append(resArgs, extraArgs...)
1501 resDeps = append(resDeps, extraDeps...)
1502
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001503 var localResourceJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 if len(resArgs) > 0 {
1505 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1506 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001507 if ctx.Failed() {
1508 return
1509 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001510 localResourceJars = append(localResourceJars, resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 }
1512
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 if Bool(j.properties.Include_srcs) {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001514 localResourceJars = append(localResourceJars, includeSrcJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001515 }
1516
1517 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1518 if len(services) > 0 {
1519 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1520 var zipargs []string
1521 for _, file := range services {
1522 serviceFile := file.String()
1523 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1524 }
1525 rule := zip
1526 args := map[string]string{
1527 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1528 }
1529 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1530 rule = zipRE
1531 args["implicits"] = strings.Join(services.Strings(), ",")
1532 }
1533 ctx.Build(pctx, android.BuildParams{
1534 Rule: rule,
1535 Output: servicesJar,
1536 Implicits: services,
1537 Args: args,
1538 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001539 localResourceJars = append(localResourceJars, servicesJar)
1540 }
1541
1542 completeStaticLibsResourceJars := android.NewDepSet(android.PREORDER, localResourceJars, deps.transitiveStaticLibsResourceJars)
1543
1544 var combinedResourceJar android.Path
1545 var resourceJars android.Paths
1546 if ctx.Config().UseTransitiveJarsInClasspath() {
1547 resourceJars = completeStaticLibsResourceJars.ToList()
1548 } else {
1549 resourceJars = append(slices.Clone(localResourceJars), deps.staticResourceJars...)
1550 }
1551 if len(resourceJars) == 1 {
1552 combinedResourceJar = resourceJars[0]
1553 } else if len(resourceJars) > 0 {
1554 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1555 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1556 false, nil, nil)
1557 combinedResourceJar = combinedJar
1558 }
1559
1560 manifest := j.overrideManifest
1561 if !manifest.Valid() && j.properties.Manifest != nil {
1562 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
Jaewoong Jung26342642021-03-17 15:56:23 -07001563 }
1564
1565 // Combine the classes built from sources, any manifests, and any static libraries into
1566 // classes.jar. If there is only one input jar this step will be skipped.
Colin Cross7707b242024-07-26 12:02:36 -07001567 var outputFile android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -07001568
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001569 completeStaticLibsImplementationJars := android.NewDepSet(android.PREORDER, localImplementationJars, deps.transitiveStaticLibsImplementationJars)
1570
1571 var jars android.Paths
1572 if ctx.Config().UseTransitiveJarsInClasspath() {
1573 jars = completeStaticLibsImplementationJars.ToList()
1574 } else {
1575 jars = append(slices.Clone(localImplementationJars), deps.staticJars...)
1576 }
1577
1578 jars = append(jars, extraDepCombinedJars...)
1579
Jaewoong Jung26342642021-03-17 15:56:23 -07001580 if len(jars) == 1 && !manifest.Valid() {
1581 // Optimization: skip the combine step as there is nothing to do
1582 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1583 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001584 // any if len(extraJars) == 0.
Jaewoong Jung26342642021-03-17 15:56:23 -07001585
Jihoon Kang1147b312023-06-08 23:25:57 +00001586 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1587 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1588 // either with .from-source or .from-text suffix.
1589 // outputFile should be agnostic to the build configuration,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001590 // thus copy the single input static lib in order to prevent the static lib from being exposed
Jihoon Kang1147b312023-06-08 23:25:57 +00001591 // to the copy rules.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001592 if stub, _ := moduleStubLinkType(j); stub {
1593 copiedJar := android.PathForModuleOut(ctx, "combined", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001594 ctx.Build(pctx, android.BuildParams{
1595 Rule: android.Cp,
1596 Input: jars[0],
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001597 Output: copiedJar,
Jaewoong Jung26342642021-03-17 15:56:23 -07001598 })
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001599 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, android.Paths{copiedJar}, nil)
1600 outputFile = copiedJar
Colin Cross7707b242024-07-26 12:02:36 -07001601 } else {
1602 outputFile = jars[0]
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 }
1604 } else {
1605 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1606 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1607 false, nil, nil)
Colin Cross7707b242024-07-26 12:02:36 -07001608 outputFile = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001609 }
1610
1611 // jarjar implementation jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001612 jarjarFile, jarjarred := j.jarjarIfNecessary(ctx, outputFile, jarName, "")
1613 if jarjarred {
1614 localImplementationJars = android.Paths{jarjarFile}
1615 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
1616 }
Colin Crossedec77c2024-07-26 15:25:40 -07001617 outputFile = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001618
Colin Crossedec77c2024-07-26 15:25:40 -07001619 // jarjar resource jar if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001620 if combinedResourceJar != nil {
1621 resourceJarJarFile, jarjarred := j.jarjarIfNecessary(ctx, combinedResourceJar, jarName, "resource")
1622 combinedResourceJar = resourceJarJarFile
1623 if jarjarred {
1624 localResourceJars = android.Paths{resourceJarJarFile}
1625 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1626 }
Colin Crossedec77c2024-07-26 15:25:40 -07001627 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001628
Colin Crossedec77c2024-07-26 15:25:40 -07001629 if ctx.Failed() {
1630 return
Jaewoong Jung26342642021-03-17 15:56:23 -07001631 }
1632
Makoto Onuki7ded3822024-03-28 14:42:20 -07001633 if j.ravenizer.enabled {
1634 ravenizerInput := outputFile
John Wub67040d2024-10-07 18:39:06 +00001635 ravenizerOutput := android.PathForModuleOut(ctx, "ravenizer", "", jarName)
John Wu989ee842024-10-04 00:21:43 +00001636 ravenizerArgs := ""
1637 if proptools.Bool(j.properties.Ravenizer.Strip_mockito) {
1638 ravenizerArgs = "--strip-mockito"
1639 }
1640 TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
Makoto Onuki7ded3822024-03-28 14:42:20 -07001641 outputFile = ravenizerOutput
Colin Cross7e863852024-09-06 14:42:38 -07001642 localImplementationJars = android.Paths{ravenizerOutput}
1643 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
John Wub67040d2024-10-07 18:39:06 +00001644 if combinedResourceJar != nil {
1645 ravenizerInput = combinedResourceJar
1646 ravenizerOutput = android.PathForModuleOut(ctx, "ravenizer", "resources", jarName)
1647 TransformRavenizer(ctx, ravenizerOutput, ravenizerInput, ravenizerArgs)
1648 combinedResourceJar = ravenizerOutput
1649 localResourceJars = android.Paths{ravenizerOutput}
1650 completeStaticLibsResourceJars = android.NewDepSet(android.PREORDER, localResourceJars, nil)
1651 }
Makoto Onuki7ded3822024-03-28 14:42:20 -07001652 }
1653
Yihan Dong8be09c22024-08-29 15:32:13 +08001654 if j.shouldApiMapper() {
1655 inputFile := outputFile
1656 apiMapperFile := android.PathForModuleOut(ctx, "apimapper", jarName)
1657 ctx.Build(pctx, android.BuildParams{
1658 Rule: apimapper,
1659 Description: "apimapper",
1660 Input: inputFile,
1661 Output: apiMapperFile,
1662 })
1663 outputFile = apiMapperFile
Colin Cross7e863852024-09-06 14:42:38 -07001664 localImplementationJars = android.Paths{apiMapperFile}
1665 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Yihan Dong8be09c22024-08-29 15:32:13 +08001666 }
1667
Jaewoong Jung26342642021-03-17 15:56:23 -07001668 // Check package restrictions if necessary.
1669 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001670 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001671 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001672
1673 // Create a rule to copy the output jar to another path and add a validate dependency that
1674 // will check that the jar only contains the permitted packages. The new location will become
1675 // the output file of this module.
1676 inputFile := outputFile
Colin Cross7707b242024-07-26 12:02:36 -07001677 packageCheckOutputFile := android.PathForModuleOut(ctx, "package-check", jarName)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001678 ctx.Build(pctx, android.BuildParams{
1679 Rule: android.Cp,
1680 Input: inputFile,
Colin Cross7707b242024-07-26 12:02:36 -07001681 Output: packageCheckOutputFile,
Paul Duffin08a18bf2021-10-01 13:19:58 +01001682 // Make sure that any dependency on the output file will cause ninja to run the package check
1683 // rule.
1684 Validation: pkgckFile,
1685 })
Colin Cross7707b242024-07-26 12:02:36 -07001686 outputFile = packageCheckOutputFile
Colin Cross7e863852024-09-06 14:42:38 -07001687 localImplementationJars = android.Paths{packageCheckOutputFile}
1688 completeStaticLibsImplementationJars = android.NewDepSet(android.PREORDER, localImplementationJars, nil)
Paul Duffin08a18bf2021-10-01 13:19:58 +01001689
1690 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001691 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001692
1693 if ctx.Failed() {
1694 return
1695 }
1696 }
1697
1698 j.implementationJarFile = outputFile
1699 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001700 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1701 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1702 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1703 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1704 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1705 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1706 j.headerJarFile = headerJarFile
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001707 if len(localImplementationJars) == 1 && ctx.Config().UseTransitiveJarsInClasspath() {
1708 localHeaderJarFile := android.PathForModuleOut(ctx, "local-javac-header", jarName)
1709 convertImplementationJarToHeaderJar(ctx, localImplementationJars[0], localHeaderJarFile)
1710 localHeaderJars = append(localHeaderJars, localHeaderJarFile)
1711 } else {
1712 localHeaderJars = append(localHeaderJars, headerJarFile)
1713 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001714 }
1715
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001716 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1717 specs := j.jacocoModuleToZipCommand(ctx)
1718 if ctx.Failed() {
1719 return
1720 }
1721
Colin Crossb323c912024-09-24 15:21:00 -07001722 completeStaticLibsImplementationJarsToCombine := completeStaticLibsImplementationJars
1723
Jaewoong Jung26342642021-03-17 15:56:23 -07001724 if j.shouldInstrument(ctx) {
Colin Crossb323c912024-09-24 15:21:00 -07001725 instrumentedOutputFile := j.instrument(ctx, flags, outputFile, jarName, specs)
1726 completeStaticLibsImplementationJarsToCombine = android.NewDepSet(android.PREORDER, android.Paths{instrumentedOutputFile}, nil)
1727 outputFile = instrumentedOutputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 }
1729
1730 // merge implementation jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001731 var implementationAndResourcesJarsToCombine android.Paths
1732 if ctx.Config().UseTransitiveJarsInClasspath() {
1733 resourceJars := completeStaticLibsResourceJars.ToList()
1734 if len(resourceJars) > 0 {
Colin Crossb323c912024-09-24 15:21:00 -07001735 implementationAndResourcesJarsToCombine = append(resourceJars, completeStaticLibsImplementationJarsToCombine.ToList()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001736 implementationAndResourcesJarsToCombine = append(implementationAndResourcesJarsToCombine, extraDepCombinedJars...)
1737 }
1738 } else {
1739 if combinedResourceJar != nil {
1740 implementationAndResourcesJarsToCombine = android.Paths{combinedResourceJar, outputFile}
1741 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001742 }
1743
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001744 if len(implementationAndResourcesJarsToCombine) > 0 {
1745 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
1746 TransformJarsToJar(ctx, combinedJar, "for resources", implementationAndResourcesJarsToCombine, manifest,
1747 false, nil, nil)
1748 outputFile = combinedJar
1749 }
1750
1751 j.implementationAndResourcesJar = outputFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001752
1753 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001754 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001755 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001756 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001757 if compileDex == nil {
1758 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001759 }
1760 if j.deviceProperties.Hostdex == nil {
1761 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1762 }
1763 }
1764
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001765 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001766 if j.hasCode(ctx) {
1767 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001768 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001769 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1770 }
1771 // Dex compilation
Colin Cross7707b242024-07-26 12:02:36 -07001772 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00001773 params := &compileDexParams{
1774 flags: flags,
1775 sdkVersion: j.SdkVersion(ctx),
1776 minSdkVersion: j.MinSdkVersion(ctx),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001777 classesJar: outputFile,
Spandan Dasc404cc72023-02-23 18:05:05 +00001778 jarName: jarName,
1779 }
Cole Fausteb032462024-09-19 11:12:54 -07001780 if j.GetProfileGuided(ctx) && j.optimizeOrObfuscateEnabled() && !j.EnableProfileRewriting(ctx) {
Spandan Das15a67112024-05-30 00:07:40 +00001781 ctx.PropertyErrorf("enable_profile_rewriting",
1782 "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.",
1783 )
1784 }
Cole Fausteb032462024-09-19 11:12:54 -07001785 if j.EnableProfileRewriting(ctx) {
1786 profile := j.GetProfile(ctx)
1787 if profile == "" || !j.GetProfileGuided(ctx) {
Spandan Das3dbda182024-05-20 22:23:10 +00001788 ctx.PropertyErrorf("enable_profile_rewriting", "Profile and Profile_guided must be set when enable_profile_rewriting is true")
1789 }
1790 params.artProfileInput = &profile
1791 }
1792 dexOutputFile, dexArtProfileOutput := j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001793 if ctx.Failed() {
1794 return
1795 }
1796
Spandan Das3dbda182024-05-20 22:23:10 +00001797 // If r8/d8 provides a profile that matches the optimized dex, use that for dexpreopt.
1798 if dexArtProfileOutput != nil {
Colin Cross7707b242024-07-26 12:02:36 -07001799 j.dexpreopter.SetRewrittenProfile(dexArtProfileOutput)
Spandan Das3dbda182024-05-20 22:23:10 +00001800 }
1801
Jaewoong Jung26342642021-03-17 15:56:23 -07001802 // merge dex jar with resources if necessary
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001803 var dexAndResourceJarsToCombine android.Paths
1804 if ctx.Config().UseTransitiveJarsInClasspath() {
1805 resourceJars := completeStaticLibsResourceJars.ToList()
1806 if len(resourceJars) > 0 {
1807 dexAndResourceJarsToCombine = append(android.Paths{dexOutputFile}, resourceJars...)
1808 }
1809 } else {
1810 if combinedResourceJar != nil {
1811 dexAndResourceJarsToCombine = android.Paths{dexOutputFile, combinedResourceJar}
1812 }
1813 }
1814 if len(dexAndResourceJarsToCombine) > 0 {
Colin Cross7707b242024-07-26 12:02:36 -07001815 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001816 TransformJarsToJar(ctx, combinedJar, "for dex resources", dexAndResourceJarsToCombine, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 false, nil, nil)
1818 if *j.dexProperties.Uncompress_dex {
Colin Cross7707b242024-07-26 12:02:36 -07001819 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName)
Cole Faust51d7bfd2023-09-07 05:31:32 +00001820 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001821 dexOutputFile = combinedAlignedJar
1822 } else {
1823 dexOutputFile = combinedJar
1824 }
1825 }
1826
Paul Duffin4de94502021-05-16 05:21:16 +01001827 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001828
1829 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001830
1831 // Encode hidden API flags in dex file, if needed.
1832 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1833
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001834 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001835
1836 // Dexpreopting
Jihoon Kanga3a05462024-04-05 00:36:44 +00001837 libName := android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())
1838 if j.SdkLibraryName() != nil && strings.HasSuffix(ctx.ModuleName(), ".impl") {
1839 libName = strings.TrimSuffix(libName, ".impl")
1840 }
1841 j.dexpreopt(ctx, libName, dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001842
1843 outputFile = dexOutputFile
Colin Crossa6182ab2024-08-21 10:47:44 -07001844
1845 ctx.CheckbuildFile(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001846 } else {
1847 // There is no code to compile into a dex jar, make sure the resources are propagated
1848 // to the APK if this is an app.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001849 j.dexJarFile = makeDexJarPathFromPath(combinedResourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001850 }
1851
1852 if ctx.Failed() {
1853 return
1854 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001855 }
1856
1857 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001858 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001859 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001860 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001861 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001862 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001863 }
1864 }
1865
1866 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001867 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1868 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001869 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1870 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001871 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001872 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001873 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001874 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 j.linter.javaLanguageLevel = flags.javaVersion.String()
1876 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001877 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001878 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1879 j.linter.buildModuleReportZip = true
1880 }
1881 j.linter.lint(ctx)
1882 }
1883
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001884 j.collectTransitiveSrcFiles(ctx, srcFiles)
1885
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001886 if ctx.Config().UseTransitiveJarsInClasspath() {
1887 if len(localImplementationJars) > 0 || len(localResourceJars) > 0 || len(localHeaderJars) > 0 {
1888 ctx.CheckbuildFile(localImplementationJars...)
1889 ctx.CheckbuildFile(localResourceJars...)
1890 ctx.CheckbuildFile(localHeaderJars...)
1891 } else {
1892 // There are no local sources or resources in this module, so there is nothing to checkbuild.
1893 ctx.UncheckedModule()
1894 }
1895 } else {
1896 ctx.CheckbuildFile(j.implementationJarFile)
1897 ctx.CheckbuildFile(j.headerJarFile)
1898 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001899
Colin Cross7727c7f2024-07-18 15:36:32 -07001900 android.SetProvider(ctx, JavaInfoProvider, &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001901 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1902 RepackagedHeaderJars: android.PathsIfNonNil(repackagedHeaderJarFile),
1903
1904 LocalHeaderJars: localHeaderJars,
1905 TransitiveStaticLibsHeaderJars: android.NewDepSet(android.PREORDER, localHeaderJars, transitiveStaticLibsHeaderJars),
1906 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
1907 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
1908
Colin Cross9ffaf282024-08-12 13:50:09 -07001909 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
1910 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
Jihoon Kang705e63e2024-03-13 01:21:16 +00001911 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1912 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001913 ResourceJars: android.PathsIfNonNil(combinedResourceJar),
Jihoon Kang705e63e2024-03-13 01:21:16 +00001914 AidlIncludeDirs: j.exportAidlIncludeDirs,
1915 SrcJarArgs: j.srcJarArgs,
1916 SrcJarDeps: j.srcJarDeps,
1917 TransitiveSrcFiles: j.transitiveSrcFiles,
1918 ExportedPlugins: j.exportedPluginJars,
1919 ExportedPluginClasses: j.exportedPluginClasses,
1920 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1921 JacocoReportClassesFile: j.jacocoReportClassesFile,
1922 StubsLinkType: j.stubsLinkType,
Jihoon Kang3921f0b2024-03-12 23:51:37 +00001923 AconfigIntermediateCacheOutputPaths: j.aconfigCacheFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001924 })
1925
1926 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1927 j.outputFile = outputFile.WithoutRel()
1928}
1929
Cole Faustb7493472024-08-28 11:55:52 -07001930func (j *Module) useCompose(ctx android.BaseModuleContext) bool {
1931 return android.InList("androidx.compose.runtime_runtime", j.staticLibs(ctx))
Colin Crossa1ff7c62021-09-17 14:11:52 -07001932}
1933
Colin Crosscde55342024-03-27 14:11:51 -07001934func collectDepProguardSpecInfo(ctx android.ModuleContext) (transitiveProguardFlags, transitiveUnconditionalExportedFlags []*android.DepSet[android.Path]) {
Sam Delmerico95d70942023-08-02 18:00:35 -04001935 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001936 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001937 depTag := ctx.OtherModuleDependencyTag(m)
1938
1939 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1940 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1941 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1942 }
1943
1944 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1945 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1946 }
1947 })
1948
Colin Crosscde55342024-03-27 14:11:51 -07001949 return transitiveProguardFlags, transitiveUnconditionalExportedFlags
1950}
1951
1952func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1953 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
1954
Sam Delmerico95d70942023-08-02 18:00:35 -04001955 directUnconditionalExportedFlags := android.Paths{}
1956 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1957 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1958 if exportUnconditionally {
1959 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1960 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1961 directUnconditionalExportedFlags = proguardFlagsForThisModule
1962 }
1963
1964 return ProguardSpecInfo{
1965 Export_proguard_flags_files: exportUnconditionally,
1966 ProguardFlagsFiles: android.NewDepSet[android.Path](
1967 android.POSTORDER,
1968 proguardFlagsForThisModule,
1969 transitiveProguardFlags,
1970 ),
1971 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1972 android.POSTORDER,
1973 directUnconditionalExportedFlags,
1974 transitiveUnconditionalExportedFlags,
1975 ),
1976 }
1977
1978}
1979
Cole Faust75fffb12021-06-13 15:23:16 -07001980// Returns a copy of the supplied flags, but with all the errorprone-related
1981// fields copied to the regular build's fields.
1982func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1983 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1984
1985 if len(flags.errorProneExtraJavacFlags) > 0 {
1986 if len(flags.javacFlags) > 0 {
1987 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1988 } else {
1989 flags.javacFlags = flags.errorProneExtraJavacFlags
1990 }
1991 }
1992 return flags
1993}
1994
Jaewoong Jung26342642021-03-17 15:56:23 -07001995func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
Colin Cross7707b242024-07-26 12:02:36 -07001996 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07001997
1998 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001999 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07002000 if idx >= 0 {
2001 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00002002 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07002003 jarName += strconv.Itoa(idx)
2004 }
2005
Colin Cross7707b242024-07-26 12:02:36 -07002006 classes := android.PathForModuleOut(ctx, "javac", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002007 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07002008
Cole Faust9decf832024-06-11 11:45:53 -07002009 if ctx.Config().EmitXrefRules() && ctx.Module() == ctx.PrimaryModule() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002010 extractionFile := android.PathForModuleOut(ctx, kzipName)
2011 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
2012 j.kytheFiles = append(j.kytheFiles, extractionFile)
2013 }
2014
Vadim Spivak3c496f02023-06-08 06:14:59 +00002015 if len(flags.processorPath) > 0 {
2016 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
2017 }
2018
Jaewoong Jung26342642021-03-17 15:56:23 -07002019 return classes
2020}
2021
2022// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
2023// since some of these flags may be used internally.
2024func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
2025 for _, flag := range flags {
2026 flag = strings.TrimSpace(flag)
2027
2028 if !strings.HasPrefix(flag, "-") {
2029 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
2030 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
2031 ctx.PropertyErrorf("kotlincflags",
2032 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
2033 } else if inList(flag, config.KotlincIllegalFlags) {
2034 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
2035 } else if flag == "-include-runtime" {
2036 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
2037 } else {
2038 args := strings.Split(flag, " ")
2039 if args[0] == "-kotlin-home" {
2040 ctx.PropertyErrorf("kotlincflags",
2041 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
2042 }
2043 }
2044 }
2045}
2046
2047func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
2048 deps deps, flags javaBuilderFlags, jarName string,
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002049 extraJars android.Paths) (localHeaderJars android.Paths, combinedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002050
Jaewoong Jung26342642021-03-17 15:56:23 -07002051 if len(srcFiles) > 0 || len(srcJars) > 0 {
2052 // Compile java sources into turbine.jar.
2053 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
2054 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002055 localHeaderJars = append(localHeaderJars, turbineJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07002056 }
2057
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002058 localHeaderJars = append(localHeaderJars, extraJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002059
2060 // Combine any static header libraries into classes-header.jar. If there is only
2061 // one input jar this step will be skipped.
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002062 var jars android.Paths
2063 if ctx.Config().UseTransitiveJarsInClasspath() {
2064 depSet := android.NewDepSet(android.PREORDER, localHeaderJars, deps.transitiveStaticLibsHeaderJars)
2065 jars = depSet.ToList()
2066 } else {
2067 jars = append(slices.Clone(localHeaderJars), deps.staticHeaderJars...)
2068 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002069
2070 // we cannot skip the combine step for now if there is only one jar
2071 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
Colin Crossedec77c2024-07-26 15:25:40 -07002072 combinedHeaderJarOutputPath := android.PathForModuleOut(ctx, "turbine-combined", jarName)
2073 TransformJarsToJar(ctx, combinedHeaderJarOutputPath, "for turbine", jars, android.OptionalPath{},
Jaewoong Jung26342642021-03-17 15:56:23 -07002074 false, nil, []string{"META-INF/TRANSITIVE"})
Jaewoong Jung26342642021-03-17 15:56:23 -07002075
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002076 return localHeaderJars, combinedHeaderJarOutputPath
Jaewoong Jung26342642021-03-17 15:56:23 -07002077}
2078
2079func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Colin Cross7707b242024-07-26 12:02:36 -07002080 classesJar android.Path, jarName string, specs string) android.Path {
Jaewoong Jung26342642021-03-17 15:56:23 -07002081
2082 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
Colin Cross7707b242024-07-26 12:02:36 -07002083 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07002084
2085 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
2086
2087 j.jacocoReportClassesFile = jacocoReportClassesFile
2088
2089 return instrumentedJar
2090}
2091
Colin Cross9ffaf282024-08-12 13:50:09 -07002092type providesTransitiveHeaderJarsForR8 struct {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002093 // set of header jars for all transitive libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002094 transitiveLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002095 // set of header jars for all transitive static libs deps
Colin Cross9ffaf282024-08-12 13:50:09 -07002096 transitiveStaticLibsHeaderJarsForR8 *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002097}
2098
Colin Cross9ffaf282024-08-12 13:50:09 -07002099// collectTransitiveHeaderJarsForR8 visits direct dependencies and collects all transitive libs and static_libs
2100// header jars. The semantics of the collected jars are odd (it collects combined jars that contain the static
2101// libs, but also the static libs, and it collects transitive libs dependencies of static_libs), so these
2102// are only used to expand the --lib arguments to R8.
2103func (j *providesTransitiveHeaderJarsForR8) collectTransitiveHeaderJarsForR8(ctx android.ModuleContext) {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002104 directLibs := android.Paths{}
2105 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07002106 transitiveLibs := []*android.DepSet[android.Path]{}
2107 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002108 ctx.VisitDirectDeps(func(module android.Module) {
2109 // don't add deps of the prebuilt version of the same library
2110 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
2111 return
2112 }
2113
Colin Cross7727c7f2024-07-18 15:36:32 -07002114 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2115 tag := ctx.OtherModuleDependencyTag(module)
2116 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
2117 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
2118 directLibs = append(directLibs, dep.HeaderJars...)
2119 } else if tag == staticLibTag {
2120 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
2121 } else {
2122 // Don't propagate transitive libs for other kinds of dependencies.
2123 return
2124 }
Jared Dukeefb6d602023-10-27 18:47:10 +00002125
Colin Cross9ffaf282024-08-12 13:50:09 -07002126 if dep.TransitiveLibsHeaderJarsForR8 != nil {
2127 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002128 }
Colin Cross9ffaf282024-08-12 13:50:09 -07002129 if dep.TransitiveStaticLibsHeaderJarsForR8 != nil {
2130 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJarsForR8)
Colin Cross7727c7f2024-07-18 15:36:32 -07002131 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002132
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002133 }
2134 })
Colin Cross9ffaf282024-08-12 13:50:09 -07002135 j.transitiveLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
2136 j.transitiveStaticLibsHeaderJarsForR8 = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002137}
2138
Jaewoong Jung26342642021-03-17 15:56:23 -07002139func (j *Module) HeaderJars() android.Paths {
2140 if j.headerJarFile == nil {
2141 return nil
2142 }
2143 return android.Paths{j.headerJarFile}
2144}
2145
2146func (j *Module) ImplementationJars() android.Paths {
2147 if j.implementationJarFile == nil {
2148 return nil
2149 }
2150 return android.Paths{j.implementationJarFile}
2151}
2152
Spandan Das59a4a2b2024-01-09 21:35:56 +00002153func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07002154 return j.dexJarFile
2155}
2156
2157func (j *Module) DexJarInstallPath() android.Path {
2158 return j.installFile
2159}
2160
2161func (j *Module) ImplementationAndResourcesJars() android.Paths {
2162 if j.implementationAndResourcesJar == nil {
2163 return nil
2164 }
2165 return android.Paths{j.implementationAndResourcesJar}
2166}
2167
2168func (j *Module) AidlIncludeDirs() android.Paths {
2169 // exportAidlIncludeDirs is type android.Paths already
2170 return j.exportAidlIncludeDirs
2171}
2172
2173func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2174 return j.classLoaderContexts
2175}
2176
2177// Collect information for opening IDE project files in java/jdeps.go.
Cole Faustb36d31d2024-08-27 16:04:28 -07002178func (j *Module) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002179 if j.expandJarjarRules != nil {
2180 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
Spandan Das096b8d62024-10-08 22:41:26 +00002181 // Add the header jar so that the rdeps can be resolved to the repackaged classes.
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002182 dpInfo.Jars = append(dpInfo.Jars, j.headerJarFile.String())
Jaewoong Jung26342642021-03-17 15:56:23 -07002183 }
Spandan Das096b8d62024-10-08 22:41:26 +00002184 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2185 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2186 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Spandan Dasb4cd5df2024-08-08 21:57:22 +00002187 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2188 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
Cole Faustb7493472024-08-28 11:55:52 -07002189 dpInfo.Static_libs = append(dpInfo.Static_libs, j.staticLibs(ctx)...)
Yikef6282022022-04-13 20:41:01 +08002190 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002191}
2192
2193func (j *Module) CompilerDeps() []string {
Spandan Das8aac9932024-07-18 23:14:13 +00002194 return j.compileDepNames
Jaewoong Jung26342642021-03-17 15:56:23 -07002195}
2196
2197func (j *Module) hasCode(ctx android.ModuleContext) bool {
2198 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2199 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2200}
2201
2202// Implements android.ApexModule
2203func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2204 return j.depIsInSameApex(ctx, dep)
2205}
2206
2207// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002208func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002209 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002210 minSdkVersion := j.MinSdkVersion(ctx)
2211 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002212 return fmt.Errorf("min_sdk_version is not specified")
2213 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002214 // If the module is compiling against core (via sdk_version), skip comparison check.
2215 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002216 return nil
2217 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002218 if minSdkVersion.GreaterThan(sdkVersion) {
2219 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002220 }
2221 return nil
2222}
2223
2224func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002225 if j.stem == "" {
2226 panic("Stem() called before stem property was set")
2227 }
2228 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002229}
2230
Jaewoong Jung26342642021-03-17 15:56:23 -07002231func (j *Module) JacocoReportClassesFile() android.Path {
2232 return j.jacocoReportClassesFile
2233}
2234
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002235func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2236 var fromDeps []*android.DepSet[android.Path]
2237 ctx.VisitDirectDeps(func(module android.Module) {
2238 tag := ctx.OtherModuleDependencyTag(module)
2239 if tag == staticLibTag {
Colin Cross7727c7f2024-07-18 15:36:32 -07002240 if depInfo, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2241 if depInfo.TransitiveSrcFiles != nil {
2242 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2243 }
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002244 }
2245 }
2246 })
2247
2248 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2249}
2250
Jaewoong Jung26342642021-03-17 15:56:23 -07002251func (j *Module) IsInstallable() bool {
2252 return Bool(j.properties.Installable)
2253}
2254
2255type sdkLinkType int
2256
2257const (
2258 // TODO(jiyong) rename these for better readability. Make the allowed
2259 // and disallowed link types explicit
2260 // order is important here. See rank()
2261 javaCore sdkLinkType = iota
2262 javaSdk
2263 javaSystem
2264 javaModule
2265 javaSystemServer
2266 javaPlatform
2267)
2268
2269func (lt sdkLinkType) String() string {
2270 switch lt {
2271 case javaCore:
2272 return "core Java API"
2273 case javaSdk:
2274 return "Android API"
2275 case javaSystem:
2276 return "system API"
2277 case javaModule:
2278 return "module API"
2279 case javaSystemServer:
2280 return "system server API"
2281 case javaPlatform:
2282 return "private API"
2283 default:
2284 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2285 }
2286}
2287
2288// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2289// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2290// can't statically depend on modules that use Platform API.
2291func (lt sdkLinkType) rank() int {
2292 return int(lt)
2293}
2294
2295type moduleWithSdkDep interface {
2296 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002297 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002298}
2299
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002300func sdkLinkTypeFromSdkKind(k android.SdkKind) sdkLinkType {
2301 switch k {
2302 case android.SdkCore:
2303 return javaCore
2304 case android.SdkSystem:
2305 return javaSystem
2306 case android.SdkPublic:
2307 return javaSdk
2308 case android.SdkModule:
2309 return javaModule
2310 case android.SdkSystemServer:
2311 return javaSystemServer
2312 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
2313 return javaPlatform
2314 default:
2315 return javaSdk
2316 }
2317}
2318
Jiyong Park92315372021-04-02 08:45:46 +09002319func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002320 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002321 case android.SdkCore.DefaultJavaLibraryName(),
2322 "legacy.core.platform.api.stubs",
2323 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002324 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002325 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002326 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002327 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002328 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002329 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002330 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002331 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002332 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002333 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002334 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002335 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002336 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002337 return javaSystem, true
2338 }
2339
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002340 if stub, linkType := moduleStubLinkType(m); stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07002341 return linkType, true
2342 }
2343
Jiyong Park92315372021-04-02 08:45:46 +09002344 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002345 if !ver.Valid() {
2346 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002347 }
Jihoon Kangfa3f0782024-08-21 20:42:18 +00002348
2349 return sdkLinkTypeFromSdkKind(ver.Kind), false
Jaewoong Jung26342642021-03-17 15:56:23 -07002350}
2351
2352// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2353// this module's. See the comment on rank() for details and an example.
2354func (j *Module) checkSdkLinkType(
2355 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2356 if ctx.Host() {
2357 return
2358 }
2359
Jiyong Park92315372021-04-02 08:45:46 +09002360 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002361 if stubs {
2362 return
2363 }
Jiyong Park92315372021-04-02 08:45:46 +09002364 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002365
2366 if myLinkType.rank() < depLinkType.rank() {
2367 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2368 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2369 "property of the source or target module so that target module is built "+
2370 "with the same or smaller API set when compared to the source.",
2371 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2372 }
2373}
2374
2375func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2376 var deps deps
2377
Jiyong Park92315372021-04-02 08:45:46 +09002378 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002379
Colin Cross9ffaf282024-08-12 13:50:09 -07002380 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002381
2382 var transitiveBootClasspathHeaderJars []*android.DepSet[android.Path]
2383 var transitiveClasspathHeaderJars []*android.DepSet[android.Path]
2384 var transitiveJava9ClasspathHeaderJars []*android.DepSet[android.Path]
2385 var transitiveStaticJarsHeaderLibs []*android.DepSet[android.Path]
2386 var transitiveStaticJarsImplementationLibs []*android.DepSet[android.Path]
2387 var transitiveStaticJarsResourceLibs []*android.DepSet[android.Path]
2388
Jaewoong Jung26342642021-03-17 15:56:23 -07002389 ctx.VisitDirectDeps(func(module android.Module) {
2390 otherName := ctx.OtherModuleName(module)
2391 tag := ctx.OtherModuleDependencyTag(module)
2392
2393 if IsJniDepTag(tag) {
2394 // Handled by AndroidApp.collectAppDeps
2395 return
2396 }
2397 if tag == certificateTag {
2398 // Handled by AndroidApp.collectAppDeps
2399 return
2400 }
2401
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002402 if sdkInfo, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -07002403 switch tag {
Jihoon Kang28c96572024-09-11 23:44:44 +00002404 case sdkLibTag, libTag, staticLibTag:
Jihoon Kang28c96572024-09-11 23:44:44 +00002405 generatingLibsString := android.PrettyConcat(
2406 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
2407 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 -07002408 }
Colin Cross313aa542023-12-13 13:47:44 -08002409 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2410 if sdkLinkType != javaPlatform {
2411 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2412 // dep is a sysprop implementation library, but this module is not linking against
2413 // the platform, so it gets the sysprop public stubs library instead. Replace
2414 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2415 dep = syspropDep.JavaInfo
2416 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002417 }
2418 switch tag {
2419 case bootClasspathTag:
2420 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002421 if dep.TransitiveStaticLibsHeaderJars != nil {
2422 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2423 }
Liz Kammeref28a4c2022-09-23 16:50:56 -04002424 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002425 if _, ok := module.(*Plugin); ok {
2426 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2427 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002428 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002429 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002430 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2431 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2432 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2433 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002434 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2435 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2436 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002437
2438 if dep.TransitiveStaticLibsHeaderJars != nil {
2439 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2440 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002441 case java9LibTag:
2442 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002443 if dep.TransitiveStaticLibsHeaderJars != nil {
2444 transitiveJava9ClasspathHeaderJars = append(transitiveJava9ClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2445 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002446 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002447 if _, ok := module.(*Plugin); ok {
2448 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2449 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002450 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2451 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2452 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2453 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2454 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2455 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2456 // Turbine doesn't run annotation processors, so any module that uses an
2457 // annotation processor that generates API is incompatible with the turbine
2458 // optimization.
2459 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
Jihoon Kang705e63e2024-03-13 01:21:16 +00002460 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.AconfigIntermediateCacheOutputPaths...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002461
2462 if dep.TransitiveStaticLibsHeaderJars != nil {
2463 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2464 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, dep.TransitiveStaticLibsHeaderJars)
2465 }
2466 if dep.TransitiveStaticLibsImplementationJars != nil {
2467 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, dep.TransitiveStaticLibsImplementationJars)
2468 }
2469 if dep.TransitiveStaticLibsResourceJars != nil {
2470 transitiveStaticJarsResourceLibs = append(transitiveStaticJarsResourceLibs, dep.TransitiveStaticLibsResourceJars)
2471 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002472 case pluginTag:
2473 if plugin, ok := module.(*Plugin); ok {
2474 if plugin.pluginProperties.Processor_class != nil {
2475 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2476 } else {
2477 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2478 }
2479 // Turbine doesn't run annotation processors, so any module that uses an
2480 // annotation processor that generates API is incompatible with the turbine
2481 // optimization.
2482 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2483 } else {
2484 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2485 }
2486 case errorpronePluginTag:
2487 if _, ok := module.(*Plugin); ok {
2488 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2489 } else {
2490 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2491 }
2492 case exportedPluginTag:
2493 if plugin, ok := module.(*Plugin); ok {
2494 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2495 if plugin.pluginProperties.Processor_class != nil {
2496 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2497 }
2498 // Turbine doesn't run annotation processors, so any module that uses an
2499 // annotation processor that generates API is incompatible with the turbine
2500 // optimization.
2501 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2502 } else {
2503 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2504 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07002505 case kotlinPluginTag:
Luca Stefani50098f72024-10-12 17:55:31 +02002506 if _, ok := module.(*KotlinPlugin); ok {
2507 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
2508 } else {
2509 ctx.PropertyErrorf("kotlin_plugins", "%q is not a kotlin_plugin module", otherName)
2510 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002511 case syspropPublicStubDepTag:
2512 // This is a sysprop implementation library, forward the JavaInfoProvider from
2513 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002514 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002515 JavaInfo: dep,
2516 })
2517 }
2518 } else if dep, ok := module.(android.SourceFileProducer); ok {
2519 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002520 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002521 checkProducesJars(ctx, dep)
2522 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002523 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002524 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars,
2525 android.NewDepSet(android.PREORDER, dep.Srcs(), nil))
Jaewoong Jung26342642021-03-17 15:56:23 -07002526 case staticLibTag:
2527 checkProducesJars(ctx, dep)
2528 deps.classpath = append(deps.classpath, dep.Srcs()...)
2529 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2530 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002531
2532 depHeaderJars := android.NewDepSet(android.PREORDER, dep.Srcs(), nil)
2533 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, depHeaderJars)
2534 transitiveStaticJarsHeaderLibs = append(transitiveStaticJarsHeaderLibs, depHeaderJars)
2535 transitiveStaticJarsImplementationLibs = append(transitiveStaticJarsImplementationLibs, depHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07002536 }
Jihoon Kang705e63e2024-03-13 01:21:16 +00002537 } else if dep, ok := android.OtherModuleProvider(ctx, module, android.CodegenInfoProvider); ok {
Jihoon Kang3921f0b2024-03-12 23:51:37 +00002538 switch tag {
2539 case staticLibTag:
2540 deps.aconfigProtoFiles = append(deps.aconfigProtoFiles, dep.IntermediateCacheOutputPaths...)
2541 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002542 } else {
2543 switch tag {
2544 case bootClasspathTag:
2545 // If a system modules dependency has been added to the bootclasspath
2546 // then add its libs to the bootclasspath.
Colin Crossb61c2262024-08-08 14:04:42 -07002547 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002548 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars...)
2549 if sm.TransitiveStaticLibsHeaderJars != nil {
2550 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars,
2551 sm.TransitiveStaticLibsHeaderJars)
2552 }
Colin Crossb61c2262024-08-08 14:04:42 -07002553 } else {
2554 ctx.PropertyErrorf("boot classpath dependency %q does not provide SystemModulesProvider",
2555 ctx.OtherModuleName(module))
2556 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002557
2558 case systemModulesTag:
2559 if deps.systemModules != nil {
2560 panic("Found two system module dependencies")
2561 }
Colin Crossb61c2262024-08-08 14:04:42 -07002562 if sm, ok := android.OtherModuleProvider(ctx, module, SystemModulesProvider); ok {
2563 deps.systemModules = &systemModules{sm.OutputDir, sm.OutputDirDeps}
2564 } else {
2565 ctx.PropertyErrorf("system modules dependency %q does not provide SystemModulesProvider",
2566 ctx.OtherModuleName(module))
2567 }
Paul Duffin53a70a42022-01-11 14:35:55 +00002568
2569 case instrumentationForTag:
2570 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 -07002571 }
2572 }
2573
Spandan Das8aac9932024-07-18 23:14:13 +00002574 if android.InList(tag, compileDependencyTags) {
2575 // Add the dependency name to compileDepNames so that it can be recorded in module_bp_java_deps.json
2576 j.compileDepNames = append(j.compileDepNames, otherName)
2577 }
2578
Jaewoong Jung26342642021-03-17 15:56:23 -07002579 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiakai Zhang36937082024-04-15 11:15:50 +00002580 addMissingOptionalUsesLibsFromDep(ctx, module, &j.usesLibrary)
Jaewoong Jung26342642021-03-17 15:56:23 -07002581 })
2582
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002583 deps.transitiveStaticLibsHeaderJars = transitiveStaticJarsHeaderLibs
2584 deps.transitiveStaticLibsImplementationJars = transitiveStaticJarsImplementationLibs
2585 deps.transitiveStaticLibsResourceJars = transitiveStaticJarsResourceLibs
2586
2587 if ctx.Config().UseTransitiveJarsInClasspath() {
2588 depSet := android.NewDepSet(android.PREORDER, nil, transitiveClasspathHeaderJars)
2589 deps.classpath = depSet.ToList()
2590 depSet = android.NewDepSet(android.PREORDER, nil, transitiveBootClasspathHeaderJars)
2591 deps.bootClasspath = depSet.ToList()
2592 depSet = android.NewDepSet(android.PREORDER, nil, transitiveJava9ClasspathHeaderJars)
2593 deps.java9Classpath = depSet.ToList()
2594 }
2595
2596 if ctx.Device() {
2597 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
2598 if sdkDep.invalidVersion {
2599 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2600 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2601 } else if sdkDep.useFiles {
2602 // sdkDep.jar is actually equivalent to turbine header.jar.
2603 deps.classpath = append(slices.Clone(classpath(sdkDep.jars)), deps.classpath...)
2604 deps.dexClasspath = append(slices.Clone(classpath(sdkDep.jars)), deps.dexClasspath...)
2605 deps.aidlPreprocess = sdkDep.aidl
2606 // Add the sdk module dependency to `compileDepNames`.
2607 // This ensures that the dependency is reported in `module_bp_java_deps.json`
2608 // TODO (b/358608607): Move this to decodeSdkDep
2609 sdkSpec := android.SdkContext(j).SdkVersion(ctx)
2610 j.compileDepNames = append(j.compileDepNames, fmt.Sprintf("sdk_%s_%s_android", sdkSpec.Kind.String(), sdkSpec.ApiLevel.String()))
2611 } else {
2612 deps.aidlPreprocess = sdkDep.aidl
2613 }
2614 }
2615
Jaewoong Jung26342642021-03-17 15:56:23 -07002616 return deps
2617}
2618
Joe Onorato349ae8d2024-02-05 22:46:00 +00002619// Provider for jarjar renaming rules.
2620//
2621// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2622// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2623// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2624// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2625// be renamed from that module.
2626// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002627type DependencyUse int
2628
2629const (
2630 RenameUseInvalid DependencyUse = iota
2631 RenameUseInclude
2632 RenameUseExclude
2633)
2634
2635type RenameUseElement struct {
2636 DepName string
2637 RenameUse DependencyUse
2638 Why string // token for determining where in the logic the decision was made.
2639}
2640
Joe Onorato349ae8d2024-02-05 22:46:00 +00002641type JarJarProviderData struct {
2642 // Mapping of class names: original --> renamed. If the value is "", the class will be
2643 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2644 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002645 Rename map[string]string
2646 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002647}
2648
2649func (this JarJarProviderData) GetDebugString() string {
2650 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002651 for _, k := range android.SortedKeys(this.Rename) {
2652 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002653 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2654 result += k + "--&gt;" + v + ";"
2655 }
2656 }
2657 return result
2658}
2659
2660var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2661
2662var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2663
2664func init() {
2665 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
Yu Liu26a716d2024-08-30 23:40:32 +00002666
2667 gob.Register(BaseJarJarProviderData{})
Joe Onorato349ae8d2024-02-05 22:46:00 +00002668}
2669
2670// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2671// whether they are java modules or not.
2672type BaseJarJarProviderData struct {
2673 JarJarProviderData JarJarProviderData
2674}
2675
2676func (this BaseJarJarProviderData) GetDebugString() string {
2677 return this.JarJarProviderData.GetDebugString()
2678}
2679
2680var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2681
2682// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2683// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2684// either JarJarProvider or BaseJarJarProvider.
2685func mergeJarJarPrefixes(ctx android.ModuleContext) {
2686 mod := ctx.Module()
2687 // Explicitly avoid propagating into some module types.
2688 switch reflect.TypeOf(mod).String() {
2689 case "*java.Droidstubs":
2690 return
2691 }
2692 jarJarData := collectDirectDepsProviders(ctx)
2693 if jarJarData != nil {
2694 providerData := BaseJarJarProviderData{
2695 JarJarProviderData: *jarJarData,
2696 }
2697 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2698 }
2699
2700}
2701
2702// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2703func (module *Module) addJarJarRenameRule(original string, renamed string) {
2704 if module.jarjarRenameRules == nil {
2705 module.jarjarRenameRules = make(map[string]string)
2706 }
2707 module.jarjarRenameRules[original] = renamed
2708}
2709
2710func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2711 // Gather repackage information from deps
2712 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002713
2714 module := ctx.Module()
2715 moduleName := module.Name()
2716
Colin Cross648daea2024-09-12 14:35:29 -07002717 ctx.VisitDirectDeps(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002718 tag := ctx.OtherModuleDependencyTag(m)
2719 // This logic mirrors that in (*Module).collectDeps above. There are several places
2720 // where we explicitly return RenameUseExclude, even though it is the default, to
2721 // indicate that it has been verified to be the case.
2722 //
2723 // Note well: there are probably cases that are getting to the unconditional return
2724 // and are therefore wrong.
2725 shouldIncludeRenames := func() (DependencyUse, string) {
2726 if moduleName == m.Name() {
2727 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2728 }
2729 if sc, ok := module.(android.SdkContext); ok {
2730 if ctx.Device() {
2731 sdkDep := decodeSdkDep(ctx, sc)
2732 if !sdkDep.invalidVersion && sdkDep.useFiles {
2733 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002734 }
2735 }
LaMont Jones63683e42024-02-08 14:30:45 -08002736 }
2737 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2738 return RenameUseExclude, "tags"
2739 }
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002740 if _, ok := android.OtherModuleProvider(ctx, m, SdkLibraryInfoProvider); ok {
LaMont Jones63683e42024-02-08 14:30:45 -08002741 switch tag {
2742 case sdkLibTag, libTag:
2743 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2744 }
2745 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2746 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2747 switch ji.StubsLinkType {
2748 case Stubs:
2749 return RenameUseExclude, "info"
2750 case Implementation:
2751 return RenameUseInclude, "info"
2752 default:
LaMont Jones09721862024-06-11 10:30:50 -07002753 //fmt.Printf("collectDirectDepsProviders: %v -> %v StubsLinkType unknown\n", module, m)
LaMont Jones63683e42024-02-08 14:30:45 -08002754 // Fall through to the heuristic logic.
2755 }
2756 switch reflect.TypeOf(m).String() {
2757 case "*java.GeneratedJavaLibraryModule":
2758 // Probably a java_aconfig_library module.
2759 // TODO: make this check better.
2760 return RenameUseInclude, "reflect"
2761 }
2762 switch tag {
2763 case bootClasspathTag:
2764 return RenameUseExclude, "tagswitch"
2765 case sdkLibTag, libTag, instrumentationForTag:
2766 return RenameUseInclude, "tagswitch"
2767 case java9LibTag:
2768 return RenameUseExclude, "tagswitch"
2769 case staticLibTag:
2770 return RenameUseInclude, "tagswitch"
2771 case pluginTag:
2772 return RenameUseInclude, "tagswitch"
2773 case errorpronePluginTag:
2774 return RenameUseInclude, "tagswitch"
2775 case exportedPluginTag:
2776 return RenameUseInclude, "tagswitch"
LaMont Jones63683e42024-02-08 14:30:45 -08002777 case kotlinPluginTag:
2778 return RenameUseInclude, "tagswitch"
2779 default:
2780 return RenameUseExclude, "tagswitch"
2781 }
2782 } else if _, ok := m.(android.SourceFileProducer); ok {
2783 switch tag {
2784 case sdkLibTag, libTag, staticLibTag:
2785 return RenameUseInclude, "srcfile"
2786 default:
2787 return RenameUseExclude, "srcfile"
2788 }
Yu Liu67a28422024-03-05 00:36:31 +00002789 } else if _, ok := android.OtherModuleProvider(ctx, m, android.CodegenInfoProvider); ok {
Jihoon Kang03d014f2024-02-16 22:22:18 +00002790 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002791 } else {
2792 switch tag {
2793 case bootClasspathTag:
2794 return RenameUseExclude, "else"
2795 case systemModulesTag:
2796 return RenameUseInclude, "else"
2797 }
2798 }
2799 // If we got here, choose the safer option, which may lead to a build failure, rather
2800 // than runtime failures on the device.
2801 return RenameUseExclude, "end"
2802 }
2803
2804 if result == nil {
2805 result = &JarJarProviderData{
2806 Rename: make(map[string]string),
2807 RenameUse: make([]RenameUseElement, 0),
2808 }
2809 }
2810 how, why := shouldIncludeRenames()
2811 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2812 if how != RenameUseInclude {
2813 // Nothing to merge.
2814 return
2815 }
2816
2817 merge := func(theirs *JarJarProviderData) {
2818 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002819 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2820 result.Rename[orig] = renamed
2821 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2822 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2823 result.Rename[orig] = renamed
2824 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2825 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2826 continue
2827 }
2828 }
2829 }
2830 }
2831 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2832 merge(&theirs)
2833 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2834 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2835 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2836 // to java.Module.
2837 merge(&theirs.JarJarProviderData)
2838 }
2839 })
2840 return
2841}
2842
2843func (this Module) GetDebugString() string {
2844 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2845}
2846
2847// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2848// us, and if it's been set, apply the jarjar_prefix property to rename them.
2849func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2850 // Gather repackage information from deps
2851 result := collectDirectDepsProviders(ctx)
2852
Joe Onoratoa5d17172024-07-20 17:39:56 -07002853 add := func(orig string, renamed string) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002854 if result == nil {
2855 result = &JarJarProviderData{
2856 Rename: make(map[string]string),
2857 }
2858 }
2859 if renamed != "" {
2860 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2861 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
Joe Onoratoa5d17172024-07-20 17:39:56 -07002862 return
Joe Onorato349ae8d2024-02-05 22:46:00 +00002863 }
2864 }
2865 (*result).Rename[orig] = renamed
2866 }
2867
Joe Onoratoa5d17172024-07-20 17:39:56 -07002868 // Update that with entries we've stored for ourself
2869 for orig, renamed := range module.jarjarRenameRules {
2870 add(orig, renamed)
2871 }
2872
2873 // Update that with entries given in the jarjar_rename property.
2874 for _, orig := range module.properties.Jarjar_rename {
2875 add(orig, "")
2876 }
2877
Joe Onorato349ae8d2024-02-05 22:46:00 +00002878 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2879 if result == nil {
2880 return nil
2881 }
2882
2883 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2884 // that have not yet been renamed.
2885 prefix := proptools.String(module.properties.Jarjar_prefix)
2886 if prefix != "" {
2887 if prefix[0] == '.' {
2888 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2889 return nil
2890 }
2891 if prefix[len(prefix)-1] == '.' {
2892 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2893 return nil
2894 }
2895
2896 var updated map[string]string
2897 for orig, renamed := range (*result).Rename {
2898 if renamed == "" {
2899 if updated == nil {
2900 updated = make(map[string]string)
2901 }
2902 updated[orig] = prefix + "." + orig
2903 }
2904 }
2905 for orig, renamed := range updated {
2906 (*result).Rename[orig] = renamed
2907 }
2908 }
2909
2910 return result
2911}
2912
2913// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2914// to "" won't be in this list because they shouldn't be renamed yet.
2915func getJarJarRuleText(provider *JarJarProviderData) string {
2916 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002917 for _, orig := range android.SortedKeys(provider.Rename) {
2918 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002919 if renamed != "" {
2920 result += "rule " + orig + " " + renamed + "\n"
2921 }
2922 }
2923 return result
2924}
2925
Zi Wangddb2ee52024-04-02 16:44:02 +00002926// Repackage the flags if the jarjar rule txt for the flags is generated
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002927func (j *Module) repackageFlagsIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Zi Wangddb2ee52024-04-02 16:44:02 +00002928 if j.repackageJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002929 return infile, false
Zi Wangddb2ee52024-04-02 16:44:02 +00002930 }
Colin Crossedec77c2024-07-26 15:25:40 -07002931 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", info, jarName)
Zi Wangddb2ee52024-04-02 16:44:02 +00002932 TransformJarJar(ctx, repackagedJarjarFile, infile, j.repackageJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002933 return repackagedJarjarFile, true
Zi Wangddb2ee52024-04-02 16:44:02 +00002934}
2935
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002936func (j *Module) jarjarIfNecessary(ctx android.ModuleContext, infile android.Path, jarName, info string) (android.Path, bool) {
Colin Crossedec77c2024-07-26 15:25:40 -07002937 if j.expandJarjarRules == nil {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002938 return infile, false
Colin Crossedec77c2024-07-26 15:25:40 -07002939 }
2940 jarjarFile := android.PathForModuleOut(ctx, "jarjar", info, jarName)
2941 TransformJarJar(ctx, jarjarFile, infile, j.expandJarjarRules)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002942 return jarjarFile, true
Colin Crossedec77c2024-07-26 15:25:40 -07002943
2944}
2945
Jaewoong Jung26342642021-03-17 15:56:23 -07002946func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2947 deps.processorPath = append(deps.processorPath, pluginJars...)
2948 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2949}
2950
2951// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2952// this interface.
2953type ProvidesUsesLib interface {
2954 ProvidesUsesLib() *string
2955}
2956
2957func (j *Module) ProvidesUsesLib() *string {
2958 return j.usesLibraryProperties.Provides_uses_lib
2959}
satayev1c564cc2021-05-25 19:50:30 +01002960
2961type ModuleWithStem interface {
2962 Stem() string
2963}
2964
2965var _ ModuleWithStem = (*Module)(nil)
Jiakai Zhangf98da192024-04-15 11:15:41 +00002966
2967type ModuleWithUsesLibrary interface {
2968 UsesLibrary() *usesLibrary
2969}
2970
2971func (j *Module) UsesLibrary() *usesLibrary {
2972 return &j.usesLibrary
2973}
2974
2975var _ ModuleWithUsesLibrary = (*Module)(nil)