blob: 06e17c9025459d55f3a28fda4c58c5832eadff1a [file] [log] [blame]
Paul Duffinc6bb7cf2021-04-08 17:49:27 +01001// Copyright (C) 2021 The Android Open Source Project
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 (
Paul Duffin7487a7a2021-05-19 09:36:09 +010018 "fmt"
Paul Duffindfa10832021-05-13 17:31:51 +010019 "strings"
20
Paul Duffinc6bb7cf2021-04-08 17:49:27 +010021 "android/soong/android"
Spandan Das64c9e0c2023-12-20 20:13:34 +000022 "android/soong/dexpreopt"
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +010023
Paul Duffin9b381ef2021-04-08 23:01:37 +010024 "github.com/google/blueprint"
Paul Duffinc6bb7cf2021-04-08 17:49:27 +010025)
26
27// Contains support for processing hiddenAPI in a modular fashion.
28
Paul Duffin31fad802021-06-18 18:14:25 +010029// HiddenAPIScope encapsulates all the information that the hidden API processing needs about API
30// scopes, i.e. what is called android.SdkKind and apiScope. It does not just use those as they do
31// not provide the information needed by hidden API processing.
32type HiddenAPIScope struct {
33 // The name of the scope, used for debug purposes.
34 name string
35
36 // The corresponding android.SdkKind, used for retrieving paths from java_sdk_library* modules.
37 sdkKind android.SdkKind
38
39 // The option needed to passed to "hiddenapi list".
40 hiddenAPIListOption string
Paul Duffin5cca7c42021-05-26 10:16:01 +010041
Jihoon Kang244d42a2023-10-06 16:54:58 +000042 // The names of the source stub library modules that contain the API provided by the platform,
Paul Duffin5cca7c42021-05-26 10:16:01 +010043 // i.e. by modules that are not in an APEX.
44 nonUpdatableSourceModule string
45
Jihoon Kang244d42a2023-10-06 16:54:58 +000046 // The names of from-text stub library modules that contain the API provided by the platform,
47 // i.e. by modules that are not in an APEX.
48 nonUpdatableFromTextModule string
49
Paul Duffin5cca7c42021-05-26 10:16:01 +010050 // The names of the prebuilt stub library modules that contain the API provided by the platform,
51 // i.e. by modules that are not in an APEX.
52 nonUpdatablePrebuiltModule string
Paul Duffin31fad802021-06-18 18:14:25 +010053}
54
55// initHiddenAPIScope initializes the scope.
56func initHiddenAPIScope(apiScope *HiddenAPIScope) *HiddenAPIScope {
Paul Duffin5cca7c42021-05-26 10:16:01 +010057 sdkKind := apiScope.sdkKind
58 // The platform does not provide a core platform API.
59 if sdkKind != android.SdkCorePlatform {
60 kindAsString := sdkKind.String()
61 var insert string
62 if sdkKind == android.SdkPublic {
63 insert = ""
64 } else {
65 insert = "." + strings.ReplaceAll(kindAsString, "-", "_")
66 }
67
68 nonUpdatableModule := "android-non-updatable"
69
70 // Construct the name of the android-non-updatable source module for this scope.
71 apiScope.nonUpdatableSourceModule = fmt.Sprintf("%s.stubs%s", nonUpdatableModule, insert)
72
73 prebuiltModuleName := func(name string, kind string) string {
74 return fmt.Sprintf("sdk_%s_current_%s", kind, name)
75 }
76
77 // Construct the name of the android-non-updatable prebuilt module for this scope.
78 apiScope.nonUpdatablePrebuiltModule = prebuiltModuleName(nonUpdatableModule, kindAsString)
79 }
80
Paul Duffin31fad802021-06-18 18:14:25 +010081 return apiScope
82}
83
Paul Duffin5cca7c42021-05-26 10:16:01 +010084// android-non-updatable takes the name of a module and returns a possibly scope specific name of
85// the module.
86func (l *HiddenAPIScope) scopeSpecificStubModule(ctx android.BaseModuleContext, name string) string {
87 // The android-non-updatable is not a java_sdk_library but there are separate stub libraries for
88 // each scope.
89 // TODO(b/192067200): Remove special handling of android-non-updatable.
90 if name == "android-non-updatable" {
91 if ctx.Config().AlwaysUsePrebuiltSdks() {
92 return l.nonUpdatablePrebuiltModule
93 } else {
Jihoon Kang244d42a2023-10-06 16:54:58 +000094 if l.nonUpdatableFromTextModule != "" && ctx.Config().BuildFromTextStub() {
95 return l.nonUpdatableFromTextModule
96 }
Paul Duffin5cca7c42021-05-26 10:16:01 +010097 return l.nonUpdatableSourceModule
98 }
99 } else {
100 // Assume that the module is either a java_sdk_library (or equivalent) and so will provide
101 // separate stub jars for each scope or is a java_library (or equivalent) in which case it will
102 // have the same stub jar for each scope.
103 return name
104 }
105}
106
Paul Duffin31fad802021-06-18 18:14:25 +0100107func (l *HiddenAPIScope) String() string {
108 return fmt.Sprintf("HiddenAPIScope{%s}", l.name)
109}
110
111var (
112 PublicHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
113 name: "public",
114 sdkKind: android.SdkPublic,
115 hiddenAPIListOption: "--public-stub-classpath",
116 })
117 SystemHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
118 name: "system",
119 sdkKind: android.SdkSystem,
120 hiddenAPIListOption: "--system-stub-classpath",
121 })
122 TestHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
123 name: "test",
124 sdkKind: android.SdkTest,
125 hiddenAPIListOption: "--test-stub-classpath",
126 })
Paul Duffinb51db2e2021-06-21 14:08:08 +0100127 ModuleLibHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
Jihoon Kang244d42a2023-10-06 16:54:58 +0000128 name: "module-lib",
129 sdkKind: android.SdkModule,
130 nonUpdatableFromTextModule: "android-non-updatable.stubs.test_module_lib",
Paul Duffinb51db2e2021-06-21 14:08:08 +0100131 })
Paul Duffin31fad802021-06-18 18:14:25 +0100132 CorePlatformHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
133 name: "core-platform",
134 sdkKind: android.SdkCorePlatform,
135 hiddenAPIListOption: "--core-platform-stub-classpath",
136 })
137
138 // hiddenAPIRelevantSdkKinds lists all the android.SdkKind instances that are needed by the hidden
139 // API processing.
140 //
141 // These are roughly in order from narrowest API surface to widest. Widest means the API stubs
142 // with the biggest API surface, e.g. test is wider than system is wider than public.
143 //
Paul Duffinb51db2e2021-06-21 14:08:08 +0100144 // Core platform is considered wider than system/module-lib because those modules that provide
145 // core platform APIs either do not have any system/module-lib APIs at all, or if they do it is
146 // because the core platform API is being converted to system/module-lib APIs. In either case the
147 // system/module-lib APIs are subsets of the core platform API.
Paul Duffin31fad802021-06-18 18:14:25 +0100148 //
149 // This is not strictly in order from narrowest to widest as the Test API is wider than system but
Paul Duffinb51db2e2021-06-21 14:08:08 +0100150 // is neither wider or narrower than the module-lib or core platform APIs. However, this works
151 // well enough at the moment.
Paul Duffin31fad802021-06-18 18:14:25 +0100152 // TODO(b/191644675): Correctly reflect the sub/superset relationships between APIs.
153 hiddenAPIScopes = []*HiddenAPIScope{
154 PublicHiddenAPIScope,
155 SystemHiddenAPIScope,
156 TestHiddenAPIScope,
Paul Duffinb51db2e2021-06-21 14:08:08 +0100157 ModuleLibHiddenAPIScope,
Paul Duffin31fad802021-06-18 18:14:25 +0100158 CorePlatformHiddenAPIScope,
159 }
160
161 // The HiddenAPIScope instances that are supported by a java_sdk_library.
162 //
163 // CorePlatformHiddenAPIScope is not used as the java_sdk_library does not have special support
164 // for core_platform API, instead it is implemented as a customized form of PublicHiddenAPIScope.
165 hiddenAPISdkLibrarySupportedScopes = []*HiddenAPIScope{
166 PublicHiddenAPIScope,
167 SystemHiddenAPIScope,
168 TestHiddenAPIScope,
Paul Duffinb51db2e2021-06-21 14:08:08 +0100169 ModuleLibHiddenAPIScope,
Paul Duffin31fad802021-06-18 18:14:25 +0100170 }
171
172 // The HiddenAPIScope instances that are supported by the `hiddenapi list`.
173 hiddenAPIFlagScopes = []*HiddenAPIScope{
174 PublicHiddenAPIScope,
175 SystemHiddenAPIScope,
176 TestHiddenAPIScope,
177 CorePlatformHiddenAPIScope,
178 }
179)
180
Paul Duffin74431d52021-04-21 14:10:42 +0100181type hiddenAPIStubsDependencyTag struct {
182 blueprint.BaseDependencyTag
Paul Duffin31fad802021-06-18 18:14:25 +0100183
184 // The api scope for which this dependency was added.
185 apiScope *HiddenAPIScope
Paul Duffin5cca7c42021-05-26 10:16:01 +0100186
187 // Indicates that the dependency is not for an API provided by the current bootclasspath fragment
188 // but is an additional API provided by a module that is not part of the current bootclasspath
189 // fragment.
190 fromAdditionalDependency bool
Paul Duffin74431d52021-04-21 14:10:42 +0100191}
192
193func (b hiddenAPIStubsDependencyTag) ExcludeFromApexContents() {
194}
195
196func (b hiddenAPIStubsDependencyTag) ReplaceSourceWithPrebuilt() bool {
197 return false
198}
199
Paul Duffin976b0e52021-04-27 23:20:26 +0100200func (b hiddenAPIStubsDependencyTag) SdkMemberType(child android.Module) android.SdkMemberType {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100201 // Do not add additional dependencies to the sdk.
202 if b.fromAdditionalDependency {
203 return nil
204 }
205
Paul Duffin976b0e52021-04-27 23:20:26 +0100206 // If the module is a java_sdk_library then treat it as if it was specific in the java_sdk_libs
207 // property, otherwise treat if it was specified in the java_header_libs property.
208 if javaSdkLibrarySdkMemberType.IsInstance(child) {
209 return javaSdkLibrarySdkMemberType
210 }
211
212 return javaHeaderLibsSdkMemberType
213}
214
215func (b hiddenAPIStubsDependencyTag) ExportMember() bool {
216 // Export the module added via this dependency tag from the sdk.
217 return true
218}
219
Paul Duffin74431d52021-04-21 14:10:42 +0100220// Avoid having to make stubs content explicitly visible to dependent modules.
221//
222// This is a temporary workaround to make it easier to migrate to bootclasspath_fragment modules
223// with proper dependencies.
224// TODO(b/177892522): Remove this and add needed visibility.
225func (b hiddenAPIStubsDependencyTag) ExcludeFromVisibilityEnforcement() {
226}
227
228var _ android.ExcludeFromVisibilityEnforcementTag = hiddenAPIStubsDependencyTag{}
229var _ android.ReplaceSourceWithPrebuilt = hiddenAPIStubsDependencyTag{}
230var _ android.ExcludeFromApexContentsTag = hiddenAPIStubsDependencyTag{}
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100231var _ android.SdkMemberDependencyTag = hiddenAPIStubsDependencyTag{}
Paul Duffin74431d52021-04-21 14:10:42 +0100232
Paul Duffin74431d52021-04-21 14:10:42 +0100233// hiddenAPIComputeMonolithicStubLibModules computes the set of module names that provide stubs
234// needed to produce the hidden API monolithic stub flags file.
Paul Duffin31fad802021-06-18 18:14:25 +0100235func hiddenAPIComputeMonolithicStubLibModules(config android.Config) map[*HiddenAPIScope][]string {
Paul Duffin74431d52021-04-21 14:10:42 +0100236 var publicStubModules []string
237 var systemStubModules []string
238 var testStubModules []string
239 var corePlatformStubModules []string
240
241 if config.AlwaysUsePrebuiltSdks() {
242 // Build configuration mandates using prebuilt stub modules
243 publicStubModules = append(publicStubModules, "sdk_public_current_android")
244 systemStubModules = append(systemStubModules, "sdk_system_current_android")
245 testStubModules = append(testStubModules, "sdk_test_current_android")
246 } else {
247 // Use stub modules built from source
Jihoon Kangbd093452023-12-26 19:08:01 +0000248 if config.ReleaseHiddenApiExportableStubs() {
249 publicStubModules = append(publicStubModules, android.SdkPublic.DefaultExportableJavaLibraryName())
250 systemStubModules = append(systemStubModules, android.SdkSystem.DefaultExportableJavaLibraryName())
251 testStubModules = append(testStubModules, android.SdkTest.DefaultExportableJavaLibraryName())
252 } else {
253 publicStubModules = append(publicStubModules, android.SdkPublic.DefaultJavaLibraryName())
254 systemStubModules = append(systemStubModules, android.SdkSystem.DefaultJavaLibraryName())
255 testStubModules = append(testStubModules, android.SdkTest.DefaultJavaLibraryName())
256 }
Paul Duffin74431d52021-04-21 14:10:42 +0100257 }
258 // We do not have prebuilts of the core platform api yet
Jihoon Kangbd093452023-12-26 19:08:01 +0000259 if config.ReleaseHiddenApiExportableStubs() {
260 corePlatformStubModules = append(corePlatformStubModules, "legacy.core.platform.api.stubs.exportable")
261 } else {
262 corePlatformStubModules = append(corePlatformStubModules, "legacy.core.platform.api.stubs")
263 }
Paul Duffin74431d52021-04-21 14:10:42 +0100264
265 // Allow products to define their own stubs for custom product jars that apps can use.
266 publicStubModules = append(publicStubModules, config.ProductHiddenAPIStubs()...)
267 systemStubModules = append(systemStubModules, config.ProductHiddenAPIStubsSystem()...)
268 testStubModules = append(testStubModules, config.ProductHiddenAPIStubsTest()...)
269 if config.IsEnvTrue("EMMA_INSTRUMENT") {
Paul Duffin098c8782021-05-14 10:45:25 +0100270 // Add jacoco-stubs to public, system and test. It doesn't make any real difference as public
271 // allows everyone access but it is needed to ensure consistent flags between the
272 // bootclasspath fragment generated flags and the platform_bootclasspath generated flags.
Paul Duffin74431d52021-04-21 14:10:42 +0100273 publicStubModules = append(publicStubModules, "jacoco-stubs")
Paul Duffin098c8782021-05-14 10:45:25 +0100274 systemStubModules = append(systemStubModules, "jacoco-stubs")
275 testStubModules = append(testStubModules, "jacoco-stubs")
Paul Duffin74431d52021-04-21 14:10:42 +0100276 }
277
Paul Duffin31fad802021-06-18 18:14:25 +0100278 m := map[*HiddenAPIScope][]string{}
279 m[PublicHiddenAPIScope] = publicStubModules
280 m[SystemHiddenAPIScope] = systemStubModules
281 m[TestHiddenAPIScope] = testStubModules
282 m[CorePlatformHiddenAPIScope] = corePlatformStubModules
Paul Duffin74431d52021-04-21 14:10:42 +0100283 return m
284}
285
286// hiddenAPIAddStubLibDependencies adds dependencies onto the modules specified in
Paul Duffin31fad802021-06-18 18:14:25 +0100287// apiScopeToStubLibModules. It adds them in a well known order and uses a HiddenAPIScope specific
288// tag to identify the source of the dependency.
289func hiddenAPIAddStubLibDependencies(ctx android.BottomUpMutatorContext, apiScopeToStubLibModules map[*HiddenAPIScope][]string) {
Paul Duffin74431d52021-04-21 14:10:42 +0100290 module := ctx.Module()
Paul Duffin31fad802021-06-18 18:14:25 +0100291 for _, apiScope := range hiddenAPIScopes {
292 modules := apiScopeToStubLibModules[apiScope]
293 ctx.AddDependency(module, hiddenAPIStubsDependencyTag{apiScope: apiScope}, modules...)
Paul Duffin74431d52021-04-21 14:10:42 +0100294 }
295}
296
Paul Duffin74431d52021-04-21 14:10:42 +0100297// hiddenAPIRetrieveDexJarBuildPath retrieves the DexJarBuildPath from the specified module, if
298// available, or reports an error.
Paul Duffin10931582021-04-25 10:13:54 +0100299func hiddenAPIRetrieveDexJarBuildPath(ctx android.ModuleContext, module android.Module, kind android.SdkKind) android.Path {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100300 var dexJar OptionalDexJarPath
Paul Duffin10931582021-04-25 10:13:54 +0100301 if sdkLibrary, ok := module.(SdkLibraryDependency); ok {
Jihoon Kangbd093452023-12-26 19:08:01 +0000302 if ctx.Config().ReleaseHiddenApiExportableStubs() {
303 dexJar = sdkLibrary.SdkApiExportableStubDexJar(ctx, kind)
304 } else {
305 dexJar = sdkLibrary.SdkApiStubDexJar(ctx, kind)
306 }
307
Paul Duffin10931582021-04-25 10:13:54 +0100308 } else if j, ok := module.(UsesLibraryDependency); ok {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000309 dexJar = j.DexJarBuildPath(ctx)
Paul Duffin74431d52021-04-21 14:10:42 +0100310 } else {
311 ctx.ModuleErrorf("dependency %s of module type %s does not support providing a dex jar", module, ctx.OtherModuleType(module))
Paul Duffin10931582021-04-25 10:13:54 +0100312 return nil
Paul Duffin74431d52021-04-21 14:10:42 +0100313 }
Paul Duffin10931582021-04-25 10:13:54 +0100314
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100315 if !dexJar.Valid() {
316 ctx.ModuleErrorf("dependency %s does not provide a dex jar: %s", module, dexJar.InvalidReason())
317 return nil
Paul Duffin10931582021-04-25 10:13:54 +0100318 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100319 return dexJar.Path()
Paul Duffin74431d52021-04-21 14:10:42 +0100320}
321
Paul Duffinbd88c882022-04-07 23:32:19 +0100322// HIDDENAPI_STUB_FLAGS_IMPL_FLAGS is the set of flags that identify implementation only signatures,
323// i.e. those signatures that are not part of any API (including the hidden API).
324var HIDDENAPI_STUB_FLAGS_IMPL_FLAGS = []string{}
325
326var HIDDENAPI_FLAGS_CSV_IMPL_FLAGS = []string{"blocked"}
327
Paul Duffin4539a372021-06-23 23:20:43 +0100328// buildRuleToGenerateHiddenAPIStubFlagsFile creates a rule to create a hidden API stub flags file.
Paul Duffin74431d52021-04-21 14:10:42 +0100329//
330// The rule is initialized but not built so that the caller can modify it and select an appropriate
331// name.
Paul Duffin67b9d612021-07-21 17:38:47 +0100332func buildRuleToGenerateHiddenAPIStubFlagsFile(ctx android.BuilderContext, name, desc string, outputPath android.WritablePath, bootDexJars android.Paths, input HiddenAPIFlagInput, stubFlagSubsets SignatureCsvSubsets) {
Paul Duffin74431d52021-04-21 14:10:42 +0100333 // Singleton rule which applies hiddenapi on all boot class path dex files.
334 rule := android.NewRuleBuilder(pctx, ctx)
335
336 tempPath := tempPathForRestat(ctx, outputPath)
337
Paul Duffinf1b358c2021-05-17 07:38:47 +0100338 // Find the widest API stubs provided by the fragments on which this depends, if any.
Paul Duffind2b1e0c2021-06-27 20:53:39 +0100339 dependencyStubDexJars := input.DependencyStubDexJarsByScope.StubDexJarsForWidestAPIScope()
Paul Duffin5cca7c42021-05-26 10:16:01 +0100340
341 // Add widest API stubs from the additional dependencies of this, if any.
Paul Duffind2b1e0c2021-06-27 20:53:39 +0100342 dependencyStubDexJars = append(dependencyStubDexJars, input.AdditionalStubDexJarsByScope.StubDexJarsForWidestAPIScope()...)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100343
Paul Duffin74431d52021-04-21 14:10:42 +0100344 command := rule.Command().
345 Tool(ctx.Config().HostToolPath(ctx, "hiddenapi")).
346 Text("list").
Paul Duffinf1b358c2021-05-17 07:38:47 +0100347 FlagForEachInput("--dependency-stub-dex=", dependencyStubDexJars).
Paul Duffin74431d52021-04-21 14:10:42 +0100348 FlagForEachInput("--boot-dex=", bootDexJars)
349
Paul Duffin156b5d32021-06-24 23:06:52 +0100350 // If no module stub flags paths are provided then this must be being called for a
351 // bootclasspath_fragment and not the whole platform_bootclasspath.
Paul Duffin67b9d612021-07-21 17:38:47 +0100352 if stubFlagSubsets == nil {
Paul Duffin156b5d32021-06-24 23:06:52 +0100353 // This is being run on a fragment of the bootclasspath.
354 command.Flag("--fragment")
355 }
356
Paul Duffin31fad802021-06-18 18:14:25 +0100357 // Iterate over the api scopes in a fixed order.
358 for _, apiScope := range hiddenAPIFlagScopes {
359 // Merge in the stub dex jar paths for this api scope from the fragments on which it depends.
360 // They will be needed to resolve dependencies from this fragment's stubs to classes in the
361 // other fragment's APIs.
362 var paths android.Paths
Paul Duffin280a31a2021-06-27 20:28:29 +0100363 paths = append(paths, input.DependencyStubDexJarsByScope.StubDexJarsForScope(apiScope)...)
364 paths = append(paths, input.AdditionalStubDexJarsByScope.StubDexJarsForScope(apiScope)...)
365 paths = append(paths, input.StubDexJarsByScope.StubDexJarsForScope(apiScope)...)
Paul Duffin74431d52021-04-21 14:10:42 +0100366 if len(paths) > 0 {
Paul Duffin31fad802021-06-18 18:14:25 +0100367 option := apiScope.hiddenAPIListOption
368 command.FlagWithInputList(option+"=", paths, ":")
Paul Duffin74431d52021-04-21 14:10:42 +0100369 }
370 }
371
372 // Add the output path.
373 command.FlagWithOutput("--out-api-flags=", tempPath)
374
Paul Duffin2e880972021-06-23 23:29:09 +0100375 // If there are stub flag files that have been generated by fragments on which this depends then
376 // use them to validate the stub flag file generated by the rules created by this method.
Alyssa Ketpreechasawat7daf2782023-11-01 13:58:39 +0000377 if !ctx.Config().DisableVerifyOverlaps() && len(stubFlagSubsets) > 0 {
Paul Duffinbd88c882022-04-07 23:32:19 +0100378 validFile := buildRuleValidateOverlappingCsvFiles(ctx, name, desc, outputPath, stubFlagSubsets,
379 HIDDENAPI_STUB_FLAGS_IMPL_FLAGS)
Paul Duffin2e880972021-06-23 23:29:09 +0100380
381 // Add the file that indicates that the file generated by this is valid.
382 //
383 // This will cause the validation rule above to be run any time that the output of this rule
384 // changes but the validation will run in parallel with other rules that depend on this file.
385 command.Validation(validFile)
386 }
387
Paul Duffin74431d52021-04-21 14:10:42 +0100388 commitChangeForRestat(rule, tempPath, outputPath)
Paul Duffin4539a372021-06-23 23:20:43 +0100389
390 rule.Build(name, desc)
Paul Duffin74431d52021-04-21 14:10:42 +0100391}
392
Paul Duffin46169772021-04-14 15:01:56 +0100393// HiddenAPIFlagFileProperties contains paths to the flag files that can be used to augment the
394// information obtained from annotations within the source code in order to create the complete set
395// of flags that should be applied to the dex implementation jars on the bootclasspath.
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100396//
397// Each property contains a list of paths. With the exception of the Unsupported_packages the paths
398// of each property reference a plain text file that contains a java signature per line. The flags
399// for each of those signatures will be updated in a property specific way.
400//
401// The Unsupported_packages property contains a list of paths, each of which is a plain text file
402// with one Java package per line. All members of all classes within that package (but not nested
403// packages) will be updated in a property specific way.
Paul Duffin46169772021-04-14 15:01:56 +0100404type HiddenAPIFlagFileProperties struct {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000405 Hidden_api struct {
406 // Marks each signature in the referenced files as being unsupported.
407 Unsupported []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100408
Paul Duffin9b61abb2022-07-27 16:16:54 +0000409 // Marks each signature in the referenced files as being unsupported because it has been
410 // removed. Any conflicts with other flags are ignored.
411 Removed []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100412
Paul Duffin9b61abb2022-07-27 16:16:54 +0000413 // Marks each signature in the referenced files as being supported only for
414 // targetSdkVersion <= R and low priority.
415 Max_target_r_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100416
Paul Duffin9b61abb2022-07-27 16:16:54 +0000417 // Marks each signature in the referenced files as being supported only for
418 // targetSdkVersion <= Q.
419 Max_target_q []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100420
Paul Duffin9b61abb2022-07-27 16:16:54 +0000421 // Marks each signature in the referenced files as being supported only for
422 // targetSdkVersion <= P.
423 Max_target_p []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100424
Paul Duffin9b61abb2022-07-27 16:16:54 +0000425 // Marks each signature in the referenced files as being supported only for
426 // targetSdkVersion <= O
427 // and low priority. Any conflicts with other flags are ignored.
428 Max_target_o_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100429
Paul Duffin9b61abb2022-07-27 16:16:54 +0000430 // Marks each signature in the referenced files as being blocked.
431 Blocked []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100432
Paul Duffin9b61abb2022-07-27 16:16:54 +0000433 // Marks each signature in every package in the referenced files as being unsupported.
434 Unsupported_packages []string `android:"path"`
435 }
Paul Duffin702210b2021-04-08 20:12:41 +0100436}
437
Paul Duffine3dc6602021-04-14 09:50:43 +0100438type hiddenAPIFlagFileCategory struct {
Paul Duffin524c82c2021-06-09 14:39:28 +0100439 // PropertyName is the name of the property for this category.
440 PropertyName string
Paul Duffine3dc6602021-04-14 09:50:43 +0100441
Paul Duffincc17bfe2021-04-19 13:21:20 +0100442 // propertyValueReader retrieves the value of the property for this category from the set of
Paul Duffine3dc6602021-04-14 09:50:43 +0100443 // properties.
Paul Duffincc17bfe2021-04-19 13:21:20 +0100444 propertyValueReader func(properties *HiddenAPIFlagFileProperties) []string
Paul Duffine3dc6602021-04-14 09:50:43 +0100445
446 // commandMutator adds the appropriate command line options for this category to the supplied
447 // command
448 commandMutator func(command *android.RuleBuilderCommand, path android.Path)
449}
450
Paul Duffin32cf58a2021-05-18 16:32:50 +0100451// The flag file category for removed members of the API.
452//
Paul Duffin524c82c2021-06-09 14:39:28 +0100453// This is extracted from HiddenAPIFlagFileCategories as it is needed to add the dex signatures
Paul Duffin32cf58a2021-05-18 16:32:50 +0100454// list of removed API members that are generated automatically from the removed.txt files provided
455// by API stubs.
456var hiddenAPIRemovedFlagFileCategory = &hiddenAPIFlagFileCategory{
457 // See HiddenAPIFlagFileProperties.Removed
Paul Duffin524c82c2021-06-09 14:39:28 +0100458 PropertyName: "removed",
Paul Duffin32cf58a2021-05-18 16:32:50 +0100459 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000460 return properties.Hidden_api.Removed
Paul Duffin32cf58a2021-05-18 16:32:50 +0100461 },
462 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
463 command.FlagWithInput("--unsupported ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "removed")
464 },
465}
466
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000467type hiddenAPIFlagFileCategories []*hiddenAPIFlagFileCategory
468
469func (c hiddenAPIFlagFileCategories) byProperty(name string) *hiddenAPIFlagFileCategory {
470 for _, category := range c {
471 if category.PropertyName == name {
472 return category
473 }
474 }
475 panic(fmt.Errorf("no category exists with property name %q in %v", name, c))
476}
477
478var HiddenAPIFlagFileCategories = hiddenAPIFlagFileCategories{
Paul Duffin46169772021-04-14 15:01:56 +0100479 // See HiddenAPIFlagFileProperties.Unsupported
Paul Duffine3dc6602021-04-14 09:50:43 +0100480 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100481 PropertyName: "unsupported",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100482 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000483 return properties.Hidden_api.Unsupported
Paul Duffine3dc6602021-04-14 09:50:43 +0100484 },
485 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
486 command.FlagWithInput("--unsupported ", path)
487 },
488 },
Paul Duffin32cf58a2021-05-18 16:32:50 +0100489 hiddenAPIRemovedFlagFileCategory,
Paul Duffin46169772021-04-14 15:01:56 +0100490 // See HiddenAPIFlagFileProperties.Max_target_r_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100491 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100492 PropertyName: "max_target_r_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100493 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000494 return properties.Hidden_api.Max_target_r_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100495 },
496 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
497 command.FlagWithInput("--max-target-r ", path).FlagWithArg("--tag ", "lo-prio")
498 },
499 },
Paul Duffin46169772021-04-14 15:01:56 +0100500 // See HiddenAPIFlagFileProperties.Max_target_q
Paul Duffine3dc6602021-04-14 09:50:43 +0100501 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100502 PropertyName: "max_target_q",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100503 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000504 return properties.Hidden_api.Max_target_q
Paul Duffine3dc6602021-04-14 09:50:43 +0100505 },
506 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
507 command.FlagWithInput("--max-target-q ", path)
508 },
509 },
Paul Duffin46169772021-04-14 15:01:56 +0100510 // See HiddenAPIFlagFileProperties.Max_target_p
Paul Duffine3dc6602021-04-14 09:50:43 +0100511 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100512 PropertyName: "max_target_p",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100513 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000514 return properties.Hidden_api.Max_target_p
Paul Duffine3dc6602021-04-14 09:50:43 +0100515 },
516 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
517 command.FlagWithInput("--max-target-p ", path)
518 },
519 },
Paul Duffin46169772021-04-14 15:01:56 +0100520 // See HiddenAPIFlagFileProperties.Max_target_o_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100521 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100522 PropertyName: "max_target_o_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100523 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000524 return properties.Hidden_api.Max_target_o_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100525 },
526 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
527 command.FlagWithInput("--max-target-o ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "lo-prio")
528 },
529 },
Paul Duffin46169772021-04-14 15:01:56 +0100530 // See HiddenAPIFlagFileProperties.Blocked
Paul Duffine3dc6602021-04-14 09:50:43 +0100531 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100532 PropertyName: "blocked",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100533 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000534 return properties.Hidden_api.Blocked
Paul Duffine3dc6602021-04-14 09:50:43 +0100535 },
536 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
537 command.FlagWithInput("--blocked ", path)
538 },
539 },
Paul Duffin46169772021-04-14 15:01:56 +0100540 // See HiddenAPIFlagFileProperties.Unsupported_packages
Paul Duffine3dc6602021-04-14 09:50:43 +0100541 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100542 PropertyName: "unsupported_packages",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100543 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000544 return properties.Hidden_api.Unsupported_packages
Paul Duffine3dc6602021-04-14 09:50:43 +0100545 },
546 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
547 command.FlagWithInput("--unsupported ", path).Flag("--packages ")
548 },
549 },
Paul Duffin702210b2021-04-08 20:12:41 +0100550}
551
Paul Duffin438eb572021-05-21 16:58:23 +0100552// FlagFilesByCategory maps a hiddenAPIFlagFileCategory to the paths to the files in that category.
553type FlagFilesByCategory map[*hiddenAPIFlagFileCategory]android.Paths
554
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000555// append the supplied flags files to the corresponding category in this map.
Paul Duffin438eb572021-05-21 16:58:23 +0100556func (s FlagFilesByCategory) append(other FlagFilesByCategory) {
Paul Duffin524c82c2021-06-09 14:39:28 +0100557 for _, category := range HiddenAPIFlagFileCategories {
Paul Duffin438eb572021-05-21 16:58:23 +0100558 s[category] = append(s[category], other[category]...)
559 }
560}
561
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000562// sort the paths for each category in this map.
563func (s FlagFilesByCategory) sort() {
564 for category, value := range s {
565 s[category] = android.SortedUniquePaths(value)
566 }
567}
568
Paul Duffinaf99afa2021-05-21 22:18:56 +0100569// HiddenAPIInfo contains information provided by the hidden API processing.
Paul Duffin2fef1362021-04-15 13:32:00 +0100570//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100571// That includes paths resolved from HiddenAPIFlagFileProperties and also generated by hidden API
572// processing.
573type HiddenAPIInfo struct {
Paul Duffin438eb572021-05-21 16:58:23 +0100574 // FlagFilesByCategory maps from the flag file category to the paths containing information for
575 // that category.
576 FlagFilesByCategory FlagFilesByCategory
Paul Duffin2fef1362021-04-15 13:32:00 +0100577
Paul Duffin280a31a2021-06-27 20:28:29 +0100578 // The paths to the stub dex jars for each of the *HiddenAPIScope in hiddenAPIScopes provided by
579 // this fragment and the fragments on which this depends.
580 TransitiveStubDexJarsByScope StubDexJarsByModule
Paul Duffin18cf1972021-05-21 22:46:59 +0100581
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100582 // The output from the hidden API processing needs to be made available to other modules.
583 HiddenAPIFlagOutput
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100584}
Paul Duffin702210b2021-04-08 20:12:41 +0100585
Paul Duffinf1b358c2021-05-17 07:38:47 +0100586func newHiddenAPIInfo() *HiddenAPIInfo {
587 info := HiddenAPIInfo{
Paul Duffin31fad802021-06-18 18:14:25 +0100588 FlagFilesByCategory: FlagFilesByCategory{},
Paul Duffin280a31a2021-06-27 20:28:29 +0100589 TransitiveStubDexJarsByScope: StubDexJarsByModule{},
Paul Duffinf1b358c2021-05-17 07:38:47 +0100590 }
591 return &info
592}
593
594func (i *HiddenAPIInfo) mergeFromFragmentDeps(ctx android.ModuleContext, fragments []android.Module) {
595 // Merge all the information from the fragments. The fragments form a DAG so it is possible that
596 // this will introduce duplicates so they will be resolved after processing all the fragments.
597 for _, fragment := range fragments {
Colin Cross313aa542023-12-13 13:47:44 -0800598 if info, ok := android.OtherModuleProvider(ctx, fragment, HiddenAPIInfoProvider); ok {
Paul Duffin280a31a2021-06-27 20:28:29 +0100599 i.TransitiveStubDexJarsByScope.addStubDexJarsByModule(info.TransitiveStubDexJarsByScope)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100600 }
601 }
Paul Duffinf1b358c2021-05-17 07:38:47 +0100602}
603
Paul Duffin191be3a2021-08-10 16:14:16 +0100604// StubFlagSubset returns a SignatureCsvSubset that contains a path to a filtered-stub-flags.csv
605// file and a path to a signature-patterns.csv file that defines a subset of the monolithic stub
606// flags file, i.e. out/soong/hiddenapi/hiddenapi-stub-flags.txt, against which it will be compared.
Paul Duffin67b9d612021-07-21 17:38:47 +0100607func (i *HiddenAPIInfo) StubFlagSubset() SignatureCsvSubset {
Paul Duffin191be3a2021-08-10 16:14:16 +0100608 return SignatureCsvSubset{i.FilteredStubFlagsPath, i.SignaturePatternsPath}
Paul Duffin67b9d612021-07-21 17:38:47 +0100609}
610
Paul Duffin191be3a2021-08-10 16:14:16 +0100611// FlagSubset returns a SignatureCsvSubset that contains a path to a filtered-flags.csv file and a
Paul Duffin67b9d612021-07-21 17:38:47 +0100612// path to a signature-patterns.csv file that defines a subset of the monolithic flags file, i.e.
613// out/soong/hiddenapi/hiddenapi-flags.csv, against which it will be compared.
614func (i *HiddenAPIInfo) FlagSubset() SignatureCsvSubset {
Paul Duffin191be3a2021-08-10 16:14:16 +0100615 return SignatureCsvSubset{i.FilteredFlagsPath, i.SignaturePatternsPath}
Paul Duffin67b9d612021-07-21 17:38:47 +0100616}
617
Colin Crossbc7d76c2023-12-12 16:39:03 -0800618var HiddenAPIInfoProvider = blueprint.NewProvider[HiddenAPIInfo]()
Paul Duffin9b381ef2021-04-08 23:01:37 +0100619
Paul Duffin887efdd2022-09-14 16:37:12 +0100620// HiddenAPIInfoForSdk contains information provided by the hidden API processing for use
621// by the sdk snapshot.
622//
623// That includes paths resolved from HiddenAPIFlagFileProperties and also generated by hidden API
624// processing.
625type HiddenAPIInfoForSdk struct {
626 // FlagFilesByCategory maps from the flag file category to the paths containing information for
627 // that category.
628 FlagFilesByCategory FlagFilesByCategory
629
630 // The output from the hidden API processing needs to be made available to other modules.
631 HiddenAPIFlagOutput
632}
633
634// Provides hidden API info for the sdk snapshot.
Colin Crossbc7d76c2023-12-12 16:39:03 -0800635var HiddenAPIInfoForSdkProvider = blueprint.NewProvider[HiddenAPIInfoForSdk]()
Paul Duffin887efdd2022-09-14 16:37:12 +0100636
Paul Duffin280a31a2021-06-27 20:28:29 +0100637// ModuleStubDexJars contains the stub dex jars provided by a single module.
638//
639// It maps a *HiddenAPIScope to the path to stub dex jars appropriate for that scope. See
640// hiddenAPIScopes for a list of the acceptable *HiddenAPIScope values.
641type ModuleStubDexJars map[*HiddenAPIScope]android.Path
Paul Duffin1352f7c2021-05-21 22:18:49 +0100642
Paul Duffin280a31a2021-06-27 20:28:29 +0100643// stubDexJarForWidestAPIScope returns the stub dex jars for the widest API scope provided by this
Paul Duffin1352f7c2021-05-21 22:18:49 +0100644// map.
Paul Duffin280a31a2021-06-27 20:28:29 +0100645//
646// The relative width of APIs is determined by their order in hiddenAPIScopes.
647func (s ModuleStubDexJars) stubDexJarForWidestAPIScope() android.Path {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100648 for i := len(hiddenAPIScopes) - 1; i >= 0; i-- {
649 apiScope := hiddenAPIScopes[i]
Paul Duffin280a31a2021-06-27 20:28:29 +0100650 if stubsForAPIScope, ok := s[apiScope]; ok {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100651 return stubsForAPIScope
652 }
653 }
654
655 return nil
656}
657
Paul Duffin280a31a2021-06-27 20:28:29 +0100658// StubDexJarsByModule contains the stub dex jars provided by a set of modules.
659//
660// It maps a module name to the path to the stub dex jars provided by that module.
661type StubDexJarsByModule map[string]ModuleStubDexJars
662
663// addStubDexJar adds a stub dex jar path provided by the specified module for the specified scope.
664func (s StubDexJarsByModule) addStubDexJar(ctx android.ModuleContext, module android.Module, scope *HiddenAPIScope, stubDexJar android.Path) {
665 name := android.RemoveOptionalPrebuiltPrefix(module.Name())
Paul Duffin3f0290e2021-06-30 18:25:36 +0100666
667 // Each named module provides one dex jar for each scope. However, in some cases different API
668 // versions of a single classes are provided by separate modules. e.g. the core platform
669 // version of java.lang.Object is provided by the legacy.art.module.platform.api module but the
670 // public version is provided by the art.module.public.api module. In those cases it is necessary
671 // to treat all those modules as they were the same name, otherwise it will result in multiple
672 // definitions of a single class being passed to hidden API processing which will cause an error.
Jihoon Kang244d42a2023-10-06 16:54:58 +0000673 if name == scope.nonUpdatablePrebuiltModule || name == scope.nonUpdatableSourceModule || name == scope.nonUpdatableFromTextModule {
Paul Duffin280a31a2021-06-27 20:28:29 +0100674 // Treat all *android-non-updatable* modules as if they were part of an android-non-updatable
675 // java_sdk_library.
676 // TODO(b/192067200): Remove once android-non-updatable is a java_sdk_library or equivalent.
677 name = "android-non-updatable"
678 } else if name == "legacy.art.module.platform.api" {
679 // Treat legacy.art.module.platform.api as if it was an API scope provided by the
680 // art.module.public.api java_sdk_library which will be the case once the former has been
681 // migrated to a module_lib API.
682 name = "art.module.public.api"
683 } else if name == "legacy.i18n.module.platform.api" {
684 // Treat legacy.i18n.module.platform.api as if it was an API scope provided by the
685 // i18n.module.public.api java_sdk_library which will be the case once the former has been
686 // migrated to a module_lib API.
687 name = "i18n.module.public.api"
688 } else if name == "conscrypt.module.platform.api" {
689 // Treat conscrypt.module.platform.api as if it was an API scope provided by the
690 // conscrypt.module.public.api java_sdk_library which will be the case once the former has been
691 // migrated to a module_lib API.
692 name = "conscrypt.module.public.api"
Paul Duffin3f0290e2021-06-30 18:25:36 +0100693 } else if d, ok := module.(SdkLibraryComponentDependency); ok {
694 sdkLibraryName := d.SdkLibraryName()
695 if sdkLibraryName != nil {
696 // The module is a component of a java_sdk_library so use the name of the java_sdk_library.
697 // e.g. if this module is `foo.system.stubs` and is part of the `foo` java_sdk_library then
698 // use `foo` as the name.
699 name = *sdkLibraryName
700 }
Paul Duffin280a31a2021-06-27 20:28:29 +0100701 }
702 stubDexJarsByScope := s[name]
703 if stubDexJarsByScope == nil {
704 stubDexJarsByScope = ModuleStubDexJars{}
705 s[name] = stubDexJarsByScope
706 }
707 stubDexJarsByScope[scope] = stubDexJar
708}
709
710// addStubDexJarsByModule adds the stub dex jars in the supplied StubDexJarsByModule to this map.
711func (s StubDexJarsByModule) addStubDexJarsByModule(other StubDexJarsByModule) {
712 for module, stubDexJarsByScope := range other {
713 s[module] = stubDexJarsByScope
714 }
715}
716
717// StubDexJarsForWidestAPIScope returns a list of stub dex jars containing the widest API scope
718// provided by each module.
719//
720// The relative width of APIs is determined by their order in hiddenAPIScopes.
721func (s StubDexJarsByModule) StubDexJarsForWidestAPIScope() android.Paths {
722 stubDexJars := android.Paths{}
Cole Faust18994c72023-02-28 16:02:16 -0800723 modules := android.SortedKeys(s)
Paul Duffin280a31a2021-06-27 20:28:29 +0100724 for _, module := range modules {
725 stubDexJarsByScope := s[module]
726
727 stubDexJars = append(stubDexJars, stubDexJarsByScope.stubDexJarForWidestAPIScope())
728 }
729
730 return stubDexJars
731}
732
733// StubDexJarsForScope returns a list of stub dex jars containing the stub dex jars provided by each
734// module for the specified scope.
735//
736// If a module does not provide a stub dex jar for the supplied scope then it does not contribute to
737// the returned list.
738func (s StubDexJarsByModule) StubDexJarsForScope(scope *HiddenAPIScope) android.Paths {
739 stubDexJars := android.Paths{}
Cole Faust18994c72023-02-28 16:02:16 -0800740 modules := android.SortedKeys(s)
Paul Duffin280a31a2021-06-27 20:28:29 +0100741 for _, module := range modules {
742 stubDexJarsByScope := s[module]
743 // Not every module will have the same set of
744 if jars, ok := stubDexJarsByScope[scope]; ok {
745 stubDexJars = append(stubDexJars, jars)
746 }
747 }
748
749 return stubDexJars
750}
751
Paul Duffin1e9e9382022-07-27 15:55:06 +0000752type HiddenAPIPropertyInfo struct {
Paul Duffin1352f7c2021-05-21 22:18:49 +0100753 // FlagFilesByCategory contains the flag files that override the initial flags that are derived
754 // from the stub dex files.
755 FlagFilesByCategory FlagFilesByCategory
756
Paul Duffin1e9e9382022-07-27 15:55:06 +0000757 // See HiddenAPIFlagFileProperties.Package_prefixes
758 PackagePrefixes []string
759
760 // See HiddenAPIFlagFileProperties.Single_packages
761 SinglePackages []string
762
763 // See HiddenAPIFlagFileProperties.Split_packages
764 SplitPackages []string
765}
766
Colin Crossbc7d76c2023-12-12 16:39:03 -0800767var hiddenAPIPropertyInfoProvider = blueprint.NewProvider[HiddenAPIPropertyInfo]()
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000768
Paul Duffin1e9e9382022-07-27 15:55:06 +0000769// newHiddenAPIPropertyInfo creates a new initialized HiddenAPIPropertyInfo struct.
770func newHiddenAPIPropertyInfo() HiddenAPIPropertyInfo {
771 return HiddenAPIPropertyInfo{
772 FlagFilesByCategory: FlagFilesByCategory{},
773 }
774}
775
776// extractFlagFilesFromProperties extracts the paths to flag files that are specified in the
777// supplied properties and stores them in this struct.
778func (i *HiddenAPIPropertyInfo) extractFlagFilesFromProperties(ctx android.ModuleContext, p *HiddenAPIFlagFileProperties) {
779 for _, category := range HiddenAPIFlagFileCategories {
780 paths := android.PathsForModuleSrc(ctx, category.propertyValueReader(p))
781 i.FlagFilesByCategory[category] = paths
782 }
783}
784
785// extractPackageRulesFromProperties extracts the package rules that are specified in the supplied
786// properties and stores them in this struct.
787func (i *HiddenAPIPropertyInfo) extractPackageRulesFromProperties(p *HiddenAPIPackageProperties) {
788 i.PackagePrefixes = p.Hidden_api.Package_prefixes
789 i.SinglePackages = p.Hidden_api.Single_packages
790 i.SplitPackages = p.Hidden_api.Split_packages
791}
792
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000793func (i *HiddenAPIPropertyInfo) gatherPropertyInfo(ctx android.ModuleContext, contents []android.Module) {
794 for _, module := range contents {
Colin Cross313aa542023-12-13 13:47:44 -0800795 if info, ok := android.OtherModuleProvider(ctx, module, hiddenAPIPropertyInfoProvider); ok {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000796 i.FlagFilesByCategory.append(info.FlagFilesByCategory)
797 i.PackagePrefixes = append(i.PackagePrefixes, info.PackagePrefixes...)
798 i.SinglePackages = append(i.SinglePackages, info.SinglePackages...)
799 i.SplitPackages = append(i.SplitPackages, info.SplitPackages...)
800 }
801 }
802
803 // Dedup and sort the information to ensure consistent builds.
804 i.FlagFilesByCategory.sort()
805 i.PackagePrefixes = android.SortedUniqueStrings(i.PackagePrefixes)
806 i.SinglePackages = android.SortedUniqueStrings(i.SinglePackages)
807 i.SplitPackages = android.SortedUniqueStrings(i.SplitPackages)
808}
809
Paul Duffin1e9e9382022-07-27 15:55:06 +0000810// HiddenAPIFlagInput encapsulates information obtained from a module and its dependencies that are
811// needed for hidden API flag generation.
812type HiddenAPIFlagInput struct {
813 HiddenAPIPropertyInfo
814
Paul Duffin31fad802021-06-18 18:14:25 +0100815 // StubDexJarsByScope contains the stub dex jars for different *HiddenAPIScope and which determine
Paul Duffin1352f7c2021-05-21 22:18:49 +0100816 // the initial flags for each dex member.
Paul Duffin280a31a2021-06-27 20:28:29 +0100817 StubDexJarsByScope StubDexJarsByModule
Paul Duffinf1b358c2021-05-17 07:38:47 +0100818
Paul Duffin31fad802021-06-18 18:14:25 +0100819 // DependencyStubDexJarsByScope contains the stub dex jars provided by the fragments on which this
820 // depends. It is the result of merging HiddenAPIInfo.TransitiveStubDexJarsByScope from each
Paul Duffinf1b358c2021-05-17 07:38:47 +0100821 // fragment on which this depends.
Paul Duffin280a31a2021-06-27 20:28:29 +0100822 DependencyStubDexJarsByScope StubDexJarsByModule
Paul Duffin32cf58a2021-05-18 16:32:50 +0100823
Paul Duffin5cca7c42021-05-26 10:16:01 +0100824 // AdditionalStubDexJarsByScope contains stub dex jars provided by other modules in addition to
825 // the ones that are obtained from fragments on which this depends.
826 //
827 // These are kept separate from stub dex jars in HiddenAPIFlagInput.DependencyStubDexJarsByScope
828 // as there are not propagated transitively to other fragments that depend on this.
Paul Duffin280a31a2021-06-27 20:28:29 +0100829 AdditionalStubDexJarsByScope StubDexJarsByModule
Paul Duffin5cca7c42021-05-26 10:16:01 +0100830
Paul Duffin32cf58a2021-05-18 16:32:50 +0100831 // RemovedTxtFiles is the list of removed.txt files provided by java_sdk_library modules that are
832 // specified in the bootclasspath_fragment's stub_libs and contents properties.
833 RemovedTxtFiles android.Paths
Paul Duffin1352f7c2021-05-21 22:18:49 +0100834}
835
Paul Duffin1e9e9382022-07-27 15:55:06 +0000836// newHiddenAPIFlagInput creates a new initialized HiddenAPIFlagInput struct.
Paul Duffin1352f7c2021-05-21 22:18:49 +0100837func newHiddenAPIFlagInput() HiddenAPIFlagInput {
838 input := HiddenAPIFlagInput{
Paul Duffin1e9e9382022-07-27 15:55:06 +0000839 HiddenAPIPropertyInfo: newHiddenAPIPropertyInfo(),
Paul Duffin280a31a2021-06-27 20:28:29 +0100840 StubDexJarsByScope: StubDexJarsByModule{},
841 DependencyStubDexJarsByScope: StubDexJarsByModule{},
842 AdditionalStubDexJarsByScope: StubDexJarsByModule{},
Paul Duffin1352f7c2021-05-21 22:18:49 +0100843 }
844
845 return input
846}
847
848// gatherStubLibInfo gathers information from the stub libs needed by hidden API processing from the
849// dependencies added in hiddenAPIAddStubLibDependencies.
850//
851// That includes paths to the stub dex jars as well as paths to the *removed.txt files.
852func (i *HiddenAPIFlagInput) gatherStubLibInfo(ctx android.ModuleContext, contents []android.Module) {
Paul Duffin31fad802021-06-18 18:14:25 +0100853 addFromModule := func(ctx android.ModuleContext, module android.Module, apiScope *HiddenAPIScope) {
854 sdkKind := apiScope.sdkKind
855 dexJar := hiddenAPIRetrieveDexJarBuildPath(ctx, module, sdkKind)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100856 if dexJar != nil {
Paul Duffin280a31a2021-06-27 20:28:29 +0100857 i.StubDexJarsByScope.addStubDexJar(ctx, module, apiScope, dexJar)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100858 }
Paul Duffin32cf58a2021-05-18 16:32:50 +0100859
860 if sdkLibrary, ok := module.(SdkLibraryDependency); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100861 removedTxtFile := sdkLibrary.SdkRemovedTxtFile(ctx, sdkKind)
Paul Duffin32cf58a2021-05-18 16:32:50 +0100862 i.RemovedTxtFiles = append(i.RemovedTxtFiles, removedTxtFile.AsPaths()...)
863 }
Paul Duffin1352f7c2021-05-21 22:18:49 +0100864 }
865
866 // If the contents includes any java_sdk_library modules then add them to the stubs.
867 for _, module := range contents {
868 if _, ok := module.(SdkLibraryDependency); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100869 // Add information for every possible API scope needed by hidden API.
870 for _, apiScope := range hiddenAPISdkLibrarySupportedScopes {
871 addFromModule(ctx, module, apiScope)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100872 }
873 }
874 }
875
Paul Duffind061d402021-06-07 21:36:01 +0100876 ctx.VisitDirectDeps(func(module android.Module) {
Paul Duffin1352f7c2021-05-21 22:18:49 +0100877 tag := ctx.OtherModuleDependencyTag(module)
878 if hiddenAPIStubsTag, ok := tag.(hiddenAPIStubsDependencyTag); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100879 apiScope := hiddenAPIStubsTag.apiScope
Paul Duffin5cca7c42021-05-26 10:16:01 +0100880 if hiddenAPIStubsTag.fromAdditionalDependency {
881 dexJar := hiddenAPIRetrieveDexJarBuildPath(ctx, module, apiScope.sdkKind)
882 if dexJar != nil {
Paul Duffin280a31a2021-06-27 20:28:29 +0100883 i.AdditionalStubDexJarsByScope.addStubDexJar(ctx, module, apiScope, dexJar)
Paul Duffin5cca7c42021-05-26 10:16:01 +0100884 }
885 } else {
886 addFromModule(ctx, module, apiScope)
887 }
Paul Duffin1352f7c2021-05-21 22:18:49 +0100888 }
889 })
890
891 // Normalize the paths, i.e. remove duplicates and sort.
Paul Duffin32cf58a2021-05-18 16:32:50 +0100892 i.RemovedTxtFiles = android.SortedUniquePaths(i.RemovedTxtFiles)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100893}
894
Paul Duffin280a31a2021-06-27 20:28:29 +0100895func (i *HiddenAPIFlagInput) transitiveStubDexJarsByScope() StubDexJarsByModule {
Paul Duffin31fad802021-06-18 18:14:25 +0100896 transitive := i.DependencyStubDexJarsByScope
Paul Duffin280a31a2021-06-27 20:28:29 +0100897 transitive.addStubDexJarsByModule(i.StubDexJarsByScope)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100898 return transitive
899}
900
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100901// HiddenAPIFlagOutput contains paths to output files from the hidden API flag generation for a
902// bootclasspath_fragment module.
903type HiddenAPIFlagOutput struct {
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100904 // The path to the generated annotation-flags.csv file.
905 AnnotationFlagsPath android.Path
906
907 // The path to the generated metadata.csv file.
908 MetadataPath android.Path
909
910 // The path to the generated index.csv file.
911 IndexPath android.Path
912
Paul Duffin191be3a2021-08-10 16:14:16 +0100913 // The path to the generated stub-flags.csv file.
914 StubFlagsPath android.Path
915
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100916 // The path to the generated all-flags.csv file.
917 AllFlagsPath android.Path
Paul Duffin67b9d612021-07-21 17:38:47 +0100918
919 // The path to the generated signature-patterns.txt file which defines the subset of the
920 // monolithic hidden API files provided in this.
921 SignaturePatternsPath android.Path
Paul Duffin191be3a2021-08-10 16:14:16 +0100922
923 // The path to the generated filtered-stub-flags.csv file.
924 FilteredStubFlagsPath android.Path
925
926 // The path to the generated filtered-flags.csv file.
927 FilteredFlagsPath android.Path
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100928}
929
Paul Duffin5f148ca2021-06-02 17:24:22 +0100930// bootDexJarByModule is a map from base module name (without prebuilt_ prefix) to the boot dex
931// path.
932type bootDexJarByModule map[string]android.Path
933
934// addPath adds the path for a module to the map.
935func (b bootDexJarByModule) addPath(module android.Module, path android.Path) {
936 b[android.RemoveOptionalPrebuiltPrefix(module.Name())] = path
937}
938
Paul Duffine5218812021-06-07 13:28:19 +0100939// bootDexJars returns the boot dex jar paths sorted by their keys.
940func (b bootDexJarByModule) bootDexJars() android.Paths {
941 paths := android.Paths{}
Cole Faust18994c72023-02-28 16:02:16 -0800942 for _, k := range android.SortedKeys(b) {
Paul Duffine5218812021-06-07 13:28:19 +0100943 paths = append(paths, b[k])
944 }
945 return paths
946}
947
Paul Duffin7f872162021-06-17 19:33:24 +0100948// bootDexJarsWithoutCoverage returns the boot dex jar paths sorted by their keys without coverage
949// libraries if present.
950func (b bootDexJarByModule) bootDexJarsWithoutCoverage() android.Paths {
951 paths := android.Paths{}
Cole Faust18994c72023-02-28 16:02:16 -0800952 for _, k := range android.SortedKeys(b) {
Paul Duffin7f872162021-06-17 19:33:24 +0100953 if k == "jacocoagent" {
954 continue
955 }
956 paths = append(paths, b[k])
957 }
958 return paths
959}
960
Paul Duffine5218812021-06-07 13:28:19 +0100961// HiddenAPIOutput encapsulates the output from the hidden API processing.
962type HiddenAPIOutput struct {
963 HiddenAPIFlagOutput
964
965 // The map from base module name to the path to the encoded boot dex file.
Spandan Das5be63332023-12-13 00:06:32 +0000966 // This field is not available in prebuilt apexes
Paul Duffine5218812021-06-07 13:28:19 +0100967 EncodedBootDexFilesByModule bootDexJarByModule
968}
969
Paul Duffindfa10832021-05-13 17:31:51 +0100970// pathForValidation creates a path of the same type as the supplied type but with a name of
971// <path>.valid.
972//
973// e.g. If path is an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv then this will return
974// an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv.valid
975func pathForValidation(ctx android.PathContext, path android.WritablePath) android.WritablePath {
976 extWithoutLeadingDot := strings.TrimPrefix(path.Ext(), ".")
977 return path.ReplaceExtension(ctx, extWithoutLeadingDot+".valid")
978}
979
Paul Duffin2fef1362021-04-15 13:32:00 +0100980// buildRuleToGenerateHiddenApiFlags creates a rule to create the monolithic hidden API flags from
981// the flags from all the modules, the stub flags, augmented with some additional configuration
982// files.
Paul Duffin702210b2021-04-08 20:12:41 +0100983//
984// baseFlagsPath is the path to the flags file containing all the information from the stubs plus
985// an entry for every single member in the dex implementation jars of the individual modules. Every
986// signature in any of the other files MUST be included in this file.
987//
Paul Duffin537ea3d2021-05-14 10:38:00 +0100988// annotationFlags is the path to the annotation flags file generated from annotation information
989// in each module.
Paul Duffin702210b2021-04-08 20:12:41 +0100990//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100991// hiddenAPIInfo is a struct containing paths to files that augment the information provided by
Paul Duffin537ea3d2021-05-14 10:38:00 +0100992// the annotationFlags.
Paul Duffin32cf58a2021-05-18 16:32:50 +0100993func buildRuleToGenerateHiddenApiFlags(ctx android.BuilderContext, name, desc string,
Paul Duffind061d402021-06-07 21:36:01 +0100994 outputPath android.WritablePath, baseFlagsPath android.Path, annotationFlagPaths android.Paths,
Paul Duffin67b9d612021-07-21 17:38:47 +0100995 flagFilesByCategory FlagFilesByCategory, flagSubsets SignatureCsvSubsets, generatedRemovedDexSignatures android.OptionalPath) {
Paul Duffindfa10832021-05-13 17:31:51 +0100996
Paul Duffindfa10832021-05-13 17:31:51 +0100997 // Create the rule that will generate the flag files.
Paul Duffind3c15132021-04-21 22:12:35 +0100998 tempPath := tempPathForRestat(ctx, outputPath)
Paul Duffin702210b2021-04-08 20:12:41 +0100999 rule := android.NewRuleBuilder(pctx, ctx)
1000 command := rule.Command().
1001 BuiltTool("generate_hiddenapi_lists").
1002 FlagWithInput("--csv ", baseFlagsPath).
Paul Duffind061d402021-06-07 21:36:01 +01001003 Inputs(annotationFlagPaths).
Paul Duffin702210b2021-04-08 20:12:41 +01001004 FlagWithOutput("--output ", tempPath)
1005
Paul Duffine3dc6602021-04-14 09:50:43 +01001006 // Add the options for the different categories of flag files.
Paul Duffin524c82c2021-06-09 14:39:28 +01001007 for _, category := range HiddenAPIFlagFileCategories {
Paul Duffin438eb572021-05-21 16:58:23 +01001008 paths := flagFilesByCategory[category]
Paul Duffine3dc6602021-04-14 09:50:43 +01001009 for _, path := range paths {
1010 category.commandMutator(command, path)
1011 }
Paul Duffin702210b2021-04-08 20:12:41 +01001012 }
1013
Paul Duffin32cf58a2021-05-18 16:32:50 +01001014 // If available then pass the automatically generated file containing dex signatures of removed
1015 // API members to the rule so they can be marked as removed.
1016 if generatedRemovedDexSignatures.Valid() {
1017 hiddenAPIRemovedFlagFileCategory.commandMutator(command, generatedRemovedDexSignatures.Path())
1018 }
1019
Paul Duffin702210b2021-04-08 20:12:41 +01001020 commitChangeForRestat(rule, tempPath, outputPath)
1021
Paul Duffin2e880972021-06-23 23:29:09 +01001022 // If there are flag files that have been generated by fragments on which this depends then use
1023 // them to validate the flag file generated by the rules created by this method.
Alyssa Ketpreechasawat7daf2782023-11-01 13:58:39 +00001024 if !ctx.Config().DisableVerifyOverlaps() && len(flagSubsets) > 0 {
Paul Duffinbd88c882022-04-07 23:32:19 +01001025 validFile := buildRuleValidateOverlappingCsvFiles(ctx, name, desc, outputPath, flagSubsets,
1026 HIDDENAPI_FLAGS_CSV_IMPL_FLAGS)
Paul Duffin2e880972021-06-23 23:29:09 +01001027
Paul Duffindfa10832021-05-13 17:31:51 +01001028 // Add the file that indicates that the file generated by this is valid.
1029 //
1030 // This will cause the validation rule above to be run any time that the output of this rule
1031 // changes but the validation will run in parallel with other rules that depend on this file.
1032 command.Validation(validFile)
1033 }
1034
Paul Duffin2fef1362021-04-15 13:32:00 +01001035 rule.Build(name, desc)
1036}
1037
Paul Duffin67b9d612021-07-21 17:38:47 +01001038// SignatureCsvSubset describes a subset of a monolithic flags file, i.e. either
1039// out/soong/hiddenapi/hiddenapi-stub-flags.txt or out/soong/hiddenapi/hiddenapi-flags.csv
1040type SignatureCsvSubset struct {
1041 // The path to the CSV file containing hidden API flags.
1042 //
1043 // It has the dex member signature as the first column, with flags, one per column, in the
1044 // subsequent columns.
1045 CsvFile android.Path
1046
1047 // The path to the CSV file containing the signature patterns.
1048 //
1049 // It is a single column CSV file with the column containing a signature pattern.
1050 SignaturePatternsFile android.Path
1051}
1052
1053type SignatureCsvSubsets []SignatureCsvSubset
1054
1055func (s SignatureCsvSubsets) RelativeToTop() []string {
1056 result := []string{}
1057 for _, subset := range s {
1058 result = append(result, fmt.Sprintf("%s:%s", subset.CsvFile.RelativeToTop(), subset.SignaturePatternsFile.RelativeToTop()))
1059 }
1060 return result
1061}
1062
1063// buildRuleSignaturePatternsFile creates a rule to generate a file containing the set of signature
1064// patterns that will select a subset of the monolithic flags.
Paul Duffin846beb72022-03-15 17:45:57 +00001065func buildRuleSignaturePatternsFile(
1066 ctx android.ModuleContext, flagsPath android.Path,
Paul Duffin1938dba2022-07-26 23:53:00 +00001067 splitPackages []string, packagePrefixes []string, singlePackages []string,
1068 suffix string) android.Path {
1069 hiddenApiSubDir := "modular-hiddenapi" + suffix
1070
1071 patternsFile := android.PathForModuleOut(ctx, hiddenApiSubDir, "signature-patterns.csv")
Paul Duffin67b9d612021-07-21 17:38:47 +01001072 // Create a rule to validate the output from the following rule.
1073 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffin1e18e982021-08-03 15:42:27 +01001074
1075 // Quote any * in the packages to avoid them being expanded by the shell.
1076 quotedSplitPackages := []string{}
1077 for _, pkg := range splitPackages {
1078 quotedSplitPackages = append(quotedSplitPackages, strings.ReplaceAll(pkg, "*", "\\*"))
1079 }
1080
Paul Duffin67b9d612021-07-21 17:38:47 +01001081 rule.Command().
1082 BuiltTool("signature_patterns").
1083 FlagWithInput("--flags ", flagsPath).
Paul Duffin1e18e982021-08-03 15:42:27 +01001084 FlagForEachArg("--split-package ", quotedSplitPackages).
1085 FlagForEachArg("--package-prefix ", packagePrefixes).
Paul Duffin846beb72022-03-15 17:45:57 +00001086 FlagForEachArg("--single-package ", singlePackages).
Paul Duffin67b9d612021-07-21 17:38:47 +01001087 FlagWithOutput("--output ", patternsFile)
Paul Duffin1938dba2022-07-26 23:53:00 +00001088 rule.Build("hiddenAPISignaturePatterns"+suffix, "hidden API signature patterns"+suffix)
Paul Duffin67b9d612021-07-21 17:38:47 +01001089
1090 return patternsFile
1091}
1092
Paul Duffinbd88c882022-04-07 23:32:19 +01001093// buildRuleRemoveSignaturesWithImplementationFlags creates a rule that will remove signatures from
1094// the input flags file which have only the implementation flags, i.e. are not part of an API.
1095//
1096// The implementationFlags specifies the set of default flags that identifies the signature of a
1097// private, implementation only, member. Signatures that match those flags are removed from the
1098// flags as they are implementation only.
1099//
1100// This is used to remove implementation only signatures from the signature files that are persisted
1101// in the sdk snapshot as the sdk snapshots should not include implementation details. The
1102// signatures generated by this method will be compared by the buildRuleValidateOverlappingCsvFiles
1103// method which treats any missing signatures as if they were implementation only signatures.
1104func buildRuleRemoveSignaturesWithImplementationFlags(ctx android.BuilderContext,
1105 name string, desc string, inputPath android.Path, filteredPath android.WritablePath,
1106 implementationFlags []string) {
1107
Paul Duffin280bae62021-07-20 18:03:53 +01001108 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffinbd88c882022-04-07 23:32:19 +01001109 implementationFlagPattern := ""
1110 for _, implementationFlag := range implementationFlags {
1111 implementationFlagPattern = implementationFlagPattern + "," + implementationFlag
1112 }
Paul Duffin280bae62021-07-20 18:03:53 +01001113 rule.Command().
Paul Duffinbd88c882022-04-07 23:32:19 +01001114 Text(`grep -vE "^[^,]+` + implementationFlagPattern + `$"`).Input(inputPath).
1115 Text(">").Output(filteredPath).
Paul Duffin280bae62021-07-20 18:03:53 +01001116 // Grep's exit code depends on whether it finds anything. It is 0 (build success) when it finds
1117 // something and 1 (build failure) when it does not and 2 (when it encounters an error).
1118 // However, while it is unlikely it is not an error if this does not find any matches. The
1119 // following will only run if the grep does not find something and in that case it will treat
1120 // an exit code of 1 as success and anything else as failure.
1121 Text("|| test $? -eq 1")
1122 rule.Build(name, desc)
1123}
1124
Paul Duffin2e880972021-06-23 23:29:09 +01001125// buildRuleValidateOverlappingCsvFiles checks that the modular CSV files, i.e. the files generated
1126// by the individual bootclasspath_fragment modules are subsets of the monolithic CSV file.
Paul Duffinbd88c882022-04-07 23:32:19 +01001127//
1128// The implementationFlags specifies the set of default flags that identifies the signature of a
1129// private, implementation only, member. A signature which is present in a monolithic flags subset
1130// defined by SignatureCsvSubset but which is not present in the flags file from the corresponding
1131// module is assumed to be an implementation only member and so must have these flags.
1132func buildRuleValidateOverlappingCsvFiles(ctx android.BuilderContext, name string, desc string,
1133 monolithicFilePath android.WritablePath, csvSubsets SignatureCsvSubsets,
1134 implementationFlags []string) android.WritablePath {
Paul Duffin2e880972021-06-23 23:29:09 +01001135 // The file which is used to record that the flags file is valid.
1136 validFile := pathForValidation(ctx, monolithicFilePath)
1137
1138 // Create a rule to validate the output from the following rule.
1139 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffin67b9d612021-07-21 17:38:47 +01001140 command := rule.Command().
Paul Duffin2e880972021-06-23 23:29:09 +01001141 BuiltTool("verify_overlaps").
Paul Duffin0c12b782022-04-08 00:28:11 +01001142 FlagWithInput("--monolithic-flags ", monolithicFilePath)
Paul Duffin67b9d612021-07-21 17:38:47 +01001143
1144 for _, subset := range csvSubsets {
1145 command.
Paul Duffin0c12b782022-04-08 00:28:11 +01001146 Flag("--module-flags ").
Paul Duffin67b9d612021-07-21 17:38:47 +01001147 Textf("%s:%s", subset.CsvFile, subset.SignaturePatternsFile).
1148 Implicit(subset.CsvFile).Implicit(subset.SignaturePatternsFile)
1149 }
1150
Paul Duffinbd88c882022-04-07 23:32:19 +01001151 for _, implementationFlag := range implementationFlags {
1152 command.FlagWithArg("--implementation-flag ", implementationFlag)
1153 }
1154
Paul Duffin67b9d612021-07-21 17:38:47 +01001155 // If validation passes then update the file that records that.
1156 command.Text("&& touch").Output(validFile)
Paul Duffin2e880972021-06-23 23:29:09 +01001157 rule.Build(name+"Validation", desc+" validation")
1158
1159 return validFile
1160}
1161
Paul Duffinaf705182022-09-14 11:47:34 +01001162// hiddenAPIFlagRulesForBootclasspathFragment will generate all the flags for a fragment of the
1163// bootclasspath.
Paul Duffin2fef1362021-04-15 13:32:00 +01001164//
1165// It takes:
1166// * Map from android.SdkKind to stub dex jar paths defining the API for that sdk kind.
1167// * The list of modules that are the contents of the fragment.
1168// * The additional manually curated flag files to use.
1169//
1170// It generates:
1171// * stub-flags.csv
1172// * annotation-flags.csv
1173// * metadata.csv
1174// * index.csv
1175// * all-flags.csv
Paul Duffin1938dba2022-07-26 23:53:00 +00001176func hiddenAPIFlagRulesForBootclasspathFragment(ctx android.ModuleContext, bootDexInfoByModule bootDexInfoByModule, contents []android.Module, input HiddenAPIFlagInput, suffix string) HiddenAPIFlagOutput {
1177 hiddenApiSubDir := "modular-hiddenapi" + suffix
Paul Duffin2fef1362021-04-15 13:32:00 +01001178
Paul Duffin1352f7c2021-05-21 22:18:49 +01001179 // Generate the stub-flags.csv.
Paul Duffin2fef1362021-04-15 13:32:00 +01001180 stubFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "stub-flags.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001181 buildRuleToGenerateHiddenAPIStubFlagsFile(ctx, "modularHiddenAPIStubFlagsFile"+suffix, "modular hiddenapi stub flags", stubFlagsCSV, bootDexInfoByModule.bootDexJars(), input, nil)
Paul Duffin2fef1362021-04-15 13:32:00 +01001182
Paul Duffin537ea3d2021-05-14 10:38:00 +01001183 // Extract the classes jars from the contents.
Paul Duffindd5993f2021-06-10 10:18:22 +01001184 classesJars := extractClassesJarsFromModules(contents)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001185
Paul Duffin2fef1362021-04-15 13:32:00 +01001186 // Generate the set of flags from the annotations in the source code.
1187 annotationFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "annotation-flags.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001188 buildRuleToGenerateAnnotationFlags(ctx, "modular hiddenapi annotation flags"+suffix, classesJars, stubFlagsCSV, annotationFlagsCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001189
1190 // Generate the metadata from the annotations in the source code.
1191 metadataCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "metadata.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001192 buildRuleToGenerateMetadata(ctx, "modular hiddenapi metadata"+suffix, classesJars, stubFlagsCSV, metadataCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001193
Paul Duffin537ea3d2021-05-14 10:38:00 +01001194 // Generate the index file from the CSV files in the classes jars.
Paul Duffin2fef1362021-04-15 13:32:00 +01001195 indexCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "index.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001196 buildRuleToGenerateIndex(ctx, "modular hiddenapi index"+suffix, classesJars, indexCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001197
Paul Duffinaf99afa2021-05-21 22:18:56 +01001198 // Removed APIs need to be marked and in order to do that the hiddenAPIInfo needs to specify files
Paul Duffin2fef1362021-04-15 13:32:00 +01001199 // containing dex signatures of all the removed APIs. In the monolithic files that is done by
1200 // manually combining all the removed.txt files for each API and then converting them to dex
Paul Duffin32cf58a2021-05-18 16:32:50 +01001201 // signatures, see the combined-removed-dex module. This does that automatically by using the
1202 // *removed.txt files retrieved from the java_sdk_library modules that are specified in the
1203 // stub_libs and contents properties of a bootclasspath_fragment.
Paul Duffin1938dba2022-07-26 23:53:00 +00001204 removedDexSignatures := buildRuleToGenerateRemovedDexSignatures(ctx, suffix, input.RemovedTxtFiles)
Paul Duffin2fef1362021-04-15 13:32:00 +01001205
1206 // Generate the all-flags.csv which are the flags that will, in future, be encoded into the dex
1207 // files.
Paul Duffine5218812021-06-07 13:28:19 +01001208 allFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "all-flags.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001209 buildRuleToGenerateHiddenApiFlags(ctx, "modularHiddenApiAllFlags"+suffix, "modular hiddenapi all flags"+suffix, allFlagsCSV, stubFlagsCSV, android.Paths{annotationFlagsCSV}, input.FlagFilesByCategory, nil, removedDexSignatures)
Paul Duffine5218812021-06-07 13:28:19 +01001210
Paul Duffin280bae62021-07-20 18:03:53 +01001211 // Generate the filtered-stub-flags.csv file which contains the filtered stub flags that will be
1212 // compared against the monolithic stub flags.
1213 filteredStubFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "filtered-stub-flags.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001214 buildRuleRemoveSignaturesWithImplementationFlags(ctx, "modularHiddenApiFilteredStubFlags"+suffix,
1215 "modular hiddenapi filtered stub flags"+suffix, stubFlagsCSV, filteredStubFlagsCSV,
Paul Duffinbd88c882022-04-07 23:32:19 +01001216 HIDDENAPI_STUB_FLAGS_IMPL_FLAGS)
Paul Duffin280bae62021-07-20 18:03:53 +01001217
1218 // Generate the filtered-flags.csv file which contains the filtered flags that will be compared
1219 // against the monolithic flags.
1220 filteredFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "filtered-flags.csv")
Paul Duffin1938dba2022-07-26 23:53:00 +00001221 buildRuleRemoveSignaturesWithImplementationFlags(ctx, "modularHiddenApiFilteredFlags"+suffix,
1222 "modular hiddenapi filtered flags"+suffix, allFlagsCSV, filteredFlagsCSV,
Paul Duffinbd88c882022-04-07 23:32:19 +01001223 HIDDENAPI_FLAGS_CSV_IMPL_FLAGS)
Paul Duffin280bae62021-07-20 18:03:53 +01001224
Paul Duffin2fef1362021-04-15 13:32:00 +01001225 // Store the paths in the info for use by other modules and sdk snapshot generation.
Paul Duffinaf705182022-09-14 11:47:34 +01001226 return HiddenAPIFlagOutput{
1227 AnnotationFlagsPath: annotationFlagsCSV,
1228 MetadataPath: metadataCSV,
1229 IndexPath: indexCSV,
1230 StubFlagsPath: stubFlagsCSV,
1231 AllFlagsPath: allFlagsCSV,
1232 FilteredStubFlagsPath: filteredStubFlagsCSV,
1233 FilteredFlagsPath: filteredFlagsCSV,
Paul Duffin1e6f5c42021-05-21 16:15:31 +01001234 }
Paul Duffinaf705182022-09-14 11:47:34 +01001235}
1236
1237// hiddenAPIEncodeRulesForBootclasspathFragment generates rules to encode hidden API flags into the
1238// dex jars in bootDexInfoByModule.
1239func hiddenAPIEncodeRulesForBootclasspathFragment(ctx android.ModuleContext, bootDexInfoByModule bootDexInfoByModule, allFlagsCSV android.Path) bootDexJarByModule {
1240 // Encode the flags into the boot dex files.
1241 encodedBootDexJarsByModule := bootDexJarByModule{}
1242 outputDir := android.PathForModuleOut(ctx, "hiddenapi-modular/encoded").OutputPath
Cole Faust18994c72023-02-28 16:02:16 -08001243 for _, name := range android.SortedKeys(bootDexInfoByModule) {
Paul Duffinaf705182022-09-14 11:47:34 +01001244 bootDexInfo := bootDexInfoByModule[name]
1245 unencodedDex := bootDexInfo.path
1246 encodedDex := hiddenAPIEncodeDex(ctx, unencodedDex, allFlagsCSV, bootDexInfo.uncompressDex, bootDexInfo.minSdkVersion, outputDir)
1247 encodedBootDexJarsByModule[name] = encodedDex
1248 }
1249 return encodedBootDexJarsByModule
Paul Duffin702210b2021-04-08 20:12:41 +01001250}
Paul Duffin537ea3d2021-05-14 10:38:00 +01001251
Paul Duffin1938dba2022-07-26 23:53:00 +00001252func buildRuleToGenerateRemovedDexSignatures(ctx android.ModuleContext, suffix string, removedTxtFiles android.Paths) android.OptionalPath {
Paul Duffin32cf58a2021-05-18 16:32:50 +01001253 if len(removedTxtFiles) == 0 {
1254 return android.OptionalPath{}
1255 }
1256
Paul Duffin1938dba2022-07-26 23:53:00 +00001257 output := android.PathForModuleOut(ctx, "module-hiddenapi"+suffix, "removed-dex-signatures.txt")
Paul Duffin32cf58a2021-05-18 16:32:50 +01001258
1259 rule := android.NewRuleBuilder(pctx, ctx)
1260 rule.Command().
1261 BuiltTool("metalava").
Paul Duffin32cf58a2021-05-18 16:32:50 +01001262 Inputs(removedTxtFiles).
1263 FlagWithOutput("--dex-api ", output)
Paul Duffin1938dba2022-07-26 23:53:00 +00001264 rule.Build("modular-hiddenapi-removed-dex-signatures"+suffix, "modular hiddenapi removed dex signatures"+suffix)
Paul Duffin32cf58a2021-05-18 16:32:50 +01001265 return android.OptionalPathForPath(output)
1266}
1267
Paul Duffindd5993f2021-06-10 10:18:22 +01001268// extractBootDexJarsFromModules extracts the boot dex jars from the supplied modules.
Spandan Das64c9e0c2023-12-20 20:13:34 +00001269// This information can come from two mechanisms
1270// 1. New: Direct deps to _selected_ apexes. The apexes contain a ApexExportsInfo
1271// 2. Legacy: An edge to java_sdk_library(_import) module. For prebuilt apexes, this serves as a hook and is populated by deapexers of prebuilt apxes
1272// TODO: b/308174306 - Once all mainline modules have been flagged, drop (2)
Paul Duffine5218812021-06-07 13:28:19 +01001273func extractBootDexJarsFromModules(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
1274 bootDexJars := bootDexJarByModule{}
Spandan Das64c9e0c2023-12-20 20:13:34 +00001275
1276 apexNameToApexExportsInfoMap := getApexNameToApexExportsInfoMap(ctx)
1277 // For ART and mainline module jars, query apexNameToApexExportsInfoMap to get the dex file
1278 apexJars := dexpreopt.GetGlobalConfig(ctx).ArtApexJars.AppendList(&dexpreopt.GetGlobalConfig(ctx).ApexBootJars)
1279 for i := 0; i < apexJars.Len(); i++ {
1280 if dex, found := apexNameToApexExportsInfoMap.javaLibraryDexPathOnHost(ctx, apexJars.Apex(i), apexJars.Jar(i)); found {
1281 bootDexJars[apexJars.Jar(i)] = dex
1282 }
1283 }
1284
1285 // TODO - b/308174306: Drop the legacy mechanism
Paul Duffin537ea3d2021-05-14 10:38:00 +01001286 for _, module := range contents {
Spandan Das64c9e0c2023-12-20 20:13:34 +00001287 if _, exists := bootDexJars[android.RemoveOptionalPrebuiltPrefix(module.Name())]; exists {
1288 continue
1289 }
Paul Duffindd5993f2021-06-10 10:18:22 +01001290 hiddenAPIModule := hiddenAPIModuleFromModule(ctx, module)
1291 if hiddenAPIModule == nil {
1292 continue
1293 }
Paul Duffine5218812021-06-07 13:28:19 +01001294 bootDexJar := retrieveBootDexJarFromHiddenAPIModule(ctx, hiddenAPIModule)
1295 bootDexJars.addPath(module, bootDexJar)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001296 }
1297 return bootDexJars
1298}
1299
Paul Duffindd5993f2021-06-10 10:18:22 +01001300func hiddenAPIModuleFromModule(ctx android.BaseModuleContext, module android.Module) hiddenAPIModule {
1301 if hiddenAPIModule, ok := module.(hiddenAPIModule); ok {
1302 return hiddenAPIModule
1303 } else if _, ok := module.(*DexImport); ok {
1304 // Ignore this for the purposes of hidden API processing
1305 } else {
1306 ctx.ModuleErrorf("module %s does not implement hiddenAPIModule", module)
1307 }
1308
1309 return nil
1310}
1311
Paul Duffine5218812021-06-07 13:28:19 +01001312// bootDexInfo encapsulates both the path and uncompressDex status retrieved from a hiddenAPIModule.
1313type bootDexInfo struct {
1314 // The path to the dex jar that has not had hidden API flags encoded into it.
1315 path android.Path
1316
1317 // Indicates whether the dex jar needs uncompressing before encoding.
1318 uncompressDex bool
Paul Duffin09817d62022-04-28 17:45:11 +01001319
1320 // The minimum sdk version that the dex jar will be used on.
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001321 minSdkVersion android.ApiLevel
Paul Duffine5218812021-06-07 13:28:19 +01001322}
1323
1324// bootDexInfoByModule is a map from module name (as returned by module.Name()) to the boot dex
1325// path (as returned by hiddenAPIModule.bootDexJar()) and the uncompressDex flag.
1326type bootDexInfoByModule map[string]bootDexInfo
1327
1328// bootDexJars returns the boot dex jar paths sorted by their keys.
1329func (b bootDexInfoByModule) bootDexJars() android.Paths {
1330 paths := android.Paths{}
Cole Faust18994c72023-02-28 16:02:16 -08001331 for _, m := range android.SortedKeys(b) {
Paul Duffine5218812021-06-07 13:28:19 +01001332 paths = append(paths, b[m].path)
1333 }
1334 return paths
1335}
1336
1337// extractBootDexInfoFromModules extracts the boot dex jar and uncompress dex state from
1338// each of the supplied modules which must implement hiddenAPIModule.
1339func extractBootDexInfoFromModules(ctx android.ModuleContext, contents []android.Module) bootDexInfoByModule {
1340 bootDexJarsByModule := bootDexInfoByModule{}
1341 for _, module := range contents {
1342 hiddenAPIModule := module.(hiddenAPIModule)
1343 bootDexJar := retrieveBootDexJarFromHiddenAPIModule(ctx, hiddenAPIModule)
1344 bootDexJarsByModule[module.Name()] = bootDexInfo{
1345 path: bootDexJar,
1346 uncompressDex: *hiddenAPIModule.uncompressDex(),
Paul Duffin09817d62022-04-28 17:45:11 +01001347 minSdkVersion: hiddenAPIModule.MinSdkVersion(ctx),
Paul Duffine5218812021-06-07 13:28:19 +01001348 }
1349 }
1350
1351 return bootDexJarsByModule
1352}
1353
1354// retrieveBootDexJarFromHiddenAPIModule retrieves the boot dex jar from the hiddenAPIModule.
1355//
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001356// If the module does not provide a boot dex jar, i.e. the returned boot dex jar is unset or
1357// invalid, then create a fake path and either report an error immediately or defer reporting of the
1358// error until the path is actually used.
Paul Duffine5218812021-06-07 13:28:19 +01001359func retrieveBootDexJarFromHiddenAPIModule(ctx android.ModuleContext, module hiddenAPIModule) android.Path {
1360 bootDexJar := module.bootDexJar()
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001361 if !bootDexJar.Valid() {
Paul Duffine5218812021-06-07 13:28:19 +01001362 fake := android.PathForModuleOut(ctx, fmt.Sprintf("fake/boot-dex/%s.jar", module.Name()))
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001363 handleMissingDexBootFile(ctx, module, fake, bootDexJar.InvalidReason())
1364 return fake
Paul Duffine5218812021-06-07 13:28:19 +01001365 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001366 return bootDexJar.Path()
Paul Duffine5218812021-06-07 13:28:19 +01001367}
1368
Paul Duffindd5993f2021-06-10 10:18:22 +01001369// extractClassesJarsFromModules extracts the class jars from the supplied modules.
1370func extractClassesJarsFromModules(contents []android.Module) android.Paths {
Paul Duffin537ea3d2021-05-14 10:38:00 +01001371 classesJars := android.Paths{}
1372 for _, module := range contents {
Paul Duffindd5993f2021-06-10 10:18:22 +01001373 classesJars = append(classesJars, retrieveClassesJarsFromModule(module)...)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001374 }
1375 return classesJars
1376}
Paul Duffin5f148ca2021-06-02 17:24:22 +01001377
Paul Duffindd5993f2021-06-10 10:18:22 +01001378// retrieveClassesJarsFromModule retrieves the classes jars from the supplied module.
1379func retrieveClassesJarsFromModule(module android.Module) android.Paths {
1380 if hiddenAPIModule, ok := module.(hiddenAPIModule); ok {
1381 return hiddenAPIModule.classesJars()
1382 }
1383
1384 return nil
1385}
1386
Paul Duffin5f148ca2021-06-02 17:24:22 +01001387// deferReportingMissingBootDexJar returns true if a missing boot dex jar should not be reported by
1388// Soong but should instead only be reported in ninja if the file is actually built.
1389func deferReportingMissingBootDexJar(ctx android.ModuleContext, module android.Module) bool {
Paul Duffine5218812021-06-07 13:28:19 +01001390 // Any missing dependency should be allowed.
1391 if ctx.Config().AllowMissingDependencies() {
1392 return true
1393 }
1394
Paul Duffin5f148ca2021-06-02 17:24:22 +01001395 // This is called for both platform_bootclasspath and bootclasspath_fragment modules.
1396 //
1397 // A bootclasspath_fragment module should only use the APEX variant of source or prebuilt modules.
1398 // Ideally, a bootclasspath_fragment module should never have a platform variant created for it
1399 // but unfortunately, due to b/187910671 it does.
1400 //
1401 // That causes issues when obtaining a boot dex jar for a prebuilt module as a prebuilt module
1402 // used by a bootclasspath_fragment can only provide a boot dex jar when it is part of APEX, i.e.
1403 // has an APEX variant not a platform variant.
1404 //
1405 // There are some other situations when a prebuilt module used by a bootclasspath_fragment cannot
1406 // provide a boot dex jar:
1407 // 1. If the bootclasspath_fragment is not exported by the prebuilt_apex/apex_set module then it
1408 // does not have an APEX variant and only has a platform variant and neither do its content
1409 // modules.
1410 // 2. Some build configurations, e.g. setting TARGET_BUILD_USE_PREBUILT_SDKS causes all
1411 // java_sdk_library_import modules to be treated as preferred and as many of them are not part
1412 // of an apex they cannot provide a boot dex jar.
1413 //
1414 // The first case causes problems when the affected prebuilt modules are preferred but that is an
1415 // invalid configuration and it is ok for it to fail as the work to enable that is not yet
1416 // complete. The second case is used for building targets that do not use boot dex jars and so
1417 // deferring error reporting to ninja is fine as the affected ninja targets should never be built.
1418 // That is handled above.
1419 //
1420 // A platform_bootclasspath module can use libraries from both platform and APEX variants. Unlike
1421 // the bootclasspath_fragment it supports dex_import modules which provides the dex file. So, it
1422 // can obtain a boot dex jar from a prebuilt that is not part of an APEX. However, it is assumed
1423 // that if the library can be part of an APEX then it is the APEX variant that is used.
1424 //
1425 // This check handles the slightly different requirements of the bootclasspath_fragment and
1426 // platform_bootclasspath modules by only deferring error reporting for the platform variant of
1427 // a prebuilt modules that has other variants which are part of an APEX.
1428 //
1429 // TODO(b/187910671): Remove this once platform variants are no longer created unnecessarily.
1430 if android.IsModulePrebuilt(module) {
Paul Duffinef083c92021-06-29 13:36:34 +01001431 // An inactive source module can still contribute to the APEX but an inactive prebuilt module
1432 // should not contribute to anything. So, rather than have a missing dex jar cause a Soong
1433 // failure defer the error reporting to Ninja. Unless the prebuilt build target is explicitly
1434 // built Ninja should never use the dex jar file.
1435 if !isActiveModule(module) {
1436 return true
1437 }
1438
Paul Duffin5f148ca2021-06-02 17:24:22 +01001439 if am, ok := module.(android.ApexModule); ok && am.InAnyApex() {
Colin Cross313aa542023-12-13 13:47:44 -08001440 apexInfo, _ := android.OtherModuleProvider(ctx, module, android.ApexInfoProvider)
Paul Duffin5f148ca2021-06-02 17:24:22 +01001441 if apexInfo.IsForPlatform() {
1442 return true
1443 }
1444 }
1445 }
1446
Paul Duffin5f148ca2021-06-02 17:24:22 +01001447 return false
1448}
1449
1450// handleMissingDexBootFile will either log a warning or create an error rule to create the fake
1451// file depending on the value returned from deferReportingMissingBootDexJar.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001452func handleMissingDexBootFile(ctx android.ModuleContext, module android.Module, fake android.WritablePath, reason string) {
Paul Duffin5f148ca2021-06-02 17:24:22 +01001453 if deferReportingMissingBootDexJar(ctx, module) {
1454 // Create an error rule that pretends to create the output file but will actually fail if it
1455 // is run.
1456 ctx.Build(pctx, android.BuildParams{
1457 Rule: android.ErrorRule,
1458 Output: fake,
1459 Args: map[string]string{
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001460 "error": fmt.Sprintf("missing boot dex jar dependency for %s: %s", module, reason),
Paul Duffin5f148ca2021-06-02 17:24:22 +01001461 },
1462 })
1463 } else {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001464 ctx.ModuleErrorf("module %s does not provide a dex jar: %s", module, reason)
Paul Duffin5f148ca2021-06-02 17:24:22 +01001465 }
1466}
1467
1468// retrieveEncodedBootDexJarFromModule returns a path to the boot dex jar from the supplied module's
1469// DexJarBuildPath() method.
1470//
1471// The returned path will usually be to a dex jar file that has been encoded with hidden API flags.
1472// However, under certain conditions, e.g. errors, or special build configurations it will return
1473// a path to a fake file.
1474func retrieveEncodedBootDexJarFromModule(ctx android.ModuleContext, module android.Module) android.Path {
Spandan Das59a4a2b2024-01-09 21:35:56 +00001475 bootDexJar := module.(interface {
1476 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
1477 }).DexJarBuildPath(ctx)
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001478 if !bootDexJar.Valid() {
Paul Duffin5f148ca2021-06-02 17:24:22 +01001479 fake := android.PathForModuleOut(ctx, fmt.Sprintf("fake/encoded-dex/%s.jar", module.Name()))
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001480 handleMissingDexBootFile(ctx, module, fake, bootDexJar.InvalidReason())
1481 return fake
Paul Duffin5f148ca2021-06-02 17:24:22 +01001482 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001483 return bootDexJar.Path()
Paul Duffin5f148ca2021-06-02 17:24:22 +01001484}
1485
1486// extractEncodedDexJarsFromModules extracts the encoded dex jars from the supplied modules.
1487func extractEncodedDexJarsFromModules(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
1488 encodedDexJarsByModuleName := bootDexJarByModule{}
1489 for _, module := range contents {
1490 path := retrieveEncodedBootDexJarFromModule(ctx, module)
1491 encodedDexJarsByModuleName.addPath(module, path)
1492 }
1493 return encodedDexJarsByModuleName
1494}