blob: 40d6f18f294c3d1a6b29bc5be8c2ab1e3351f86f [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"
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +020020 "regexp"
Colin Cross2207f872021-03-24 12:39:08 -070021 "strings"
22
Yu Liucbb50c22025-01-15 20:57:49 +000023 "github.com/google/blueprint"
Colin Cross2207f872021-03-24 12:39:08 -070024 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/java/config"
28 "android/soong/remoteexec"
29)
30
Yu Liu35acd332025-01-24 23:11:22 +000031type StubsInfo struct {
32 ApiVersionsXml android.Path
33 AnnotationsZip android.Path
34 ApiFile android.Path
35 RemovedApiFile android.Path
Yu Liu3a892962025-01-15 23:14:27 +000036}
37
Yu Liucbb50c22025-01-15 20:57:49 +000038type DroidStubsInfo struct {
39 CurrentApiTimestamp android.Path
Yu Liu35acd332025-01-24 23:11:22 +000040 EverythingStubsInfo StubsInfo
41 ExportableStubsInfo StubsInfo
Yu Liucbb50c22025-01-15 20:57:49 +000042}
43
44var DroidStubsInfoProvider = blueprint.NewProvider[DroidStubsInfo]()
45
Yu Liu35acd332025-01-24 23:11:22 +000046type StubsSrcInfo struct {
47 EverythingStubsSrcJar android.Path
48 ExportableStubsSrcJar android.Path
49}
50
51var StubsSrcInfoProvider = blueprint.NewProvider[StubsSrcInfo]()
52
Pedro Loureirocc203502021-10-04 17:24:00 +000053// The values allowed for Droidstubs' Api_levels_sdk_type
Cole Faust051fa912022-10-05 12:45:42 -070054var allowedApiLevelSdkTypes = []string{"public", "system", "module-lib", "system-server"}
Pedro Loureirocc203502021-10-04 17:24:00 +000055
Jihoon Kang6592e872023-12-19 01:13:16 +000056type StubsType int
57
58const (
59 Everything StubsType = iota
60 Runtime
61 Exportable
Jihoon Kang78f89142023-12-27 01:40:29 +000062 Unavailable
Jihoon Kang6592e872023-12-19 01:13:16 +000063)
64
65func (s StubsType) String() string {
66 switch s {
67 case Everything:
68 return "everything"
69 case Runtime:
70 return "runtime"
71 case Exportable:
72 return "exportable"
73 default:
74 return ""
75 }
76}
77
Jihoon Kang5d701272024-02-15 21:53:49 +000078func StringToStubsType(s string) StubsType {
79 switch strings.ToLower(s) {
80 case Everything.String():
81 return Everything
82 case Runtime.String():
83 return Runtime
84 case Exportable.String():
85 return Exportable
86 default:
87 return Unavailable
88 }
89}
90
Colin Cross2207f872021-03-24 12:39:08 -070091func init() {
92 RegisterStubsBuildComponents(android.InitRegistrationContext)
93}
94
95func RegisterStubsBuildComponents(ctx android.RegistrationContext) {
96 ctx.RegisterModuleType("stubs_defaults", StubsDefaultsFactory)
97
98 ctx.RegisterModuleType("droidstubs", DroidstubsFactory)
99 ctx.RegisterModuleType("droidstubs_host", DroidstubsHostFactory)
100
101 ctx.RegisterModuleType("prebuilt_stubs_sources", PrebuiltStubsSourcesFactory)
102}
103
Jihoon Kangee113282024-01-23 00:16:41 +0000104type stubsArtifacts struct {
105 nullabilityWarningsFile android.WritablePath
106 annotationsZip android.WritablePath
107 apiVersionsXml android.WritablePath
108 metadataZip android.WritablePath
109 metadataDir android.WritablePath
110}
111
Colin Cross2207f872021-03-24 12:39:08 -0700112// Droidstubs
Colin Cross2207f872021-03-24 12:39:08 -0700113type Droidstubs struct {
114 Javadoc
Spandan Das2cc80ba2023-10-27 17:21:52 +0000115 embeddableInModuleAndImport
Colin Cross2207f872021-03-24 12:39:08 -0700116
Jihoon Kangee113282024-01-23 00:16:41 +0000117 properties DroidstubsProperties
118 apiFile android.Path
119 removedApiFile android.Path
Colin Cross2207f872021-03-24 12:39:08 -0700120
121 checkCurrentApiTimestamp android.WritablePath
122 updateCurrentApiTimestamp android.WritablePath
123 checkLastReleasedApiTimestamp android.WritablePath
124 apiLintTimestamp android.WritablePath
125 apiLintReport android.WritablePath
126
127 checkNullabilityWarningsTimestamp android.WritablePath
128
Jihoon Kangee113282024-01-23 00:16:41 +0000129 everythingArtifacts stubsArtifacts
130 exportableArtifacts stubsArtifacts
Jihoon Kang3c89f042023-12-19 02:40:22 +0000131
Jihoon Kangee113282024-01-23 00:16:41 +0000132 exportableApiFile android.WritablePath
133 exportableRemovedApiFile android.WritablePath
Colin Cross2207f872021-03-24 12:39:08 -0700134}
135
136type DroidstubsProperties struct {
137 // The generated public API filename by Metalava, defaults to <module>_api.txt
138 Api_filename *string
139
140 // the generated removed API filename by Metalava, defaults to <module>_removed.txt
141 Removed_api_filename *string
142
Colin Cross2207f872021-03-24 12:39:08 -0700143 Check_api struct {
144 Last_released ApiToCheck
145
146 Current ApiToCheck
147
148 Api_lint struct {
149 Enabled *bool
150
151 // If set, performs api_lint on any new APIs not found in the given signature file
152 New_since *string `android:"path"`
153
154 // If not blank, path to the baseline txt file for approved API lint violations.
155 Baseline_file *string `android:"path"`
156 }
157 }
158
159 // user can specify the version of previous released API file in order to do compatibility check.
160 Previous_api *string `android:"path"`
161
162 // is set to true, Metalava will allow framework SDK to contain annotations.
163 Annotations_enabled *bool
164
165 // a list of top-level directories containing files to merge qualifier annotations (i.e. those intended to be included in the stubs written) from.
166 Merge_annotations_dirs []string
167
168 // a list of top-level directories containing Java stub files to merge show/hide annotations from.
169 Merge_inclusion_annotations_dirs []string
170
171 // a file containing a list of classes to do nullability validation for.
172 Validate_nullability_from_list *string
173
174 // a file containing expected warnings produced by validation of nullability annotations.
175 Check_nullability_warnings *string
176
177 // if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
178 Create_doc_stubs *bool
179
180 // if set to true, cause Metalava to output Javadoc comments in the stubs source files. Defaults to false.
181 // Has no effect if create_doc_stubs: true.
182 Output_javadoc_comments *bool
183
184 // if set to false then do not write out stubs. Defaults to true.
185 //
186 // TODO(b/146727827): Remove capability when we do not need to generate stubs and API separately.
187 Generate_stubs *bool
188
189 // if set to true, provides a hint to the build system that this rule uses a lot of memory,
Liz Kammer170dd722023-10-16 15:08:39 -0400190 // which can be used for scheduling purposes
Colin Cross2207f872021-03-24 12:39:08 -0700191 High_mem *bool
192
satayev783195c2021-06-23 21:49:57 +0100193 // if set to true, Metalava will allow framework SDK to contain API levels annotations.
Colin Cross2207f872021-03-24 12:39:08 -0700194 Api_levels_annotations_enabled *bool
195
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000196 // Apply the api levels database created by this module rather than generating one in this droidstubs.
197 Api_levels_module *string
198
Colin Cross2207f872021-03-24 12:39:08 -0700199 // the dirs which Metalava extracts API levels annotations from.
200 Api_levels_annotations_dirs []string
201
Cole Faust051fa912022-10-05 12:45:42 -0700202 // the sdk kind which Metalava extracts API levels annotations from. Supports 'public', 'system', 'module-lib' and 'system-server'; defaults to public.
satayev783195c2021-06-23 21:49:57 +0100203 Api_levels_sdk_type *string
204
Colin Cross2207f872021-03-24 12:39:08 -0700205 // the filename which Metalava extracts API levels annotations from. Defaults to android.jar.
206 Api_levels_jar_filename *string
207
208 // if set to true, collect the values used by the Dev tools and
209 // write them in files packaged with the SDK. Defaults to false.
210 Write_sdk_values *bool
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200211
212 // path or filegroup to file defining extension an SDK name <-> numerical ID mapping and
213 // what APIs exist in which SDKs; passed to metalava via --sdk-extensions-info
214 Extensions_info_file *string `android:"path"`
Jihoon Kang3198f3c2023-01-26 08:08:52 +0000215
216 // API surface of this module. If set, the module contributes to an API surface.
217 // For the full list of available API surfaces, refer to soong/android/sdk_version.go
218 Api_surface *string
Jihoon Kang6592e872023-12-19 01:13:16 +0000219
220 // a list of aconfig_declarations module names that the stubs generated in this module
221 // depend on.
222 Aconfig_declarations []string
Paul Duffin27819362024-07-22 21:03:50 +0100223
224 // List of hard coded filegroups containing Metalava config files that are passed to every
225 // Metalava invocation that this module performs. See addMetalavaConfigFilesToCmd.
226 ConfigFiles []string `android:"path" blueprint:"mutated"`
Colin Cross2207f872021-03-24 12:39:08 -0700227}
228
Anton Hansson52609322021-05-05 10:36:05 +0100229// Used by xsd_config
230type ApiFilePath interface {
Jihoon Kangee113282024-01-23 00:16:41 +0000231 ApiFilePath(StubsType) (android.Path, error)
Anton Hansson52609322021-05-05 10:36:05 +0100232}
233
234type ApiStubsSrcProvider interface {
Jihoon Kangee113282024-01-23 00:16:41 +0000235 StubsSrcJar(StubsType) (android.Path, error)
Jihoon Kangf55a5f72024-01-08 08:56:20 +0000236}
237
Anton Hansson52609322021-05-05 10:36:05 +0100238// Provider of information about API stubs, used by java_sdk_library.
239type ApiStubsProvider interface {
Jihoon Kangee113282024-01-23 00:16:41 +0000240 AnnotationsZip(StubsType) (android.Path, error)
Anton Hansson52609322021-05-05 10:36:05 +0100241 ApiFilePath
Jihoon Kangee113282024-01-23 00:16:41 +0000242 RemovedApiFilePath(StubsType) (android.Path, error)
Anton Hansson52609322021-05-05 10:36:05 +0100243
244 ApiStubsSrcProvider
245}
246
Jihoon Kang063ec002023-06-28 01:16:23 +0000247type currentApiTimestampProvider interface {
248 CurrentApiTimestamp() android.Path
249}
250
Jihoon Kang3c89f042023-12-19 02:40:22 +0000251type annotationFlagsParams struct {
252 migratingNullability bool
253 validatingNullability bool
254 nullabilityWarningsFile android.WritablePath
255 annotationsZip android.WritablePath
256}
257type stubsCommandParams struct {
258 srcJarDir android.ModuleOutPath
259 stubsDir android.OptionalPath
260 stubsSrcJar android.WritablePath
261 metadataZip android.WritablePath
262 metadataDir android.WritablePath
263 apiVersionsXml android.WritablePath
264 nullabilityWarningsFile android.WritablePath
265 annotationsZip android.WritablePath
266 stubConfig stubsCommandConfigParams
267}
268type stubsCommandConfigParams struct {
Jihoon Kanga11d6792024-03-05 16:12:20 +0000269 stubsType StubsType
270 javaVersion javaVersion
271 deps deps
272 checkApi bool
273 generateStubs bool
274 doApiLint bool
275 doCheckReleased bool
276 writeSdkValues bool
277 migratingNullability bool
278 validatingNullability bool
Jihoon Kang3c89f042023-12-19 02:40:22 +0000279}
280
Colin Cross2207f872021-03-24 12:39:08 -0700281// droidstubs passes sources files through Metalava to generate stub .java files that only contain the API to be
282// documented, filtering out hidden classes and methods. The resulting .java files are intended to be passed to
283// a droiddoc module to generate documentation.
284func DroidstubsFactory() android.Module {
285 module := &Droidstubs{}
286
287 module.AddProperties(&module.properties,
288 &module.Javadoc.properties)
Paul Duffin27819362024-07-22 21:03:50 +0100289 module.properties.ConfigFiles = getMetalavaConfigFilegroupReference()
Spandan Das2cc80ba2023-10-27 17:21:52 +0000290 module.initModuleAndImport(module)
Colin Cross2207f872021-03-24 12:39:08 -0700291
292 InitDroiddocModule(module, android.HostAndDeviceSupported)
Jihoon Kang3198f3c2023-01-26 08:08:52 +0000293
294 module.SetDefaultableHook(func(ctx android.DefaultableHookContext) {
295 module.createApiContribution(ctx)
296 })
Colin Cross2207f872021-03-24 12:39:08 -0700297 return module
298}
299
300// droidstubs_host passes sources files through Metalava to generate stub .java files that only contain the API
301// to be documented, filtering out hidden classes and methods. The resulting .java files are intended to be
302// passed to a droiddoc_host module to generate documentation. Use a droidstubs_host instead of a droidstubs
303// module when symbols needed by the source files are provided by java_library_host modules.
304func DroidstubsHostFactory() android.Module {
305 module := &Droidstubs{}
306
307 module.AddProperties(&module.properties,
308 &module.Javadoc.properties)
309
Paul Duffin27819362024-07-22 21:03:50 +0100310 module.properties.ConfigFiles = getMetalavaConfigFilegroupReference()
Colin Cross2207f872021-03-24 12:39:08 -0700311 InitDroiddocModule(module, android.HostSupported)
312 return module
313}
314
Jihoon Kang246690a2024-02-01 21:55:01 +0000315func (d *Droidstubs) AnnotationsZip(stubsType StubsType) (ret android.Path, err error) {
Jihoon Kang78f89142023-12-27 01:40:29 +0000316 switch stubsType {
317 case Everything:
Jihoon Kang246690a2024-02-01 21:55:01 +0000318 ret, err = d.everythingArtifacts.annotationsZip, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000319 case Exportable:
Jihoon Kang246690a2024-02-01 21:55:01 +0000320 ret, err = d.exportableArtifacts.annotationsZip, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000321 default:
Jihoon Kang246690a2024-02-01 21:55:01 +0000322 ret, err = nil, fmt.Errorf("annotations zip not supported for the stub type %s", stubsType.String())
Jihoon Kang78f89142023-12-27 01:40:29 +0000323 }
Jihoon Kang246690a2024-02-01 21:55:01 +0000324 return ret, err
Jihoon Kang78f89142023-12-27 01:40:29 +0000325}
326
Jihoon Kang246690a2024-02-01 21:55:01 +0000327func (d *Droidstubs) ApiFilePath(stubsType StubsType) (ret android.Path, err error) {
Jihoon Kang78f89142023-12-27 01:40:29 +0000328 switch stubsType {
329 case Everything:
Jihoon Kang246690a2024-02-01 21:55:01 +0000330 ret, err = d.apiFile, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000331 case Exportable:
Jihoon Kang246690a2024-02-01 21:55:01 +0000332 ret, err = d.exportableApiFile, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000333 default:
Jihoon Kang246690a2024-02-01 21:55:01 +0000334 ret, err = nil, fmt.Errorf("api file path not supported for the stub type %s", stubsType.String())
Jihoon Kang78f89142023-12-27 01:40:29 +0000335 }
Jihoon Kang246690a2024-02-01 21:55:01 +0000336 if ret == nil && err == nil {
Jihoon Kang36c3d962024-03-14 17:28:44 +0000337 err = fmt.Errorf("api file is null for the stub type %s", stubsType.String())
Jihoon Kang246690a2024-02-01 21:55:01 +0000338 }
339 return ret, err
Jihoon Kang78f89142023-12-27 01:40:29 +0000340}
341
Jihoon Kang246690a2024-02-01 21:55:01 +0000342func (d *Droidstubs) ApiVersionsXmlFilePath(stubsType StubsType) (ret android.Path, err error) {
Jihoon Kang78f89142023-12-27 01:40:29 +0000343 switch stubsType {
344 case Everything:
Jihoon Kang246690a2024-02-01 21:55:01 +0000345 ret, err = d.everythingArtifacts.apiVersionsXml, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000346 case Exportable:
Jihoon Kang246690a2024-02-01 21:55:01 +0000347 ret, err = d.exportableArtifacts.apiVersionsXml, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000348 default:
Jihoon Kang246690a2024-02-01 21:55:01 +0000349 ret, err = nil, fmt.Errorf("api versions xml file path not supported for the stub type %s", stubsType.String())
Jihoon Kang78f89142023-12-27 01:40:29 +0000350 }
Jihoon Kang246690a2024-02-01 21:55:01 +0000351 if ret == nil && err == nil {
352 err = fmt.Errorf("api versions xml file is null for the stub type %s", stubsType.String())
353 }
354 return ret, err
Jihoon Kang78f89142023-12-27 01:40:29 +0000355}
356
Jihoon Kang246690a2024-02-01 21:55:01 +0000357func (d *Droidstubs) DocZip(stubsType StubsType) (ret android.Path, err error) {
Jihoon Kang78f89142023-12-27 01:40:29 +0000358 switch stubsType {
359 case Everything:
Jihoon Kang246690a2024-02-01 21:55:01 +0000360 ret, err = d.docZip, nil
Jihoon Kang78f89142023-12-27 01:40:29 +0000361 default:
Jihoon Kang246690a2024-02-01 21:55:01 +0000362 ret, err = nil, fmt.Errorf("docs zip not supported for the stub type %s", stubsType.String())
Jihoon Kang78f89142023-12-27 01:40:29 +0000363 }
Jihoon Kang246690a2024-02-01 21:55:01 +0000364 if ret == nil && err == nil {
365 err = fmt.Errorf("docs zip is null for the stub type %s", stubsType.String())
366 }
367 return ret, err
368}
369
370func (d *Droidstubs) RemovedApiFilePath(stubsType StubsType) (ret android.Path, err error) {
371 switch stubsType {
372 case Everything:
373 ret, err = d.removedApiFile, nil
374 case Exportable:
375 ret, err = d.exportableRemovedApiFile, nil
376 default:
377 ret, err = nil, fmt.Errorf("removed api file path not supported for the stub type %s", stubsType.String())
378 }
379 if ret == nil && err == nil {
380 err = fmt.Errorf("removed api file is null for the stub type %s", stubsType.String())
381 }
382 return ret, err
383}
384
385func (d *Droidstubs) StubsSrcJar(stubsType StubsType) (ret android.Path, err error) {
386 switch stubsType {
387 case Everything:
388 ret, err = d.stubsSrcJar, nil
389 case Exportable:
390 ret, err = d.exportableStubsSrcJar, nil
391 default:
392 ret, err = nil, fmt.Errorf("stubs srcjar not supported for the stub type %s", stubsType.String())
393 }
394 if ret == nil && err == nil {
395 err = fmt.Errorf("stubs srcjar is null for the stub type %s", stubsType.String())
396 }
397 return ret, err
Jihoon Kang78f89142023-12-27 01:40:29 +0000398}
399
Jihoon Kang063ec002023-06-28 01:16:23 +0000400func (d *Droidstubs) CurrentApiTimestamp() android.Path {
401 return d.checkCurrentApiTimestamp
402}
403
Colin Cross2207f872021-03-24 12:39:08 -0700404var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
405var metalavaMergeInclusionAnnotationsDirTag = dependencyTag{name: "metalava-merge-inclusion-annotations-dir"}
406var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000407var metalavaAPILevelsModuleTag = dependencyTag{name: "metalava-api-levels-module-tag"}
Jihoon Kang063ec002023-06-28 01:16:23 +0000408var metalavaCurrentApiTimestampTag = dependencyTag{name: "metalava-current-api-timestamp-tag"}
Colin Cross2207f872021-03-24 12:39:08 -0700409
410func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
411 d.Javadoc.addDeps(ctx)
412
413 if len(d.properties.Merge_annotations_dirs) != 0 {
414 for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
415 ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
416 }
417 }
418
419 if len(d.properties.Merge_inclusion_annotations_dirs) != 0 {
420 for _, mergeInclusionAnnotationsDir := range d.properties.Merge_inclusion_annotations_dirs {
421 ctx.AddDependency(ctx.Module(), metalavaMergeInclusionAnnotationsDirTag, mergeInclusionAnnotationsDir)
422 }
423 }
424
425 if len(d.properties.Api_levels_annotations_dirs) != 0 {
426 for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
427 ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
428 }
429 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000430
Jihoon Kang6592e872023-12-19 01:13:16 +0000431 if len(d.properties.Aconfig_declarations) != 0 {
432 for _, aconfigDeclarationModuleName := range d.properties.Aconfig_declarations {
433 ctx.AddDependency(ctx.Module(), aconfigDeclarationTag, aconfigDeclarationModuleName)
434 }
435 }
436
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000437 if d.properties.Api_levels_module != nil {
438 ctx.AddDependency(ctx.Module(), metalavaAPILevelsModuleTag, proptools.String(d.properties.Api_levels_module))
439 }
Colin Cross2207f872021-03-24 12:39:08 -0700440}
441
Jihoon Kang3c89f042023-12-19 02:40:22 +0000442func (d *Droidstubs) sdkValuesFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, metadataDir android.WritablePath) {
443 cmd.FlagWithArg("--sdk-values ", metadataDir.String())
444}
445
446func (d *Droidstubs) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath, stubsType StubsType, checkApi bool) {
Jihoon Kang3c89f042023-12-19 02:40:22 +0000447
Jihoon Kang36c3d962024-03-14 17:28:44 +0000448 apiFileName := proptools.StringDefault(d.properties.Api_filename, ctx.ModuleName()+"_api.txt")
449 uncheckedApiFile := android.PathForModuleOut(ctx, stubsType.String(), apiFileName)
450 cmd.FlagWithOutput("--api ", uncheckedApiFile)
451 if checkApi || String(d.properties.Api_filename) != "" {
Jihoon Kang3c89f042023-12-19 02:40:22 +0000452 if stubsType == Everything {
453 d.apiFile = uncheckedApiFile
454 } else if stubsType == Exportable {
455 d.exportableApiFile = uncheckedApiFile
456 }
Colin Cross2207f872021-03-24 12:39:08 -0700457 } else if sourceApiFile := proptools.String(d.properties.Check_api.Current.Api_file); sourceApiFile != "" {
Jihoon Kang36c3d962024-03-14 17:28:44 +0000458 if stubsType == Everything {
459 // If check api is disabled then make the source file available for export.
460 d.apiFile = android.PathForModuleSrc(ctx, sourceApiFile)
461 } else if stubsType == Exportable {
462 d.exportableApiFile = uncheckedApiFile
463 }
Colin Cross2207f872021-03-24 12:39:08 -0700464 }
465
Jihoon Kang36c3d962024-03-14 17:28:44 +0000466 removedApiFileName := proptools.StringDefault(d.properties.Removed_api_filename, ctx.ModuleName()+"_removed.txt")
467 uncheckedRemovedFile := android.PathForModuleOut(ctx, stubsType.String(), removedApiFileName)
468 cmd.FlagWithOutput("--removed-api ", uncheckedRemovedFile)
Jihoon Kang3c89f042023-12-19 02:40:22 +0000469 if checkApi || String(d.properties.Removed_api_filename) != "" {
Jihoon Kang3c89f042023-12-19 02:40:22 +0000470 if stubsType == Everything {
471 d.removedApiFile = uncheckedRemovedFile
472 } else if stubsType == Exportable {
473 d.exportableRemovedApiFile = uncheckedRemovedFile
474 }
Colin Cross2207f872021-03-24 12:39:08 -0700475 } else if sourceRemovedApiFile := proptools.String(d.properties.Check_api.Current.Removed_api_file); sourceRemovedApiFile != "" {
Jihoon Kang36c3d962024-03-14 17:28:44 +0000476 if stubsType == Everything {
477 // If check api is disabled then make the source removed api file available for export.
478 d.removedApiFile = android.PathForModuleSrc(ctx, sourceRemovedApiFile)
479 } else if stubsType == Exportable {
480 d.exportableRemovedApiFile = uncheckedRemovedFile
481 }
Colin Cross2207f872021-03-24 12:39:08 -0700482 }
483
Colin Cross2207f872021-03-24 12:39:08 -0700484 if stubsDir.Valid() {
485 if Bool(d.properties.Create_doc_stubs) {
486 cmd.FlagWithArg("--doc-stubs ", stubsDir.String())
487 } else {
488 cmd.FlagWithArg("--stubs ", stubsDir.String())
489 if !Bool(d.properties.Output_javadoc_comments) {
490 cmd.Flag("--exclude-documentation-from-stubs")
491 }
492 }
493 }
494}
495
Jihoon Kang3c89f042023-12-19 02:40:22 +0000496func (d *Droidstubs) annotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, params annotationFlagsParams) {
Jihoon Kanga11d6792024-03-05 16:12:20 +0000497 if Bool(d.properties.Annotations_enabled) {
498 cmd.Flag(config.MetalavaAnnotationsFlags)
Andrei Onea4985e512021-04-29 16:29:34 +0100499
Jihoon Kanga11d6792024-03-05 16:12:20 +0000500 if params.migratingNullability {
Jihoon Kang5623e542024-01-31 23:27:26 +0000501 previousApiFiles := android.PathsForModuleSrc(ctx, []string{String(d.properties.Previous_api)})
502 cmd.FlagForEachInput("--migrate-nullness ", previousApiFiles)
Jihoon Kanga11d6792024-03-05 16:12:20 +0000503 }
Jihoon Kang6b93b382024-01-26 22:37:41 +0000504
Jihoon Kanga11d6792024-03-05 16:12:20 +0000505 if s := String(d.properties.Validate_nullability_from_list); s != "" {
506 cmd.FlagWithInput("--validate-nullability-from-list ", android.PathForModuleSrc(ctx, s))
507 }
Jihoon Kang6b93b382024-01-26 22:37:41 +0000508
Jihoon Kanga11d6792024-03-05 16:12:20 +0000509 if params.validatingNullability {
510 cmd.FlagWithOutput("--nullability-warnings-txt ", params.nullabilityWarningsFile)
511 }
Jihoon Kang6b93b382024-01-26 22:37:41 +0000512
Jihoon Kangca2f9e82024-01-26 01:45:12 +0000513 cmd.FlagWithOutput("--extract-annotations ", params.annotationsZip)
Jihoon Kang6b93b382024-01-26 22:37:41 +0000514
Jihoon Kanga11d6792024-03-05 16:12:20 +0000515 if len(d.properties.Merge_annotations_dirs) != 0 {
516 d.mergeAnnoDirFlags(ctx, cmd)
517 }
Jihoon Kang6b93b382024-01-26 22:37:41 +0000518
Jihoon Kanga11d6792024-03-05 16:12:20 +0000519 cmd.Flag(config.MetalavaAnnotationsWarningsFlags)
Colin Cross2207f872021-03-24 12:39:08 -0700520 }
Colin Cross2207f872021-03-24 12:39:08 -0700521}
522
523func (d *Droidstubs) mergeAnnoDirFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
Yu Liu3a892962025-01-15 23:14:27 +0000524 ctx.VisitDirectDepsProxyWithTag(metalavaMergeAnnotationsDirTag, func(m android.ModuleProxy) {
525 if t, ok := android.OtherModuleProvider(ctx, m, ExportedDroiddocDirInfoProvider); ok {
526 cmd.FlagWithArg("--merge-qualifier-annotations ", t.Dir.String()).Implicits(t.Deps)
Colin Cross2207f872021-03-24 12:39:08 -0700527 } else {
528 ctx.PropertyErrorf("merge_annotations_dirs",
529 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
530 }
531 })
532}
533
534func (d *Droidstubs) inclusionAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
Yu Liu3a892962025-01-15 23:14:27 +0000535 ctx.VisitDirectDepsProxyWithTag(metalavaMergeInclusionAnnotationsDirTag, func(m android.ModuleProxy) {
536 if t, ok := android.OtherModuleProvider(ctx, m, ExportedDroiddocDirInfoProvider); ok {
537 cmd.FlagWithArg("--merge-inclusion-annotations ", t.Dir.String()).Implicits(t.Deps)
Colin Cross2207f872021-03-24 12:39:08 -0700538 } else {
539 ctx.PropertyErrorf("merge_inclusion_annotations_dirs",
540 "module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
541 }
542 })
543}
544
Jihoon Kanga11d6792024-03-05 16:12:20 +0000545func (d *Droidstubs) apiLevelsAnnotationsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsType StubsType, apiVersionsXml android.WritablePath) {
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000546 var apiVersions android.Path
Jihoon Kanga11d6792024-03-05 16:12:20 +0000547 if proptools.Bool(d.properties.Api_levels_annotations_enabled) {
Jihoon Kang3c89f042023-12-19 02:40:22 +0000548 d.apiLevelsGenerationFlags(ctx, cmd, stubsType, apiVersionsXml)
Jihoon Kangd9a06942024-01-26 01:49:20 +0000549 apiVersions = apiVersionsXml
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000550 } else {
Yu Liu3a892962025-01-15 23:14:27 +0000551 ctx.VisitDirectDepsProxyWithTag(metalavaAPILevelsModuleTag, func(m android.ModuleProxy) {
552 if s, ok := android.OtherModuleProvider(ctx, m, DroidStubsInfoProvider); ok {
Jihoon Kangd9a06942024-01-26 01:49:20 +0000553 if stubsType == Everything {
Yu Liu35acd332025-01-24 23:11:22 +0000554 apiVersions = s.EverythingStubsInfo.ApiVersionsXml
Jihoon Kangd9a06942024-01-26 01:49:20 +0000555 } else if stubsType == Exportable {
Yu Liu35acd332025-01-24 23:11:22 +0000556 apiVersions = s.ExportableStubsInfo.ApiVersionsXml
Jihoon Kangd9a06942024-01-26 01:49:20 +0000557 } else {
Jihoon Kangd40c5912024-03-05 16:12:20 +0000558 ctx.ModuleErrorf("%s stubs type does not generate api-versions.xml file", stubsType.String())
Jihoon Kangd9a06942024-01-26 01:49:20 +0000559 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000560 } else {
561 ctx.PropertyErrorf("api_levels_module",
562 "module %q is not a droidstubs module", ctx.OtherModuleName(m))
563 }
564 })
Colin Cross2207f872021-03-24 12:39:08 -0700565 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000566 if apiVersions != nil {
MÃ¥rten Kongstad13ae6872025-02-18 16:58:36 +0100567 // We are migrating from a single API level to major.minor
568 // versions and PlatformSdkVersionFull is not yet set in all
569 // release configs. If it is not set, fall back on the single
570 // API level.
571 if fullSdkVersion := ctx.Config().PlatformSdkVersionFull(); len(fullSdkVersion) > 0 {
572 cmd.FlagWithArg("--current-version ", fullSdkVersion)
573 } else {
574 cmd.FlagWithArg("--current-version ", ctx.Config().PlatformSdkVersion().String())
575 }
Linus Tufvesson45fc16c2025-01-29 14:04:24 +0100576 if ctx.Config().PlatformSdkVersion().String() != "36" || ctx.Config().PlatformSdkCodename() != "Baklava" {
577 cmd.FlagWithArg("--current-codename ", ctx.Config().PlatformSdkCodename())
578 }
Anton Hanssonc04a16e2022-05-09 09:30:26 +0000579 cmd.FlagWithInput("--apply-api-levels ", apiVersions)
580 }
581}
Colin Cross2207f872021-03-24 12:39:08 -0700582
Paul Duffin5a195f42024-05-01 12:52:35 +0100583// AndroidPlusUpdatableJar is the name of some extra jars added into `module-lib` and
584// `system-server` directories that contain all the APIs provided by the platform and updatable
585// modules because the `android.jar` files do not. See b/337836752.
586const AndroidPlusUpdatableJar = "android-plus-updatable.jar"
587
Jihoon Kang3c89f042023-12-19 02:40:22 +0000588func (d *Droidstubs) apiLevelsGenerationFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsType StubsType, apiVersionsXml android.WritablePath) {
Colin Cross2207f872021-03-24 12:39:08 -0700589 if len(d.properties.Api_levels_annotations_dirs) == 0 {
590 ctx.PropertyErrorf("api_levels_annotations_dirs",
591 "has to be non-empty if api levels annotations was enabled!")
592 }
593
Jihoon Kang3c89f042023-12-19 02:40:22 +0000594 cmd.FlagWithOutput("--generate-api-levels ", apiVersionsXml)
Colin Cross2207f872021-03-24 12:39:08 -0700595
596 filename := proptools.StringDefault(d.properties.Api_levels_jar_filename, "android.jar")
597
Paul Duffin58cfc9a2024-04-25 17:01:49 +0100598 // TODO: Avoid the duplication of API surfaces, reuse apiScope.
599 // Add all relevant --android-jar-pattern patterns for Metalava.
600 // When parsing a stub jar for a specific version, Metalava picks the first pattern that defines
601 // an actual file present on disk (in the order the patterns were passed). For system APIs for
602 // privileged apps that are only defined since API level 21 (Lollipop), fallback to public stubs
603 // for older releases. Similarly, module-lib falls back to system API.
604 var sdkDirs []string
Paul Duffin92efc612024-05-02 17:18:05 +0100605 apiLevelsSdkType := proptools.StringDefault(d.properties.Api_levels_sdk_type, "public")
606 switch apiLevelsSdkType {
Paul Duffin58cfc9a2024-04-25 17:01:49 +0100607 case "system-server":
608 sdkDirs = []string{"system-server", "module-lib", "system", "public"}
609 case "module-lib":
610 sdkDirs = []string{"module-lib", "system", "public"}
611 case "system":
612 sdkDirs = []string{"system", "public"}
613 case "public":
614 sdkDirs = []string{"public"}
615 default:
616 ctx.PropertyErrorf("api_levels_sdk_type", "needs to be one of %v", allowedApiLevelSdkTypes)
617 return
618 }
619
Paul Duffin92efc612024-05-02 17:18:05 +0100620 // Construct a pattern to match the appropriate extensions that should be included in the
621 // generated api-versions.xml file.
622 //
Paul Duffin58cfc9a2024-04-25 17:01:49 +0100623 // Use the first item in the sdkDirs array as that is the sdk type for the target API levels
624 // being generated but has the advantage over `Api_levels_sdk_type` as it has been validated.
Paul Duffin92efc612024-05-02 17:18:05 +0100625 // The exception is for system-server which needs to include module-lib and system-server. That
626 // is because while system-server extends module-lib the system-server extension directory only
627 // contains service-* modules which provide system-server APIs it does not list the modules which
628 // only provide a module-lib, so they have to be included separately.
629 extensionSurfacesPattern := sdkDirs[0]
630 if apiLevelsSdkType == "system-server" {
631 // Take the first two items in sdkDirs, which are system-server and module-lib, and construct
632 // a pattern that will match either.
633 extensionSurfacesPattern = strings.Join(sdkDirs[0:2], "|")
634 }
635 extensionsPattern := fmt.Sprintf(`/extensions/[0-9]+/(%s)/.*\.jar`, extensionSurfacesPattern)
Paul Duffin58cfc9a2024-04-25 17:01:49 +0100636
satayev783195c2021-06-23 21:49:57 +0100637 var dirs []string
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200638 var extensions_dir string
Yu Liu3a892962025-01-15 23:14:27 +0000639 ctx.VisitDirectDepsProxyWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.ModuleProxy) {
640 if t, ok := android.OtherModuleProvider(ctx, m, ExportedDroiddocDirInfoProvider); ok {
641 extRegex := regexp.MustCompile(t.Dir.String() + extensionsPattern)
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200642
643 // Grab the first extensions_dir and we find while scanning ExportedDroiddocDir.deps;
644 // ideally this should be read from prebuiltApis.properties.Extensions_*
Yu Liu3a892962025-01-15 23:14:27 +0000645 for _, dep := range t.Deps {
Paul Duffin2ced2eb2024-05-01 13:13:51 +0100646 // Check to see if it matches an extension first.
647 depBase := dep.Base()
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200648 if extRegex.MatchString(dep.String()) && d.properties.Extensions_info_file != nil {
649 if extensions_dir == "" {
Yu Liu3a892962025-01-15 23:14:27 +0000650 extensions_dir = t.Dir.String() + "/extensions"
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200651 }
652 cmd.Implicit(dep)
Paul Duffin2ced2eb2024-05-01 13:13:51 +0100653 } else if depBase == filename {
654 // Check to see if it matches a dessert release for an SDK, e.g. Android, Car, Wear, etc..
Colin Cross5f6ffc72021-03-29 21:54:45 -0700655 cmd.Implicit(dep)
Paul Duffin5a195f42024-05-01 12:52:35 +0100656 } else if depBase == AndroidPlusUpdatableJar && d.properties.Extensions_info_file != nil {
657 // The output api-versions.xml has been requested to include information on SDK
Paul Duffinee5e0932025-01-15 18:00:35 +0000658 // extensions, i.e. updatable Apis. That means it also needs to include the history of
659 // those updatable APIs. Usually, they would be included in the `android.jar` file but
660 // unfortunately, the `module-lib` and `system-server` cannot as it would lead to build
661 // cycles. So, the module-lib and system-server directories contain an
662 // `android-plus-updatable.jar` that should be used instead of `android.jar`. See
663 // AndroidPlusUpdatableJar for more information.
Paul Duffin5a195f42024-05-01 12:52:35 +0100664 cmd.Implicit(dep)
Colin Cross2207f872021-03-24 12:39:08 -0700665 }
666 }
satayev783195c2021-06-23 21:49:57 +0100667
Yu Liu3a892962025-01-15 23:14:27 +0000668 dirs = append(dirs, t.Dir.String())
Colin Cross2207f872021-03-24 12:39:08 -0700669 } else {
670 ctx.PropertyErrorf("api_levels_annotations_dirs",
671 "module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
672 }
673 })
satayev783195c2021-06-23 21:49:57 +0100674
Paul Duffin5a195f42024-05-01 12:52:35 +0100675 // Generate the list of --android-jar-pattern options. The order matters so the first one which
Paul Duffin4c9d3052025-01-07 16:03:10 +0000676 // matches will be the one that is used for a specific api level.
Pedro Loureirocc203502021-10-04 17:24:00 +0000677 for _, sdkDir := range sdkDirs {
678 for _, dir := range dirs {
Paul Duffin5a195f42024-05-01 12:52:35 +0100679 addPattern := func(jarFilename string) {
Paul Duffin9820c1a2025-01-20 10:35:45 +0000680 cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/{version:major.minor?}/%s/%s", dir, sdkDir, jarFilename))
Paul Duffin5a195f42024-05-01 12:52:35 +0100681 }
682
683 if sdkDir == "module-lib" || sdkDir == "system-server" {
684 // The module-lib and system-server android.jars do not include the updatable modules (as
685 // doing so in the source would introduce dependency cycles and the prebuilts have to
686 // match the sources). So, instead an additional `android-plus-updatable.jar` will be used
687 // that does include the updatable modules and this pattern will match that. This pattern
688 // is added in addition to the following pattern to decouple this change from the change
689 // to add the `android-plus-updatable.jar`.
690 addPattern(AndroidPlusUpdatableJar)
691 }
692
693 addPattern(filename)
Pedro Loureirocc203502021-10-04 17:24:00 +0000694 }
Paul Duffin4f707292025-01-16 14:12:31 +0000695
696 if extensions_dir != "" {
697 cmd.FlagWithArg("--android-jar-pattern ", fmt.Sprintf("%s/{version:extension}/%s/{module}.jar", extensions_dir, sdkDir))
698 }
satayev783195c2021-06-23 21:49:57 +0100699 }
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200700
701 if d.properties.Extensions_info_file != nil {
702 if extensions_dir == "" {
703 ctx.ModuleErrorf("extensions_info_file set, but no SDK extension dirs found")
704 }
705 info_file := android.PathForModuleSrc(ctx, *d.properties.Extensions_info_file)
706 cmd.Implicit(info_file)
MÃ¥rten Kongstad802ae0f2022-07-27 13:47:32 +0200707 cmd.FlagWithArg("--sdk-extensions-info ", info_file.String())
708 }
Colin Cross2207f872021-03-24 12:39:08 -0700709}
710
Jihoon Kang472f73f2024-03-28 20:59:29 +0000711func (d *Droidstubs) apiCompatibilityFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsType StubsType) {
712 if len(d.Javadoc.properties.Out) > 0 {
713 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
714 }
715
Jihoon Kang5623e542024-01-31 23:27:26 +0000716 apiFiles := android.PathsForModuleSrc(ctx, []string{String(d.properties.Check_api.Last_released.Api_file)})
717 removedApiFiles := android.PathsForModuleSrc(ctx, []string{String(d.properties.Check_api.Last_released.Removed_api_file)})
Jihoon Kang472f73f2024-03-28 20:59:29 +0000718
Jihoon Kang5623e542024-01-31 23:27:26 +0000719 cmd.FlagForEachInput("--check-compatibility:api:released ", apiFiles)
720 cmd.FlagForEachInput("--check-compatibility:removed:released ", removedApiFiles)
Jihoon Kang472f73f2024-03-28 20:59:29 +0000721
722 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
723 if baselineFile.Valid() {
724 cmd.FlagWithInput("--baseline:compatibility:released ", baselineFile.Path())
725 }
726}
727
Colin Crosse52c2ac2022-03-28 17:03:35 -0700728func metalavaUseRbe(ctx android.ModuleContext) bool {
729 return ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_METALAVA")
730}
731
Jihoon Kang421c1cd2024-04-22 21:17:12 +0000732func metalavaCmd(ctx android.ModuleContext, rule *android.RuleBuilder, srcs android.Paths,
Paul Duffind71dc402025-01-24 16:10:09 +0000733 srcJarList android.Path, homeDir android.WritablePath, params stubsCommandConfigParams,
734 configFiles android.Paths, apiSurface *string) *android.RuleBuilderCommand {
Colin Cross2207f872021-03-24 12:39:08 -0700735 rule.Command().Text("rm -rf").Flag(homeDir.String())
736 rule.Command().Text("mkdir -p").Flag(homeDir.String())
737
Anton Hansson556e8142021-06-04 16:20:25 +0100738 cmd := rule.Command()
Colin Cross2207f872021-03-24 12:39:08 -0700739 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
740
Colin Crosse52c2ac2022-03-28 17:03:35 -0700741 if metalavaUseRbe(ctx) {
Colin Cross2207f872021-03-24 12:39:08 -0700742 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
Colin Cross8095c292021-03-30 16:40:48 -0700743 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
Anas Sulaiman9d7a36d2023-11-21 23:00:07 +0000744 compare := ctx.Config().IsEnvTrue("RBE_METALAVA_COMPARE")
745 remoteUpdateCache := !ctx.Config().IsEnvFalse("RBE_METALAVA_REMOTE_UPDATE_CACHE")
Colin Cross8095c292021-03-30 16:40:48 -0700746 labels := map[string]string{"type": "tool", "name": "metalava"}
747 // TODO: metalava pool rejects these jobs
748 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
749 rule.Rewrapper(&remoteexec.REParams{
Anas Sulaiman9d7a36d2023-11-21 23:00:07 +0000750 Labels: labels,
751 ExecStrategy: execStrategy,
752 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
753 Platform: map[string]string{remoteexec.PoolKey: pool},
754 Compare: compare,
755 NumLocalRuns: 1,
756 NumRemoteRuns: 1,
757 NoRemoteUpdateCache: !remoteUpdateCache,
Colin Cross8095c292021-03-30 16:40:48 -0700758 })
Colin Cross2207f872021-03-24 12:39:08 -0700759 }
760
Colin Cross6aa5c402021-03-24 12:28:50 -0700761 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
Colin Cross2207f872021-03-24 12:39:08 -0700762 Flag(config.JavacVmFlags).
Liz Kammere09e20e2023-10-16 15:07:54 -0400763 Flag(config.MetalavaAddOpens).
Jihoon Kang421c1cd2024-04-22 21:17:12 +0000764 FlagWithArg("--java-source ", params.javaVersion.String()).
765 FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, fmt.Sprintf("%s.metalava.rsp", params.stubsType.String())), srcs).
Colin Cross2207f872021-03-24 12:39:08 -0700766 FlagWithInput("@", srcJarList)
767
Paul Duffinf8aaaa12023-08-10 15:16:35 +0100768 // Metalava does not differentiate between bootclasspath and classpath and has not done so for
769 // years, so it is unlikely to change any time soon.
Jihoon Kang421c1cd2024-04-22 21:17:12 +0000770 combinedPaths := append(([]android.Path)(nil), params.deps.bootClasspath.Paths()...)
771 combinedPaths = append(combinedPaths, params.deps.classpath.Paths()...)
Paul Duffinf8aaaa12023-08-10 15:16:35 +0100772 if len(combinedPaths) > 0 {
773 cmd.FlagWithInputList("--classpath ", combinedPaths, ":")
Colin Cross2207f872021-03-24 12:39:08 -0700774 }
775
Liz Kammere09e20e2023-10-16 15:07:54 -0400776 cmd.Flag(config.MetalavaFlags)
Jihoon Kangc8313892023-09-20 00:54:47 +0000777
Paul Duffin27819362024-07-22 21:03:50 +0100778 addMetalavaConfigFilesToCmd(cmd, configFiles)
779
Paul Duffind71dc402025-01-24 16:10:09 +0000780 addOptionalApiSurfaceToCmd(cmd, apiSurface)
781
Colin Cross2207f872021-03-24 12:39:08 -0700782 return cmd
783}
784
Paul Duffin27819362024-07-22 21:03:50 +0100785// MetalavaConfigFilegroup is the name of the filegroup in build/soong/java/metalava that lists
786// the configuration files to pass to Metalava.
787const MetalavaConfigFilegroup = "metalava-config-files"
788
789// Get a reference to the MetalavaConfigFilegroup suitable for use in a property.
790func getMetalavaConfigFilegroupReference() []string {
791 return []string{":" + MetalavaConfigFilegroup}
792}
793
794// addMetalavaConfigFilesToCmd adds --config-file options to use the config files list in the
795// MetalavaConfigFilegroup filegroup.
796func addMetalavaConfigFilesToCmd(cmd *android.RuleBuilderCommand, configFiles android.Paths) {
797 cmd.FlagForEachInput("--config-file ", configFiles)
798}
799
Paul Duffind71dc402025-01-24 16:10:09 +0000800// addOptionalApiSurfaceToCmd adds --api-surface option is apiSurface is not `nil`.
801func addOptionalApiSurfaceToCmd(cmd *android.RuleBuilderCommand, apiSurface *string) {
802 if apiSurface != nil {
803 cmd.Flag("--api-surface")
804 cmd.Flag(*apiSurface)
805 }
806}
807
Jihoon Kang3c89f042023-12-19 02:40:22 +0000808// Pass flagged apis related flags to metalava. When aconfig_declarations property is not
809// defined for a module, simply revert all flagged apis annotations. If aconfig_declarations
810// property is defined, apply transformations and only revert the flagged apis that are not
811// enabled via release configurations and are not specified in aconfig_declarations
Jihoon Kang5d701272024-02-15 21:53:49 +0000812func generateRevertAnnotationArgs(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsType StubsType, aconfigFlagsPaths android.Paths) {
Jihoon Kang6592e872023-12-19 01:13:16 +0000813 var filterArgs string
814 switch stubsType {
815 // No flagged apis specific flags need to be passed to metalava when generating
816 // everything stubs
817 case Everything:
818 return
819
820 case Runtime:
821 filterArgs = "--filter='state:ENABLED+permission:READ_ONLY' --filter='permission:READ_WRITE'"
822
823 case Exportable:
Jihoon Kang59198152024-02-06 22:43:18 +0000824 // When the build flag RELEASE_EXPORT_RUNTIME_APIS is set to true, apis marked with
825 // the flagged apis that have read_write permissions are exposed on top of the enabled
826 // and read_only apis. This is to support local override of flag values at runtime.
827 if ctx.Config().ReleaseExportRuntimeApis() {
828 filterArgs = "--filter='state:ENABLED+permission:READ_ONLY' --filter='permission:READ_WRITE'"
829 } else {
830 filterArgs = "--filter='state:ENABLED+permission:READ_ONLY'"
831 }
Jihoon Kang6592e872023-12-19 01:13:16 +0000832 }
833
Jihoon Kangf1e0ff02024-11-20 21:10:40 +0000834 if len(aconfigFlagsPaths) == 0 {
835 // This argument should not be added for "everything" stubs
836 cmd.Flag("--revert-annotation android.annotation.FlaggedApi")
837 return
838 }
839
840 releasedFlaggedApisFile := android.PathForModuleOut(ctx, fmt.Sprintf("released-flagged-apis-%s.txt", stubsType.String()))
841 revertAnnotationsFile := android.PathForModuleOut(ctx, fmt.Sprintf("revert-annotations-%s.txt", stubsType.String()))
842
Jihoon Kang6592e872023-12-19 01:13:16 +0000843 ctx.Build(pctx, android.BuildParams{
844 Rule: gatherReleasedFlaggedApisRule,
845 Inputs: aconfigFlagsPaths,
846 Output: releasedFlaggedApisFile,
847 Description: fmt.Sprintf("%s gather aconfig flags", stubsType),
848 Args: map[string]string{
849 "flags_path": android.JoinPathsWithPrefix(aconfigFlagsPaths, "--cache "),
850 "filter_args": filterArgs,
851 },
852 })
853
854 ctx.Build(pctx, android.BuildParams{
855 Rule: generateMetalavaRevertAnnotationsRule,
856 Input: releasedFlaggedApisFile,
857 Output: revertAnnotationsFile,
858 Description: fmt.Sprintf("%s revert annotations", stubsType),
859 })
Jihoon Kang3c89f042023-12-19 02:40:22 +0000860
861 cmd.FlagWithInput("@", revertAnnotationsFile)
Jihoon Kang6592e872023-12-19 01:13:16 +0000862}
863
Jihoon Kang3c89f042023-12-19 02:40:22 +0000864func (d *Droidstubs) commonMetalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
865 params stubsCommandParams) *android.RuleBuilderCommand {
Colin Cross2207f872021-03-24 12:39:08 -0700866 if BoolDefault(d.properties.High_mem, false) {
867 // This metalava run uses lots of memory, restrict the number of metalava jobs that can run in parallel.
868 rule.HighMem()
869 }
870
Jihoon Kang3c89f042023-12-19 02:40:22 +0000871 if params.stubConfig.generateStubs {
872 rule.Command().Text("rm -rf").Text(params.stubsDir.String())
873 rule.Command().Text("mkdir -p").Text(params.stubsDir.String())
Colin Cross2207f872021-03-24 12:39:08 -0700874 }
875
Jihoon Kang3c89f042023-12-19 02:40:22 +0000876 srcJarList := zipSyncCmd(ctx, rule, params.srcJarDir, d.Javadoc.srcJars)
Colin Cross2207f872021-03-24 12:39:08 -0700877
Jihoon Kang3c89f042023-12-19 02:40:22 +0000878 homeDir := android.PathForModuleOut(ctx, params.stubConfig.stubsType.String(), "home")
Paul Duffin27819362024-07-22 21:03:50 +0100879
880 configFiles := android.PathsForModuleSrc(ctx, d.properties.ConfigFiles)
881
Paul Duffind71dc402025-01-24 16:10:09 +0000882 cmd := metalavaCmd(ctx, rule, d.Javadoc.srcFiles, srcJarList, homeDir, params.stubConfig,
883 configFiles, d.properties.Api_surface)
Colin Cross2207f872021-03-24 12:39:08 -0700884 cmd.Implicits(d.Javadoc.implicits)
885
Jihoon Kang3c89f042023-12-19 02:40:22 +0000886 d.stubsFlags(ctx, cmd, params.stubsDir, params.stubConfig.stubsType, params.stubConfig.checkApi)
Colin Cross2207f872021-03-24 12:39:08 -0700887
Jihoon Kang3c89f042023-12-19 02:40:22 +0000888 if params.stubConfig.writeSdkValues {
889 d.sdkValuesFlags(ctx, cmd, params.metadataDir)
890 }
891
892 annotationParams := annotationFlagsParams{
893 migratingNullability: params.stubConfig.migratingNullability,
894 validatingNullability: params.stubConfig.validatingNullability,
895 nullabilityWarningsFile: params.nullabilityWarningsFile,
896 annotationsZip: params.annotationsZip,
897 }
898
Jihoon Kanga11d6792024-03-05 16:12:20 +0000899 d.annotationsFlags(ctx, cmd, annotationParams)
Colin Cross2207f872021-03-24 12:39:08 -0700900 d.inclusionAnnotationsFlags(ctx, cmd)
Jihoon Kanga11d6792024-03-05 16:12:20 +0000901 d.apiLevelsAnnotationsFlags(ctx, cmd, params.stubConfig.stubsType, params.apiVersionsXml)
Colin Cross2207f872021-03-24 12:39:08 -0700902
Jihoon Kang472f73f2024-03-28 20:59:29 +0000903 if params.stubConfig.doCheckReleased {
904 d.apiCompatibilityFlags(ctx, cmd, params.stubConfig.stubsType)
905 }
906
Colin Crossbc139922021-03-25 18:33:16 -0700907 d.expandArgs(ctx, cmd)
Colin Cross2207f872021-03-24 12:39:08 -0700908
Colin Cross2207f872021-03-24 12:39:08 -0700909 for _, o := range d.Javadoc.properties.Out {
910 cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
911 }
912
Jihoon Kang3c89f042023-12-19 02:40:22 +0000913 return cmd
914}
Colin Cross2207f872021-03-24 12:39:08 -0700915
Jihoon Kang3c89f042023-12-19 02:40:22 +0000916// Sandbox rule for generating the everything stubs and other artifacts
917func (d *Droidstubs) everythingStubCmd(ctx android.ModuleContext, params stubsCommandConfigParams) {
918 srcJarDir := android.PathForModuleOut(ctx, Everything.String(), "srcjars")
919 rule := android.NewRuleBuilder(pctx, ctx)
920 rule.Sbox(android.PathForModuleOut(ctx, Everything.String()),
921 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
922 SandboxInputs()
923
924 var stubsDir android.OptionalPath
925 if params.generateStubs {
926 stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, Everything.String(), "stubsDir"))
927 d.Javadoc.stubsSrcJar = android.PathForModuleOut(ctx, Everything.String(), ctx.ModuleName()+"-"+"stubs.srcjar")
928 }
929
930 if params.writeSdkValues {
Jihoon Kangee113282024-01-23 00:16:41 +0000931 d.everythingArtifacts.metadataDir = android.PathForModuleOut(ctx, Everything.String(), "metadata")
932 d.everythingArtifacts.metadataZip = android.PathForModuleOut(ctx, Everything.String(), ctx.ModuleName()+"-metadata.zip")
Jihoon Kang3c89f042023-12-19 02:40:22 +0000933 }
934
Jihoon Kanga11d6792024-03-05 16:12:20 +0000935 if Bool(d.properties.Annotations_enabled) {
Jihoon Kang3c89f042023-12-19 02:40:22 +0000936 if params.validatingNullability {
Jihoon Kangee113282024-01-23 00:16:41 +0000937 d.everythingArtifacts.nullabilityWarningsFile = android.PathForModuleOut(ctx, Everything.String(), ctx.ModuleName()+"_nullability_warnings.txt")
Jihoon Kang3c89f042023-12-19 02:40:22 +0000938 }
Jihoon Kangee113282024-01-23 00:16:41 +0000939 d.everythingArtifacts.annotationsZip = android.PathForModuleOut(ctx, Everything.String(), ctx.ModuleName()+"_annotations.zip")
Jihoon Kang3c89f042023-12-19 02:40:22 +0000940 }
Jihoon Kanga11d6792024-03-05 16:12:20 +0000941 if Bool(d.properties.Api_levels_annotations_enabled) {
Jihoon Kangee113282024-01-23 00:16:41 +0000942 d.everythingArtifacts.apiVersionsXml = android.PathForModuleOut(ctx, Everything.String(), "api-versions.xml")
Jihoon Kang3c89f042023-12-19 02:40:22 +0000943 }
944
945 commonCmdParams := stubsCommandParams{
946 srcJarDir: srcJarDir,
947 stubsDir: stubsDir,
948 stubsSrcJar: d.Javadoc.stubsSrcJar,
Jihoon Kangee113282024-01-23 00:16:41 +0000949 metadataDir: d.everythingArtifacts.metadataDir,
950 apiVersionsXml: d.everythingArtifacts.apiVersionsXml,
951 nullabilityWarningsFile: d.everythingArtifacts.nullabilityWarningsFile,
952 annotationsZip: d.everythingArtifacts.annotationsZip,
Jihoon Kang3c89f042023-12-19 02:40:22 +0000953 stubConfig: params,
954 }
955
956 cmd := d.commonMetalavaStubCmd(ctx, rule, commonCmdParams)
957
958 d.everythingOptionalCmd(ctx, cmd, params.doApiLint, params.doCheckReleased)
959
960 if params.generateStubs {
961 rule.Command().
962 BuiltTool("soong_zip").
963 Flag("-write_if_changed").
964 Flag("-jar").
965 FlagWithOutput("-o ", d.Javadoc.stubsSrcJar).
966 FlagWithArg("-C ", stubsDir.String()).
967 FlagWithArg("-D ", stubsDir.String())
968 }
969
970 if params.writeSdkValues {
971 rule.Command().
972 BuiltTool("soong_zip").
973 Flag("-write_if_changed").
974 Flag("-d").
Jihoon Kangee113282024-01-23 00:16:41 +0000975 FlagWithOutput("-o ", d.everythingArtifacts.metadataZip).
976 FlagWithArg("-C ", d.everythingArtifacts.metadataDir.String()).
977 FlagWithArg("-D ", d.everythingArtifacts.metadataDir.String())
Jihoon Kang3c89f042023-12-19 02:40:22 +0000978 }
979
980 // TODO: We don't really need two separate API files, but this is a reminiscence of how
981 // we used to run metalava separately for API lint and the "last_released" check. Unify them.
982 if params.doApiLint {
983 rule.Command().Text("touch").Output(d.apiLintTimestamp)
984 }
985 if params.doCheckReleased {
986 rule.Command().Text("touch").Output(d.checkLastReleasedApiTimestamp)
987 }
988
989 // TODO(b/183630617): rewrapper doesn't support restat rules
990 if !metalavaUseRbe(ctx) {
991 rule.Restat()
992 }
993
994 zipSyncCleanupCmd(rule, srcJarDir)
995
996 rule.Build("metalava", "metalava merged")
997}
998
999// Sandbox rule for generating the everything artifacts that are not run by
1000// default but only run based on the module configurations
1001func (d *Droidstubs) everythingOptionalCmd(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, doApiLint bool, doCheckReleased bool) {
Colin Cross2207f872021-03-24 12:39:08 -07001002
1003 // Add API lint options.
Paul Duffinbaf34782024-05-28 17:27:22 +01001004 treatDocumentationIssuesAsErrors := false
Jihoon Kang3c89f042023-12-19 02:40:22 +00001005 if doApiLint {
Jihoon Kang5623e542024-01-31 23:27:26 +00001006 var newSince android.Paths
1007 if d.properties.Check_api.Api_lint.New_since != nil {
1008 newSince = android.PathsForModuleSrc(ctx, []string{proptools.String(d.properties.Check_api.Api_lint.New_since)})
1009 }
Paul Duffin0a71d732024-04-22 13:22:56 +01001010 cmd.Flag("--api-lint")
1011 cmd.FlagForEachInput("--api-lint-previous-api ", newSince)
Jihoon Kang3c89f042023-12-19 02:40:22 +00001012 d.apiLintReport = android.PathForModuleOut(ctx, Everything.String(), "api_lint_report.txt")
Colin Cross2207f872021-03-24 12:39:08 -07001013 cmd.FlagWithOutput("--report-even-if-suppressed ", d.apiLintReport) // TODO: Change to ":api-lint"
1014
Paul Duffinc540bee2024-08-29 15:35:58 +01001015 // If UnflaggedApi issues have not already been configured then make sure that existing
1016 // UnflaggedApi issues are reported as warnings but issues in new/changed code are treated as
1017 // errors by the Build Warnings Aye Aye Analyzer in Gerrit.
Paul Duffin88d3b392024-08-28 17:37:36 +01001018 // Once existing issues have been fixed this will be changed to error.
Paul Duffinc540bee2024-08-29 15:35:58 +01001019 // TODO(b/362771529): Switch to --error
1020 if !strings.Contains(cmd.String(), " UnflaggedApi ") {
1021 cmd.Flag("--error-when-new UnflaggedApi")
1022 }
Paul Duffin88d3b392024-08-28 17:37:36 +01001023
Colin Cross0d532412021-03-25 09:38:45 -07001024 // TODO(b/154317059): Clean up this allowlist by baselining and/or checking in last-released.
Colin Cross2207f872021-03-24 12:39:08 -07001025 if d.Name() != "android.car-system-stubs-docs" &&
1026 d.Name() != "android.car-stubs-docs" {
Paul Duffinbaf34782024-05-28 17:27:22 +01001027 treatDocumentationIssuesAsErrors = true
Colin Cross2207f872021-03-24 12:39:08 -07001028 cmd.Flag("--warnings-as-errors") // Most lints are actually warnings.
1029 }
1030
1031 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
Jihoon Kang3c89f042023-12-19 02:40:22 +00001032 updatedBaselineOutput := android.PathForModuleOut(ctx, Everything.String(), "api_lint_baseline.txt")
1033 d.apiLintTimestamp = android.PathForModuleOut(ctx, Everything.String(), "api_lint.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -07001034
1035 // Note this string includes a special shell quote $' ... ', which decodes the "\n"s.
Colin Cross2207f872021-03-24 12:39:08 -07001036 //
1037 // TODO: metalava also has a slightly different message hardcoded. Should we unify this
1038 // message and metalava's one?
1039 msg := `$'` + // Enclose with $' ... '
1040 `************************************************************\n` +
1041 `Your API changes are triggering API Lint warnings or errors.\n` +
Colin Cross2207f872021-03-24 12:39:08 -07001042 `\n` +
Adrian Roos40be6472024-11-05 14:25:35 +00001043 `To make the failures go away:\n` +
Colin Cross2207f872021-03-24 12:39:08 -07001044 `\n` +
Adrian Roos40be6472024-11-05 14:25:35 +00001045 `1. REQUIRED: Read the messages carefully and address them by` +
1046 ` fixing the API if appropriate.\n` +
1047 `2. If the failure is a false positive, you can suppress it with:\n` +
1048 ` @SuppressLint("<id>")\n` +
Aurimas Liutikasb23b7452021-05-24 18:00:37 +00001049 ` where the <id> is given in brackets in the error message above.\n`
Colin Cross2207f872021-03-24 12:39:08 -07001050
1051 if baselineFile.Valid() {
1052 cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
1053 cmd.FlagWithOutput("--update-baseline:api-lint ", updatedBaselineOutput)
1054
1055 msg += fmt.Sprintf(``+
Cole Faust5146e782024-11-15 14:47:49 -08001056 `3. FOR LSC ONLY: You can update the baseline by executing\n`+
Adrian Roos40be6472024-11-05 14:25:35 +00001057 ` the following command:\n`+
Colin Cross63eeda02021-04-15 19:01:57 -07001058 ` (cd $ANDROID_BUILD_TOP && cp \\\n`+
1059 ` "%s" \\\n`+
1060 ` "%s")\n`+
Colin Cross2207f872021-03-24 12:39:08 -07001061 ` To submit the revised baseline.txt to the main Android\n`+
1062 ` repository, you will need approval.\n`, updatedBaselineOutput, baselineFile.Path())
1063 } else {
1064 msg += fmt.Sprintf(``+
Adrian Roos40be6472024-11-05 14:25:35 +00001065 `3. FOR LSC ONLY: You can add a baseline file of existing lint failures\n`+
Colin Cross2207f872021-03-24 12:39:08 -07001066 ` to the build rule of %s.\n`, d.Name())
1067 }
1068 // Note the message ends with a ' (single quote), to close the $' ... ' .
1069 msg += `************************************************************\n'`
1070
1071 cmd.FlagWithArg("--error-message:api-lint ", msg)
1072 }
1073
Paul Duffinbaf34782024-05-28 17:27:22 +01001074 if !treatDocumentationIssuesAsErrors {
Paul Duffinb679bdd2024-06-10 14:29:41 +01001075 treatDocumentationIssuesAsWarningErrorWhenNew(cmd)
Paul Duffinbaf34782024-05-28 17:27:22 +01001076 }
1077
Colin Cross2207f872021-03-24 12:39:08 -07001078 // Add "check released" options. (Detect incompatible API changes from the last public release)
Jihoon Kang3c89f042023-12-19 02:40:22 +00001079 if doCheckReleased {
Colin Cross2207f872021-03-24 12:39:08 -07001080 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Last_released.Baseline_file)
Jihoon Kang3c89f042023-12-19 02:40:22 +00001081 d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, Everything.String(), "check_last_released_api.timestamp")
Colin Cross2207f872021-03-24 12:39:08 -07001082 if baselineFile.Valid() {
Jihoon Kang472f73f2024-03-28 20:59:29 +00001083 updatedBaselineOutput := android.PathForModuleOut(ctx, Everything.String(), "last_released_baseline.txt")
Colin Cross2207f872021-03-24 12:39:08 -07001084 cmd.FlagWithOutput("--update-baseline:compatibility:released ", updatedBaselineOutput)
1085 }
Colin Cross2207f872021-03-24 12:39:08 -07001086 // Note this string includes quote ($' ... '), which decodes the "\n"s.
1087 msg := `$'\n******************************\n` +
1088 `You have tried to change the API from what has been previously released in\n` +
1089 `an SDK. Please fix the errors listed above.\n` +
1090 `******************************\n'`
1091
1092 cmd.FlagWithArg("--error-message:compatibility:released ", msg)
1093 }
1094
Paul Duffin10a23c22023-08-11 22:47:31 +01001095 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
1096 // Pass the current API file into metalava so it can use it as the basis for determining how to
1097 // generate the output signature files (both api and removed).
1098 currentApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
1099 cmd.FlagWithInput("--use-same-format-as ", currentApiFile)
1100 }
Jihoon Kang3c89f042023-12-19 02:40:22 +00001101}
Paul Duffin10a23c22023-08-11 22:47:31 +01001102
Paul Duffinb679bdd2024-06-10 14:29:41 +01001103// HIDDEN_DOCUMENTATION_ISSUES is the set of documentation related issues that should always be
1104// hidden as they are very noisy and provide little value.
1105var HIDDEN_DOCUMENTATION_ISSUES = []string{
1106 "Deprecated",
1107 "IntDef",
1108 "Nullable",
1109}
1110
1111func treatDocumentationIssuesAsWarningErrorWhenNew(cmd *android.RuleBuilderCommand) {
1112 // Treat documentation issues as warnings, but error when new.
1113 cmd.Flag("--error-when-new-category").Flag("Documentation")
1114
1115 // Hide some documentation issues that generated a lot of noise for little benefit.
1116 cmd.FlagForEachArg("--hide ", HIDDEN_DOCUMENTATION_ISSUES)
1117}
1118
Jihoon Kang3c89f042023-12-19 02:40:22 +00001119// Sandbox rule for generating exportable stubs and other artifacts
1120func (d *Droidstubs) exportableStubCmd(ctx android.ModuleContext, params stubsCommandConfigParams) {
1121 optionalCmdParams := stubsCommandParams{
1122 stubConfig: params,
1123 }
1124
Jihoon Kang246690a2024-02-01 21:55:01 +00001125 if params.generateStubs {
1126 d.Javadoc.exportableStubsSrcJar = android.PathForModuleOut(ctx, params.stubsType.String(), ctx.ModuleName()+"-"+"stubs.srcjar")
1127 optionalCmdParams.stubsSrcJar = d.Javadoc.exportableStubsSrcJar
1128 }
1129
Jihoon Kang3c89f042023-12-19 02:40:22 +00001130 if params.writeSdkValues {
Jihoon Kangee113282024-01-23 00:16:41 +00001131 d.exportableArtifacts.metadataZip = android.PathForModuleOut(ctx, params.stubsType.String(), ctx.ModuleName()+"-metadata.zip")
1132 d.exportableArtifacts.metadataDir = android.PathForModuleOut(ctx, params.stubsType.String(), "metadata")
1133 optionalCmdParams.metadataZip = d.exportableArtifacts.metadataZip
1134 optionalCmdParams.metadataDir = d.exportableArtifacts.metadataDir
Jihoon Kang3c89f042023-12-19 02:40:22 +00001135 }
1136
Jihoon Kanga11d6792024-03-05 16:12:20 +00001137 if Bool(d.properties.Annotations_enabled) {
Jihoon Kang3c89f042023-12-19 02:40:22 +00001138 if params.validatingNullability {
Jihoon Kangee113282024-01-23 00:16:41 +00001139 d.exportableArtifacts.nullabilityWarningsFile = android.PathForModuleOut(ctx, params.stubsType.String(), ctx.ModuleName()+"_nullability_warnings.txt")
1140 optionalCmdParams.nullabilityWarningsFile = d.exportableArtifacts.nullabilityWarningsFile
Jihoon Kang3c89f042023-12-19 02:40:22 +00001141 }
Jihoon Kangee113282024-01-23 00:16:41 +00001142 d.exportableArtifacts.annotationsZip = android.PathForModuleOut(ctx, params.stubsType.String(), ctx.ModuleName()+"_annotations.zip")
1143 optionalCmdParams.annotationsZip = d.exportableArtifacts.annotationsZip
Jihoon Kang3c89f042023-12-19 02:40:22 +00001144 }
Jihoon Kanga11d6792024-03-05 16:12:20 +00001145 if Bool(d.properties.Api_levels_annotations_enabled) {
Jihoon Kangee113282024-01-23 00:16:41 +00001146 d.exportableArtifacts.apiVersionsXml = android.PathForModuleOut(ctx, params.stubsType.String(), "api-versions.xml")
1147 optionalCmdParams.apiVersionsXml = d.exportableArtifacts.apiVersionsXml
Jihoon Kang3c89f042023-12-19 02:40:22 +00001148 }
1149
1150 if params.checkApi || String(d.properties.Api_filename) != "" {
1151 filename := proptools.StringDefault(d.properties.Api_filename, ctx.ModuleName()+"_api.txt")
1152 d.exportableApiFile = android.PathForModuleOut(ctx, params.stubsType.String(), filename)
1153 }
1154
1155 if params.checkApi || String(d.properties.Removed_api_filename) != "" {
1156 filename := proptools.StringDefault(d.properties.Removed_api_filename, ctx.ModuleName()+"_api.txt")
1157 d.exportableRemovedApiFile = android.PathForModuleOut(ctx, params.stubsType.String(), filename)
1158 }
1159
1160 d.optionalStubCmd(ctx, optionalCmdParams)
1161}
1162
1163func (d *Droidstubs) optionalStubCmd(ctx android.ModuleContext, params stubsCommandParams) {
1164
1165 params.srcJarDir = android.PathForModuleOut(ctx, params.stubConfig.stubsType.String(), "srcjars")
1166 rule := android.NewRuleBuilder(pctx, ctx)
1167 rule.Sbox(android.PathForModuleOut(ctx, params.stubConfig.stubsType.String()),
1168 android.PathForModuleOut(ctx, fmt.Sprintf("metalava_%s.sbox.textproto", params.stubConfig.stubsType.String()))).
1169 SandboxInputs()
1170
1171 if params.stubConfig.generateStubs {
1172 params.stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, params.stubConfig.stubsType.String(), "stubsDir"))
1173 }
1174
1175 cmd := d.commonMetalavaStubCmd(ctx, rule, params)
1176
Jihoon Kang5d701272024-02-15 21:53:49 +00001177 generateRevertAnnotationArgs(ctx, cmd, params.stubConfig.stubsType, params.stubConfig.deps.aconfigProtoFiles)
Jihoon Kang3c89f042023-12-19 02:40:22 +00001178
1179 if params.stubConfig.doApiLint {
1180 // Pass the lint baseline file as an input to resolve the lint errors.
1181 // The exportable stubs generation does not update the lint baseline file.
1182 // Lint baseline file update is handled by the everything stubs
1183 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Api_lint.Baseline_file)
1184 if baselineFile.Valid() {
1185 cmd.FlagWithInput("--baseline:api-lint ", baselineFile.Path())
1186 }
1187 }
1188
Paul Duffin71527b72024-05-31 13:30:32 +01001189 // Treat documentation issues as warnings, but error when new.
Paul Duffinb679bdd2024-06-10 14:29:41 +01001190 treatDocumentationIssuesAsWarningErrorWhenNew(cmd)
Paul Duffin71527b72024-05-31 13:30:32 +01001191
Jihoon Kang3c89f042023-12-19 02:40:22 +00001192 if params.stubConfig.generateStubs {
Colin Cross2207f872021-03-24 12:39:08 -07001193 rule.Command().
1194 BuiltTool("soong_zip").
1195 Flag("-write_if_changed").
1196 Flag("-jar").
Jihoon Kang3c89f042023-12-19 02:40:22 +00001197 FlagWithOutput("-o ", params.stubsSrcJar).
1198 FlagWithArg("-C ", params.stubsDir.String()).
1199 FlagWithArg("-D ", params.stubsDir.String())
Colin Cross2207f872021-03-24 12:39:08 -07001200 }
1201
Jihoon Kang3c89f042023-12-19 02:40:22 +00001202 if params.stubConfig.writeSdkValues {
Colin Cross2207f872021-03-24 12:39:08 -07001203 rule.Command().
1204 BuiltTool("soong_zip").
1205 Flag("-write_if_changed").
1206 Flag("-d").
Jihoon Kang3c89f042023-12-19 02:40:22 +00001207 FlagWithOutput("-o ", params.metadataZip).
1208 FlagWithArg("-C ", params.metadataDir.String()).
1209 FlagWithArg("-D ", params.metadataDir.String())
Colin Cross2207f872021-03-24 12:39:08 -07001210 }
1211
Colin Cross6aa5c402021-03-24 12:28:50 -07001212 // TODO(b/183630617): rewrapper doesn't support restat rules
Colin Crosse52c2ac2022-03-28 17:03:35 -07001213 if !metalavaUseRbe(ctx) {
1214 rule.Restat()
1215 }
Colin Cross2207f872021-03-24 12:39:08 -07001216
Jihoon Kang3c89f042023-12-19 02:40:22 +00001217 zipSyncCleanupCmd(rule, params.srcJarDir)
Colin Cross2207f872021-03-24 12:39:08 -07001218
Jihoon Kang3c89f042023-12-19 02:40:22 +00001219 rule.Build(fmt.Sprintf("metalava_%s", params.stubConfig.stubsType.String()), "metalava merged")
1220}
1221
Jihoon Kange9eecc72025-01-28 18:57:18 +00001222func (d *Droidstubs) setPhonyRules(ctx android.ModuleContext) {
1223 if d.apiFile != nil {
1224 ctx.Phony(d.Name(), d.apiFile)
1225 ctx.Phony(fmt.Sprintf("%s.txt", d.Name()), d.apiFile)
1226 }
1227 if d.removedApiFile != nil {
1228 ctx.Phony(d.Name(), d.removedApiFile)
1229 ctx.Phony(fmt.Sprintf("%s.txt", d.Name()), d.removedApiFile)
1230 }
1231 if d.checkCurrentApiTimestamp != nil {
1232 ctx.Phony(fmt.Sprintf("%s-check-current-api", d.Name()), d.checkCurrentApiTimestamp)
1233 ctx.Phony("checkapi", d.checkCurrentApiTimestamp)
Jihoon Kange9eecc72025-01-28 18:57:18 +00001234 }
1235 if d.updateCurrentApiTimestamp != nil {
1236 ctx.Phony(fmt.Sprintf("%s-update-current-api", d.Name()), d.updateCurrentApiTimestamp)
1237 ctx.Phony("update-api", d.updateCurrentApiTimestamp)
1238 }
1239 if d.checkLastReleasedApiTimestamp != nil {
1240 ctx.Phony(fmt.Sprintf("%s-check-last-released-api", d.Name()), d.checkLastReleasedApiTimestamp)
Jihoon Kange9eecc72025-01-28 18:57:18 +00001241 }
1242 if d.apiLintTimestamp != nil {
1243 ctx.Phony(fmt.Sprintf("%s-api-lint", d.Name()), d.apiLintTimestamp)
Jihoon Kange9eecc72025-01-28 18:57:18 +00001244 }
1245 if d.checkNullabilityWarningsTimestamp != nil {
1246 ctx.Phony(fmt.Sprintf("%s-check-nullability-warnings", d.Name()), d.checkNullabilityWarningsTimestamp)
Jihoon Kange9eecc72025-01-28 18:57:18 +00001247 }
1248}
1249
Jihoon Kang3c89f042023-12-19 02:40:22 +00001250func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1251 deps := d.Javadoc.collectDeps(ctx)
1252
1253 javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), android.SdkContext(d))
1254 generateStubs := BoolDefault(d.properties.Generate_stubs, true)
1255
1256 // Add options for the other optional tasks: API-lint and check-released.
1257 // We generate separate timestamp files for them.
1258 doApiLint := BoolDefault(d.properties.Check_api.Api_lint.Enabled, false)
1259 doCheckReleased := apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released")
1260
1261 writeSdkValues := Bool(d.properties.Write_sdk_values)
1262
1263 annotationsEnabled := Bool(d.properties.Annotations_enabled)
1264
1265 migratingNullability := annotationsEnabled && String(d.properties.Previous_api) != ""
1266 validatingNullability := annotationsEnabled && (strings.Contains(String(d.Javadoc.properties.Args), "--validate-nullability-from-merged-stubs") ||
1267 String(d.properties.Validate_nullability_from_list) != "")
1268
1269 checkApi := apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") ||
1270 apiCheckEnabled(ctx, d.properties.Check_api.Last_released, "last_released")
1271
1272 stubCmdParams := stubsCommandConfigParams{
Jihoon Kanga11d6792024-03-05 16:12:20 +00001273 javaVersion: javaVersion,
1274 deps: deps,
1275 checkApi: checkApi,
1276 generateStubs: generateStubs,
1277 doApiLint: doApiLint,
1278 doCheckReleased: doCheckReleased,
1279 writeSdkValues: writeSdkValues,
1280 migratingNullability: migratingNullability,
1281 validatingNullability: validatingNullability,
Jihoon Kang3c89f042023-12-19 02:40:22 +00001282 }
1283 stubCmdParams.stubsType = Everything
1284 // Create default (i.e. "everything" stubs) rule for metalava
1285 d.everythingStubCmd(ctx, stubCmdParams)
1286
Jihoon Kangd40c5912024-03-05 16:12:20 +00001287 // The module generates "exportable" (and "runtime" eventually) stubs regardless of whether
Jihoon Kang3c89f042023-12-19 02:40:22 +00001288 // aconfig_declarations property is defined or not. If the property is not defined, the module simply
1289 // strips all flagged apis to generate the "exportable" stubs
1290 stubCmdParams.stubsType = Exportable
1291 d.exportableStubCmd(ctx, stubCmdParams)
Paul Duffinc166b682022-05-27 12:23:08 +00001292
Jihoon Kang90f70332025-01-28 19:36:27 +00001293 if String(d.properties.Check_nullability_warnings) != "" {
1294 if d.everythingArtifacts.nullabilityWarningsFile == nil {
1295 ctx.PropertyErrorf("check_nullability_warnings",
1296 "Cannot specify check_nullability_warnings unless validating nullability")
1297 }
1298
1299 checkNullabilityWarningsPath := android.PathForModuleSrc(ctx, String(d.properties.Check_nullability_warnings))
1300
1301 d.checkNullabilityWarningsTimestamp = android.PathForModuleOut(ctx, Everything.String(), "check_nullability_warnings.timestamp")
1302
1303 msg := fmt.Sprintf(`\n******************************\n`+
1304 `The warnings encountered during nullability annotation validation did\n`+
1305 `not match the checked in file of expected warnings. The diffs are shown\n`+
1306 `above. You have two options:\n`+
1307 ` 1. Resolve the differences by editing the nullability annotations.\n`+
1308 ` 2. Update the file of expected warnings by running:\n`+
1309 ` cp %s %s\n`+
1310 ` and submitting the updated file as part of your change.`,
1311 d.everythingArtifacts.nullabilityWarningsFile, checkNullabilityWarningsPath)
1312
1313 rule := android.NewRuleBuilder(pctx, ctx)
1314
1315 rule.Command().
1316 Text("(").
1317 Text("diff").Input(checkNullabilityWarningsPath).Input(d.everythingArtifacts.nullabilityWarningsFile).
1318 Text("&&").
1319 Text("touch").Output(d.checkNullabilityWarningsTimestamp).
1320 Text(") || (").
1321 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
1322 Text("; exit 38").
1323 Text(")")
1324
1325 rule.Build("nullabilityWarningsCheck", "nullability warnings check")
1326 }
1327
Paul Duffine7a86642022-08-16 15:43:20 +00001328 if apiCheckEnabled(ctx, d.properties.Check_api.Current, "current") {
1329
1330 if len(d.Javadoc.properties.Out) > 0 {
1331 ctx.PropertyErrorf("out", "out property may not be combined with check_api")
1332 }
1333
1334 apiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Api_file))
1335 removedApiFile := android.PathForModuleSrc(ctx, String(d.properties.Check_api.Current.Removed_api_file))
1336 baselineFile := android.OptionalPathForModuleSrc(ctx, d.properties.Check_api.Current.Baseline_file)
1337
1338 if baselineFile.Valid() {
1339 ctx.PropertyErrorf("baseline_file", "current API check can't have a baseline file. (module %s)", ctx.ModuleName())
1340 }
1341
Jihoon Kang3c89f042023-12-19 02:40:22 +00001342 d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, Everything.String(), "check_current_api.timestamp")
Paul Duffine7a86642022-08-16 15:43:20 +00001343
1344 rule := android.NewRuleBuilder(pctx, ctx)
1345
1346 // Diff command line.
1347 // -F matches the closest "opening" line, such as "package android {"
1348 // and " public class Intent {".
1349 diff := `diff -u -F '{ *$'`
1350
1351 rule.Command().Text("( true")
1352 rule.Command().
1353 Text(diff).
1354 Input(apiFile).Input(d.apiFile)
1355
1356 rule.Command().
1357 Text(diff).
1358 Input(removedApiFile).Input(d.removedApiFile)
1359
1360 msg := fmt.Sprintf(`\n******************************\n`+
1361 `You have tried to change the API from what has been previously approved.\n\n`+
1362 `To make these errors go away, you have two choices:\n`+
1363 ` 1. You can add '@hide' javadoc comments (and remove @SystemApi/@TestApi/etc)\n`+
1364 ` to the new methods, etc. shown in the above diff.\n\n`+
1365 ` 2. You can update current.txt and/or removed.txt by executing the following command:\n`+
1366 ` m %s-update-current-api\n\n`+
1367 ` To submit the revised current.txt to the main Android repository,\n`+
1368 ` you will need approval.\n`+
Jihoon Kang3ea64672023-11-03 00:40:26 +00001369 `If your build failed due to stub validation, you can resolve the errors with\n`+
1370 `either of the two choices above and try re-building the target.\n`+
1371 `If the mismatch between the stubs and the current.txt is intended,\n`+
1372 `you can try re-building the target by executing the following command:\n`+
Jihoon Kang91bf3dd2024-01-24 00:40:23 +00001373 `m DISABLE_STUB_VALIDATION=true <your build target>.\n`+
1374 `Note that DISABLE_STUB_VALIDATION=true does not bypass checkapi.\n`+
Paul Duffine7a86642022-08-16 15:43:20 +00001375 `******************************\n`, ctx.ModuleName())
1376
Jihoon Kang90f70332025-01-28 19:36:27 +00001377 cmd := rule.Command().
Paul Duffine7a86642022-08-16 15:43:20 +00001378 Text("touch").Output(d.checkCurrentApiTimestamp).
1379 Text(") || (").
1380 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
1381 Text("; exit 38").
1382 Text(")")
1383
Jihoon Kang90f70332025-01-28 19:36:27 +00001384 if d.apiLintTimestamp != nil {
1385 cmd.Validation(d.apiLintTimestamp)
1386 }
1387
1388 if d.checkLastReleasedApiTimestamp != nil {
1389 cmd.Validation(d.checkLastReleasedApiTimestamp)
1390 }
1391
1392 if d.checkNullabilityWarningsTimestamp != nil {
1393 cmd.Validation(d.checkNullabilityWarningsTimestamp)
1394 }
1395
Paul Duffine7a86642022-08-16 15:43:20 +00001396 rule.Build("metalavaCurrentApiCheck", "check current API")
1397
Jihoon Kang3c89f042023-12-19 02:40:22 +00001398 d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, Everything.String(), "update_current_api.timestamp")
Paul Duffine7a86642022-08-16 15:43:20 +00001399
1400 // update API rule
1401 rule = android.NewRuleBuilder(pctx, ctx)
1402
1403 rule.Command().Text("( true")
1404
1405 rule.Command().
1406 Text("cp").Flag("-f").
1407 Input(d.apiFile).Flag(apiFile.String())
1408
1409 rule.Command().
1410 Text("cp").Flag("-f").
1411 Input(d.removedApiFile).Flag(removedApiFile.String())
1412
1413 msg = "failed to update public API"
1414
1415 rule.Command().
1416 Text("touch").Output(d.updateCurrentApiTimestamp).
1417 Text(") || (").
1418 Text("echo").Flag("-e").Flag(`"` + msg + `"`).
1419 Text("; exit 38").
1420 Text(")")
1421
1422 rule.Build("metalavaCurrentApiUpdate", "update current API")
1423 }
1424
Yu Liu35acd332025-01-24 23:11:22 +00001425 droidInfo := DroidStubsInfo{
Yu Liucbb50c22025-01-15 20:57:49 +00001426 CurrentApiTimestamp: d.CurrentApiTimestamp(),
Yu Liu35acd332025-01-24 23:11:22 +00001427 EverythingStubsInfo: StubsInfo{},
1428 ExportableStubsInfo: StubsInfo{},
1429 }
1430 setDroidInfo(ctx, d, &droidInfo.EverythingStubsInfo, Everything)
1431 setDroidInfo(ctx, d, &droidInfo.ExportableStubsInfo, Exportable)
1432 android.SetProvider(ctx, DroidStubsInfoProvider, droidInfo)
1433
1434 android.SetProvider(ctx, StubsSrcInfoProvider, StubsSrcInfo{
1435 EverythingStubsSrcJar: d.stubsSrcJar,
1436 ExportableStubsSrcJar: d.exportableStubsSrcJar,
Yu Liucbb50c22025-01-15 20:57:49 +00001437 })
1438
mrziwang39e68ff2024-07-01 16:35:32 -07001439 d.setOutputFiles(ctx)
Jihoon Kange9eecc72025-01-28 18:57:18 +00001440
1441 d.setPhonyRules(ctx)
Cole Fausta43fb252025-02-11 17:02:53 -08001442
1443 if d.apiLintTimestamp != nil {
1444 if d.apiLintReport != nil {
1445 ctx.DistForGoalsWithFilename(
1446 []string{fmt.Sprintf("%s-api-lint", d.Name()), "droidcore"},
1447 d.apiLintReport,
1448 fmt.Sprintf("apilint/%s-lint-report.txt", d.Name()),
1449 )
1450 }
1451 }
mrziwang39e68ff2024-07-01 16:35:32 -07001452}
1453
Yu Liu35acd332025-01-24 23:11:22 +00001454func setDroidInfo(ctx android.ModuleContext, d *Droidstubs, info *StubsInfo, typ StubsType) {
1455 if typ == Everything {
1456 info.ApiFile = d.apiFile
1457 info.RemovedApiFile = d.removedApiFile
1458 info.AnnotationsZip = d.everythingArtifacts.annotationsZip
1459 info.ApiVersionsXml = d.everythingArtifacts.apiVersionsXml
1460 } else if typ == Exportable {
1461 info.ApiFile = d.exportableApiFile
1462 info.RemovedApiFile = d.exportableRemovedApiFile
1463 info.AnnotationsZip = d.exportableArtifacts.annotationsZip
1464 info.ApiVersionsXml = d.exportableArtifacts.apiVersionsXml
1465 } else {
1466 ctx.ModuleErrorf("failed to set ApiVersionsXml, stubs type not supported: %d", typ)
1467 }
1468}
1469
mrziwang39e68ff2024-07-01 16:35:32 -07001470// This method sets the outputFiles property, which is used to set the
1471// OutputFilesProvider later.
1472// Droidstubs' tag supports specifying with the stubs type.
1473// While supporting the pre-existing tags, it also supports tags with
1474// the stubs type prefix. Some examples are shown below:
1475// {.annotations.zip} - pre-existing behavior. Returns the path to the
1476// annotation zip.
1477// {.exportable} - Returns the path to the exportable stubs src jar.
1478// {.exportable.annotations.zip} - Returns the path to the exportable
1479// annotations zip file.
1480// {.runtime.api_versions.xml} - Runtime stubs does not generate api versions
1481// xml file. For unsupported combinations, the default everything output file
1482// is returned.
1483func (d *Droidstubs) setOutputFiles(ctx android.ModuleContext) {
1484 tagToOutputFileFunc := map[string]func(StubsType) (android.Path, error){
1485 "": d.StubsSrcJar,
1486 ".docs.zip": d.DocZip,
1487 ".api.txt": d.ApiFilePath,
1488 android.DefaultDistTag: d.ApiFilePath,
1489 ".removed-api.txt": d.RemovedApiFilePath,
1490 ".annotations.zip": d.AnnotationsZip,
1491 ".api_versions.xml": d.ApiVersionsXmlFilePath,
1492 }
1493 stubsTypeToPrefix := map[StubsType]string{
1494 Everything: "",
1495 Exportable: ".exportable",
1496 }
1497 for _, tag := range android.SortedKeys(tagToOutputFileFunc) {
1498 for _, stubType := range android.SortedKeys(stubsTypeToPrefix) {
1499 tagWithPrefix := stubsTypeToPrefix[stubType] + tag
1500 outputFile, err := tagToOutputFileFunc[tag](stubType)
Cole Faust5146e782024-11-15 14:47:49 -08001501 if err == nil && outputFile != nil {
mrziwang39e68ff2024-07-01 16:35:32 -07001502 ctx.SetOutputFiles(android.Paths{outputFile}, tagWithPrefix)
1503 }
1504 }
1505 }
Colin Cross2207f872021-03-24 12:39:08 -07001506}
1507
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001508func (d *Droidstubs) createApiContribution(ctx android.DefaultableHookContext) {
1509 api_file := d.properties.Check_api.Current.Api_file
1510 api_surface := d.properties.Api_surface
1511
1512 props := struct {
1513 Name *string
1514 Api_surface *string
1515 Api_file *string
Jihoon Kang42b589c2023-02-03 22:56:13 +00001516 Visibility []string
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001517 }{}
1518
1519 props.Name = proptools.StringPtr(d.Name() + ".api.contribution")
1520 props.Api_surface = api_surface
1521 props.Api_file = api_file
Jihoon Kang42b589c2023-02-03 22:56:13 +00001522 props.Visibility = []string{"//visibility:override", "//visibility:public"}
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001523
1524 ctx.CreateModule(ApiContributionFactory, &props)
1525}
1526
Spandan Das0b555e32022-11-28 18:48:51 +00001527// TODO (b/262014796): Export the API contributions of CorePlatformApi
1528// A map to populate the api surface of a droidstub from a substring appearing in its name
1529// This map assumes that droidstubs (either checked-in or created by java_sdk_library)
1530// use a strict naming convention
1531var (
1532 droidstubsModuleNamingToSdkKind = map[string]android.SdkKind{
Paul Duffin2ced2eb2024-05-01 13:13:51 +01001533 // public is commented out since the core libraries use public in their java_sdk_library names
Spandan Das0b555e32022-11-28 18:48:51 +00001534 "intracore": android.SdkIntraCore,
1535 "intra.core": android.SdkIntraCore,
1536 "system_server": android.SdkSystemServer,
1537 "system-server": android.SdkSystemServer,
1538 "system": android.SdkSystem,
1539 "module_lib": android.SdkModule,
1540 "module-lib": android.SdkModule,
Spandan Dasda977552023-01-26 20:45:16 +00001541 "platform.api": android.SdkCorePlatform,
Spandan Das0b555e32022-11-28 18:48:51 +00001542 "test": android.SdkTest,
Spandan Das4ac2aed2022-12-28 01:54:29 +00001543 "toolchain": android.SdkToolchain,
Spandan Das0b555e32022-11-28 18:48:51 +00001544 }
1545)
1546
Colin Cross2207f872021-03-24 12:39:08 -07001547func StubsDefaultsFactory() android.Module {
1548 module := &DocDefaults{}
1549
1550 module.AddProperties(
1551 &JavadocProperties{},
1552 &DroidstubsProperties{},
1553 )
1554
1555 android.InitDefaultsModule(module)
1556
1557 return module
1558}
1559
1560var _ android.PrebuiltInterface = (*PrebuiltStubsSources)(nil)
1561
1562type PrebuiltStubsSourcesProperties struct {
1563 Srcs []string `android:"path"`
Spandan Das23956d12024-01-19 00:22:22 +00001564
1565 // Name of the source soong module that gets shadowed by this prebuilt
1566 // If unspecified, follows the naming convention that the source module of
1567 // the prebuilt is Name() without "prebuilt_" prefix
1568 Source_module_name *string
1569
1570 // Non-nil if this prebuilt stub srcs module was dynamically created by a java_sdk_library_import
1571 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
1572 // (without any prebuilt_ prefix)
1573 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
1574}
1575
1576func (j *PrebuiltStubsSources) BaseModuleName() string {
1577 return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name())
1578}
1579
1580func (j *PrebuiltStubsSources) CreatedByJavaSdkLibraryName() *string {
1581 return j.properties.Created_by_java_sdk_library_name
Colin Cross2207f872021-03-24 12:39:08 -07001582}
1583
1584type PrebuiltStubsSources struct {
1585 android.ModuleBase
1586 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00001587 embeddableInModuleAndImport
1588
Colin Cross2207f872021-03-24 12:39:08 -07001589 prebuilt android.Prebuilt
Colin Cross2207f872021-03-24 12:39:08 -07001590
1591 properties PrebuiltStubsSourcesProperties
1592
kgui67007242022-01-25 13:50:25 +08001593 stubsSrcJar android.Path
Colin Cross2207f872021-03-24 12:39:08 -07001594}
1595
Jihoon Kangee113282024-01-23 00:16:41 +00001596func (d *PrebuiltStubsSources) StubsSrcJar(_ StubsType) (android.Path, error) {
1597 return d.stubsSrcJar, nil
Colin Cross2207f872021-03-24 12:39:08 -07001598}
1599
1600func (p *PrebuiltStubsSources) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross2207f872021-03-24 12:39:08 -07001601 if len(p.properties.Srcs) != 1 {
Anton Hansson86758ac2021-11-03 14:44:12 +00001602 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 -07001603 return
1604 }
1605
Anton Hansson86758ac2021-11-03 14:44:12 +00001606 src := p.properties.Srcs[0]
1607 if filepath.Ext(src) == ".srcjar" {
1608 // This is a srcjar. We can use it directly.
1609 p.stubsSrcJar = android.PathForModuleSrc(ctx, src)
1610 } else {
1611 outPath := android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
Colin Cross2207f872021-03-24 12:39:08 -07001612
Anton Hansson86758ac2021-11-03 14:44:12 +00001613 // This is a directory. Glob the contents just in case the directory does not exist.
1614 srcGlob := src + "/**/*"
1615 srcPaths := android.PathsForModuleSrc(ctx, []string{srcGlob})
Colin Cross2207f872021-03-24 12:39:08 -07001616
Anton Hansson86758ac2021-11-03 14:44:12 +00001617 // Although PathForModuleSrc can return nil if either the path doesn't exist or
1618 // the path components are invalid it won't in this case because no components
1619 // are specified and the module directory must exist in order to get this far.
1620 srcDir := android.PathForModuleSrc(ctx).(android.SourcePath).Join(ctx, src)
Colin Cross2207f872021-03-24 12:39:08 -07001621
Anton Hansson86758ac2021-11-03 14:44:12 +00001622 rule := android.NewRuleBuilder(pctx, ctx)
1623 rule.Command().
1624 BuiltTool("soong_zip").
1625 Flag("-write_if_changed").
1626 Flag("-jar").
1627 FlagWithOutput("-o ", outPath).
1628 FlagWithArg("-C ", srcDir.String()).
1629 FlagWithRspFileInputList("-r ", outPath.ReplaceExtension(ctx, "rsp"), srcPaths)
1630 rule.Restat()
1631 rule.Build("zip src", "Create srcjar from prebuilt source")
1632 p.stubsSrcJar = outPath
1633 }
mrziwangaa2a2b62024-07-01 12:09:20 -07001634
Yu Liu35acd332025-01-24 23:11:22 +00001635 android.SetProvider(ctx, StubsSrcInfoProvider, StubsSrcInfo{
1636 EverythingStubsSrcJar: p.stubsSrcJar,
1637 ExportableStubsSrcJar: p.stubsSrcJar,
1638 })
1639
mrziwangaa2a2b62024-07-01 12:09:20 -07001640 ctx.SetOutputFiles(android.Paths{p.stubsSrcJar}, "")
1641 // prebuilt droidstubs does not output "exportable" stubs.
1642 // Output the "everything" stubs srcjar file if the tag is ".exportable".
1643 ctx.SetOutputFiles(android.Paths{p.stubsSrcJar}, ".exportable")
Colin Cross2207f872021-03-24 12:39:08 -07001644}
1645
1646func (p *PrebuiltStubsSources) Prebuilt() *android.Prebuilt {
1647 return &p.prebuilt
1648}
1649
1650func (p *PrebuiltStubsSources) Name() string {
1651 return p.prebuilt.Name(p.ModuleBase.Name())
1652}
1653
1654// prebuilt_stubs_sources imports a set of java source files as if they were
1655// generated by droidstubs.
1656//
1657// By default, a prebuilt_stubs_sources has a single variant that expects a
1658// set of `.java` files generated by droidstubs.
1659//
1660// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1661// for host modules.
1662//
1663// Intended only for use by sdk snapshots.
1664func PrebuiltStubsSourcesFactory() android.Module {
1665 module := &PrebuiltStubsSources{}
1666
1667 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001668 module.initModuleAndImport(module)
Colin Cross2207f872021-03-24 12:39:08 -07001669
1670 android.InitPrebuiltModule(module, &module.properties.Srcs)
Colin Cross2207f872021-03-24 12:39:08 -07001671 InitDroiddocModule(module, android.HostAndDeviceSupported)
1672 return module
1673}