blob: 874ceee09412811fb660554908de487f08b67e71 [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"
Cole Fauste5bf3fb2022-07-01 19:39:14 +000020 "strconv"
Colin Cross988dfcc2020-07-16 17:32:17 -070021 "strings"
Colin Cross014489c2020-06-02 20:09:13 -070022
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
59 // Name of the file that lint uses as the baseline. Defaults to "lint-baseline.xml".
60 Baseline_filename *string
Jaewoong Jung48de8832021-04-21 16:17:25 -070061
62 // If true, baselining updatability lint checks (e.g. NewApi) is prohibited. Defaults to false.
63 Strict_updatability_linting *bool
Cole Faustd57e8b22022-08-11 11:59:04 -070064
65 // Treat the code in this module as test code for @VisibleForTesting enforcement.
66 // This will be true by default for test module types, false otherwise.
67 // If soong gets support for testonly, this flag should be replaced with that.
68 Test *bool
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +100069
70 // Whether to ignore the exit code of Android lint. This is the --exit_code
71 // option. Defaults to false.
72 Suppress_exit_code *bool
Colin Cross014489c2020-06-02 20:09:13 -070073 }
74}
75
76type linter struct {
Pedro Loureirof4a88b12021-02-25 16:23:22 +000077 name string
78 manifest android.Path
79 mergedManifest android.Path
80 srcs android.Paths
81 srcJars android.Paths
82 resources android.Paths
83 classpath android.Paths
84 classes android.Path
85 extraLintCheckJars android.Paths
Pedro Loureirof4a88b12021-02-25 16:23:22 +000086 library bool
Cole Fauste5bf3fb2022-07-01 19:39:14 +000087 minSdkVersion int
88 targetSdkVersion int
89 compileSdkVersion int
Pedro Loureiro18233a22021-06-08 18:11:21 +000090 compileSdkKind android.SdkKind
Pedro Loureirof4a88b12021-02-25 16:23:22 +000091 javaLanguageLevel string
92 kotlinLanguageLevel string
93 outputs lintOutputs
94 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
103type lintOutputs struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800104 html android.Path
105 text android.Path
106 xml android.Path
107 referenceBaseline android.Path
Colin Crossc0efd1d2020-07-03 11:56:24 -0700108
Colin Cross08dca382020-07-21 20:31:17 -0700109 depSets LintDepSets
Colin Crossc0efd1d2020-07-03 11:56:24 -0700110}
111
Colin Cross08dca382020-07-21 20:31:17 -0700112type lintOutputsIntf interface {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700113 lintOutputs() *lintOutputs
114}
115
Spandan Das17854f52022-01-14 21:19:14 +0000116type LintDepSetsIntf interface {
Colin Cross08dca382020-07-21 20:31:17 -0700117 LintDepSets() LintDepSets
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700118
119 // Methods used to propagate strict_updatability_linting values.
Spandan Das17854f52022-01-14 21:19:14 +0000120 GetStrictUpdatabilityLinting() bool
121 SetStrictUpdatabilityLinting(bool)
Colin Cross08dca382020-07-21 20:31:17 -0700122}
123
124type LintDepSets struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700125 HTML, Text, XML *android.DepSet[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700126}
127
128type LintDepSetsBuilder struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700129 HTML, Text, XML *android.DepSetBuilder[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700130}
131
132func NewLintDepSetBuilder() LintDepSetsBuilder {
133 return LintDepSetsBuilder{
Colin Crossc85750b2022-04-21 12:50:51 -0700134 HTML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
135 Text: android.NewDepSetBuilder[android.Path](android.POSTORDER),
136 XML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
Colin Cross08dca382020-07-21 20:31:17 -0700137 }
138}
139
140func (l LintDepSetsBuilder) Direct(html, text, xml android.Path) LintDepSetsBuilder {
141 l.HTML.Direct(html)
142 l.Text.Direct(text)
143 l.XML.Direct(xml)
144 return l
145}
146
147func (l LintDepSetsBuilder) Transitive(depSets LintDepSets) LintDepSetsBuilder {
148 if depSets.HTML != nil {
149 l.HTML.Transitive(depSets.HTML)
150 }
151 if depSets.Text != nil {
152 l.Text.Transitive(depSets.Text)
153 }
154 if depSets.XML != nil {
155 l.XML.Transitive(depSets.XML)
156 }
157 return l
158}
159
160func (l LintDepSetsBuilder) Build() LintDepSets {
161 return LintDepSets{
162 HTML: l.HTML.Build(),
163 Text: l.Text.Build(),
164 XML: l.XML.Build(),
165 }
166}
167
Cole Faust69861aa2023-01-31 15:49:07 -0800168type lintDatabaseFiles struct {
169 apiVersionsModule string
170 apiVersionsCopiedName string
171 apiVersionsPrebuiltPath string
172 annotationsModule string
173 annotationCopiedName string
174 annotationPrebuiltpath string
175}
176
177var allLintDatabasefiles = map[android.SdkKind]lintDatabaseFiles{
178 android.SdkPublic: {
179 apiVersionsModule: "api_versions_public",
180 apiVersionsCopiedName: "api_versions_public.xml",
181 apiVersionsPrebuiltPath: "prebuilts/sdk/current/public/data/api-versions.xml",
182 annotationsModule: "sdk-annotations.zip",
183 annotationCopiedName: "annotations-public.zip",
184 annotationPrebuiltpath: "prebuilts/sdk/current/public/data/annotations.zip",
185 },
186 android.SdkSystem: {
187 apiVersionsModule: "api_versions_system",
188 apiVersionsCopiedName: "api_versions_system.xml",
189 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system/data/api-versions.xml",
190 annotationsModule: "sdk-annotations-system.zip",
191 annotationCopiedName: "annotations-system.zip",
192 annotationPrebuiltpath: "prebuilts/sdk/current/system/data/annotations.zip",
193 },
194 android.SdkModule: {
195 apiVersionsModule: "api_versions_module_lib",
196 apiVersionsCopiedName: "api_versions_module_lib.xml",
197 apiVersionsPrebuiltPath: "prebuilts/sdk/current/module-lib/data/api-versions.xml",
198 annotationsModule: "sdk-annotations-module-lib.zip",
199 annotationCopiedName: "annotations-module-lib.zip",
200 annotationPrebuiltpath: "prebuilts/sdk/current/module-lib/data/annotations.zip",
201 },
202 android.SdkSystemServer: {
203 apiVersionsModule: "api_versions_system_server",
204 apiVersionsCopiedName: "api_versions_system_server.xml",
205 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system-server/data/api-versions.xml",
206 annotationsModule: "sdk-annotations-system-server.zip",
207 annotationCopiedName: "annotations-system-server.zip",
208 annotationPrebuiltpath: "prebuilts/sdk/current/system-server/data/annotations.zip",
209 },
210}
211
Colin Cross08dca382020-07-21 20:31:17 -0700212func (l *linter) LintDepSets() LintDepSets {
213 return l.outputs.depSets
214}
215
Spandan Das17854f52022-01-14 21:19:14 +0000216func (l *linter) GetStrictUpdatabilityLinting() bool {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700217 return BoolDefault(l.properties.Lint.Strict_updatability_linting, false)
218}
219
Spandan Das17854f52022-01-14 21:19:14 +0000220func (l *linter) SetStrictUpdatabilityLinting(strictLinting bool) {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700221 l.properties.Lint.Strict_updatability_linting = &strictLinting
222}
223
Spandan Das17854f52022-01-14 21:19:14 +0000224var _ LintDepSetsIntf = (*linter)(nil)
Colin Cross08dca382020-07-21 20:31:17 -0700225
226var _ lintOutputsIntf = (*linter)(nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700227
228func (l *linter) lintOutputs() *lintOutputs {
229 return &l.outputs
Colin Cross014489c2020-06-02 20:09:13 -0700230}
231
232func (l *linter) enabled() bool {
233 return BoolDefault(l.properties.Lint.Enabled, true)
234}
235
Colin Cross92e4b462020-06-18 15:56:48 -0700236func (l *linter) deps(ctx android.BottomUpMutatorContext) {
237 if !l.enabled() {
238 return
239 }
240
Colin Cross988dfcc2020-07-16 17:32:17 -0700241 extraCheckModules := l.properties.Lint.Extra_check_modules
242
mattgilbridee17645f2022-11-18 18:20:20 +0000243 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
244 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700245 }
246
247 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
248 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700249}
250
Colin Crossad22bc22021-03-10 09:45:40 -0800251// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
252// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800253type lintPaths struct {
254 projectXML android.WritablePath
255 configXML android.WritablePath
256 cacheDir android.WritablePath
257 homeDir android.WritablePath
258 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800259}
260
Colin Cross9b93af42021-03-10 10:40:58 -0800261func lintRBEExecStrategy(ctx android.ModuleContext) string {
262 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
263}
264
Colin Cross62695b92022-08-12 16:09:24 -0700265func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path) lintPaths {
Colin Cross31972dc2021-03-04 10:44:12 -0800266 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700267 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800268 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
269 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
270 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700271
Colin Cross1661aff2021-03-12 17:56:51 -0800272 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700273 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
274
275 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700276 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700277 FlagWithOutput("--project_out ", projectXMLPath).
278 FlagWithOutput("--config_out ", configXMLPath).
279 FlagWithArg("--name ", ctx.ModuleName())
280
281 if l.library {
282 cmd.Flag("--library")
283 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700284 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700285 cmd.Flag("--test")
286 }
287 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700288 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700289 }
290 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700291 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700292 }
293
Colin Cross5bedfa22021-03-23 17:07:14 -0700294 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
295 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700296 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700297
298 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700299
Colin Cross5bedfa22021-03-23 17:07:14 -0700300 if len(l.resources) > 0 {
301 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
302 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700303 }
304
305 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700306 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700307 }
308
Colin Cross5bedfa22021-03-23 17:07:14 -0700309 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700310
Colin Cross5bedfa22021-03-23 17:07:14 -0700311 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700312
Colin Cross1661aff2021-03-12 17:56:51 -0800313 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700314
315 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
316 // the root dir is not set.
317 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700318
319 cmd.FlagWithInput("@",
320 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
321
Cole Faust69861aa2023-01-31 15:49:07 -0800322 if l.compileSdkKind == android.SdkPublic {
323 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
324 } else {
325 // TODO(b/268261262): Remove this branch. We're demoting NewApi to a warning due to pre-existing issues that need to be fixed.
326 cmd.FlagForEachArg("--warning_check ", l.extraMainlineLintErrors)
327 }
Colin Cross014489c2020-06-02 20:09:13 -0700328 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
329 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
330 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
331 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
332
Cole Faust1021ccd2023-02-26 21:15:25 -0800333 // TODO(b/193460475): Re-enable strict updatability linting
334 //if l.GetStrictUpdatabilityLinting() {
335 // // Verify the module does not baseline issues that endanger safe updatability.
336 // if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
337 // cmd.FlagWithInput("--baseline ", baselinePath.Path())
338 // cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
339 // }
340 //}
Jaewoong Jung48de8832021-04-21 16:17:25 -0700341
Colin Cross31972dc2021-03-04 10:44:12 -0800342 return lintPaths{
343 projectXML: projectXMLPath,
344 configXML: configXMLPath,
345 cacheDir: cacheDir,
346 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800347 }
348
Colin Cross014489c2020-06-02 20:09:13 -0700349}
350
Liz Kammer20ebfb42020-07-28 11:32:07 -0700351// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700352// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800353func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700354 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
355
356 rule.Command().Text("(").
357 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
358 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
359 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000360 Textf(`echo " <uses-sdk android:minSdkVersion='%d' android:targetSdkVersion='%d'/>" &&`,
361 l.minSdkVersion, l.targetSdkVersion).
Colin Cross014489c2020-06-02 20:09:13 -0700362 Text(`echo "</manifest>"`).
363 Text(") >").Output(manifestPath)
364
365 return manifestPath
366}
367
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700368func (l *linter) getBaselineFilepath(ctx android.ModuleContext) android.OptionalPath {
369 var lintBaseline android.OptionalPath
370 if lintFilename := proptools.StringDefault(l.properties.Lint.Baseline_filename, "lint-baseline.xml"); lintFilename != "" {
371 if String(l.properties.Lint.Baseline_filename) != "" {
372 // if manually specified, we require the file to exist
373 lintBaseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, lintFilename))
374 } else {
375 lintBaseline = android.ExistentPathForSource(ctx, ctx.ModuleDir(), lintFilename)
376 }
377 }
378 return lintBaseline
379}
380
Colin Cross014489c2020-06-02 20:09:13 -0700381func (l *linter) lint(ctx android.ModuleContext) {
382 if !l.enabled() {
383 return
384 }
385
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000386 if l.minSdkVersion != l.compileSdkVersion {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700387 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100388 // Skip lint warning checks for NewApi warnings for libcore where they come from source
389 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100390 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100391 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
392
393 if len(filtered) != 0 {
394 ctx.PropertyErrorf("lint.warning_checks",
395 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
396 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700397 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100398
399 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700400 if len(filtered) != 0 {
401 ctx.PropertyErrorf("lint.disabled_checks",
402 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
403 }
Cole Faust3f646262022-06-29 14:58:03 -0700404
405 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
406 if ctx.ModuleName() == "PermissionController" {
407 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
408 return s != "NewApi"
409 })
410 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
411 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000412 }
413
Colin Cross92e4b462020-06-18 15:56:48 -0700414 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
415 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Crossdcf71b22021-02-01 13:59:03 -0800416 if ctx.OtherModuleHasProvider(extraLintCheckModule, JavaInfoProvider) {
417 dep := ctx.OtherModuleProvider(extraLintCheckModule, JavaInfoProvider).(JavaInfo)
418 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700419 } else {
420 ctx.PropertyErrorf("lint.extra_check_modules",
421 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
422 }
423 }
424
mattgilbride5aecabe2022-11-29 20:16:36 +0000425 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
426 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
427
Colin Cross1661aff2021-03-12 17:56:51 -0800428 rule := android.NewRuleBuilder(pctx, ctx).
429 Sbox(android.PathForModuleOut(ctx, "lint"),
430 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
431 SandboxInputs()
432
433 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
434 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
435 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
436 rule.Rewrapper(&remoteexec.REParams{
437 Labels: map[string]string{"type": "tool", "name": "lint"},
438 ExecStrategy: lintRBEExecStrategy(ctx),
439 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700440 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800441 })
442 }
Colin Cross014489c2020-06-02 20:09:13 -0700443
444 if l.manifest == nil {
445 manifest := l.generateManifest(ctx, rule)
446 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800447 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700448 }
449
Colin Cross62695b92022-08-12 16:09:24 -0700450 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
451 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
Cole Faustdf1efd72023-12-08 12:27:24 -0800452 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList).Implicits(l.compile_data)
Colin Cross62695b92022-08-12 16:09:24 -0700453
454 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700455
Colin Cross1661aff2021-03-12 17:56:51 -0800456 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
457 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
458 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Cole Faustdf38f7a2023-03-02 16:43:15 -0800459 referenceBaseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700460
Colin Cross08dca382020-07-21 20:31:17 -0700461 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700462
463 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000464 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700465 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700466 }
467 })
Colin Cross014489c2020-06-02 20:09:13 -0700468
Colin Cross31972dc2021-03-04 10:44:12 -0800469 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
470 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800471 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700472
Cole Faust69861aa2023-01-31 15:49:07 -0800473 files, ok := allLintDatabasefiles[l.compileSdkKind]
474 if !ok {
475 files = allLintDatabasefiles[android.SdkPublic]
Pedro Loureiro18233a22021-06-08 18:11:21 +0000476 }
Colin Cross8a6ed372020-07-06 11:45:51 -0700477 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900478 if ctx.Config().AlwaysUsePrebuiltSdks() {
Cole Faust69861aa2023-01-31 15:49:07 -0800479 annotationsZipPath = android.PathForSource(ctx, files.annotationPrebuiltpath)
480 apiVersionsXMLPath = android.PathForSource(ctx, files.apiVersionsPrebuiltPath)
Colin Cross8a6ed372020-07-06 11:45:51 -0700481 } else {
Cole Faust69861aa2023-01-31 15:49:07 -0800482 annotationsZipPath = copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName)
483 apiVersionsXMLPath = copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700484 }
485
Colin Cross31972dc2021-03-04 10:44:12 -0800486 cmd := rule.Command()
487
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000488 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800489 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700490 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800491 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
492
Colin Cross1661aff2021-03-12 17:56:51 -0800493 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700494 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800495 FlagWithInput("--project ", lintPaths.projectXML).
496 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700497 FlagWithOutput("--html ", html).
498 FlagWithOutput("--text ", text).
499 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000500 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700501 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
502 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
503 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
Colin Cross62695b92022-08-12 16:09:24 -0700504 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700505 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800506 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700507 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700508
Colin Cross1661aff2021-03-12 17:56:51 -0800509 rule.Temporary(lintPaths.projectXML)
510 rule.Temporary(lintPaths.configXML)
511
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +1000512 suppressExitCode := BoolDefault(l.properties.Lint.Suppress_exit_code, false)
513 if exitCode := ctx.Config().Getenv("ANDROID_LINT_SUPPRESS_EXIT_CODE"); exitCode == "" && !suppressExitCode {
mattgilbrideb597abd2023-03-22 17:44:18 +0000514 cmd.Flag("--exitcode")
515 }
516
Colin Cross988dfcc2020-07-16 17:32:17 -0700517 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
518 cmd.FlagWithArg("--check ", checkOnly)
519 }
520
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700521 lintBaseline := l.getBaselineFilepath(ctx)
522 if lintBaseline.Valid() {
523 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000524 }
525
Cole Faustdf38f7a2023-03-02 16:43:15 -0800526 cmd.FlagWithOutput("--write-reference-baseline ", referenceBaseline)
Colin Cross6b76c152021-09-09 09:36:25 -0700527
Colin Cross1b9e6832022-10-11 11:22:24 -0700528 cmd.Text("; EXITCODE=$?; ")
529
530 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
531 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
532 // a fatal error.
533 cmd.BuiltTool("soong_zip").
534 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
535 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
536 FlagWithInput("-r ", srcsList)
537
538 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 -0700539
Colin Cross31972dc2021-03-04 10:44:12 -0800540 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700541
Colin Crossee4a8b72021-04-05 18:38:05 -0700542 // The HTML output contains a date, remove it to make the output deterministic.
543 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
544
Colin Crossf1a035e2020-11-16 17:32:30 -0800545 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700546
Colin Crossc0efd1d2020-07-03 11:56:24 -0700547 l.outputs = lintOutputs{
Cole Faustdf38f7a2023-03-02 16:43:15 -0800548 html: html,
549 text: text,
550 xml: xml,
551 referenceBaseline: referenceBaseline,
Colin Cross014489c2020-06-02 20:09:13 -0700552
Colin Cross08dca382020-07-21 20:31:17 -0700553 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700554 }
Colin Cross014489c2020-06-02 20:09:13 -0700555
Colin Crossc0efd1d2020-07-03 11:56:24 -0700556 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700557 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700558 }
559}
Colin Cross014489c2020-06-02 20:09:13 -0700560
Colin Cross08dca382020-07-21 20:31:17 -0700561func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
Colin Crossc85750b2022-04-21 12:50:51 -0700562 htmlList := android.SortedUniquePaths(depSets.HTML.ToList())
563 textList := android.SortedUniquePaths(depSets.Text.ToList())
564 xmlList := android.SortedUniquePaths(depSets.XML.ToList())
Colin Cross08dca382020-07-21 20:31:17 -0700565
566 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
567 return nil
568 }
569
570 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
571 lintZip(ctx, htmlList, htmlZip)
572
573 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
574 lintZip(ctx, textList, textZip)
575
576 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
577 lintZip(ctx, xmlList, xmlZip)
578
579 return android.Paths{htmlZip, textZip, xmlZip}
580}
581
Colin Cross014489c2020-06-02 20:09:13 -0700582type lintSingleton struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800583 htmlZip android.WritablePath
584 textZip android.WritablePath
585 xmlZip android.WritablePath
586 referenceBaselineZip android.WritablePath
Colin Cross014489c2020-06-02 20:09:13 -0700587}
588
589func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
590 l.generateLintReportZips(ctx)
591 l.copyLintDependencies(ctx)
592}
593
Pedro Loureiro18233a22021-06-08 18:11:21 +0000594func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
595 var res android.Module
596 ctx.VisitAllModules(func(m android.Module) {
597 if ctx.ModuleName(m) == moduleName {
598 if res == nil {
599 res = m
600 } else {
601 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
602 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
603 }
604 }
605 })
606 return res
607}
608
Colin Cross014489c2020-06-02 20:09:13 -0700609func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900610 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700611 return
612 }
613
Cole Faust69861aa2023-01-31 15:49:07 -0800614 for _, sdk := range android.SortedKeys(allLintDatabasefiles) {
615 files := allLintDatabasefiles[sdk]
616 apiVersionsDb := findModuleOrErr(ctx, files.apiVersionsModule)
617 if apiVersionsDb == nil {
618 if !ctx.Config().AllowMissingDependencies() {
619 ctx.Errorf("lint: missing module api_versions_public")
620 }
621 return
Colin Cross014489c2020-06-02 20:09:13 -0700622 }
Colin Cross014489c2020-06-02 20:09:13 -0700623
Cole Faust69861aa2023-01-31 15:49:07 -0800624 sdkAnnotations := findModuleOrErr(ctx, files.annotationsModule)
625 if sdkAnnotations == nil {
626 if !ctx.Config().AllowMissingDependencies() {
627 ctx.Errorf("lint: missing module sdk-annotations.zip")
628 }
629 return
Anton Hanssonea17a452022-05-09 09:42:17 +0000630 }
Cole Faust69861aa2023-01-31 15:49:07 -0800631
632 ctx.Build(pctx, android.BuildParams{
633 Rule: android.CpIfChanged,
634 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
635 Output: copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName),
636 })
637
638 ctx.Build(pctx, android.BuildParams{
639 Rule: android.CpIfChanged,
640 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
641 Output: copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName),
642 })
Anton Hanssonea17a452022-05-09 09:42:17 +0000643 }
Colin Cross014489c2020-06-02 20:09:13 -0700644}
645
Cole Faust69861aa2023-01-31 15:49:07 -0800646func copiedLintDatabaseFilesPath(ctx android.PathContext, name string) android.WritablePath {
Pedro Loureiro18233a22021-06-08 18:11:21 +0000647 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700648}
649
650func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700651 if ctx.Config().UnbundledBuild() {
652 return
653 }
654
Colin Cross014489c2020-06-02 20:09:13 -0700655 var outputs []*lintOutputs
656 var dirs []string
657 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500658 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700659 return
660 }
661
Colin Cross56a83212020-09-15 18:30:11 -0700662 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
663 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
664 if apexInfo.IsForPlatform() {
665 // There are stray platform variants of modules in apexes that are not available for
666 // the platform, and they sometimes can't be built. Don't depend on them.
667 return
668 }
Colin Cross014489c2020-06-02 20:09:13 -0700669 }
670
Colin Cross08dca382020-07-21 20:31:17 -0700671 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700672 outputs = append(outputs, l.lintOutputs())
673 }
674 })
675
676 dirs = android.SortedUniqueStrings(dirs)
677
678 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
679 var paths android.Paths
680
681 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700682 if p := get(output); p != nil {
683 paths = append(paths, p)
684 }
Colin Cross014489c2020-06-02 20:09:13 -0700685 }
686
Colin Crossc0efd1d2020-07-03 11:56:24 -0700687 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700688 }
689
690 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
691 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
692
693 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
694 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
695
696 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
697 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
698
Cole Faustdf38f7a2023-03-02 16:43:15 -0800699 l.referenceBaselineZip = android.PathForOutput(ctx, "lint-report-reference-baselines.zip")
700 zip(l.referenceBaselineZip, func(l *lintOutputs) android.Path { return l.referenceBaseline })
701
702 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross014489c2020-06-02 20:09:13 -0700703}
704
705func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700706 if !ctx.Config().UnbundledBuild() {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800707 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross8a6ed372020-07-06 11:45:51 -0700708 }
Colin Cross014489c2020-06-02 20:09:13 -0700709}
710
711var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
712
713func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +0000714 android.RegisterParallelSingletonType("lint",
Colin Cross014489c2020-06-02 20:09:13 -0700715 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700716
717 registerLintBuildComponents(android.InitRegistrationContext)
718}
719
720func registerLintBuildComponents(ctx android.RegistrationContext) {
721 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
722 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
723 })
Colin Cross014489c2020-06-02 20:09:13 -0700724}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700725
726func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
727 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
728
729 sort.Slice(paths, func(i, j int) bool {
730 return paths[i].String() < paths[j].String()
731 })
732
Colin Crossf1a035e2020-11-16 17:32:30 -0800733 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700734
Colin Crossf1a035e2020-11-16 17:32:30 -0800735 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700736 FlagWithOutput("-o ", outputPath).
737 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800738 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700739
Colin Crossf1a035e2020-11-16 17:32:30 -0800740 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700741}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700742
743// Enforce the strict updatability linting to all applicable transitive dependencies.
744func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
745 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000746 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700747 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000748 if a, ok := d.(LintDepSetsIntf); ok {
749 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700750 }
751 })
752 }
753}