droidstubs.go 33 KB

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