blob: b1a9debe144e062070966a16bcf93db8c933f370 [file] [log] [blame]
Colin Cross8faf8fc2019-01-16 15:15:52 -08001// Copyright 2019 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
Colin Cross8faf8fc2019-01-16 15:15:52 -080018 "github.com/google/blueprint"
19
20 "android/soong/android"
21)
22
Cole Fausta5f64f02023-02-14 17:50:31 -080023var (
24 hiddenAPIGenerateCSVRule = pctx.AndroidStaticRule("hiddenAPIGenerateCSV", blueprint.RuleParams{
25 Command: "${config.Class2NonSdkList} --stub-api-flags ${stubAPIFlags} $in $outFlag $out",
26 CommandDeps: []string{"${config.Class2NonSdkList}"},
27 }, "outFlag", "stubAPIFlags")
28
29 hiddenAPIGenerateIndexRule = pctx.AndroidStaticRule("hiddenAPIGenerateIndex", blueprint.RuleParams{
30 Command: "${config.MergeCsvCommand} --zip_input --key_field signature --output=$out $in",
31 CommandDeps: []string{"${config.MergeCsvCommand}"},
32 })
33)
Colin Cross8faf8fc2019-01-16 15:15:52 -080034
Colin Crossf24a22a2019-01-31 14:12:44 -080035type hiddenAPI struct {
Paul Duffinf75e5272021-02-09 14:34:25 +000036 // True if the module containing this structure contributes to the hiddenapi information or has
37 // that information encoded within it.
Paul Duffin4103e922021-02-01 19:01:34 +000038 active bool
39
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +010040 // The path to the dex jar that is in the boot class path. If this is unset then the associated
Paul Duffinff774a02021-01-29 12:53:15 +000041 // module is not a boot jar, but could be one of the <x>-hiddenapi modules that provide additional
42 // annotations for the <x> boot dex jar but which do not actually provide a boot dex jar
43 // themselves.
Paul Duffin4103e922021-02-01 19:01:34 +000044 //
45 // This must be the path to the unencoded dex jar as the encoded dex jar indirectly depends on
46 // this file so using the encoded dex jar here would result in a cycle in the ninja rules.
Spandan Das3a392012024-01-17 18:26:27 +000047 bootDexJarPath OptionalDexJarPath
48 bootDexJarPathErr error
Paul Duffinff774a02021-01-29 12:53:15 +000049
Paul Duffin36187b22021-04-22 16:43:06 +010050 // The paths to the classes jars that contain classes and class members annotated with
51 // the UnsupportedAppUsage annotation that need to be extracted as part of the hidden API
52 // processing.
53 classesJarPaths android.Paths
Paul Duffin1bbd0622021-05-14 15:52:25 +010054
55 // The compressed state of the dex file being encoded. This is used to ensure that the encoded
56 // dex file has the same state.
57 uncompressDexState *bool
Colin Crossf24a22a2019-01-31 14:12:44 -080058}
59
Spandan Das3a392012024-01-17 18:26:27 +000060func (h *hiddenAPI) bootDexJar(ctx android.ModuleErrorfContext) OptionalDexJarPath {
61 if h.bootDexJarPathErr != nil {
62 ctx.ModuleErrorf(h.bootDexJarPathErr.Error())
63 }
Colin Crossf24a22a2019-01-31 14:12:44 -080064 return h.bootDexJarPath
65}
66
Paul Duffin36187b22021-04-22 16:43:06 +010067func (h *hiddenAPI) classesJars() android.Paths {
68 return h.classesJarPaths
69}
70
Paul Duffin1bbd0622021-05-14 15:52:25 +010071func (h *hiddenAPI) uncompressDex() *bool {
72 return h.uncompressDexState
73}
74
Paul Duffin537ea3d2021-05-14 10:38:00 +010075// hiddenAPIModule is the interface a module that embeds the hiddenAPI structure must implement.
76type hiddenAPIModule interface {
77 android.Module
78 hiddenAPIIntf
Paul Duffin09817d62022-04-28 17:45:11 +010079
Spandan Das8c9ae7e2023-03-03 21:20:36 +000080 MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel
Paul Duffin537ea3d2021-05-14 10:38:00 +010081}
82
Colin Crossf24a22a2019-01-31 14:12:44 -080083type hiddenAPIIntf interface {
Spandan Das3a392012024-01-17 18:26:27 +000084 bootDexJar(ctx android.ModuleErrorfContext) OptionalDexJarPath
Paul Duffin36187b22021-04-22 16:43:06 +010085 classesJars() android.Paths
Paul Duffin1bbd0622021-05-14 15:52:25 +010086 uncompressDex() *bool
Colin Crossf24a22a2019-01-31 14:12:44 -080087}
88
89var _ hiddenAPIIntf = (*hiddenAPI)(nil)
90
Paul Duffin4103e922021-02-01 19:01:34 +000091// Initialize the hiddenapi structure
Paul Duffin1bbd0622021-05-14 15:52:25 +010092//
93// uncompressedDexState should be nil when the module is a prebuilt and so does not require hidden
94// API encoding.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +010095func (h *hiddenAPI) initHiddenAPI(ctx android.ModuleContext, dexJar OptionalDexJarPath, classesJar android.Path, uncompressedDexState *bool) {
Paul Duffin74d18d12021-05-14 14:18:47 +010096
97 // Save the classes jars even if this is not active as they may be used by modular hidden API
98 // processing.
99 classesJars := android.Paths{classesJar}
100 ctx.VisitDirectDepsWithTag(hiddenApiAnnotationsTag, func(dep android.Module) {
Colin Cross7727c7f2024-07-18 15:36:32 -0700101 if javaInfo, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
102 classesJars = append(classesJars, javaInfo.ImplementationJars...)
103 }
Paul Duffin74d18d12021-05-14 14:18:47 +0100104 })
105 h.classesJarPaths = classesJars
106
107 // Save the unencoded dex jar so it can be used when generating the
108 // hiddenAPISingletonPathsStruct.stubFlags file.
109 h.bootDexJarPath = dexJar
110
Paul Duffin1bbd0622021-05-14 15:52:25 +0100111 h.uncompressDexState = uncompressedDexState
112
Paul Duffin4103e922021-02-01 19:01:34 +0000113 // If hiddenapi processing is disabled treat this as inactive.
Pratyushfaec4db2023-07-20 11:19:04 +0000114 if ctx.Config().DisableHiddenApiChecks() {
Paul Duffin4103e922021-02-01 19:01:34 +0000115 return
116 }
117
Paul Duffin74d18d12021-05-14 14:18:47 +0100118 // The context module must implement hiddenAPIModule.
119 module := ctx.Module().(hiddenAPIModule)
120
Paul Duffinb6f53c02021-05-14 07:52:42 +0100121 // If the frameworks/base directories does not exist and no prebuilt hidden API flag files have
122 // been configured then it is not possible to do hidden API encoding.
123 if !ctx.Config().FrameworksBaseDirExists(ctx) && ctx.Config().PrebuiltHiddenApiDir(ctx) == "" {
124 return
125 }
126
Paul Duffin4103e922021-02-01 19:01:34 +0000127 // It is important that hiddenapi information is only gathered for/from modules that are actually
128 // on the boot jars list because the runtime only enforces access to the hidden API for the
129 // bootclassloader. If information is gathered for modules not on the list then that will cause
130 // failures in the CtsHiddenApiBlocklist... tests.
Paul Duffin82b3fcf2021-02-12 15:42:46 +0000131 h.active = isModuleInBootClassPath(ctx, module)
Paul Duffin4103e922021-02-01 19:01:34 +0000132}
133
Spandan Das3a392012024-01-17 18:26:27 +0000134// Store any error encountered during the initialization of hiddenapi structure (e.g. unflagged co-existing prebuilt apexes)
135func (h *hiddenAPI) initHiddenAPIError(err error) {
136 h.bootDexJarPathErr = err
137}
138
Paul Duffin82b3fcf2021-02-12 15:42:46 +0000139func isModuleInBootClassPath(ctx android.BaseModuleContext, module android.Module) bool {
satayevd604b212021-07-21 14:23:52 +0100140 // Get the configured platform and apex boot jars.
141 nonApexBootJars := ctx.Config().NonApexBootJars()
142 apexBootJars := ctx.Config().ApexBootJars()
143 active := isModuleInConfiguredList(ctx, module, nonApexBootJars) ||
144 isModuleInConfiguredList(ctx, module, apexBootJars)
Paul Duffin82b3fcf2021-02-12 15:42:46 +0000145 return active
146}
147
Paul Duffinafaa47c2021-05-14 13:04:04 +0100148// hiddenAPIEncodeDex is called by any module that needs to encode dex files.
Paul Duffin4103e922021-02-01 19:01:34 +0000149//
150// It ignores any module that has not had initHiddenApi() called on it and which is not in the boot
Paul Duffinafaa47c2021-05-14 13:04:04 +0100151// jar list. In that case it simply returns the supplied dex jar path.
Paul Duffin4103e922021-02-01 19:01:34 +0000152//
Paul Duffinafaa47c2021-05-14 13:04:04 +0100153// Otherwise, it creates a copy of the supplied dex file into which it has encoded the hiddenapi
154// flags and returns this instead of the supplied dex jar.
Colin Cross7707b242024-07-26 12:02:36 -0700155func (h *hiddenAPI) hiddenAPIEncodeDex(ctx android.ModuleContext, dexJar android.Path) android.Path {
Paul Duffin001e6062021-05-14 01:13:55 +0100156
Paul Duffin4103e922021-02-01 19:01:34 +0000157 if !h.active {
158 return dexJar
159 }
Paul Duffind2aceca2019-02-28 16:13:20 +0000160
Paul Duffin1bbd0622021-05-14 15:52:25 +0100161 // A nil uncompressDexState prevents the dex file from being encoded.
162 if h.uncompressDexState == nil {
163 ctx.ModuleErrorf("cannot encode dex file %s when uncompressDexState is nil", dexJar)
164 }
165 uncompressDex := *h.uncompressDexState
166
Paul Duffinf8f4af82021-02-12 15:42:20 +0000167 // Create a copy of the dex jar which has been encoded with hiddenapi flags.
Paul Duffin09165952021-05-16 23:32:52 +0100168 flagsCSV := hiddenAPISingletonPaths(ctx).flags
169 outputDir := android.PathForModuleOut(ctx, "hiddenapi").OutputPath
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000170 encodedDex := hiddenAPIEncodeDex(ctx, dexJar, flagsCSV, uncompressDex, android.NoneApiLevel, outputDir)
Paul Duffin4103e922021-02-01 19:01:34 +0000171
Paul Duffinf8f4af82021-02-12 15:42:20 +0000172 // Use the encoded dex jar from here onwards.
Paul Duffin09165952021-05-16 23:32:52 +0100173 return encodedDex
Colin Crossf24a22a2019-01-31 14:12:44 -0800174}
175
Paul Duffin850e61f2021-05-14 09:58:48 +0100176// buildRuleToGenerateAnnotationFlags builds a ninja rule to generate the annotation-flags.csv file
177// from the classes jars and stub-flags.csv files.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100178//
179// The annotation-flags.csv file contains mappings from Java signature to various flags derived from
180// annotations in the source, e.g. whether it is public or the sdk version above which it can no
181// longer be used.
182//
183// It is created by the Class2NonSdkList tool which processes the .class files in the class
184// implementation jar looking for UnsupportedAppUsage and CovariantReturnType annotations. The
185// tool also consumes the hiddenAPISingletonPathsStruct.stubFlags file in order to perform
186// consistency checks on the information in the annotations and to filter out bridge methods
187// that are already part of the public API.
Paul Duffin850e61f2021-05-14 09:58:48 +0100188func buildRuleToGenerateAnnotationFlags(ctx android.ModuleContext, desc string, classesJars android.Paths, stubFlagsCSV android.Path, outputPath android.WritablePath) {
Colin Cross8faf8fc2019-01-16 15:15:52 -0800189 ctx.Build(pctx, android.BuildParams{
190 Rule: hiddenAPIGenerateCSVRule,
Paul Duffin850e61f2021-05-14 09:58:48 +0100191 Description: desc,
Paul Duffin031d8692021-02-12 11:46:42 +0000192 Inputs: classesJars,
Paul Duffin850e61f2021-05-14 09:58:48 +0100193 Output: outputPath,
David Brazdil0f670a22019-01-18 16:30:03 +0000194 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800195 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000196 "outFlag": "--write-flags-csv",
197 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800198 },
199 })
Paul Duffin850e61f2021-05-14 09:58:48 +0100200}
Colin Cross8faf8fc2019-01-16 15:15:52 -0800201
Paul Duffin850e61f2021-05-14 09:58:48 +0100202// buildRuleToGenerateMetadata builds a ninja rule to generate the metadata.csv file from
203// the classes jars and stub-flags.csv files.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100204//
205// The metadata.csv file contains mappings from Java signature to the value of properties specified
206// on UnsupportedAppUsage annotations in the source.
207//
208// Like the annotation-flags.csv file this is also created by the Class2NonSdkList in the same way.
209// Although the two files could potentially be created in a single invocation of the
210// Class2NonSdkList at the moment they are created using their own invocation, with the behavior
211// being determined by the property that is used.
Paul Duffin850e61f2021-05-14 09:58:48 +0100212func buildRuleToGenerateMetadata(ctx android.ModuleContext, desc string, classesJars android.Paths, stubFlagsCSV android.Path, metadataCSV android.WritablePath) {
Colin Cross8faf8fc2019-01-16 15:15:52 -0800213 ctx.Build(pctx, android.BuildParams{
214 Rule: hiddenAPIGenerateCSVRule,
Paul Duffin850e61f2021-05-14 09:58:48 +0100215 Description: desc,
Paul Duffin031d8692021-02-12 11:46:42 +0000216 Inputs: classesJars,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800217 Output: metadataCSV,
David Brazdil0f670a22019-01-18 16:30:03 +0000218 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800219 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000220 "outFlag": "--write-metadata-csv",
221 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800222 },
223 })
Paul Duffin850e61f2021-05-14 09:58:48 +0100224}
Colin Cross8faf8fc2019-01-16 15:15:52 -0800225
Paul Duffinafaa47c2021-05-14 13:04:04 +0100226// buildRuleToGenerateIndex builds a ninja rule to generate the index.csv file from the classes
Paul Duffin850e61f2021-05-14 09:58:48 +0100227// jars.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100228//
229// The index.csv file contains mappings from Java signature to source location information.
230//
231// It is created by the merge_csv tool which processes the class implementation jar, extracting
232// all the files ending in .uau (which are CSV files) and merges them together. The .uau files are
233// created by the unsupported app usage annotation processor during compilation of the class
234// implementation jar.
Paul Duffin850e61f2021-05-14 09:58:48 +0100235func buildRuleToGenerateIndex(ctx android.ModuleContext, desc string, classesJars android.Paths, indexCSV android.WritablePath) {
Cole Fausta5f64f02023-02-14 17:50:31 -0800236 ctx.Build(pctx, android.BuildParams{
237 Rule: hiddenAPIGenerateIndexRule,
238 Description: desc,
239 Inputs: classesJars,
240 Output: indexCSV,
241 })
Colin Cross8faf8fc2019-01-16 15:15:52 -0800242}
243
244var hiddenAPIEncodeDexRule = pctx.AndroidStaticRule("hiddenAPIEncodeDex", blueprint.RuleParams{
Artur Satayevb5df8a02020-02-19 16:39:59 +0000245 Command: `rm -rf $tmpDir && mkdir -p $tmpDir && mkdir $tmpDir/dex-input && mkdir $tmpDir/dex-output &&
Colin Crossd783bbb2020-07-11 22:30:45 -0700246 unzip -qoDD $in 'classes*.dex' -d $tmpDir/dex-input &&
Artur Satayevb5df8a02020-02-19 16:39:59 +0000247 for INPUT_DEX in $$(find $tmpDir/dex-input -maxdepth 1 -name 'classes*.dex' | sort); do
248 echo "--input-dex=$${INPUT_DEX}";
249 echo "--output-dex=$tmpDir/dex-output/$$(basename $${INPUT_DEX})";
250 done | xargs ${config.HiddenAPI} encode --api-flags=$flagsCsv $hiddenapiFlags &&
251 ${config.SoongZipCmd} $soongZipFlags -o $tmpDir/dex.jar -C $tmpDir/dex-output -f "$tmpDir/dex-output/classes*.dex" &&
Paul Duffin4de94502021-05-16 05:21:16 +0100252 ${config.MergeZipsCmd} -j -D -zipToNotStrip $tmpDir/dex.jar -stripFile "classes*.dex" -stripFile "**/*.uau" $out $tmpDir/dex.jar $in`,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800253 CommandDeps: []string{
254 "${config.HiddenAPI}",
255 "${config.SoongZipCmd}",
256 "${config.MergeZipsCmd}",
257 },
David Brazdil91b4e3e2019-01-23 21:04:05 +0000258}, "flagsCsv", "hiddenapiFlags", "tmpDir", "soongZipFlags")
Colin Cross8faf8fc2019-01-16 15:15:52 -0800259
Paul Duffin09165952021-05-16 23:32:52 +0100260// hiddenAPIEncodeDex generates the build rule that will encode the supplied dex jar and place the
261// encoded dex jar in a file of the same name in the output directory.
262//
263// The encode dex rule requires unzipping, encoding and rezipping the classes.dex files along with
264// all the resources from the input jar. It also ensures that if it was uncompressed in the input
265// it stays uncompressed in the output.
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000266func hiddenAPIEncodeDex(ctx android.ModuleContext, dexInput, flagsCSV android.Path, uncompressDex bool, minSdkVersion android.ApiLevel, outputDir android.OutputPath) android.OutputPath {
Colin Crosscd964b32019-01-18 22:03:02 -0800267
Paul Duffin09165952021-05-16 23:32:52 +0100268 // The output file has the same name as the input file and is in the output directory.
269 output := outputDir.Join(ctx, dexInput.Base())
Colin Cross8faf8fc2019-01-16 15:15:52 -0800270
Paul Duffin09165952021-05-16 23:32:52 +0100271 // Create a jar specific temporary directory in which to do the work just in case this is called
272 // with the same output directory for multiple modules.
273 tmpDir := outputDir.Join(ctx, dexInput.Base()+"-tmp")
274
275 // If the input is uncompressed then generate the output of the encode rule to an intermediate
276 // file as the final output will need further processing after encoding.
Colin Crosscd964b32019-01-18 22:03:02 -0800277 soongZipFlags := ""
Paul Duffin09165952021-05-16 23:32:52 +0100278 encodeRuleOutput := output
Colin Crosscd964b32019-01-18 22:03:02 -0800279 if uncompressDex {
280 soongZipFlags = "-L 0"
Paul Duffin09165952021-05-16 23:32:52 +0100281 encodeRuleOutput = outputDir.Join(ctx, "unaligned", dexInput.Base())
Colin Crosscd964b32019-01-18 22:03:02 -0800282 }
Jiyong Park93e57a02020-02-21 16:04:53 +0900283
Jiyong Park93e57a02020-02-21 16:04:53 +0900284 // b/149353192: when a module is instrumented, jacoco adds synthetic members
285 // $jacocoData and $jacocoInit. Since they don't exist when building the hidden API flags,
286 // don't complain when we don't find hidden API flags for the synthetic members.
Paul Duffin09165952021-05-16 23:32:52 +0100287 hiddenapiFlags := ""
Paul Duffinc495d2b2020-05-19 21:07:52 +0100288 if j, ok := ctx.Module().(interface {
289 shouldInstrument(android.BaseModuleContext) bool
290 }); ok && j.shouldInstrument(ctx) {
David Brazdil91b4e3e2019-01-23 21:04:05 +0000291 hiddenapiFlags = "--no-force-assign-all"
292 }
Colin Crosscd964b32019-01-18 22:03:02 -0800293
Paul Duffin09817d62022-04-28 17:45:11 +0100294 // If the library is targeted for Q and/or R then make sure that they do not
295 // have any S+ flags encoded as that will break the runtime.
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000296 minApiLevel := minSdkVersion
Paul Duffin09817d62022-04-28 17:45:11 +0100297 if !minApiLevel.IsNone() {
298 if minApiLevel.LessThanOrEqualTo(android.ApiLevelOrPanic(ctx, "R")) {
299 hiddenapiFlags = hiddenapiFlags + " --max-hiddenapi-level=max-target-r"
300 }
301 }
302
Colin Cross8faf8fc2019-01-16 15:15:52 -0800303 ctx.Build(pctx, android.BuildParams{
304 Rule: hiddenAPIEncodeDexRule,
305 Description: "hiddenapi encode dex",
306 Input: dexInput,
Paul Duffin09165952021-05-16 23:32:52 +0100307 Output: encodeRuleOutput,
Colin Crossf24a22a2019-01-31 14:12:44 -0800308 Implicit: flagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800309 Args: map[string]string{
Colin Crossf24a22a2019-01-31 14:12:44 -0800310 "flagsCsv": flagsCSV.String(),
David Brazdil91b4e3e2019-01-23 21:04:05 +0000311 "tmpDir": tmpDir.String(),
312 "soongZipFlags": soongZipFlags,
313 "hiddenapiFlags": hiddenapiFlags,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800314 },
315 })
316
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000317 if uncompressDex {
Cole Faust51d7bfd2023-09-07 05:31:32 +0000318 TransformZipAlign(ctx, output, encodeRuleOutput, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000319 }
Paul Duffin09165952021-05-16 23:32:52 +0100320
321 return output
Colin Cross8faf8fc2019-01-16 15:15:52 -0800322}
Paul Duffin031d8692021-02-12 11:46:42 +0000323
324type hiddenApiAnnotationsDependencyTag struct {
325 blueprint.BaseDependencyTag
Colin Crossce564252022-01-12 11:13:32 -0800326 android.LicenseAnnotationSharedDependencyTag
Paul Duffin031d8692021-02-12 11:46:42 +0000327}
328
329// Tag used to mark dependencies on java_library instances that contains Java source files whose
330// sole purpose is to provide additional hiddenapi annotations.
331var hiddenApiAnnotationsTag hiddenApiAnnotationsDependencyTag
332
333// Mark this tag so dependencies that use it are excluded from APEX contents.
334func (t hiddenApiAnnotationsDependencyTag) ExcludeFromApexContents() {}
335
336var _ android.ExcludeFromApexContentsTag = hiddenApiAnnotationsTag