droidstubs.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. // 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. package java
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "regexp"
  19. "strings"
  20. "github.com/google/blueprint/proptools"
  21. "android/soong/android"
  22. "android/soong/java/config"
  23. "android/soong/remoteexec"
  24. )
  25. // The values allowed for Droidstubs' Api_levels_sdk_type
  26. var allowedApiLevelSdkTypes = []string{"public", "system", "module-lib", "system-server"}
  27. func init() {
  28. RegisterStubsBuildComponents(android.InitRegistrationContext)
  29. }
  30. func RegisterStubsBuildComponents(ctx android.RegistrationContext) {
  31. ctx.RegisterModuleType("stubs_defaults", StubsDefaultsFactory)
  32. ctx.RegisterModuleType("droidstubs", DroidstubsFactory)
  33. ctx.RegisterModuleType("droidstubs_host", DroidstubsHostFactory)
  34. ctx.RegisterModuleType("prebuilt_stubs_sources", PrebuiltStubsSourcesFactory)
  35. }
  36. // Droidstubs
  37. type Droidstubs struct {
  38. Javadoc
  39. properties DroidstubsProperties
  40. apiFile android.Path
  41. removedApiFile android.Path
  42. nullabilityWarningsFile android.WritablePath
  43. checkCurrentApiTimestamp android.WritablePath
  44. updateCurrentApiTimestamp android.WritablePath
  45. checkLastReleasedApiTimestamp android.WritablePath
  46. apiLintTimestamp android.WritablePath
  47. apiLintReport android.WritablePath
  48. checkNullabilityWarningsTimestamp android.WritablePath
  49. annotationsZip android.WritablePath
  50. apiVersionsXml android.WritablePath
  51. metadataZip android.WritablePath
  52. metadataDir android.WritablePath
  53. }
  54. type DroidstubsProperties struct {
  55. // The generated public API filename by Metalava, defaults to <module>_api.txt
  56. Api_filename *string
  57. // the generated removed API filename by Metalava, defaults to <module>_removed.txt
  58. Removed_api_filename *string
  59. Check_api struct {
  60. Last_released ApiToCheck
  61. Current ApiToCheck
  62. Api_lint struct {
  63. Enabled *bool
  64. // If set, performs api_lint on any new APIs not found in the given signature file
  65. New_since *string `android:"path"`
  66. // If not blank, path to the baseline txt file for approved API lint violations.
  67. Baseline_file *string `android:"path"`
  68. }
  69. }
  70. // user can specify the version of previous released API file in order to do compatibility check.
  71. Previous_api *string `android:"path"`
  72. // is set to true, Metalava will allow framework SDK to contain annotations.
  73. Annotations_enabled *bool
  74. // a list of top-level directories containing files to merge qualifier annotations (i.e. those intended to be included in the stubs written) from.
  75. Merge_annotations_dirs []string
  76. // a list of top-level directories containing Java stub files to merge show/hide annotations from.
  77. Merge_inclusion_annotations_dirs []string
  78. // a file containing a list of classes to do nullability validation for.
  79. Validate_nullability_from_list *string
  80. // a file containing expected warnings produced by validation of nullability annotations.
  81. Check_nullability_warnings *string
  82. // if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
  83. Create_doc_stubs *bool
  84. // if set to true, cause Metalava to output Javadoc comments in the stubs source files. Defaults to false.
  85. // Has no effect if create_doc_stubs: true.
  86. Output_javadoc_comments *bool
  87. // if set to false then do not write out stubs. Defaults to true.
  88. //
  89. // TODO(b/146727827): Remove capability when we do not need to generate stubs and API separately.
  90. Generate_stubs *bool
  91. // if set to true, provides a hint to the build system that this rule uses a lot of memory,
  92. // whicih can be used for scheduling purposes
  93. High_mem *bool
  94. // if set to true, Metalava will allow framework SDK to contain API levels annotations.
  95. Api_levels_annotations_enabled *bool
  96. // Apply the api levels database created by this module rather than generating one in this droidstubs.
  97. Api_levels_module *string
  98. // the dirs which Metalava extracts API levels annotations from.
  99. Api_levels_annotations_dirs []string
  100. // the sdk kind which Metalava extracts API levels annotations from. Supports 'public', 'system', 'module-lib' and 'system-server'; defaults to public.
  101. Api_levels_sdk_type *string
  102. // the filename which Metalava extracts API levels annotations from. Defaults to android.jar.
  103. Api_levels_jar_filename *string
  104. // if set to true, collect the values used by the Dev tools and
  105. // write them in files packaged with the SDK. Defaults to false.
  106. Write_sdk_values *bool
  107. // path or filegroup to file defining extension an SDK name <-> numerical ID mapping and
  108. // what APIs exist in which SDKs; passed to metalava via --sdk-extensions-info
  109. Extensions_info_file *string `android:"path"`
  110. }
  111. // Used by xsd_config
  112. type ApiFilePath interface {
  113. ApiFilePath() android.Path
  114. }
  115. type ApiStubsSrcProvider interface {
  116. StubsSrcJar() android.Path
  117. }
  118. // Provider of information about API stubs, used by java_sdk_library.
  119. type ApiStubsProvider interface {
  120. AnnotationsZip() android.Path
  121. ApiFilePath
  122. RemovedApiFilePath() android.Path
  123. ApiStubsSrcProvider
  124. }
  125. // droidstubs passes sources files through Metalava to generate stub .java files that only contain the API to be
  126. // documented, filtering out hidden classes and methods. The resulting .java files are intended to be passed to
  127. // a droiddoc module to generate documentation.
  128. func DroidstubsFactory() android.Module {
  129. module := &Droidstubs{}
  130. module.AddProperties(&module.properties,
  131. &module.Javadoc.properties)
  132. InitDroiddocModule(module, android.HostAndDeviceSupported)
  133. return module
  134. }
  135. // droidstubs_host passes sources files through Metalava to generate stub .java files that only contain the API
  136. // to be documented, filtering out hidden classes and methods. The resulting .java files are intended to be
  137. // passed to a droiddoc_host module to generate documentation. Use a droidstubs_host instead of a droidstubs
  138. // module when symbols needed by the source files are provided by java_library_host modules.
  139. func DroidstubsHostFactory() android.Module {
  140. module := &Droidstubs{}
  141. module.AddProperties(&module.properties,
  142. &module.Javadoc.properties)
  143. InitDroiddocModule(module, android.HostSupported)
  144. return module
  145. }
  146. func (d *Droidstubs) OutputFiles(tag string) (android.Paths, error) {
  147. switch tag {
  148. case "":
  149. return android.Paths{d.stubsSrcJar}, nil
  150. case ".docs.zip":
  151. return android.Paths{d.docZip}, nil
  152. case ".api.txt", android.DefaultDistTag:
  153. // This is the default dist path for dist properties that have no tag property.
  154. return android.Paths{d.apiFile}, nil
  155. case ".removed-api.txt":
  156. return android.Paths{d.removedApiFile}, nil
  157. case ".annotations.zip":
  158. return android.Paths{d.annotationsZip}, nil
  159. case ".api_versions.xml":
  160. return android.Paths{d.apiVersionsXml}, nil
  161. default:
  162. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  163. }
  164. }
  165. func (d *Droidstubs) AnnotationsZip() android.Path {
  166. return d.annotationsZip
  167. }
  168. func (d *Droidstubs) ApiFilePath() android.Path {
  169. return d.apiFile
  170. }
  171. func (d *Droidstubs) RemovedApiFilePath() android.Path {
  172. return d.removedApiFile
  173. }
  174. func (d *Droidstubs) StubsSrcJar() android.Path {
  175. return d.stubsSrcJar
  176. }
  177. var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
  178. var metalavaMergeInclusionAnnotationsDirTag = dependencyTag{name: "metalava-merge-inclusion-annotations-dir"}
  179. var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
  180. var metalavaAPILevelsModuleTag = dependencyTag{name: "metalava-api-levels-module-tag"}
  181. func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
  182. d.Javadoc.addDeps(ctx)
  183. if len(d.properties.Merge_annotations_dirs) != 0 {
  184. for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
  185. ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
  186. }
  187. }
  188. if len(d.properties.Merge_inclusion_annotations_dirs) != 0 {
  189. for _, mergeInclusionAnnotationsDir := range d.properties.Merge_inclusion_annotations_dirs {
  190. ctx.AddDependency(ctx.Module(), metalavaMergeInclusionAnnotationsDirTag, mergeInclusionAnnotationsDir)
  191. }
  192. }
  193. if len(d.properties.Api_levels_annotations_dirs) != 0 {
  194. for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
  195. ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
  196. }
  197. }
  198. if d.properties.Api_levels_module != nil {
  199. ctx.AddDependency(ctx.Module(), metalavaAPILevelsModuleTag, proptools.String(d.properties.Api_levels_module))
  200. }
  201. }
  202. func (d *Droidstubs) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
  203. if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
  204. apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
  205. String(d.properties.Api_filename) != "" {
  206. filename := proptools.StringDefault(d.properties.Api_filename, ctx.ModuleName()+"_api.txt")
  207. uncheckedApiFile := android.PathForModuleOut(ctx, "metalava", filename)
  208. cmd.FlagWithOutput("--api ", uncheckedApiFile)
  209. d.apiFile = uncheckedApiFile
  210. } else if sourceApiFile := proptools.String(d.properties.Check_api.Current.Api_file); sourceApiFile != "" {
  211. // If check api is disabled then make the source file available for export.
  212. d.apiFile = android.PathForModuleSrc(ctx, sourceApiFile)
  213. }
  214. if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
  215. apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") ||
  216. String(d.properties.Removed_api_filename) != "" {
  217. filename := proptools.StringDefault(d.properties.Removed_api_filename, ctx.ModuleName()+"_removed.txt")
  218. uncheckedRemovedFile := android.PathForModuleOut(ctx, "metalava", filename)
  219. cmd.FlagWithOutput("--removed-api ", uncheckedRemovedFile)
  220. d.removedApiFile = uncheckedRemovedFile
  221. } else if sourceRemovedApiFile := proptools.String(d.properties.Check_api.Current.Removed_api_file); sourceRemovedApiFile != "" {
  222. // If check api is disabled then make the source removed api file available for export.
  223. d.removedApiFile = android.PathForModuleSrc(ctx, sourceRemovedApiFile)
  224. }
  225. if Bool(d.properties.Write_sdk_values) {
  226. d.metadataDir = android.PathForModuleOut(ctx, "metalava", "metadata")
  227. cmd.FlagWithArg("--sdk-values ", d.metadataDir.String())
  228. }
  229. if stubsDir.Valid() {
  230. if Bool(d.properties.Create_doc_stubs) {
  231. cmd.FlagWithArg("--doc-stubs ", stubsDir.String())
  232. } else {
  233. cmd.FlagWithArg("--stubs ", stubsDir.String())
  234. if !Bool(d.properties.Output_javadoc_comments) {
  235. cmd.Flag("--exclude-documentation-from-stubs")
  236. }
  237. }
  238. }
  239. }
  240. func (d *Droidstubs) annotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  241. if Bool(d.properties.Annotations_enabled) {
  242. cmd.Flag("--include-annotations")
  243. cmd.FlagWithArg("--exclude-annotation ", "androidx.annotation.RequiresApi")
  244. validatingNullability :=
  245. strings.Contains(String(d.Javadoc.properties.Args), "--validate-nullability-from-merged-stubs") ||
  246. String(d.properties.Validate_nullability_from_list) != ""
  247. migratingNullability := String(d.properties.Previous_api) != ""
  248. if migratingNullability {
  249. previousApi := android.PathForModuleSrc(ctx, String(d.properties.Previous_api))
  250. cmd.FlagWithInput("--migrate-nullness ", previousApi)
  251. }
  252. if s := String(d.properties.Validate_nullability_from_list); s != "" {
  253. cmd.FlagWithInput("--validate-nullability-from-list ", android.PathForModuleSrc(ctx, s))
  254. }
  255. if validatingNullability {
  256. d.nullabilityWarningsFile = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_nullability_warnings.txt")
  257. cmd.FlagWithOutput("--nullability-warnings-txt ", d.nullabilityWarningsFile)
  258. }
  259. d.annotationsZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"_annotations.zip")
  260. cmd.FlagWithOutput("--extract-annotations ", d.annotationsZip)
  261. if len(d.properties.Merge_annotations_dirs) != 0 {
  262. d.mergeAnnoDirFlags(ctx, cmd)
  263. }
  264. // TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
  265. cmd.FlagWithArg("--hide ", "HiddenTypedefConstant").
  266. FlagWithArg("--hide ", "SuperfluousPrefix").
  267. FlagWithArg("--hide ", "AnnotationExtraction").
  268. // b/222738070
  269. FlagWithArg("--hide ", "BannedThrow").
  270. // b/223382732
  271. FlagWithArg("--hide ", "ChangedDefault")
  272. }
  273. }
  274. func (d *Droidstubs) mergeAnnoDirFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  275. ctx.VisitDirectDepsWithTag(metalavaMergeAnnotationsDirTag, func(m android.Module) {
  276. if t, ok := m.(*ExportedDroiddocDir); ok {
  277. cmd.FlagWithArg("--merge-qualifier-annotations ", t.dir.String()).Implicits(t.deps)
  278. } else {
  279. ctx.PropertyErrorf("merge_annotations_dirs",
  280. "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
  281. }
  282. })
  283. }
  284. func (d *Droidstubs) inclusionAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  285. ctx.VisitDirectDepsWithTag(metalavaMergeInclusionAnnotationsDirTag, func(m android.Module) {
  286. if t, ok := m.(*ExportedDroiddocDir); ok {
  287. cmd.FlagWithArg("--merge-inclusion-annotations ", t.dir.String()).Implicits(t.deps)
  288. } else {
  289. ctx.PropertyErrorf("merge_inclusion_annotations_dirs",
  290. "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
  291. }
  292. })
  293. }
  294. func (d *Droidstubs) apiLevelsAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  295. var apiVersions android.Path
  296. if proptools.Bool(d.properties.Api_levels_annotations_enabled) {
  297. d.apiLevelsGenerationFlags(ctx, cmd)
  298. apiVersions = d.apiVersionsXml
  299. } else {
  300. ctx.VisitDirectDepsWithTag(metalavaAPILevelsModuleTag, func(m android.Module) {
  301. if s, ok := m.(*Droidstubs); ok {
  302. apiVersions = s.apiVersionsXml
  303. } else {
  304. ctx.PropertyErrorf("api_levels_module",
  305. "module %q is not a droidstubs module", ctx.OtherModuleName(m))
  306. }
  307. })
  308. }
  309. if apiVersions != nil {
  310. cmd.FlagWithArg("--current-version ", ctx.Config().PlatformSdkVersion().String())
  311. cmd.FlagWithArg("--current-codename ", ctx.Config().PlatformSdkCodename())
  312. cmd.FlagWithInput("--apply-api-levels ", apiVersions)
  313. }
  314. }
  315. func (d *Droidstubs) apiLevelsGenerationFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  316. if len(d.properties.Api_levels_annotations_dirs) == 0 {
  317. ctx.PropertyErrorf("api_levels_annotations_dirs",
  318. "has to be non-empty if api levels annotations was enabled!")
  319. }
  320. d.apiVersionsXml = android.PathForModuleOut(ctx, "metalava", "api-versions.xml")
  321. cmd.FlagWithOutput("--generate-api-levels ", d.apiVersionsXml)
  322. filename := proptools.StringDefault(d.properties.Api_levels_jar_filename, "android.jar")
  323. var dirs []string
  324. var extensions_dir string
  325. ctx.VisitDirectDepsWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.Module) {
  326. if t, ok := m.(*ExportedDroiddocDir); ok {
  327. extRegex := regexp.MustCompile(t.dir.String() + `/extensions/[0-9]+/public/.*\.jar`)
  328. // Grab the first extensions_dir and we find while scanning ExportedDroiddocDir.deps;
  329. // ideally this should be read from prebuiltApis.properties.Extensions_*
  330. for _, dep := range t.deps {
  331. if extRegex.MatchString(dep.String()) && d.properties.Extensions_info_file != nil {
  332. if extensions_dir == "" {
  333. extensions_dir = t.dir.String() + "/extensions"
  334. }
  335. cmd.Implicit(dep)
  336. }
  337. if dep.Base() == filename {
  338. cmd.Implicit(dep)
  339. }
  340. if filename != "android.jar" && dep.Base() == "android.jar" {
  341. // Metalava implicitly searches these patterns:
  342. // prebuilts/tools/common/api-versions/android-%/android.jar
  343. // prebuilts/sdk/%/public/android.jar
  344. // Add android.jar files from the api_levels_annotations_dirs directories to try
  345. // to satisfy these patterns. If Metalava can't find a match for an API level
  346. // between 1 and 28 in at least one pattern it will fail.
  347. cmd.Implicit(dep)
  348. }
  349. }
  350. dirs = append(dirs, t.dir.String())
  351. } else {
  352. ctx.PropertyErrorf("api_levels_annotations_dirs",
  353. "module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
  354. }
  355. })
  356. // Add all relevant --android-jar-pattern patterns for Metalava.
  357. // When parsing a stub jar for a specific version, Metalava picks the first pattern that defines
  358. // an actual file present on disk (in the order the patterns were passed). For system APIs for
  359. // privileged apps that are only defined since API level 21 (Lollipop), fallback to public stubs
  360. // for older releases. Similarly, module-lib falls back to system API.
  361. var sdkDirs []string
  362. switch proptools.StringDefault(d.properties.Api_levels_sdk_type, "public") {
  363. case "system-server":
  364. sdkDirs = []string{"system-server", "module-lib", "system", "public"}
  365. case "module-lib":
  366. sdkDirs = []string{"module-lib", "system", "public"}
  367. case "system":
  368. sdkDirs = []string{"system", "public"}
  369. case "public":
  370. sdkDirs = []string{"public"}
  371. default:
  372. ctx.PropertyErrorf("api_levels_sdk_type", "needs to be one of %v", allowedApiLevelSdkTypes)
  373. return
  374. }
  375. for _, sdkDir := range sdkDirs {
  376. for _, dir := range dirs {
  377. cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/%%/%s/%s", dir, sdkDir, filename))
  378. }
  379. }
  380. if d.properties.Extensions_info_file != nil {
  381. if extensions_dir == "" {
  382. ctx.ModuleErrorf("extensions_info_file set, but no SDK extension dirs found")
  383. }
  384. info_file := android.PathForModuleSrc(ctx, *d.properties.Extensions_info_file)
  385. cmd.Implicit(info_file)
  386. cmd.FlagWithArg("--sdk-extensions-root ", extensions_dir)
  387. cmd.FlagWithArg("--sdk-extensions-info ", info_file.String())
  388. }
  389. }
  390. func metalavaUseRbe(ctx android.ModuleContext) bool {
  391. return ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_METALAVA")
  392. }
  393. func metalavaCmd(ctx android.ModuleContext, rule *android.RuleBuilder, javaVersion javaVersion, srcs android.Paths,
  394. srcJarList android.Path, bootclasspath, classpath classpath, homeDir android.WritablePath) *android.RuleBuilderCommand {
  395. rule.Command().Text("rm -rf").Flag(homeDir.String())
  396. rule.Command().Text("mkdir -p").Flag(homeDir.String())
  397. cmd := rule.Command()
  398. cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
  399. if metalavaUseRbe(ctx) {
  400. rule.Remoteable(android.RemoteRuleSupports{RBE: true})
  401. execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
  402. labels := map[string]string{"type": "tool", "name": "metalava"}
  403. // TODO: metalava pool rejects these jobs
  404. pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
  405. rule.Rewrapper(&remoteexec.REParams{
  406. Labels: labels,
  407. ExecStrategy: execStrategy,
  408. ToolchainInputs: []string{config.JavaCmd(ctx).String()},
  409. Platform: map[string]string{remoteexec.PoolKey: pool},
  410. })
  411. }
  412. cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
  413. Flag(config.JavacVmFlags).
  414. Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
  415. FlagWithArg("-encoding ", "UTF-8").
  416. FlagWithArg("-source ", javaVersion.String()).
  417. FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, "metalava.rsp"), srcs).
  418. FlagWithInput("@", srcJarList)
  419. if len(bootclasspath) > 0 {
  420. cmd.FlagWithInputList("-bootclasspath ", bootclasspath.Paths(), ":")
  421. }
  422. if len(classpath) > 0 {
  423. cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
  424. }
  425. cmd.Flag("--no-banner").
  426. Flag("--color").
  427. Flag("--quiet").
  428. Flag("--format=v2").
  429. FlagWithArg("--repeat-errors-max ", "10").
  430. FlagWithArg("--hide ", "UnresolvedImport").
  431. FlagWithArg("--hide ", "InvalidNullabilityOverride").
  432. // b/223382732
  433. FlagWithArg("--hide ", "ChangedDefault")
  434. return cmd
  435. }
  436. func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  437. deps := d.Javadoc.collectDeps(ctx)
  438. javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), android.SdkContext(d))
  439. // Create rule for metalava
  440. srcJarDir := android.PathForModuleOut(ctx, "metalava", "srcjars")
  441. rule := android.NewRuleBuilder(pctx, ctx)
  442. rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
  443. android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
  444. SandboxInputs()
  445. if BoolDefault(d.properties.High_mem, false) {
  446. // This metalava run uses lots of memory, restrict the number of metalava jobs that can run in parallel.
  447. rule.HighMem()
  448. }
  449. generateStubs := BoolDefault(d.properties.Generate_stubs, true)
  450. var stubsDir android.OptionalPath
  451. if generateStubs {
  452. d.Javadoc.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
  453. stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
  454. rule.Command().Text("rm -rf").Text(stubsDir.String())
  455. rule.Command().Text("mkdir -p").Text(stubsDir.String())
  456. }
  457. srcJarList := zipSyncCmd(ctx, rule, srcJarDir, d.Javadoc.srcJars)
  458. homeDir := android.PathForModuleOut(ctx, "metalava", "home")
  459. cmd := metalavaCmd(ctx, rule, javaVersion, d.Javadoc.srcFiles, srcJarList,
  460. deps.bootClasspath, deps.classpath, homeDir)
  461. cmd.Implicits(d.Javadoc.implicits)
  462. d.stubsFlags(ctx, cmd, stubsDir)
  463. d.annotationsFlags(ctx, cmd)
  464. d.inclusionAnnotationsFlags(ctx, cmd)
  465. d.apiLevelsAnnotationsFlags(ctx, cmd)
  466. d.expandArgs(ctx, cmd)
  467. for _, o := range d.Javadoc.properties.Out {
  468. cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
  469. }
  470. // Add options for the other optional tasks: API-lint and check-released.
  471. // We generate separate timestamp files for them.
  472. doApiLint := false
  473. doCheckReleased := false
  474. // Add API lint options.
  475. if BoolDefault(d.properties.Check_api.Api_lint.Enabled, false) {
  476. doApiLint = true
  477. newSince := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.New_since)
  478. if newSince.Valid() {
  479. cmd.FlagWithInput("--api-lint ", newSince.Path())
  480. } else {
  481. cmd.Flag("--api-lint")
  482. }
  483. d.apiLintReport = android.PathForModuleOut(ctx, "metalava", "api_lint_report.txt")
  484. cmd.FlagWithOutput("--report-even-if-suppressed ", d.apiLintReport) // TODO: Change to ":api-lint"
  485. // TODO(b/154317059): Clean up this allowlist by baselining and/or checking in last-released.
  486. if d.Name() != "android.car-system-stubs-docs" &&
  487. d.Name() != "android.car-stubs-docs" {
  488. cmd.Flag("--lints-as-errors")
  489. cmd.Flag("--warnings-as-errors") // Most lints are actually warnings.
  490. }
  491. baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
  492. updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "api_lint_baseline.txt")
  493. d.apiLintTimestamp = android.PathForModuleOut(ctx, "metalava", "api_lint.timestamp")
  494. // Note this string includes a special shell quote $' ... ', which decodes the "\n"s.
  495. //
  496. // TODO: metalava also has a slightly different message hardcoded. Should we unify this
  497. // message and metalava's one?
  498. msg := `$'` + // Enclose with $' ... '
  499. `************************************************************\n` +
  500. `Your API changes are triggering API Lint warnings or errors.\n` +
  501. `To make these errors go away, fix the code according to the\n` +
  502. `error and/or warning messages above.\n` +
  503. `\n` +
  504. `If it is not possible to do so, there are workarounds:\n` +
  505. `\n` +
  506. `1. You can suppress the errors with @SuppressLint("<id>")\n` +
  507. ` where the <id> is given in brackets in the error message above.\n`
  508. if baselineFile.Valid() {
  509. cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
  510. cmd.FlagWithOutput("--update-baseline:api-lint ", updatedBaselineOutput)
  511. msg += fmt.Sprintf(``+
  512. `2. You can update the baseline by executing the following\n`+
  513. ` command:\n`+
  514. ` (cd $ANDROID_BUILD_TOP && cp \\\n`+
  515. ` "%s" \\\n`+
  516. ` "%s")\n`+
  517. ` To submit the revised baseline.txt to the main Android\n`+
  518. ` repository, you will need approval.\n`, updatedBaselineOutput, baselineFile.Path())
  519. } else {
  520. msg += fmt.Sprintf(``+
  521. `2. You can add a baseline file of existing lint failures\n`+
  522. ` to the build rule of %s.\n`, d.Name())
  523. }
  524. // Note the message ends with a ' (single quote), to close the $' ... ' .
  525. msg += `************************************************************\n'`
  526. cmd.FlagWithArg("--error-message:api-lint ", msg)
  527. }
  528. // Add "check released" options. (Detect incompatible API changes from the last public release)
  529. if apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released") {
  530. doCheckReleased = true
  531. if len(d.Javadoc.properties.Out) > 0 {
  532. ctx.PropertyErrorf("out", "out property may not be combined with check_api")
  533. }
  534. apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Api_file))
  535. removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Last_released.Removed_api_file))
  536. baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
  537. updatedBaselineOutput := android.PathForModuleOut(ctx, "metalava", "last_released_baseline.txt")
  538. d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_last_released_api.timestamp")
  539. cmd.FlagWithInput("--check-compatibility:api:released ", apiFile)
  540. cmd.FlagWithInput("--check-compatibility:removed:released ", removedApiFile)
  541. if baselineFile.Valid() {
  542. cmd.FlagWithInput("--baseline:compatibility:released ", baselineFile.Path())
  543. cmd.FlagWithOutput("--update-baseline:compatibility:released ", updatedBaselineOutput)
  544. }
  545. // Note this string includes quote ($' ... '), which decodes the "\n"s.
  546. msg := `$'\n******************************\n` +
  547. `You have tried to change the API from what has been previously released in\n` +
  548. `an SDK. Please fix the errors listed above.\n` +
  549. `******************************\n'`
  550. cmd.FlagWithArg("--error-message:compatibility:released ", msg)
  551. }
  552. if generateStubs {
  553. rule.Command().
  554. BuiltTool("soong_zip").
  555. Flag("-write_if_changed").
  556. Flag("-jar").
  557. FlagWithOutput("-o ", d.Javadoc.stubsSrcJar).
  558. FlagWithArg("-C ", stubsDir.String()).
  559. FlagWithArg("-D ", stubsDir.String())
  560. }
  561. if Bool(d.properties.Write_sdk_values) {
  562. d.metadataZip = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-metadata.zip")
  563. rule.Command().
  564. BuiltTool("soong_zip").
  565. Flag("-write_if_changed").
  566. Flag("-d").
  567. FlagWithOutput("-o ", d.metadataZip).
  568. FlagWithArg("-C ", d.metadataDir.String()).
  569. FlagWithArg("-D ", d.metadataDir.String())
  570. }
  571. // TODO: We don't really need two separate API files, but this is a reminiscence of how
  572. // we used to run metalava separately for API lint and the "last_released" check. Unify them.
  573. if doApiLint {
  574. rule.Command().Text("touch").Output(d.apiLintTimestamp)
  575. }
  576. if doCheckReleased {
  577. rule.Command().Text("touch").Output(d.checkLastReleasedApiTimestamp)
  578. }
  579. // TODO(b/183630617): rewrapper doesn't support restat rules
  580. if !metalavaUseRbe(ctx) {
  581. rule.Restat()
  582. }
  583. zipSyncCleanupCmd(rule, srcJarDir)
  584. rule.Build("metalava", "metalava merged")
  585. if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
  586. if len(d.Javadoc.properties.Out) > 0 {
  587. ctx.PropertyErrorf("out", "out property may not be combined with check_api")
  588. }
  589. apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
  590. removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Removed_api_file))
  591. baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Current.Baseline_file)
  592. if baselineFile.Valid() {
  593. ctx.PropertyErrorf("baseline_file", "current API check can't have a baseline file. (module %s)", ctx.ModuleName())
  594. }
  595. d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "check_current_api.timestamp")
  596. rule := android.NewRuleBuilder(pctx, ctx)
  597. // Diff command line.
  598. // -F matches the closest "opening" line, such as "package android {"
  599. // and " public class Intent {".
  600. diff := `diff -u -F '{ *$'`
  601. rule.Command().Text("( true")
  602. rule.Command().
  603. Text(diff).
  604. Input(apiFile).Input(d.apiFile)
  605. rule.Command().
  606. Text(diff).
  607. Input(removedApiFile).Input(d.removedApiFile)
  608. msg := fmt.Sprintf(`\n******************************\n`+
  609. `You have tried to change the API from what has been previously approved.\n\n`+
  610. `To make these errors go away, you have two choices:\n`+
  611. ` 1. You can add '@hide' javadoc comments (and remove @SystemApi/@TestApi/etc)\n`+
  612. ` to the new methods, etc. shown in the above diff.\n\n`+
  613. ` 2. You can update current.txt and/or removed.txt by executing the following command:\n`+
  614. ` m %s-update-current-api\n\n`+
  615. ` To submit the revised current.txt to the main Android repository,\n`+
  616. ` you will need approval.\n`+
  617. `******************************\n`, ctx.ModuleName())
  618. rule.Command().
  619. Text("touch").Output(d.checkCurrentApiTimestamp).
  620. Text(") || (").
  621. Text("echo").Flag("-e").Flag(`"` + msg + `"`).
  622. Text("; exit 38").
  623. Text(")")
  624. rule.Build("metalavaCurrentApiCheck", "check current API")
  625. d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "metalava", "update_current_api.timestamp")
  626. // update API rule
  627. rule = android.NewRuleBuilder(pctx, ctx)
  628. rule.Command().Text("( true")
  629. rule.Command().
  630. Text("cp").Flag("-f").
  631. Input(d.apiFile).Flag(apiFile.String())
  632. rule.Command().
  633. Text("cp").Flag("-f").
  634. Input(d.removedApiFile).Flag(removedApiFile.String())
  635. msg = "failed to update public API"
  636. rule.Command().
  637. Text("touch").Output(d.updateCurrentApiTimestamp).
  638. Text(") || (").
  639. Text("echo").Flag("-e").Flag(`"` + msg + `"`).
  640. Text("; exit 38").
  641. Text(")")
  642. rule.Build("metalavaCurrentApiUpdate", "update current API")
  643. }
  644. if String(d.properties.Check_nullability_warnings) != "" {
  645. if d.nullabilityWarningsFile == nil {
  646. ctx.PropertyErrorf("check_nullability_warnings",
  647. "Cannot specify check_nullability_warnings unless validating nullability")
  648. }
  649. checkNullabilityWarnings := android.PathForModuleSrc(ctx, String(d.properties.Check_nullability_warnings))
  650. d.checkNullabilityWarningsTimestamp = android.PathForModuleOut(ctx, "metalava", "check_nullability_warnings.timestamp")
  651. msg := fmt.Sprintf(`\n******************************\n`+
  652. `The warnings encountered during nullability annotation validation did\n`+
  653. `not match the checked in file of expected warnings. The diffs are shown\n`+
  654. `above. You have two options:\n`+
  655. ` 1. Resolve the differences by editing the nullability annotations.\n`+
  656. ` 2. Update the file of expected warnings by running:\n`+
  657. ` cp %s %s\n`+
  658. ` and submitting the updated file as part of your change.`,
  659. d.nullabilityWarningsFile, checkNullabilityWarnings)
  660. rule := android.NewRuleBuilder(pctx, ctx)
  661. rule.Command().
  662. Text("(").
  663. Text("diff").Input(checkNullabilityWarnings).Input(d.nullabilityWarningsFile).
  664. Text("&&").
  665. Text("touch").Output(d.checkNullabilityWarningsTimestamp).
  666. Text(") || (").
  667. Text("echo").Flag("-e").Flag(`"` + msg + `"`).
  668. Text("; exit 38").
  669. Text(")")
  670. rule.Build("nullabilityWarningsCheck", "nullability warnings check")
  671. }
  672. }
  673. func StubsDefaultsFactory() android.Module {
  674. module := &DocDefaults{}
  675. module.AddProperties(
  676. &JavadocProperties{},
  677. &DroidstubsProperties{},
  678. )
  679. android.InitDefaultsModule(module)
  680. return module
  681. }
  682. var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
  683. type PrebuiltStubsSourcesProperties struct {
  684. Srcs []string `android:"path"`
  685. }
  686. type PrebuiltStubsSources struct {
  687. android.ModuleBase
  688. android.DefaultableModuleBase
  689. prebuilt android.Prebuilt
  690. properties PrebuiltStubsSourcesProperties
  691. stubsSrcJar android.Path
  692. }
  693. func (p *PrebuiltStubsSources) OutputFiles(tag string) (android.Paths, error) {
  694. switch tag {
  695. case "":
  696. return android.Paths{p.stubsSrcJar}, nil
  697. default:
  698. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  699. }
  700. }
  701. func (d *PrebuiltStubsSources) StubsSrcJar() android.Path {
  702. return d.stubsSrcJar
  703. }
  704. func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  705. if len(p.properties.Srcs) != 1 {
  706. ctx.PropertyErrorf("srcs", "must only specify one directory path or srcjar, contains %d paths", len(p.properties.Srcs))
  707. return
  708. }
  709. src := p.properties.Srcs[0]
  710. if filepath.Ext(src) == ".srcjar" {
  711. // This is a srcjar. We can use it directly.
  712. p.stubsSrcJar = android.PathForModuleSrc(ctx, src)
  713. } else {
  714. outPath := android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
  715. // This is a directory. Glob the contents just in case the directory does not exist.
  716. srcGlob := src + "/**/*"
  717. srcPaths := android.PathsForModuleSrc(ctx, []string{srcGlob})
  718. // Although PathForModuleSrc can return nil if either the path doesn't exist or
  719. // the path components are invalid it won't in this case because no components
  720. // are specified and the module directory must exist in order to get this far.
  721. srcDir := android.PathForModuleSrc(ctx).(android.SourcePath).Join(ctx, src)
  722. rule := android.NewRuleBuilder(pctx, ctx)
  723. rule.Command().
  724. BuiltTool("soong_zip").
  725. Flag("-write_if_changed").
  726. Flag("-jar").
  727. FlagWithOutput("-o ", outPath).
  728. FlagWithArg("-C ", srcDir.String()).
  729. FlagWithRspFileInputList("-r ", outPath.ReplaceExtension(ctx, "rsp"), srcPaths)
  730. rule.Restat()
  731. rule.Build("zip src", "Create srcjar from prebuilt source")
  732. p.stubsSrcJar = outPath
  733. }
  734. }
  735. func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
  736. return &p.prebuilt
  737. }
  738. func (p *PrebuiltStubsSources) Name() string {
  739. return p.prebuilt.Name(p.ModuleBase.Name())
  740. }
  741. // prebuilt_stubs_sources imports a set of java source files as if they were
  742. // generated by droidstubs.
  743. //
  744. // By default, a prebuilt_stubs_sources has a single variant that expects a
  745. // set of `.java` files generated by droidstubs.
  746. //
  747. // Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
  748. // for host modules.
  749. //
  750. // Intended only for use by sdk snapshots.
  751. func PrebuiltStubsSourcesFactory() android.Module {
  752. module := &PrebuiltStubsSources{}
  753. module.AddProperties(&module.properties)
  754. android.InitPrebuiltModule(module, &module.properties.Srcs)
  755. InitDroiddocModule(module, android.HostAndDeviceSupported)
  756. return module
  757. }