blob: 2b499e2a53129361d12d84dc0a8575dc31dfd384 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
Joe Onorato349ae8d2024-02-05 22:46:00 +000020 "reflect"
21 "slices"
Jaewoong Jung26342642021-03-17 15:56:23 -070022 "strconv"
23 "strings"
24
Colin Crossd788b3e2023-11-28 13:14:56 -080025 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070026 "github.com/google/blueprint/pathtools"
27 "github.com/google/blueprint/proptools"
28
Jihoon Kang03d014f2024-02-16 22:22:18 +000029 "android/soong/aconfig"
Jaewoong Jung26342642021-03-17 15:56:23 -070030 "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
84 Static_libs []string `android:"arch_variant"`
85
Jihoon Kang381c2fa2023-06-01 22:17:32 +000086 // list of java libraries that should not be used to build this module
87 Exclude_static_libs []string `android:"arch_variant"`
88
Jaewoong Jung26342642021-03-17 15:56:23 -070089 // manifest file to be included in resulting jar
90 Manifest *string `android:"path"`
91
92 // if not blank, run jarjar using the specified rules file
93 Jarjar_rules *string `android:"path,arch_variant"`
94
Joe Onorato349ae8d2024-02-05 22:46:00 +000095 // if not blank, used as prefix to generate repackage rule
96 Jarjar_prefix *string
97
Jaewoong Jung26342642021-03-17 15:56:23 -070098 // If not blank, set the java version passed to javac as -source and -target
99 Java_version *string
100
101 // If set to true, allow this module to be dexed and installed on devices. Has no
102 // effect on host modules, which are always considered installable.
103 Installable *bool
104
105 // If set to true, include sources used to compile the module in to the final jar
106 Include_srcs *bool
107
108 // If not empty, classes are restricted to the specified packages and their sub-packages.
109 // This restriction is checked after applying jarjar rules and including static libs.
110 Permitted_packages []string
111
112 // List of modules to use as annotation processors
113 Plugins []string
114
115 // List of modules to export to libraries that directly depend on this library as annotation
116 // processors. Note that if the plugins set generates_api: true this will disable the turbine
117 // optimization on modules that depend on this module, which will reduce parallelism and cause
118 // more recompilation.
119 Exported_plugins []string
120
121 // The number of Java source entries each Javac instance can process
122 Javac_shard_size *int64
123
124 // Add host jdk tools.jar to bootclasspath
125 Use_tools_jar *bool
126
127 Openjdk9 struct {
128 // List of source files that should only be used when passing -source 1.9 or higher
129 Srcs []string `android:"path"`
130
131 // List of javac flags that should only be used when passing -source 1.9 or higher
132 Javacflags []string
133 }
134
135 // When compiling language level 9+ .java code in packages that are part of
136 // a system module, patch_module names the module that your sources and
137 // dependencies should be patched into. The Android runtime currently
138 // doesn't implement the JEP 261 module system so this option is only
139 // supported at compile time. It should only be needed to compile tests in
140 // packages that exist in libcore and which are inconvenient to move
141 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400142 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700143
144 Jacoco struct {
145 // List of classes to include for instrumentation with jacoco to collect coverage
146 // information at runtime when building with coverage enabled. If unset defaults to all
147 // classes.
148 // Supports '*' as the last character of an entry in the list as a wildcard match.
149 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
150 // it matches classes in the package that have the class name as a prefix.
151 Include_filter []string
152
153 // List of classes to exclude from instrumentation with jacoco to collect coverage
154 // information at runtime when building with coverage enabled. Overrides classes selected
155 // by the include_filter property.
156 // Supports '*' as the last character of an entry in the list as a wildcard match.
157 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
158 // it matches classes in the package that have the class name as a prefix.
159 Exclude_filter []string
160 }
161
162 Errorprone struct {
163 // List of javac flags that should only be used when running errorprone.
164 Javacflags []string
165
166 // List of java_plugin modules that provide extra errorprone checks.
167 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700168
Cole Faust2b1536e2021-06-18 12:25:54 -0700169 // This property can be in 3 states. When set to true, errorprone will
170 // be run during the regular build. When set to false, errorprone will
171 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
172 // environment variable is true. Setting this to false will improve build
173 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700174 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700175 }
176
177 Proto struct {
178 // List of extra options that will be passed to the proto generator.
179 Output_params []string
180 }
181
Sam Delmericoc7593722022-08-31 15:57:52 -0400182 // If true, then jacocoagent is automatically added as a libs dependency so that
183 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700184 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000185 // If true, then the module supports statically including the jacocoagent
186 // into the library.
187 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700188
189 // List of files to include in the META-INF/services folder of the resulting jar.
190 Services []string `android:"path,arch_variant"`
191
192 // If true, package the kotlin stdlib into the jar. Defaults to true.
193 Static_kotlin_stdlib *bool `android:"arch_variant"`
194
195 // A list of java_library instances that provide additional hiddenapi annotations for the library.
196 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700197
198 // Additional srcJars tacked in by GeneratedJavaLibraryModule
199 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000200
201 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400202 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800203
204 // A list of files or dependencies to make available to the build sandbox. This is
205 // useful if source files are symlinks, the targets of the symlinks must be listed here.
206 // Note that currently not all actions implemented by android_apps are sandboxed, so you
207 // may only see this being necessary in lint builds.
208 Compile_data []string `android:"path"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000209
210 // Property signifying whether the module compiles stubs or not.
211 // Should be set to true when srcs of this module are stub files.
212 // This property does not need to be set to true when the module depends on
213 // the stubs via libs, but should be set to true when the module depends on
214 // the stubs via static libs.
215 Is_stubs_module *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700216}
217
218// Properties that are specific to device modules. Host module factories should not add these when
219// constructing a new module.
220type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000221 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000222 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000223 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000224 // 1) numerical API level, "current", "none", or "core_platform"
225 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
226 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
227 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700228 Sdk_version *string
229
230 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000231 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700232 Min_sdk_version *string
233
satayev0a420e72021-11-29 17:25:52 +0000234 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
235 // Defaults to empty string "". See sdk_version for possible values.
236 Max_sdk_version *string
237
William Loh5a082f92022-05-17 20:21:50 +0000238 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
239 // Defaults to empty string "". See sdk_version for possible values.
240 Replace_max_sdk_version_placeholder *string
241
Jaewoong Jung26342642021-03-17 15:56:23 -0700242 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000243 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700244 Target_sdk_version *string
245
246 // Whether to compile against the platform APIs instead of an SDK.
247 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000248 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700249 Platform_apis *bool
250
251 Aidl struct {
252 // Top level directories to pass to aidl tool
253 Include_dirs []string
254
255 // Directories rooted at the Android.bp file to pass to aidl tool
256 Local_include_dirs []string
257
258 // directories that should be added as include directories for any aidl sources of modules
259 // that depend on this module, as well as to aidl for this module.
260 Export_include_dirs []string
261
262 // whether to generate traces (for systrace) for this interface
263 Generate_traces *bool
264
265 // whether to generate Binder#GetTransaction name method.
266 Generate_get_transaction_name *bool
267
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100268 // whether all interfaces should be annotated with required permissions.
269 Enforce_permissions *bool
270
271 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
272 Enforce_permissions_exceptions []string `android:"path"`
273
Jaewoong Jung26342642021-03-17 15:56:23 -0700274 // list of flags that will be passed to the AIDL compiler
275 Flags []string
276 }
277
278 // If true, export a copy of the module as a -hostdex module for host testing.
279 Hostdex *bool
280
281 Target struct {
282 Hostdex struct {
283 // Additional required dependencies to add to -hostdex modules.
284 Required []string
285 }
286 }
287
288 // When targeting 1.9 and above, override the modules to use with --system,
289 // otherwise provides defaults libraries to add to the bootclasspath.
290 System_modules *string
291
Jaewoong Jung26342642021-03-17 15:56:23 -0700292 IsSDKLibrary bool `blueprint:"mutated"`
293
294 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
295 // Defaults to false.
296 V4_signature *bool
297
298 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
299 // public stubs library.
300 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000301
302 HiddenAPIPackageProperties
303 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700304}
305
Jooyung Han01d80d82022-01-08 12:16:32 +0900306// Device properties that can be overridden by overriding module (e.g. override_android_app)
307type OverridableDeviceProperties struct {
308 // set the name of the output. If not set, `name` is used.
309 // To override a module with this property set, overriding module might need to set this as well.
310 // Otherwise, both the overridden and the overriding modules will have the same output name, which
311 // can cause the duplicate output error.
312 Stem *string
313}
314
Jaewoong Jung26342642021-03-17 15:56:23 -0700315// Functionality common to Module and Import
316//
317// It is embedded in Module so its functionality can be used by methods in Module
318// but it is currently only initialized by Import and Library.
319type embeddableInModuleAndImport struct {
320
321 // Functionality related to this being used as a component of a java_sdk_library.
322 EmbeddableSdkLibraryComponent
323}
324
Paul Duffin71b33cc2021-06-23 11:39:47 +0100325func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
326 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700327}
328
329// Module/Import's DepIsInSameApex(...) delegates to this method.
330//
331// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
332// the one provided by ApexModuleBase.
333func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
334 // dependencies other than the static linkage are all considered crossing APEX boundary
335 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
336 return true
337 }
338 return false
339}
340
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100341// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
342// or an invalid path describing the reason it is invalid.
343//
344// It is unset if a dex jar isn't applicable, i.e. no build rule has been
345// requested to create one.
346//
347// If a dex jar has been requested to be built then it is set, and it may be
348// either a valid android.Path, or invalid with a reason message. The latter
349// happens if the source that should produce the dex file isn't able to.
350//
351// E.g. it is invalid with a reason message if there is a prebuilt APEX that
352// could produce the dex jar through a deapexer module, but the APEX isn't
353// installable so doing so wouldn't be safe.
354type OptionalDexJarPath struct {
355 isSet bool
356 path android.OptionalPath
357}
358
359// IsSet returns true if a path has been set, either invalid or valid.
360func (o OptionalDexJarPath) IsSet() bool {
361 return o.isSet
362}
363
364// Valid returns true if there is a path that is valid.
365func (o OptionalDexJarPath) Valid() bool {
366 return o.isSet && o.path.Valid()
367}
368
369// Path returns the valid path, or panics if it's either not set or is invalid.
370func (o OptionalDexJarPath) Path() android.Path {
371 if !o.isSet {
372 panic("path isn't set")
373 }
374 return o.path.Path()
375}
376
377// PathOrNil returns the path if it's set and valid, or else nil.
378func (o OptionalDexJarPath) PathOrNil() android.Path {
379 if o.Valid() {
380 return o.Path()
381 }
382 return nil
383}
384
385// InvalidReason returns the reason for an invalid path, which is never "". It
386// returns "" for an unset or valid path.
387func (o OptionalDexJarPath) InvalidReason() string {
388 if !o.isSet {
389 return ""
390 }
391 return o.path.InvalidReason()
392}
393
394func (o OptionalDexJarPath) String() string {
395 if !o.isSet {
396 return "<unset>"
397 }
398 return o.path.String()
399}
400
401// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
402func makeUnsetDexJarPath() OptionalDexJarPath {
403 return OptionalDexJarPath{isSet: false}
404}
405
406// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
407// the given OptionalPath, which may be valid or invalid.
408func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
409 return OptionalDexJarPath{isSet: true, path: path}
410}
411
412// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
413// valid given path. It returns an unset OptionalDexJarPath if the given path is
414// nil.
415func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
416 if path == nil {
417 return makeUnsetDexJarPath()
418 }
419 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
420}
421
Jaewoong Jung26342642021-03-17 15:56:23 -0700422// Module contains the properties and members used by all java module types
423type Module struct {
424 android.ModuleBase
425 android.DefaultableModuleBase
426 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700427
428 // Functionality common to Module and Import.
429 embeddableInModuleAndImport
430
431 properties CommonProperties
432 protoProperties android.ProtoProperties
433 deviceProperties DeviceProperties
434
Jooyung Han01d80d82022-01-08 12:16:32 +0900435 overridableDeviceProperties OverridableDeviceProperties
436
Jaewoong Jung26342642021-03-17 15:56:23 -0700437 // jar file containing header classes including static library dependencies, suitable for
438 // inserting into the bootclasspath/classpath of another compile
439 headerJarFile android.Path
440
Joe Onorato349ae8d2024-02-05 22:46:00 +0000441 repackagedHeaderJarFile android.Path
442
Jaewoong Jung26342642021-03-17 15:56:23 -0700443 // jar file containing implementation classes including static library dependencies but no
444 // resources
445 implementationJarFile android.Path
446
447 // jar file containing only resources including from static library dependencies
448 resourceJar android.Path
449
450 // args and dependencies to package source files into a srcjar
451 srcJarArgs []string
452 srcJarDeps android.Paths
453
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000454 // the source files of this module and all its static dependencies
455 transitiveSrcFiles *android.DepSet[android.Path]
456
Jaewoong Jung26342642021-03-17 15:56:23 -0700457 // jar file containing implementation classes and resources including static library
458 // dependencies
459 implementationAndResourcesJar android.Path
460
461 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100462 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700463
464 // output file containing uninstrumented classes that will be instrumented by jacoco
465 jacocoReportClassesFile android.Path
466
467 // output file of the module, which may be a classes jar or a dex jar
468 outputFile android.Path
469 extraOutputFiles android.Paths
470
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100471 exportAidlIncludeDirs android.Paths
472 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700473
474 logtagsSrcs android.Paths
475
476 // installed file for binary dependency
477 installFile android.Path
478
Colin Cross3108ce12021-11-10 14:38:50 -0800479 // installed file for hostdex copy
480 hostdexInstallFile android.InstallPath
481
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800482 // list of unique .java and .kt source files
483 uniqueSrcFiles android.Paths
484
485 // list of srcjars that was passed to javac
486 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700487
488 // manifest file to use instead of properties.Manifest
489 overrideManifest android.OptionalPath
490
Jaewoong Jung26342642021-03-17 15:56:23 -0700491 // list of plugins that this java module is exporting
492 exportedPluginJars android.Paths
493
494 // list of plugins that this java module is exporting
495 exportedPluginClasses []string
496
497 // if true, the exported plugins generate API and require disabling turbine.
498 exportedDisableTurbine bool
499
500 // list of source files, collected from srcFiles with unique java and all kt files,
501 // will be used by android.IDEInfo struct
502 expandIDEInfoCompiledSrcs []string
503
504 // expanded Jarjar_rules
505 expandJarjarRules android.Path
506
Joe Onorato349ae8d2024-02-05 22:46:00 +0000507 // jarjar rule for inherited jarjar rules
508 repackageJarjarRules android.Path
509
Jaewoong Jung26342642021-03-17 15:56:23 -0700510 // Extra files generated by the module type to be added as java resources.
511 extraResources android.Paths
512
513 hiddenAPI
514 dexer
515 dexpreopter
516 usesLibrary
517 linter
518
519 // list of the xref extraction files
520 kytheFiles android.Paths
521
Jaewoong Jung26342642021-03-17 15:56:23 -0700522 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900523
524 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000525 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000526 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400527
528 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000529
530 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000531
532 // output file name based on Stem property.
533 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
534 // or the module should override Stem().
535 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700536
Colin Crossd788b3e2023-11-28 13:14:56 -0800537 // Single aconfig "cache file" merged from this module and all dependencies.
538 mergedAconfigFiles map[string]android.Paths
Joe Onorato349ae8d2024-02-05 22:46:00 +0000539
540 // Values that will be set in the JarJarProvider data for jarjar repackaging,
541 // and merged with our dependencies' rules.
542 jarjarRenameRules map[string]string
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000543
544 stubsLinkType StubsLinkType
Jaewoong Jung26342642021-03-17 15:56:23 -0700545}
546
Jiyong Park92315372021-04-02 08:45:46 +0900547func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
548 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900549 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700550 return nil
551 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900552 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000553 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700554 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
555 } else {
556 // Treat stable core platform as stable.
557 return nil
558 }
559 } else {
560 return fmt.Errorf("non stable SDK %v", sdkVersion)
561 }
562}
563
564// checkSdkVersions enforces restrictions around SDK dependencies.
565func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
566 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900567 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900568 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700569 ctx.PropertyErrorf("sdk_version",
570 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
571 }
572 }
573 }
574
575 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
576 // See rank() for details.
577 ctx.VisitDirectDeps(func(module android.Module) {
578 tag := ctx.OtherModuleDependencyTag(module)
579 switch module.(type) {
580 // TODO(satayev): cover other types as well, e.g. imports
581 case *Library, *AndroidLibrary:
582 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400583 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700584 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
585 }
586 }
587 })
588}
589
590func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900591 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700592 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900593 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700594 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000595 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 -0700596 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000597 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 -0700598 }
599
600 }
601}
602
Mark Whitea15790a2023-08-22 21:28:11 +0000603func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
604 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400605 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000606 installable := proptools.Bool(j.properties.Installable)
607
608 if headersOnly && installable {
609 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.")
610 }
611 }
612}
613
Jaewoong Jung26342642021-03-17 15:56:23 -0700614func (j *Module) addHostProperties() {
615 j.AddProperties(
616 &j.properties,
617 &j.protoProperties,
618 &j.usesLibraryProperties,
619 )
620}
621
622func (j *Module) addHostAndDeviceProperties() {
623 j.addHostProperties()
624 j.AddProperties(
625 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900626 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700627 &j.dexer.dexProperties,
628 &j.dexpreoptProperties,
629 &j.linter.properties,
630 )
631}
632
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000633// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
634// makes it available through the hiddenAPIPropertyInfoProvider.
635func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
636 hiddenAPIInfo := newHiddenAPIPropertyInfo()
637
638 // Populate with flag file paths from the properties.
639 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
640
641 // Populate with package rules from the properties.
642 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
643
Colin Cross40213022023-12-13 15:19:49 -0800644 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000645}
646
Jaewoong Jung26342642021-03-17 15:56:23 -0700647func (j *Module) OutputFiles(tag string) (android.Paths, error) {
648 switch tag {
649 case "":
650 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
651 case android.DefaultDistTag:
652 return android.Paths{j.outputFile}, nil
653 case ".jar":
654 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700655 case ".hjar":
656 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700657 case ".proguard_map":
658 if j.dexer.proguardDictionary.Valid() {
659 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
660 }
661 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700662 case ".generated_srcjars":
663 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000664 case ".lint":
665 if j.linter.outputs.xml != nil {
666 return android.Paths{j.linter.outputs.xml}, nil
667 }
668 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700669 default:
670 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
671 }
672}
673
674var _ android.OutputFileProducer = (*Module)(nil)
675
676func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
677 initJavaModule(module, hod, false)
678}
679
680func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
681 initJavaModule(module, hod, true)
682}
683
684func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
685 multilib := android.MultilibCommon
686 if multiTargets {
687 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
688 } else {
689 android.InitAndroidArchModule(module, hod, multilib)
690 }
691 android.InitDefaultableModule(module)
692}
693
694func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
695 return j.properties.Instrument &&
696 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
697 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
698}
699
700func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000701 return j.properties.Supports_static_instrumentation &&
702 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700703 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
704 ctx.Config().UnbundledBuild())
705}
706
707func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
708 // Force enable the instrumentation for java code that is built for APEXes ...
709 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
710 // 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 -0800711 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700712 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
713 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
714 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
715 return true
716 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
717 return true
718 }
719 }
720 return false
721}
722
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400723func (j *Module) setInstrument(value bool) {
724 j.properties.Instrument = value
725}
726
Jiyong Park92315372021-04-02 08:45:46 +0900727func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
728 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700729}
730
Jiyong Parkf1691d22021-03-29 20:11:58 +0900731func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700732 return proptools.String(j.deviceProperties.System_modules)
733}
734
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000735func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700736 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000737 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700738 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000739 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700740}
741
Yu Liuf2b94012023-09-19 15:09:10 -0700742func (j *Module) GetDeviceProperties() *DeviceProperties {
743 return &j.deviceProperties
744}
745
Spandan Dasa26eda72023-03-02 00:56:06 +0000746func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
747 if j.deviceProperties.Max_sdk_version != nil {
748 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
749 }
750 // Default is PrivateApiLevel
751 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000752}
753
Spandan Dasa26eda72023-03-02 00:56:06 +0000754func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
755 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
756 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
757 }
758 // Default is PrivateApiLevel
759 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000760}
761
Jiyong Parkf1691d22021-03-29 20:11:58 +0900762func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000763 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900764}
765
Spandan Dasca70fc42023-03-01 23:38:49 +0000766func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900767 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000768 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900769 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000770 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700771}
772
773func (j *Module) AvailableFor(what string) bool {
774 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
775 // Exception: for hostdex: true libraries, the platform variant is created
776 // even if it's not marked as available to platform. In that case, the platform
777 // variant is used only for the hostdex and not installed to the device.
778 return true
779 }
780 return j.ApexModuleBase.AvailableFor(what)
781}
782
783func (j *Module) deps(ctx android.BottomUpMutatorContext) {
784 if ctx.Device() {
785 j.linter.deps(ctx)
786
Jiyong Parkf1691d22021-03-29 20:11:58 +0900787 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700788
789 if j.deviceProperties.SyspropPublicStub != "" {
790 // This is a sysprop implementation library that has a corresponding sysprop public
791 // stubs library, and a dependency on it so that dependencies on the implementation can
792 // be forwarded to the public stubs library when necessary.
793 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
794 }
795 }
796
797 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000798
799 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700800 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
801
802 // Add dependency on libraries that provide additional hidden api annotations.
803 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
804
805 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
806 // Require java_sdk_library at inter-partition java dependency to ensure stable
807 // interface between partitions. If inter-partition java_library dependency is detected,
808 // raise build error because java_library doesn't have a stable interface.
809 //
810 // Inputs:
811 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
812 // if true, enable enforcement
813 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
814 // exception list of java_library names to allow inter-partition dependency
815 for idx := range j.properties.Libs {
816 if libDeps[idx] == nil {
817 continue
818 }
819
820 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
821 // java_sdk_library is always allowed at inter-partition dependency.
822 // So, skip check.
823 if _, ok := javaDep.(*SdkLibrary); ok {
824 continue
825 }
826
827 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
828 }
829 }
830 }
831
832 // For library dependencies that are component libraries (like stubs), add the implementation
833 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
834 for _, dep := range libDeps {
835 if dep != nil {
836 if component, ok := dep.(SdkLibraryComponentDependency); ok {
837 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100838 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100839 tag := usesLibReqTag
840 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
841 tag = usesLibOptTag
842 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100843 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700844 }
845 }
846 }
847 }
848
849 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
850 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
851 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
852
853 android.ProtoDeps(ctx, &j.protoProperties)
854 if j.hasSrcExt(".proto") {
855 protoDeps(ctx, &j.protoProperties)
856 }
857
858 if j.hasSrcExt(".kt") {
859 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
860 // Kotlin files
861 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
862 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700863 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700864 }
865
866 // Framework libraries need special handling in static coverage builds: they should not have
867 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
868 // the same jacoco classes coming from different bootclasspath jars.
869 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
870 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
871 j.properties.Instrument = true
872 }
873 } else if j.shouldInstrumentStatic(ctx) {
874 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
875 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700876
877 if j.useCompose() {
878 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
879 "androidx.compose.compiler_compiler-hosted")
880 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700881}
882
883func hasSrcExt(srcs []string, ext string) bool {
884 for _, src := range srcs {
885 if filepath.Ext(src) == ext {
886 return true
887 }
888 }
889
890 return false
891}
892
893func (j *Module) hasSrcExt(ext string) bool {
894 return hasSrcExt(j.properties.Srcs, ext)
895}
896
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100897func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
898 var flags string
899
900 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
901 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
902 flags = "-Wmissing-permission-annotation -Werror"
903 }
904 }
905 return flags
906}
907
Jaewoong Jung26342642021-03-17 15:56:23 -0700908func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000909 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700910
911 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
912 aidlIncludes = append(aidlIncludes,
913 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
914 aidlIncludes = append(aidlIncludes,
915 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
916
917 var flags []string
918 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000919 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700920
921 flags = append(flags, j.deviceProperties.Aidl.Flags...)
922
923 if aidlPreprocess.Valid() {
924 flags = append(flags, "-p"+aidlPreprocess.String())
925 deps = append(deps, aidlPreprocess.Path())
926 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000927 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700928 }
929
930 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000931 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700932 }
933
934 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000935 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700936 }
937
Sam Delmerico2351eac2022-05-24 17:10:02 +0000938 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700939 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000940 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700941 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000942 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
943 // add flags for dirs containing AIDL srcs that haven't been specified yet
944 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700945
Zim8774ae12022-08-17 11:46:34 +0100946 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000947 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100948 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700949 flags = append(flags, "-t")
950 }
951
952 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
953 flags = append(flags, "--transaction_names")
954 }
955
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100956 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
957 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
958 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
959 }
960
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000961 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900962 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
963
Jaewoong Jung26342642021-03-17 15:56:23 -0700964 return strings.Join(flags, " "), deps
965}
966
967func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
968
969 var flags javaBuilderFlags
970
971 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900972 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700973
Cole Faust2b1536e2021-06-18 12:25:54 -0700974 epEnabled := j.properties.Errorprone.Enabled
975 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100976 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700977 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
978 }
979
980 errorProneFlags := []string{
981 "-Xplugin:ErrorProne",
982 "${config.ErrorProneChecks}",
983 }
984 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
985
Colin Cross8bf6cad2022-02-28 13:07:03 -0800986 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700987 "'" + strings.Join(errorProneFlags, " ") + "'"
988 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
989 }
990
991 // classpath
992 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
993 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700994 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700995 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
996 flags.processorPath = append(flags.processorPath, deps.processorPath...)
997 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
998
999 flags.processors = append(flags.processors, deps.processorClasses...)
1000 flags.processors = android.FirstUniqueStrings(flags.processors)
1001
1002 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +09001003 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001004 // Give host-side tools a version of OpenJDK's standard libraries
1005 // close to what they're targeting. As of Dec 2017, AOSP is only
1006 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
1007 //
1008 // When building with OpenJDK 8, the following should have no
1009 // effect since those jars would be available by default.
1010 //
1011 // When building with OpenJDK 9 but targeting a version < 1.8,
1012 // putting them on the bootclasspath means that:
1013 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
1014 // b) references to existing APIs are not reinterpreted in an
1015 // OpenJDK 9-specific way, eg. calls to subclasses of
1016 // java.nio.Buffer as in http://b/70862583
1017 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
1018 flags.bootClasspath = append(flags.bootClasspath,
1019 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1020 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1021 if Bool(j.properties.Use_tools_jar) {
1022 flags.bootClasspath = append(flags.bootClasspath,
1023 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1024 }
1025 }
1026
1027 // systemModules
1028 flags.systemModules = deps.systemModules
1029
Jaewoong Jung26342642021-03-17 15:56:23 -07001030 return flags
1031}
1032
1033func (j *Module) collectJavacFlags(
1034 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1035 // javac flags.
1036 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001037 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001038
Mythri Alle4b9f6182023-10-25 15:17:11 +00001039 needsDebugInfo = false
1040 for _, flag := range javacFlags {
1041 if strings.HasPrefix(flag, "-g") {
1042 needsDebugInfo = true
1043 }
1044 }
1045
1046 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001047 // For non-host binaries, override the -g flag passed globally to remove
1048 // local variable debug info to reduce disk and memory usage.
1049 javacFlags = append(javacFlags, "-g:source,lines")
1050 }
1051 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1052
1053 if flags.javaVersion.usesJavaModules() {
1054 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001055 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1056 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1057 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1058 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001059
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001060 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001061 if j.properties.Patch_module != nil {
1062 // Manually specify build directory in case it is not under the repo root.
1063 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1064 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001065 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001066
Jaewoong Jung26342642021-03-17 15:56:23 -07001067 classPath := flags.classpath.FormJavaClassPath("")
1068 if classPath != "" {
1069 patchPaths = append(patchPaths, classPath)
1070 }
1071 javacFlags = append(
1072 javacFlags,
1073 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1074 }
1075 }
1076
1077 if len(javacFlags) > 0 {
1078 // optimization.
1079 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1080 flags.javacFlags = "$javacFlags"
1081 }
1082
1083 return flags
1084}
1085
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001086func (j *Module) AddJSONData(d *map[string]interface{}) {
1087 (&j.ModuleBase).AddJSONData(d)
1088 (*d)["Java"] = map[string]interface{}{
1089 "SourceExtensions": j.sourceExtensions,
1090 }
1091
1092}
1093
usta0391ca42023-09-19 15:51:59 -04001094func (j *Module) addGeneratedSrcJars(path android.Path) {
1095 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001096}
1097
Colin Cross4eae06d2023-06-20 22:40:02 -07001098func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001099
1100 // Auto-propagating jarjar rules
1101 jarjarProviderData := j.collectJarJarRules(ctx)
1102 if jarjarProviderData != nil {
1103 android.SetProvider(ctx, JarJarProvider, *jarjarProviderData)
1104 text := getJarJarRuleText(jarjarProviderData)
1105 if text != "" {
1106 ruleTextFile := android.PathForModuleOut(ctx, "repackaged-jarjar", "repackaging.txt")
1107 android.WriteFileRule(ctx, ruleTextFile, text)
1108 j.repackageJarjarRules = ruleTextFile
1109 }
1110 }
1111
Jaewoong Jung26342642021-03-17 15:56:23 -07001112 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1113
1114 deps := j.collectDeps(ctx)
1115 flags := j.collectBuilderFlags(ctx, deps)
1116
1117 if flags.javaVersion.usesJavaModules() {
1118 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001119 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1120 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1121 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001122 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001123
Jaewoong Jung26342642021-03-17 15:56:23 -07001124 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001125 j.sourceExtensions = []string{}
1126 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1127 if hasSrcExt(srcFiles.Strings(), ext) {
1128 j.sourceExtensions = append(j.sourceExtensions, ext)
1129 }
1130 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001131 if hasSrcExt(srcFiles.Strings(), ".proto") {
1132 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1133 }
1134
1135 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1136 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1137 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1138 }
1139
Sam Delmerico2351eac2022-05-24 17:10:02 +00001140 aidlSrcs := srcFiles.FilterByExt(".aidl")
1141 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1142
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001143 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 srcFiles = j.genSources(ctx, srcFiles, flags)
1145
1146 // Collect javac flags only after computing the full set of srcFiles to
1147 // ensure that the --patch-module lookup paths are complete.
1148 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1149
1150 srcJars := srcFiles.FilterByExt(".srcjar")
1151 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001152 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001153 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001154 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001155
1156 if j.properties.Jarjar_rules != nil {
1157 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1158 }
1159
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001160 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001161
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001162 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001164 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001165 if _, found := set[v.String()]; !found {
1166 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001167 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001168 }
1169 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001170 var uniqueKtFiles android.Paths
1171 for _, v := range srcFiles.FilterByExt(".kt") {
1172 if _, found := set[v.String()]; !found {
1173 set[v.String()] = true
1174 uniqueKtFiles = append(uniqueKtFiles, v)
1175 }
1176 }
1177
1178 var uniqueSrcFiles android.Paths
1179 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1180 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1181 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001182 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001183
Colin Crossb5db4012022-03-28 17:12:39 -07001184 // We don't currently run annotation processors in turbine, which means we can't use turbine
1185 // generated header jars when an annotation processor that generates API is enabled. One
1186 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1187 // is used to run all of the annotation processors.
1188 disableTurbine := deps.disableTurbine
1189
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001190 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001191 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1192
1193 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001194 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001195
Colin Cross4eae06d2023-06-20 22:40:02 -07001196 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1197 // any dependencies so that it can override any non-final R classes from dependencies with the
1198 // final R classes from the app.
1199 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1200
Mark Whitea15790a2023-08-22 21:28:11 +00001201 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001202 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001203 if srcFiles.HasExt(".kt") {
1204 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1205 }
1206 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1207 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1208 }
1209
Joe Onorato349ae8d2024-02-05 22:46:00 +00001210 _, j.headerJarFile, _ =
Mark Whitea15790a2023-08-22 21:28:11 +00001211 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1212 extraCombinedJars)
1213 if ctx.Failed() {
1214 return
1215 }
1216
Colin Cross40213022023-12-13 15:19:49 -08001217 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Mark Whitea15790a2023-08-22 21:28:11 +00001218 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1219 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1220 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1221 AidlIncludeDirs: j.exportAidlIncludeDirs,
1222 ExportedPlugins: j.exportedPluginJars,
1223 ExportedPluginClasses: j.exportedPluginClasses,
1224 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
Jihoon Kangfe914ed2024-02-12 22:49:21 +00001225 StubsLinkType: j.stubsLinkType,
Mark Whitea15790a2023-08-22 21:28:11 +00001226 })
1227
1228 j.outputFile = j.headerJarFile
1229 return
1230 }
1231
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001233 // When using kotlin sources turbine is used to generate annotation processor sources,
1234 // including for annotation processors that generate API, so we can use turbine for
1235 // java sources too.
1236 disableTurbine = false
1237
Jaewoong Jung26342642021-03-17 15:56:23 -07001238 // user defined kotlin flags.
1239 kotlincFlags := j.properties.Kotlincflags
1240 CheckKotlincFlags(ctx, kotlincFlags)
1241
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001242 // Workaround for KT-46512
1243 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001244
1245 // If there are kotlin files, compile them first but pass all the kotlin and java files
1246 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1247 // won't emit any classes for them.
1248 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1249 if ctx.Device() {
1250 kotlincFlags = append(kotlincFlags, "-no-jdk")
1251 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001252
1253 for _, plugin := range deps.kotlinPlugins {
1254 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1255 }
1256 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1257
Jaewoong Jung26342642021-03-17 15:56:23 -07001258 if len(kotlincFlags) > 0 {
1259 // optimization.
1260 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1261 flags.kotlincFlags += "$kotlincFlags"
1262 }
1263
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001264 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001265 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1266
1267 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1268 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1269
1270 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1271 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1272
Isaac Chioua23d9942022-04-06 06:14:38 +00001273 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001274 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001275 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1276 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001277 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001278 srcJars = append(srcJars, kaptSrcJar)
1279 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001280 // Disable annotation processing in javac, it's already been handled by kapt
1281 flags.processorPath = nil
1282 flags.processors = nil
1283 }
1284
1285 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001286 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001287 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001288 if ctx.Failed() {
1289 return
1290 }
1291
Isaac Chioua23d9942022-04-06 06:14:38 +00001292 // Make javac rule depend on the kotlinc rule
1293 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1294
Jaewoong Jung26342642021-03-17 15:56:23 -07001295 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001296 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1297
Jaewoong Jung26342642021-03-17 15:56:23 -07001298 // Jar kotlin classes into the final jar after javac
1299 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1300 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001301 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001302 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001303 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001304 } else {
1305 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001306 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001307 }
1308 }
1309
1310 jars := append(android.Paths(nil), kotlinJars...)
1311
Jaewoong Jung26342642021-03-17 15:56:23 -07001312 j.compiledSrcJars = srcJars
1313
1314 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001315 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001316 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001317 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1318 enableSharding = true
1319 // Formerly, there was a check here that prevented annotation processors
1320 // from being used when sharding was enabled, as some annotation processors
1321 // do not function correctly in sharded environments. It was removed to
1322 // allow for the use of annotation processors that do function correctly
1323 // with sharding enabled. See: b/77284273.
1324 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001325 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00001326 headerJarFileWithoutDepsOrJarjar, j.headerJarFile, j.repackagedHeaderJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001327 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001328 if ctx.Failed() {
1329 return
1330 }
1331 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001332 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001333 hasErrorproneableFiles := false
1334 for _, ext := range j.sourceExtensions {
1335 if ext != ".proto" && ext != ".aidl" {
1336 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1337 // compile, and it's not useful to have warnings on these generated sources.
1338 hasErrorproneableFiles = true
1339 break
1340 }
1341 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001342 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001343 if Bool(j.properties.Errorprone.Enabled) {
1344 // If error-prone is enabled, enable errorprone flags on the regular
1345 // build.
1346 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001347 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001348 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1349 // a new jar file just for compiling with the errorprone compiler to.
1350 // This is because we don't want to cause the java files to get completely
1351 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1352 // We also don't want to run this if errorprone is enabled by default for
1353 // this module, or else we could have duplicated errorprone messages.
1354 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001355 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001356 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001357
Vadim Spivak3c496f02023-06-08 06:14:59 +00001358 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001359 "errorprone", "errorprone")
1360
Jaewoong Jung26342642021-03-17 15:56:23 -07001361 extraJarDeps = append(extraJarDeps, errorprone)
1362 }
1363
1364 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001365 if headerJarFileWithoutDepsOrJarjar != nil {
1366 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1367 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001368 shardSize := int(*(j.properties.Javac_shard_size))
1369 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001370 if len(uniqueJavaFiles) > 0 {
1371 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001372 for idx, shardSrc := range shardSrcs {
1373 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1374 nil, flags, extraJarDeps)
1375 jars = append(jars, classes)
1376 }
1377 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001378 // Assume approximately 5 sources per srcjar.
1379 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1380 // 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 -07001381 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001382 startIdx := len(shardSrcs)
1383 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1384 for idx, shardSrcJars := range shardSrcJarsList {
1385 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1386 nil, shardSrcJars, flags, extraJarDeps)
1387 jars = append(jars, classes)
1388 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001389 }
1390 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001391 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001392 jars = append(jars, classes)
1393 }
1394 if ctx.Failed() {
1395 return
1396 }
1397 }
1398
1399 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1400
1401 var includeSrcJar android.WritablePath
1402 if Bool(j.properties.Include_srcs) {
1403 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1404 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1405 }
1406
1407 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1408 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1409 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1410 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1411
1412 var resArgs []string
1413 var resDeps android.Paths
1414
1415 resArgs = append(resArgs, dirArgs...)
1416 resDeps = append(resDeps, dirDeps...)
1417
1418 resArgs = append(resArgs, fileArgs...)
1419 resDeps = append(resDeps, fileDeps...)
1420
1421 resArgs = append(resArgs, extraArgs...)
1422 resDeps = append(resDeps, extraDeps...)
1423
1424 if len(resArgs) > 0 {
1425 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1426 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1427 j.resourceJar = resourceJar
1428 if ctx.Failed() {
1429 return
1430 }
1431 }
1432
1433 var resourceJars android.Paths
1434 if j.resourceJar != nil {
1435 resourceJars = append(resourceJars, j.resourceJar)
1436 }
1437 if Bool(j.properties.Include_srcs) {
1438 resourceJars = append(resourceJars, includeSrcJar)
1439 }
1440 resourceJars = append(resourceJars, deps.staticResourceJars...)
1441
1442 if len(resourceJars) > 1 {
1443 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1444 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1445 false, nil, nil)
1446 j.resourceJar = combinedJar
1447 } else if len(resourceJars) == 1 {
1448 j.resourceJar = resourceJars[0]
1449 }
1450
1451 if len(deps.staticJars) > 0 {
1452 jars = append(jars, deps.staticJars...)
1453 }
1454
1455 manifest := j.overrideManifest
1456 if !manifest.Valid() && j.properties.Manifest != nil {
1457 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1458 }
1459
1460 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1461 if len(services) > 0 {
1462 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1463 var zipargs []string
1464 for _, file := range services {
1465 serviceFile := file.String()
1466 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1467 }
1468 rule := zip
1469 args := map[string]string{
1470 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1471 }
1472 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1473 rule = zipRE
1474 args["implicits"] = strings.Join(services.Strings(), ",")
1475 }
1476 ctx.Build(pctx, android.BuildParams{
1477 Rule: rule,
1478 Output: servicesJar,
1479 Implicits: services,
1480 Args: args,
1481 })
1482 jars = append(jars, servicesJar)
1483 }
1484
Colin Cross4eae06d2023-06-20 22:40:02 -07001485 jars = append(android.CopyOf(extraCombinedJars), jars...)
1486
Jaewoong Jung26342642021-03-17 15:56:23 -07001487 // Combine the classes built from sources, any manifests, and any static libraries into
1488 // classes.jar. If there is only one input jar this step will be skipped.
1489 var outputFile android.OutputPath
1490
1491 if len(jars) == 1 && !manifest.Valid() {
1492 // Optimization: skip the combine step as there is nothing to do
1493 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1494 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1495 // any if len(jars) == 1.
1496
Jihoon Kang1147b312023-06-08 23:25:57 +00001497 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1498 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1499 // either with .from-source or .from-text suffix.
1500 // outputFile should be agnostic to the build configuration,
1501 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1502 // to the copy rules.
1503 stub, _ := moduleStubLinkType(ctx.ModuleName())
1504
Jaewoong Jung26342642021-03-17 15:56:23 -07001505 // Transform the single path to the jar into an OutputPath as that is required by the following
1506 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001507 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001508 // The path contains an embedded OutputPath so reuse that.
1509 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001510 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 // The path is an OutputPath so reuse it directly.
1512 outputFile = outputPath
1513 } else {
1514 // The file is not in the out directory so create an OutputPath into which it can be copied
1515 // and which the following code can use to refer to it.
1516 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1517 ctx.Build(pctx, android.BuildParams{
1518 Rule: android.Cp,
1519 Input: jars[0],
1520 Output: combinedJar,
1521 })
1522 outputFile = combinedJar.OutputPath
1523 }
1524 } else {
1525 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1526 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1527 false, nil, nil)
1528 outputFile = combinedJar.OutputPath
1529 }
1530
1531 // jarjar implementation jar if necessary
1532 if j.expandJarjarRules != nil {
1533 // Transform classes.jar into classes-jarjar.jar
1534 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1535 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1536 outputFile = jarjarFile
1537
1538 // jarjar resource jar if necessary
1539 if j.resourceJar != nil {
1540 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1541 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1542 j.resourceJar = resourceJarJarFile
1543 }
1544
1545 if ctx.Failed() {
1546 return
1547 }
1548 }
1549
Joe Onorato349ae8d2024-02-05 22:46:00 +00001550 // Automatic jarjar rules propagation
1551 if j.repackageJarjarRules != nil {
1552 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-jarjar", jarName).OutputPath
1553 TransformJarJar(ctx, repackagedJarjarFile, outputFile, j.repackageJarjarRules)
1554 outputFile = repackagedJarjarFile
1555 if ctx.Failed() {
1556 return
1557 }
1558 }
1559
Jaewoong Jung26342642021-03-17 15:56:23 -07001560 // Check package restrictions if necessary.
1561 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001562 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001563 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001564
1565 // Create a rule to copy the output jar to another path and add a validate dependency that
1566 // will check that the jar only contains the permitted packages. The new location will become
1567 // the output file of this module.
1568 inputFile := outputFile
1569 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1570 ctx.Build(pctx, android.BuildParams{
1571 Rule: android.Cp,
1572 Input: inputFile,
1573 Output: outputFile,
1574 // Make sure that any dependency on the output file will cause ninja to run the package check
1575 // rule.
1576 Validation: pkgckFile,
1577 })
1578
1579 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001580 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001581
1582 if ctx.Failed() {
1583 return
1584 }
1585 }
1586
1587 j.implementationJarFile = outputFile
1588 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001589 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1590 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1591 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1592 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1593 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1594 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1595 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001596 }
1597
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001598 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1599 specs := j.jacocoModuleToZipCommand(ctx)
1600 if ctx.Failed() {
1601 return
1602 }
1603
Jaewoong Jung26342642021-03-17 15:56:23 -07001604 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001605 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001606 }
1607
1608 // merge implementation jar with resources if necessary
1609 implementationAndResourcesJar := outputFile
1610 if j.resourceJar != nil {
1611 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1612 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1613 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1614 false, nil, nil)
1615 implementationAndResourcesJar = combinedJar
1616 }
1617
1618 j.implementationAndResourcesJar = implementationAndResourcesJar
1619
1620 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001621 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001622 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001623 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001624 if compileDex == nil {
1625 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001626 }
1627 if j.deviceProperties.Hostdex == nil {
1628 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1629 }
1630 }
1631
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001632 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001633 if j.hasCode(ctx) {
1634 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001635 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001636 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1637 }
1638 // Dex compilation
1639 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001640 params := &compileDexParams{
1641 flags: flags,
1642 sdkVersion: j.SdkVersion(ctx),
1643 minSdkVersion: j.MinSdkVersion(ctx),
1644 classesJar: implementationAndResourcesJar,
1645 jarName: jarName,
1646 }
1647 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001648 if ctx.Failed() {
1649 return
1650 }
1651
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 // merge dex jar with resources if necessary
1653 if j.resourceJar != nil {
1654 jars := android.Paths{dexOutputFile, j.resourceJar}
1655 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1656 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1657 false, nil, nil)
1658 if *j.dexProperties.Uncompress_dex {
1659 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001660 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001661 dexOutputFile = combinedAlignedJar
1662 } else {
1663 dexOutputFile = combinedJar
1664 }
1665 }
1666
Paul Duffin4de94502021-05-16 05:21:16 +01001667 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001668
1669 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001670
1671 // Encode hidden API flags in dex file, if needed.
1672 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1673
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001674 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001675
1676 // Dexpreopting
Spandan Dase21a8d42024-01-23 23:56:29 +00001677 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001678
1679 outputFile = dexOutputFile
1680 } else {
1681 // There is no code to compile into a dex jar, make sure the resources are propagated
1682 // to the APK if this is an app.
1683 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001684 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001685 }
1686
1687 if ctx.Failed() {
1688 return
1689 }
1690 } else {
1691 outputFile = implementationAndResourcesJar
1692 }
1693
1694 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001695 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001696 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001697 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001698 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001699 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001700 }
1701 }
1702
1703 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001704 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1705 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001706 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1707 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001708 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001709 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001710 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001711 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001712 j.linter.javaLanguageLevel = flags.javaVersion.String()
1713 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001714 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001715 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1716 j.linter.buildModuleReportZip = true
1717 }
1718 j.linter.lint(ctx)
1719 }
1720
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001721 j.collectTransitiveSrcFiles(ctx, srcFiles)
1722
Jaewoong Jung26342642021-03-17 15:56:23 -07001723 ctx.CheckbuildFile(outputFile)
1724
LaMont Jonesaa005ae2023-12-19 19:01:57 +00001725 android.CollectDependencyAconfigFiles(ctx, &j.mergedAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001726
Colin Cross40213022023-12-13 15:19:49 -08001727 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Joe Onorato349ae8d2024-02-05 22:46:00 +00001729 RepackagedHeaderJars: android.PathsIfNonNil(j.repackagedHeaderJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001730 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1731 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001732 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1733 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1734 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1735 AidlIncludeDirs: j.exportAidlIncludeDirs,
1736 SrcJarArgs: j.srcJarArgs,
1737 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001738 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001739 ExportedPlugins: j.exportedPluginJars,
1740 ExportedPluginClasses: j.exportedPluginClasses,
1741 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1742 JacocoReportClassesFile: j.jacocoReportClassesFile,
Jihoon Kangfe914ed2024-02-12 22:49:21 +00001743 StubsLinkType: j.stubsLinkType,
Jaewoong Jung26342642021-03-17 15:56:23 -07001744 })
1745
1746 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1747 j.outputFile = outputFile.WithoutRel()
1748}
1749
Colin Crossa1ff7c62021-09-17 14:11:52 -07001750func (j *Module) useCompose() bool {
1751 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1752}
1753
Sam Delmerico95d70942023-08-02 18:00:35 -04001754func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1755 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1756 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1757
1758 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001759 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001760 depTag := ctx.OtherModuleDependencyTag(m)
1761
1762 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1763 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1764 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1765 }
1766
1767 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1768 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1769 }
1770 })
1771
1772 directUnconditionalExportedFlags := android.Paths{}
1773 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1774 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1775 if exportUnconditionally {
1776 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1777 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1778 directUnconditionalExportedFlags = proguardFlagsForThisModule
1779 }
1780
1781 return ProguardSpecInfo{
1782 Export_proguard_flags_files: exportUnconditionally,
1783 ProguardFlagsFiles: android.NewDepSet[android.Path](
1784 android.POSTORDER,
1785 proguardFlagsForThisModule,
1786 transitiveProguardFlags,
1787 ),
1788 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1789 android.POSTORDER,
1790 directUnconditionalExportedFlags,
1791 transitiveUnconditionalExportedFlags,
1792 ),
1793 }
1794
1795}
1796
Cole Faust75fffb12021-06-13 15:23:16 -07001797// Returns a copy of the supplied flags, but with all the errorprone-related
1798// fields copied to the regular build's fields.
1799func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1800 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1801
1802 if len(flags.errorProneExtraJavacFlags) > 0 {
1803 if len(flags.javacFlags) > 0 {
1804 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1805 } else {
1806 flags.javacFlags = flags.errorProneExtraJavacFlags
1807 }
1808 }
1809 return flags
1810}
1811
Jaewoong Jung26342642021-03-17 15:56:23 -07001812func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1813 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1814
1815 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001816 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 if idx >= 0 {
1818 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001819 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001820 jarName += strconv.Itoa(idx)
1821 }
1822
1823 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001824 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001825
1826 if ctx.Config().EmitXrefRules() {
1827 extractionFile := android.PathForModuleOut(ctx, kzipName)
1828 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1829 j.kytheFiles = append(j.kytheFiles, extractionFile)
1830 }
1831
Vadim Spivak3c496f02023-06-08 06:14:59 +00001832 if len(flags.processorPath) > 0 {
1833 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1834 }
1835
Jaewoong Jung26342642021-03-17 15:56:23 -07001836 return classes
1837}
1838
1839// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1840// since some of these flags may be used internally.
1841func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1842 for _, flag := range flags {
1843 flag = strings.TrimSpace(flag)
1844
1845 if !strings.HasPrefix(flag, "-") {
1846 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1847 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1848 ctx.PropertyErrorf("kotlincflags",
1849 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1850 } else if inList(flag, config.KotlincIllegalFlags) {
1851 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1852 } else if flag == "-include-runtime" {
1853 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1854 } else {
1855 args := strings.Split(flag, " ")
1856 if args[0] == "-kotlin-home" {
1857 ctx.PropertyErrorf("kotlincflags",
1858 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1859 }
1860 }
1861 }
1862}
1863
1864func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1865 deps deps, flags javaBuilderFlags, jarName string,
Joe Onorato349ae8d2024-02-05 22:46:00 +00001866 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar, jarjarAndDepsRepackagedHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001867
1868 var jars android.Paths
1869 if len(srcFiles) > 0 || len(srcJars) > 0 {
1870 // Compile java sources into turbine.jar.
1871 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1872 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1873 if ctx.Failed() {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001874 return nil, nil, nil
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 }
1876 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001877 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001878 }
1879
1880 jars = append(jars, extraJars...)
1881
1882 // Combine any static header libraries into classes-header.jar. If there is only
1883 // one input jar this step will be skipped.
1884 jars = append(jars, deps.staticHeaderJars...)
1885
1886 // we cannot skip the combine step for now if there is only one jar
1887 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1888 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1889 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1890 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001891 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001892
1893 if j.expandJarjarRules != nil {
1894 // Transform classes.jar into classes-jarjar.jar
1895 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001896 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1897 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001898 if ctx.Failed() {
Joe Onorato349ae8d2024-02-05 22:46:00 +00001899 return nil, nil, nil
Jaewoong Jung26342642021-03-17 15:56:23 -07001900 }
1901 }
1902
Joe Onorato349ae8d2024-02-05 22:46:00 +00001903 if j.repackageJarjarRules != nil {
1904 repackagedJarjarFile := android.PathForModuleOut(ctx, "repackaged-turbine-jarjar", jarName)
1905 TransformJarJar(ctx, repackagedJarjarFile, jarjarAndDepsHeaderJar, j.repackageJarjarRules)
1906 jarjarAndDepsRepackagedHeaderJar = repackagedJarjarFile
1907 if ctx.Failed() {
1908 return nil, nil, nil
1909 }
1910 } else {
1911 jarjarAndDepsRepackagedHeaderJar = jarjarAndDepsHeaderJar
1912 }
1913
1914 return headerJar, jarjarAndDepsHeaderJar, jarjarAndDepsRepackagedHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001915}
1916
1917func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001918 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001919
1920 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1921 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1922
1923 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1924
1925 j.jacocoReportClassesFile = jacocoReportClassesFile
1926
1927 return instrumentedJar
1928}
1929
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001930type providesTransitiveHeaderJars struct {
1931 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001932 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001933 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001934 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001935}
1936
Colin Crossc85750b2022-04-21 12:50:51 -07001937func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001938 return j.transitiveLibsHeaderJars
1939}
1940
Colin Crossc85750b2022-04-21 12:50:51 -07001941func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001942 return j.transitiveStaticLibsHeaderJars
1943}
1944
1945func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1946 directLibs := android.Paths{}
1947 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001948 transitiveLibs := []*android.DepSet[android.Path]{}
1949 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001950 ctx.VisitDirectDeps(func(module android.Module) {
1951 // don't add deps of the prebuilt version of the same library
1952 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1953 return
1954 }
1955
Colin Cross313aa542023-12-13 13:47:44 -08001956 dep, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001957 tag := ctx.OtherModuleDependencyTag(module)
1958 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1959 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1960 directLibs = append(directLibs, dep.HeaderJars...)
1961 } else if tag == staticLibTag {
1962 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001963 } else {
1964 // Don't propagate transitive libs for other kinds of dependencies.
1965 return
1966 }
1967
1968 if dep.TransitiveLibsHeaderJars != nil {
1969 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1970 }
1971 if dep.TransitiveStaticLibsHeaderJars != nil {
1972 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001973 }
1974 })
1975 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1976 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1977}
1978
Jaewoong Jung26342642021-03-17 15:56:23 -07001979func (j *Module) HeaderJars() android.Paths {
1980 if j.headerJarFile == nil {
1981 return nil
1982 }
1983 return android.Paths{j.headerJarFile}
1984}
1985
1986func (j *Module) ImplementationJars() android.Paths {
1987 if j.implementationJarFile == nil {
1988 return nil
1989 }
1990 return android.Paths{j.implementationJarFile}
1991}
1992
Spandan Das59a4a2b2024-01-09 21:35:56 +00001993func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001994 return j.dexJarFile
1995}
1996
1997func (j *Module) DexJarInstallPath() android.Path {
1998 return j.installFile
1999}
2000
2001func (j *Module) ImplementationAndResourcesJars() android.Paths {
2002 if j.implementationAndResourcesJar == nil {
2003 return nil
2004 }
2005 return android.Paths{j.implementationAndResourcesJar}
2006}
2007
2008func (j *Module) AidlIncludeDirs() android.Paths {
2009 // exportAidlIncludeDirs is type android.Paths already
2010 return j.exportAidlIncludeDirs
2011}
2012
2013func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2014 return j.classLoaderContexts
2015}
2016
2017// Collect information for opening IDE project files in java/jdeps.go.
2018func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
2019 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2020 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2021 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2022 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
2023 if j.expandJarjarRules != nil {
2024 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
2025 }
Yikef6282022022-04-13 20:41:01 +08002026 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2027 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002028 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002029}
2030
2031func (j *Module) CompilerDeps() []string {
2032 jdeps := []string{}
2033 jdeps = append(jdeps, j.properties.Libs...)
2034 jdeps = append(jdeps, j.properties.Static_libs...)
2035 return jdeps
2036}
2037
2038func (j *Module) hasCode(ctx android.ModuleContext) bool {
2039 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2040 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2041}
2042
2043// Implements android.ApexModule
2044func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2045 return j.depIsInSameApex(ctx, dep)
2046}
2047
2048// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002049func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002050 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002051 minSdkVersion := j.MinSdkVersion(ctx)
2052 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002053 return fmt.Errorf("min_sdk_version is not specified")
2054 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002055 // If the module is compiling against core (via sdk_version), skip comparison check.
2056 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002057 return nil
2058 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002059 if minSdkVersion.GreaterThan(sdkVersion) {
2060 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002061 }
2062 return nil
2063}
2064
2065func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002066 if j.stem == "" {
2067 panic("Stem() called before stem property was set")
2068 }
2069 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002070}
2071
Jaewoong Jung26342642021-03-17 15:56:23 -07002072func (j *Module) JacocoReportClassesFile() android.Path {
2073 return j.jacocoReportClassesFile
2074}
2075
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002076func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2077 var fromDeps []*android.DepSet[android.Path]
2078 ctx.VisitDirectDeps(func(module android.Module) {
2079 tag := ctx.OtherModuleDependencyTag(module)
2080 if tag == staticLibTag {
Colin Cross313aa542023-12-13 13:47:44 -08002081 depInfo, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002082 if depInfo.TransitiveSrcFiles != nil {
2083 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2084 }
2085 }
2086 })
2087
2088 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2089}
2090
Jaewoong Jung26342642021-03-17 15:56:23 -07002091func (j *Module) IsInstallable() bool {
2092 return Bool(j.properties.Installable)
2093}
2094
2095type sdkLinkType int
2096
2097const (
2098 // TODO(jiyong) rename these for better readability. Make the allowed
2099 // and disallowed link types explicit
2100 // order is important here. See rank()
2101 javaCore sdkLinkType = iota
2102 javaSdk
2103 javaSystem
2104 javaModule
2105 javaSystemServer
2106 javaPlatform
2107)
2108
2109func (lt sdkLinkType) String() string {
2110 switch lt {
2111 case javaCore:
2112 return "core Java API"
2113 case javaSdk:
2114 return "Android API"
2115 case javaSystem:
2116 return "system API"
2117 case javaModule:
2118 return "module API"
2119 case javaSystemServer:
2120 return "system server API"
2121 case javaPlatform:
2122 return "private API"
2123 default:
2124 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2125 }
2126}
2127
2128// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2129// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2130// can't statically depend on modules that use Platform API.
2131func (lt sdkLinkType) rank() int {
2132 return int(lt)
2133}
2134
2135type moduleWithSdkDep interface {
2136 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002137 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002138}
2139
Jiyong Park92315372021-04-02 08:45:46 +09002140func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002141 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002142 case android.SdkCore.DefaultJavaLibraryName(),
2143 "legacy.core.platform.api.stubs",
2144 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002145 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002146 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002147 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002148 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002149 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002150 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002151 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002152 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002153 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002154 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002155 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002156 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002157 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002158 return javaSystem, true
2159 }
2160
2161 if stub, linkType := moduleStubLinkType(name); stub {
2162 return linkType, true
2163 }
2164
Jiyong Park92315372021-04-02 08:45:46 +09002165 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002166 switch ver.Kind {
2167 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002168 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002169 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002170 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002171 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002172 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002173 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002174 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002175 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002176 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002177 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002178 return javaPlatform, false
2179 }
2180
Jiyong Parkf1691d22021-03-29 20:11:58 +09002181 if !ver.Valid() {
2182 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002183 }
2184 return javaSdk, false
2185}
2186
2187// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2188// this module's. See the comment on rank() for details and an example.
2189func (j *Module) checkSdkLinkType(
2190 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2191 if ctx.Host() {
2192 return
2193 }
2194
Jiyong Park92315372021-04-02 08:45:46 +09002195 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002196 if stubs {
2197 return
2198 }
Jiyong Park92315372021-04-02 08:45:46 +09002199 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002200
2201 if myLinkType.rank() < depLinkType.rank() {
2202 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2203 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2204 "property of the source or target module so that target module is built "+
2205 "with the same or smaller API set when compared to the source.",
2206 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2207 }
2208}
2209
2210func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2211 var deps deps
2212
2213 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002214 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002215 if sdkDep.invalidVersion {
2216 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2217 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2218 } else if sdkDep.useFiles {
2219 // sdkDep.jar is actually equivalent to turbine header.jar.
2220 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002221 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002222 deps.aidlPreprocess = sdkDep.aidl
2223 } else {
2224 deps.aidlPreprocess = sdkDep.aidl
2225 }
2226 }
2227
Jiyong Park92315372021-04-02 08:45:46 +09002228 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002229
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002230 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002231 ctx.VisitDirectDeps(func(module android.Module) {
2232 otherName := ctx.OtherModuleName(module)
2233 tag := ctx.OtherModuleDependencyTag(module)
2234
2235 if IsJniDepTag(tag) {
2236 // Handled by AndroidApp.collectAppDeps
2237 return
2238 }
2239 if tag == certificateTag {
2240 // Handled by AndroidApp.collectAppDeps
2241 return
2242 }
2243
2244 if dep, ok := module.(SdkLibraryDependency); ok {
2245 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002246 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002247 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2248 deps.classpath = append(deps.classpath, depHeaderJars...)
2249 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002250 case staticLibTag:
2251 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2252 }
Colin Cross313aa542023-12-13 13:47:44 -08002253 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2254 if sdkLinkType != javaPlatform {
2255 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2256 // dep is a sysprop implementation library, but this module is not linking against
2257 // the platform, so it gets the sysprop public stubs library instead. Replace
2258 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2259 dep = syspropDep.JavaInfo
2260 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002261 }
2262 switch tag {
2263 case bootClasspathTag:
2264 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002265 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002266 if _, ok := module.(*Plugin); ok {
2267 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2268 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002269 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002270 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Joe Onorato349ae8d2024-02-05 22:46:00 +00002271 if len(dep.RepackagedHeaderJars) == 1 && !slices.Contains(dep.HeaderJars, dep.RepackagedHeaderJars[0]) {
2272 deps.classpath = append(deps.classpath, dep.RepackagedHeaderJars...)
2273 deps.dexClasspath = append(deps.dexClasspath, dep.RepackagedHeaderJars...)
2274 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002275 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2276 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2277 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2278 case java9LibTag:
2279 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2280 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002281 if _, ok := module.(*Plugin); ok {
2282 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2283 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002284 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2285 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2286 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2287 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2288 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2289 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2290 // Turbine doesn't run annotation processors, so any module that uses an
2291 // annotation processor that generates API is incompatible with the turbine
2292 // optimization.
2293 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2294 case pluginTag:
2295 if plugin, ok := module.(*Plugin); ok {
2296 if plugin.pluginProperties.Processor_class != nil {
2297 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2298 } else {
2299 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2300 }
2301 // Turbine doesn't run annotation processors, so any module that uses an
2302 // annotation processor that generates API is incompatible with the turbine
2303 // optimization.
2304 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2305 } else {
2306 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2307 }
2308 case errorpronePluginTag:
2309 if _, ok := module.(*Plugin); ok {
2310 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2311 } else {
2312 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2313 }
2314 case exportedPluginTag:
2315 if plugin, ok := module.(*Plugin); ok {
2316 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2317 if plugin.pluginProperties.Processor_class != nil {
2318 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2319 }
2320 // Turbine doesn't run annotation processors, so any module that uses an
2321 // annotation processor that generates API is incompatible with the turbine
2322 // optimization.
2323 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2324 } else {
2325 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2326 }
2327 case kotlinStdlibTag:
2328 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2329 case kotlinAnnotationsTag:
2330 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002331 case kotlinPluginTag:
2332 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002333 case syspropPublicStubDepTag:
2334 // This is a sysprop implementation library, forward the JavaInfoProvider from
2335 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002336 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002337 JavaInfo: dep,
2338 })
2339 }
2340 } else if dep, ok := module.(android.SourceFileProducer); ok {
2341 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002342 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002343 checkProducesJars(ctx, dep)
2344 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002345 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002346 case staticLibTag:
2347 checkProducesJars(ctx, dep)
2348 deps.classpath = append(deps.classpath, dep.Srcs()...)
2349 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2350 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2351 }
2352 } else {
2353 switch tag {
2354 case bootClasspathTag:
2355 // If a system modules dependency has been added to the bootclasspath
2356 // then add its libs to the bootclasspath.
2357 sm := module.(SystemModulesProvider)
2358 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2359
2360 case systemModulesTag:
2361 if deps.systemModules != nil {
2362 panic("Found two system module dependencies")
2363 }
2364 sm := module.(SystemModulesProvider)
2365 outputDir, outputDeps := sm.OutputDirAndDeps()
2366 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002367
2368 case instrumentationForTag:
2369 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 -07002370 }
2371 }
2372
2373 addCLCFromDep(ctx, module, j.classLoaderContexts)
2374 })
2375
2376 return deps
2377}
2378
Joe Onorato349ae8d2024-02-05 22:46:00 +00002379// Provider for jarjar renaming rules.
2380//
2381// Modules can set their jarjar renaming rules with addJarJarRenameRule, and those renamings will be
2382// passed to all rdeps. The typical way that these renamings will NOT be inherited is when a module
2383// links against stubs -- these are not passed through stubs. The classes will remain unrenamed on
2384// classes until a module with jarjar_prefix is reached, and all as yet unrenamed classes will then
2385// be renamed from that module.
2386// TODO: Add another property to suppress the forwarding of
LaMont Jones63683e42024-02-08 14:30:45 -08002387type DependencyUse int
2388
2389const (
2390 RenameUseInvalid DependencyUse = iota
2391 RenameUseInclude
2392 RenameUseExclude
2393)
2394
2395type RenameUseElement struct {
2396 DepName string
2397 RenameUse DependencyUse
2398 Why string // token for determining where in the logic the decision was made.
2399}
2400
Joe Onorato349ae8d2024-02-05 22:46:00 +00002401type JarJarProviderData struct {
2402 // Mapping of class names: original --> renamed. If the value is "", the class will be
2403 // renamed by the next rdep that has the jarjar_prefix attribute (or this module if it has
2404 // attribute). Rdeps of that module will inherit the renaming.
LaMont Jones63683e42024-02-08 14:30:45 -08002405 Rename map[string]string
2406 RenameUse []RenameUseElement
Joe Onorato349ae8d2024-02-05 22:46:00 +00002407}
2408
2409func (this JarJarProviderData) GetDebugString() string {
2410 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002411 for _, k := range android.SortedKeys(this.Rename) {
2412 v := this.Rename[k]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002413 if strings.Contains(k, "android.companion.virtual.flags.FakeFeatureFlagsImpl") {
2414 result += k + "--&gt;" + v + ";"
2415 }
2416 }
2417 return result
2418}
2419
2420var JarJarProvider = blueprint.NewProvider[JarJarProviderData]()
2421
2422var overridableJarJarPrefix = "com.android.internal.hidden_from_bootclasspath"
2423
2424func init() {
2425 android.SetJarJarPrefixHandler(mergeJarJarPrefixes)
2426}
2427
2428// BaseJarJarProviderData contains information that will propagate across dependencies regardless of
2429// whether they are java modules or not.
2430type BaseJarJarProviderData struct {
2431 JarJarProviderData JarJarProviderData
2432}
2433
2434func (this BaseJarJarProviderData) GetDebugString() string {
2435 return this.JarJarProviderData.GetDebugString()
2436}
2437
2438var BaseJarJarProvider = blueprint.NewProvider[BaseJarJarProviderData]()
2439
2440// mergeJarJarPrefixes is called immediately before module.GenerateAndroidBuildActions is called.
2441// Since there won't be a JarJarProvider, we create the BaseJarJarProvider if any of our deps have
2442// either JarJarProvider or BaseJarJarProvider.
2443func mergeJarJarPrefixes(ctx android.ModuleContext) {
2444 mod := ctx.Module()
2445 // Explicitly avoid propagating into some module types.
2446 switch reflect.TypeOf(mod).String() {
2447 case "*java.Droidstubs":
2448 return
2449 }
2450 jarJarData := collectDirectDepsProviders(ctx)
2451 if jarJarData != nil {
2452 providerData := BaseJarJarProviderData{
2453 JarJarProviderData: *jarJarData,
2454 }
2455 android.SetProvider(ctx, BaseJarJarProvider, providerData)
2456 }
2457
2458}
2459
2460// Add a jarjar renaming rule to this module, to be inherited to all dependent modules.
2461func (module *Module) addJarJarRenameRule(original string, renamed string) {
2462 if module.jarjarRenameRules == nil {
2463 module.jarjarRenameRules = make(map[string]string)
2464 }
2465 module.jarjarRenameRules[original] = renamed
2466}
2467
2468func collectDirectDepsProviders(ctx android.ModuleContext) (result *JarJarProviderData) {
2469 // Gather repackage information from deps
2470 // If the dep jas a JarJarProvider, it is used. Otherwise, any BaseJarJarProvider is used.
LaMont Jones63683e42024-02-08 14:30:45 -08002471
2472 module := ctx.Module()
2473 moduleName := module.Name()
2474
Joe Onorato349ae8d2024-02-05 22:46:00 +00002475 ctx.VisitDirectDepsIgnoreBlueprint(func(m android.Module) {
LaMont Jones63683e42024-02-08 14:30:45 -08002476 tag := ctx.OtherModuleDependencyTag(m)
2477 // This logic mirrors that in (*Module).collectDeps above. There are several places
2478 // where we explicitly return RenameUseExclude, even though it is the default, to
2479 // indicate that it has been verified to be the case.
2480 //
2481 // Note well: there are probably cases that are getting to the unconditional return
2482 // and are therefore wrong.
2483 shouldIncludeRenames := func() (DependencyUse, string) {
2484 if moduleName == m.Name() {
2485 return RenameUseInclude, "name" // If we have the same module name, include the renames.
2486 }
2487 if sc, ok := module.(android.SdkContext); ok {
2488 if ctx.Device() {
2489 sdkDep := decodeSdkDep(ctx, sc)
2490 if !sdkDep.invalidVersion && sdkDep.useFiles {
2491 return RenameUseExclude, "useFiles"
Joe Onorato349ae8d2024-02-05 22:46:00 +00002492 }
2493 }
LaMont Jones63683e42024-02-08 14:30:45 -08002494 }
2495 if IsJniDepTag(tag) || tag == certificateTag || tag == proguardRaiseTag {
2496 return RenameUseExclude, "tags"
2497 }
2498 if _, ok := m.(SdkLibraryDependency); ok {
2499 switch tag {
2500 case sdkLibTag, libTag:
2501 return RenameUseExclude, "sdklibdep" // matches collectDeps()
2502 }
2503 return RenameUseInvalid, "sdklibdep" // dep is not used in collectDeps()
2504 } else if ji, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
2505 switch ji.StubsLinkType {
2506 case Stubs:
2507 return RenameUseExclude, "info"
2508 case Implementation:
2509 return RenameUseInclude, "info"
2510 default:
2511 //fmt.Printf("LJ: %v -> %v StubsLinkType unknown\n", module, m)
2512 // Fall through to the heuristic logic.
2513 }
2514 switch reflect.TypeOf(m).String() {
2515 case "*java.GeneratedJavaLibraryModule":
2516 // Probably a java_aconfig_library module.
2517 // TODO: make this check better.
2518 return RenameUseInclude, "reflect"
2519 }
2520 switch tag {
2521 case bootClasspathTag:
2522 return RenameUseExclude, "tagswitch"
2523 case sdkLibTag, libTag, instrumentationForTag:
2524 return RenameUseInclude, "tagswitch"
2525 case java9LibTag:
2526 return RenameUseExclude, "tagswitch"
2527 case staticLibTag:
2528 return RenameUseInclude, "tagswitch"
2529 case pluginTag:
2530 return RenameUseInclude, "tagswitch"
2531 case errorpronePluginTag:
2532 return RenameUseInclude, "tagswitch"
2533 case exportedPluginTag:
2534 return RenameUseInclude, "tagswitch"
2535 case kotlinStdlibTag, kotlinAnnotationsTag:
2536 return RenameUseExclude, "tagswitch"
2537 case kotlinPluginTag:
2538 return RenameUseInclude, "tagswitch"
2539 default:
2540 return RenameUseExclude, "tagswitch"
2541 }
2542 } else if _, ok := m.(android.SourceFileProducer); ok {
2543 switch tag {
2544 case sdkLibTag, libTag, staticLibTag:
2545 return RenameUseInclude, "srcfile"
2546 default:
2547 return RenameUseExclude, "srcfile"
2548 }
Jihoon Kang03d014f2024-02-16 22:22:18 +00002549 } else if _, ok := android.OtherModuleProvider(ctx, m, aconfig.CodegenInfoProvider); ok {
2550 return RenameUseInclude, "aconfig_declarations_group"
LaMont Jones63683e42024-02-08 14:30:45 -08002551 } else {
2552 switch tag {
2553 case bootClasspathTag:
2554 return RenameUseExclude, "else"
2555 case systemModulesTag:
2556 return RenameUseInclude, "else"
2557 }
2558 }
2559 // If we got here, choose the safer option, which may lead to a build failure, rather
2560 // than runtime failures on the device.
2561 return RenameUseExclude, "end"
2562 }
2563
2564 if result == nil {
2565 result = &JarJarProviderData{
2566 Rename: make(map[string]string),
2567 RenameUse: make([]RenameUseElement, 0),
2568 }
2569 }
2570 how, why := shouldIncludeRenames()
2571 result.RenameUse = append(result.RenameUse, RenameUseElement{DepName: m.Name(), RenameUse: how, Why: why})
2572 if how != RenameUseInclude {
2573 // Nothing to merge.
2574 return
2575 }
2576
2577 merge := func(theirs *JarJarProviderData) {
2578 for orig, renamed := range theirs.Rename {
Joe Onorato349ae8d2024-02-05 22:46:00 +00002579 if preexisting, exists := (*result).Rename[orig]; !exists || preexisting == "" {
2580 result.Rename[orig] = renamed
2581 } else if preexisting != "" && renamed != "" && preexisting != renamed {
2582 if strings.HasPrefix(preexisting, overridableJarJarPrefix) {
2583 result.Rename[orig] = renamed
2584 } else if !strings.HasPrefix(renamed, overridableJarJarPrefix) {
2585 ctx.ModuleErrorf("1. Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting, ctx.ModuleName(), m.Name())
2586 continue
2587 }
2588 }
2589 }
2590 }
2591 if theirs, ok := android.OtherModuleProvider(ctx, m, JarJarProvider); ok {
2592 merge(&theirs)
2593 } else if theirs, ok := android.OtherModuleProvider(ctx, m, BaseJarJarProvider); ok {
2594 // TODO: if every java.Module should have a JarJarProvider, and we find only the
2595 // BaseJarJarProvider, then there is a bug. Consider seeing if m can be cast
2596 // to java.Module.
2597 merge(&theirs.JarJarProviderData)
2598 }
2599 })
2600 return
2601}
2602
2603func (this Module) GetDebugString() string {
2604 return "sdk_version=" + proptools.String(this.deviceProperties.Sdk_version)
2605}
2606
2607// Merge the jarjar rules we inherit from our dependencies, any that have been added directly to
2608// us, and if it's been set, apply the jarjar_prefix property to rename them.
2609func (module *Module) collectJarJarRules(ctx android.ModuleContext) *JarJarProviderData {
2610 // Gather repackage information from deps
2611 result := collectDirectDepsProviders(ctx)
2612
2613 // Update that with entries we've stored for ourself
2614 for orig, renamed := range module.jarjarRenameRules {
2615 if result == nil {
2616 result = &JarJarProviderData{
2617 Rename: make(map[string]string),
2618 }
2619 }
2620 if renamed != "" {
2621 if preexisting, exists := (*result).Rename[orig]; exists && preexisting != renamed {
2622 ctx.ModuleErrorf("Conflicting jarjar rules inherited for class: %s (%s and %s)", orig, renamed, preexisting)
2623 continue
2624 }
2625 }
2626 (*result).Rename[orig] = renamed
2627 }
2628
2629 // If there are no renamings, then jarjar_prefix does nothing, so skip the extra work.
2630 if result == nil {
2631 return nil
2632 }
2633
2634 // If they've given us a jarjar_prefix property, then we will use that to rename any classes
2635 // that have not yet been renamed.
2636 prefix := proptools.String(module.properties.Jarjar_prefix)
2637 if prefix != "" {
2638 if prefix[0] == '.' {
2639 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not start with '.'")
2640 return nil
2641 }
2642 if prefix[len(prefix)-1] == '.' {
2643 ctx.PropertyErrorf("jarjar_prefix", "jarjar_prefix can not end with '.'")
2644 return nil
2645 }
2646
2647 var updated map[string]string
2648 for orig, renamed := range (*result).Rename {
2649 if renamed == "" {
2650 if updated == nil {
2651 updated = make(map[string]string)
2652 }
2653 updated[orig] = prefix + "." + orig
2654 }
2655 }
2656 for orig, renamed := range updated {
2657 (*result).Rename[orig] = renamed
2658 }
2659 }
2660
2661 return result
2662}
2663
2664// Get the jarjar rule text for a given provider for the fully resolved rules. Classes that map
2665// to "" won't be in this list because they shouldn't be renamed yet.
2666func getJarJarRuleText(provider *JarJarProviderData) string {
2667 result := ""
Inseob Kim3c0c9d72024-02-28 14:28:59 +09002668 for _, orig := range android.SortedKeys(provider.Rename) {
2669 renamed := provider.Rename[orig]
Joe Onorato349ae8d2024-02-05 22:46:00 +00002670 if renamed != "" {
2671 result += "rule " + orig + " " + renamed + "\n"
2672 }
2673 }
2674 return result
2675}
2676
Jaewoong Jung26342642021-03-17 15:56:23 -07002677func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2678 deps.processorPath = append(deps.processorPath, pluginJars...)
2679 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2680}
2681
2682// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2683// this interface.
2684type ProvidesUsesLib interface {
2685 ProvidesUsesLib() *string
2686}
2687
2688func (j *Module) ProvidesUsesLib() *string {
2689 return j.usesLibraryProperties.Provides_uses_lib
2690}
satayev1c564cc2021-05-25 19:50:30 +01002691
2692type ModuleWithStem interface {
2693 Stem() string
2694}
2695
2696var _ ModuleWithStem = (*Module)(nil)