blob: 3a58675ec02fe4faa7bd0a82c9a39fe442ef8c65 [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"
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +010022
Paul Duffin9b381ef2021-04-08 23:01:37 +010023 "github.com/google/blueprint"
Paul Duffinc6bb7cf2021-04-08 17:49:27 +010024)
25
26// Contains support for processing hiddenAPI in a modular fashion.
27
Paul Duffin31fad802021-06-18 18:14:25 +010028// HiddenAPIScope encapsulates all the information that the hidden API processing needs about API
29// scopes, i.e. what is called android.SdkKind and apiScope. It does not just use those as they do
30// not provide the information needed by hidden API processing.
31type HiddenAPIScope struct {
32 // The name of the scope, used for debug purposes.
33 name string
34
35 // The corresponding android.SdkKind, used for retrieving paths from java_sdk_library* modules.
36 sdkKind android.SdkKind
37
38 // The option needed to passed to "hiddenapi list".
39 hiddenAPIListOption string
Paul Duffin5cca7c42021-05-26 10:16:01 +010040
41 // The name sof the source stub library modules that contain the API provided by the platform,
42 // i.e. by modules that are not in an APEX.
43 nonUpdatableSourceModule string
44
45 // The names of the prebuilt stub library modules that contain the API provided by the platform,
46 // i.e. by modules that are not in an APEX.
47 nonUpdatablePrebuiltModule string
Paul Duffin31fad802021-06-18 18:14:25 +010048}
49
50// initHiddenAPIScope initializes the scope.
51func initHiddenAPIScope(apiScope *HiddenAPIScope) *HiddenAPIScope {
Paul Duffin5cca7c42021-05-26 10:16:01 +010052 sdkKind := apiScope.sdkKind
53 // The platform does not provide a core platform API.
54 if sdkKind != android.SdkCorePlatform {
55 kindAsString := sdkKind.String()
56 var insert string
57 if sdkKind == android.SdkPublic {
58 insert = ""
59 } else {
60 insert = "." + strings.ReplaceAll(kindAsString, "-", "_")
61 }
62
63 nonUpdatableModule := "android-non-updatable"
64
65 // Construct the name of the android-non-updatable source module for this scope.
66 apiScope.nonUpdatableSourceModule = fmt.Sprintf("%s.stubs%s", nonUpdatableModule, insert)
67
68 prebuiltModuleName := func(name string, kind string) string {
69 return fmt.Sprintf("sdk_%s_current_%s", kind, name)
70 }
71
72 // Construct the name of the android-non-updatable prebuilt module for this scope.
73 apiScope.nonUpdatablePrebuiltModule = prebuiltModuleName(nonUpdatableModule, kindAsString)
74 }
75
Paul Duffin31fad802021-06-18 18:14:25 +010076 return apiScope
77}
78
Paul Duffin5cca7c42021-05-26 10:16:01 +010079// android-non-updatable takes the name of a module and returns a possibly scope specific name of
80// the module.
81func (l *HiddenAPIScope) scopeSpecificStubModule(ctx android.BaseModuleContext, name string) string {
82 // The android-non-updatable is not a java_sdk_library but there are separate stub libraries for
83 // each scope.
84 // TODO(b/192067200): Remove special handling of android-non-updatable.
85 if name == "android-non-updatable" {
86 if ctx.Config().AlwaysUsePrebuiltSdks() {
87 return l.nonUpdatablePrebuiltModule
88 } else {
89 return l.nonUpdatableSourceModule
90 }
91 } else {
92 // Assume that the module is either a java_sdk_library (or equivalent) and so will provide
93 // separate stub jars for each scope or is a java_library (or equivalent) in which case it will
94 // have the same stub jar for each scope.
95 return name
96 }
97}
98
Paul Duffin31fad802021-06-18 18:14:25 +010099func (l *HiddenAPIScope) String() string {
100 return fmt.Sprintf("HiddenAPIScope{%s}", l.name)
101}
102
103var (
104 PublicHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
105 name: "public",
106 sdkKind: android.SdkPublic,
107 hiddenAPIListOption: "--public-stub-classpath",
108 })
109 SystemHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
110 name: "system",
111 sdkKind: android.SdkSystem,
112 hiddenAPIListOption: "--system-stub-classpath",
113 })
114 TestHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
115 name: "test",
116 sdkKind: android.SdkTest,
117 hiddenAPIListOption: "--test-stub-classpath",
118 })
Paul Duffinb51db2e2021-06-21 14:08:08 +0100119 ModuleLibHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
120 name: "module-lib",
121 sdkKind: android.SdkModule,
122 })
Paul Duffin31fad802021-06-18 18:14:25 +0100123 CorePlatformHiddenAPIScope = initHiddenAPIScope(&HiddenAPIScope{
124 name: "core-platform",
125 sdkKind: android.SdkCorePlatform,
126 hiddenAPIListOption: "--core-platform-stub-classpath",
127 })
128
129 // hiddenAPIRelevantSdkKinds lists all the android.SdkKind instances that are needed by the hidden
130 // API processing.
131 //
132 // These are roughly in order from narrowest API surface to widest. Widest means the API stubs
133 // with the biggest API surface, e.g. test is wider than system is wider than public.
134 //
Paul Duffinb51db2e2021-06-21 14:08:08 +0100135 // Core platform is considered wider than system/module-lib because those modules that provide
136 // core platform APIs either do not have any system/module-lib APIs at all, or if they do it is
137 // because the core platform API is being converted to system/module-lib APIs. In either case the
138 // system/module-lib APIs are subsets of the core platform API.
Paul Duffin31fad802021-06-18 18:14:25 +0100139 //
140 // 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 +0100141 // is neither wider or narrower than the module-lib or core platform APIs. However, this works
142 // well enough at the moment.
Paul Duffin31fad802021-06-18 18:14:25 +0100143 // TODO(b/191644675): Correctly reflect the sub/superset relationships between APIs.
144 hiddenAPIScopes = []*HiddenAPIScope{
145 PublicHiddenAPIScope,
146 SystemHiddenAPIScope,
147 TestHiddenAPIScope,
Paul Duffinb51db2e2021-06-21 14:08:08 +0100148 ModuleLibHiddenAPIScope,
Paul Duffin31fad802021-06-18 18:14:25 +0100149 CorePlatformHiddenAPIScope,
150 }
151
152 // The HiddenAPIScope instances that are supported by a java_sdk_library.
153 //
154 // CorePlatformHiddenAPIScope is not used as the java_sdk_library does not have special support
155 // for core_platform API, instead it is implemented as a customized form of PublicHiddenAPIScope.
156 hiddenAPISdkLibrarySupportedScopes = []*HiddenAPIScope{
157 PublicHiddenAPIScope,
158 SystemHiddenAPIScope,
159 TestHiddenAPIScope,
Paul Duffinb51db2e2021-06-21 14:08:08 +0100160 ModuleLibHiddenAPIScope,
Paul Duffin31fad802021-06-18 18:14:25 +0100161 }
162
163 // The HiddenAPIScope instances that are supported by the `hiddenapi list`.
164 hiddenAPIFlagScopes = []*HiddenAPIScope{
165 PublicHiddenAPIScope,
166 SystemHiddenAPIScope,
167 TestHiddenAPIScope,
168 CorePlatformHiddenAPIScope,
169 }
170)
171
Paul Duffin74431d52021-04-21 14:10:42 +0100172type hiddenAPIStubsDependencyTag struct {
173 blueprint.BaseDependencyTag
Paul Duffin31fad802021-06-18 18:14:25 +0100174
175 // The api scope for which this dependency was added.
176 apiScope *HiddenAPIScope
Paul Duffin5cca7c42021-05-26 10:16:01 +0100177
178 // Indicates that the dependency is not for an API provided by the current bootclasspath fragment
179 // but is an additional API provided by a module that is not part of the current bootclasspath
180 // fragment.
181 fromAdditionalDependency bool
Paul Duffin74431d52021-04-21 14:10:42 +0100182}
183
184func (b hiddenAPIStubsDependencyTag) ExcludeFromApexContents() {
185}
186
187func (b hiddenAPIStubsDependencyTag) ReplaceSourceWithPrebuilt() bool {
188 return false
189}
190
Paul Duffin976b0e52021-04-27 23:20:26 +0100191func (b hiddenAPIStubsDependencyTag) SdkMemberType(child android.Module) android.SdkMemberType {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100192 // Do not add additional dependencies to the sdk.
193 if b.fromAdditionalDependency {
194 return nil
195 }
196
Paul Duffin976b0e52021-04-27 23:20:26 +0100197 // If the module is a java_sdk_library then treat it as if it was specific in the java_sdk_libs
198 // property, otherwise treat if it was specified in the java_header_libs property.
199 if javaSdkLibrarySdkMemberType.IsInstance(child) {
200 return javaSdkLibrarySdkMemberType
201 }
202
203 return javaHeaderLibsSdkMemberType
204}
205
206func (b hiddenAPIStubsDependencyTag) ExportMember() bool {
207 // Export the module added via this dependency tag from the sdk.
208 return true
209}
210
Paul Duffin74431d52021-04-21 14:10:42 +0100211// Avoid having to make stubs content explicitly visible to dependent modules.
212//
213// This is a temporary workaround to make it easier to migrate to bootclasspath_fragment modules
214// with proper dependencies.
215// TODO(b/177892522): Remove this and add needed visibility.
216func (b hiddenAPIStubsDependencyTag) ExcludeFromVisibilityEnforcement() {
217}
218
219var _ android.ExcludeFromVisibilityEnforcementTag = hiddenAPIStubsDependencyTag{}
220var _ android.ReplaceSourceWithPrebuilt = hiddenAPIStubsDependencyTag{}
221var _ android.ExcludeFromApexContentsTag = hiddenAPIStubsDependencyTag{}
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100222var _ android.SdkMemberDependencyTag = hiddenAPIStubsDependencyTag{}
Paul Duffin74431d52021-04-21 14:10:42 +0100223
Paul Duffin74431d52021-04-21 14:10:42 +0100224// hiddenAPIComputeMonolithicStubLibModules computes the set of module names that provide stubs
225// needed to produce the hidden API monolithic stub flags file.
Paul Duffin31fad802021-06-18 18:14:25 +0100226func hiddenAPIComputeMonolithicStubLibModules(config android.Config) map[*HiddenAPIScope][]string {
Paul Duffin74431d52021-04-21 14:10:42 +0100227 var publicStubModules []string
228 var systemStubModules []string
229 var testStubModules []string
230 var corePlatformStubModules []string
231
232 if config.AlwaysUsePrebuiltSdks() {
233 // Build configuration mandates using prebuilt stub modules
234 publicStubModules = append(publicStubModules, "sdk_public_current_android")
235 systemStubModules = append(systemStubModules, "sdk_system_current_android")
236 testStubModules = append(testStubModules, "sdk_test_current_android")
237 } else {
238 // Use stub modules built from source
239 publicStubModules = append(publicStubModules, "android_stubs_current")
240 systemStubModules = append(systemStubModules, "android_system_stubs_current")
241 testStubModules = append(testStubModules, "android_test_stubs_current")
242 }
243 // We do not have prebuilts of the core platform api yet
244 corePlatformStubModules = append(corePlatformStubModules, "legacy.core.platform.api.stubs")
245
246 // Allow products to define their own stubs for custom product jars that apps can use.
247 publicStubModules = append(publicStubModules, config.ProductHiddenAPIStubs()...)
248 systemStubModules = append(systemStubModules, config.ProductHiddenAPIStubsSystem()...)
249 testStubModules = append(testStubModules, config.ProductHiddenAPIStubsTest()...)
250 if config.IsEnvTrue("EMMA_INSTRUMENT") {
Paul Duffin098c8782021-05-14 10:45:25 +0100251 // Add jacoco-stubs to public, system and test. It doesn't make any real difference as public
252 // allows everyone access but it is needed to ensure consistent flags between the
253 // bootclasspath fragment generated flags and the platform_bootclasspath generated flags.
Paul Duffin74431d52021-04-21 14:10:42 +0100254 publicStubModules = append(publicStubModules, "jacoco-stubs")
Paul Duffin098c8782021-05-14 10:45:25 +0100255 systemStubModules = append(systemStubModules, "jacoco-stubs")
256 testStubModules = append(testStubModules, "jacoco-stubs")
Paul Duffin74431d52021-04-21 14:10:42 +0100257 }
258
Paul Duffin31fad802021-06-18 18:14:25 +0100259 m := map[*HiddenAPIScope][]string{}
260 m[PublicHiddenAPIScope] = publicStubModules
261 m[SystemHiddenAPIScope] = systemStubModules
262 m[TestHiddenAPIScope] = testStubModules
263 m[CorePlatformHiddenAPIScope] = corePlatformStubModules
Paul Duffin74431d52021-04-21 14:10:42 +0100264 return m
265}
266
267// hiddenAPIAddStubLibDependencies adds dependencies onto the modules specified in
Paul Duffin31fad802021-06-18 18:14:25 +0100268// apiScopeToStubLibModules. It adds them in a well known order and uses a HiddenAPIScope specific
269// tag to identify the source of the dependency.
270func hiddenAPIAddStubLibDependencies(ctx android.BottomUpMutatorContext, apiScopeToStubLibModules map[*HiddenAPIScope][]string) {
Paul Duffin74431d52021-04-21 14:10:42 +0100271 module := ctx.Module()
Paul Duffin31fad802021-06-18 18:14:25 +0100272 for _, apiScope := range hiddenAPIScopes {
273 modules := apiScopeToStubLibModules[apiScope]
274 ctx.AddDependency(module, hiddenAPIStubsDependencyTag{apiScope: apiScope}, modules...)
Paul Duffin74431d52021-04-21 14:10:42 +0100275 }
276}
277
Paul Duffin74431d52021-04-21 14:10:42 +0100278// hiddenAPIRetrieveDexJarBuildPath retrieves the DexJarBuildPath from the specified module, if
279// available, or reports an error.
Paul Duffin10931582021-04-25 10:13:54 +0100280func hiddenAPIRetrieveDexJarBuildPath(ctx android.ModuleContext, module android.Module, kind android.SdkKind) android.Path {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100281 var dexJar OptionalDexJarPath
Paul Duffin10931582021-04-25 10:13:54 +0100282 if sdkLibrary, ok := module.(SdkLibraryDependency); ok {
283 dexJar = sdkLibrary.SdkApiStubDexJar(ctx, kind)
284 } else if j, ok := module.(UsesLibraryDependency); ok {
285 dexJar = j.DexJarBuildPath()
Paul Duffin74431d52021-04-21 14:10:42 +0100286 } else {
287 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 +0100288 return nil
Paul Duffin74431d52021-04-21 14:10:42 +0100289 }
Paul Duffin10931582021-04-25 10:13:54 +0100290
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100291 if !dexJar.Valid() {
292 ctx.ModuleErrorf("dependency %s does not provide a dex jar: %s", module, dexJar.InvalidReason())
293 return nil
Paul Duffin10931582021-04-25 10:13:54 +0100294 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100295 return dexJar.Path()
Paul Duffin74431d52021-04-21 14:10:42 +0100296}
297
Paul Duffinbd88c882022-04-07 23:32:19 +0100298// HIDDENAPI_STUB_FLAGS_IMPL_FLAGS is the set of flags that identify implementation only signatures,
299// i.e. those signatures that are not part of any API (including the hidden API).
300var HIDDENAPI_STUB_FLAGS_IMPL_FLAGS = []string{}
301
302var HIDDENAPI_FLAGS_CSV_IMPL_FLAGS = []string{"blocked"}
303
Paul Duffin4539a372021-06-23 23:20:43 +0100304// buildRuleToGenerateHiddenAPIStubFlagsFile creates a rule to create a hidden API stub flags file.
Paul Duffin74431d52021-04-21 14:10:42 +0100305//
306// The rule is initialized but not built so that the caller can modify it and select an appropriate
307// name.
Paul Duffin67b9d612021-07-21 17:38:47 +0100308func buildRuleToGenerateHiddenAPIStubFlagsFile(ctx android.BuilderContext, name, desc string, outputPath android.WritablePath, bootDexJars android.Paths, input HiddenAPIFlagInput, stubFlagSubsets SignatureCsvSubsets) {
Paul Duffin74431d52021-04-21 14:10:42 +0100309 // Singleton rule which applies hiddenapi on all boot class path dex files.
310 rule := android.NewRuleBuilder(pctx, ctx)
311
312 tempPath := tempPathForRestat(ctx, outputPath)
313
Paul Duffinf1b358c2021-05-17 07:38:47 +0100314 // Find the widest API stubs provided by the fragments on which this depends, if any.
Paul Duffind2b1e0c2021-06-27 20:53:39 +0100315 dependencyStubDexJars := input.DependencyStubDexJarsByScope.StubDexJarsForWidestAPIScope()
Paul Duffin5cca7c42021-05-26 10:16:01 +0100316
317 // Add widest API stubs from the additional dependencies of this, if any.
Paul Duffind2b1e0c2021-06-27 20:53:39 +0100318 dependencyStubDexJars = append(dependencyStubDexJars, input.AdditionalStubDexJarsByScope.StubDexJarsForWidestAPIScope()...)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100319
Paul Duffin74431d52021-04-21 14:10:42 +0100320 command := rule.Command().
321 Tool(ctx.Config().HostToolPath(ctx, "hiddenapi")).
322 Text("list").
Paul Duffinf1b358c2021-05-17 07:38:47 +0100323 FlagForEachInput("--dependency-stub-dex=", dependencyStubDexJars).
Paul Duffin74431d52021-04-21 14:10:42 +0100324 FlagForEachInput("--boot-dex=", bootDexJars)
325
Paul Duffin156b5d32021-06-24 23:06:52 +0100326 // If no module stub flags paths are provided then this must be being called for a
327 // bootclasspath_fragment and not the whole platform_bootclasspath.
Paul Duffin67b9d612021-07-21 17:38:47 +0100328 if stubFlagSubsets == nil {
Paul Duffin156b5d32021-06-24 23:06:52 +0100329 // This is being run on a fragment of the bootclasspath.
330 command.Flag("--fragment")
331 }
332
Paul Duffin31fad802021-06-18 18:14:25 +0100333 // Iterate over the api scopes in a fixed order.
334 for _, apiScope := range hiddenAPIFlagScopes {
335 // Merge in the stub dex jar paths for this api scope from the fragments on which it depends.
336 // They will be needed to resolve dependencies from this fragment's stubs to classes in the
337 // other fragment's APIs.
338 var paths android.Paths
Paul Duffin280a31a2021-06-27 20:28:29 +0100339 paths = append(paths, input.DependencyStubDexJarsByScope.StubDexJarsForScope(apiScope)...)
340 paths = append(paths, input.AdditionalStubDexJarsByScope.StubDexJarsForScope(apiScope)...)
341 paths = append(paths, input.StubDexJarsByScope.StubDexJarsForScope(apiScope)...)
Paul Duffin74431d52021-04-21 14:10:42 +0100342 if len(paths) > 0 {
Paul Duffin31fad802021-06-18 18:14:25 +0100343 option := apiScope.hiddenAPIListOption
344 command.FlagWithInputList(option+"=", paths, ":")
Paul Duffin74431d52021-04-21 14:10:42 +0100345 }
346 }
347
348 // Add the output path.
349 command.FlagWithOutput("--out-api-flags=", tempPath)
350
Paul Duffin2e880972021-06-23 23:29:09 +0100351 // If there are stub flag files that have been generated by fragments on which this depends then
352 // use them to validate the stub flag file generated by the rules created by this method.
Paul Duffin67b9d612021-07-21 17:38:47 +0100353 if len(stubFlagSubsets) > 0 {
Paul Duffinbd88c882022-04-07 23:32:19 +0100354 validFile := buildRuleValidateOverlappingCsvFiles(ctx, name, desc, outputPath, stubFlagSubsets,
355 HIDDENAPI_STUB_FLAGS_IMPL_FLAGS)
Paul Duffin2e880972021-06-23 23:29:09 +0100356
357 // Add the file that indicates that the file generated by this is valid.
358 //
359 // This will cause the validation rule above to be run any time that the output of this rule
360 // changes but the validation will run in parallel with other rules that depend on this file.
361 command.Validation(validFile)
362 }
363
Paul Duffin74431d52021-04-21 14:10:42 +0100364 commitChangeForRestat(rule, tempPath, outputPath)
Paul Duffin4539a372021-06-23 23:20:43 +0100365
366 rule.Build(name, desc)
Paul Duffin74431d52021-04-21 14:10:42 +0100367}
368
Paul Duffin46169772021-04-14 15:01:56 +0100369// HiddenAPIFlagFileProperties contains paths to the flag files that can be used to augment the
370// information obtained from annotations within the source code in order to create the complete set
371// of flags that should be applied to the dex implementation jars on the bootclasspath.
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100372//
373// Each property contains a list of paths. With the exception of the Unsupported_packages the paths
374// of each property reference a plain text file that contains a java signature per line. The flags
375// for each of those signatures will be updated in a property specific way.
376//
377// The Unsupported_packages property contains a list of paths, each of which is a plain text file
378// with one Java package per line. All members of all classes within that package (but not nested
379// packages) will be updated in a property specific way.
Paul Duffin46169772021-04-14 15:01:56 +0100380type HiddenAPIFlagFileProperties struct {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000381 Hidden_api struct {
382 // Marks each signature in the referenced files as being unsupported.
383 Unsupported []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100384
Paul Duffin9b61abb2022-07-27 16:16:54 +0000385 // Marks each signature in the referenced files as being unsupported because it has been
386 // removed. Any conflicts with other flags are ignored.
387 Removed []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100388
Paul Duffin9b61abb2022-07-27 16:16:54 +0000389 // Marks each signature in the referenced files as being supported only for
390 // targetSdkVersion <= R and low priority.
391 Max_target_r_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100392
Paul Duffin9b61abb2022-07-27 16:16:54 +0000393 // Marks each signature in the referenced files as being supported only for
394 // targetSdkVersion <= Q.
395 Max_target_q []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100396
Paul Duffin9b61abb2022-07-27 16:16:54 +0000397 // Marks each signature in the referenced files as being supported only for
398 // targetSdkVersion <= P.
399 Max_target_p []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100400
Paul Duffin9b61abb2022-07-27 16:16:54 +0000401 // Marks each signature in the referenced files as being supported only for
402 // targetSdkVersion <= O
403 // and low priority. Any conflicts with other flags are ignored.
404 Max_target_o_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100405
Paul Duffin9b61abb2022-07-27 16:16:54 +0000406 // Marks each signature in the referenced files as being blocked.
407 Blocked []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100408
Paul Duffin9b61abb2022-07-27 16:16:54 +0000409 // Marks each signature in every package in the referenced files as being unsupported.
410 Unsupported_packages []string `android:"path"`
411 }
Paul Duffin702210b2021-04-08 20:12:41 +0100412}
413
Paul Duffine3dc6602021-04-14 09:50:43 +0100414type hiddenAPIFlagFileCategory struct {
Paul Duffin524c82c2021-06-09 14:39:28 +0100415 // PropertyName is the name of the property for this category.
416 PropertyName string
Paul Duffine3dc6602021-04-14 09:50:43 +0100417
Paul Duffincc17bfe2021-04-19 13:21:20 +0100418 // propertyValueReader retrieves the value of the property for this category from the set of
Paul Duffine3dc6602021-04-14 09:50:43 +0100419 // properties.
Paul Duffincc17bfe2021-04-19 13:21:20 +0100420 propertyValueReader func(properties *HiddenAPIFlagFileProperties) []string
Paul Duffine3dc6602021-04-14 09:50:43 +0100421
422 // commandMutator adds the appropriate command line options for this category to the supplied
423 // command
424 commandMutator func(command *android.RuleBuilderCommand, path android.Path)
425}
426
Paul Duffin32cf58a2021-05-18 16:32:50 +0100427// The flag file category for removed members of the API.
428//
Paul Duffin524c82c2021-06-09 14:39:28 +0100429// This is extracted from HiddenAPIFlagFileCategories as it is needed to add the dex signatures
Paul Duffin32cf58a2021-05-18 16:32:50 +0100430// list of removed API members that are generated automatically from the removed.txt files provided
431// by API stubs.
432var hiddenAPIRemovedFlagFileCategory = &hiddenAPIFlagFileCategory{
433 // See HiddenAPIFlagFileProperties.Removed
Paul Duffin524c82c2021-06-09 14:39:28 +0100434 PropertyName: "removed",
Paul Duffin32cf58a2021-05-18 16:32:50 +0100435 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000436 return properties.Hidden_api.Removed
Paul Duffin32cf58a2021-05-18 16:32:50 +0100437 },
438 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
439 command.FlagWithInput("--unsupported ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "removed")
440 },
441}
442
Paul Duffin524c82c2021-06-09 14:39:28 +0100443var HiddenAPIFlagFileCategories = []*hiddenAPIFlagFileCategory{
Paul Duffin46169772021-04-14 15:01:56 +0100444 // See HiddenAPIFlagFileProperties.Unsupported
Paul Duffine3dc6602021-04-14 09:50:43 +0100445 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100446 PropertyName: "unsupported",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100447 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000448 return properties.Hidden_api.Unsupported
Paul Duffine3dc6602021-04-14 09:50:43 +0100449 },
450 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
451 command.FlagWithInput("--unsupported ", path)
452 },
453 },
Paul Duffin32cf58a2021-05-18 16:32:50 +0100454 hiddenAPIRemovedFlagFileCategory,
Paul Duffin46169772021-04-14 15:01:56 +0100455 // See HiddenAPIFlagFileProperties.Max_target_r_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100456 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100457 PropertyName: "max_target_r_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100458 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000459 return properties.Hidden_api.Max_target_r_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100460 },
461 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
462 command.FlagWithInput("--max-target-r ", path).FlagWithArg("--tag ", "lo-prio")
463 },
464 },
Paul Duffin46169772021-04-14 15:01:56 +0100465 // See HiddenAPIFlagFileProperties.Max_target_q
Paul Duffine3dc6602021-04-14 09:50:43 +0100466 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100467 PropertyName: "max_target_q",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100468 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000469 return properties.Hidden_api.Max_target_q
Paul Duffine3dc6602021-04-14 09:50:43 +0100470 },
471 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
472 command.FlagWithInput("--max-target-q ", path)
473 },
474 },
Paul Duffin46169772021-04-14 15:01:56 +0100475 // See HiddenAPIFlagFileProperties.Max_target_p
Paul Duffine3dc6602021-04-14 09:50:43 +0100476 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100477 PropertyName: "max_target_p",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100478 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000479 return properties.Hidden_api.Max_target_p
Paul Duffine3dc6602021-04-14 09:50:43 +0100480 },
481 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
482 command.FlagWithInput("--max-target-p ", path)
483 },
484 },
Paul Duffin46169772021-04-14 15:01:56 +0100485 // See HiddenAPIFlagFileProperties.Max_target_o_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100486 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100487 PropertyName: "max_target_o_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100488 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000489 return properties.Hidden_api.Max_target_o_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100490 },
491 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
492 command.FlagWithInput("--max-target-o ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "lo-prio")
493 },
494 },
Paul Duffin46169772021-04-14 15:01:56 +0100495 // See HiddenAPIFlagFileProperties.Blocked
Paul Duffine3dc6602021-04-14 09:50:43 +0100496 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100497 PropertyName: "blocked",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100498 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000499 return properties.Hidden_api.Blocked
Paul Duffine3dc6602021-04-14 09:50:43 +0100500 },
501 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
502 command.FlagWithInput("--blocked ", path)
503 },
504 },
Paul Duffin46169772021-04-14 15:01:56 +0100505 // See HiddenAPIFlagFileProperties.Unsupported_packages
Paul Duffine3dc6602021-04-14 09:50:43 +0100506 {
Paul Duffin524c82c2021-06-09 14:39:28 +0100507 PropertyName: "unsupported_packages",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100508 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffin9b61abb2022-07-27 16:16:54 +0000509 return properties.Hidden_api.Unsupported_packages
Paul Duffine3dc6602021-04-14 09:50:43 +0100510 },
511 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
512 command.FlagWithInput("--unsupported ", path).Flag("--packages ")
513 },
514 },
Paul Duffin702210b2021-04-08 20:12:41 +0100515}
516
Paul Duffin438eb572021-05-21 16:58:23 +0100517// FlagFilesByCategory maps a hiddenAPIFlagFileCategory to the paths to the files in that category.
518type FlagFilesByCategory map[*hiddenAPIFlagFileCategory]android.Paths
519
520// append appends the supplied flags files to the corresponding category in this map.
521func (s FlagFilesByCategory) append(other FlagFilesByCategory) {
Paul Duffin524c82c2021-06-09 14:39:28 +0100522 for _, category := range HiddenAPIFlagFileCategories {
Paul Duffin438eb572021-05-21 16:58:23 +0100523 s[category] = append(s[category], other[category]...)
524 }
525}
526
Paul Duffinaf99afa2021-05-21 22:18:56 +0100527// HiddenAPIInfo contains information provided by the hidden API processing.
Paul Duffin2fef1362021-04-15 13:32:00 +0100528//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100529// That includes paths resolved from HiddenAPIFlagFileProperties and also generated by hidden API
530// processing.
531type HiddenAPIInfo struct {
Paul Duffin438eb572021-05-21 16:58:23 +0100532 // FlagFilesByCategory maps from the flag file category to the paths containing information for
533 // that category.
534 FlagFilesByCategory FlagFilesByCategory
Paul Duffin2fef1362021-04-15 13:32:00 +0100535
Paul Duffin280a31a2021-06-27 20:28:29 +0100536 // The paths to the stub dex jars for each of the *HiddenAPIScope in hiddenAPIScopes provided by
537 // this fragment and the fragments on which this depends.
538 TransitiveStubDexJarsByScope StubDexJarsByModule
Paul Duffin18cf1972021-05-21 22:46:59 +0100539
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100540 // The output from the hidden API processing needs to be made available to other modules.
541 HiddenAPIFlagOutput
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100542}
Paul Duffin702210b2021-04-08 20:12:41 +0100543
Paul Duffinf1b358c2021-05-17 07:38:47 +0100544func newHiddenAPIInfo() *HiddenAPIInfo {
545 info := HiddenAPIInfo{
Paul Duffin31fad802021-06-18 18:14:25 +0100546 FlagFilesByCategory: FlagFilesByCategory{},
Paul Duffin280a31a2021-06-27 20:28:29 +0100547 TransitiveStubDexJarsByScope: StubDexJarsByModule{},
Paul Duffinf1b358c2021-05-17 07:38:47 +0100548 }
549 return &info
550}
551
552func (i *HiddenAPIInfo) mergeFromFragmentDeps(ctx android.ModuleContext, fragments []android.Module) {
553 // Merge all the information from the fragments. The fragments form a DAG so it is possible that
554 // this will introduce duplicates so they will be resolved after processing all the fragments.
555 for _, fragment := range fragments {
556 if ctx.OtherModuleHasProvider(fragment, HiddenAPIInfoProvider) {
557 info := ctx.OtherModuleProvider(fragment, HiddenAPIInfoProvider).(HiddenAPIInfo)
Paul Duffin280a31a2021-06-27 20:28:29 +0100558 i.TransitiveStubDexJarsByScope.addStubDexJarsByModule(info.TransitiveStubDexJarsByScope)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100559 }
560 }
Paul Duffinf1b358c2021-05-17 07:38:47 +0100561}
562
Paul Duffin191be3a2021-08-10 16:14:16 +0100563// StubFlagSubset returns a SignatureCsvSubset that contains a path to a filtered-stub-flags.csv
564// file and a path to a signature-patterns.csv file that defines a subset of the monolithic stub
565// flags file, i.e. out/soong/hiddenapi/hiddenapi-stub-flags.txt, against which it will be compared.
Paul Duffin67b9d612021-07-21 17:38:47 +0100566func (i *HiddenAPIInfo) StubFlagSubset() SignatureCsvSubset {
Paul Duffin191be3a2021-08-10 16:14:16 +0100567 return SignatureCsvSubset{i.FilteredStubFlagsPath, i.SignaturePatternsPath}
Paul Duffin67b9d612021-07-21 17:38:47 +0100568}
569
Paul Duffin191be3a2021-08-10 16:14:16 +0100570// FlagSubset returns a SignatureCsvSubset that contains a path to a filtered-flags.csv file and a
Paul Duffin67b9d612021-07-21 17:38:47 +0100571// path to a signature-patterns.csv file that defines a subset of the monolithic flags file, i.e.
572// out/soong/hiddenapi/hiddenapi-flags.csv, against which it will be compared.
573func (i *HiddenAPIInfo) FlagSubset() SignatureCsvSubset {
Paul Duffin191be3a2021-08-10 16:14:16 +0100574 return SignatureCsvSubset{i.FilteredFlagsPath, i.SignaturePatternsPath}
Paul Duffin67b9d612021-07-21 17:38:47 +0100575}
576
Paul Duffinaf99afa2021-05-21 22:18:56 +0100577var HiddenAPIInfoProvider = blueprint.NewProvider(HiddenAPIInfo{})
Paul Duffin9b381ef2021-04-08 23:01:37 +0100578
Paul Duffin280a31a2021-06-27 20:28:29 +0100579// ModuleStubDexJars contains the stub dex jars provided by a single module.
580//
581// It maps a *HiddenAPIScope to the path to stub dex jars appropriate for that scope. See
582// hiddenAPIScopes for a list of the acceptable *HiddenAPIScope values.
583type ModuleStubDexJars map[*HiddenAPIScope]android.Path
Paul Duffin1352f7c2021-05-21 22:18:49 +0100584
Paul Duffin280a31a2021-06-27 20:28:29 +0100585// stubDexJarForWidestAPIScope returns the stub dex jars for the widest API scope provided by this
Paul Duffin1352f7c2021-05-21 22:18:49 +0100586// map.
Paul Duffin280a31a2021-06-27 20:28:29 +0100587//
588// The relative width of APIs is determined by their order in hiddenAPIScopes.
589func (s ModuleStubDexJars) stubDexJarForWidestAPIScope() android.Path {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100590 for i := len(hiddenAPIScopes) - 1; i >= 0; i-- {
591 apiScope := hiddenAPIScopes[i]
Paul Duffin280a31a2021-06-27 20:28:29 +0100592 if stubsForAPIScope, ok := s[apiScope]; ok {
Paul Duffin5cca7c42021-05-26 10:16:01 +0100593 return stubsForAPIScope
594 }
595 }
596
597 return nil
598}
599
Paul Duffin280a31a2021-06-27 20:28:29 +0100600// StubDexJarsByModule contains the stub dex jars provided by a set of modules.
601//
602// It maps a module name to the path to the stub dex jars provided by that module.
603type StubDexJarsByModule map[string]ModuleStubDexJars
604
605// addStubDexJar adds a stub dex jar path provided by the specified module for the specified scope.
606func (s StubDexJarsByModule) addStubDexJar(ctx android.ModuleContext, module android.Module, scope *HiddenAPIScope, stubDexJar android.Path) {
607 name := android.RemoveOptionalPrebuiltPrefix(module.Name())
Paul Duffin3f0290e2021-06-30 18:25:36 +0100608
609 // Each named module provides one dex jar for each scope. However, in some cases different API
610 // versions of a single classes are provided by separate modules. e.g. the core platform
611 // version of java.lang.Object is provided by the legacy.art.module.platform.api module but the
612 // public version is provided by the art.module.public.api module. In those cases it is necessary
613 // to treat all those modules as they were the same name, otherwise it will result in multiple
614 // definitions of a single class being passed to hidden API processing which will cause an error.
Paul Duffin280a31a2021-06-27 20:28:29 +0100615 if name == scope.nonUpdatablePrebuiltModule || name == scope.nonUpdatableSourceModule {
616 // Treat all *android-non-updatable* modules as if they were part of an android-non-updatable
617 // java_sdk_library.
618 // TODO(b/192067200): Remove once android-non-updatable is a java_sdk_library or equivalent.
619 name = "android-non-updatable"
620 } else if name == "legacy.art.module.platform.api" {
621 // Treat legacy.art.module.platform.api as if it was an API scope provided by the
622 // art.module.public.api java_sdk_library which will be the case once the former has been
623 // migrated to a module_lib API.
624 name = "art.module.public.api"
625 } else if name == "legacy.i18n.module.platform.api" {
626 // Treat legacy.i18n.module.platform.api as if it was an API scope provided by the
627 // i18n.module.public.api java_sdk_library which will be the case once the former has been
628 // migrated to a module_lib API.
629 name = "i18n.module.public.api"
630 } else if name == "conscrypt.module.platform.api" {
631 // Treat conscrypt.module.platform.api as if it was an API scope provided by the
632 // conscrypt.module.public.api java_sdk_library which will be the case once the former has been
633 // migrated to a module_lib API.
634 name = "conscrypt.module.public.api"
Paul Duffin3f0290e2021-06-30 18:25:36 +0100635 } else if d, ok := module.(SdkLibraryComponentDependency); ok {
636 sdkLibraryName := d.SdkLibraryName()
637 if sdkLibraryName != nil {
638 // The module is a component of a java_sdk_library so use the name of the java_sdk_library.
639 // e.g. if this module is `foo.system.stubs` and is part of the `foo` java_sdk_library then
640 // use `foo` as the name.
641 name = *sdkLibraryName
642 }
Paul Duffin280a31a2021-06-27 20:28:29 +0100643 }
644 stubDexJarsByScope := s[name]
645 if stubDexJarsByScope == nil {
646 stubDexJarsByScope = ModuleStubDexJars{}
647 s[name] = stubDexJarsByScope
648 }
649 stubDexJarsByScope[scope] = stubDexJar
650}
651
652// addStubDexJarsByModule adds the stub dex jars in the supplied StubDexJarsByModule to this map.
653func (s StubDexJarsByModule) addStubDexJarsByModule(other StubDexJarsByModule) {
654 for module, stubDexJarsByScope := range other {
655 s[module] = stubDexJarsByScope
656 }
657}
658
659// StubDexJarsForWidestAPIScope returns a list of stub dex jars containing the widest API scope
660// provided by each module.
661//
662// The relative width of APIs is determined by their order in hiddenAPIScopes.
663func (s StubDexJarsByModule) StubDexJarsForWidestAPIScope() android.Paths {
664 stubDexJars := android.Paths{}
665 modules := android.SortedStringKeys(s)
666 for _, module := range modules {
667 stubDexJarsByScope := s[module]
668
669 stubDexJars = append(stubDexJars, stubDexJarsByScope.stubDexJarForWidestAPIScope())
670 }
671
672 return stubDexJars
673}
674
675// StubDexJarsForScope returns a list of stub dex jars containing the stub dex jars provided by each
676// module for the specified scope.
677//
678// If a module does not provide a stub dex jar for the supplied scope then it does not contribute to
679// the returned list.
680func (s StubDexJarsByModule) StubDexJarsForScope(scope *HiddenAPIScope) android.Paths {
681 stubDexJars := android.Paths{}
682 modules := android.SortedStringKeys(s)
683 for _, module := range modules {
684 stubDexJarsByScope := s[module]
685 // Not every module will have the same set of
686 if jars, ok := stubDexJarsByScope[scope]; ok {
687 stubDexJars = append(stubDexJars, jars)
688 }
689 }
690
691 return stubDexJars
692}
693
Paul Duffin1e9e9382022-07-27 15:55:06 +0000694type HiddenAPIPropertyInfo struct {
Paul Duffin1352f7c2021-05-21 22:18:49 +0100695 // FlagFilesByCategory contains the flag files that override the initial flags that are derived
696 // from the stub dex files.
697 FlagFilesByCategory FlagFilesByCategory
698
Paul Duffin1e9e9382022-07-27 15:55:06 +0000699 // See HiddenAPIFlagFileProperties.Package_prefixes
700 PackagePrefixes []string
701
702 // See HiddenAPIFlagFileProperties.Single_packages
703 SinglePackages []string
704
705 // See HiddenAPIFlagFileProperties.Split_packages
706 SplitPackages []string
707}
708
709// newHiddenAPIPropertyInfo creates a new initialized HiddenAPIPropertyInfo struct.
710func newHiddenAPIPropertyInfo() HiddenAPIPropertyInfo {
711 return HiddenAPIPropertyInfo{
712 FlagFilesByCategory: FlagFilesByCategory{},
713 }
714}
715
716// extractFlagFilesFromProperties extracts the paths to flag files that are specified in the
717// supplied properties and stores them in this struct.
718func (i *HiddenAPIPropertyInfo) extractFlagFilesFromProperties(ctx android.ModuleContext, p *HiddenAPIFlagFileProperties) {
719 for _, category := range HiddenAPIFlagFileCategories {
720 paths := android.PathsForModuleSrc(ctx, category.propertyValueReader(p))
721 i.FlagFilesByCategory[category] = paths
722 }
723}
724
725// extractPackageRulesFromProperties extracts the package rules that are specified in the supplied
726// properties and stores them in this struct.
727func (i *HiddenAPIPropertyInfo) extractPackageRulesFromProperties(p *HiddenAPIPackageProperties) {
728 i.PackagePrefixes = p.Hidden_api.Package_prefixes
729 i.SinglePackages = p.Hidden_api.Single_packages
730 i.SplitPackages = p.Hidden_api.Split_packages
731}
732
733// HiddenAPIFlagInput encapsulates information obtained from a module and its dependencies that are
734// needed for hidden API flag generation.
735type HiddenAPIFlagInput struct {
736 HiddenAPIPropertyInfo
737
Paul Duffin31fad802021-06-18 18:14:25 +0100738 // StubDexJarsByScope contains the stub dex jars for different *HiddenAPIScope and which determine
Paul Duffin1352f7c2021-05-21 22:18:49 +0100739 // the initial flags for each dex member.
Paul Duffin280a31a2021-06-27 20:28:29 +0100740 StubDexJarsByScope StubDexJarsByModule
Paul Duffinf1b358c2021-05-17 07:38:47 +0100741
Paul Duffin31fad802021-06-18 18:14:25 +0100742 // DependencyStubDexJarsByScope contains the stub dex jars provided by the fragments on which this
743 // depends. It is the result of merging HiddenAPIInfo.TransitiveStubDexJarsByScope from each
Paul Duffinf1b358c2021-05-17 07:38:47 +0100744 // fragment on which this depends.
Paul Duffin280a31a2021-06-27 20:28:29 +0100745 DependencyStubDexJarsByScope StubDexJarsByModule
Paul Duffin32cf58a2021-05-18 16:32:50 +0100746
Paul Duffin5cca7c42021-05-26 10:16:01 +0100747 // AdditionalStubDexJarsByScope contains stub dex jars provided by other modules in addition to
748 // the ones that are obtained from fragments on which this depends.
749 //
750 // These are kept separate from stub dex jars in HiddenAPIFlagInput.DependencyStubDexJarsByScope
751 // as there are not propagated transitively to other fragments that depend on this.
Paul Duffin280a31a2021-06-27 20:28:29 +0100752 AdditionalStubDexJarsByScope StubDexJarsByModule
Paul Duffin5cca7c42021-05-26 10:16:01 +0100753
Paul Duffin32cf58a2021-05-18 16:32:50 +0100754 // RemovedTxtFiles is the list of removed.txt files provided by java_sdk_library modules that are
755 // specified in the bootclasspath_fragment's stub_libs and contents properties.
756 RemovedTxtFiles android.Paths
Paul Duffin1352f7c2021-05-21 22:18:49 +0100757}
758
Paul Duffin1e9e9382022-07-27 15:55:06 +0000759// newHiddenAPIFlagInput creates a new initialized HiddenAPIFlagInput struct.
Paul Duffin1352f7c2021-05-21 22:18:49 +0100760func newHiddenAPIFlagInput() HiddenAPIFlagInput {
761 input := HiddenAPIFlagInput{
Paul Duffin1e9e9382022-07-27 15:55:06 +0000762 HiddenAPIPropertyInfo: newHiddenAPIPropertyInfo(),
Paul Duffin280a31a2021-06-27 20:28:29 +0100763 StubDexJarsByScope: StubDexJarsByModule{},
764 DependencyStubDexJarsByScope: StubDexJarsByModule{},
765 AdditionalStubDexJarsByScope: StubDexJarsByModule{},
Paul Duffin1352f7c2021-05-21 22:18:49 +0100766 }
767
768 return input
769}
770
771// gatherStubLibInfo gathers information from the stub libs needed by hidden API processing from the
772// dependencies added in hiddenAPIAddStubLibDependencies.
773//
774// That includes paths to the stub dex jars as well as paths to the *removed.txt files.
775func (i *HiddenAPIFlagInput) gatherStubLibInfo(ctx android.ModuleContext, contents []android.Module) {
Paul Duffin31fad802021-06-18 18:14:25 +0100776 addFromModule := func(ctx android.ModuleContext, module android.Module, apiScope *HiddenAPIScope) {
777 sdkKind := apiScope.sdkKind
778 dexJar := hiddenAPIRetrieveDexJarBuildPath(ctx, module, sdkKind)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100779 if dexJar != nil {
Paul Duffin280a31a2021-06-27 20:28:29 +0100780 i.StubDexJarsByScope.addStubDexJar(ctx, module, apiScope, dexJar)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100781 }
Paul Duffin32cf58a2021-05-18 16:32:50 +0100782
783 if sdkLibrary, ok := module.(SdkLibraryDependency); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100784 removedTxtFile := sdkLibrary.SdkRemovedTxtFile(ctx, sdkKind)
Paul Duffin32cf58a2021-05-18 16:32:50 +0100785 i.RemovedTxtFiles = append(i.RemovedTxtFiles, removedTxtFile.AsPaths()...)
786 }
Paul Duffin1352f7c2021-05-21 22:18:49 +0100787 }
788
789 // If the contents includes any java_sdk_library modules then add them to the stubs.
790 for _, module := range contents {
791 if _, ok := module.(SdkLibraryDependency); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100792 // Add information for every possible API scope needed by hidden API.
793 for _, apiScope := range hiddenAPISdkLibrarySupportedScopes {
794 addFromModule(ctx, module, apiScope)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100795 }
796 }
797 }
798
Paul Duffind061d402021-06-07 21:36:01 +0100799 ctx.VisitDirectDeps(func(module android.Module) {
Paul Duffin1352f7c2021-05-21 22:18:49 +0100800 tag := ctx.OtherModuleDependencyTag(module)
801 if hiddenAPIStubsTag, ok := tag.(hiddenAPIStubsDependencyTag); ok {
Paul Duffin31fad802021-06-18 18:14:25 +0100802 apiScope := hiddenAPIStubsTag.apiScope
Paul Duffin5cca7c42021-05-26 10:16:01 +0100803 if hiddenAPIStubsTag.fromAdditionalDependency {
804 dexJar := hiddenAPIRetrieveDexJarBuildPath(ctx, module, apiScope.sdkKind)
805 if dexJar != nil {
Paul Duffin280a31a2021-06-27 20:28:29 +0100806 i.AdditionalStubDexJarsByScope.addStubDexJar(ctx, module, apiScope, dexJar)
Paul Duffin5cca7c42021-05-26 10:16:01 +0100807 }
808 } else {
809 addFromModule(ctx, module, apiScope)
810 }
Paul Duffin1352f7c2021-05-21 22:18:49 +0100811 }
812 })
813
814 // Normalize the paths, i.e. remove duplicates and sort.
Paul Duffin32cf58a2021-05-18 16:32:50 +0100815 i.RemovedTxtFiles = android.SortedUniquePaths(i.RemovedTxtFiles)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100816}
817
Paul Duffin280a31a2021-06-27 20:28:29 +0100818func (i *HiddenAPIFlagInput) transitiveStubDexJarsByScope() StubDexJarsByModule {
Paul Duffin31fad802021-06-18 18:14:25 +0100819 transitive := i.DependencyStubDexJarsByScope
Paul Duffin280a31a2021-06-27 20:28:29 +0100820 transitive.addStubDexJarsByModule(i.StubDexJarsByScope)
Paul Duffinf1b358c2021-05-17 07:38:47 +0100821 return transitive
822}
823
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100824// HiddenAPIFlagOutput contains paths to output files from the hidden API flag generation for a
825// bootclasspath_fragment module.
826type HiddenAPIFlagOutput struct {
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100827 // The path to the generated annotation-flags.csv file.
828 AnnotationFlagsPath android.Path
829
830 // The path to the generated metadata.csv file.
831 MetadataPath android.Path
832
833 // The path to the generated index.csv file.
834 IndexPath android.Path
835
Paul Duffin191be3a2021-08-10 16:14:16 +0100836 // The path to the generated stub-flags.csv file.
837 StubFlagsPath android.Path
838
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100839 // The path to the generated all-flags.csv file.
840 AllFlagsPath android.Path
Paul Duffin67b9d612021-07-21 17:38:47 +0100841
842 // The path to the generated signature-patterns.txt file which defines the subset of the
843 // monolithic hidden API files provided in this.
844 SignaturePatternsPath android.Path
Paul Duffin191be3a2021-08-10 16:14:16 +0100845
846 // The path to the generated filtered-stub-flags.csv file.
847 FilteredStubFlagsPath android.Path
848
849 // The path to the generated filtered-flags.csv file.
850 FilteredFlagsPath android.Path
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100851}
852
Paul Duffin5f148ca2021-06-02 17:24:22 +0100853// bootDexJarByModule is a map from base module name (without prebuilt_ prefix) to the boot dex
854// path.
855type bootDexJarByModule map[string]android.Path
856
857// addPath adds the path for a module to the map.
858func (b bootDexJarByModule) addPath(module android.Module, path android.Path) {
859 b[android.RemoveOptionalPrebuiltPrefix(module.Name())] = path
860}
861
Paul Duffine5218812021-06-07 13:28:19 +0100862// bootDexJars returns the boot dex jar paths sorted by their keys.
863func (b bootDexJarByModule) bootDexJars() android.Paths {
864 paths := android.Paths{}
865 for _, k := range android.SortedStringKeys(b) {
866 paths = append(paths, b[k])
867 }
868 return paths
869}
870
Paul Duffin7f872162021-06-17 19:33:24 +0100871// bootDexJarsWithoutCoverage returns the boot dex jar paths sorted by their keys without coverage
872// libraries if present.
873func (b bootDexJarByModule) bootDexJarsWithoutCoverage() android.Paths {
874 paths := android.Paths{}
875 for _, k := range android.SortedStringKeys(b) {
876 if k == "jacocoagent" {
877 continue
878 }
879 paths = append(paths, b[k])
880 }
881 return paths
882}
883
Paul Duffine5218812021-06-07 13:28:19 +0100884// HiddenAPIOutput encapsulates the output from the hidden API processing.
885type HiddenAPIOutput struct {
886 HiddenAPIFlagOutput
887
888 // The map from base module name to the path to the encoded boot dex file.
889 EncodedBootDexFilesByModule bootDexJarByModule
890}
891
Paul Duffindfa10832021-05-13 17:31:51 +0100892// pathForValidation creates a path of the same type as the supplied type but with a name of
893// <path>.valid.
894//
895// e.g. If path is an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv then this will return
896// an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv.valid
897func pathForValidation(ctx android.PathContext, path android.WritablePath) android.WritablePath {
898 extWithoutLeadingDot := strings.TrimPrefix(path.Ext(), ".")
899 return path.ReplaceExtension(ctx, extWithoutLeadingDot+".valid")
900}
901
Paul Duffin2fef1362021-04-15 13:32:00 +0100902// buildRuleToGenerateHiddenApiFlags creates a rule to create the monolithic hidden API flags from
903// the flags from all the modules, the stub flags, augmented with some additional configuration
904// files.
Paul Duffin702210b2021-04-08 20:12:41 +0100905//
906// baseFlagsPath is the path to the flags file containing all the information from the stubs plus
907// an entry for every single member in the dex implementation jars of the individual modules. Every
908// signature in any of the other files MUST be included in this file.
909//
Paul Duffin537ea3d2021-05-14 10:38:00 +0100910// annotationFlags is the path to the annotation flags file generated from annotation information
911// in each module.
Paul Duffin702210b2021-04-08 20:12:41 +0100912//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100913// hiddenAPIInfo is a struct containing paths to files that augment the information provided by
Paul Duffin537ea3d2021-05-14 10:38:00 +0100914// the annotationFlags.
Paul Duffin32cf58a2021-05-18 16:32:50 +0100915func buildRuleToGenerateHiddenApiFlags(ctx android.BuilderContext, name, desc string,
Paul Duffind061d402021-06-07 21:36:01 +0100916 outputPath android.WritablePath, baseFlagsPath android.Path, annotationFlagPaths android.Paths,
Paul Duffin67b9d612021-07-21 17:38:47 +0100917 flagFilesByCategory FlagFilesByCategory, flagSubsets SignatureCsvSubsets, generatedRemovedDexSignatures android.OptionalPath) {
Paul Duffindfa10832021-05-13 17:31:51 +0100918
Paul Duffindfa10832021-05-13 17:31:51 +0100919 // Create the rule that will generate the flag files.
Paul Duffind3c15132021-04-21 22:12:35 +0100920 tempPath := tempPathForRestat(ctx, outputPath)
Paul Duffin702210b2021-04-08 20:12:41 +0100921 rule := android.NewRuleBuilder(pctx, ctx)
922 command := rule.Command().
923 BuiltTool("generate_hiddenapi_lists").
924 FlagWithInput("--csv ", baseFlagsPath).
Paul Duffind061d402021-06-07 21:36:01 +0100925 Inputs(annotationFlagPaths).
Paul Duffin702210b2021-04-08 20:12:41 +0100926 FlagWithOutput("--output ", tempPath)
927
Paul Duffine3dc6602021-04-14 09:50:43 +0100928 // Add the options for the different categories of flag files.
Paul Duffin524c82c2021-06-09 14:39:28 +0100929 for _, category := range HiddenAPIFlagFileCategories {
Paul Duffin438eb572021-05-21 16:58:23 +0100930 paths := flagFilesByCategory[category]
Paul Duffine3dc6602021-04-14 09:50:43 +0100931 for _, path := range paths {
932 category.commandMutator(command, path)
933 }
Paul Duffin702210b2021-04-08 20:12:41 +0100934 }
935
Paul Duffin32cf58a2021-05-18 16:32:50 +0100936 // If available then pass the automatically generated file containing dex signatures of removed
937 // API members to the rule so they can be marked as removed.
938 if generatedRemovedDexSignatures.Valid() {
939 hiddenAPIRemovedFlagFileCategory.commandMutator(command, generatedRemovedDexSignatures.Path())
940 }
941
Paul Duffin702210b2021-04-08 20:12:41 +0100942 commitChangeForRestat(rule, tempPath, outputPath)
943
Paul Duffin2e880972021-06-23 23:29:09 +0100944 // If there are flag files that have been generated by fragments on which this depends then use
945 // them to validate the flag file generated by the rules created by this method.
Paul Duffin67b9d612021-07-21 17:38:47 +0100946 if len(flagSubsets) > 0 {
Paul Duffinbd88c882022-04-07 23:32:19 +0100947 validFile := buildRuleValidateOverlappingCsvFiles(ctx, name, desc, outputPath, flagSubsets,
948 HIDDENAPI_FLAGS_CSV_IMPL_FLAGS)
Paul Duffin2e880972021-06-23 23:29:09 +0100949
Paul Duffindfa10832021-05-13 17:31:51 +0100950 // Add the file that indicates that the file generated by this is valid.
951 //
952 // This will cause the validation rule above to be run any time that the output of this rule
953 // changes but the validation will run in parallel with other rules that depend on this file.
954 command.Validation(validFile)
955 }
956
Paul Duffin2fef1362021-04-15 13:32:00 +0100957 rule.Build(name, desc)
958}
959
Paul Duffin67b9d612021-07-21 17:38:47 +0100960// SignatureCsvSubset describes a subset of a monolithic flags file, i.e. either
961// out/soong/hiddenapi/hiddenapi-stub-flags.txt or out/soong/hiddenapi/hiddenapi-flags.csv
962type SignatureCsvSubset struct {
963 // The path to the CSV file containing hidden API flags.
964 //
965 // It has the dex member signature as the first column, with flags, one per column, in the
966 // subsequent columns.
967 CsvFile android.Path
968
969 // The path to the CSV file containing the signature patterns.
970 //
971 // It is a single column CSV file with the column containing a signature pattern.
972 SignaturePatternsFile android.Path
973}
974
975type SignatureCsvSubsets []SignatureCsvSubset
976
977func (s SignatureCsvSubsets) RelativeToTop() []string {
978 result := []string{}
979 for _, subset := range s {
980 result = append(result, fmt.Sprintf("%s:%s", subset.CsvFile.RelativeToTop(), subset.SignaturePatternsFile.RelativeToTop()))
981 }
982 return result
983}
984
985// buildRuleSignaturePatternsFile creates a rule to generate a file containing the set of signature
986// patterns that will select a subset of the monolithic flags.
Paul Duffin846beb72022-03-15 17:45:57 +0000987func buildRuleSignaturePatternsFile(
988 ctx android.ModuleContext, flagsPath android.Path,
989 splitPackages []string, packagePrefixes []string, singlePackages []string) android.Path {
Paul Duffin67b9d612021-07-21 17:38:47 +0100990 patternsFile := android.PathForModuleOut(ctx, "modular-hiddenapi", "signature-patterns.csv")
991 // Create a rule to validate the output from the following rule.
992 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffin1e18e982021-08-03 15:42:27 +0100993
994 // Quote any * in the packages to avoid them being expanded by the shell.
995 quotedSplitPackages := []string{}
996 for _, pkg := range splitPackages {
997 quotedSplitPackages = append(quotedSplitPackages, strings.ReplaceAll(pkg, "*", "\\*"))
998 }
999
Paul Duffin67b9d612021-07-21 17:38:47 +01001000 rule.Command().
1001 BuiltTool("signature_patterns").
1002 FlagWithInput("--flags ", flagsPath).
Paul Duffin1e18e982021-08-03 15:42:27 +01001003 FlagForEachArg("--split-package ", quotedSplitPackages).
1004 FlagForEachArg("--package-prefix ", packagePrefixes).
Paul Duffin846beb72022-03-15 17:45:57 +00001005 FlagForEachArg("--single-package ", singlePackages).
Paul Duffin67b9d612021-07-21 17:38:47 +01001006 FlagWithOutput("--output ", patternsFile)
1007 rule.Build("hiddenAPISignaturePatterns", "hidden API signature patterns")
1008
1009 return patternsFile
1010}
1011
Paul Duffinbd88c882022-04-07 23:32:19 +01001012// buildRuleRemoveSignaturesWithImplementationFlags creates a rule that will remove signatures from
1013// the input flags file which have only the implementation flags, i.e. are not part of an API.
1014//
1015// The implementationFlags specifies the set of default flags that identifies the signature of a
1016// private, implementation only, member. Signatures that match those flags are removed from the
1017// flags as they are implementation only.
1018//
1019// This is used to remove implementation only signatures from the signature files that are persisted
1020// in the sdk snapshot as the sdk snapshots should not include implementation details. The
1021// signatures generated by this method will be compared by the buildRuleValidateOverlappingCsvFiles
1022// method which treats any missing signatures as if they were implementation only signatures.
1023func buildRuleRemoveSignaturesWithImplementationFlags(ctx android.BuilderContext,
1024 name string, desc string, inputPath android.Path, filteredPath android.WritablePath,
1025 implementationFlags []string) {
1026
Paul Duffin280bae62021-07-20 18:03:53 +01001027 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffinbd88c882022-04-07 23:32:19 +01001028 implementationFlagPattern := ""
1029 for _, implementationFlag := range implementationFlags {
1030 implementationFlagPattern = implementationFlagPattern + "," + implementationFlag
1031 }
Paul Duffin280bae62021-07-20 18:03:53 +01001032 rule.Command().
Paul Duffinbd88c882022-04-07 23:32:19 +01001033 Text(`grep -vE "^[^,]+` + implementationFlagPattern + `$"`).Input(inputPath).
1034 Text(">").Output(filteredPath).
Paul Duffin280bae62021-07-20 18:03:53 +01001035 // Grep's exit code depends on whether it finds anything. It is 0 (build success) when it finds
1036 // something and 1 (build failure) when it does not and 2 (when it encounters an error).
1037 // However, while it is unlikely it is not an error if this does not find any matches. The
1038 // following will only run if the grep does not find something and in that case it will treat
1039 // an exit code of 1 as success and anything else as failure.
1040 Text("|| test $? -eq 1")
1041 rule.Build(name, desc)
1042}
1043
Paul Duffin2e880972021-06-23 23:29:09 +01001044// buildRuleValidateOverlappingCsvFiles checks that the modular CSV files, i.e. the files generated
1045// by the individual bootclasspath_fragment modules are subsets of the monolithic CSV file.
Paul Duffinbd88c882022-04-07 23:32:19 +01001046//
1047// The implementationFlags specifies the set of default flags that identifies the signature of a
1048// private, implementation only, member. A signature which is present in a monolithic flags subset
1049// defined by SignatureCsvSubset but which is not present in the flags file from the corresponding
1050// module is assumed to be an implementation only member and so must have these flags.
1051func buildRuleValidateOverlappingCsvFiles(ctx android.BuilderContext, name string, desc string,
1052 monolithicFilePath android.WritablePath, csvSubsets SignatureCsvSubsets,
1053 implementationFlags []string) android.WritablePath {
Paul Duffin2e880972021-06-23 23:29:09 +01001054 // The file which is used to record that the flags file is valid.
1055 validFile := pathForValidation(ctx, monolithicFilePath)
1056
1057 // Create a rule to validate the output from the following rule.
1058 rule := android.NewRuleBuilder(pctx, ctx)
Paul Duffin67b9d612021-07-21 17:38:47 +01001059 command := rule.Command().
Paul Duffin2e880972021-06-23 23:29:09 +01001060 BuiltTool("verify_overlaps").
Paul Duffin0c12b782022-04-08 00:28:11 +01001061 FlagWithInput("--monolithic-flags ", monolithicFilePath)
Paul Duffin67b9d612021-07-21 17:38:47 +01001062
1063 for _, subset := range csvSubsets {
1064 command.
Paul Duffin0c12b782022-04-08 00:28:11 +01001065 Flag("--module-flags ").
Paul Duffin67b9d612021-07-21 17:38:47 +01001066 Textf("%s:%s", subset.CsvFile, subset.SignaturePatternsFile).
1067 Implicit(subset.CsvFile).Implicit(subset.SignaturePatternsFile)
1068 }
1069
Paul Duffinbd88c882022-04-07 23:32:19 +01001070 for _, implementationFlag := range implementationFlags {
1071 command.FlagWithArg("--implementation-flag ", implementationFlag)
1072 }
1073
Paul Duffin67b9d612021-07-21 17:38:47 +01001074 // If validation passes then update the file that records that.
1075 command.Text("&& touch").Output(validFile)
Paul Duffin2e880972021-06-23 23:29:09 +01001076 rule.Build(name+"Validation", desc+" validation")
1077
1078 return validFile
1079}
1080
Paul Duffine5218812021-06-07 13:28:19 +01001081// hiddenAPIRulesForBootclasspathFragment will generate all the flags for a fragment of the
1082// bootclasspath and then encode the flags into the boot dex files.
Paul Duffin2fef1362021-04-15 13:32:00 +01001083//
1084// It takes:
1085// * Map from android.SdkKind to stub dex jar paths defining the API for that sdk kind.
1086// * The list of modules that are the contents of the fragment.
1087// * The additional manually curated flag files to use.
1088//
1089// It generates:
1090// * stub-flags.csv
1091// * annotation-flags.csv
1092// * metadata.csv
1093// * index.csv
1094// * all-flags.csv
Paul Duffine5218812021-06-07 13:28:19 +01001095// * encoded boot dex files
1096func hiddenAPIRulesForBootclasspathFragment(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput {
Paul Duffin2fef1362021-04-15 13:32:00 +01001097 hiddenApiSubDir := "modular-hiddenapi"
1098
Paul Duffine5218812021-06-07 13:28:19 +01001099 // Gather information about the boot dex files for the boot libraries provided by this fragment.
1100 bootDexInfoByModule := extractBootDexInfoFromModules(ctx, contents)
Paul Duffin1352f7c2021-05-21 22:18:49 +01001101
1102 // Generate the stub-flags.csv.
Paul Duffin2fef1362021-04-15 13:32:00 +01001103 stubFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "stub-flags.csv")
Paul Duffin2e880972021-06-23 23:29:09 +01001104 buildRuleToGenerateHiddenAPIStubFlagsFile(ctx, "modularHiddenAPIStubFlagsFile", "modular hiddenapi stub flags", stubFlagsCSV, bootDexInfoByModule.bootDexJars(), input, nil)
Paul Duffin2fef1362021-04-15 13:32:00 +01001105
Paul Duffin537ea3d2021-05-14 10:38:00 +01001106 // Extract the classes jars from the contents.
Paul Duffindd5993f2021-06-10 10:18:22 +01001107 classesJars := extractClassesJarsFromModules(contents)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001108
Paul Duffin2fef1362021-04-15 13:32:00 +01001109 // Generate the set of flags from the annotations in the source code.
1110 annotationFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "annotation-flags.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +01001111 buildRuleToGenerateAnnotationFlags(ctx, "modular hiddenapi annotation flags", classesJars, stubFlagsCSV, annotationFlagsCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001112
1113 // Generate the metadata from the annotations in the source code.
1114 metadataCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "metadata.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +01001115 buildRuleToGenerateMetadata(ctx, "modular hiddenapi metadata", classesJars, stubFlagsCSV, metadataCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001116
Paul Duffin537ea3d2021-05-14 10:38:00 +01001117 // Generate the index file from the CSV files in the classes jars.
Paul Duffin2fef1362021-04-15 13:32:00 +01001118 indexCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "index.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +01001119 buildRuleToGenerateIndex(ctx, "modular hiddenapi index", classesJars, indexCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +01001120
Paul Duffinaf99afa2021-05-21 22:18:56 +01001121 // 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 +01001122 // containing dex signatures of all the removed APIs. In the monolithic files that is done by
1123 // manually combining all the removed.txt files for each API and then converting them to dex
Paul Duffin32cf58a2021-05-18 16:32:50 +01001124 // signatures, see the combined-removed-dex module. This does that automatically by using the
1125 // *removed.txt files retrieved from the java_sdk_library modules that are specified in the
1126 // stub_libs and contents properties of a bootclasspath_fragment.
1127 removedDexSignatures := buildRuleToGenerateRemovedDexSignatures(ctx, input.RemovedTxtFiles)
Paul Duffin2fef1362021-04-15 13:32:00 +01001128
1129 // Generate the all-flags.csv which are the flags that will, in future, be encoded into the dex
1130 // files.
Paul Duffine5218812021-06-07 13:28:19 +01001131 allFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "all-flags.csv")
Paul Duffind061d402021-06-07 21:36:01 +01001132 buildRuleToGenerateHiddenApiFlags(ctx, "modularHiddenApiAllFlags", "modular hiddenapi all flags", allFlagsCSV, stubFlagsCSV, android.Paths{annotationFlagsCSV}, input.FlagFilesByCategory, nil, removedDexSignatures)
Paul Duffine5218812021-06-07 13:28:19 +01001133
1134 // Encode the flags into the boot dex files.
1135 encodedBootDexJarsByModule := map[string]android.Path{}
1136 outputDir := android.PathForModuleOut(ctx, "hiddenapi-modular/encoded").OutputPath
1137 for _, name := range android.SortedStringKeys(bootDexInfoByModule) {
1138 bootDexInfo := bootDexInfoByModule[name]
1139 unencodedDex := bootDexInfo.path
Paul Duffin09817d62022-04-28 17:45:11 +01001140 encodedDex := hiddenAPIEncodeDex(ctx, unencodedDex, allFlagsCSV, bootDexInfo.uncompressDex, bootDexInfo.minSdkVersion, outputDir)
Paul Duffine5218812021-06-07 13:28:19 +01001141 encodedBootDexJarsByModule[name] = encodedDex
1142 }
Paul Duffin2fef1362021-04-15 13:32:00 +01001143
Paul Duffin280bae62021-07-20 18:03:53 +01001144 // Generate the filtered-stub-flags.csv file which contains the filtered stub flags that will be
1145 // compared against the monolithic stub flags.
1146 filteredStubFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "filtered-stub-flags.csv")
Paul Duffinbd88c882022-04-07 23:32:19 +01001147 buildRuleRemoveSignaturesWithImplementationFlags(ctx, "modularHiddenApiFilteredStubFlags",
1148 "modular hiddenapi filtered stub flags", stubFlagsCSV, filteredStubFlagsCSV,
1149 HIDDENAPI_STUB_FLAGS_IMPL_FLAGS)
Paul Duffin280bae62021-07-20 18:03:53 +01001150
1151 // Generate the filtered-flags.csv file which contains the filtered flags that will be compared
1152 // against the monolithic flags.
1153 filteredFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "filtered-flags.csv")
Paul Duffinbd88c882022-04-07 23:32:19 +01001154 buildRuleRemoveSignaturesWithImplementationFlags(ctx, "modularHiddenApiFilteredFlags",
1155 "modular hiddenapi filtered flags", allFlagsCSV, filteredFlagsCSV,
1156 HIDDENAPI_FLAGS_CSV_IMPL_FLAGS)
Paul Duffin280bae62021-07-20 18:03:53 +01001157
Paul Duffin2fef1362021-04-15 13:32:00 +01001158 // Store the paths in the info for use by other modules and sdk snapshot generation.
Paul Duffine5218812021-06-07 13:28:19 +01001159 output := HiddenAPIOutput{
1160 HiddenAPIFlagOutput: HiddenAPIFlagOutput{
Paul Duffin191be3a2021-08-10 16:14:16 +01001161 AnnotationFlagsPath: annotationFlagsCSV,
1162 MetadataPath: metadataCSV,
1163 IndexPath: indexCSV,
1164 StubFlagsPath: stubFlagsCSV,
1165 AllFlagsPath: allFlagsCSV,
1166 FilteredStubFlagsPath: filteredStubFlagsCSV,
1167 FilteredFlagsPath: filteredFlagsCSV,
Paul Duffine5218812021-06-07 13:28:19 +01001168 },
1169 EncodedBootDexFilesByModule: encodedBootDexJarsByModule,
Paul Duffin1e6f5c42021-05-21 16:15:31 +01001170 }
1171 return &output
Paul Duffin702210b2021-04-08 20:12:41 +01001172}
Paul Duffin537ea3d2021-05-14 10:38:00 +01001173
Paul Duffin32cf58a2021-05-18 16:32:50 +01001174func buildRuleToGenerateRemovedDexSignatures(ctx android.ModuleContext, removedTxtFiles android.Paths) android.OptionalPath {
1175 if len(removedTxtFiles) == 0 {
1176 return android.OptionalPath{}
1177 }
1178
1179 output := android.PathForModuleOut(ctx, "modular-hiddenapi/removed-dex-signatures.txt")
1180
1181 rule := android.NewRuleBuilder(pctx, ctx)
1182 rule.Command().
1183 BuiltTool("metalava").
1184 Flag("--no-banner").
1185 Inputs(removedTxtFiles).
1186 FlagWithOutput("--dex-api ", output)
1187 rule.Build("modular-hiddenapi-removed-dex-signatures", "modular hiddenapi removed dex signatures")
1188 return android.OptionalPathForPath(output)
1189}
1190
Paul Duffindd5993f2021-06-10 10:18:22 +01001191// extractBootDexJarsFromModules extracts the boot dex jars from the supplied modules.
Paul Duffine5218812021-06-07 13:28:19 +01001192func extractBootDexJarsFromModules(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
1193 bootDexJars := bootDexJarByModule{}
Paul Duffin537ea3d2021-05-14 10:38:00 +01001194 for _, module := range contents {
Paul Duffindd5993f2021-06-10 10:18:22 +01001195 hiddenAPIModule := hiddenAPIModuleFromModule(ctx, module)
1196 if hiddenAPIModule == nil {
1197 continue
1198 }
Paul Duffine5218812021-06-07 13:28:19 +01001199 bootDexJar := retrieveBootDexJarFromHiddenAPIModule(ctx, hiddenAPIModule)
1200 bootDexJars.addPath(module, bootDexJar)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001201 }
1202 return bootDexJars
1203}
1204
Paul Duffindd5993f2021-06-10 10:18:22 +01001205func hiddenAPIModuleFromModule(ctx android.BaseModuleContext, module android.Module) hiddenAPIModule {
1206 if hiddenAPIModule, ok := module.(hiddenAPIModule); ok {
1207 return hiddenAPIModule
1208 } else if _, ok := module.(*DexImport); ok {
1209 // Ignore this for the purposes of hidden API processing
1210 } else {
1211 ctx.ModuleErrorf("module %s does not implement hiddenAPIModule", module)
1212 }
1213
1214 return nil
1215}
1216
Paul Duffine5218812021-06-07 13:28:19 +01001217// bootDexInfo encapsulates both the path and uncompressDex status retrieved from a hiddenAPIModule.
1218type bootDexInfo struct {
1219 // The path to the dex jar that has not had hidden API flags encoded into it.
1220 path android.Path
1221
1222 // Indicates whether the dex jar needs uncompressing before encoding.
1223 uncompressDex bool
Paul Duffin09817d62022-04-28 17:45:11 +01001224
1225 // The minimum sdk version that the dex jar will be used on.
1226 minSdkVersion android.SdkSpec
Paul Duffine5218812021-06-07 13:28:19 +01001227}
1228
1229// bootDexInfoByModule is a map from module name (as returned by module.Name()) to the boot dex
1230// path (as returned by hiddenAPIModule.bootDexJar()) and the uncompressDex flag.
1231type bootDexInfoByModule map[string]bootDexInfo
1232
1233// bootDexJars returns the boot dex jar paths sorted by their keys.
1234func (b bootDexInfoByModule) bootDexJars() android.Paths {
1235 paths := android.Paths{}
1236 for _, m := range android.SortedStringKeys(b) {
1237 paths = append(paths, b[m].path)
1238 }
1239 return paths
1240}
1241
1242// extractBootDexInfoFromModules extracts the boot dex jar and uncompress dex state from
1243// each of the supplied modules which must implement hiddenAPIModule.
1244func extractBootDexInfoFromModules(ctx android.ModuleContext, contents []android.Module) bootDexInfoByModule {
1245 bootDexJarsByModule := bootDexInfoByModule{}
1246 for _, module := range contents {
1247 hiddenAPIModule := module.(hiddenAPIModule)
1248 bootDexJar := retrieveBootDexJarFromHiddenAPIModule(ctx, hiddenAPIModule)
1249 bootDexJarsByModule[module.Name()] = bootDexInfo{
1250 path: bootDexJar,
1251 uncompressDex: *hiddenAPIModule.uncompressDex(),
Paul Duffin09817d62022-04-28 17:45:11 +01001252 minSdkVersion: hiddenAPIModule.MinSdkVersion(ctx),
Paul Duffine5218812021-06-07 13:28:19 +01001253 }
1254 }
1255
1256 return bootDexJarsByModule
1257}
1258
1259// retrieveBootDexJarFromHiddenAPIModule retrieves the boot dex jar from the hiddenAPIModule.
1260//
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001261// If the module does not provide a boot dex jar, i.e. the returned boot dex jar is unset or
1262// invalid, then create a fake path and either report an error immediately or defer reporting of the
1263// error until the path is actually used.
Paul Duffine5218812021-06-07 13:28:19 +01001264func retrieveBootDexJarFromHiddenAPIModule(ctx android.ModuleContext, module hiddenAPIModule) android.Path {
1265 bootDexJar := module.bootDexJar()
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001266 if !bootDexJar.Valid() {
Paul Duffine5218812021-06-07 13:28:19 +01001267 fake := android.PathForModuleOut(ctx, fmt.Sprintf("fake/boot-dex/%s.jar", module.Name()))
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001268 handleMissingDexBootFile(ctx, module, fake, bootDexJar.InvalidReason())
1269 return fake
Paul Duffine5218812021-06-07 13:28:19 +01001270 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001271 return bootDexJar.Path()
Paul Duffine5218812021-06-07 13:28:19 +01001272}
1273
Paul Duffindd5993f2021-06-10 10:18:22 +01001274// extractClassesJarsFromModules extracts the class jars from the supplied modules.
1275func extractClassesJarsFromModules(contents []android.Module) android.Paths {
Paul Duffin537ea3d2021-05-14 10:38:00 +01001276 classesJars := android.Paths{}
1277 for _, module := range contents {
Paul Duffindd5993f2021-06-10 10:18:22 +01001278 classesJars = append(classesJars, retrieveClassesJarsFromModule(module)...)
Paul Duffin537ea3d2021-05-14 10:38:00 +01001279 }
1280 return classesJars
1281}
Paul Duffin5f148ca2021-06-02 17:24:22 +01001282
Paul Duffindd5993f2021-06-10 10:18:22 +01001283// retrieveClassesJarsFromModule retrieves the classes jars from the supplied module.
1284func retrieveClassesJarsFromModule(module android.Module) android.Paths {
1285 if hiddenAPIModule, ok := module.(hiddenAPIModule); ok {
1286 return hiddenAPIModule.classesJars()
1287 }
1288
1289 return nil
1290}
1291
Paul Duffin5f148ca2021-06-02 17:24:22 +01001292// deferReportingMissingBootDexJar returns true if a missing boot dex jar should not be reported by
1293// Soong but should instead only be reported in ninja if the file is actually built.
1294func deferReportingMissingBootDexJar(ctx android.ModuleContext, module android.Module) bool {
Paul Duffine5218812021-06-07 13:28:19 +01001295 // Any missing dependency should be allowed.
1296 if ctx.Config().AllowMissingDependencies() {
1297 return true
1298 }
1299
Paul Duffinef083c92021-06-29 13:36:34 +01001300 // A bootclasspath module that is part of a versioned sdk never provides a boot dex jar as there
1301 // is no equivalently versioned prebuilt APEX file from which it can be obtained. However,
1302 // versioned bootclasspath modules are processed by Soong so in order to avoid them causing build
1303 // failures missing boot dex jars need to be deferred.
1304 if android.IsModuleInVersionedSdk(ctx.Module()) {
1305 return true
1306 }
1307
Paul Duffin5f148ca2021-06-02 17:24:22 +01001308 // This is called for both platform_bootclasspath and bootclasspath_fragment modules.
1309 //
1310 // A bootclasspath_fragment module should only use the APEX variant of source or prebuilt modules.
1311 // Ideally, a bootclasspath_fragment module should never have a platform variant created for it
1312 // but unfortunately, due to b/187910671 it does.
1313 //
1314 // That causes issues when obtaining a boot dex jar for a prebuilt module as a prebuilt module
1315 // used by a bootclasspath_fragment can only provide a boot dex jar when it is part of APEX, i.e.
1316 // has an APEX variant not a platform variant.
1317 //
1318 // There are some other situations when a prebuilt module used by a bootclasspath_fragment cannot
1319 // provide a boot dex jar:
1320 // 1. If the bootclasspath_fragment is not exported by the prebuilt_apex/apex_set module then it
1321 // does not have an APEX variant and only has a platform variant and neither do its content
1322 // modules.
1323 // 2. Some build configurations, e.g. setting TARGET_BUILD_USE_PREBUILT_SDKS causes all
1324 // java_sdk_library_import modules to be treated as preferred and as many of them are not part
1325 // of an apex they cannot provide a boot dex jar.
1326 //
1327 // The first case causes problems when the affected prebuilt modules are preferred but that is an
1328 // invalid configuration and it is ok for it to fail as the work to enable that is not yet
1329 // complete. The second case is used for building targets that do not use boot dex jars and so
1330 // deferring error reporting to ninja is fine as the affected ninja targets should never be built.
1331 // That is handled above.
1332 //
1333 // A platform_bootclasspath module can use libraries from both platform and APEX variants. Unlike
1334 // the bootclasspath_fragment it supports dex_import modules which provides the dex file. So, it
1335 // can obtain a boot dex jar from a prebuilt that is not part of an APEX. However, it is assumed
1336 // that if the library can be part of an APEX then it is the APEX variant that is used.
1337 //
1338 // This check handles the slightly different requirements of the bootclasspath_fragment and
1339 // platform_bootclasspath modules by only deferring error reporting for the platform variant of
1340 // a prebuilt modules that has other variants which are part of an APEX.
1341 //
1342 // TODO(b/187910671): Remove this once platform variants are no longer created unnecessarily.
1343 if android.IsModulePrebuilt(module) {
Paul Duffinef083c92021-06-29 13:36:34 +01001344 // An inactive source module can still contribute to the APEX but an inactive prebuilt module
1345 // should not contribute to anything. So, rather than have a missing dex jar cause a Soong
1346 // failure defer the error reporting to Ninja. Unless the prebuilt build target is explicitly
1347 // built Ninja should never use the dex jar file.
1348 if !isActiveModule(module) {
1349 return true
1350 }
1351
Paul Duffin5f148ca2021-06-02 17:24:22 +01001352 if am, ok := module.(android.ApexModule); ok && am.InAnyApex() {
1353 apexInfo := ctx.OtherModuleProvider(module, android.ApexInfoProvider).(android.ApexInfo)
1354 if apexInfo.IsForPlatform() {
1355 return true
1356 }
1357 }
1358 }
1359
Paul Duffin5f148ca2021-06-02 17:24:22 +01001360 return false
1361}
1362
1363// handleMissingDexBootFile will either log a warning or create an error rule to create the fake
1364// file depending on the value returned from deferReportingMissingBootDexJar.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001365func handleMissingDexBootFile(ctx android.ModuleContext, module android.Module, fake android.WritablePath, reason string) {
Paul Duffin5f148ca2021-06-02 17:24:22 +01001366 if deferReportingMissingBootDexJar(ctx, module) {
1367 // Create an error rule that pretends to create the output file but will actually fail if it
1368 // is run.
1369 ctx.Build(pctx, android.BuildParams{
1370 Rule: android.ErrorRule,
1371 Output: fake,
1372 Args: map[string]string{
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001373 "error": fmt.Sprintf("missing boot dex jar dependency for %s: %s", module, reason),
Paul Duffin5f148ca2021-06-02 17:24:22 +01001374 },
1375 })
1376 } else {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001377 ctx.ModuleErrorf("module %s does not provide a dex jar: %s", module, reason)
Paul Duffin5f148ca2021-06-02 17:24:22 +01001378 }
1379}
1380
1381// retrieveEncodedBootDexJarFromModule returns a path to the boot dex jar from the supplied module's
1382// DexJarBuildPath() method.
1383//
1384// The returned path will usually be to a dex jar file that has been encoded with hidden API flags.
1385// However, under certain conditions, e.g. errors, or special build configurations it will return
1386// a path to a fake file.
1387func retrieveEncodedBootDexJarFromModule(ctx android.ModuleContext, module android.Module) android.Path {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001388 bootDexJar := module.(interface{ DexJarBuildPath() OptionalDexJarPath }).DexJarBuildPath()
1389 if !bootDexJar.Valid() {
Paul Duffin5f148ca2021-06-02 17:24:22 +01001390 fake := android.PathForModuleOut(ctx, fmt.Sprintf("fake/encoded-dex/%s.jar", module.Name()))
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001391 handleMissingDexBootFile(ctx, module, fake, bootDexJar.InvalidReason())
1392 return fake
Paul Duffin5f148ca2021-06-02 17:24:22 +01001393 }
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001394 return bootDexJar.Path()
Paul Duffin5f148ca2021-06-02 17:24:22 +01001395}
1396
1397// extractEncodedDexJarsFromModules extracts the encoded dex jars from the supplied modules.
1398func extractEncodedDexJarsFromModules(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
1399 encodedDexJarsByModuleName := bootDexJarByModule{}
1400 for _, module := range contents {
1401 path := retrieveEncodedBootDexJarFromModule(ctx, module)
1402 encodedDexJarsByModuleName.addPath(module, path)
1403 }
1404 return encodedDexJarsByModuleName
1405}