blob: 2cbefc3bbaa6a904410776fffeaf19760be590dc [file] [log] [blame]
Colin Cross014489c2020-06-02 20:09:13 -07001// Copyright 2020 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"
19 "sort"
Colin Cross988dfcc2020-07-16 17:32:17 -070020 "strings"
Colin Cross014489c2020-06-02 20:09:13 -070021
Colin Crossb79aa8f2024-09-25 15:41:01 -070022 "github.com/google/blueprint"
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000023 "github.com/google/blueprint/proptools"
24
Colin Cross014489c2020-06-02 20:09:13 -070025 "android/soong/android"
Colin Cross31972dc2021-03-04 10:44:12 -080026 "android/soong/java/config"
27 "android/soong/remoteexec"
Colin Cross014489c2020-06-02 20:09:13 -070028)
29
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -070030// lint checks automatically enforced for modules that have different min_sdk_version than
31// sdk_version
32var updatabilityChecks = []string{"NewApi"}
33
Colin Cross014489c2020-06-02 20:09:13 -070034type LintProperties struct {
35 // Controls for running Android Lint on the module.
36 Lint struct {
37
38 // If true, run Android Lint on the module. Defaults to true.
39 Enabled *bool
40
41 // Flags to pass to the Android Lint tool.
42 Flags []string
43
44 // Checks that should be treated as fatal.
45 Fatal_checks []string
46
47 // Checks that should be treated as errors.
48 Error_checks []string
49
50 // Checks that should be treated as warnings.
51 Warning_checks []string
52
53 // Checks that should be skipped.
54 Disabled_checks []string
Colin Cross92e4b462020-06-18 15:56:48 -070055
56 // Modules that provide extra lint checks
57 Extra_check_modules []string
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000058
Cole Faustb765d6b2024-01-04 10:29:27 -080059 // The lint baseline file to use. If specified, lint warnings listed in this file will be
60 // suppressed during lint checks.
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000061 Baseline_filename *string
Jaewoong Jung48de8832021-04-21 16:17:25 -070062
63 // If true, baselining updatability lint checks (e.g. NewApi) is prohibited. Defaults to false.
64 Strict_updatability_linting *bool
Cole Faustd57e8b22022-08-11 11:59:04 -070065
66 // Treat the code in this module as test code for @VisibleForTesting enforcement.
67 // This will be true by default for test module types, false otherwise.
68 // If soong gets support for testonly, this flag should be replaced with that.
69 Test *bool
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +100070
71 // Whether to ignore the exit code of Android lint. This is the --exit_code
72 // option. Defaults to false.
73 Suppress_exit_code *bool
Colin Cross014489c2020-06-02 20:09:13 -070074 }
75}
76
77type linter struct {
Pedro Loureirof4a88b12021-02-25 16:23:22 +000078 name string
79 manifest android.Path
80 mergedManifest android.Path
81 srcs android.Paths
82 srcJars android.Paths
83 resources android.Paths
84 classpath android.Paths
85 classes android.Path
86 extraLintCheckJars android.Paths
Pedro Loureirof4a88b12021-02-25 16:23:22 +000087 library bool
Zi Wange1166f02023-11-06 11:43:17 -080088 minSdkVersion android.ApiLevel
89 targetSdkVersion android.ApiLevel
90 compileSdkVersion android.ApiLevel
Pedro Loureiro18233a22021-06-08 18:11:21 +000091 compileSdkKind android.SdkKind
Pedro Loureirof4a88b12021-02-25 16:23:22 +000092 javaLanguageLevel string
93 kotlinLanguageLevel string
Pedro Loureirof4a88b12021-02-25 16:23:22 +000094 properties LintProperties
95 extraMainlineLintErrors []string
Cole Faustdf1efd72023-12-08 12:27:24 -080096 compile_data android.Paths
Colin Crossc0efd1d2020-07-03 11:56:24 -070097
Colin Cross08dca382020-07-21 20:31:17 -070098 reports android.Paths
99
Colin Crossc0efd1d2020-07-03 11:56:24 -0700100 buildModuleReportZip bool
Colin Cross014489c2020-06-02 20:09:13 -0700101}
102
Colin Cross08dca382020-07-21 20:31:17 -0700103type LintDepSets struct {
Colin Cross87427352024-09-25 15:41:19 -0700104 HTML, Text, XML, Baseline *android.DepSet[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700105}
106
107type LintDepSetsBuilder struct {
Colin Cross87427352024-09-25 15:41:19 -0700108 HTML, Text, XML, Baseline *android.DepSetBuilder[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700109}
110
111func NewLintDepSetBuilder() LintDepSetsBuilder {
112 return LintDepSetsBuilder{
Colin Cross87427352024-09-25 15:41:19 -0700113 HTML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
114 Text: android.NewDepSetBuilder[android.Path](android.POSTORDER),
115 XML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
116 Baseline: android.NewDepSetBuilder[android.Path](android.POSTORDER),
Colin Cross08dca382020-07-21 20:31:17 -0700117 }
118}
119
Colin Cross87427352024-09-25 15:41:19 -0700120func (l LintDepSetsBuilder) Direct(html, text, xml android.Path, baseline android.OptionalPath) LintDepSetsBuilder {
Colin Cross08dca382020-07-21 20:31:17 -0700121 l.HTML.Direct(html)
122 l.Text.Direct(text)
123 l.XML.Direct(xml)
Colin Cross87427352024-09-25 15:41:19 -0700124 if baseline.Valid() {
125 l.Baseline.Direct(baseline.Path())
126 }
Colin Cross08dca382020-07-21 20:31:17 -0700127 return l
128}
129
Colin Crossb79aa8f2024-09-25 15:41:01 -0700130func (l LintDepSetsBuilder) Transitive(info *LintInfo) LintDepSetsBuilder {
131 if info.TransitiveHTML != nil {
132 l.HTML.Transitive(info.TransitiveHTML)
Colin Cross08dca382020-07-21 20:31:17 -0700133 }
Colin Crossb79aa8f2024-09-25 15:41:01 -0700134 if info.TransitiveText != nil {
135 l.Text.Transitive(info.TransitiveText)
Colin Cross08dca382020-07-21 20:31:17 -0700136 }
Colin Crossb79aa8f2024-09-25 15:41:01 -0700137 if info.TransitiveXML != nil {
138 l.XML.Transitive(info.TransitiveXML)
Colin Cross08dca382020-07-21 20:31:17 -0700139 }
Colin Cross87427352024-09-25 15:41:19 -0700140 if info.TransitiveBaseline != nil {
141 l.Baseline.Transitive(info.TransitiveBaseline)
142 }
Colin Cross08dca382020-07-21 20:31:17 -0700143 return l
144}
145
146func (l LintDepSetsBuilder) Build() LintDepSets {
147 return LintDepSets{
Colin Cross87427352024-09-25 15:41:19 -0700148 HTML: l.HTML.Build(),
149 Text: l.Text.Build(),
150 XML: l.XML.Build(),
151 Baseline: l.Baseline.Build(),
Colin Cross08dca382020-07-21 20:31:17 -0700152 }
153}
154
Cole Faust69861aa2023-01-31 15:49:07 -0800155type lintDatabaseFiles struct {
156 apiVersionsModule string
157 apiVersionsCopiedName string
158 apiVersionsPrebuiltPath string
159 annotationsModule string
160 annotationCopiedName string
161 annotationPrebuiltpath string
162}
163
164var allLintDatabasefiles = map[android.SdkKind]lintDatabaseFiles{
165 android.SdkPublic: {
166 apiVersionsModule: "api_versions_public",
167 apiVersionsCopiedName: "api_versions_public.xml",
168 apiVersionsPrebuiltPath: "prebuilts/sdk/current/public/data/api-versions.xml",
169 annotationsModule: "sdk-annotations.zip",
170 annotationCopiedName: "annotations-public.zip",
171 annotationPrebuiltpath: "prebuilts/sdk/current/public/data/annotations.zip",
172 },
173 android.SdkSystem: {
174 apiVersionsModule: "api_versions_system",
175 apiVersionsCopiedName: "api_versions_system.xml",
176 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system/data/api-versions.xml",
177 annotationsModule: "sdk-annotations-system.zip",
178 annotationCopiedName: "annotations-system.zip",
179 annotationPrebuiltpath: "prebuilts/sdk/current/system/data/annotations.zip",
180 },
181 android.SdkModule: {
182 apiVersionsModule: "api_versions_module_lib",
183 apiVersionsCopiedName: "api_versions_module_lib.xml",
184 apiVersionsPrebuiltPath: "prebuilts/sdk/current/module-lib/data/api-versions.xml",
185 annotationsModule: "sdk-annotations-module-lib.zip",
186 annotationCopiedName: "annotations-module-lib.zip",
187 annotationPrebuiltpath: "prebuilts/sdk/current/module-lib/data/annotations.zip",
188 },
189 android.SdkSystemServer: {
190 apiVersionsModule: "api_versions_system_server",
191 apiVersionsCopiedName: "api_versions_system_server.xml",
192 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system-server/data/api-versions.xml",
193 annotationsModule: "sdk-annotations-system-server.zip",
194 annotationCopiedName: "annotations-system-server.zip",
195 annotationPrebuiltpath: "prebuilts/sdk/current/system-server/data/annotations.zip",
196 },
197}
198
Colin Crossb79aa8f2024-09-25 15:41:01 -0700199var LintProvider = blueprint.NewProvider[*LintInfo]()
Colin Crossc0efd1d2020-07-03 11:56:24 -0700200
Colin Crossb79aa8f2024-09-25 15:41:01 -0700201type LintInfo struct {
202 HTML android.Path
203 Text android.Path
204 XML android.Path
205 ReferenceBaseline android.Path
206
Colin Cross87427352024-09-25 15:41:19 -0700207 TransitiveHTML *android.DepSet[android.Path]
208 TransitiveText *android.DepSet[android.Path]
209 TransitiveXML *android.DepSet[android.Path]
210 TransitiveBaseline *android.DepSet[android.Path]
Colin Cross014489c2020-06-02 20:09:13 -0700211}
212
213func (l *linter) enabled() bool {
214 return BoolDefault(l.properties.Lint.Enabled, true)
215}
216
Colin Cross92e4b462020-06-18 15:56:48 -0700217func (l *linter) deps(ctx android.BottomUpMutatorContext) {
218 if !l.enabled() {
219 return
220 }
221
Colin Cross988dfcc2020-07-16 17:32:17 -0700222 extraCheckModules := l.properties.Lint.Extra_check_modules
223
mattgilbridee17645f2022-11-18 18:20:20 +0000224 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
225 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700226 }
227
228 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
229 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700230}
231
Colin Crossad22bc22021-03-10 09:45:40 -0800232// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
233// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800234type lintPaths struct {
235 projectXML android.WritablePath
236 configXML android.WritablePath
237 cacheDir android.WritablePath
238 homeDir android.WritablePath
239 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800240}
241
Colin Cross9b93af42021-03-10 10:40:58 -0800242func lintRBEExecStrategy(ctx android.ModuleContext) string {
243 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
244}
245
Colin Cross87427352024-09-25 15:41:19 -0700246func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path,
247 baselines android.Paths) lintPaths {
248
Colin Cross31972dc2021-03-04 10:44:12 -0800249 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700250 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800251 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
252 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
253 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700254
Colin Cross1661aff2021-03-12 17:56:51 -0800255 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700256 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
257
258 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700259 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700260 FlagWithOutput("--project_out ", projectXMLPath).
261 FlagWithOutput("--config_out ", configXMLPath).
262 FlagWithArg("--name ", ctx.ModuleName())
263
264 if l.library {
265 cmd.Flag("--library")
266 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700267 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700268 cmd.Flag("--test")
269 }
270 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700271 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700272 }
273 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700274 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700275 }
276
Colin Cross5bedfa22021-03-23 17:07:14 -0700277 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
278 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700279 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700280
281 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700282
Colin Cross5bedfa22021-03-23 17:07:14 -0700283 if len(l.resources) > 0 {
284 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
285 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700286 }
287
288 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700289 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700290 }
291
Colin Cross5bedfa22021-03-23 17:07:14 -0700292 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700293
Colin Cross5bedfa22021-03-23 17:07:14 -0700294 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700295
Colin Cross1661aff2021-03-12 17:56:51 -0800296 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700297
298 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
299 // the root dir is not set.
300 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700301
302 cmd.FlagWithInput("@",
303 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
304
Cole Faust028b94c2024-01-16 17:17:11 -0800305 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
Colin Cross014489c2020-06-02 20:09:13 -0700306 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
307 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
308 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
309 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
310
Colin Cross87427352024-09-25 15:41:19 -0700311 if Bool(l.properties.Lint.Strict_updatability_linting) && len(baselines) > 0 {
Cole Faust24e25c02024-01-19 14:12:17 -0800312 // Verify the module does not baseline issues that endanger safe updatability.
Colin Cross87427352024-09-25 15:41:19 -0700313 strictUpdatabilityChecksOutputFile := VerifyStrictUpdatabilityChecks(ctx, baselines)
314 cmd.Validation(strictUpdatabilityChecksOutputFile)
Cole Faust24e25c02024-01-19 14:12:17 -0800315 }
Jaewoong Jung48de8832021-04-21 16:17:25 -0700316
Colin Cross31972dc2021-03-04 10:44:12 -0800317 return lintPaths{
318 projectXML: projectXMLPath,
319 configXML: configXMLPath,
320 cacheDir: cacheDir,
321 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800322 }
323
Colin Cross014489c2020-06-02 20:09:13 -0700324}
325
Colin Cross87427352024-09-25 15:41:19 -0700326func VerifyStrictUpdatabilityChecks(ctx android.ModuleContext, baselines android.Paths) android.Path {
327 rule := android.NewRuleBuilder(pctx, ctx)
328 baselineRspFile := android.PathForModuleOut(ctx, "lint_strict_updatability_check_baselines.rsp")
329 outputFile := android.PathForModuleOut(ctx, "lint_strict_updatability_check.stamp")
330 rule.Command().Text("rm -f").Output(outputFile)
331 rule.Command().
332 BuiltTool("lint_strict_updatability_checks").
333 FlagWithArg("--name ", ctx.ModuleName()).
334 FlagWithRspFileInputList("--baselines ", baselineRspFile, baselines).
335 FlagForEachArg("--disallowed_issues ", updatabilityChecks)
336 rule.Command().Text("touch").Output(outputFile)
337 rule.Build("lint_strict_updatability_checks", "lint strict updatability checks")
338
339 return outputFile
340}
341
Liz Kammer20ebfb42020-07-28 11:32:07 -0700342// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700343// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800344func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700345 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
346
347 rule.Command().Text("(").
348 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
349 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
350 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Zi Wange1166f02023-11-06 11:43:17 -0800351 Textf(`echo " <uses-sdk android:minSdkVersion='%s' android:targetSdkVersion='%s'/>" &&`,
352 l.minSdkVersion.String(), l.targetSdkVersion.String()).
Colin Cross014489c2020-06-02 20:09:13 -0700353 Text(`echo "</manifest>"`).
354 Text(") >").Output(manifestPath)
355
356 return manifestPath
357}
358
359func (l *linter) lint(ctx android.ModuleContext) {
360 if !l.enabled() {
361 return
362 }
363
Cole Faust5d0aaf42024-01-29 13:49:14 -0800364 for _, flag := range l.properties.Lint.Flags {
365 if strings.Contains(flag, "--disable") || strings.Contains(flag, "--enable") || strings.Contains(flag, "--check") {
366 ctx.PropertyErrorf("lint.flags", "Don't use --disable, --enable, or --check in the flags field, instead use the dedicated disabled_checks, warning_checks, error_checks, or fatal_checks fields")
367 }
368 }
369
Zi Wange1166f02023-11-06 11:43:17 -0800370 if l.minSdkVersion.CompareTo(l.compileSdkVersion) == -1 {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700371 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100372 // Skip lint warning checks for NewApi warnings for libcore where they come from source
373 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100374 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100375 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
376
377 if len(filtered) != 0 {
378 ctx.PropertyErrorf("lint.warning_checks",
379 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
380 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700381 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100382
383 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700384 if len(filtered) != 0 {
385 ctx.PropertyErrorf("lint.disabled_checks",
386 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
387 }
Cole Faust3f646262022-06-29 14:58:03 -0700388
389 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
390 if ctx.ModuleName() == "PermissionController" {
391 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
392 return s != "NewApi"
393 })
394 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
395 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000396 }
397
Colin Cross92e4b462020-06-18 15:56:48 -0700398 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
399 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Cross313aa542023-12-13 13:47:44 -0800400 if dep, ok := android.OtherModuleProvider(ctx, extraLintCheckModule, JavaInfoProvider); ok {
Colin Crossdcf71b22021-02-01 13:59:03 -0800401 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700402 } else {
403 ctx.PropertyErrorf("lint.extra_check_modules",
404 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
405 }
406 }
407
mattgilbride5aecabe2022-11-29 20:16:36 +0000408 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
409 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
410
Colin Cross87427352024-09-25 15:41:19 -0700411 var baseline android.OptionalPath
412 if l.properties.Lint.Baseline_filename != nil {
413 baseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *l.properties.Lint.Baseline_filename))
414 }
415
416 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
417 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
418 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
419 referenceBaseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
420
421 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml, baseline)
422
423 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
424 if info, ok := android.OtherModuleProvider(ctx, dep, LintProvider); ok {
425 depSetsBuilder.Transitive(info)
426 }
427 })
428
429 depSets := depSetsBuilder.Build()
430
Colin Cross1661aff2021-03-12 17:56:51 -0800431 rule := android.NewRuleBuilder(pctx, ctx).
432 Sbox(android.PathForModuleOut(ctx, "lint"),
433 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
434 SandboxInputs()
435
436 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
437 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
438 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
439 rule.Rewrapper(&remoteexec.REParams{
440 Labels: map[string]string{"type": "tool", "name": "lint"},
441 ExecStrategy: lintRBEExecStrategy(ctx),
442 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700443 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800444 })
445 }
Colin Cross014489c2020-06-02 20:09:13 -0700446
447 if l.manifest == nil {
448 manifest := l.generateManifest(ctx, rule)
449 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800450 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700451 }
452
Colin Cross62695b92022-08-12 16:09:24 -0700453 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
454 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
Cole Faustdf1efd72023-12-08 12:27:24 -0800455 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList).Implicits(l.compile_data)
Colin Cross62695b92022-08-12 16:09:24 -0700456
Colin Cross87427352024-09-25 15:41:19 -0700457 baselines := depSets.Baseline.ToList()
Colin Cross014489c2020-06-02 20:09:13 -0700458
Colin Cross87427352024-09-25 15:41:19 -0700459 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList, baselines)
Colin Crossb79aa8f2024-09-25 15:41:01 -0700460
Colin Cross31972dc2021-03-04 10:44:12 -0800461 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
462 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800463 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700464
Cole Faust69861aa2023-01-31 15:49:07 -0800465 files, ok := allLintDatabasefiles[l.compileSdkKind]
466 if !ok {
467 files = allLintDatabasefiles[android.SdkPublic]
Pedro Loureiro18233a22021-06-08 18:11:21 +0000468 }
Colin Cross8a6ed372020-07-06 11:45:51 -0700469 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900470 if ctx.Config().AlwaysUsePrebuiltSdks() {
Cole Faust69861aa2023-01-31 15:49:07 -0800471 annotationsZipPath = android.PathForSource(ctx, files.annotationPrebuiltpath)
472 apiVersionsXMLPath = android.PathForSource(ctx, files.apiVersionsPrebuiltPath)
Colin Cross8a6ed372020-07-06 11:45:51 -0700473 } else {
Cole Faust69861aa2023-01-31 15:49:07 -0800474 annotationsZipPath = copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName)
475 apiVersionsXMLPath = copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700476 }
477
Colin Cross31972dc2021-03-04 10:44:12 -0800478 cmd := rule.Command()
479
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000480 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800481 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700482 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800483 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
484
Colin Cross1661aff2021-03-12 17:56:51 -0800485 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700486 Flag("--quiet").
Tor Norbyecabafde2023-12-07 21:57:28 +0000487 Flag("--include-aosp-issues").
Colin Cross31972dc2021-03-04 10:44:12 -0800488 FlagWithInput("--project ", lintPaths.projectXML).
489 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700490 FlagWithOutput("--html ", html).
491 FlagWithOutput("--text ", text).
492 FlagWithOutput("--xml ", xml).
Zi Wange1166f02023-11-06 11:43:17 -0800493 FlagWithArg("--compile-sdk-version ", l.compileSdkVersion.String()).
Colin Cross014489c2020-06-02 20:09:13 -0700494 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
495 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
496 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
Colin Cross62695b92022-08-12 16:09:24 -0700497 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700498 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800499 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700500 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700501
Colin Cross1661aff2021-03-12 17:56:51 -0800502 rule.Temporary(lintPaths.projectXML)
503 rule.Temporary(lintPaths.configXML)
504
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +1000505 suppressExitCode := BoolDefault(l.properties.Lint.Suppress_exit_code, false)
506 if exitCode := ctx.Config().Getenv("ANDROID_LINT_SUPPRESS_EXIT_CODE"); exitCode == "" && !suppressExitCode {
mattgilbrideb597abd2023-03-22 17:44:18 +0000507 cmd.Flag("--exitcode")
508 }
509
Colin Cross988dfcc2020-07-16 17:32:17 -0700510 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
511 cmd.FlagWithArg("--check ", checkOnly)
512 }
513
Colin Cross87427352024-09-25 15:41:19 -0700514 if baseline.Valid() {
515 cmd.FlagWithInput("--baseline ", baseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000516 }
517
Cole Faustdf38f7a2023-03-02 16:43:15 -0800518 cmd.FlagWithOutput("--write-reference-baseline ", referenceBaseline)
Colin Cross6b76c152021-09-09 09:36:25 -0700519
Colin Cross1b9e6832022-10-11 11:22:24 -0700520 cmd.Text("; EXITCODE=$?; ")
521
522 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
523 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
524 // a fatal error.
525 cmd.BuiltTool("soong_zip").
526 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
527 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
528 FlagWithInput("-r ", srcsList)
529
530 cmd.Text("; if [ $EXITCODE != 0 ]; then if [ -e").Input(text).Text("]; then cat").Input(text).Text("; fi; exit $EXITCODE; fi")
Colin Cross014489c2020-06-02 20:09:13 -0700531
Colin Cross31972dc2021-03-04 10:44:12 -0800532 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700533
Colin Crossee4a8b72021-04-05 18:38:05 -0700534 // The HTML output contains a date, remove it to make the output deterministic.
535 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
536
Colin Crossf1a035e2020-11-16 17:32:30 -0800537 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700538
Colin Crossb79aa8f2024-09-25 15:41:01 -0700539 android.SetProvider(ctx, LintProvider, &LintInfo{
540 HTML: html,
541 Text: text,
542 XML: xml,
543 ReferenceBaseline: referenceBaseline,
Colin Cross014489c2020-06-02 20:09:13 -0700544
Colin Cross87427352024-09-25 15:41:19 -0700545 TransitiveHTML: depSets.HTML,
546 TransitiveText: depSets.Text,
547 TransitiveXML: depSets.XML,
548 TransitiveBaseline: depSets.Baseline,
Colin Crossb79aa8f2024-09-25 15:41:01 -0700549 })
Colin Cross014489c2020-06-02 20:09:13 -0700550
Colin Crossc0efd1d2020-07-03 11:56:24 -0700551 if l.buildModuleReportZip {
Colin Cross87427352024-09-25 15:41:19 -0700552 l.reports = BuildModuleLintReportZips(ctx, depSets, nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700553 }
Colin Crossb9176412024-01-05 12:51:25 -0800554
555 // Create a per-module phony target to run the lint check.
556 phonyName := ctx.ModuleName() + "-lint"
557 ctx.Phony(phonyName, xml)
Colin Crossb79aa8f2024-09-25 15:41:01 -0700558
559 ctx.SetOutputFiles(android.Paths{xml}, ".lint")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700560}
Colin Cross014489c2020-06-02 20:09:13 -0700561
Colin Cross87427352024-09-25 15:41:19 -0700562func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets, validations android.Paths) android.Paths {
Colin Crossc85750b2022-04-21 12:50:51 -0700563 htmlList := android.SortedUniquePaths(depSets.HTML.ToList())
564 textList := android.SortedUniquePaths(depSets.Text.ToList())
565 xmlList := android.SortedUniquePaths(depSets.XML.ToList())
Colin Cross08dca382020-07-21 20:31:17 -0700566
567 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
568 return nil
569 }
570
571 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
Colin Cross87427352024-09-25 15:41:19 -0700572 lintZip(ctx, htmlList, htmlZip, validations)
Colin Cross08dca382020-07-21 20:31:17 -0700573
574 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
Colin Cross87427352024-09-25 15:41:19 -0700575 lintZip(ctx, textList, textZip, validations)
Colin Cross08dca382020-07-21 20:31:17 -0700576
577 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
Colin Cross87427352024-09-25 15:41:19 -0700578 lintZip(ctx, xmlList, xmlZip, validations)
Colin Cross08dca382020-07-21 20:31:17 -0700579
580 return android.Paths{htmlZip, textZip, xmlZip}
581}
582
Colin Cross014489c2020-06-02 20:09:13 -0700583type lintSingleton struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800584 htmlZip android.WritablePath
585 textZip android.WritablePath
586 xmlZip android.WritablePath
587 referenceBaselineZip android.WritablePath
Colin Cross014489c2020-06-02 20:09:13 -0700588}
589
590func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
591 l.generateLintReportZips(ctx)
592 l.copyLintDependencies(ctx)
593}
594
Pedro Loureiro18233a22021-06-08 18:11:21 +0000595func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
596 var res android.Module
597 ctx.VisitAllModules(func(m android.Module) {
598 if ctx.ModuleName(m) == moduleName {
599 if res == nil {
600 res = m
601 } else {
602 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
603 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
604 }
605 }
606 })
607 return res
608}
609
Colin Cross014489c2020-06-02 20:09:13 -0700610func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900611 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700612 return
613 }
614
Cole Faust69861aa2023-01-31 15:49:07 -0800615 for _, sdk := range android.SortedKeys(allLintDatabasefiles) {
616 files := allLintDatabasefiles[sdk]
617 apiVersionsDb := findModuleOrErr(ctx, files.apiVersionsModule)
618 if apiVersionsDb == nil {
619 if !ctx.Config().AllowMissingDependencies() {
Paul Duffin375acd82024-05-02 12:44:20 +0100620 ctx.Errorf("lint: missing module %s", files.apiVersionsModule)
Cole Faust69861aa2023-01-31 15:49:07 -0800621 }
622 return
Colin Cross014489c2020-06-02 20:09:13 -0700623 }
Colin Cross014489c2020-06-02 20:09:13 -0700624
Cole Faust69861aa2023-01-31 15:49:07 -0800625 sdkAnnotations := findModuleOrErr(ctx, files.annotationsModule)
626 if sdkAnnotations == nil {
627 if !ctx.Config().AllowMissingDependencies() {
Paul Duffin375acd82024-05-02 12:44:20 +0100628 ctx.Errorf("lint: missing module %s", files.annotationsModule)
Cole Faust69861aa2023-01-31 15:49:07 -0800629 }
630 return
Anton Hanssonea17a452022-05-09 09:42:17 +0000631 }
Cole Faust69861aa2023-01-31 15:49:07 -0800632
633 ctx.Build(pctx, android.BuildParams{
634 Rule: android.CpIfChanged,
635 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
636 Output: copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName),
637 })
638
639 ctx.Build(pctx, android.BuildParams{
640 Rule: android.CpIfChanged,
641 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
642 Output: copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName),
643 })
Anton Hanssonea17a452022-05-09 09:42:17 +0000644 }
Colin Cross014489c2020-06-02 20:09:13 -0700645}
646
Cole Faust69861aa2023-01-31 15:49:07 -0800647func copiedLintDatabaseFilesPath(ctx android.PathContext, name string) android.WritablePath {
Pedro Loureiro18233a22021-06-08 18:11:21 +0000648 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700649}
650
651func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700652 if ctx.Config().UnbundledBuild() {
653 return
654 }
655
Colin Crossb79aa8f2024-09-25 15:41:01 -0700656 var outputs []*LintInfo
Colin Cross014489c2020-06-02 20:09:13 -0700657 var dirs []string
658 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500659 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700660 return
661 }
662
Colin Cross56a83212020-09-15 18:30:11 -0700663 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
Yu Liu663e4502024-08-12 18:23:59 +0000664 apexInfo, _ := android.OtherModuleProvider(ctx, m, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -0700665 if apexInfo.IsForPlatform() {
666 // There are stray platform variants of modules in apexes that are not available for
667 // the platform, and they sometimes can't be built. Don't depend on them.
668 return
669 }
Colin Cross014489c2020-06-02 20:09:13 -0700670 }
671
Colin Crossb79aa8f2024-09-25 15:41:01 -0700672 if lintInfo, ok := android.OtherModuleProvider(ctx, m, LintProvider); ok {
673 outputs = append(outputs, lintInfo)
Colin Cross014489c2020-06-02 20:09:13 -0700674 }
675 })
676
677 dirs = android.SortedUniqueStrings(dirs)
678
Colin Crossb79aa8f2024-09-25 15:41:01 -0700679 zip := func(outputPath android.WritablePath, get func(*LintInfo) android.Path) {
Colin Cross014489c2020-06-02 20:09:13 -0700680 var paths android.Paths
681
682 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700683 if p := get(output); p != nil {
684 paths = append(paths, p)
685 }
Colin Cross014489c2020-06-02 20:09:13 -0700686 }
687
Colin Cross87427352024-09-25 15:41:19 -0700688 lintZip(ctx, paths, outputPath, nil)
Colin Cross014489c2020-06-02 20:09:13 -0700689 }
690
691 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
Colin Crossb79aa8f2024-09-25 15:41:01 -0700692 zip(l.htmlZip, func(l *LintInfo) android.Path { return l.HTML })
Colin Cross014489c2020-06-02 20:09:13 -0700693
694 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
Colin Crossb79aa8f2024-09-25 15:41:01 -0700695 zip(l.textZip, func(l *LintInfo) android.Path { return l.Text })
Colin Cross014489c2020-06-02 20:09:13 -0700696
697 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
Colin Crossb79aa8f2024-09-25 15:41:01 -0700698 zip(l.xmlZip, func(l *LintInfo) android.Path { return l.XML })
Colin Cross014489c2020-06-02 20:09:13 -0700699
Cole Faustdf38f7a2023-03-02 16:43:15 -0800700 l.referenceBaselineZip = android.PathForOutput(ctx, "lint-report-reference-baselines.zip")
Colin Crossb79aa8f2024-09-25 15:41:01 -0700701 zip(l.referenceBaselineZip, func(l *LintInfo) android.Path { return l.ReferenceBaseline })
Cole Faustdf38f7a2023-03-02 16:43:15 -0800702
703 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross014489c2020-06-02 20:09:13 -0700704}
705
706func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700707 if !ctx.Config().UnbundledBuild() {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800708 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross8a6ed372020-07-06 11:45:51 -0700709 }
Colin Cross014489c2020-06-02 20:09:13 -0700710}
711
712var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
713
714func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +0000715 android.RegisterParallelSingletonType("lint",
Colin Cross014489c2020-06-02 20:09:13 -0700716 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700717}
718
Colin Cross87427352024-09-25 15:41:19 -0700719func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath, validations android.Paths) {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700720 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
721
722 sort.Slice(paths, func(i, j int) bool {
723 return paths[i].String() < paths[j].String()
724 })
725
Colin Crossf1a035e2020-11-16 17:32:30 -0800726 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700727
Colin Crossf1a035e2020-11-16 17:32:30 -0800728 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700729 FlagWithOutput("-o ", outputPath).
730 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross87427352024-09-25 15:41:19 -0700731 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths).
732 Validations(validations)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700733
Colin Crossf1a035e2020-11-16 17:32:30 -0800734 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700735}