blob: d444738a63a3e2df4c2b0c46d7174f5f4959a557 [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
53 apiFile android.WritablePath
54 apiXmlFile android.WritablePath
55 lastReleasedApiXmlFile android.WritablePath
56 privateApiFile android.WritablePath
57 removedApiFile android.WritablePath
Colin Cross2207f872021-03-24 12:39:08 -070058 nullabilityWarningsFile android.WritablePath
59
60 checkCurrentApiTimestamp android.WritablePath
61 updateCurrentApiTimestamp android.WritablePath
62 checkLastReleasedApiTimestamp android.WritablePath
63 apiLintTimestamp android.WritablePath
64 apiLintReport android.WritablePath
65
66 checkNullabilityWarningsTimestamp android.WritablePath
67
68 annotationsZip android.WritablePath
69 apiVersionsXml android.WritablePath
70
71 apiFilePath android.Path
72 removedApiFilePath android.Path
73
74 metadataZip android.WritablePath
75 metadataDir android.WritablePath
76}
77
78type DroidstubsProperties struct {
79 // The generated public API filename by Metalava, defaults to <module>_api.txt
80 Api_filename *string
81
82 // the generated removed API filename by Metalava, defaults to <module>_removed.txt
83 Removed_api_filename *string
84
Colin Cross2207f872021-03-24 12:39:08 -070085 Check_api struct {
86 Last_released ApiToCheck
87
88 Current ApiToCheck
89
90 Api_lint struct {
91 Enabled *bool
92
93 // If set, performs api_lint on any new APIs not found in the given signature file
94 New_since *string `android:"path"`
95
96 // If not blank, path to the baseline txt file for approved API lint violations.
97 Baseline_file *string `android:"path"`
98 }
99 }
100
101 // user can specify the version of previous released API file in order to do compatibility check.
102 Previous_api *string `android:"path"`
103
104 // is set to true, Metalava will allow framework SDK to contain annotations.
105 Annotations_enabled *bool
106
107 // a list of top-level directories containing files to merge qualifier annotations (i.e. those intended to be included in the stubs written) from.
108 Merge_annotations_dirs []string
109
110 // a list of top-level directories containing Java stub files to merge show/hide annotations from.
111 Merge_inclusion_annotations_dirs []string
112
113 // a file containing a list of classes to do nullability validation for.
114 Validate_nullability_from_list *string
115
116 // a file containing expected warnings produced by validation of nullability annotations.
117 Check_nullability_warnings *string
118
119 // if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
120 Create_doc_stubs *bool
121
122 // if set to true, cause Metalava to output Javadoc comments in the stubs source files. Defaults to false.
123 // Has no effect if create_doc_stubs: true.
124 Output_javadoc_comments *bool
125
126 // if set to false then do not write out stubs. Defaults to true.
127 //
128 // TODO(b/146727827): Remove capability when we do not need to generate stubs and API separately.
129 Generate_stubs *bool
130
131 // if set to true, provides a hint to the build system that this rule uses a lot of memory,
132 // whicih can be used for scheduling purposes
133 High_mem *bool
134
satayev783195c2021-06-23 21:49:57 +0100135 // if set to true, Metalava will allow framework SDK to contain API levels annotations.
Colin Cross2207f872021-03-24 12:39:08 -0700136 Api_levels_annotations_enabled *bool
137
138 // the dirs which Metalava extracts API levels annotations from.
139 Api_levels_annotations_dirs []string
140
Pedro Loureirocc203502021-10-04 17:24:00 +0000141 // 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 +0100142 Api_levels_sdk_type *string
143
Colin Cross2207f872021-03-24 12:39:08 -0700144 // the filename which Metalava extracts API levels annotations from. Defaults to android.jar.
145 Api_levels_jar_filename *string
146
147 // if set to true, collect the values used by the Dev tools and
148 // write them in files packaged with the SDK. Defaults to false.
149 Write_sdk_values *bool
150}
151
Anton Hansson52609322021-05-05 10:36:05 +0100152// Used by xsd_config
153type ApiFilePath interface {
154 ApiFilePath() android.Path
155}
156
157type ApiStubsSrcProvider interface {
158 StubsSrcJar() android.Path
159}
160
161// Provider of information about API stubs, used by java_sdk_library.
162type ApiStubsProvider interface {
Anton Hanssond78eb762021-09-21 15:25:12 +0100163 AnnotationsZip() android.Path
Anton Hansson52609322021-05-05 10:36:05 +0100164 ApiFilePath
165 RemovedApiFilePath() android.Path
166
167 ApiStubsSrcProvider
168}
169
Colin Cross2207f872021-03-24 12:39:08 -0700170// droidstubs passes sources files through Metalava to generate stub .java files that only contain the API to be
171// documented, filtering out hidden classes and methods. The resulting .java files are intended to be passed to
172// a droiddoc module to generate documentation.
173func DroidstubsFactory() android.Module {
174 module := &Droidstubs{}
175
176 module.AddProperties(&module.properties,
177 &module.Javadoc.properties)
178
179 InitDroiddocModule(module, android.HostAndDeviceSupported)
180 android.InitSdkAwareModule(module)
181 return module
182}
183
184// droidstubs_host passes sources files through Metalava to generate stub .java files that only contain the API
185// to be documented, filtering out hidden classes and methods. The resulting .java files are intended to be
186// passed to a droiddoc_host module to generate documentation. Use a droidstubs_host instead of a droidstubs
187// module when symbols needed by the source files are provided by java_library_host modules.
188func DroidstubsHostFactory() android.Module {
189 module := &Droidstubs{}
190
191 module.AddProperties(&module.properties,
192 &module.Javadoc.properties)
193
194 InitDroiddocModule(module, android.HostSupported)
195 return module
196}
197
198func (d *Droidstubs) OutputFiles(tag string) (android.Paths, error) {
199 switch tag {
200 case "":
201 return android.Paths{d.stubsSrcJar}, nil
202 case ".docs.zip":
203 return android.Paths{d.docZip}, nil
204 case ".api.txt", android.DefaultDistTag:
205 // This is the default dist path for dist properties that have no tag property.
206 return android.Paths{d.apiFilePath}, nil
207 case ".removed-api.txt":
208 return android.Paths{d.removedApiFilePath}, nil
209 case ".annotations.zip":
210 return android.Paths{d.annotationsZip}, nil
211 case ".api_versions.xml":
212 return android.Paths{d.apiVersionsXml}, nil
213 default:
214 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
215 }
216}
217
Anton Hanssond78eb762021-09-21 15:25:12 +0100218func (d *Droidstubs) AnnotationsZip() android.Path {
219 return d.annotationsZip
220}
221
Colin Cross2207f872021-03-24 12:39:08 -0700222func (d *Droidstubs) ApiFilePath() android.Path {
223 return d.apiFilePath
224}
225
226func (d *Droidstubs) RemovedApiFilePath() android.Path {
227 return d.removedApiFilePath
228}
229
230func (d *Droidstubs) StubsSrcJar() android.Path {
231 return d.stubsSrcJar
232}
233
234var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
235var metalavaMergeInclusionAnnotationsDirTag = dependencyTag{name: "metalava-merge-inclusion-annotations-dir"}
236var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
237
238func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
239 d.Javadoc.addDeps(ctx)
240
241 if len(d.properties.Merge_annotations_dirs) != 0 {
242 for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
243 ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
244 }
245 }
246
247 if len(d.properties.Merge_inclusion_annotations_dirs) != 0 {
248 for _, mergeInclusionAnnotationsDir := range d.properties.Merge_inclusion_annotations_dirs {
249 ctx.AddDependency(ctx.Module(), metalavaMergeInclusionAnnotationsDirTag, mergeInclusionAnnotationsDir)
250 }
251 }
252
253 if len(d.properties.Api_levels_annotations_dirs) != 0 {
254 for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
255 ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
256 }
257 }
258}
259
260func (d *Droidstubs) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
261 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
262 apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
263 String(d.properties.Api_filename) != "" {
264 filename := proptools.StringDefault(d.properties.Api_filename, ctx.ModuleName()+"_api.txt")
Colin Crosscb77f752021-03-24 12:04:44 -0700265 d.apiFile = android.PathForModuleOut(ctx, "metalava", filename)
Colin Cross2207f872021-03-24 12:39:08 -0700266 cmd.FlagWithOutput("--api ", d.apiFile)
267 d.apiFilePath = d.apiFile
268 } else if sourceApiFile := proptools.String(d.properties.Check_api.Current.Api_file); sourceApiFile != "" {
269 // If check api is disabled then make the source file available for export.
270 d.apiFilePath = android.PathForModuleSrc(ctx, sourceApiFile)
271 }
272
273 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
274 apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
275 String(d.properties.Removed_api_filename) != "" {
276 filename := proptools.StringDefault(d.properties.Removed_api_filename, ctx.ModuleName()+"_removed.txt")
Colin Crosscb77f752021-03-24 12:04:44 -0700277 d.removedApiFile = android.PathForModuleOut(ctx, "metalava", filename)
Colin Cross2207f872021-03-24 12:39:08 -0700278 cmd.FlagWithOutput("--removed-api ", d.removedApiFile)
279 d.removedApiFilePath = d.removedApiFile
280 } else if sourceRemovedApiFile := proptools.String(d.properties.Check_api.Current.Removed_api_file); sourceRemovedApiFile != "" {
281 // If check api is disabled then make the source removed api file available for export.
282 d.removedApiFilePath = android.PathForModuleSrc(ctx, sourceRemovedApiFile)
283 }
284
Colin Cross2207f872021-03-24 12:39:08 -0700285 if Bool(d.properties.Write_sdk_values) {
Colin Crosscb77f752021-03-24 12:04:44 -0700286 d.metadataDir = android.PathForModuleOut(ctx, "metalava", "metadata")
Colin Cross2207f872021-03-24 12:39:08 -0700287 cmd.FlagWithArg("--sdk-values ", d.metadataDir.String())
288 }
289
290 if stubsDir.Valid() {
291 if Bool(d.properties.Create_doc_stubs) {
292 cmd.FlagWithArg("--doc-stubs ", stubsDir.String())
293 } else {
294 cmd.FlagWithArg("--stubs ", stubsDir.String())
295 if !Bool(d.properties.Output_javadoc_comments) {
296 cmd.Flag("--exclude-documentation-from-stubs")
297 }
298 }
299 }
300}
301
302func (d *Droidstubs) annotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
303 if Bool(d.properties.Annotations_enabled) {
304 cmd.Flag("--include-annotations")
305
Andrei Onea4985e512021-04-29 16:29:34 +0100306 cmd.FlagWithArg("--exclude-annotation ", "androidx.annotation.RequiresApi")
307
Colin Cross2207f872021-03-24 12:39:08 -0700308 validatingNullability :=
Colin Crossbc139922021-03-25 18:33:16 -0700309 strings.Contains(String(d.Javadoc.properties.Args), "--validate-nullability-from-merged-stubs") ||
Colin Cross2207f872021-03-24 12:39:08 -0700310 String(d.properties.Validate_nullability_from_list) != ""
311
312 migratingNullability := String(d.properties.Previous_api) != ""
313 if migratingNullability {
314 previousApi := android.PathForModuleSrc(ctx, String(d.properties.Previous_api))
315 cmd.FlagWithInput("--migrate-nullness ", previousApi)
316 }
317
318 if s := String(d.properties.Validate_nullability_from_list); s != "" {
319 cmd.FlagWithInput("--validate-nullability-from-list ", android.PathForModuleSrc(ctx, s))
320 }
321
322 if validatingNullability {
Colin Crosscb77f752021-03-24 12:04:44 -0700323 d.nullabilityWarningsFile = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_nullability_warnings.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700324 cmd.FlagWithOutput("--nullability-warnings-txt ", d.nullabilityWarningsFile)
325 }
326
Colin Crosscb77f752021-03-24 12:04:44 -0700327 d.annotationsZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_annotations.zip")
Colin Cross2207f872021-03-24 12:39:08 -0700328 cmd.FlagWithOutput("--extract-annotations ", d.annotationsZip)
329
330 if len(d.properties.Merge_annotations_dirs) != 0 {
331 d.mergeAnnoDirFlags(ctx, cmd)
332 }
333
334 // TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
335 cmd.FlagWithArg("--hide ", "HiddenTypedefConstant").
336 FlagWithArg("--hide ", "SuperfluousPrefix").
Sam Gilbert049af112022-03-04 16:03:53 -0500337 FlagWithArg("--hide ", "AnnotationExtraction").
338 // b/222738070
Sam Gilbert675f0b42022-03-08 11:24:44 -0500339 FlagWithArg("--hide ", "BannedThrow").
340 // b/223382732
341 FlagWithArg("--hide ", "ChangedDefault")
Colin Cross2207f872021-03-24 12:39:08 -0700342 }
343}
344
345func (d *Droidstubs) mergeAnnoDirFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
346 ctx.VisitDirectDepsWithTag(metalavaMergeAnnotationsDirTag, func(m android.Module) {
347 if t, ok := m.(*ExportedDroiddocDir); ok {
348 cmd.FlagWithArg("--merge-qualifier-annotations ", t.dir.String()).Implicits(t.deps)
349 } else {
350 ctx.PropertyErrorf("merge_annotations_dirs",
351 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
352 }
353 })
354}
355
356func (d *Droidstubs) inclusionAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
357 ctx.VisitDirectDepsWithTag(metalavaMergeInclusionAnnotationsDirTag, func(m android.Module) {
358 if t, ok := m.(*ExportedDroiddocDir); ok {
359 cmd.FlagWithArg("--merge-inclusion-annotations ", t.dir.String()).Implicits(t.deps)
360 } else {
361 ctx.PropertyErrorf("merge_inclusion_annotations_dirs",
362 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
363 }
364 })
365}
366
367func (d *Droidstubs) apiLevelsAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
368 if !Bool(d.properties.Api_levels_annotations_enabled) {
369 return
370 }
371
Colin Crosscb77f752021-03-24 12:04:44 -0700372 d.apiVersionsXml = android.PathForModuleOut(ctx, "metalava", "api-versions.xml")
Colin Cross2207f872021-03-24 12:39:08 -0700373
374 if len(d.properties.Api_levels_annotations_dirs) == 0 {
375 ctx.PropertyErrorf("api_levels_annotations_dirs",
376 "has to be non-empty if api levels annotations was enabled!")
377 }
378
379 cmd.FlagWithOutput("--generate-api-levels ", d.apiVersionsXml)
380 cmd.FlagWithInput("--apply-api-levels ", d.apiVersionsXml)
381 cmd.FlagWithArg("--current-version ", ctx.Config().PlatformSdkVersion().String())
Jeff Sharkey50493f02021-06-01 12:12:31 -0600382 // STOPSHIP: RESTORE THIS LOGIC WHEN DECLARING "REL" BUILD
383 // cmd.FlagWithArg("--current-codename ", ctx.Config().PlatformSdkCodename())
Colin Cross2207f872021-03-24 12:39:08 -0700384
385 filename := proptools.StringDefault(d.properties.Api_levels_jar_filename, "android.jar")
386
satayev783195c2021-06-23 21:49:57 +0100387 var dirs []string
Colin Cross2207f872021-03-24 12:39:08 -0700388 ctx.VisitDirectDepsWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.Module) {
389 if t, ok := m.(*ExportedDroiddocDir); ok {
390 for _, dep := range t.deps {
Colin Cross5f6ffc72021-03-29 21:54:45 -0700391 if dep.Base() == filename {
392 cmd.Implicit(dep)
393 }
394 if filename != "android.jar" && dep.Base() == "android.jar" {
395 // Metalava implicitly searches these patterns:
396 // prebuilts/tools/common/api-versions/android-%/android.jar
397 // prebuilts/sdk/%/public/android.jar
398 // Add android.jar files from the api_levels_annotations_dirs directories to try
399 // to satisfy these patterns. If Metalava can't find a match for an API level
400 // between 1 and 28 in at least one pattern it will fail.
Colin Cross2207f872021-03-24 12:39:08 -0700401 cmd.Implicit(dep)
402 }
403 }
satayev783195c2021-06-23 21:49:57 +0100404
405 dirs = append(dirs, t.dir.String())
Colin Cross2207f872021-03-24 12:39:08 -0700406 } else {
407 ctx.PropertyErrorf("api_levels_annotations_dirs",
408 "module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
409 }
410 })
satayev783195c2021-06-23 21:49:57 +0100411
412 // Add all relevant --android-jar-pattern patterns for Metalava.
413 // When parsing a stub jar for a specific version, Metalava picks the first pattern that defines
414 // an actual file present on disk (in the order the patterns were passed). For system APIs for
415 // privileged apps that are only defined since API level 21 (Lollipop), fallback to public stubs
Pedro Loureirocc203502021-10-04 17:24:00 +0000416 // for older releases. Similarly, module-lib falls back to system API.
417 var sdkDirs []string
418 switch proptools.StringDefault(d.properties.Api_levels_sdk_type, "public") {
419 case "module-lib":
420 sdkDirs = []string{"module-lib", "system", "public"}
421 case "system":
422 sdkDirs = []string{"system", "public"}
423 case "public":
424 sdkDirs = []string{"public"}
425 default:
426 ctx.PropertyErrorf("api_levels_sdk_type", "needs to be one of %v", allowedApiLevelSdkTypes)
427 return
satayev783195c2021-06-23 21:49:57 +0100428 }
Pedro Loureirocc203502021-10-04 17:24:00 +0000429
430 for _, sdkDir := range sdkDirs {
431 for _, dir := range dirs {
432 cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/%%/%s/%s", dir, sdkDir, filename))
433 }
satayev783195c2021-06-23 21:49:57 +0100434 }
Colin Cross2207f872021-03-24 12:39:08 -0700435}
436
Colin Crosse52c2ac2022-03-28 17:03:35 -0700437func metalavaUseRbe(ctx android.ModuleContext) bool {
438 return ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_METALAVA")
439}
440
Colin Cross2207f872021-03-24 12:39:08 -0700441func metalavaCmd(ctx android.ModuleContext, rule *android.RuleBuilder, javaVersion javaVersion, srcs android.Paths,
Anton Hansson556e8142021-06-04 16:20:25 +0100442 srcJarList android.Path, bootclasspath, classpath classpath, homeDir android.WritablePath) *android.RuleBuilderCommand {
Colin Cross2207f872021-03-24 12:39:08 -0700443 rule.Command().Text("rm -rf").Flag(homeDir.String())
444 rule.Command().Text("mkdir -p").Flag(homeDir.String())
445
Anton Hansson556e8142021-06-04 16:20:25 +0100446 cmd := rule.Command()
Colin Cross2207f872021-03-24 12:39:08 -0700447 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
448
Colin Crosse52c2ac2022-03-28 17:03:35 -0700449 if metalavaUseRbe(ctx) {
Colin Cross2207f872021-03-24 12:39:08 -0700450 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
Colin Cross8095c292021-03-30 16:40:48 -0700451 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
452 labels := map[string]string{"type": "tool", "name": "metalava"}
453 // TODO: metalava pool rejects these jobs
454 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
455 rule.Rewrapper(&remoteexec.REParams{
456 Labels: labels,
457 ExecStrategy: execStrategy,
458 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
459 Platform: map[string]string{remoteexec.PoolKey: pool},
460 })
Colin Cross2207f872021-03-24 12:39:08 -0700461 }
462
Colin Cross6aa5c402021-03-24 12:28:50 -0700463 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
Colin Cross2207f872021-03-24 12:39:08 -0700464 Flag(config.JavacVmFlags).
465 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
466 FlagWithArg("-encoding ", "UTF-8").
467 FlagWithArg("-source ", javaVersion.String()).
468 FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, "metalava.rsp"), srcs).
469 FlagWithInput("@", srcJarList)
470
Colin Cross2207f872021-03-24 12:39:08 -0700471 if len(bootclasspath) > 0 {
472 cmd.FlagWithInputList("-bootclasspath ", bootclasspath.Paths(), ":")
473 }
474
475 if len(classpath) > 0 {
476 cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
477 }
478
Colin Cross2207f872021-03-24 12:39:08 -0700479 cmd.Flag("--no-banner").
480 Flag("--color").
481 Flag("--quiet").
482 Flag("--format=v2").
483 FlagWithArg("--repeat-errors-max ", "10").
Sam Gilbert09cb5db2021-10-06 11:28:28 -0400484 FlagWithArg("--hide ", "UnresolvedImport").
Ember Rose7c57af32022-04-01 10:34:44 -0400485 FlagWithArg("--hide ", "InvalidNullabilityOverride").
Sam Gilbert28e41282022-03-09 15:24:48 +0000486 // b/223382732
487 FlagWithArg("--hide ", "ChangedDefault")
Colin Cross2207f872021-03-24 12:39:08 -0700488
489 return cmd
490}
491
492func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
493 deps := d.Javadoc.collectDeps(ctx)
494
Jiyong Parkf1691d22021-03-29 20:11:58 +0900495 javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), android.SdkContext(d))
Colin Cross2207f872021-03-24 12:39:08 -0700496
497 // Create rule for metalava
498
Colin Crosscb77f752021-03-24 12:04:44 -0700499 srcJarDir := android.PathForModuleOut(ctx, "metalava", "srcjars")
Colin Cross2207f872021-03-24 12:39:08 -0700500
501 rule := android.NewRuleBuilder(pctx, ctx)
502
Colin Cross8095c292021-03-30 16:40:48 -0700503 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
504 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
505 SandboxInputs()
Colin Cross6aa5c402021-03-24 12:28:50 -0700506
Colin Cross2207f872021-03-24 12:39:08 -0700507 if BoolDefault(d.properties.High_mem, false) {
508 // This metalava run uses lots of memory, restrict the number of metalava jobs that can run in parallel.
509 rule.HighMem()
510 }
511
512 generateStubs := BoolDefault(d.properties.Generate_stubs, true)
513 var stubsDir android.OptionalPath
514 if generateStubs {
Colin Crosscb77f752021-03-24 12:04:44 -0700515 d.Javadoc.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
516 stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Colin Cross2207f872021-03-24 12:39:08 -0700517 rule.Command().Text("rm -rf").Text(stubsDir.String())
518 rule.Command().Text("mkdir -p").Text(stubsDir.String())
519 }
520
521 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, d.Javadoc.srcJars)
522
Colin Crosscb77f752021-03-24 12:04:44 -0700523 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
Colin Cross2207f872021-03-24 12:39:08 -0700524 cmd := metalavaCmd(ctx, rule, javaVersion, d.Javadoc.srcFiles, srcJarList,
Anton Hansson556e8142021-06-04 16:20:25 +0100525 deps.bootClasspath, deps.classpath, homeDir)
Colin Cross2207f872021-03-24 12:39:08 -0700526 cmd.Implicits(d.Javadoc.implicits)
527
528 d.stubsFlags(ctx, cmd, stubsDir)
529
530 d.annotationsFlags(ctx, cmd)
531 d.inclusionAnnotationsFlags(ctx, cmd)
532 d.apiLevelsAnnotationsFlags(ctx, cmd)
533
Colin Crossbc139922021-03-25 18:33:16 -0700534 d.expandArgs(ctx, cmd)
Colin Cross2207f872021-03-24 12:39:08 -0700535
Colin Cross2207f872021-03-24 12:39:08 -0700536 for _, o := range d.Javadoc.properties.Out {
537 cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
538 }
539
540 // Add options for the other optional tasks: API-lint and check-released.
541 // We generate separate timestamp files for them.
542
543 doApiLint := false
544 doCheckReleased := false
545
546 // Add API lint options.
547
548 if BoolDefault(d.properties.Check_api.Api_lint.Enabled, false) {
549 doApiLint = true
550
551 newSince := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.New_since)
552 if newSince.Valid() {
553 cmd.FlagWithInput("--api-lint ", newSince.Path())
554 } else {
555 cmd.Flag("--api-lint")
556 }
Colin Crosscb77f752021-03-24 12:04:44 -0700557 d.apiLintReport = android.PathForModuleOut(ctx, "metalava", "api_lint_report.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700558 cmd.FlagWithOutput("--report-even-if-suppressed ", d.apiLintReport) // TODO: Change to ":api-lint"
559
Colin Cross0d532412021-03-25 09:38:45 -0700560 // TODO(b/154317059): Clean up this allowlist by baselining and/or checking in last-released.
Colin Cross2207f872021-03-24 12:39:08 -0700561 if d.Name() != "android.car-system-stubs-docs" &&
562 d.Name() != "android.car-stubs-docs" {
563 cmd.Flag("--lints-as-errors")
564 cmd.Flag("--warnings-as-errors") // Most lints are actually warnings.
565 }
566
567 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700568 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "api_lint_baseline.txt")
569 d.apiLintTimestamp = android.PathForModuleOut(ctx, "metalava", "api_lint.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700570
571 // Note this string includes a special shell quote $' ... ', which decodes the "\n"s.
Colin Cross2207f872021-03-24 12:39:08 -0700572 //
573 // TODO: metalava also has a slightly different message hardcoded. Should we unify this
574 // message and metalava's one?
575 msg := `$'` + // Enclose with $' ... '
576 `************************************************************\n` +
577 `Your API changes are triggering API Lint warnings or errors.\n` +
578 `To make these errors go away, fix the code according to the\n` +
579 `error and/or warning messages above.\n` +
580 `\n` +
581 `If it is not possible to do so, there are workarounds:\n` +
582 `\n` +
Aurimas Liutikasb23b7452021-05-24 18:00:37 +0000583 `1. You can suppress the errors with @SuppressLint("<id>")\n` +
584 ` where the <id> is given in brackets in the error message above.\n`
Colin Cross2207f872021-03-24 12:39:08 -0700585
586 if baselineFile.Valid() {
587 cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
588 cmd.FlagWithOutput("--update-baseline:api-lint ", updatedBaselineOutput)
589
590 msg += fmt.Sprintf(``+
591 `2. You can update the baseline by executing the following\n`+
592 ` command:\n`+
Colin Cross63eeda02021-04-15 19:01:57 -0700593 ` (cd $ANDROID_BUILD_TOP && cp \\\n`+
594 ` "%s" \\\n`+
595 ` "%s")\n`+
Colin Cross2207f872021-03-24 12:39:08 -0700596 ` To submit the revised baseline.txt to the main Android\n`+
597 ` repository, you will need approval.\n`, updatedBaselineOutput, baselineFile.Path())
598 } else {
599 msg += fmt.Sprintf(``+
600 `2. You can add a baseline file of existing lint failures\n`+
601 ` to the build rule of %s.\n`, d.Name())
602 }
603 // Note the message ends with a ' (single quote), to close the $' ... ' .
604 msg += `************************************************************\n'`
605
606 cmd.FlagWithArg("--error-message:api-lint ", msg)
607 }
608
609 // Add "check released" options. (Detect incompatible API changes from the last public release)
610
611 if apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") {
612 doCheckReleased = true
613
614 if len(d.Javadoc.properties.Out) > 0 {
615 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
616 }
617
618 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Api_file))
619 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Removed_api_file))
620 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700621 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "last_released_baseline.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700622
Colin Crosscb77f752021-03-24 12:04:44 -0700623 d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_last_released_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700624
625 cmd.FlagWithInput("--check-compatibility:api:released ", apiFile)
626 cmd.FlagWithInput("--check-compatibility:removed:released ", removedApiFile)
627
628 if baselineFile.Valid() {
629 cmd.FlagWithInput("--baseline:compatibility:released ", baselineFile.Path())
630 cmd.FlagWithOutput("--update-baseline:compatibility:released ", updatedBaselineOutput)
631 }
632
633 // Note this string includes quote ($' ... '), which decodes the "\n"s.
634 msg := `$'\n******************************\n` +
635 `You have tried to change the API from what has been previously released in\n` +
636 `an SDK. Please fix the errors listed above.\n` +
637 `******************************\n'`
638
639 cmd.FlagWithArg("--error-message:compatibility:released ", msg)
640 }
641
Colin Cross2207f872021-03-24 12:39:08 -0700642 if generateStubs {
643 rule.Command().
644 BuiltTool("soong_zip").
645 Flag("-write_if_changed").
646 Flag("-jar").
647 FlagWithOutput("-o ", d.Javadoc.stubsSrcJar).
648 FlagWithArg("-C ", stubsDir.String()).
649 FlagWithArg("-D ", stubsDir.String())
650 }
651
652 if Bool(d.properties.Write_sdk_values) {
Colin Crosscb77f752021-03-24 12:04:44 -0700653 d.metadataZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-metadata.zip")
Colin Cross2207f872021-03-24 12:39:08 -0700654 rule.Command().
655 BuiltTool("soong_zip").
656 Flag("-write_if_changed").
657 Flag("-d").
658 FlagWithOutput("-o ", d.metadataZip).
659 FlagWithArg("-C ", d.metadataDir.String()).
660 FlagWithArg("-D ", d.metadataDir.String())
661 }
662
663 // TODO: We don't really need two separate API files, but this is a reminiscence of how
664 // we used to run metalava separately for API lint and the "last_released" check. Unify them.
665 if doApiLint {
666 rule.Command().Text("touch").Output(d.apiLintTimestamp)
667 }
668 if doCheckReleased {
669 rule.Command().Text("touch").Output(d.checkLastReleasedApiTimestamp)
670 }
671
Colin Cross6aa5c402021-03-24 12:28:50 -0700672 // TODO(b/183630617): rewrapper doesn't support restat rules
Colin Crosse52c2ac2022-03-28 17:03:35 -0700673 if !metalavaUseRbe(ctx) {
674 rule.Restat()
675 }
Colin Cross2207f872021-03-24 12:39:08 -0700676
677 zipSyncCleanupCmd(rule, srcJarDir)
678
679 rule.Build("metalava", "metalava merged")
680
681 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
682
683 if len(d.Javadoc.properties.Out) > 0 {
684 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
685 }
686
687 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
688 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Removed_api_file))
689 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Current.Baseline_file)
690
691 if baselineFile.Valid() {
692 ctx.PropertyErrorf("baseline_file", "current API check can't have a baseline file. (module %s)", ctx.ModuleName())
693 }
694
Colin Crosscb77f752021-03-24 12:04:44 -0700695 d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_current_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700696
697 rule := android.NewRuleBuilder(pctx, ctx)
698
699 // Diff command line.
700 // -F matches the closest "opening" line, such as "package android {"
701 // and " public class Intent {".
702 diff := `diff -u -F '{ *$'`
703
704 rule.Command().Text("( true")
705 rule.Command().
706 Text(diff).
707 Input(apiFile).Input(d.apiFile)
708
709 rule.Command().
710 Text(diff).
711 Input(removedApiFile).Input(d.removedApiFile)
712
713 msg := fmt.Sprintf(`\n******************************\n`+
714 `You have tried to change the API from what has been previously approved.\n\n`+
715 `To make these errors go away, you have two choices:\n`+
716 ` 1. You can add '@hide' javadoc comments (and remove @SystemApi/@TestApi/etc)\n`+
717 ` to the new methods, etc. shown in the above diff.\n\n`+
718 ` 2. You can update current.txt and/or removed.txt by executing the following command:\n`+
719 ` m %s-update-current-api\n\n`+
720 ` To submit the revised current.txt to the main Android repository,\n`+
721 ` you will need approval.\n`+
722 `******************************\n`, ctx.ModuleName())
723
724 rule.Command().
725 Text("touch").Output(d.checkCurrentApiTimestamp).
726 Text(") || (").
727 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
728 Text("; exit 38").
729 Text(")")
730
731 rule.Build("metalavaCurrentApiCheck", "check current API")
732
Colin Crosscb77f752021-03-24 12:04:44 -0700733 d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "update_current_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700734
735 // update API rule
736 rule = android.NewRuleBuilder(pctx, ctx)
737
738 rule.Command().Text("( true")
739
740 rule.Command().
741 Text("cp").Flag("-f").
742 Input(d.apiFile).Flag(apiFile.String())
743
744 rule.Command().
745 Text("cp").Flag("-f").
746 Input(d.removedApiFile).Flag(removedApiFile.String())
747
748 msg = "failed to update public API"
749
750 rule.Command().
751 Text("touch").Output(d.updateCurrentApiTimestamp).
752 Text(") || (").
753 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
754 Text("; exit 38").
755 Text(")")
756
757 rule.Build("metalavaCurrentApiUpdate", "update current API")
758 }
759
760 if String(d.properties.Check_nullability_warnings) != "" {
761 if d.nullabilityWarningsFile == nil {
762 ctx.PropertyErrorf("check_nullability_warnings",
763 "Cannot specify check_nullability_warnings unless validating nullability")
764 }
765
766 checkNullabilityWarnings := android.PathForModuleSrc(ctx, String(d.properties.Check_nullability_warnings))
767
Colin Crosscb77f752021-03-24 12:04:44 -0700768 d.checkNullabilityWarningsTimestamp = android.PathForModuleOut(ctx, "metalava", "check_nullability_warnings.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700769
770 msg := fmt.Sprintf(`\n******************************\n`+
771 `The warnings encountered during nullability annotation validation did\n`+
772 `not match the checked in file of expected warnings. The diffs are shown\n`+
773 `above. You have two options:\n`+
774 ` 1. Resolve the differences by editing the nullability annotations.\n`+
775 ` 2. Update the file of expected warnings by running:\n`+
776 ` cp %s %s\n`+
777 ` and submitting the updated file as part of your change.`,
778 d.nullabilityWarningsFile, checkNullabilityWarnings)
779
780 rule := android.NewRuleBuilder(pctx, ctx)
781
782 rule.Command().
783 Text("(").
784 Text("diff").Input(checkNullabilityWarnings).Input(d.nullabilityWarningsFile).
785 Text("&&").
786 Text("touch").Output(d.checkNullabilityWarningsTimestamp).
787 Text(") || (").
788 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
789 Text("; exit 38").
790 Text(")")
791
792 rule.Build("nullabilityWarningsCheck", "nullability warnings check")
793 }
794}
795
796func StubsDefaultsFactory() android.Module {
797 module := &DocDefaults{}
798
799 module.AddProperties(
800 &JavadocProperties{},
801 &DroidstubsProperties{},
802 )
803
804 android.InitDefaultsModule(module)
805
806 return module
807}
808
809var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
810
811type PrebuiltStubsSourcesProperties struct {
812 Srcs []string `android:"path"`
813}
814
815type PrebuiltStubsSources struct {
816 android.ModuleBase
817 android.DefaultableModuleBase
818 prebuilt android.Prebuilt
819 android.SdkBase
820
821 properties PrebuiltStubsSourcesProperties
822
kgui67007242022-01-25 13:50:25 +0800823 stubsSrcJar android.Path
Colin Cross2207f872021-03-24 12:39:08 -0700824}
825
826func (p *PrebuiltStubsSources) OutputFiles(tag string) (android.Paths, error) {
827 switch tag {
828 case "":
829 return android.Paths{p.stubsSrcJar}, nil
830 default:
831 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
832 }
833}
834
835func (d *PrebuiltStubsSources) StubsSrcJar() android.Path {
836 return d.stubsSrcJar
837}
838
839func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross2207f872021-03-24 12:39:08 -0700840 if len(p.properties.Srcs) != 1 {
Anton Hansson86758ac2021-11-03 14:44:12 +0000841 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 -0700842 return
843 }
844
Anton Hansson86758ac2021-11-03 14:44:12 +0000845 src := p.properties.Srcs[0]
846 if filepath.Ext(src) == ".srcjar" {
847 // This is a srcjar. We can use it directly.
848 p.stubsSrcJar = android.PathForModuleSrc(ctx, src)
849 } else {
850 outPath := android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
Colin Cross2207f872021-03-24 12:39:08 -0700851
Anton Hansson86758ac2021-11-03 14:44:12 +0000852 // This is a directory. Glob the contents just in case the directory does not exist.
853 srcGlob := src + "/**/*"
854 srcPaths := android.PathsForModuleSrc(ctx, []string{srcGlob})
Colin Cross2207f872021-03-24 12:39:08 -0700855
Anton Hansson86758ac2021-11-03 14:44:12 +0000856 // Although PathForModuleSrc can return nil if either the path doesn't exist or
857 // the path components are invalid it won't in this case because no components
858 // are specified and the module directory must exist in order to get this far.
859 srcDir := android.PathForModuleSrc(ctx).(android.SourcePath).Join(ctx, src)
Colin Cross2207f872021-03-24 12:39:08 -0700860
Anton Hansson86758ac2021-11-03 14:44:12 +0000861 rule := android.NewRuleBuilder(pctx, ctx)
862 rule.Command().
863 BuiltTool("soong_zip").
864 Flag("-write_if_changed").
865 Flag("-jar").
866 FlagWithOutput("-o ", outPath).
867 FlagWithArg("-C ", srcDir.String()).
868 FlagWithRspFileInputList("-r ", outPath.ReplaceExtension(ctx, "rsp"), srcPaths)
869 rule.Restat()
870 rule.Build("zip src", "Create srcjar from prebuilt source")
871 p.stubsSrcJar = outPath
872 }
Colin Cross2207f872021-03-24 12:39:08 -0700873}
874
875func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
876 return &p.prebuilt
877}
878
879func (p *PrebuiltStubsSources) Name() string {
880 return p.prebuilt.Name(p.ModuleBase.Name())
881}
882
883// prebuilt_stubs_sources imports a set of java source files as if they were
884// generated by droidstubs.
885//
886// By default, a prebuilt_stubs_sources has a single variant that expects a
887// set of `.java` files generated by droidstubs.
888//
889// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
890// for host modules.
891//
892// Intended only for use by sdk snapshots.
893func PrebuiltStubsSourcesFactory() android.Module {
894 module := &PrebuiltStubsSources{}
895
896 module.AddProperties(&module.properties)
897
898 android.InitPrebuiltModule(module, &module.properties.Srcs)
899 android.InitSdkAwareModule(module)
900 InitDroiddocModule(module, android.HostAndDeviceSupported)
901 return module
902}