blob: 12590ca509ae641c0a1ef37a7d2782fe2c276fb3 [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
Colin Cross2207f872021-03-24 12:39:08 -070045// Droidstubs
Colin Cross2207f872021-03-24 12:39:08 -070046type Droidstubs struct {
47 Javadoc
48 android.SdkBase
49
50 properties DroidstubsProperties
Paul Duffinc71d2b72022-08-16 15:24:01 +000051 apiFile android.Path
52 removedApiFile android.Path
Colin Cross2207f872021-03-24 12:39:08 -070053 nullabilityWarningsFile android.WritablePath
54
55 checkCurrentApiTimestamp android.WritablePath
56 updateCurrentApiTimestamp android.WritablePath
57 checkLastReleasedApiTimestamp android.WritablePath
58 apiLintTimestamp android.WritablePath
59 apiLintReport android.WritablePath
60
61 checkNullabilityWarningsTimestamp android.WritablePath
62
63 annotationsZip android.WritablePath
64 apiVersionsXml android.WritablePath
65
Colin Cross2207f872021-03-24 12:39:08 -070066 metadataZip android.WritablePath
67 metadataDir android.WritablePath
68}
69
70type DroidstubsProperties struct {
71 // The generated public API filename by Metalava, defaults to <module>_api.txt
72 Api_filename *string
73
74 // the generated removed API filename by Metalava, defaults to <module>_removed.txt
75 Removed_api_filename *string
76
Colin Cross2207f872021-03-24 12:39:08 -070077 Check_api struct {
78 Last_released ApiToCheck
79
80 Current ApiToCheck
81
82 Api_lint struct {
83 Enabled *bool
84
85 // If set, performs api_lint on any new APIs not found in the given signature file
86 New_since *string `android:"path"`
87
88 // If not blank, path to the baseline txt file for approved API lint violations.
89 Baseline_file *string `android:"path"`
90 }
91 }
92
93 // user can specify the version of previous released API file in order to do compatibility check.
94 Previous_api *string `android:"path"`
95
96 // is set to true, Metalava will allow framework SDK to contain annotations.
97 Annotations_enabled *bool
98
99 // a list of top-level directories containing files to merge qualifier annotations (i.e. those intended to be included in the stubs written) from.
100 Merge_annotations_dirs []string
101
102 // a list of top-level directories containing Java stub files to merge show/hide annotations from.
103 Merge_inclusion_annotations_dirs []string
104
105 // a file containing a list of classes to do nullability validation for.
106 Validate_nullability_from_list *string
107
108 // a file containing expected warnings produced by validation of nullability annotations.
109 Check_nullability_warnings *string
110
111 // if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
112 Create_doc_stubs *bool
113
114 // if set to true, cause Metalava to output Javadoc comments in the stubs source files. Defaults to false.
115 // Has no effect if create_doc_stubs: true.
116 Output_javadoc_comments *bool
117
118 // if set to false then do not write out stubs. Defaults to true.
119 //
120 // TODO(b/146727827): Remove capability when we do not need to generate stubs and API separately.
121 Generate_stubs *bool
122
123 // if set to true, provides a hint to the build system that this rule uses a lot of memory,
124 // whicih can be used for scheduling purposes
125 High_mem *bool
126
satayev783195c2021-06-23 21:49:57 +0100127 // if set to true, Metalava will allow framework SDK to contain API levels annotations.
Colin Cross2207f872021-03-24 12:39:08 -0700128 Api_levels_annotations_enabled *bool
129
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000130 // Apply the api levels database created by this module rather than generating one in this droidstubs.
131 Api_levels_module *string
132
Colin Cross2207f872021-03-24 12:39:08 -0700133 // the dirs which Metalava extracts API levels annotations from.
134 Api_levels_annotations_dirs []string
135
Pedro Loureirocc203502021-10-04 17:24:00 +0000136 // 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 +0100137 Api_levels_sdk_type *string
138
Colin Cross2207f872021-03-24 12:39:08 -0700139 // the filename which Metalava extracts API levels annotations from. Defaults to android.jar.
140 Api_levels_jar_filename *string
141
142 // if set to true, collect the values used by the Dev tools and
143 // write them in files packaged with the SDK. Defaults to false.
144 Write_sdk_values *bool
145}
146
Anton Hansson52609322021-05-05 10:36:05 +0100147// Used by xsd_config
148type ApiFilePath interface {
149 ApiFilePath() android.Path
150}
151
152type ApiStubsSrcProvider interface {
153 StubsSrcJar() android.Path
154}
155
156// Provider of information about API stubs, used by java_sdk_library.
157type ApiStubsProvider interface {
Anton Hanssond78eb762021-09-21 15:25:12 +0100158 AnnotationsZip() android.Path
Anton Hansson52609322021-05-05 10:36:05 +0100159 ApiFilePath
160 RemovedApiFilePath() android.Path
161
162 ApiStubsSrcProvider
163}
164
Colin Cross2207f872021-03-24 12:39:08 -0700165// droidstubs passes sources files through Metalava to generate stub .java files that only contain the API to be
166// documented, filtering out hidden classes and methods. The resulting .java files are intended to be passed to
167// a droiddoc module to generate documentation.
168func DroidstubsFactory() android.Module {
169 module := &Droidstubs{}
170
171 module.AddProperties(&module.properties,
172 &module.Javadoc.properties)
173
174 InitDroiddocModule(module, android.HostAndDeviceSupported)
175 android.InitSdkAwareModule(module)
176 return module
177}
178
179// droidstubs_host passes sources files through Metalava to generate stub .java files that only contain the API
180// to be documented, filtering out hidden classes and methods. The resulting .java files are intended to be
181// passed to a droiddoc_host module to generate documentation. Use a droidstubs_host instead of a droidstubs
182// module when symbols needed by the source files are provided by java_library_host modules.
183func DroidstubsHostFactory() android.Module {
184 module := &Droidstubs{}
185
186 module.AddProperties(&module.properties,
187 &module.Javadoc.properties)
188
189 InitDroiddocModule(module, android.HostSupported)
190 return module
191}
192
193func (d *Droidstubs) OutputFiles(tag string) (android.Paths, error) {
194 switch tag {
195 case "":
196 return android.Paths{d.stubsSrcJar}, nil
197 case ".docs.zip":
198 return android.Paths{d.docZip}, nil
199 case ".api.txt", android.DefaultDistTag:
200 // This is the default dist path for dist properties that have no tag property.
Paul Duffinc71d2b72022-08-16 15:24:01 +0000201 return android.Paths{d.apiFile}, nil
Colin Cross2207f872021-03-24 12:39:08 -0700202 case ".removed-api.txt":
Paul Duffinc71d2b72022-08-16 15:24:01 +0000203 return android.Paths{d.removedApiFile}, nil
Colin Cross2207f872021-03-24 12:39:08 -0700204 case ".annotations.zip":
205 return android.Paths{d.annotationsZip}, nil
206 case ".api_versions.xml":
207 return android.Paths{d.apiVersionsXml}, nil
208 default:
209 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
210 }
211}
212
Anton Hanssond78eb762021-09-21 15:25:12 +0100213func (d *Droidstubs) AnnotationsZip() android.Path {
214 return d.annotationsZip
215}
216
Colin Cross2207f872021-03-24 12:39:08 -0700217func (d *Droidstubs) ApiFilePath() android.Path {
Paul Duffinc71d2b72022-08-16 15:24:01 +0000218 return d.apiFile
Colin Cross2207f872021-03-24 12:39:08 -0700219}
220
221func (d *Droidstubs) RemovedApiFilePath() android.Path {
Paul Duffinc71d2b72022-08-16 15:24:01 +0000222 return d.removedApiFile
Colin Cross2207f872021-03-24 12:39:08 -0700223}
224
225func (d *Droidstubs) StubsSrcJar() android.Path {
226 return d.stubsSrcJar
227}
228
229var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
230var metalavaMergeInclusionAnnotationsDirTag = dependencyTag{name: "metalava-merge-inclusion-annotations-dir"}
231var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000232var metalavaAPILevelsModuleTag = dependencyTag{name: "metalava-api-levels-module-tag"}
Colin Cross2207f872021-03-24 12:39:08 -0700233
234func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
235 d.Javadoc.addDeps(ctx)
236
237 if len(d.properties.Merge_annotations_dirs) != 0 {
238 for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
239 ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
240 }
241 }
242
243 if len(d.properties.Merge_inclusion_annotations_dirs) != 0 {
244 for _, mergeInclusionAnnotationsDir := range d.properties.Merge_inclusion_annotations_dirs {
245 ctx.AddDependency(ctx.Module(), metalavaMergeInclusionAnnotationsDirTag, mergeInclusionAnnotationsDir)
246 }
247 }
248
249 if len(d.properties.Api_levels_annotations_dirs) != 0 {
250 for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
251 ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
252 }
253 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000254
255 if d.properties.Api_levels_module != nil {
256 ctx.AddDependency(ctx.Module(), metalavaAPILevelsModuleTag, proptools.String(d.properties.Api_levels_module))
257 }
Colin Cross2207f872021-03-24 12:39:08 -0700258}
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")
Paul Duffinc71d2b72022-08-16 15:24:01 +0000265 uncheckedApiFile := android.PathForModuleOut(ctx, "metalava", filename)
266 cmd.FlagWithOutput("--api ", uncheckedApiFile)
267 d.apiFile = uncheckedApiFile
Colin Cross2207f872021-03-24 12:39:08 -0700268 } 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.
Paul Duffinc71d2b72022-08-16 15:24:01 +0000270 d.apiFile = android.PathForModuleSrc(ctx, sourceApiFile)
Colin Cross2207f872021-03-24 12:39:08 -0700271 }
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")
Paul Duffinc71d2b72022-08-16 15:24:01 +0000277 uncheckedRemovedFile := android.PathForModuleOut(ctx, "metalava", filename)
278 cmd.FlagWithOutput("--removed-api ", uncheckedRemovedFile)
279 d.removedApiFile = uncheckedRemovedFile
Colin Cross2207f872021-03-24 12:39:08 -0700280 } 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.
Paul Duffinc71d2b72022-08-16 15:24:01 +0000282 d.removedApiFile = android.PathForModuleSrc(ctx, sourceRemovedApiFile)
Colin Cross2207f872021-03-24 12:39:08 -0700283 }
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) {
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000368 var apiVersions android.Path
369 if proptools.Bool(d.properties.Api_levels_annotations_enabled) {
370 d.apiLevelsGenerationFlags(ctx, cmd)
371 apiVersions = d.apiVersionsXml
372 } else {
373 ctx.VisitDirectDepsWithTag(metalavaAPILevelsModuleTag, func(m android.Module) {
374 if s, ok := m.(*Droidstubs); ok {
375 apiVersions = s.apiVersionsXml
376 } else {
377 ctx.PropertyErrorf("api_levels_module",
378 "module %q is not a droidstubs module", ctx.OtherModuleName(m))
379 }
380 })
Colin Cross2207f872021-03-24 12:39:08 -0700381 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000382 if apiVersions != nil {
383 cmd.FlagWithArg("--current-version ", ctx.Config().PlatformSdkVersion().String())
384 cmd.FlagWithArg("--current-codename ", ctx.Config().PlatformSdkCodename())
385 cmd.FlagWithInput("--apply-api-levels ", apiVersions)
386 }
387}
Colin Cross2207f872021-03-24 12:39:08 -0700388
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000389func (d *Droidstubs) apiLevelsGenerationFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
Colin Cross2207f872021-03-24 12:39:08 -0700390 if len(d.properties.Api_levels_annotations_dirs) == 0 {
391 ctx.PropertyErrorf("api_levels_annotations_dirs",
392 "has to be non-empty if api levels annotations was enabled!")
393 }
394
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000395 d.apiVersionsXml = android.PathForModuleOut(ctx, "metalava", "api-versions.xml")
Colin Cross2207f872021-03-24 12:39:08 -0700396 cmd.FlagWithOutput("--generate-api-levels ", d.apiVersionsXml)
Colin Cross2207f872021-03-24 12:39:08 -0700397
398 filename := proptools.StringDefault(d.properties.Api_levels_jar_filename, "android.jar")
399
satayev783195c2021-06-23 21:49:57 +0100400 var dirs []string
Colin Cross2207f872021-03-24 12:39:08 -0700401 ctx.VisitDirectDepsWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.Module) {
402 if t, ok := m.(*ExportedDroiddocDir); ok {
403 for _, dep := range t.deps {
Colin Cross5f6ffc72021-03-29 21:54:45 -0700404 if dep.Base() == filename {
405 cmd.Implicit(dep)
406 }
407 if filename != "android.jar" && dep.Base() == "android.jar" {
408 // Metalava implicitly searches these patterns:
409 // prebuilts/tools/common/api-versions/android-%/android.jar
410 // prebuilts/sdk/%/public/android.jar
411 // Add android.jar files from the api_levels_annotations_dirs directories to try
412 // to satisfy these patterns. If Metalava can't find a match for an API level
413 // between 1 and 28 in at least one pattern it will fail.
Colin Cross2207f872021-03-24 12:39:08 -0700414 cmd.Implicit(dep)
415 }
416 }
satayev783195c2021-06-23 21:49:57 +0100417
418 dirs = append(dirs, t.dir.String())
Colin Cross2207f872021-03-24 12:39:08 -0700419 } else {
420 ctx.PropertyErrorf("api_levels_annotations_dirs",
421 "module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
422 }
423 })
satayev783195c2021-06-23 21:49:57 +0100424
425 // Add all relevant --android-jar-pattern patterns for Metalava.
426 // When parsing a stub jar for a specific version, Metalava picks the first pattern that defines
427 // an actual file present on disk (in the order the patterns were passed). For system APIs for
428 // privileged apps that are only defined since API level 21 (Lollipop), fallback to public stubs
Pedro Loureirocc203502021-10-04 17:24:00 +0000429 // for older releases. Similarly, module-lib falls back to system API.
430 var sdkDirs []string
431 switch proptools.StringDefault(d.properties.Api_levels_sdk_type, "public") {
432 case "module-lib":
433 sdkDirs = []string{"module-lib", "system", "public"}
434 case "system":
435 sdkDirs = []string{"system", "public"}
436 case "public":
437 sdkDirs = []string{"public"}
438 default:
439 ctx.PropertyErrorf("api_levels_sdk_type", "needs to be one of %v", allowedApiLevelSdkTypes)
440 return
satayev783195c2021-06-23 21:49:57 +0100441 }
Pedro Loureirocc203502021-10-04 17:24:00 +0000442
443 for _, sdkDir := range sdkDirs {
444 for _, dir := range dirs {
445 cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/%%/%s/%s", dir, sdkDir, filename))
446 }
satayev783195c2021-06-23 21:49:57 +0100447 }
Colin Cross2207f872021-03-24 12:39:08 -0700448}
449
Colin Crosse52c2ac2022-03-28 17:03:35 -0700450func metalavaUseRbe(ctx android.ModuleContext) bool {
451 return ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_METALAVA")
452}
453
Colin Cross2207f872021-03-24 12:39:08 -0700454func metalavaCmd(ctx android.ModuleContext, rule *android.RuleBuilder, javaVersion javaVersion, srcs android.Paths,
Anton Hansson556e8142021-06-04 16:20:25 +0100455 srcJarList android.Path, bootclasspath, classpath classpath, homeDir android.WritablePath) *android.RuleBuilderCommand {
Colin Cross2207f872021-03-24 12:39:08 -0700456 rule.Command().Text("rm -rf").Flag(homeDir.String())
457 rule.Command().Text("mkdir -p").Flag(homeDir.String())
458
Anton Hansson556e8142021-06-04 16:20:25 +0100459 cmd := rule.Command()
Colin Cross2207f872021-03-24 12:39:08 -0700460 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
461
Colin Crosse52c2ac2022-03-28 17:03:35 -0700462 if metalavaUseRbe(ctx) {
Colin Cross2207f872021-03-24 12:39:08 -0700463 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
Colin Cross8095c292021-03-30 16:40:48 -0700464 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
465 labels := map[string]string{"type": "tool", "name": "metalava"}
466 // TODO: metalava pool rejects these jobs
467 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
468 rule.Rewrapper(&remoteexec.REParams{
469 Labels: labels,
470 ExecStrategy: execStrategy,
471 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
472 Platform: map[string]string{remoteexec.PoolKey: pool},
473 })
Colin Cross2207f872021-03-24 12:39:08 -0700474 }
475
Colin Cross6aa5c402021-03-24 12:28:50 -0700476 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
Colin Cross2207f872021-03-24 12:39:08 -0700477 Flag(config.JavacVmFlags).
478 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
479 FlagWithArg("-encoding ", "UTF-8").
480 FlagWithArg("-source ", javaVersion.String()).
481 FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, "metalava.rsp"), srcs).
482 FlagWithInput("@", srcJarList)
483
Colin Cross2207f872021-03-24 12:39:08 -0700484 if len(bootclasspath) > 0 {
485 cmd.FlagWithInputList("-bootclasspath ", bootclasspath.Paths(), ":")
486 }
487
488 if len(classpath) > 0 {
489 cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
490 }
491
Colin Cross2207f872021-03-24 12:39:08 -0700492 cmd.Flag("--no-banner").
493 Flag("--color").
494 Flag("--quiet").
495 Flag("--format=v2").
496 FlagWithArg("--repeat-errors-max ", "10").
Sam Gilbert09cb5db2021-10-06 11:28:28 -0400497 FlagWithArg("--hide ", "UnresolvedImport").
Ember Rose7c57af32022-04-01 10:34:44 -0400498 FlagWithArg("--hide ", "InvalidNullabilityOverride").
Sam Gilbert28e41282022-03-09 15:24:48 +0000499 // b/223382732
500 FlagWithArg("--hide ", "ChangedDefault")
Colin Cross2207f872021-03-24 12:39:08 -0700501
502 return cmd
503}
504
505func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
506 deps := d.Javadoc.collectDeps(ctx)
507
Jiyong Parkf1691d22021-03-29 20:11:58 +0900508 javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), android.SdkContext(d))
Colin Cross2207f872021-03-24 12:39:08 -0700509
510 // Create rule for metalava
511
Colin Crosscb77f752021-03-24 12:04:44 -0700512 srcJarDir := android.PathForModuleOut(ctx, "metalava", "srcjars")
Colin Cross2207f872021-03-24 12:39:08 -0700513
514 rule := android.NewRuleBuilder(pctx, ctx)
515
Colin Cross8095c292021-03-30 16:40:48 -0700516 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
517 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
518 SandboxInputs()
Colin Cross6aa5c402021-03-24 12:28:50 -0700519
Colin Cross2207f872021-03-24 12:39:08 -0700520 if BoolDefault(d.properties.High_mem, false) {
521 // This metalava run uses lots of memory, restrict the number of metalava jobs that can run in parallel.
522 rule.HighMem()
523 }
524
525 generateStubs := BoolDefault(d.properties.Generate_stubs, true)
526 var stubsDir android.OptionalPath
527 if generateStubs {
Colin Crosscb77f752021-03-24 12:04:44 -0700528 d.Javadoc.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
529 stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Colin Cross2207f872021-03-24 12:39:08 -0700530 rule.Command().Text("rm -rf").Text(stubsDir.String())
531 rule.Command().Text("mkdir -p").Text(stubsDir.String())
532 }
533
534 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, d.Javadoc.srcJars)
535
Colin Crosscb77f752021-03-24 12:04:44 -0700536 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
Colin Cross2207f872021-03-24 12:39:08 -0700537 cmd := metalavaCmd(ctx, rule, javaVersion, d.Javadoc.srcFiles, srcJarList,
Anton Hansson556e8142021-06-04 16:20:25 +0100538 deps.bootClasspath, deps.classpath, homeDir)
Colin Cross2207f872021-03-24 12:39:08 -0700539 cmd.Implicits(d.Javadoc.implicits)
540
541 d.stubsFlags(ctx, cmd, stubsDir)
542
543 d.annotationsFlags(ctx, cmd)
544 d.inclusionAnnotationsFlags(ctx, cmd)
545 d.apiLevelsAnnotationsFlags(ctx, cmd)
546
Colin Crossbc139922021-03-25 18:33:16 -0700547 d.expandArgs(ctx, cmd)
Colin Cross2207f872021-03-24 12:39:08 -0700548
Colin Cross2207f872021-03-24 12:39:08 -0700549 for _, o := range d.Javadoc.properties.Out {
550 cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
551 }
552
553 // Add options for the other optional tasks: API-lint and check-released.
554 // We generate separate timestamp files for them.
555
556 doApiLint := false
557 doCheckReleased := false
558
559 // Add API lint options.
560
561 if BoolDefault(d.properties.Check_api.Api_lint.Enabled, false) {
562 doApiLint = true
563
564 newSince := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.New_since)
565 if newSince.Valid() {
566 cmd.FlagWithInput("--api-lint ", newSince.Path())
567 } else {
568 cmd.Flag("--api-lint")
569 }
Colin Crosscb77f752021-03-24 12:04:44 -0700570 d.apiLintReport = android.PathForModuleOut(ctx, "metalava", "api_lint_report.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700571 cmd.FlagWithOutput("--report-even-if-suppressed ", d.apiLintReport) // TODO: Change to ":api-lint"
572
Colin Cross0d532412021-03-25 09:38:45 -0700573 // TODO(b/154317059): Clean up this allowlist by baselining and/or checking in last-released.
Colin Cross2207f872021-03-24 12:39:08 -0700574 if d.Name() != "android.car-system-stubs-docs" &&
575 d.Name() != "android.car-stubs-docs" {
576 cmd.Flag("--lints-as-errors")
577 cmd.Flag("--warnings-as-errors") // Most lints are actually warnings.
578 }
579
580 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700581 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "api_lint_baseline.txt")
582 d.apiLintTimestamp = android.PathForModuleOut(ctx, "metalava", "api_lint.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700583
584 // Note this string includes a special shell quote $' ... ', which decodes the "\n"s.
Colin Cross2207f872021-03-24 12:39:08 -0700585 //
586 // TODO: metalava also has a slightly different message hardcoded. Should we unify this
587 // message and metalava's one?
588 msg := `$'` + // Enclose with $' ... '
589 `************************************************************\n` +
590 `Your API changes are triggering API Lint warnings or errors.\n` +
591 `To make these errors go away, fix the code according to the\n` +
592 `error and/or warning messages above.\n` +
593 `\n` +
594 `If it is not possible to do so, there are workarounds:\n` +
595 `\n` +
Aurimas Liutikasb23b7452021-05-24 18:00:37 +0000596 `1. You can suppress the errors with @SuppressLint("<id>")\n` +
597 ` where the <id> is given in brackets in the error message above.\n`
Colin Cross2207f872021-03-24 12:39:08 -0700598
599 if baselineFile.Valid() {
600 cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
601 cmd.FlagWithOutput("--update-baseline:api-lint ", updatedBaselineOutput)
602
603 msg += fmt.Sprintf(``+
604 `2. You can update the baseline by executing the following\n`+
605 ` command:\n`+
Colin Cross63eeda02021-04-15 19:01:57 -0700606 ` (cd $ANDROID_BUILD_TOP && cp \\\n`+
607 ` "%s" \\\n`+
608 ` "%s")\n`+
Colin Cross2207f872021-03-24 12:39:08 -0700609 ` To submit the revised baseline.txt to the main Android\n`+
610 ` repository, you will need approval.\n`, updatedBaselineOutput, baselineFile.Path())
611 } else {
612 msg += fmt.Sprintf(``+
613 `2. You can add a baseline file of existing lint failures\n`+
614 ` to the build rule of %s.\n`, d.Name())
615 }
616 // Note the message ends with a ' (single quote), to close the $' ... ' .
617 msg += `************************************************************\n'`
618
619 cmd.FlagWithArg("--error-message:api-lint ", msg)
620 }
621
622 // Add "check released" options. (Detect incompatible API changes from the last public release)
623
624 if apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") {
625 doCheckReleased = true
626
627 if len(d.Javadoc.properties.Out) > 0 {
628 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
629 }
630
631 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Api_file))
632 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Removed_api_file))
633 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
Colin Crosscb77f752021-03-24 12:04:44 -0700634 updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "last_released_baseline.txt")
Colin Cross2207f872021-03-24 12:39:08 -0700635
Colin Crosscb77f752021-03-24 12:04:44 -0700636 d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_last_released_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700637
638 cmd.FlagWithInput("--check-compatibility:api:released ", apiFile)
639 cmd.FlagWithInput("--check-compatibility:removed:released ", removedApiFile)
640
641 if baselineFile.Valid() {
642 cmd.FlagWithInput("--baseline:compatibility:released ", baselineFile.Path())
643 cmd.FlagWithOutput("--update-baseline:compatibility:released ", updatedBaselineOutput)
644 }
645
646 // Note this string includes quote ($' ... '), which decodes the "\n"s.
647 msg := `$'\n******************************\n` +
648 `You have tried to change the API from what has been previously released in\n` +
649 `an SDK. Please fix the errors listed above.\n` +
650 `******************************\n'`
651
652 cmd.FlagWithArg("--error-message:compatibility:released ", msg)
653 }
654
Colin Cross2207f872021-03-24 12:39:08 -0700655 if generateStubs {
656 rule.Command().
657 BuiltTool("soong_zip").
658 Flag("-write_if_changed").
659 Flag("-jar").
660 FlagWithOutput("-o ", d.Javadoc.stubsSrcJar).
661 FlagWithArg("-C ", stubsDir.String()).
662 FlagWithArg("-D ", stubsDir.String())
663 }
664
665 if Bool(d.properties.Write_sdk_values) {
Colin Crosscb77f752021-03-24 12:04:44 -0700666 d.metadataZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-metadata.zip")
Colin Cross2207f872021-03-24 12:39:08 -0700667 rule.Command().
668 BuiltTool("soong_zip").
669 Flag("-write_if_changed").
670 Flag("-d").
671 FlagWithOutput("-o ", d.metadataZip).
672 FlagWithArg("-C ", d.metadataDir.String()).
673 FlagWithArg("-D ", d.metadataDir.String())
674 }
675
676 // TODO: We don't really need two separate API files, but this is a reminiscence of how
677 // we used to run metalava separately for API lint and the "last_released" check. Unify them.
678 if doApiLint {
679 rule.Command().Text("touch").Output(d.apiLintTimestamp)
680 }
681 if doCheckReleased {
682 rule.Command().Text("touch").Output(d.checkLastReleasedApiTimestamp)
683 }
684
Colin Cross6aa5c402021-03-24 12:28:50 -0700685 // TODO(b/183630617): rewrapper doesn't support restat rules
Colin Crosse52c2ac2022-03-28 17:03:35 -0700686 if !metalavaUseRbe(ctx) {
687 rule.Restat()
688 }
Colin Cross2207f872021-03-24 12:39:08 -0700689
690 zipSyncCleanupCmd(rule, srcJarDir)
691
Paul Duffinc166b682022-05-27 12:23:08 +0000692 rule.Build("metalava", "metalava merged")
693
Paul Duffine7a86642022-08-16 15:43:20 +0000694 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
695
696 if len(d.Javadoc.properties.Out) > 0 {
697 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
698 }
699
700 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
701 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Removed_api_file))
702 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Current.Baseline_file)
703
704 if baselineFile.Valid() {
705 ctx.PropertyErrorf("baseline_file", "current API check can't have a baseline file. (module %s)", ctx.ModuleName())
706 }
707
708 d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_current_api.timestamp")
709
710 rule := android.NewRuleBuilder(pctx, ctx)
711
712 // Diff command line.
713 // -F matches the closest "opening" line, such as "package android {"
714 // and " public class Intent {".
715 diff := `diff -u -F '{ *$'`
716
717 rule.Command().Text("( true")
718 rule.Command().
719 Text(diff).
720 Input(apiFile).Input(d.apiFile)
721
722 rule.Command().
723 Text(diff).
724 Input(removedApiFile).Input(d.removedApiFile)
725
726 msg := fmt.Sprintf(`\n******************************\n`+
727 `You have tried to change the API from what has been previously approved.\n\n`+
728 `To make these errors go away, you have two choices:\n`+
729 ` 1. You can add '@hide' javadoc comments (and remove @SystemApi/@TestApi/etc)\n`+
730 ` to the new methods, etc. shown in the above diff.\n\n`+
731 ` 2. You can update current.txt and/or removed.txt by executing the following command:\n`+
732 ` m %s-update-current-api\n\n`+
733 ` To submit the revised current.txt to the main Android repository,\n`+
734 ` you will need approval.\n`+
735 `******************************\n`, ctx.ModuleName())
736
737 rule.Command().
738 Text("touch").Output(d.checkCurrentApiTimestamp).
739 Text(") || (").
740 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
741 Text("; exit 38").
742 Text(")")
743
744 rule.Build("metalavaCurrentApiCheck", "check current API")
745
746 d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "update_current_api.timestamp")
747
748 // update API rule
749 rule = android.NewRuleBuilder(pctx, ctx)
750
751 rule.Command().Text("( true")
752
753 rule.Command().
754 Text("cp").Flag("-f").
755 Input(d.apiFile).Flag(apiFile.String())
756
757 rule.Command().
758 Text("cp").Flag("-f").
759 Input(d.removedApiFile).Flag(removedApiFile.String())
760
761 msg = "failed to update public API"
762
763 rule.Command().
764 Text("touch").Output(d.updateCurrentApiTimestamp).
765 Text(") || (").
766 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
767 Text("; exit 38").
768 Text(")")
769
770 rule.Build("metalavaCurrentApiUpdate", "update current API")
771 }
772
Colin Cross2207f872021-03-24 12:39:08 -0700773 if String(d.properties.Check_nullability_warnings) != "" {
774 if d.nullabilityWarningsFile == nil {
775 ctx.PropertyErrorf("check_nullability_warnings",
776 "Cannot specify check_nullability_warnings unless validating nullability")
777 }
778
779 checkNullabilityWarnings := android.PathForModuleSrc(ctx, String(d.properties.Check_nullability_warnings))
780
Colin Crosscb77f752021-03-24 12:04:44 -0700781 d.checkNullabilityWarningsTimestamp = android.PathForModuleOut(ctx, "metalava", "check_nullability_warnings.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -0700782
783 msg := fmt.Sprintf(`\n******************************\n`+
784 `The warnings encountered during nullability annotation validation did\n`+
785 `not match the checked in file of expected warnings. The diffs are shown\n`+
786 `above. You have two options:\n`+
787 ` 1. Resolve the differences by editing the nullability annotations.\n`+
788 ` 2. Update the file of expected warnings by running:\n`+
789 ` cp %s %s\n`+
790 ` and submitting the updated file as part of your change.`,
791 d.nullabilityWarningsFile, checkNullabilityWarnings)
792
793 rule := android.NewRuleBuilder(pctx, ctx)
794
795 rule.Command().
796 Text("(").
797 Text("diff").Input(checkNullabilityWarnings).Input(d.nullabilityWarningsFile).
798 Text("&&").
799 Text("touch").Output(d.checkNullabilityWarningsTimestamp).
800 Text(") || (").
801 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
802 Text("; exit 38").
803 Text(")")
804
805 rule.Build("nullabilityWarningsCheck", "nullability warnings check")
806 }
807}
808
809func StubsDefaultsFactory() android.Module {
810 module := &DocDefaults{}
811
812 module.AddProperties(
813 &JavadocProperties{},
814 &DroidstubsProperties{},
815 )
816
817 android.InitDefaultsModule(module)
818
819 return module
820}
821
822var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
823
824type PrebuiltStubsSourcesProperties struct {
825 Srcs []string `android:"path"`
826}
827
828type PrebuiltStubsSources struct {
829 android.ModuleBase
830 android.DefaultableModuleBase
831 prebuilt android.Prebuilt
832 android.SdkBase
833
834 properties PrebuiltStubsSourcesProperties
835
kgui67007242022-01-25 13:50:25 +0800836 stubsSrcJar android.Path
Colin Cross2207f872021-03-24 12:39:08 -0700837}
838
839func (p *PrebuiltStubsSources) OutputFiles(tag string) (android.Paths, error) {
840 switch tag {
841 case "":
842 return android.Paths{p.stubsSrcJar}, nil
843 default:
844 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
845 }
846}
847
848func (d *PrebuiltStubsSources) StubsSrcJar() android.Path {
849 return d.stubsSrcJar
850}
851
852func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross2207f872021-03-24 12:39:08 -0700853 if len(p.properties.Srcs) != 1 {
Anton Hansson86758ac2021-11-03 14:44:12 +0000854 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 -0700855 return
856 }
857
Anton Hansson86758ac2021-11-03 14:44:12 +0000858 src := p.properties.Srcs[0]
859 if filepath.Ext(src) == ".srcjar" {
860 // This is a srcjar. We can use it directly.
861 p.stubsSrcJar = android.PathForModuleSrc(ctx, src)
862 } else {
863 outPath := android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
Colin Cross2207f872021-03-24 12:39:08 -0700864
Anton Hansson86758ac2021-11-03 14:44:12 +0000865 // This is a directory. Glob the contents just in case the directory does not exist.
866 srcGlob := src + "/**/*"
867 srcPaths := android.PathsForModuleSrc(ctx, []string{srcGlob})
Colin Cross2207f872021-03-24 12:39:08 -0700868
Anton Hansson86758ac2021-11-03 14:44:12 +0000869 // Although PathForModuleSrc can return nil if either the path doesn't exist or
870 // the path components are invalid it won't in this case because no components
871 // are specified and the module directory must exist in order to get this far.
872 srcDir := android.PathForModuleSrc(ctx).(android.SourcePath).Join(ctx, src)
Colin Cross2207f872021-03-24 12:39:08 -0700873
Anton Hansson86758ac2021-11-03 14:44:12 +0000874 rule := android.NewRuleBuilder(pctx, ctx)
875 rule.Command().
876 BuiltTool("soong_zip").
877 Flag("-write_if_changed").
878 Flag("-jar").
879 FlagWithOutput("-o ", outPath).
880 FlagWithArg("-C ", srcDir.String()).
881 FlagWithRspFileInputList("-r ", outPath.ReplaceExtension(ctx, "rsp"), srcPaths)
882 rule.Restat()
883 rule.Build("zip src", "Create srcjar from prebuilt source")
884 p.stubsSrcJar = outPath
885 }
Colin Cross2207f872021-03-24 12:39:08 -0700886}
887
888func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
889 return &p.prebuilt
890}
891
892func (p *PrebuiltStubsSources) Name() string {
893 return p.prebuilt.Name(p.ModuleBase.Name())
894}
895
896// prebuilt_stubs_sources imports a set of java source files as if they were
897// generated by droidstubs.
898//
899// By default, a prebuilt_stubs_sources has a single variant that expects a
900// set of `.java` files generated by droidstubs.
901//
902// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
903// for host modules.
904//
905// Intended only for use by sdk snapshots.
906func PrebuiltStubsSourcesFactory() android.Module {
907 module := &PrebuiltStubsSources{}
908
909 module.AddProperties(&module.properties)
910
911 android.InitPrebuiltModule(module, &module.properties.Srcs)
912 android.InitSdkAwareModule(module)
913 InitDroiddocModule(module, android.HostAndDeviceSupported)
914 return module
915}