blob: d705a4d6b5386722d3969c9ca9543c1f10791f44 [file] [log] [blame]
Colin Cross2207f872021-03-24 12:39:08 -07001// Copyright 2021 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 (
18 "fmt"
Anton Hansson86758ac2021-11-03 14:44:12 +000019 "path/filepath"
Colin Cross2207f872021-03-24 12:39:08 -070020 "strings"
21
22 "github.com/google/blueprint/proptools"
23
24 "android/soong/android"
25 "android/soong/java/config"
26 "android/soong/remoteexec"
27)
28
Pedro Loureirocc203502021-10-04 17:24:00 +000029// The values allowed for Droidstubs' Api_levels_sdk_type
30var allowedApiLevelSdkTypes = []string{"public", "system", "module-lib"}
31
Colin Cross2207f872021-03-24 12:39:08 -070032func init() {
33 RegisterStubsBuildComponents(android.InitRegistrationContext)
34}
35
36func RegisterStubsBuildComponents(ctx android.RegistrationContext) {
37 ctx.RegisterModuleType("stubs_defaults", StubsDefaultsFactory)
38
39 ctx.RegisterModuleType("droidstubs", DroidstubsFactory)
40 ctx.RegisterModuleType("droidstubs_host", DroidstubsHostFactory)
41
42 ctx.RegisterModuleType("prebuilt_stubs_sources", PrebuiltStubsSourcesFactory)
43}
44
45//
46// Droidstubs
47//
48type Droidstubs struct {
49 Javadoc
50 android.SdkBase
51
52 properties DroidstubsProperties
Paul Duffin6cdfd3f2022-08-16 15:24:01 +000053 apiFile android.Path
54 removedApiFile android.Path
Colin Cross2207f872021-03-24 12:39:08 -070055 nullabilityWarningsFile android.WritablePath
56
57 checkCurrentApiTimestamp android.WritablePath
58 updateCurrentApiTimestamp android.WritablePath
59 checkLastReleasedApiTimestamp android.WritablePath
60 apiLintTimestamp android.WritablePath
61 apiLintReport android.WritablePath
62
63 checkNullabilityWarningsTimestamp android.WritablePath
64
65 annotationsZip android.WritablePath
66 apiVersionsXml android.WritablePath
67
Colin Cross2207f872021-03-24 12:39:08 -070068 metadataZip android.WritablePath
69 metadataDir android.WritablePath
70}
71
72type DroidstubsProperties struct {
73 // The generated public API filename by Metalava, defaults to <module>_api.txt
74 Api_filename *string
75
76 // the generated removed API filename by Metalava, defaults to <module>_removed.txt
77 Removed_api_filename *string
78
Colin Cross2207f872021-03-24 12:39:08 -070079 Check_api struct {
80 Last_released ApiToCheck
81
82 Current ApiToCheck
83
84 Api_lint struct {
85 Enabled *bool
86
87 // If set, performs api_lint on any new APIs not found in the given signature file
88 New_since *string `android:"path"`
89
90 // If not blank, path to the baseline txt file for approved API lint violations.
91 Baseline_file *string `android:"path"`
92 }
93 }
94
95 // user can specify the version of previous released API file in order to do compatibility check.
96 Previous_api *string `android:"path"`
97
98 // is set to true, Metalava will allow framework SDK to contain annotations.
99 Annotations_enabled *bool
100
101 // a list of top-level directories containing files to merge qualifier annotations (i.e. those intended to be included in the stubs written) from.
102 Merge_annotations_dirs []string
103
104 // a list of top-level directories containing Java stub files to merge show/hide annotations from.
105 Merge_inclusion_annotations_dirs []string
106
107 // a file containing a list of classes to do nullability validation for.
108 Validate_nullability_from_list *string
109
110 // a file containing expected warnings produced by validation of nullability annotations.
111 Check_nullability_warnings *string
112
113 // if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
114 Create_doc_stubs *bool
115
116 // if set to true, cause Metalava to output Javadoc comments in the stubs source files. Defaults to false.
117 // Has no effect if create_doc_stubs: true.
118 Output_javadoc_comments *bool
119
120 // if set to false then do not write out stubs. Defaults to true.
121 //
122 // TODO(b/146727827): Remove capability when we do not need to generate stubs and API separately.
123 Generate_stubs *bool
124
125 // if set to true, provides a hint to the build system that this rule uses a lot of memory,
126 // whicih can be used for scheduling purposes
127 High_mem *bool
128
satayev783195c2021-06-23 21:49:57 +0100129 // if set to true, Metalava will allow framework SDK to contain API levels annotations.
Colin Cross2207f872021-03-24 12:39:08 -0700130 Api_levels_annotations_enabled *bool
131
132 // the dirs which Metalava extracts API levels annotations from.
133 Api_levels_annotations_dirs []string
134
Pedro Loureirocc203502021-10-04 17:24:00 +0000135 // the sdk kind which Metalava extracts API levels annotations from. Supports 'public', 'system' and 'module-lib' for now; defaults to public.
satayev783195c2021-06-23 21:49:57 +0100136 Api_levels_sdk_type *string
137
Colin Cross2207f872021-03-24 12:39:08 -0700138 // the filename which Metalava extracts API levels annotations from. Defaults to android.jar.
139 Api_levels_jar_filename *string
140
141 // if set to true, collect the values used by the Dev tools and
142 // write them in files packaged with the SDK. Defaults to false.
143 Write_sdk_values *bool
144}
145
Anton Hansson52609322021-05-05 10:36:05 +0100146// Used by xsd_config
147type ApiFilePath interface {
148 ApiFilePath() android.Path
149}
150
151type ApiStubsSrcProvider interface {
152 StubsSrcJar() android.Path
153}
154
155// Provider of information about API stubs, used by java_sdk_library.
156type ApiStubsProvider interface {
Anton Hanssond78eb762021-09-21 15:25:12 +0100157 AnnotationsZip() android.Path
Anton Hansson52609322021-05-05 10:36:05 +0100158 ApiFilePath
159 RemovedApiFilePath() android.Path
160
161 ApiStubsSrcProvider
162}
163
Colin Cross2207f872021-03-24 12:39:08 -0700164// droidstubs passes sources files through Metalava to generate stub .java files that only contain the API to be
165// documented, filtering out hidden classes and methods. The resulting .java files are intended to be passed to
166// a droiddoc module to generate documentation.
167func DroidstubsFactory() android.Module {
168 module := &Droidstubs{}
169
170 module.AddProperties(&module.properties,
171 &module.Javadoc.properties)
172
173 InitDroiddocModule(module, android.HostAndDeviceSupported)
174 android.InitSdkAwareModule(module)
175 return module
176}
177
178// droidstubs_host passes sources files through Metalava to generate stub .java files that only contain the API
179// to be documented, filtering out hidden classes and methods. The resulting .java files are intended to be
180// passed to a droiddoc_host module to generate documentation. Use a droidstubs_host instead of a droidstubs
181// module when symbols needed by the source files are provided by java_library_host modules.
182func DroidstubsHostFactory() android.Module {
183 module := &Droidstubs{}
184
185 module.AddProperties(&module.properties,
186 &module.Javadoc.properties)
187
188 InitDroiddocModule(module, android.HostSupported)
189 return module
190}
191
192func (d *Droidstubs) OutputFiles(tag string) (android.Paths, error) {
193 switch tag {
194 case "":
195 return android.Paths{d.stubsSrcJar}, nil
196 case ".docs.zip":
197 return android.Paths{d.docZip}, nil
198 case ".api.txt", android.DefaultDistTag:
199 // This is the default dist path for dist properties that have no tag property.
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000200 return android.Paths{d.apiFile}, nil
Colin Cross2207f872021-03-24 12:39:08 -0700201 case ".removed-api.txt":
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000202 return android.Paths{d.removedApiFile}, nil
Colin Cross2207f872021-03-24 12:39:08 -0700203 case ".annotations.zip":
204 return android.Paths{d.annotationsZip}, nil
205 case ".api_versions.xml":
206 return android.Paths{d.apiVersionsXml}, nil
207 default:
208 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
209 }
210}
211
Anton Hanssond78eb762021-09-21 15:25:12 +0100212func (d *Droidstubs) AnnotationsZip() android.Path {
213 return d.annotationsZip
214}
215
Colin Cross2207f872021-03-24 12:39:08 -0700216func (d *Droidstubs) ApiFilePath() android.Path {
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000217 return d.apiFile
Colin Cross2207f872021-03-24 12:39:08 -0700218}
219
220func (d *Droidstubs) RemovedApiFilePath() android.Path {
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000221 return d.removedApiFile
Colin Cross2207f872021-03-24 12:39:08 -0700222}
223
224func (d *Droidstubs) StubsSrcJar() android.Path {
225 return d.stubsSrcJar
226}
227
228var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
229var metalavaMergeInclusionAnnotationsDirTag = dependencyTag{name: "metalava-merge-inclusion-annotations-dir"}
230var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
231
232func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
233 d.Javadoc.addDeps(ctx)
234
235 if len(d.properties.Merge_annotations_dirs) != 0 {
236 for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
237 ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
238 }
239 }
240
241 if len(d.properties.Merge_inclusion_annotations_dirs) != 0 {
242 for _, mergeInclusionAnnotationsDir := range d.properties.Merge_inclusion_annotations_dirs {
243 ctx.AddDependency(ctx.Module(), metalavaMergeInclusionAnnotationsDirTag, mergeInclusionAnnotationsDir)
244 }
245 }
246
247 if len(d.properties.Api_levels_annotations_dirs) != 0 {
248 for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
249 ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
250 }
251 }
252}
253
254func (d *Droidstubs) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
255 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
256 apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
257 String(d.properties.Api_filename) != "" {
258 filename := proptools.StringDefault(d.properties.Api_filename, ctx.ModuleName()+"_api.txt")
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000259 uncheckedApiFile := android.PathForModuleOut(ctx, "metalava", filename)
260 cmd.FlagWithOutput("--api ", uncheckedApiFile)
261 d.apiFile = uncheckedApiFile
Colin Cross2207f872021-03-24 12:39:08 -0700262 } else if sourceApiFile := proptools.String(d.properties.Check_api.Current.Api_file); sourceApiFile != "" {
263 // If check api is disabled then make the source file available for export.
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000264 d.apiFile = android.PathForModuleSrc(ctx, sourceApiFile)
Colin Cross2207f872021-03-24 12:39:08 -0700265 }
266
267 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
268 apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
269 String(d.properties.Removed_api_filename) != "" {
270 filename := proptools.StringDefault(d.properties.Removed_api_filename, ctx.ModuleName()+"_removed.txt")
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000271 uncheckedRemovedFile := android.PathForModuleOut(ctx, "metalava", filename)
272 cmd.FlagWithOutput("--removed-api ", uncheckedRemovedFile)
273 d.removedApiFile = uncheckedRemovedFile
Colin Cross2207f872021-03-24 12:39:08 -0700274 } else if sourceRemovedApiFile := proptools.String(d.properties.Check_api.Current.Removed_api_file); sourceRemovedApiFile != "" {
275 // If check api is disabled then make the source removed api file available for export.
Paul Duffin6cdfd3f2022-08-16 15:24:01 +0000276 d.removedApiFile = android.PathForModuleSrc(ctx, sourceRemovedApiFile)
Colin Cross2207f872021-03-24 12:39:08 -0700277 }
278
Colin Cross2207f872021-03-24 12:39:08 -0700279 if Bool(d.properties.Write_sdk_values) {
Colin Crosscb77f752021-03-24 12:04:44 -0700280 d.metadataDir = android.PathForModuleOut(ctx, "metalava", "metadata")
Colin Cross2207f872021-03-24 12:39:08 -0700281 cmd.FlagWithArg("--sdk-values ", d.metadataDir.String())
282 }
283
284 if stubsDir.Valid() {
285 if Bool(d.properties.Create_doc_stubs) {
286 cmd.FlagWithArg("--doc-stubs ", stubsDir.String())
287 } else {
288 cmd.FlagWithArg("--stubs ", stubsDir.String())
289 if !Bool(d.properties.Output_javadoc_comments) {
290 cmd.Flag("--exclude-documentation-from-stubs")
291 }
292 }
293 }
294}
295
296func (d *Droidstubs) annotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
297 if Bool(d.properties.Annotations_enabled) {
298 cmd.Flag("--include-annotations")
299
Andrei Onea4985e512021-04-29 16:29:34 +0100300 cmd.FlagWithArg("--exclude-annotation ", "androidx.annotation.RequiresApi")
301
Colin Cross2207f872021-03-24 12:39:08 -0700302 validatingNullability :=
Colin Crossbc139922021-03-25 18:33:16 -0700303 strings.Contains(String(d.Javadoc.properties.Args), "--validate-nullability-from-merged-stubs") ||
Colin Cross2207f872021-03-24 12:39:08 -0700304 String(d.properties.Validate_nullability_from_list) != ""
305
306 migratingNullability := String(d.properties.Previous_api) != ""
307 if migratingNullability {
308 previousApi := android.PathForModuleSrc(ctx, String(d.properties.Previous_api))
309 cmd.FlagWithInput("--migrate-nullness ", previousApi)
310 }
311
312 if s := String(d.properties.Validate_nullability_from_list); s != "" {
313 cmd.FlagWithInput("--validate-nullability-from-list ", android.PathForModuleSrc(ctx, s))
314 }
315
316 if validatingNullability {
Colin Crosscb77f752021-03-24 12:04:44 -0700317 d.nullabilityWarningsFile = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_nullability_warnings.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700318 cmd.FlagWithOutput("--nullability-warnings-txt ", d.nullabilityWarningsFile)
319 }
320
Colin Crosscb77f752021-03-24 12:04:44 -0700321 d.annotationsZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_annotations.zip")
Colin Cross2207f872021-03-24 12:39:08 -0700322 cmd.FlagWithOutput("--extract-annotations ", d.annotationsZip)
323
324 if len(d.properties.Merge_annotations_dirs) != 0 {
325 d.mergeAnnoDirFlags(ctx, cmd)
326 }
327
328 // TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
329 cmd.FlagWithArg("--hide ", "HiddenTypedefConstant").
330 FlagWithArg("--hide ", "SuperfluousPrefix").
Sam Gilbert049af112022-03-04 16:03:53 -0500331 FlagWithArg("--hide ", "AnnotationExtraction").
332 // b/222738070
Sam Gilbert675f0b42022-03-08 11:24:44 -0500333 FlagWithArg("--hide ", "BannedThrow").
334 // b/223382732
335 FlagWithArg("--hide ", "ChangedDefault")
Colin Cross2207f872021-03-24 12:39:08 -0700336 }
337}
338
339func (d *Droidstubs) mergeAnnoDirFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
340 ctx.VisitDirectDepsWithTag(metalavaMergeAnnotationsDirTag, func(m android.Module) {
341 if t, ok := m.(*ExportedDroiddocDir); ok {
342 cmd.FlagWithArg("--merge-qualifier-annotations ", t.dir.String()).Implicits(t.deps)
343 } else {
344 ctx.PropertyErrorf("merge_annotations_dirs",
345 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
346 }
347 })
348}
349
350func (d *Droidstubs) inclusionAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
351 ctx.VisitDirectDepsWithTag(metalavaMergeInclusionAnnotationsDirTag, func(m android.Module) {
352 if t, ok := m.(*ExportedDroiddocDir); ok {
353 cmd.FlagWithArg("--merge-inclusion-annotations ", t.dir.String()).Implicits(t.deps)
354 } else {
355 ctx.PropertyErrorf("merge_inclusion_annotations_dirs",
356 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
357 }
358 })
359}
360
361func (d *Droidstubs) apiLevelsAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
362 if !Bool(d.properties.Api_levels_annotations_enabled) {
363 return
364 }
365
Colin Crosscb77f752021-03-24 12:04:44 -0700366 d.apiVersionsXml = android.PathForModuleOut(ctx, "metalava", "api-versions.xml")
Colin Cross2207f872021-03-24 12:39:08 -0700367
368 if len(d.properties.Api_levels_annotations_dirs) == 0 {
369 ctx.PropertyErrorf("api_levels_annotations_dirs",
370 "has to be non-empty if api levels annotations was enabled!")
371 }
372
373 cmd.FlagWithOutput("--generate-api-levels ", d.apiVersionsXml)
374 cmd.FlagWithInput("--apply-api-levels ", d.apiVersionsXml)
375 cmd.FlagWithArg("--current-version ", ctx.Config().PlatformSdkVersion().String())
Yurii Zubrytskyi3cdd3512022-05-03 08:48:39 +0000376 cmd.FlagWithArg("--current-codename ", ctx.Config().PlatformSdkCodename())
Colin Cross2207f872021-03-24 12:39:08 -0700377
378 filename := proptools.StringDefault(d.properties.Api_levels_jar_filename, "android.jar")
379
satayev783195c2021-06-23 21:49:57 +0100380 var dirs []string
Colin Cross2207f872021-03-24 12:39:08 -0700381 ctx.VisitDirectDepsWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.Module) {
382 if t, ok := m.(*ExportedDroiddocDir); ok {
383 for _, dep := range t.deps {
Colin Cross5f6ffc72021-03-29 21:54:45 -0700384 if dep.Base() == filename {
385 cmd.Implicit(dep)
386 }
387 if filename != "android.jar" && dep.Base() == "android.jar" {
388 // Metalava implicitly searches these patterns:
389 // prebuilts/tools/common/api-versions/android-%/android.jar
390 // prebuilts/sdk/%/public/android.jar
391 // Add android.jar files from the api_levels_annotations_dirs directories to try
392 // to satisfy these patterns. If Metalava can't find a match for an API level
393 // between 1 and 28 in at least one pattern it will fail.
Colin Cross2207f872021-03-24 12:39:08 -0700394 cmd.Implicit(dep)
395 }
396 }
satayev783195c2021-06-23 21:49:57 +0100397
398 dirs = append(dirs, t.dir.String())
Colin Cross2207f872021-03-24 12:39:08 -0700399 } else {
400 ctx.PropertyErrorf("api_levels_annotations_dirs",
401 "module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
402 }
403 })
satayev783195c2021-06-23 21:49:57 +0100404
405 // Add all relevant --android-jar-pattern patterns for Metalava.
406 // When parsing a stub jar for a specific version, Metalava picks the first pattern that defines
407 // an actual file present on disk (in the order the patterns were passed). For system APIs for
408 // privileged apps that are only defined since API level 21 (Lollipop), fallback to public stubs
Pedro Loureirocc203502021-10-04 17:24:00 +0000409 // for older releases. Similarly, module-lib falls back to system API.
410 var sdkDirs []string
411 switch proptools.StringDefault(d.properties.Api_levels_sdk_type, "public") {
412 case "module-lib":
413 sdkDirs = []string{"module-lib", "system", "public"}
414 case "system":
415 sdkDirs = []string{"system", "public"}
416 case "public":
417 sdkDirs = []string{"public"}
418 default:
419 ctx.PropertyErrorf("api_levels_sdk_type", "needs to be one of %v", allowedApiLevelSdkTypes)
420 return
satayev783195c2021-06-23 21:49:57 +0100421 }
Pedro Loureirocc203502021-10-04 17:24:00 +0000422
423 for _, sdkDir := range sdkDirs {
424 for _, dir := range dirs {
425 cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/%%/%s/%s", dir, sdkDir, filename))
426 }
satayev783195c2021-06-23 21:49:57 +0100427 }
Colin Cross2207f872021-03-24 12:39:08 -0700428}
429
Colin Crosse52c2ac2022-03-28 17:03:35 -0700430func metalavaUseRbe(ctx android.ModuleContext) bool {
431 return ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_METALAVA")
432}
433
Colin Cross2207f872021-03-24 12:39:08 -0700434func metalavaCmd(ctx android.ModuleContext, rule *android.RuleBuilder, javaVersion javaVersion, srcs android.Paths,
Anton Hansson556e8142021-06-04 16:20:25 +0100435 srcJarList android.Path, bootclasspath, classpath classpath, homeDir android.WritablePath) *android.RuleBuilderCommand {
Colin Cross2207f872021-03-24 12:39:08 -0700436 rule.Command().Text("rm -rf").Flag(homeDir.String())
437 rule.Command().Text("mkdir -p").Flag(homeDir.String())
438
Anton Hansson556e8142021-06-04 16:20:25 +0100439 cmd := rule.Command()
Colin Cross2207f872021-03-24 12:39:08 -0700440 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
441
Colin Crosse52c2ac2022-03-28 17:03:35 -0700442 if metalavaUseRbe(ctx) {
Colin Cross2207f872021-03-24 12:39:08 -0700443 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
Colin Cross8095c292021-03-30 16:40:48 -0700444 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
445 labels := map[string]string{"type": "tool", "name": "metalava"}
446 // TODO: metalava pool rejects these jobs
447 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
448 rule.Rewrapper(&remoteexec.REParams{
449 Labels: labels,
450 ExecStrategy: execStrategy,
451 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
452 Platform: map[string]string{remoteexec.PoolKey: pool},
453 })
Colin Cross2207f872021-03-24 12:39:08 -0700454 }
455
Colin Cross6aa5c402021-03-24 12:28:50 -0700456 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
Colin Cross2207f872021-03-24 12:39:08 -0700457 Flag(config.JavacVmFlags).
458 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
459 FlagWithArg("-encoding ", "UTF-8").
460 FlagWithArg("-source ", javaVersion.String()).
461 FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, "metalava.rsp"), srcs).
462 FlagWithInput("@", srcJarList)
463
Colin Cross2207f872021-03-24 12:39:08 -0700464 if len(bootclasspath) > 0 {
465 cmd.FlagWithInputList("-bootclasspath ", bootclasspath.Paths(), ":")
466 }
467
468 if len(classpath) > 0 {
469 cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
470 }
471
Colin Cross2207f872021-03-24 12:39:08 -0700472 cmd.Flag("--no-banner").
473 Flag("--color").
474 Flag("--quiet").
475 Flag("--format=v2").
476 FlagWithArg("--repeat-errors-max ", "10").
Sam Gilbert09cb5db2021-10-06 11:28:28 -0400477 FlagWithArg("--hide ", "UnresolvedImport").
Ember Rose7c57af32022-04-01 10:34:44 -0400478 FlagWithArg("--hide ", "InvalidNullabilityOverride").
Sam Gilbert28e41282022-03-09 15:24:48 +0000479 // b/223382732
480 FlagWithArg("--hide ", "ChangedDefault")
Colin Cross2207f872021-03-24 12:39:08 -0700481
482 return cmd
483}
484
485func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
486 deps := d.Javadoc.collectDeps(ctx)
487
Jiyong Parkf1691d22021-03-29 20:11:58 +0900488 javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), android.SdkContext(d))
Colin Cross2207f872021-03-24 12:39:08 -0700489
490 // Create rule for metalava
491
Colin Crosscb77f752021-03-24 12:04:44 -0700492 srcJarDir := android.PathForModuleOut(ctx, "metalava", "srcjars")
Colin Cross2207f872021-03-24 12:39:08 -0700493
494 rule := android.NewRuleBuilder(pctx, ctx)
495
Colin Cross8095c292021-03-30 16:40:48 -0700496 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
497 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
498 SandboxInputs()
Colin Cross6aa5c402021-03-24 12:28:50 -0700499
Colin Cross2207f872021-03-24 12:39:08 -0700500 if BoolDefault(d.properties.High_mem, false) {
501 // This metalava run uses lots of memory, restrict the number of metalava jobs that can run in parallel.
502 rule.HighMem()
503 }
504
505 generateStubs := BoolDefault(d.properties.Generate_stubs, true)
506 var stubsDir android.OptionalPath
507 if generateStubs {
Colin Crosscb77f752021-03-24 12:04:44 -0700508 d.Javadoc.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
509 stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Colin Cross2207f872021-03-24 12:39:08 -0700510 rule.Command().Text("rm -rf").Text(stubsDir.String())
511 rule.Command().Text("mkdir -p").Text(stubsDir.String())
512 }
513
514 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, d.Javadoc.srcJars)
515
Colin Crosscb77f752021-03-24 12:04:44 -0700516 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
Colin Cross2207f872021-03-24 12:39:08 -0700517 cmd := metalavaCmd(ctx, rule, javaVersion, d.Javadoc.srcFiles, srcJarList,
Anton Hansson556e8142021-06-04 16:20:25 +0100518 deps.bootClasspath, deps.classpath, homeDir)
Colin Cross2207f872021-03-24 12:39:08 -0700519 cmd.Implicits(d.Javadoc.implicits)
520
521 d.stubsFlags(ctx, cmd, stubsDir)
522
523 d.annotationsFlags(ctx, cmd)
524 d.inclusionAnnotationsFlags(ctx, cmd)
525 d.apiLevelsAnnotationsFlags(ctx, cmd)
526
Colin Crossbc139922021-03-25 18:33:16 -0700527 d.expandArgs(ctx, cmd)
Colin Cross2207f872021-03-24 12:39:08 -0700528
Colin Cross2207f872021-03-24 12:39:08 -0700529 for _, o := range d.Javadoc.properties.Out {
530 cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
531 }
532
533 // Add options for the other optional tasks: API-lint and check-released.
534 // We generate separate timestamp files for them.
535
536 doApiLint := false
537 doCheckReleased := false
538
539 // Add API lint options.
540
541 if BoolDefault(d.properties.Check_api.Api_lint.Enabled, false) {
542 doApiLint = true
543
544 newSince := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.New_since)
545 if newSince.Valid() {
546 cmd.FlagWithInput("--api-lint ", newSince.Path())
547 } else {
548 cmd.Flag("--api-lint")
549 }
Colin Crosscb77f752021-03-24 12:04:44 -0700550 d.apiLintReport = android.PathForModuleOut(ctx, "metalava", "api_lint_report.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700551 cmd.FlagWithOutput("--report-even-if-suppressed ", d.apiLintReport) // TODO: Change to ":api-lint"
552
Colin Cross0d532412021-03-25 09:38:45 -0700553 // TODO(b/154317059): Clean up this allowlist by baselining and/or checking in last-released.
Colin Cross2207f872021-03-24 12:39:08 -0700554 if d.Name() != "android.car-system-stubs-docs" &&
555 d.Name() != "android.car-stubs-docs" {
556 cmd.Flag("--lints-as-errors")
557 cmd.Flag("--warnings-as-errors") // Most lints are actually warnings.
558 }
559
560 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700561 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "api_lint_baseline.txt")
562 d.apiLintTimestamp = android.PathForModuleOut(ctx, "metalava", "api_lint.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700563
564 // Note this string includes a special shell quote $' ... ', which decodes the "\n"s.
Colin Cross2207f872021-03-24 12:39:08 -0700565 //
566 // TODO: metalava also has a slightly different message hardcoded. Should we unify this
567 // message and metalava's one?
568 msg := `$'` + // Enclose with $' ... '
569 `************************************************************\n` +
570 `Your API changes are triggering API Lint warnings or errors.\n` +
571 `To make these errors go away, fix the code according to the\n` +
572 `error and/or warning messages above.\n` +
573 `\n` +
574 `If it is not possible to do so, there are workarounds:\n` +
575 `\n` +
Aurimas Liutikasb23b7452021-05-24 18:00:37 +0000576 `1. You can suppress the errors with @SuppressLint("<id>")\n` +
577 ` where the <id> is given in brackets in the error message above.\n`
Colin Cross2207f872021-03-24 12:39:08 -0700578
579 if baselineFile.Valid() {
580 cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
581 cmd.FlagWithOutput("--update-baseline:api-lint ", updatedBaselineOutput)
582
583 msg += fmt.Sprintf(``+
584 `2. You can update the baseline by executing the following\n`+
585 ` command:\n`+
Colin Cross63eeda02021-04-15 19:01:57 -0700586 ` (cd $ANDROID_BUILD_TOP && cp \\\n`+
587 ` "%s" \\\n`+
588 ` "%s")\n`+
Colin Cross2207f872021-03-24 12:39:08 -0700589 ` To submit the revised baseline.txt to the main Android\n`+
590 ` repository, you will need approval.\n`, updatedBaselineOutput, baselineFile.Path())
591 } else {
592 msg += fmt.Sprintf(``+
593 `2. You can add a baseline file of existing lint failures\n`+
594 ` to the build rule of %s.\n`, d.Name())
595 }
596 // Note the message ends with a ' (single quote), to close the $' ... ' .
597 msg += `************************************************************\n'`
598
599 cmd.FlagWithArg("--error-message:api-lint ", msg)
600 }
601
602 // Add "check released" options. (Detect incompatible API changes from the last public release)
603
604 if apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") {
605 doCheckReleased = true
606
607 if len(d.Javadoc.properties.Out) > 0 {
608 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
609 }
610
611 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Api_file))
612 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Removed_api_file))
613 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700614 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "last_released_baseline.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700615
Colin Crosscb77f752021-03-24 12:04:44 -0700616 d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_last_released_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700617
618 cmd.FlagWithInput("--check-compatibility:api:released ", apiFile)
619 cmd.FlagWithInput("--check-compatibility:removed:released ", removedApiFile)
620
621 if baselineFile.Valid() {
622 cmd.FlagWithInput("--baseline:compatibility:released ", baselineFile.Path())
623 cmd.FlagWithOutput("--update-baseline:compatibility:released ", updatedBaselineOutput)
624 }
625
626 // Note this string includes quote ($' ... '), which decodes the "\n"s.
627 msg := `$'\n******************************\n` +
628 `You have tried to change the API from what has been previously released in\n` +
629 `an SDK. Please fix the errors listed above.\n` +
630 `******************************\n'`
631
632 cmd.FlagWithArg("--error-message:compatibility:released ", msg)
633 }
634
Colin Cross2207f872021-03-24 12:39:08 -0700635 if generateStubs {
636 rule.Command().
637 BuiltTool("soong_zip").
638 Flag("-write_if_changed").
639 Flag("-jar").
640 FlagWithOutput("-o ", d.Javadoc.stubsSrcJar).
641 FlagWithArg("-C ", stubsDir.String()).
642 FlagWithArg("-D ", stubsDir.String())
643 }
644
645 if Bool(d.properties.Write_sdk_values) {
Colin Crosscb77f752021-03-24 12:04:44 -0700646 d.metadataZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-metadata.zip")
Colin Cross2207f872021-03-24 12:39:08 -0700647 rule.Command().
648 BuiltTool("soong_zip").
649 Flag("-write_if_changed").
650 Flag("-d").
651 FlagWithOutput("-o ", d.metadataZip).
652 FlagWithArg("-C ", d.metadataDir.String()).
653 FlagWithArg("-D ", d.metadataDir.String())
654 }
655
656 // TODO: We don't really need two separate API files, but this is a reminiscence of how
657 // we used to run metalava separately for API lint and the "last_released" check. Unify them.
658 if doApiLint {
659 rule.Command().Text("touch").Output(d.apiLintTimestamp)
660 }
661 if doCheckReleased {
662 rule.Command().Text("touch").Output(d.checkLastReleasedApiTimestamp)
663 }
664
Colin Cross6aa5c402021-03-24 12:28:50 -0700665 // TODO(b/183630617): rewrapper doesn't support restat rules
Colin Crosse52c2ac2022-03-28 17:03:35 -0700666 if !metalavaUseRbe(ctx) {
667 rule.Restat()
668 }
Colin Cross2207f872021-03-24 12:39:08 -0700669
670 zipSyncCleanupCmd(rule, srcJarDir)
671
Paul Duffin870462b2022-05-27 12:23:08 +0000672 rule.Build("metalava", "metalava merged")
673
Paul Duffin719cc622022-08-16 15:43:20 +0000674 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
675
676 if len(d.Javadoc.properties.Out) > 0 {
677 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
678 }
679
680 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
681 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Removed_api_file))
682 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Current.Baseline_file)
683
684 if baselineFile.Valid() {
685 ctx.PropertyErrorf("baseline_file", "current API check can't have a baseline file. (module %s)", ctx.ModuleName())
686 }
687
688 d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_current_api.timestamp")
689
690 rule := android.NewRuleBuilder(pctx, ctx)
691
692 // Diff command line.
693 // -F matches the closest "opening" line, such as "package android {"
694 // and " public class Intent {".
695 diff := `diff -u -F '{ *$'`
696
697 rule.Command().Text("( true")
698 rule.Command().
699 Text(diff).
700 Input(apiFile).Input(d.apiFile)
701
702 rule.Command().
703 Text(diff).
704 Input(removedApiFile).Input(d.removedApiFile)
705
706 msg := fmt.Sprintf(`\n******************************\n`+
707 `You have tried to change the API from what has been previously approved.\n\n`+
708 `To make these errors go away, you have two choices:\n`+
709 ` 1. You can add '@hide' javadoc comments (and remove @SystemApi/@TestApi/etc)\n`+
710 ` to the new methods, etc. shown in the above diff.\n\n`+
711 ` 2. You can update current.txt and/or removed.txt by executing the following command:\n`+
712 ` m %s-update-current-api\n\n`+
713 ` To submit the revised current.txt to the main Android repository,\n`+
714 ` you will need approval.\n`+
715 `******************************\n`, ctx.ModuleName())
716
717 rule.Command().
718 Text("touch").Output(d.checkCurrentApiTimestamp).
719 Text(") || (").
720 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
721 Text("; exit 38").
722 Text(")")
723
724 rule.Build("metalavaCurrentApiCheck", "check current API")
725
726 d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "update_current_api.timestamp")
727
728 // update API rule
729 rule = android.NewRuleBuilder(pctx, ctx)
730
731 rule.Command().Text("( true")
732
733 rule.Command().
734 Text("cp").Flag("-f").
735 Input(d.apiFile).Flag(apiFile.String())
736
737 rule.Command().
738 Text("cp").Flag("-f").
739 Input(d.removedApiFile).Flag(removedApiFile.String())
740
741 msg = "failed to update public API"
742
743 rule.Command().
744 Text("touch").Output(d.updateCurrentApiTimestamp).
745 Text(") || (").
746 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
747 Text("; exit 38").
748 Text(")")
749
750 rule.Build("metalavaCurrentApiUpdate", "update current API")
751 }
752
Colin Cross2207f872021-03-24 12:39:08 -0700753 if String(d.properties.Check_nullability_warnings) != "" {
754 if d.nullabilityWarningsFile == nil {
755 ctx.PropertyErrorf("check_nullability_warnings",
756 "Cannot specify check_nullability_warnings unless validating nullability")
757 }
758
759 checkNullabilityWarnings := android.PathForModuleSrc(ctx, String(d.properties.Check_nullability_warnings))
760
Colin Crosscb77f752021-03-24 12:04:44 -0700761 d.checkNullabilityWarningsTimestamp = android.PathForModuleOut(ctx, "metalava", "check_nullability_warnings.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700762
763 msg := fmt.Sprintf(`\n******************************\n`+
764 `The warnings encountered during nullability annotation validation did\n`+
765 `not match the checked in file of expected warnings. The diffs are shown\n`+
766 `above. You have two options:\n`+
767 ` 1. Resolve the differences by editing the nullability annotations.\n`+
768 ` 2. Update the file of expected warnings by running:\n`+
769 ` cp %s %s\n`+
770 ` and submitting the updated file as part of your change.`,
771 d.nullabilityWarningsFile, checkNullabilityWarnings)
772
773 rule := android.NewRuleBuilder(pctx, ctx)
774
775 rule.Command().
776 Text("(").
777 Text("diff").Input(checkNullabilityWarnings).Input(d.nullabilityWarningsFile).
778 Text("&&").
779 Text("touch").Output(d.checkNullabilityWarningsTimestamp).
780 Text(") || (").
781 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
782 Text("; exit 38").
783 Text(")")
784
785 rule.Build("nullabilityWarningsCheck", "nullability warnings check")
786 }
787}
788
789func StubsDefaultsFactory() android.Module {
790 module := &DocDefaults{}
791
792 module.AddProperties(
793 &JavadocProperties{},
794 &DroidstubsProperties{},
795 )
796
797 android.InitDefaultsModule(module)
798
799 return module
800}
801
802var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
803
804type PrebuiltStubsSourcesProperties struct {
805 Srcs []string `android:"path"`
806}
807
808type PrebuiltStubsSources struct {
809 android.ModuleBase
810 android.DefaultableModuleBase
811 prebuilt android.Prebuilt
812 android.SdkBase
813
814 properties PrebuiltStubsSourcesProperties
815
kgui67007242022-01-25 13:50:25 +0800816 stubsSrcJar android.Path
Colin Cross2207f872021-03-24 12:39:08 -0700817}
818
819func (p *PrebuiltStubsSources) OutputFiles(tag string) (android.Paths, error) {
820 switch tag {
821 case "":
822 return android.Paths{p.stubsSrcJar}, nil
823 default:
824 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
825 }
826}
827
828func (d *PrebuiltStubsSources) StubsSrcJar() android.Path {
829 return d.stubsSrcJar
830}
831
832func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross2207f872021-03-24 12:39:08 -0700833 if len(p.properties.Srcs) != 1 {
Anton Hansson86758ac2021-11-03 14:44:12 +0000834 ctx.PropertyErrorf("srcs", "must only specify one directory path or srcjar, contains %d paths", len(p.properties.Srcs))
Colin Cross2207f872021-03-24 12:39:08 -0700835 return
836 }
837
Anton Hansson86758ac2021-11-03 14:44:12 +0000838 src := p.properties.Srcs[0]
839 if filepath.Ext(src) == ".srcjar" {
840 // This is a srcjar. We can use it directly.
841 p.stubsSrcJar = android.PathForModuleSrc(ctx, src)
842 } else {
843 outPath := android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
Colin Cross2207f872021-03-24 12:39:08 -0700844
Anton Hansson86758ac2021-11-03 14:44:12 +0000845 // This is a directory. Glob the contents just in case the directory does not exist.
846 srcGlob := src + "/**/*"
847 srcPaths := android.PathsForModuleSrc(ctx, []string{srcGlob})
Colin Cross2207f872021-03-24 12:39:08 -0700848
Anton Hansson86758ac2021-11-03 14:44:12 +0000849 // Although PathForModuleSrc can return nil if either the path doesn't exist or
850 // the path components are invalid it won't in this case because no components
851 // are specified and the module directory must exist in order to get this far.
852 srcDir := android.PathForModuleSrc(ctx).(android.SourcePath).Join(ctx, src)
Colin Cross2207f872021-03-24 12:39:08 -0700853
Anton Hansson86758ac2021-11-03 14:44:12 +0000854 rule := android.NewRuleBuilder(pctx, ctx)
855 rule.Command().
856 BuiltTool("soong_zip").
857 Flag("-write_if_changed").
858 Flag("-jar").
859 FlagWithOutput("-o ", outPath).
860 FlagWithArg("-C ", srcDir.String()).
861 FlagWithRspFileInputList("-r ", outPath.ReplaceExtension(ctx, "rsp"), srcPaths)
862 rule.Restat()
863 rule.Build("zip src", "Create srcjar from prebuilt source")
864 p.stubsSrcJar = outPath
865 }
Colin Cross2207f872021-03-24 12:39:08 -0700866}
867
868func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
869 return &p.prebuilt
870}
871
872func (p *PrebuiltStubsSources) Name() string {
873 return p.prebuilt.Name(p.ModuleBase.Name())
874}
875
876// prebuilt_stubs_sources imports a set of java source files as if they were
877// generated by droidstubs.
878//
879// By default, a prebuilt_stubs_sources has a single variant that expects a
880// set of `.java` files generated by droidstubs.
881//
882// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
883// for host modules.
884//
885// Intended only for use by sdk snapshots.
886func PrebuiltStubsSourcesFactory() android.Module {
887 module := &PrebuiltStubsSources{}
888
889 module.AddProperties(&module.properties)
890
891 android.InitPrebuiltModule(module, &module.properties.Srcs)
892 android.InitSdkAwareModule(module)
893 InitDroiddocModule(module, android.HostAndDeviceSupported)
894 return module
895}