blob: 37f1b995c1039314da2a531f2d1fde1bd02dc7de [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
23var hiddenAPIGenerateCSVRule = pctx.AndroidStaticRule("hiddenAPIGenerateCSV", blueprint.RuleParams{
Andrei Onea23fea042020-08-12 16:48:23 +010024 Command: "${config.Class2NonSdkList} --stub-api-flags ${stubAPIFlags} $in $outFlag $out",
25 CommandDeps: []string{"${config.Class2NonSdkList}"},
David Brazdil0f670a22019-01-18 16:30:03 +000026}, "outFlag", "stubAPIFlags")
Colin Cross8faf8fc2019-01-16 15:15:52 -080027
Colin Crossf24a22a2019-01-31 14:12:44 -080028type hiddenAPI struct {
Paul Duffinf75e5272021-02-09 14:34:25 +000029 // True if the module containing this structure contributes to the hiddenapi information or has
30 // that information encoded within it.
Paul Duffin4103e922021-02-01 19:01:34 +000031 active bool
32
Paul Duffinf75e5272021-02-09 14:34:25 +000033 // Identifies the active module variant which will be used as the source of hiddenapi information.
34 //
35 // A class may be compiled into a number of different module variants each of which will need the
36 // hiddenapi information encoded into it and so will be marked as active. However, only one of
37 // them must be used as a source of information by hiddenapi otherwise it will end up with
38 // duplicate entries. That module will have primary=true.
39 //
40 // Note, that modules <x>-hiddenapi that provide additional annotation information for module <x>
41 // that is on the bootclasspath are marked as primary=true as they are the primary source of that
42 // annotation information.
43 primary bool
44
Paul Duffinff774a02021-01-29 12:53:15 +000045 // The path to the dex jar that is in the boot class path. If this is nil then the associated
46 // module is not a boot jar, but could be one of the <x>-hiddenapi modules that provide additional
47 // annotations for the <x> boot dex jar but which do not actually provide a boot dex jar
48 // themselves.
Paul Duffin4103e922021-02-01 19:01:34 +000049 //
50 // This must be the path to the unencoded dex jar as the encoded dex jar indirectly depends on
51 // 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 +000052 bootDexJarPath android.Path
53
Paul Duffin36187b22021-04-22 16:43:06 +010054 // The paths to the classes jars that contain classes and class members annotated with
55 // the UnsupportedAppUsage annotation that need to be extracted as part of the hidden API
56 // processing.
57 classesJarPaths android.Paths
Colin Crossf24a22a2019-01-31 14:12:44 -080058}
59
Colin Crossf24a22a2019-01-31 14:12:44 -080060func (h *hiddenAPI) bootDexJar() android.Path {
61 return h.bootDexJarPath
62}
63
Paul Duffin36187b22021-04-22 16:43:06 +010064func (h *hiddenAPI) classesJars() android.Paths {
65 return h.classesJarPaths
66}
67
Paul Duffin537ea3d2021-05-14 10:38:00 +010068// hiddenAPIModule is the interface a module that embeds the hiddenAPI structure must implement.
69type hiddenAPIModule interface {
70 android.Module
71 hiddenAPIIntf
72}
73
Colin Crossf24a22a2019-01-31 14:12:44 -080074type hiddenAPIIntf interface {
Colin Crossf24a22a2019-01-31 14:12:44 -080075 bootDexJar() android.Path
Paul Duffin36187b22021-04-22 16:43:06 +010076 classesJars() android.Paths
Colin Crossf24a22a2019-01-31 14:12:44 -080077}
78
79var _ hiddenAPIIntf = (*hiddenAPI)(nil)
80
Paul Duffin4103e922021-02-01 19:01:34 +000081// Initialize the hiddenapi structure
Paul Duffin74d18d12021-05-14 14:18:47 +010082func (h *hiddenAPI) initHiddenAPI(ctx android.ModuleContext, dexJar, classesJar android.Path) {
83
84 // Save the classes jars even if this is not active as they may be used by modular hidden API
85 // processing.
86 classesJars := android.Paths{classesJar}
87 ctx.VisitDirectDepsWithTag(hiddenApiAnnotationsTag, func(dep android.Module) {
88 javaInfo := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
89 classesJars = append(classesJars, javaInfo.ImplementationJars...)
90 })
91 h.classesJarPaths = classesJars
92
93 // Save the unencoded dex jar so it can be used when generating the
94 // hiddenAPISingletonPathsStruct.stubFlags file.
95 h.bootDexJarPath = dexJar
96
Paul Duffin4103e922021-02-01 19:01:34 +000097 // If hiddenapi processing is disabled treat this as inactive.
98 if ctx.Config().IsEnvTrue("UNSAFE_DISABLE_HIDDENAPI_FLAGS") {
99 return
100 }
101
Paul Duffin74d18d12021-05-14 14:18:47 +0100102 // The context module must implement hiddenAPIModule.
103 module := ctx.Module().(hiddenAPIModule)
104
Paul Duffinb6f53c02021-05-14 07:52:42 +0100105 // If the frameworks/base directories does not exist and no prebuilt hidden API flag files have
106 // been configured then it is not possible to do hidden API encoding.
107 if !ctx.Config().FrameworksBaseDirExists(ctx) && ctx.Config().PrebuiltHiddenApiDir(ctx) == "" {
108 return
109 }
110
Paul Duffin4103e922021-02-01 19:01:34 +0000111 // It is important that hiddenapi information is only gathered for/from modules that are actually
112 // on the boot jars list because the runtime only enforces access to the hidden API for the
113 // bootclassloader. If information is gathered for modules not on the list then that will cause
114 // failures in the CtsHiddenApiBlocklist... tests.
Paul Duffin82b3fcf2021-02-12 15:42:46 +0000115 h.active = isModuleInBootClassPath(ctx, module)
Paul Duffinf75e5272021-02-09 14:34:25 +0000116 if !h.active {
117 // The rest of the properties will be ignored if active is false.
118 return
119 }
Paul Duffin4103e922021-02-01 19:01:34 +0000120
Paul Duffinf75e5272021-02-09 14:34:25 +0000121 // Determine whether this module is the primary module or not.
122 primary := true
123
124 // A prebuilt module is only primary if it is preferred and conversely a source module is only
125 // primary if it has not been replaced by a prebuilt module.
Paul Duffinf75e5272021-02-09 14:34:25 +0000126 if pi, ok := module.(android.PrebuiltInterface); ok {
127 if p := pi.Prebuilt(); p != nil {
128 primary = p.UsePrebuilt()
129 }
130 } else {
Paul Duffinf75e5272021-02-09 14:34:25 +0000131 // A source module that has been replaced by a prebuilt can never be the primary module.
Paul Duffinec0fe172021-02-25 15:34:13 +0000132 if module.IsReplacedByPrebuilt() {
Paul Duffin894546d2021-04-21 01:03:30 +0100133 if ctx.HasProvider(android.ApexInfoProvider) {
134 // The source module is in an APEX but the prebuilt module on which it depends is not in an
135 // APEX and so is not the one that will actually be used for hidden API processing. That
136 // means it is not possible to check to see if it is a suitable replacement so just assume
137 // that it is.
138 primary = false
139 } else {
140 ctx.VisitDirectDepsWithTag(android.PrebuiltDepTag, func(prebuilt android.Module) {
141 if h, ok := prebuilt.(hiddenAPIIntf); ok && h.bootDexJar() != nil {
142 primary = false
143 } else {
144 ctx.ModuleErrorf(
145 "hiddenapi has determined that the source module %q should be ignored as it has been"+
146 " replaced by the prebuilt module %q but unfortunately it does not provide a"+
147 " suitable boot dex jar", ctx.ModuleName(), ctx.OtherModuleName(prebuilt))
148 }
149 })
150 }
Paul Duffinec0fe172021-02-25 15:34:13 +0000151 }
Paul Duffinf75e5272021-02-09 14:34:25 +0000152 }
153 h.primary = primary
Paul Duffin4103e922021-02-01 19:01:34 +0000154}
155
Paul Duffin82b3fcf2021-02-12 15:42:46 +0000156func isModuleInBootClassPath(ctx android.BaseModuleContext, module android.Module) bool {
157 // Get the configured non-updatable and updatable boot jars.
158 nonUpdatableBootJars := ctx.Config().NonUpdatableBootJars()
159 updatableBootJars := ctx.Config().UpdatableBootJars()
160 active := isModuleInConfiguredList(ctx, module, nonUpdatableBootJars) ||
161 isModuleInConfiguredList(ctx, module, updatableBootJars)
162 return active
163}
164
Paul Duffinafaa47c2021-05-14 13:04:04 +0100165// hiddenAPIEncodeDex is called by any module that needs to encode dex files.
Paul Duffin4103e922021-02-01 19:01:34 +0000166//
167// 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 +0100168// jar list. In that case it simply returns the supplied dex jar path.
Paul Duffin4103e922021-02-01 19:01:34 +0000169//
Paul Duffinafaa47c2021-05-14 13:04:04 +0100170// Otherwise, it creates a copy of the supplied dex file into which it has encoded the hiddenapi
171// flags and returns this instead of the supplied dex jar.
172func (h *hiddenAPI) hiddenAPIEncodeDex(ctx android.ModuleContext, dexJar android.OutputPath, uncompressDex bool) android.OutputPath {
Paul Duffin001e6062021-05-14 01:13:55 +0100173
Paul Duffin4103e922021-02-01 19:01:34 +0000174 if !h.active {
175 return dexJar
176 }
Paul Duffind2aceca2019-02-28 16:13:20 +0000177
Paul Duffin66cdbf02021-05-14 16:35:06 +0100178 hiddenAPIJar := android.PathForModuleOut(ctx, "hiddenapi", dexJar.Base()).OutputPath
Paul Duffina2058f82020-06-24 16:22:38 +0100179
Paul Duffinf8f4af82021-02-12 15:42:20 +0000180 // Create a copy of the dex jar which has been encoded with hiddenapi flags.
181 hiddenAPIEncodeDex(ctx, hiddenAPIJar, dexJar, uncompressDex)
Paul Duffin4103e922021-02-01 19:01:34 +0000182
Paul Duffinf8f4af82021-02-12 15:42:20 +0000183 // Use the encoded dex jar from here onwards.
184 dexJar = hiddenAPIJar
Colin Crossf24a22a2019-01-31 14:12:44 -0800185
186 return dexJar
187}
188
Paul Duffin850e61f2021-05-14 09:58:48 +0100189// buildRuleToGenerateAnnotationFlags builds a ninja rule to generate the annotation-flags.csv file
190// from the classes jars and stub-flags.csv files.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100191//
192// The annotation-flags.csv file contains mappings from Java signature to various flags derived from
193// annotations in the source, e.g. whether it is public or the sdk version above which it can no
194// longer be used.
195//
196// It is created by the Class2NonSdkList tool which processes the .class files in the class
197// implementation jar looking for UnsupportedAppUsage and CovariantReturnType annotations. The
198// tool also consumes the hiddenAPISingletonPathsStruct.stubFlags file in order to perform
199// consistency checks on the information in the annotations and to filter out bridge methods
200// that are already part of the public API.
Paul Duffin850e61f2021-05-14 09:58:48 +0100201func buildRuleToGenerateAnnotationFlags(ctx android.ModuleContext, desc string, classesJars android.Paths, stubFlagsCSV android.Path, outputPath android.WritablePath) {
Colin Cross8faf8fc2019-01-16 15:15:52 -0800202 ctx.Build(pctx, android.BuildParams{
203 Rule: hiddenAPIGenerateCSVRule,
Paul Duffin850e61f2021-05-14 09:58:48 +0100204 Description: desc,
Paul Duffin031d8692021-02-12 11:46:42 +0000205 Inputs: classesJars,
Paul Duffin850e61f2021-05-14 09:58:48 +0100206 Output: outputPath,
David Brazdil0f670a22019-01-18 16:30:03 +0000207 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800208 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000209 "outFlag": "--write-flags-csv",
210 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800211 },
212 })
Paul Duffin850e61f2021-05-14 09:58:48 +0100213}
Colin Cross8faf8fc2019-01-16 15:15:52 -0800214
Paul Duffin850e61f2021-05-14 09:58:48 +0100215// buildRuleToGenerateMetadata builds a ninja rule to generate the metadata.csv file from
216// the classes jars and stub-flags.csv files.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100217//
218// The metadata.csv file contains mappings from Java signature to the value of properties specified
219// on UnsupportedAppUsage annotations in the source.
220//
221// Like the annotation-flags.csv file this is also created by the Class2NonSdkList in the same way.
222// Although the two files could potentially be created in a single invocation of the
223// Class2NonSdkList at the moment they are created using their own invocation, with the behavior
224// being determined by the property that is used.
Paul Duffin850e61f2021-05-14 09:58:48 +0100225func buildRuleToGenerateMetadata(ctx android.ModuleContext, desc string, classesJars android.Paths, stubFlagsCSV android.Path, metadataCSV android.WritablePath) {
Colin Cross8faf8fc2019-01-16 15:15:52 -0800226 ctx.Build(pctx, android.BuildParams{
227 Rule: hiddenAPIGenerateCSVRule,
Paul Duffin850e61f2021-05-14 09:58:48 +0100228 Description: desc,
Paul Duffin031d8692021-02-12 11:46:42 +0000229 Inputs: classesJars,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800230 Output: metadataCSV,
David Brazdil0f670a22019-01-18 16:30:03 +0000231 Implicit: stubFlagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800232 Args: map[string]string{
David Brazdil0f670a22019-01-18 16:30:03 +0000233 "outFlag": "--write-metadata-csv",
234 "stubAPIFlags": stubFlagsCSV.String(),
Colin Cross8faf8fc2019-01-16 15:15:52 -0800235 },
236 })
Paul Duffin850e61f2021-05-14 09:58:48 +0100237}
Colin Cross8faf8fc2019-01-16 15:15:52 -0800238
Paul Duffinafaa47c2021-05-14 13:04:04 +0100239// buildRuleToGenerateIndex builds a ninja rule to generate the index.csv file from the classes
Paul Duffin850e61f2021-05-14 09:58:48 +0100240// jars.
Paul Duffinafaa47c2021-05-14 13:04:04 +0100241//
242// The index.csv file contains mappings from Java signature to source location information.
243//
244// It is created by the merge_csv tool which processes the class implementation jar, extracting
245// all the files ending in .uau (which are CSV files) and merges them together. The .uau files are
246// created by the unsupported app usage annotation processor during compilation of the class
247// implementation jar.
Paul Duffin850e61f2021-05-14 09:58:48 +0100248func buildRuleToGenerateIndex(ctx android.ModuleContext, desc string, classesJars android.Paths, indexCSV android.WritablePath) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800249 rule := android.NewRuleBuilder(pctx, ctx)
Artur Satayevb5df8a02020-02-19 16:39:59 +0000250 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -0800251 BuiltTool("merge_csv").
Paul Duffin031d8692021-02-12 11:46:42 +0000252 Flag("--zip_input").
Paul Duffin2c36f242021-02-16 16:57:06 +0000253 Flag("--key_field signature").
Paul Duffin537ea3d2021-05-14 10:38:00 +0100254 FlagWithArg("--header=", "signature,file,startline,startcol,endline,endcol,properties").
Paul Duffin031d8692021-02-12 11:46:42 +0000255 FlagWithOutput("--output=", indexCSV).
256 Inputs(classesJars)
Paul Duffin850e61f2021-05-14 09:58:48 +0100257 rule.Build(desc, desc)
Colin Cross8faf8fc2019-01-16 15:15:52 -0800258}
259
260var hiddenAPIEncodeDexRule = pctx.AndroidStaticRule("hiddenAPIEncodeDex", blueprint.RuleParams{
Artur Satayevb5df8a02020-02-19 16:39:59 +0000261 Command: `rm -rf $tmpDir && mkdir -p $tmpDir && mkdir $tmpDir/dex-input && mkdir $tmpDir/dex-output &&
Colin Crossd783bbb2020-07-11 22:30:45 -0700262 unzip -qoDD $in 'classes*.dex' -d $tmpDir/dex-input &&
Artur Satayevb5df8a02020-02-19 16:39:59 +0000263 for INPUT_DEX in $$(find $tmpDir/dex-input -maxdepth 1 -name 'classes*.dex' | sort); do
264 echo "--input-dex=$${INPUT_DEX}";
265 echo "--output-dex=$tmpDir/dex-output/$$(basename $${INPUT_DEX})";
266 done | xargs ${config.HiddenAPI} encode --api-flags=$flagsCsv $hiddenapiFlags &&
267 ${config.SoongZipCmd} $soongZipFlags -o $tmpDir/dex.jar -C $tmpDir/dex-output -f "$tmpDir/dex-output/classes*.dex" &&
268 ${config.MergeZipsCmd} -D -zipToNotStrip $tmpDir/dex.jar -stripFile "classes*.dex" -stripFile "**/*.uau" $out $tmpDir/dex.jar $in`,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800269 CommandDeps: []string{
270 "${config.HiddenAPI}",
271 "${config.SoongZipCmd}",
272 "${config.MergeZipsCmd}",
273 },
David Brazdil91b4e3e2019-01-23 21:04:05 +0000274}, "flagsCsv", "hiddenapiFlags", "tmpDir", "soongZipFlags")
Colin Cross8faf8fc2019-01-16 15:15:52 -0800275
Colin Crossf24a22a2019-01-31 14:12:44 -0800276func hiddenAPIEncodeDex(ctx android.ModuleContext, output android.WritablePath, dexInput android.Path,
Colin Crosscd964b32019-01-18 22:03:02 -0800277 uncompressDex bool) {
278
Colin Crossf24a22a2019-01-31 14:12:44 -0800279 flagsCSV := hiddenAPISingletonPaths(ctx).flags
Colin Cross8faf8fc2019-01-16 15:15:52 -0800280
Colin Crosscd964b32019-01-18 22:03:02 -0800281 // The encode dex rule requires unzipping and rezipping the classes.dex files, ensure that if it was uncompressed
282 // in the input it stays uncompressed in the output.
283 soongZipFlags := ""
David Brazdil91b4e3e2019-01-23 21:04:05 +0000284 hiddenapiFlags := ""
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000285 tmpOutput := output
286 tmpDir := android.PathForModuleOut(ctx, "hiddenapi", "dex")
Colin Crosscd964b32019-01-18 22:03:02 -0800287 if uncompressDex {
288 soongZipFlags = "-L 0"
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000289 tmpOutput = android.PathForModuleOut(ctx, "hiddenapi", "unaligned", "unaligned.jar")
290 tmpDir = android.PathForModuleOut(ctx, "hiddenapi", "unaligned")
Colin Crosscd964b32019-01-18 22:03:02 -0800291 }
Jiyong Park93e57a02020-02-21 16:04:53 +0900292
293 enforceHiddenApiFlagsToAllMembers := true
Paul Duffinb6f53c02021-05-14 07:52:42 +0100294
Jiyong Park93e57a02020-02-21 16:04:53 +0900295 // b/149353192: when a module is instrumented, jacoco adds synthetic members
296 // $jacocoData and $jacocoInit. Since they don't exist when building the hidden API flags,
297 // don't complain when we don't find hidden API flags for the synthetic members.
Paul Duffinc495d2b2020-05-19 21:07:52 +0100298 if j, ok := ctx.Module().(interface {
299 shouldInstrument(android.BaseModuleContext) bool
300 }); ok && j.shouldInstrument(ctx) {
Jiyong Park93e57a02020-02-21 16:04:53 +0900301 enforceHiddenApiFlagsToAllMembers = false
302 }
303
304 if !enforceHiddenApiFlagsToAllMembers {
David Brazdil91b4e3e2019-01-23 21:04:05 +0000305 hiddenapiFlags = "--no-force-assign-all"
306 }
Colin Crosscd964b32019-01-18 22:03:02 -0800307
Colin Cross8faf8fc2019-01-16 15:15:52 -0800308 ctx.Build(pctx, android.BuildParams{
309 Rule: hiddenAPIEncodeDexRule,
310 Description: "hiddenapi encode dex",
311 Input: dexInput,
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000312 Output: tmpOutput,
Colin Crossf24a22a2019-01-31 14:12:44 -0800313 Implicit: flagsCSV,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800314 Args: map[string]string{
Colin Crossf24a22a2019-01-31 14:12:44 -0800315 "flagsCsv": flagsCSV.String(),
David Brazdil91b4e3e2019-01-23 21:04:05 +0000316 "tmpDir": tmpDir.String(),
317 "soongZipFlags": soongZipFlags,
318 "hiddenapiFlags": hiddenapiFlags,
Colin Cross8faf8fc2019-01-16 15:15:52 -0800319 },
320 })
321
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000322 if uncompressDex {
323 TransformZipAlign(ctx, output, tmpOutput)
324 }
Colin Cross8faf8fc2019-01-16 15:15:52 -0800325}
Paul Duffin031d8692021-02-12 11:46:42 +0000326
327type hiddenApiAnnotationsDependencyTag struct {
328 blueprint.BaseDependencyTag
329}
330
331// Tag used to mark dependencies on java_library instances that contains Java source files whose
332// sole purpose is to provide additional hiddenapi annotations.
333var hiddenApiAnnotationsTag hiddenApiAnnotationsDependencyTag
334
335// Mark this tag so dependencies that use it are excluded from APEX contents.
336func (t hiddenApiAnnotationsDependencyTag) ExcludeFromApexContents() {}
337
338var _ android.ExcludeFromApexContentsTag = hiddenApiAnnotationsTag