blob: e831faf9df236e3271b792319192bc77f9dba1f8 [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
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000022 "github.com/google/blueprint/proptools"
23
Colin Cross014489c2020-06-02 20:09:13 -070024 "android/soong/android"
Colin Cross31972dc2021-03-04 10:44:12 -080025 "android/soong/java/config"
26 "android/soong/remoteexec"
Colin Cross014489c2020-06-02 20:09:13 -070027)
28
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -070029// lint checks automatically enforced for modules that have different min_sdk_version than
30// sdk_version
31var updatabilityChecks = []string{"NewApi"}
32
Colin Cross014489c2020-06-02 20:09:13 -070033type LintProperties struct {
34 // Controls for running Android Lint on the module.
35 Lint struct {
36
37 // If true, run Android Lint on the module. Defaults to true.
38 Enabled *bool
39
40 // Flags to pass to the Android Lint tool.
41 Flags []string
42
43 // Checks that should be treated as fatal.
44 Fatal_checks []string
45
46 // Checks that should be treated as errors.
47 Error_checks []string
48
49 // Checks that should be treated as warnings.
50 Warning_checks []string
51
52 // Checks that should be skipped.
53 Disabled_checks []string
Colin Cross92e4b462020-06-18 15:56:48 -070054
55 // Modules that provide extra lint checks
56 Extra_check_modules []string
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000057
58 // Name of the file that lint uses as the baseline. Defaults to "lint-baseline.xml".
59 Baseline_filename *string
Jaewoong Jung48de8832021-04-21 16:17:25 -070060
61 // If true, baselining updatability lint checks (e.g. NewApi) is prohibited. Defaults to false.
62 Strict_updatability_linting *bool
Cole Faustd57e8b22022-08-11 11:59:04 -070063
64 // Treat the code in this module as test code for @VisibleForTesting enforcement.
65 // This will be true by default for test module types, false otherwise.
66 // If soong gets support for testonly, this flag should be replaced with that.
67 Test *bool
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +100068
69 // Whether to ignore the exit code of Android lint. This is the --exit_code
70 // option. Defaults to false.
71 Suppress_exit_code *bool
Colin Cross014489c2020-06-02 20:09:13 -070072 }
73}
74
75type linter struct {
Pedro Loureirof4a88b12021-02-25 16:23:22 +000076 name string
77 manifest android.Path
78 mergedManifest android.Path
79 srcs android.Paths
80 srcJars android.Paths
81 resources android.Paths
82 classpath android.Paths
83 classes android.Path
84 extraLintCheckJars android.Paths
Pedro Loureirof4a88b12021-02-25 16:23:22 +000085 library bool
Zi Wange1166f02023-11-06 11:43:17 -080086 minSdkVersion android.ApiLevel
87 targetSdkVersion android.ApiLevel
88 compileSdkVersion android.ApiLevel
Pedro Loureiro18233a22021-06-08 18:11:21 +000089 compileSdkKind android.SdkKind
Pedro Loureirof4a88b12021-02-25 16:23:22 +000090 javaLanguageLevel string
91 kotlinLanguageLevel string
92 outputs lintOutputs
93 properties LintProperties
94 extraMainlineLintErrors []string
Colin Crossc0efd1d2020-07-03 11:56:24 -070095
Colin Cross08dca382020-07-21 20:31:17 -070096 reports android.Paths
97
Colin Crossc0efd1d2020-07-03 11:56:24 -070098 buildModuleReportZip bool
Colin Cross014489c2020-06-02 20:09:13 -070099}
100
101type lintOutputs struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800102 html android.Path
103 text android.Path
104 xml android.Path
105 referenceBaseline android.Path
Colin Crossc0efd1d2020-07-03 11:56:24 -0700106
Colin Cross08dca382020-07-21 20:31:17 -0700107 depSets LintDepSets
Colin Crossc0efd1d2020-07-03 11:56:24 -0700108}
109
Colin Cross08dca382020-07-21 20:31:17 -0700110type lintOutputsIntf interface {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700111 lintOutputs() *lintOutputs
112}
113
Spandan Das17854f52022-01-14 21:19:14 +0000114type LintDepSetsIntf interface {
Colin Cross08dca382020-07-21 20:31:17 -0700115 LintDepSets() LintDepSets
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700116
117 // Methods used to propagate strict_updatability_linting values.
Spandan Das17854f52022-01-14 21:19:14 +0000118 GetStrictUpdatabilityLinting() bool
119 SetStrictUpdatabilityLinting(bool)
Colin Cross08dca382020-07-21 20:31:17 -0700120}
121
122type LintDepSets struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700123 HTML, Text, XML *android.DepSet[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700124}
125
126type LintDepSetsBuilder struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700127 HTML, Text, XML *android.DepSetBuilder[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700128}
129
130func NewLintDepSetBuilder() LintDepSetsBuilder {
131 return LintDepSetsBuilder{
Colin Crossc85750b2022-04-21 12:50:51 -0700132 HTML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
133 Text: android.NewDepSetBuilder[android.Path](android.POSTORDER),
134 XML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
Colin Cross08dca382020-07-21 20:31:17 -0700135 }
136}
137
138func (l LintDepSetsBuilder) Direct(html, text, xml android.Path) LintDepSetsBuilder {
139 l.HTML.Direct(html)
140 l.Text.Direct(text)
141 l.XML.Direct(xml)
142 return l
143}
144
145func (l LintDepSetsBuilder) Transitive(depSets LintDepSets) LintDepSetsBuilder {
146 if depSets.HTML != nil {
147 l.HTML.Transitive(depSets.HTML)
148 }
149 if depSets.Text != nil {
150 l.Text.Transitive(depSets.Text)
151 }
152 if depSets.XML != nil {
153 l.XML.Transitive(depSets.XML)
154 }
155 return l
156}
157
158func (l LintDepSetsBuilder) Build() LintDepSets {
159 return LintDepSets{
160 HTML: l.HTML.Build(),
161 Text: l.Text.Build(),
162 XML: l.XML.Build(),
163 }
164}
165
Cole Faust69861aa2023-01-31 15:49:07 -0800166type lintDatabaseFiles struct {
167 apiVersionsModule string
168 apiVersionsCopiedName string
169 apiVersionsPrebuiltPath string
170 annotationsModule string
171 annotationCopiedName string
172 annotationPrebuiltpath string
173}
174
175var allLintDatabasefiles = map[android.SdkKind]lintDatabaseFiles{
176 android.SdkPublic: {
177 apiVersionsModule: "api_versions_public",
178 apiVersionsCopiedName: "api_versions_public.xml",
179 apiVersionsPrebuiltPath: "prebuilts/sdk/current/public/data/api-versions.xml",
180 annotationsModule: "sdk-annotations.zip",
181 annotationCopiedName: "annotations-public.zip",
182 annotationPrebuiltpath: "prebuilts/sdk/current/public/data/annotations.zip",
183 },
184 android.SdkSystem: {
185 apiVersionsModule: "api_versions_system",
186 apiVersionsCopiedName: "api_versions_system.xml",
187 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system/data/api-versions.xml",
188 annotationsModule: "sdk-annotations-system.zip",
189 annotationCopiedName: "annotations-system.zip",
190 annotationPrebuiltpath: "prebuilts/sdk/current/system/data/annotations.zip",
191 },
192 android.SdkModule: {
193 apiVersionsModule: "api_versions_module_lib",
194 apiVersionsCopiedName: "api_versions_module_lib.xml",
195 apiVersionsPrebuiltPath: "prebuilts/sdk/current/module-lib/data/api-versions.xml",
196 annotationsModule: "sdk-annotations-module-lib.zip",
197 annotationCopiedName: "annotations-module-lib.zip",
198 annotationPrebuiltpath: "prebuilts/sdk/current/module-lib/data/annotations.zip",
199 },
200 android.SdkSystemServer: {
201 apiVersionsModule: "api_versions_system_server",
202 apiVersionsCopiedName: "api_versions_system_server.xml",
203 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system-server/data/api-versions.xml",
204 annotationsModule: "sdk-annotations-system-server.zip",
205 annotationCopiedName: "annotations-system-server.zip",
206 annotationPrebuiltpath: "prebuilts/sdk/current/system-server/data/annotations.zip",
207 },
208}
209
Colin Cross08dca382020-07-21 20:31:17 -0700210func (l *linter) LintDepSets() LintDepSets {
211 return l.outputs.depSets
212}
213
Spandan Das17854f52022-01-14 21:19:14 +0000214func (l *linter) GetStrictUpdatabilityLinting() bool {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700215 return BoolDefault(l.properties.Lint.Strict_updatability_linting, false)
216}
217
Spandan Das17854f52022-01-14 21:19:14 +0000218func (l *linter) SetStrictUpdatabilityLinting(strictLinting bool) {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700219 l.properties.Lint.Strict_updatability_linting = &strictLinting
220}
221
Spandan Das17854f52022-01-14 21:19:14 +0000222var _ LintDepSetsIntf = (*linter)(nil)
Colin Cross08dca382020-07-21 20:31:17 -0700223
224var _ lintOutputsIntf = (*linter)(nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700225
226func (l *linter) lintOutputs() *lintOutputs {
227 return &l.outputs
Colin Cross014489c2020-06-02 20:09:13 -0700228}
229
230func (l *linter) enabled() bool {
231 return BoolDefault(l.properties.Lint.Enabled, true)
232}
233
Colin Cross92e4b462020-06-18 15:56:48 -0700234func (l *linter) deps(ctx android.BottomUpMutatorContext) {
235 if !l.enabled() {
236 return
237 }
238
Colin Cross988dfcc2020-07-16 17:32:17 -0700239 extraCheckModules := l.properties.Lint.Extra_check_modules
240
mattgilbridee17645f2022-11-18 18:20:20 +0000241 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
242 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700243 }
244
245 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
246 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700247}
248
Colin Crossad22bc22021-03-10 09:45:40 -0800249// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
250// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800251type lintPaths struct {
252 projectXML android.WritablePath
253 configXML android.WritablePath
254 cacheDir android.WritablePath
255 homeDir android.WritablePath
256 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800257}
258
Colin Cross9b93af42021-03-10 10:40:58 -0800259func lintRBEExecStrategy(ctx android.ModuleContext) string {
260 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
261}
262
Colin Cross62695b92022-08-12 16:09:24 -0700263func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path) lintPaths {
Colin Cross31972dc2021-03-04 10:44:12 -0800264 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700265 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800266 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
267 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
268 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700269
Colin Cross1661aff2021-03-12 17:56:51 -0800270 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700271 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
272
273 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700274 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700275 FlagWithOutput("--project_out ", projectXMLPath).
276 FlagWithOutput("--config_out ", configXMLPath).
277 FlagWithArg("--name ", ctx.ModuleName())
278
279 if l.library {
280 cmd.Flag("--library")
281 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700282 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700283 cmd.Flag("--test")
284 }
285 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700286 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700287 }
288 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700289 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700290 }
291
Colin Cross5bedfa22021-03-23 17:07:14 -0700292 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
293 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700294 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700295
296 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700297
Colin Cross5bedfa22021-03-23 17:07:14 -0700298 if len(l.resources) > 0 {
299 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
300 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700301 }
302
303 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700304 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700305 }
306
Colin Cross5bedfa22021-03-23 17:07:14 -0700307 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700308
Colin Cross5bedfa22021-03-23 17:07:14 -0700309 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700310
Colin Cross1661aff2021-03-12 17:56:51 -0800311 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700312
313 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
314 // the root dir is not set.
315 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700316
317 cmd.FlagWithInput("@",
318 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
319
Cole Faust69861aa2023-01-31 15:49:07 -0800320 if l.compileSdkKind == android.SdkPublic {
321 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
322 } else {
323 // TODO(b/268261262): Remove this branch. We're demoting NewApi to a warning due to pre-existing issues that need to be fixed.
324 cmd.FlagForEachArg("--warning_check ", l.extraMainlineLintErrors)
325 }
Colin Cross014489c2020-06-02 20:09:13 -0700326 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
327 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
328 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
329 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
330
Cole Faust1021ccd2023-02-26 21:15:25 -0800331 // TODO(b/193460475): Re-enable strict updatability linting
332 //if l.GetStrictUpdatabilityLinting() {
333 // // Verify the module does not baseline issues that endanger safe updatability.
334 // if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
335 // cmd.FlagWithInput("--baseline ", baselinePath.Path())
336 // cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
337 // }
338 //}
Jaewoong Jung48de8832021-04-21 16:17:25 -0700339
Colin Cross31972dc2021-03-04 10:44:12 -0800340 return lintPaths{
341 projectXML: projectXMLPath,
342 configXML: configXMLPath,
343 cacheDir: cacheDir,
344 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800345 }
346
Colin Cross014489c2020-06-02 20:09:13 -0700347}
348
Liz Kammer20ebfb42020-07-28 11:32:07 -0700349// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700350// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800351func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700352 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
353
354 rule.Command().Text("(").
355 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
356 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
357 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Zi Wange1166f02023-11-06 11:43:17 -0800358 Textf(`echo " <uses-sdk android:minSdkVersion='%s' android:targetSdkVersion='%s'/>" &&`,
359 l.minSdkVersion.String(), l.targetSdkVersion.String()).
Colin Cross014489c2020-06-02 20:09:13 -0700360 Text(`echo "</manifest>"`).
361 Text(") >").Output(manifestPath)
362
363 return manifestPath
364}
365
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700366func (l *linter) getBaselineFilepath(ctx android.ModuleContext) android.OptionalPath {
367 var lintBaseline android.OptionalPath
368 if lintFilename := proptools.StringDefault(l.properties.Lint.Baseline_filename, "lint-baseline.xml"); lintFilename != "" {
369 if String(l.properties.Lint.Baseline_filename) != "" {
370 // if manually specified, we require the file to exist
371 lintBaseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, lintFilename))
372 } else {
373 lintBaseline = android.ExistentPathForSource(ctx, ctx.ModuleDir(), lintFilename)
374 }
375 }
376 return lintBaseline
377}
378
Colin Cross014489c2020-06-02 20:09:13 -0700379func (l *linter) lint(ctx android.ModuleContext) {
380 if !l.enabled() {
381 return
382 }
383
Zi Wange1166f02023-11-06 11:43:17 -0800384 if l.minSdkVersion.CompareTo(l.compileSdkVersion) == -1 {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700385 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100386 // Skip lint warning checks for NewApi warnings for libcore where they come from source
387 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100388 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100389 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
390
391 if len(filtered) != 0 {
392 ctx.PropertyErrorf("lint.warning_checks",
393 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
394 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700395 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100396
397 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700398 if len(filtered) != 0 {
399 ctx.PropertyErrorf("lint.disabled_checks",
400 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
401 }
Cole Faust3f646262022-06-29 14:58:03 -0700402
403 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
404 if ctx.ModuleName() == "PermissionController" {
405 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
406 return s != "NewApi"
407 })
408 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
409 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000410 }
411
Colin Cross92e4b462020-06-18 15:56:48 -0700412 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
413 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Crossdcf71b22021-02-01 13:59:03 -0800414 if ctx.OtherModuleHasProvider(extraLintCheckModule, JavaInfoProvider) {
415 dep := ctx.OtherModuleProvider(extraLintCheckModule, JavaInfoProvider).(JavaInfo)
416 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700417 } else {
418 ctx.PropertyErrorf("lint.extra_check_modules",
419 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
420 }
421 }
422
mattgilbride5aecabe2022-11-29 20:16:36 +0000423 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
424 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
425
Colin Cross1661aff2021-03-12 17:56:51 -0800426 rule := android.NewRuleBuilder(pctx, ctx).
427 Sbox(android.PathForModuleOut(ctx, "lint"),
428 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
429 SandboxInputs()
430
431 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
432 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
433 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
434 rule.Rewrapper(&remoteexec.REParams{
435 Labels: map[string]string{"type": "tool", "name": "lint"},
436 ExecStrategy: lintRBEExecStrategy(ctx),
437 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700438 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800439 })
440 }
Colin Cross014489c2020-06-02 20:09:13 -0700441
442 if l.manifest == nil {
443 manifest := l.generateManifest(ctx, rule)
444 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800445 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700446 }
447
Colin Cross62695b92022-08-12 16:09:24 -0700448 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
449 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
450 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList)
451
452 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700453
Colin Cross1661aff2021-03-12 17:56:51 -0800454 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
455 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
456 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Cole Faustdf38f7a2023-03-02 16:43:15 -0800457 referenceBaseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700458
Colin Cross08dca382020-07-21 20:31:17 -0700459 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700460
461 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000462 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700463 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700464 }
465 })
Colin Cross014489c2020-06-02 20:09:13 -0700466
Colin Cross31972dc2021-03-04 10:44:12 -0800467 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
468 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800469 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700470
Cole Faust69861aa2023-01-31 15:49:07 -0800471 files, ok := allLintDatabasefiles[l.compileSdkKind]
472 if !ok {
473 files = allLintDatabasefiles[android.SdkPublic]
Pedro Loureiro18233a22021-06-08 18:11:21 +0000474 }
Colin Cross8a6ed372020-07-06 11:45:51 -0700475 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900476 if ctx.Config().AlwaysUsePrebuiltSdks() {
Cole Faust69861aa2023-01-31 15:49:07 -0800477 annotationsZipPath = android.PathForSource(ctx, files.annotationPrebuiltpath)
478 apiVersionsXMLPath = android.PathForSource(ctx, files.apiVersionsPrebuiltPath)
Colin Cross8a6ed372020-07-06 11:45:51 -0700479 } else {
Cole Faust69861aa2023-01-31 15:49:07 -0800480 annotationsZipPath = copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName)
481 apiVersionsXMLPath = copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700482 }
483
Colin Cross31972dc2021-03-04 10:44:12 -0800484 cmd := rule.Command()
485
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000486 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800487 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700488 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800489 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
490
Colin Cross1661aff2021-03-12 17:56:51 -0800491 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700492 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800493 FlagWithInput("--project ", lintPaths.projectXML).
494 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700495 FlagWithOutput("--html ", html).
496 FlagWithOutput("--text ", text).
497 FlagWithOutput("--xml ", xml).
Zi Wange1166f02023-11-06 11:43:17 -0800498 FlagWithArg("--compile-sdk-version ", l.compileSdkVersion.String()).
Colin Cross014489c2020-06-02 20:09:13 -0700499 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
500 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
501 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
Colin Cross62695b92022-08-12 16:09:24 -0700502 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700503 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800504 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700505 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700506
Colin Cross1661aff2021-03-12 17:56:51 -0800507 rule.Temporary(lintPaths.projectXML)
508 rule.Temporary(lintPaths.configXML)
509
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +1000510 suppressExitCode := BoolDefault(l.properties.Lint.Suppress_exit_code, false)
511 if exitCode := ctx.Config().Getenv("ANDROID_LINT_SUPPRESS_EXIT_CODE"); exitCode == "" && !suppressExitCode {
mattgilbrideb597abd2023-03-22 17:44:18 +0000512 cmd.Flag("--exitcode")
513 }
514
Colin Cross988dfcc2020-07-16 17:32:17 -0700515 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
516 cmd.FlagWithArg("--check ", checkOnly)
517 }
518
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700519 lintBaseline := l.getBaselineFilepath(ctx)
520 if lintBaseline.Valid() {
521 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000522 }
523
Cole Faustdf38f7a2023-03-02 16:43:15 -0800524 cmd.FlagWithOutput("--write-reference-baseline ", referenceBaseline)
Colin Cross6b76c152021-09-09 09:36:25 -0700525
Colin Cross1b9e6832022-10-11 11:22:24 -0700526 cmd.Text("; EXITCODE=$?; ")
527
528 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
529 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
530 // a fatal error.
531 cmd.BuiltTool("soong_zip").
532 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
533 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
534 FlagWithInput("-r ", srcsList)
535
536 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 -0700537
Colin Cross31972dc2021-03-04 10:44:12 -0800538 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700539
Colin Crossee4a8b72021-04-05 18:38:05 -0700540 // The HTML output contains a date, remove it to make the output deterministic.
541 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
542
Colin Crossf1a035e2020-11-16 17:32:30 -0800543 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700544
Colin Crossc0efd1d2020-07-03 11:56:24 -0700545 l.outputs = lintOutputs{
Cole Faustdf38f7a2023-03-02 16:43:15 -0800546 html: html,
547 text: text,
548 xml: xml,
549 referenceBaseline: referenceBaseline,
Colin Cross014489c2020-06-02 20:09:13 -0700550
Colin Cross08dca382020-07-21 20:31:17 -0700551 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700552 }
Colin Cross014489c2020-06-02 20:09:13 -0700553
Colin Crossc0efd1d2020-07-03 11:56:24 -0700554 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700555 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700556 }
557}
Colin Cross014489c2020-06-02 20:09:13 -0700558
Colin Cross08dca382020-07-21 20:31:17 -0700559func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
Colin Crossc85750b2022-04-21 12:50:51 -0700560 htmlList := android.SortedUniquePaths(depSets.HTML.ToList())
561 textList := android.SortedUniquePaths(depSets.Text.ToList())
562 xmlList := android.SortedUniquePaths(depSets.XML.ToList())
Colin Cross08dca382020-07-21 20:31:17 -0700563
564 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
565 return nil
566 }
567
568 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
569 lintZip(ctx, htmlList, htmlZip)
570
571 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
572 lintZip(ctx, textList, textZip)
573
574 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
575 lintZip(ctx, xmlList, xmlZip)
576
577 return android.Paths{htmlZip, textZip, xmlZip}
578}
579
Colin Cross014489c2020-06-02 20:09:13 -0700580type lintSingleton struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800581 htmlZip android.WritablePath
582 textZip android.WritablePath
583 xmlZip android.WritablePath
584 referenceBaselineZip android.WritablePath
Colin Cross014489c2020-06-02 20:09:13 -0700585}
586
587func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
588 l.generateLintReportZips(ctx)
589 l.copyLintDependencies(ctx)
590}
591
Pedro Loureiro18233a22021-06-08 18:11:21 +0000592func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
593 var res android.Module
594 ctx.VisitAllModules(func(m android.Module) {
595 if ctx.ModuleName(m) == moduleName {
596 if res == nil {
597 res = m
598 } else {
599 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
600 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
601 }
602 }
603 })
604 return res
605}
606
Colin Cross014489c2020-06-02 20:09:13 -0700607func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900608 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700609 return
610 }
611
Cole Faust69861aa2023-01-31 15:49:07 -0800612 for _, sdk := range android.SortedKeys(allLintDatabasefiles) {
613 files := allLintDatabasefiles[sdk]
614 apiVersionsDb := findModuleOrErr(ctx, files.apiVersionsModule)
615 if apiVersionsDb == nil {
616 if !ctx.Config().AllowMissingDependencies() {
617 ctx.Errorf("lint: missing module api_versions_public")
618 }
619 return
Colin Cross014489c2020-06-02 20:09:13 -0700620 }
Colin Cross014489c2020-06-02 20:09:13 -0700621
Cole Faust69861aa2023-01-31 15:49:07 -0800622 sdkAnnotations := findModuleOrErr(ctx, files.annotationsModule)
623 if sdkAnnotations == nil {
624 if !ctx.Config().AllowMissingDependencies() {
625 ctx.Errorf("lint: missing module sdk-annotations.zip")
626 }
627 return
Anton Hanssonea17a452022-05-09 09:42:17 +0000628 }
Cole Faust69861aa2023-01-31 15:49:07 -0800629
630 ctx.Build(pctx, android.BuildParams{
631 Rule: android.CpIfChanged,
632 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
633 Output: copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName),
634 })
635
636 ctx.Build(pctx, android.BuildParams{
637 Rule: android.CpIfChanged,
638 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
639 Output: copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName),
640 })
Anton Hanssonea17a452022-05-09 09:42:17 +0000641 }
Colin Cross014489c2020-06-02 20:09:13 -0700642}
643
Cole Faust69861aa2023-01-31 15:49:07 -0800644func copiedLintDatabaseFilesPath(ctx android.PathContext, name string) android.WritablePath {
Pedro Loureiro18233a22021-06-08 18:11:21 +0000645 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700646}
647
648func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700649 if ctx.Config().UnbundledBuild() {
650 return
651 }
652
Colin Cross014489c2020-06-02 20:09:13 -0700653 var outputs []*lintOutputs
654 var dirs []string
655 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500656 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700657 return
658 }
659
Colin Cross56a83212020-09-15 18:30:11 -0700660 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
661 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
662 if apexInfo.IsForPlatform() {
663 // There are stray platform variants of modules in apexes that are not available for
664 // the platform, and they sometimes can't be built. Don't depend on them.
665 return
666 }
Colin Cross014489c2020-06-02 20:09:13 -0700667 }
668
Colin Cross08dca382020-07-21 20:31:17 -0700669 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700670 outputs = append(outputs, l.lintOutputs())
671 }
672 })
673
674 dirs = android.SortedUniqueStrings(dirs)
675
676 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
677 var paths android.Paths
678
679 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700680 if p := get(output); p != nil {
681 paths = append(paths, p)
682 }
Colin Cross014489c2020-06-02 20:09:13 -0700683 }
684
Colin Crossc0efd1d2020-07-03 11:56:24 -0700685 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700686 }
687
688 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
689 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
690
691 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
692 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
693
694 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
695 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
696
Cole Faustdf38f7a2023-03-02 16:43:15 -0800697 l.referenceBaselineZip = android.PathForOutput(ctx, "lint-report-reference-baselines.zip")
698 zip(l.referenceBaselineZip, func(l *lintOutputs) android.Path { return l.referenceBaseline })
699
700 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross014489c2020-06-02 20:09:13 -0700701}
702
703func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700704 if !ctx.Config().UnbundledBuild() {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800705 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross8a6ed372020-07-06 11:45:51 -0700706 }
Colin Cross014489c2020-06-02 20:09:13 -0700707}
708
709var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
710
711func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +0000712 android.RegisterParallelSingletonType("lint",
Colin Cross014489c2020-06-02 20:09:13 -0700713 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700714
715 registerLintBuildComponents(android.InitRegistrationContext)
716}
717
718func registerLintBuildComponents(ctx android.RegistrationContext) {
719 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
720 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
721 })
Colin Cross014489c2020-06-02 20:09:13 -0700722}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700723
724func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
725 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
726
727 sort.Slice(paths, func(i, j int) bool {
728 return paths[i].String() < paths[j].String()
729 })
730
Colin Crossf1a035e2020-11-16 17:32:30 -0800731 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700732
Colin Crossf1a035e2020-11-16 17:32:30 -0800733 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700734 FlagWithOutput("-o ", outputPath).
735 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800736 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700737
Colin Crossf1a035e2020-11-16 17:32:30 -0800738 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700739}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700740
741// Enforce the strict updatability linting to all applicable transitive dependencies.
742func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
743 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000744 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700745 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000746 if a, ok := d.(LintDepSetsIntf); ok {
747 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700748 }
749 })
750 }
751}