blob: f8e41c458e27b05abbb0d4a432d08ce71d2f8abb [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 (
Paul Duffind2aceca2019-02-28 16:13:20 +000018 "strings"
19
Colin Cross8faf8fc2019-01-16 15:15:52 -080020 "github.com/google/blueprint"
21
22 "android/soong/android"
23)
24
25var hiddenAPIGenerateCSVRule = pctx.AndroidStaticRule("hiddenAPIGenerateCSV", blueprint.RuleParams{
Andrei Onea23fea042020-08-12 16:48:23 +010026 Command: "${config.Class2NonSdkList} --stub-api-flags ${stubAPIFlags} $in $outFlag $out",
27 CommandDeps: []string{"${config.Class2NonSdkList}"},
David Brazdil0f670a22019-01-18 16:30:03 +000028}, "outFlag", "stubAPIFlags")
Colin Cross8faf8fc2019-01-16 15:15:52 -080029
Colin Crossf24a22a2019-01-31 14:12:44 -080030type hiddenAPI struct {
Paul Duffinf75e5272021-02-09 14:34:25 +000031 // The name of the module as it would be used in the boot jars configuration, e.g. without any
32 // prebuilt_ prefix (if it is a prebuilt), without any "-hiddenapi" suffix if it just provides
33 // annotations and without any ".impl" suffix if it is a java_sdk_library implementation library.
34 configurationName string
35
36 // 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
Paul Duffinf75e5272021-02-09 14:34:25 +000040 // Identifies the active module variant which will be used as the source of hiddenapi information.
41 //
42 // A class may be compiled into a number of different module variants each of which will need the
43 // hiddenapi information encoded into it and so will be marked as active. However, only one of
44 // them must be used as a source of information by hiddenapi otherwise it will end up with
45 // duplicate entries. That module will have primary=true.
46 //
47 // Note, that modules <x>-hiddenapi that provide additional annotation information for module <x>
48 // that is on the bootclasspath are marked as primary=true as they are the primary source of that
49 // annotation information.
50 primary bool
51
Paul Duffin4103e922021-02-01 19:01:34 +000052 // True if the module only contains additional annotations and so does not require hiddenapi
53 // information to be encoded in its dex file and should not be used to generate the
54 // hiddenAPISingletonPathsStruct.stubFlags file.
55 annotationsOnly bool
56
Paul Duffinff774a02021-01-29 12:53:15 +000057 // The path to the dex jar that is in the boot class path. If this is nil then the associated
58 // module is not a boot jar, but could be one of the <x>-hiddenapi modules that provide additional
59 // annotations for the <x> boot dex jar but which do not actually provide a boot dex jar
60 // themselves.
Paul Duffin4103e922021-02-01 19:01:34 +000061 //
62 // This must be the path to the unencoded dex jar as the encoded dex jar indirectly depends on
63 // this file so using the encoded dex jar here would result in a cycle in the ninja rules.
Paul Duffinff774a02021-01-29 12:53:15 +000064 bootDexJarPath android.Path
65
66 // The path to the CSV file that contains mappings from Java signature to various flags derived
67 // from annotations in the source, e.g. whether it is public or the sdk version above which it
68 // can no longer be used.
69 //
70 // It is created by the Class2NonSdkList tool which processes the .class files in the class
71 // implementation jar looking for UnsupportedAppUsage and CovariantReturnType annotations. The
72 // tool also consumes the hiddenAPISingletonPathsStruct.stubFlags file in order to perform
73 // consistency checks on the information in the annotations and to filter out bridge methods
74 // that are already part of the public API.
75 flagsCSVPath android.Path
76
77 // The path to the CSV file that contains mappings from Java signature to the value of properties
78 // specified on UnsupportedAppUsage annotations in the source.
79 //
80 // Like the flagsCSVPath file this is also created by the Class2NonSdkList in the same way.
81 // Although the two files could potentially be created in a single invocation of the
82 // Class2NonSdkList at the moment they are created using their own invocation, with the behavior
83 // being determined by the property that is used.
Artur Satayevb5df8a02020-02-19 16:39:59 +000084 metadataCSVPath android.Path
Paul Duffinff774a02021-01-29 12:53:15 +000085
86 // The path to the CSV file that contains mappings from Java signature to source location
87 // information.
88 //
89 // It is created by the merge_csv tool which processes the class implementation jar, extracting
90 // all the files ending in .uau (which are CSV files) and merges them together. The .uau files are
91 // created by the unsupported app usage annotation processor during compilation of the class
92 // implementation jar.
93 indexCSVPath android.Path
Colin Crossf24a22a2019-01-31 14:12:44 -080094}
95
96func (h *hiddenAPI) flagsCSV() android.Path {
97 return h.flagsCSVPath
98}
99
100func (h *hiddenAPI) metadataCSV() android.Path {
101 return h.metadataCSVPath
102}
103
104func (h *hiddenAPI) bootDexJar() android.Path {
105 return h.bootDexJarPath
106}
107
Artur Satayevb5df8a02020-02-19 16:39:59 +0000108func (h *hiddenAPI) indexCSV() android.Path {
109 return h.indexCSVPath
110}
111
Colin Crossf24a22a2019-01-31 14:12:44 -0800112type hiddenAPIIntf interface {
Colin Crossf24a22a2019-01-31 14:12:44 -0800113 bootDexJar() android.Path
Artur Satayevb5df8a02020-02-19 16:39:59 +0000114 flagsCSV() android.Path
115 indexCSV() android.Path
116 metadataCSV() android.Path
Colin Crossf24a22a2019-01-31 14:12:44 -0800117}
118
119var _ hiddenAPIIntf = (*hiddenAPI)(nil)
120
Paul Duffin4103e922021-02-01 19:01:34 +0000121// Initialize the hiddenapi structure
122func (h *hiddenAPI) initHiddenAPI(ctx android.BaseModuleContext, name string) {
123 // If hiddenapi processing is disabled treat this as inactive.
124 if ctx.Config().IsEnvTrue("UNSAFE_DISABLE_HIDDENAPI_FLAGS") {
125 return
126 }
127
128 // Modules whose names are of the format <x>-hiddenapi provide hiddenapi information for the boot
129 // jar module <x>. Otherwise, the module provides information for itself. Either way extract the
Paul Duffinf75e5272021-02-09 14:34:25 +0000130 // configurationName of the boot jar module.
131 configurationName := strings.TrimSuffix(name, "-hiddenapi")
132 h.configurationName = configurationName
Paul Duffin4103e922021-02-01 19:01:34 +0000133
134 // It is important that hiddenapi information is only gathered for/from modules that are actually
135 // on the boot jars list because the runtime only enforces access to the hidden API for the
136 // bootclassloader. If information is gathered for modules not on the list then that will cause
137 // failures in the CtsHiddenApiBlocklist... tests.
Paul Duffinf75e5272021-02-09 14:34:25 +0000138 h.active = inList(configurationName, ctx.Config().BootJars())
139 if !h.active {
140 // The rest of the properties will be ignored if active is false.
141 return
142 }
Paul Duffin4103e922021-02-01 19:01:34 +0000143
144 // If this module has a suffix of -hiddenapi then it only provides additional annotation
145 // information for a module on the boot jars list.
146 h.annotationsOnly = strings.HasSuffix(name, "-hiddenapi")
Paul Duffinf75e5272021-02-09 14:34:25 +0000147
148 // Determine whether this module is the primary module or not.
149 primary := true
150
151 // A prebuilt module is only primary if it is preferred and conversely a source module is only
152 // primary if it has not been replaced by a prebuilt module.
153 module := ctx.Module()
154 if pi, ok := module.(android.PrebuiltInterface); ok {
155 if p := pi.Prebuilt(); p != nil {
156 primary = p.UsePrebuilt()
157 }
158 } else {
159 // The only module that will pass a different name to its module name to this method is the
160 // implementation library of a java_sdk_library. It has a configuration name of <x> the same
161 // as its parent java_sdk_library but a module name of <x>.impl. It is not the primary module,
162 // the java_sdk_library with the name of <x> is.
163 primary = name == ctx.ModuleName()
164
165 // A source module that has been replaced by a prebuilt can never be the primary module.
166 primary = primary && !module.IsReplacedByPrebuilt()
167 }
168 h.primary = primary
Paul Duffin4103e922021-02-01 19:01:34 +0000169}
170
Paul Duffin4fd997b2021-02-03 20:06:33 +0000171// hiddenAPIExtractAndEncode is called by any module that could contribute to the hiddenapi
172// processing.
Paul Duffin4103e922021-02-01 19:01:34 +0000173//
174// It ignores any module that has not had initHiddenApi() called on it and which is not in the boot
175// jar list.
176//
177// Otherwise, it generates ninja rules to do the following:
Paul Duffin4fd997b2021-02-03 20:06:33 +0000178// 1. Extract information needed for hiddenapi processing from the module and output it into CSV
179// files.
Paul Duffin4103e922021-02-01 19:01:34 +0000180// 2. Conditionally adds the supplied dex file to the list of files used to generate the
181// hiddenAPISingletonPathsStruct.stubsFlag file.
182// 3. Conditionally creates a copy of the supplied dex file into which it has encoded the hiddenapi
183// flags and returns this instead of the supplied dex jar, otherwise simply returns the supplied
184// dex jar.
Paul Duffinf75e5272021-02-09 14:34:25 +0000185func (h *hiddenAPI) hiddenAPIExtractAndEncode(ctx android.ModuleContext, dexJar android.OutputPath,
Paul Duffin612e6102021-02-02 13:38:13 +0000186 implementationJar android.Path, uncompressDex bool) android.OutputPath {
Paul Duffind2aceca2019-02-28 16:13:20 +0000187
Paul Duffin4103e922021-02-01 19:01:34 +0000188 if !h.active {
189 return dexJar
190 }
Paul Duffind2aceca2019-02-28 16:13:20 +0000191
Paul Duffinf75e5272021-02-09 14:34:25 +0000192 h.hiddenAPIExtractInformation(ctx, dexJar, implementationJar)
Paul Duffind2aceca2019-02-28 16:13:20 +0000193
Paul Duffin4103e922021-02-01 19:01:34 +0000194 if !h.annotationsOnly {
Paul Duffinf75e5272021-02-09 14:34:25 +0000195 hiddenAPIJar := android.PathForModuleOut(ctx, "hiddenapi", h.configurationName+".jar").OutputPath
Paul Duffina2058f82020-06-24 16:22:38 +0100196
Paul Duffin4103e922021-02-01 19:01:34 +0000197 // Create a copy of the dex jar which has been encoded with hiddenapi flags.
198 hiddenAPIEncodeDex(ctx, hiddenAPIJar, dexJar, uncompressDex)
199
200 // Use the encoded dex jar from here onwards.
201 dexJar = hiddenAPIJar
Colin Crossf24a22a2019-01-31 14:12:44 -0800202 }
203
204 return dexJar
205}
206
Paul Duffin4fd997b2021-02-03 20:06:33 +0000207// hiddenAPIExtractInformation generates ninja rules to extract the information from the classes
208// jar, and outputs it to the appropriate module specific CSV file.
209//
210// It also makes the dex jar available for use when generating the
211// hiddenAPISingletonPathsStruct.stubFlags.
Paul Duffinf75e5272021-02-09 14:34:25 +0000212func (h *hiddenAPI) hiddenAPIExtractInformation(ctx android.ModuleContext, dexJar, classesJar android.Path) {
Paul Duffin9d67ca62021-02-03 20:06:33 +0000213 if !h.active {
214 return
215 }
216
217 // More than one library with the same classes may need to be encoded but only one should be
218 // used as a source of information for hidden API processing otherwise it will result in
219 // duplicate entries in the files.
Paul Duffinf75e5272021-02-09 14:34:25 +0000220 if !h.primary {
Paul Duffin9d67ca62021-02-03 20:06:33 +0000221 return
222 }
223
Paul Duffin031d8692021-02-12 11:46:42 +0000224 classesJars := android.Paths{classesJar}
225 ctx.VisitDirectDepsWithTag(hiddenApiAnnotationsTag, func(dep android.Module) {
226 javaInfo := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
227 classesJars = append(classesJars, javaInfo.ImplementationJars...)
228 })
229
Colin Crossf24a22a2019-01-31 14:12:44 -0800230 stubFlagsCSV := hiddenAPISingletonPaths(ctx).stubFlags
Colin Cross8faf8fc2019-01-16 15:15:52 -0800231
Paul Duffin34982f12021-01-27 15:11:42 +0000232 flagsCSV := android.PathForModuleOut(ctx, "hiddenapi", "flags.csv")
Colin Cross8faf8fc2019-01-16 15:15:52 -0800233 ctx.Build(pctx, android.BuildParams{
234 Rule: hiddenAPIGenerateCSVRule,
235 Description: "hiddenapi flags",
Paul Duffin031d8692021-02-12 11:46:42 +0000236 Inputs: classesJars,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800237 Output: flagsCSV,
David Brazdil0f670a22019-01-18 16:30:03 +0000238 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800239 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000240 "outFlag": "--write-flags-csv",
241 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800242 },
243 })
Artur Satayevb5df8a02020-02-19 16:39:59 +0000244 h.flagsCSVPath = flagsCSV
Colin Cross8faf8fc2019-01-16 15:15:52 -0800245
Paul Duffin34982f12021-01-27 15:11:42 +0000246 metadataCSV := android.PathForModuleOut(ctx, "hiddenapi", "metadata.csv")
Colin Cross8faf8fc2019-01-16 15:15:52 -0800247 ctx.Build(pctx, android.BuildParams{
248 Rule: hiddenAPIGenerateCSVRule,
249 Description: "hiddenapi metadata",
Paul Duffin031d8692021-02-12 11:46:42 +0000250 Inputs: classesJars,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800251 Output: metadataCSV,
David Brazdil0f670a22019-01-18 16:30:03 +0000252 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800253 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000254 "outFlag": "--write-metadata-csv",
255 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800256 },
257 })
Artur Satayevb5df8a02020-02-19 16:39:59 +0000258 h.metadataCSVPath = metadataCSV
Colin Cross8faf8fc2019-01-16 15:15:52 -0800259
Paul Duffin34982f12021-01-27 15:11:42 +0000260 indexCSV := android.PathForModuleOut(ctx, "hiddenapi", "index.csv")
Colin Crossf1a035e2020-11-16 17:32:30 -0800261 rule := android.NewRuleBuilder(pctx, ctx)
Artur Satayevb5df8a02020-02-19 16:39:59 +0000262 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800263 BuiltTool("merge_csv").
Paul Duffin031d8692021-02-12 11:46:42 +0000264 Flag("--zip_input").
265 FlagWithOutput("--output=", indexCSV).
266 Inputs(classesJars)
Colin Crossf1a035e2020-11-16 17:32:30 -0800267 rule.Build("merged-hiddenapi-index", "Merged Hidden API index")
Artur Satayevb5df8a02020-02-19 16:39:59 +0000268 h.indexCSVPath = indexCSV
Paul Duffin4fd997b2021-02-03 20:06:33 +0000269
270 // Save the unencoded dex jar so it can be used when generating the
271 // hiddenAPISingletonPathsStruct.stubFlags file.
272 h.bootDexJarPath = dexJar
Colin Cross8faf8fc2019-01-16 15:15:52 -0800273}
274
275var hiddenAPIEncodeDexRule = pctx.AndroidStaticRule("hiddenAPIEncodeDex", blueprint.RuleParams{
Artur Satayevb5df8a02020-02-19 16:39:59 +0000276 Command: `rm -rf $tmpDir && mkdir -p $tmpDir && mkdir $tmpDir/dex-input && mkdir $tmpDir/dex-output &&
Colin Crossd783bbb2020-07-11 22:30:45 -0700277 unzip -qoDD $in 'classes*.dex' -d $tmpDir/dex-input &&
Artur Satayevb5df8a02020-02-19 16:39:59 +0000278 for INPUT_DEX in $$(find $tmpDir/dex-input -maxdepth 1 -name 'classes*.dex' | sort); do
279 echo "--input-dex=$${INPUT_DEX}";
280 echo "--output-dex=$tmpDir/dex-output/$$(basename $${INPUT_DEX})";
281 done | xargs ${config.HiddenAPI} encode --api-flags=$flagsCsv $hiddenapiFlags &&
282 ${config.SoongZipCmd} $soongZipFlags -o $tmpDir/dex.jar -C $tmpDir/dex-output -f "$tmpDir/dex-output/classes*.dex" &&
283 ${config.MergeZipsCmd} -D -zipToNotStrip $tmpDir/dex.jar -stripFile "classes*.dex" -stripFile "**/*.uau" $out $tmpDir/dex.jar $in`,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800284 CommandDeps: []string{
285 "${config.HiddenAPI}",
286 "${config.SoongZipCmd}",
287 "${config.MergeZipsCmd}",
288 },
David Brazdil91b4e3e2019-01-23 21:04:05 +0000289}, "flagsCsv", "hiddenapiFlags", "tmpDir", "soongZipFlags")
Colin Cross8faf8fc2019-01-16 15:15:52 -0800290
Colin Crossf24a22a2019-01-31 14:12:44 -0800291func hiddenAPIEncodeDex(ctx android.ModuleContext, output android.WritablePath, dexInput android.Path,
Colin Crosscd964b32019-01-18 22:03:02 -0800292 uncompressDex bool) {
293
Colin Crossf24a22a2019-01-31 14:12:44 -0800294 flagsCSV := hiddenAPISingletonPaths(ctx).flags
Colin Cross8faf8fc2019-01-16 15:15:52 -0800295
Colin Crosscd964b32019-01-18 22:03:02 -0800296 // The encode dex rule requires unzipping and rezipping the classes.dex files, ensure that if it was uncompressed
297 // in the input it stays uncompressed in the output.
298 soongZipFlags := ""
David Brazdil91b4e3e2019-01-23 21:04:05 +0000299 hiddenapiFlags := ""
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000300 tmpOutput := output
301 tmpDir := android.PathForModuleOut(ctx, "hiddenapi", "dex")
Colin Crosscd964b32019-01-18 22:03:02 -0800302 if uncompressDex {
303 soongZipFlags = "-L 0"
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000304 tmpOutput = android.PathForModuleOut(ctx, "hiddenapi", "unaligned", "unaligned.jar")
305 tmpDir = android.PathForModuleOut(ctx, "hiddenapi", "unaligned")
Colin Crosscd964b32019-01-18 22:03:02 -0800306 }
Jiyong Park93e57a02020-02-21 16:04:53 +0900307
308 enforceHiddenApiFlagsToAllMembers := true
David Brazdil91b4e3e2019-01-23 21:04:05 +0000309 // If frameworks/base doesn't exist we must be building with the 'master-art' manifest.
310 // Disable assertion that all methods/fields have hidden API flags assigned.
311 if !ctx.Config().FrameworksBaseDirExists(ctx) {
Jiyong Park93e57a02020-02-21 16:04:53 +0900312 enforceHiddenApiFlagsToAllMembers = false
313 }
314 // b/149353192: when a module is instrumented, jacoco adds synthetic members
315 // $jacocoData and $jacocoInit. Since they don't exist when building the hidden API flags,
316 // don't complain when we don't find hidden API flags for the synthetic members.
Paul Duffinc495d2b2020-05-19 21:07:52 +0100317 if j, ok := ctx.Module().(interface {
318 shouldInstrument(android.BaseModuleContext) bool
319 }); ok && j.shouldInstrument(ctx) {
Jiyong Park93e57a02020-02-21 16:04:53 +0900320 enforceHiddenApiFlagsToAllMembers = false
321 }
322
323 if !enforceHiddenApiFlagsToAllMembers {
David Brazdil91b4e3e2019-01-23 21:04:05 +0000324 hiddenapiFlags = "--no-force-assign-all"
325 }
Colin Crosscd964b32019-01-18 22:03:02 -0800326
Colin Cross8faf8fc2019-01-16 15:15:52 -0800327 ctx.Build(pctx, android.BuildParams{
328 Rule: hiddenAPIEncodeDexRule,
329 Description: "hiddenapi encode dex",
330 Input: dexInput,
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000331 Output: tmpOutput,
Colin Crossf24a22a2019-01-31 14:12:44 -0800332 Implicit: flagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800333 Args: map[string]string{
Colin Crossf24a22a2019-01-31 14:12:44 -0800334 "flagsCsv": flagsCSV.String(),
David Brazdil91b4e3e2019-01-23 21:04:05 +0000335 "tmpDir": tmpDir.String(),
336 "soongZipFlags": soongZipFlags,
337 "hiddenapiFlags": hiddenapiFlags,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800338 },
339 })
340
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000341 if uncompressDex {
342 TransformZipAlign(ctx, output, tmpOutput)
343 }
Colin Cross8faf8fc2019-01-16 15:15:52 -0800344}
Paul Duffin031d8692021-02-12 11:46:42 +0000345
346type hiddenApiAnnotationsDependencyTag struct {
347 blueprint.BaseDependencyTag
348}
349
350// Tag used to mark dependencies on java_library instances that contains Java source files whose
351// sole purpose is to provide additional hiddenapi annotations.
352var hiddenApiAnnotationsTag hiddenApiAnnotationsDependencyTag
353
354// Mark this tag so dependencies that use it are excluded from APEX contents.
355func (t hiddenApiAnnotationsDependencyTag) ExcludeFromApexContents() {}
356
357var _ android.ExcludeFromApexContentsTag = hiddenApiAnnotationsTag