blob: 370794229ec3f47adc9bb400332dadd0c6928759 [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"
Paul Duffin9b381ef2021-04-08 23:01:37 +010022 "github.com/google/blueprint"
Paul Duffin62370922021-05-23 16:55:37 +010023 "github.com/google/blueprint/proptools"
Paul Duffinc6bb7cf2021-04-08 17:49:27 +010024)
25
26// Contains support for processing hiddenAPI in a modular fashion.
27
Paul Duffin74431d52021-04-21 14:10:42 +010028type hiddenAPIStubsDependencyTag struct {
29 blueprint.BaseDependencyTag
30 sdkKind android.SdkKind
31}
32
33func (b hiddenAPIStubsDependencyTag) ExcludeFromApexContents() {
34}
35
36func (b hiddenAPIStubsDependencyTag) ReplaceSourceWithPrebuilt() bool {
37 return false
38}
39
Paul Duffin976b0e52021-04-27 23:20:26 +010040func (b hiddenAPIStubsDependencyTag) SdkMemberType(child android.Module) android.SdkMemberType {
41 // If the module is a java_sdk_library then treat it as if it was specific in the java_sdk_libs
42 // property, otherwise treat if it was specified in the java_header_libs property.
43 if javaSdkLibrarySdkMemberType.IsInstance(child) {
44 return javaSdkLibrarySdkMemberType
45 }
46
47 return javaHeaderLibsSdkMemberType
48}
49
50func (b hiddenAPIStubsDependencyTag) ExportMember() bool {
51 // Export the module added via this dependency tag from the sdk.
52 return true
53}
54
Paul Duffin74431d52021-04-21 14:10:42 +010055// Avoid having to make stubs content explicitly visible to dependent modules.
56//
57// This is a temporary workaround to make it easier to migrate to bootclasspath_fragment modules
58// with proper dependencies.
59// TODO(b/177892522): Remove this and add needed visibility.
60func (b hiddenAPIStubsDependencyTag) ExcludeFromVisibilityEnforcement() {
61}
62
63var _ android.ExcludeFromVisibilityEnforcementTag = hiddenAPIStubsDependencyTag{}
64var _ android.ReplaceSourceWithPrebuilt = hiddenAPIStubsDependencyTag{}
65var _ android.ExcludeFromApexContentsTag = hiddenAPIStubsDependencyTag{}
Paul Duffin976b0e52021-04-27 23:20:26 +010066var _ android.SdkMemberTypeDependencyTag = hiddenAPIStubsDependencyTag{}
Paul Duffin74431d52021-04-21 14:10:42 +010067
Paul Duffin3e7fcc32021-04-15 13:31:38 +010068// hiddenAPIRelevantSdkKinds lists all the android.SdkKind instances that are needed by the hidden
69// API processing.
Paul Duffinf1b358c2021-05-17 07:38:47 +010070//
71// These are in order from narrowest API surface to widest. Widest means the API stubs with the
72// biggest API surface, e.g. test is wider than system is wider than public. Core platform is
73// considered wider than test even though it has no relationship with test because the libraries
74// that provide core platform API don't provide test. While the core platform API is being converted
75// to a system API the system API is still a subset of core platform.
Paul Duffin3e7fcc32021-04-15 13:31:38 +010076var hiddenAPIRelevantSdkKinds = []android.SdkKind{
77 android.SdkPublic,
78 android.SdkSystem,
79 android.SdkTest,
80 android.SdkCorePlatform,
81}
82
Paul Duffin74431d52021-04-21 14:10:42 +010083// hiddenAPIComputeMonolithicStubLibModules computes the set of module names that provide stubs
84// needed to produce the hidden API monolithic stub flags file.
85func hiddenAPIComputeMonolithicStubLibModules(config android.Config) map[android.SdkKind][]string {
86 var publicStubModules []string
87 var systemStubModules []string
88 var testStubModules []string
89 var corePlatformStubModules []string
90
91 if config.AlwaysUsePrebuiltSdks() {
92 // Build configuration mandates using prebuilt stub modules
93 publicStubModules = append(publicStubModules, "sdk_public_current_android")
94 systemStubModules = append(systemStubModules, "sdk_system_current_android")
95 testStubModules = append(testStubModules, "sdk_test_current_android")
96 } else {
97 // Use stub modules built from source
98 publicStubModules = append(publicStubModules, "android_stubs_current")
99 systemStubModules = append(systemStubModules, "android_system_stubs_current")
100 testStubModules = append(testStubModules, "android_test_stubs_current")
101 }
102 // We do not have prebuilts of the core platform api yet
103 corePlatformStubModules = append(corePlatformStubModules, "legacy.core.platform.api.stubs")
104
105 // Allow products to define their own stubs for custom product jars that apps can use.
106 publicStubModules = append(publicStubModules, config.ProductHiddenAPIStubs()...)
107 systemStubModules = append(systemStubModules, config.ProductHiddenAPIStubsSystem()...)
108 testStubModules = append(testStubModules, config.ProductHiddenAPIStubsTest()...)
109 if config.IsEnvTrue("EMMA_INSTRUMENT") {
Paul Duffin098c8782021-05-14 10:45:25 +0100110 // Add jacoco-stubs to public, system and test. It doesn't make any real difference as public
111 // allows everyone access but it is needed to ensure consistent flags between the
112 // bootclasspath fragment generated flags and the platform_bootclasspath generated flags.
Paul Duffin74431d52021-04-21 14:10:42 +0100113 publicStubModules = append(publicStubModules, "jacoco-stubs")
Paul Duffin098c8782021-05-14 10:45:25 +0100114 systemStubModules = append(systemStubModules, "jacoco-stubs")
115 testStubModules = append(testStubModules, "jacoco-stubs")
Paul Duffin74431d52021-04-21 14:10:42 +0100116 }
117
118 m := map[android.SdkKind][]string{}
119 m[android.SdkPublic] = publicStubModules
120 m[android.SdkSystem] = systemStubModules
121 m[android.SdkTest] = testStubModules
122 m[android.SdkCorePlatform] = corePlatformStubModules
123 return m
124}
125
126// hiddenAPIAddStubLibDependencies adds dependencies onto the modules specified in
127// sdkKindToStubLibModules. It adds them in a well known order and uses an SdkKind specific tag to
128// identify the source of the dependency.
129func hiddenAPIAddStubLibDependencies(ctx android.BottomUpMutatorContext, sdkKindToStubLibModules map[android.SdkKind][]string) {
130 module := ctx.Module()
131 for _, sdkKind := range hiddenAPIRelevantSdkKinds {
132 modules := sdkKindToStubLibModules[sdkKind]
133 ctx.AddDependency(module, hiddenAPIStubsDependencyTag{sdkKind: sdkKind}, modules...)
134 }
135}
136
Paul Duffin74431d52021-04-21 14:10:42 +0100137// hiddenAPIRetrieveDexJarBuildPath retrieves the DexJarBuildPath from the specified module, if
138// available, or reports an error.
Paul Duffin10931582021-04-25 10:13:54 +0100139func hiddenAPIRetrieveDexJarBuildPath(ctx android.ModuleContext, module android.Module, kind android.SdkKind) android.Path {
140 var dexJar android.Path
141 if sdkLibrary, ok := module.(SdkLibraryDependency); ok {
142 dexJar = sdkLibrary.SdkApiStubDexJar(ctx, kind)
143 } else if j, ok := module.(UsesLibraryDependency); ok {
144 dexJar = j.DexJarBuildPath()
Paul Duffin74431d52021-04-21 14:10:42 +0100145 } else {
146 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 +0100147 return nil
Paul Duffin74431d52021-04-21 14:10:42 +0100148 }
Paul Duffin10931582021-04-25 10:13:54 +0100149
150 if dexJar == nil {
151 ctx.ModuleErrorf("dependency %s does not provide a dex jar, consider setting compile_dex: true", module)
152 }
153 return dexJar
Paul Duffin74431d52021-04-21 14:10:42 +0100154}
155
156var sdkKindToHiddenapiListOption = map[android.SdkKind]string{
157 android.SdkPublic: "public-stub-classpath",
158 android.SdkSystem: "system-stub-classpath",
159 android.SdkTest: "test-stub-classpath",
160 android.SdkCorePlatform: "core-platform-stub-classpath",
161}
162
163// ruleToGenerateHiddenAPIStubFlagsFile creates a rule to create a hidden API stub flags file.
164//
165// The rule is initialized but not built so that the caller can modify it and select an appropriate
166// name.
Paul Duffin1352f7c2021-05-21 22:18:49 +0100167func ruleToGenerateHiddenAPIStubFlagsFile(ctx android.BuilderContext, outputPath android.WritablePath, bootDexJars android.Paths, input HiddenAPIFlagInput) *android.RuleBuilder {
Paul Duffin74431d52021-04-21 14:10:42 +0100168 // Singleton rule which applies hiddenapi on all boot class path dex files.
169 rule := android.NewRuleBuilder(pctx, ctx)
170
171 tempPath := tempPathForRestat(ctx, outputPath)
172
Paul Duffinf1b358c2021-05-17 07:38:47 +0100173 // Find the widest API stubs provided by the fragments on which this depends, if any.
174 var dependencyStubDexJars android.Paths
175 for i := len(hiddenAPIRelevantSdkKinds) - 1; i >= 0; i-- {
176 kind := hiddenAPIRelevantSdkKinds[i]
177 stubsForKind := input.DependencyStubDexJarsByKind[kind]
178 if len(stubsForKind) != 0 {
179 dependencyStubDexJars = stubsForKind
180 break
181 }
182 }
183
Paul Duffin74431d52021-04-21 14:10:42 +0100184 command := rule.Command().
185 Tool(ctx.Config().HostToolPath(ctx, "hiddenapi")).
186 Text("list").
Paul Duffinf1b358c2021-05-17 07:38:47 +0100187 FlagForEachInput("--dependency-stub-dex=", dependencyStubDexJars).
Paul Duffin74431d52021-04-21 14:10:42 +0100188 FlagForEachInput("--boot-dex=", bootDexJars)
189
190 // Iterate over the sdk kinds in a fixed order.
191 for _, sdkKind := range hiddenAPIRelevantSdkKinds {
Paul Duffinf1b358c2021-05-17 07:38:47 +0100192 // Merge in the stub dex jar paths for this kind from the fragments on which it depends. They
193 // will be needed to resolve dependencies from this fragment's stubs to classes in the other
194 // fragment's APIs.
195 dependencyPaths := input.DependencyStubDexJarsByKind[sdkKind]
196 paths := append(dependencyPaths, input.StubDexJarsByKind[sdkKind]...)
Paul Duffin74431d52021-04-21 14:10:42 +0100197 if len(paths) > 0 {
198 option := sdkKindToHiddenapiListOption[sdkKind]
199 command.FlagWithInputList("--"+option+"=", paths, ":")
200 }
201 }
202
203 // Add the output path.
204 command.FlagWithOutput("--out-api-flags=", tempPath)
205
206 commitChangeForRestat(rule, tempPath, outputPath)
207 return rule
208}
209
Paul Duffin46169772021-04-14 15:01:56 +0100210// HiddenAPIFlagFileProperties contains paths to the flag files that can be used to augment the
211// information obtained from annotations within the source code in order to create the complete set
212// of flags that should be applied to the dex implementation jars on the bootclasspath.
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100213//
214// Each property contains a list of paths. With the exception of the Unsupported_packages the paths
215// of each property reference a plain text file that contains a java signature per line. The flags
216// for each of those signatures will be updated in a property specific way.
217//
218// The Unsupported_packages property contains a list of paths, each of which is a plain text file
219// with one Java package per line. All members of all classes within that package (but not nested
220// packages) will be updated in a property specific way.
Paul Duffin46169772021-04-14 15:01:56 +0100221type HiddenAPIFlagFileProperties struct {
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100222 // Marks each signature in the referenced files as being unsupported.
Paul Duffin702210b2021-04-08 20:12:41 +0100223 Unsupported []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100224
225 // Marks each signature in the referenced files as being unsupported because it has been removed.
226 // Any conflicts with other flags are ignored.
Paul Duffin702210b2021-04-08 20:12:41 +0100227 Removed []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100228
229 // Marks each signature in the referenced files as being supported only for targetSdkVersion <= R
230 // and low priority.
Paul Duffin702210b2021-04-08 20:12:41 +0100231 Max_target_r_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100232
233 // Marks each signature in the referenced files as being supported only for targetSdkVersion <= Q.
Paul Duffin702210b2021-04-08 20:12:41 +0100234 Max_target_q []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100235
236 // Marks each signature in the referenced files as being supported only for targetSdkVersion <= P.
Paul Duffin702210b2021-04-08 20:12:41 +0100237 Max_target_p []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100238
239 // Marks each signature in the referenced files as being supported only for targetSdkVersion <= O
240 // and low priority. Any conflicts with other flags are ignored.
Paul Duffin702210b2021-04-08 20:12:41 +0100241 Max_target_o_low_priority []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100242
243 // Marks each signature in the referenced files as being blocked.
Paul Duffin702210b2021-04-08 20:12:41 +0100244 Blocked []string `android:"path"`
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100245
246 // Marks each signature in every package in the referenced files as being unsupported.
Paul Duffin702210b2021-04-08 20:12:41 +0100247 Unsupported_packages []string `android:"path"`
248}
249
Paul Duffine3dc6602021-04-14 09:50:43 +0100250type hiddenAPIFlagFileCategory struct {
251 // propertyName is the name of the property for this category.
252 propertyName string
253
Paul Duffincc17bfe2021-04-19 13:21:20 +0100254 // propertyValueReader retrieves the value of the property for this category from the set of
Paul Duffine3dc6602021-04-14 09:50:43 +0100255 // properties.
Paul Duffincc17bfe2021-04-19 13:21:20 +0100256 propertyValueReader func(properties *HiddenAPIFlagFileProperties) []string
Paul Duffine3dc6602021-04-14 09:50:43 +0100257
258 // commandMutator adds the appropriate command line options for this category to the supplied
259 // command
260 commandMutator func(command *android.RuleBuilderCommand, path android.Path)
261}
262
263var hiddenAPIFlagFileCategories = []*hiddenAPIFlagFileCategory{
Paul Duffin46169772021-04-14 15:01:56 +0100264 // See HiddenAPIFlagFileProperties.Unsupported
Paul Duffine3dc6602021-04-14 09:50:43 +0100265 {
266 propertyName: "unsupported",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100267 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100268 return properties.Unsupported
269 },
270 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
271 command.FlagWithInput("--unsupported ", path)
272 },
273 },
Paul Duffin46169772021-04-14 15:01:56 +0100274 // See HiddenAPIFlagFileProperties.Removed
Paul Duffine3dc6602021-04-14 09:50:43 +0100275 {
276 propertyName: "removed",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100277 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100278 return properties.Removed
279 },
280 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
281 command.FlagWithInput("--unsupported ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "removed")
282 },
283 },
Paul Duffin46169772021-04-14 15:01:56 +0100284 // See HiddenAPIFlagFileProperties.Max_target_r_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100285 {
286 propertyName: "max_target_r_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100287 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100288 return properties.Max_target_r_low_priority
289 },
290 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
291 command.FlagWithInput("--max-target-r ", path).FlagWithArg("--tag ", "lo-prio")
292 },
293 },
Paul Duffin46169772021-04-14 15:01:56 +0100294 // See HiddenAPIFlagFileProperties.Max_target_q
Paul Duffine3dc6602021-04-14 09:50:43 +0100295 {
296 propertyName: "max_target_q",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100297 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100298 return properties.Max_target_q
299 },
300 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
301 command.FlagWithInput("--max-target-q ", path)
302 },
303 },
Paul Duffin46169772021-04-14 15:01:56 +0100304 // See HiddenAPIFlagFileProperties.Max_target_p
Paul Duffine3dc6602021-04-14 09:50:43 +0100305 {
306 propertyName: "max_target_p",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100307 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100308 return properties.Max_target_p
309 },
310 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
311 command.FlagWithInput("--max-target-p ", path)
312 },
313 },
Paul Duffin46169772021-04-14 15:01:56 +0100314 // See HiddenAPIFlagFileProperties.Max_target_o_low_priority
Paul Duffine3dc6602021-04-14 09:50:43 +0100315 {
316 propertyName: "max_target_o_low_priority",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100317 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100318 return properties.Max_target_o_low_priority
319 },
320 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
321 command.FlagWithInput("--max-target-o ", path).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "lo-prio")
322 },
323 },
Paul Duffin46169772021-04-14 15:01:56 +0100324 // See HiddenAPIFlagFileProperties.Blocked
Paul Duffine3dc6602021-04-14 09:50:43 +0100325 {
326 propertyName: "blocked",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100327 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100328 return properties.Blocked
329 },
330 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
331 command.FlagWithInput("--blocked ", path)
332 },
333 },
Paul Duffin46169772021-04-14 15:01:56 +0100334 // See HiddenAPIFlagFileProperties.Unsupported_packages
Paul Duffine3dc6602021-04-14 09:50:43 +0100335 {
336 propertyName: "unsupported_packages",
Paul Duffincc17bfe2021-04-19 13:21:20 +0100337 propertyValueReader: func(properties *HiddenAPIFlagFileProperties) []string {
Paul Duffine3dc6602021-04-14 09:50:43 +0100338 return properties.Unsupported_packages
339 },
340 commandMutator: func(command *android.RuleBuilderCommand, path android.Path) {
341 command.FlagWithInput("--unsupported ", path).Flag("--packages ")
342 },
343 },
Paul Duffin702210b2021-04-08 20:12:41 +0100344}
345
Paul Duffin438eb572021-05-21 16:58:23 +0100346// FlagFilesByCategory maps a hiddenAPIFlagFileCategory to the paths to the files in that category.
347type FlagFilesByCategory map[*hiddenAPIFlagFileCategory]android.Paths
348
349// append appends the supplied flags files to the corresponding category in this map.
350func (s FlagFilesByCategory) append(other FlagFilesByCategory) {
351 for _, category := range hiddenAPIFlagFileCategories {
352 s[category] = append(s[category], other[category]...)
353 }
354}
355
356// dedup removes duplicates in the flag files, while maintaining the order in which they were
357// appended.
358func (s FlagFilesByCategory) dedup() {
359 for category, paths := range s {
360 s[category] = android.FirstUniquePaths(paths)
361 }
362}
363
Paul Duffinaf99afa2021-05-21 22:18:56 +0100364// HiddenAPIInfo contains information provided by the hidden API processing.
Paul Duffin2fef1362021-04-15 13:32:00 +0100365//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100366// That includes paths resolved from HiddenAPIFlagFileProperties and also generated by hidden API
367// processing.
368type HiddenAPIInfo struct {
Paul Duffin438eb572021-05-21 16:58:23 +0100369 // FlagFilesByCategory maps from the flag file category to the paths containing information for
370 // that category.
371 FlagFilesByCategory FlagFilesByCategory
Paul Duffin2fef1362021-04-15 13:32:00 +0100372
Paul Duffin18cf1972021-05-21 22:46:59 +0100373 // The paths to the stub dex jars for each of the android.SdkKind in hiddenAPIRelevantSdkKinds.
Paul Duffinf1b358c2021-05-17 07:38:47 +0100374 TransitiveStubDexJarsByKind StubDexJarsByKind
Paul Duffin18cf1972021-05-21 22:46:59 +0100375
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100376 // The output from the hidden API processing needs to be made available to other modules.
377 HiddenAPIFlagOutput
Paul Duffinc6bb7cf2021-04-08 17:49:27 +0100378}
Paul Duffin702210b2021-04-08 20:12:41 +0100379
Paul Duffinf1b358c2021-05-17 07:38:47 +0100380func newHiddenAPIInfo() *HiddenAPIInfo {
381 info := HiddenAPIInfo{
382 FlagFilesByCategory: FlagFilesByCategory{},
383 TransitiveStubDexJarsByKind: StubDexJarsByKind{},
384 }
385 return &info
386}
387
388func (i *HiddenAPIInfo) mergeFromFragmentDeps(ctx android.ModuleContext, fragments []android.Module) {
389 // Merge all the information from the fragments. The fragments form a DAG so it is possible that
390 // this will introduce duplicates so they will be resolved after processing all the fragments.
391 for _, fragment := range fragments {
392 if ctx.OtherModuleHasProvider(fragment, HiddenAPIInfoProvider) {
393 info := ctx.OtherModuleProvider(fragment, HiddenAPIInfoProvider).(HiddenAPIInfo)
394 i.TransitiveStubDexJarsByKind.append(info.TransitiveStubDexJarsByKind)
395 }
396 }
397
398 // Dedup and sort paths.
399 i.TransitiveStubDexJarsByKind.dedupAndSort()
400}
401
Paul Duffinaf99afa2021-05-21 22:18:56 +0100402var HiddenAPIInfoProvider = blueprint.NewProvider(HiddenAPIInfo{})
Paul Duffin9b381ef2021-04-08 23:01:37 +0100403
Paul Duffin1352f7c2021-05-21 22:18:49 +0100404// StubDexJarsByKind maps an android.SdkKind to the paths to stub dex jars appropriate for that
405// level. See hiddenAPIRelevantSdkKinds for a list of the acceptable android.SdkKind values.
406type StubDexJarsByKind map[android.SdkKind]android.Paths
407
408// append appends the supplied kind specific stub dex jar pargs to the corresponding kind in this
409// map.
410func (s StubDexJarsByKind) append(other StubDexJarsByKind) {
411 for _, kind := range hiddenAPIRelevantSdkKinds {
412 s[kind] = append(s[kind], other[kind]...)
413 }
414}
415
416// dedupAndSort removes duplicates in the stub dex jar paths and sorts them into a consistent and
417// deterministic order.
418func (s StubDexJarsByKind) dedupAndSort() {
419 for kind, paths := range s {
420 s[kind] = android.SortedUniquePaths(paths)
421 }
422}
423
424// HiddenAPIFlagInput encapsulates information obtained from a module and its dependencies that are
425// needed for hidden API flag generation.
426type HiddenAPIFlagInput struct {
427 // FlagFilesByCategory contains the flag files that override the initial flags that are derived
428 // from the stub dex files.
429 FlagFilesByCategory FlagFilesByCategory
430
431 // StubDexJarsByKind contains the stub dex jars for different android.SdkKind and which determine
432 // the initial flags for each dex member.
433 StubDexJarsByKind StubDexJarsByKind
Paul Duffinf1b358c2021-05-17 07:38:47 +0100434
435 // DependencyStubDexJarsByKind contains the stub dex jars provided by the fragments on which this
436 // depends. It is the result of merging HiddenAPIInfo.TransitiveStubDexJarsByKind from each
437 // fragment on which this depends.
438 DependencyStubDexJarsByKind StubDexJarsByKind
Paul Duffin1352f7c2021-05-21 22:18:49 +0100439}
440
441// newHiddenAPIFlagInput creates a new initialize HiddenAPIFlagInput struct.
442func newHiddenAPIFlagInput() HiddenAPIFlagInput {
443 input := HiddenAPIFlagInput{
444 FlagFilesByCategory: FlagFilesByCategory{},
445 StubDexJarsByKind: StubDexJarsByKind{},
446 }
447
448 return input
449}
450
Paul Duffin62370922021-05-23 16:55:37 +0100451// canPerformHiddenAPIProcessing determines whether hidden API processing should be performed.
452//
453// A temporary workaround to avoid existing bootclasspath_fragments that do not provide the
454// appropriate information needed for hidden API processing breaking the build.
455// TODO(b/179354495): Remove this workaround.
456func (i *HiddenAPIFlagInput) canPerformHiddenAPIProcessing(ctx android.ModuleContext, properties bootclasspathFragmentProperties) bool {
457 // Performing hidden API processing without stubs is not supported and it is unlikely to ever be
458 // required as the whole point of adding something to the bootclasspath fragment is to add it to
459 // the bootclasspath in order to be used by something else in the system. Without any stubs it
460 // cannot do that.
461 if len(i.StubDexJarsByKind) == 0 {
462 return false
463 }
464
465 // Hidden API processing is always enabled in tests.
466 if ctx.Config().TestProductVariables != nil {
467 return true
468 }
469
470 // A module that has fragments should have access to the information it needs in order to perform
471 // hidden API processing.
472 if len(properties.Fragments) != 0 {
473 return true
474 }
475
476 // The art bootclasspath fragment does not depend on any other fragments but already supports
477 // hidden API processing.
478 imageName := proptools.String(properties.Image_name)
479 if imageName == "art" {
480 return true
481 }
482
483 // Disable it for everything else.
484 return false
485}
486
Paul Duffin1352f7c2021-05-21 22:18:49 +0100487// gatherStubLibInfo gathers information from the stub libs needed by hidden API processing from the
488// dependencies added in hiddenAPIAddStubLibDependencies.
489//
490// That includes paths to the stub dex jars as well as paths to the *removed.txt files.
491func (i *HiddenAPIFlagInput) gatherStubLibInfo(ctx android.ModuleContext, contents []android.Module) {
492 addFromModule := func(ctx android.ModuleContext, module android.Module, kind android.SdkKind) {
493 dexJar := hiddenAPIRetrieveDexJarBuildPath(ctx, module, kind)
494 if dexJar != nil {
495 i.StubDexJarsByKind[kind] = append(i.StubDexJarsByKind[kind], dexJar)
496 }
497 }
498
499 // If the contents includes any java_sdk_library modules then add them to the stubs.
500 for _, module := range contents {
501 if _, ok := module.(SdkLibraryDependency); ok {
502 // Add information for every possible kind needed by hidden API. SdkCorePlatform is not used
503 // as the java_sdk_library does not have special support for core_platform API, instead it is
504 // implemented as a customized form of SdkPublic.
505 for _, kind := range []android.SdkKind{android.SdkPublic, android.SdkSystem, android.SdkTest} {
506 addFromModule(ctx, module, kind)
507 }
508 }
509 }
510
511 ctx.VisitDirectDepsIf(isActiveModule, func(module android.Module) {
512 tag := ctx.OtherModuleDependencyTag(module)
513 if hiddenAPIStubsTag, ok := tag.(hiddenAPIStubsDependencyTag); ok {
514 kind := hiddenAPIStubsTag.sdkKind
515 addFromModule(ctx, module, kind)
516 }
517 })
518
519 // Normalize the paths, i.e. remove duplicates and sort.
520 i.StubDexJarsByKind.dedupAndSort()
521}
522
523// extractFlagFilesFromProperties extracts the paths to flag files that are specified in the
524// supplied properties and stores them in this struct.
525func (i *HiddenAPIFlagInput) extractFlagFilesFromProperties(ctx android.ModuleContext, p *HiddenAPIFlagFileProperties) {
526 for _, category := range hiddenAPIFlagFileCategories {
527 paths := android.PathsForModuleSrc(ctx, category.propertyValueReader(p))
528 i.FlagFilesByCategory[category] = paths
529 }
530}
531
Paul Duffinf1b358c2021-05-17 07:38:47 +0100532func (i *HiddenAPIFlagInput) transitiveStubDexJarsByKind() StubDexJarsByKind {
533 transitive := i.DependencyStubDexJarsByKind
534 transitive.append(i.StubDexJarsByKind)
535 return transitive
536}
537
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100538// HiddenAPIFlagOutput contains paths to output files from the hidden API flag generation for a
539// bootclasspath_fragment module.
540type HiddenAPIFlagOutput struct {
541 // The path to the generated stub-flags.csv file.
542 StubFlagsPath android.Path
543
544 // The path to the generated annotation-flags.csv file.
545 AnnotationFlagsPath android.Path
546
547 // The path to the generated metadata.csv file.
548 MetadataPath android.Path
549
550 // The path to the generated index.csv file.
551 IndexPath android.Path
552
553 // The path to the generated all-flags.csv file.
554 AllFlagsPath android.Path
555}
556
Paul Duffindfa10832021-05-13 17:31:51 +0100557// pathForValidation creates a path of the same type as the supplied type but with a name of
558// <path>.valid.
559//
560// e.g. If path is an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv then this will return
561// an OutputPath for out/soong/hiddenapi/hiddenapi-flags.csv.valid
562func pathForValidation(ctx android.PathContext, path android.WritablePath) android.WritablePath {
563 extWithoutLeadingDot := strings.TrimPrefix(path.Ext(), ".")
564 return path.ReplaceExtension(ctx, extWithoutLeadingDot+".valid")
565}
566
Paul Duffin2fef1362021-04-15 13:32:00 +0100567// buildRuleToGenerateHiddenApiFlags creates a rule to create the monolithic hidden API flags from
568// the flags from all the modules, the stub flags, augmented with some additional configuration
569// files.
Paul Duffin702210b2021-04-08 20:12:41 +0100570//
571// baseFlagsPath is the path to the flags file containing all the information from the stubs plus
572// an entry for every single member in the dex implementation jars of the individual modules. Every
573// signature in any of the other files MUST be included in this file.
574//
Paul Duffin537ea3d2021-05-14 10:38:00 +0100575// annotationFlags is the path to the annotation flags file generated from annotation information
576// in each module.
Paul Duffin702210b2021-04-08 20:12:41 +0100577//
Paul Duffinaf99afa2021-05-21 22:18:56 +0100578// hiddenAPIInfo is a struct containing paths to files that augment the information provided by
Paul Duffin537ea3d2021-05-14 10:38:00 +0100579// the annotationFlags.
Paul Duffin438eb572021-05-21 16:58:23 +0100580func buildRuleToGenerateHiddenApiFlags(ctx android.BuilderContext, name, desc string, outputPath android.WritablePath, baseFlagsPath android.Path, annotationFlags android.Path, flagFilesByCategory FlagFilesByCategory, allFlagsPaths android.Paths) {
Paul Duffindfa10832021-05-13 17:31:51 +0100581
582 // The file which is used to record that the flags file is valid.
583 var validFile android.WritablePath
584
585 // If there are flag files that have been generated by fragments on which this depends then use
586 // them to validate the flag file generated by the rules created by this method.
Paul Duffin438eb572021-05-21 16:58:23 +0100587 if len(allFlagsPaths) > 0 {
Paul Duffindfa10832021-05-13 17:31:51 +0100588 // The flags file generated by the rule created by this method needs to be validated to ensure
589 // that it is consistent with the flag files generated by the individual fragments.
590
591 validFile = pathForValidation(ctx, outputPath)
592
593 // Create a rule to validate the output from the following rule.
594 rule := android.NewRuleBuilder(pctx, ctx)
595 rule.Command().
596 BuiltTool("verify_overlaps").
597 Input(outputPath).
598 Inputs(allFlagsPaths).
599 // If validation passes then update the file that records that.
600 Text("&& touch").Output(validFile)
601 rule.Build(name+"Validation", desc+" validation")
602 }
603
604 // Create the rule that will generate the flag files.
Paul Duffind3c15132021-04-21 22:12:35 +0100605 tempPath := tempPathForRestat(ctx, outputPath)
Paul Duffin702210b2021-04-08 20:12:41 +0100606 rule := android.NewRuleBuilder(pctx, ctx)
607 command := rule.Command().
608 BuiltTool("generate_hiddenapi_lists").
609 FlagWithInput("--csv ", baseFlagsPath).
Paul Duffin537ea3d2021-05-14 10:38:00 +0100610 Input(annotationFlags).
Paul Duffin702210b2021-04-08 20:12:41 +0100611 FlagWithOutput("--output ", tempPath)
612
Paul Duffine3dc6602021-04-14 09:50:43 +0100613 // Add the options for the different categories of flag files.
614 for _, category := range hiddenAPIFlagFileCategories {
Paul Duffin438eb572021-05-21 16:58:23 +0100615 paths := flagFilesByCategory[category]
Paul Duffine3dc6602021-04-14 09:50:43 +0100616 for _, path := range paths {
617 category.commandMutator(command, path)
618 }
Paul Duffin702210b2021-04-08 20:12:41 +0100619 }
620
621 commitChangeForRestat(rule, tempPath, outputPath)
622
Paul Duffindfa10832021-05-13 17:31:51 +0100623 if validFile != nil {
624 // Add the file that indicates that the file generated by this is valid.
625 //
626 // This will cause the validation rule above to be run any time that the output of this rule
627 // changes but the validation will run in parallel with other rules that depend on this file.
628 command.Validation(validFile)
629 }
630
Paul Duffin2fef1362021-04-15 13:32:00 +0100631 rule.Build(name, desc)
632}
633
634// hiddenAPIGenerateAllFlagsForBootclasspathFragment will generate all the flags for a fragment
635// of the bootclasspath.
636//
637// It takes:
638// * Map from android.SdkKind to stub dex jar paths defining the API for that sdk kind.
639// * The list of modules that are the contents of the fragment.
640// * The additional manually curated flag files to use.
641//
642// It generates:
643// * stub-flags.csv
644// * annotation-flags.csv
645// * metadata.csv
646// * index.csv
647// * all-flags.csv
Paul Duffin1352f7c2021-05-21 22:18:49 +0100648func hiddenAPIGenerateAllFlagsForBootclasspathFragment(ctx android.ModuleContext, contents []hiddenAPIModule, input HiddenAPIFlagInput) *HiddenAPIFlagOutput {
Paul Duffin2fef1362021-04-15 13:32:00 +0100649 hiddenApiSubDir := "modular-hiddenapi"
650
Paul Duffin1352f7c2021-05-21 22:18:49 +0100651 // Gather the dex files for the boot libraries provided by this fragment.
Paul Duffin537ea3d2021-05-14 10:38:00 +0100652 bootDexJars := extractBootDexJarsFromHiddenAPIModules(ctx, contents)
Paul Duffin1352f7c2021-05-21 22:18:49 +0100653
654 // Generate the stub-flags.csv.
Paul Duffin2fef1362021-04-15 13:32:00 +0100655 stubFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "stub-flags.csv")
Paul Duffin1352f7c2021-05-21 22:18:49 +0100656 rule := ruleToGenerateHiddenAPIStubFlagsFile(ctx, stubFlagsCSV, bootDexJars, input)
Paul Duffin2fef1362021-04-15 13:32:00 +0100657 rule.Build("modularHiddenAPIStubFlagsFile", "modular hiddenapi stub flags")
658
Paul Duffin537ea3d2021-05-14 10:38:00 +0100659 // Extract the classes jars from the contents.
660 classesJars := extractClassJarsFromHiddenAPIModules(ctx, contents)
661
Paul Duffin2fef1362021-04-15 13:32:00 +0100662 // Generate the set of flags from the annotations in the source code.
663 annotationFlagsCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "annotation-flags.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +0100664 buildRuleToGenerateAnnotationFlags(ctx, "modular hiddenapi annotation flags", classesJars, stubFlagsCSV, annotationFlagsCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +0100665
666 // Generate the metadata from the annotations in the source code.
667 metadataCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "metadata.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +0100668 buildRuleToGenerateMetadata(ctx, "modular hiddenapi metadata", classesJars, stubFlagsCSV, metadataCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +0100669
Paul Duffin537ea3d2021-05-14 10:38:00 +0100670 // Generate the index file from the CSV files in the classes jars.
Paul Duffin2fef1362021-04-15 13:32:00 +0100671 indexCSV := android.PathForModuleOut(ctx, hiddenApiSubDir, "index.csv")
Paul Duffin850e61f2021-05-14 09:58:48 +0100672 buildRuleToGenerateIndex(ctx, "modular hiddenapi index", classesJars, indexCSV)
Paul Duffin2fef1362021-04-15 13:32:00 +0100673
Paul Duffinaf99afa2021-05-21 22:18:56 +0100674 // 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 +0100675 // containing dex signatures of all the removed APIs. In the monolithic files that is done by
676 // manually combining all the removed.txt files for each API and then converting them to dex
677 // signatures, see the combined-removed-dex module. That will all be done automatically in future.
678 // For now removed APIs are ignored.
679 // TODO(b/179354495): handle removed apis automatically.
680
681 // Generate the all-flags.csv which are the flags that will, in future, be encoded into the dex
682 // files.
683 outputPath := android.PathForModuleOut(ctx, hiddenApiSubDir, "all-flags.csv")
Paul Duffin1352f7c2021-05-21 22:18:49 +0100684 buildRuleToGenerateHiddenApiFlags(ctx, "modularHiddenApiAllFlags", "modular hiddenapi all flags", outputPath, stubFlagsCSV, annotationFlagsCSV, input.FlagFilesByCategory, nil)
Paul Duffin2fef1362021-04-15 13:32:00 +0100685
686 // Store the paths in the info for use by other modules and sdk snapshot generation.
Paul Duffin1e6f5c42021-05-21 16:15:31 +0100687 output := HiddenAPIFlagOutput{
688 StubFlagsPath: stubFlagsCSV,
689 AnnotationFlagsPath: annotationFlagsCSV,
690 MetadataPath: metadataCSV,
691 IndexPath: indexCSV,
692 AllFlagsPath: outputPath,
693 }
694 return &output
Paul Duffin702210b2021-04-08 20:12:41 +0100695}
Paul Duffin537ea3d2021-05-14 10:38:00 +0100696
697// gatherHiddenAPIModuleFromContents gathers the hiddenAPIModule from the supplied contents.
698func gatherHiddenAPIModuleFromContents(ctx android.ModuleContext, contents []android.Module) []hiddenAPIModule {
699 hiddenAPIModules := []hiddenAPIModule{}
700 for _, module := range contents {
701 if hiddenAPI, ok := module.(hiddenAPIModule); ok {
702 hiddenAPIModules = append(hiddenAPIModules, hiddenAPI)
703 } else if _, ok := module.(*DexImport); ok {
704 // Ignore this for the purposes of hidden API processing
705 } else {
706 ctx.ModuleErrorf("module %s does not implement hiddenAPIModule", module)
707 }
708 }
709 return hiddenAPIModules
710}
711
712// extractBootDexJarsFromHiddenAPIModules extracts the boot dex jars from the supplied modules.
713func extractBootDexJarsFromHiddenAPIModules(ctx android.ModuleContext, contents []hiddenAPIModule) android.Paths {
714 bootDexJars := android.Paths{}
715 for _, module := range contents {
716 bootDexJar := module.bootDexJar()
717 if bootDexJar == nil {
Paul Duffin7487a7a2021-05-19 09:36:09 +0100718 if ctx.Config().AlwaysUsePrebuiltSdks() {
719 // TODO(b/179354495): Remove this work around when it is unnecessary.
720 // Prebuilt modules like framework-wifi do not yet provide dex implementation jars. So,
721 // create a fake one that will cause a build error only if it is used.
722 fake := android.PathForModuleOut(ctx, "fake/boot-dex/%s.jar", module.Name())
723
724 // Create an error rule that pretends to create the output file but will actually fail if it
725 // is run.
726 ctx.Build(pctx, android.BuildParams{
727 Rule: android.ErrorRule,
728 Output: fake,
729 Args: map[string]string{
730 "error": fmt.Sprintf("missing dependencies: boot dex jar for %s", module),
731 },
732 })
733 bootDexJars = append(bootDexJars, fake)
734 } else {
735 ctx.ModuleErrorf("module %s does not provide a dex jar", module)
736 }
Paul Duffin537ea3d2021-05-14 10:38:00 +0100737 } else {
738 bootDexJars = append(bootDexJars, bootDexJar)
739 }
740 }
741 return bootDexJars
742}
743
744// extractClassJarsFromHiddenAPIModules extracts the class jars from the supplied modules.
745func extractClassJarsFromHiddenAPIModules(ctx android.ModuleContext, contents []hiddenAPIModule) android.Paths {
746 classesJars := android.Paths{}
747 for _, module := range contents {
748 classesJars = append(classesJars, module.classesJars()...)
749 }
750 return classesJars
751}