blob: 81666bfbb54aa0f56f454c1a1a930378c3ff3b45 [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
Colin Cross014489c2020-06-02 20:09:13 -070069 }
70}
71
72type linter struct {
Pedro Loureirof4a88b12021-02-25 16:23:22 +000073 name string
74 manifest android.Path
75 mergedManifest android.Path
76 srcs android.Paths
77 srcJars android.Paths
78 resources android.Paths
79 classpath android.Paths
80 classes android.Path
81 extraLintCheckJars android.Paths
Pedro Loureirof4a88b12021-02-25 16:23:22 +000082 library bool
Cole Fauste5bf3fb2022-07-01 19:39:14 +000083 minSdkVersion int
84 targetSdkVersion int
85 compileSdkVersion int
Pedro Loureiro18233a22021-06-08 18:11:21 +000086 compileSdkKind android.SdkKind
Pedro Loureirof4a88b12021-02-25 16:23:22 +000087 javaLanguageLevel string
88 kotlinLanguageLevel string
89 outputs lintOutputs
90 properties LintProperties
91 extraMainlineLintErrors []string
Colin Crossc0efd1d2020-07-03 11:56:24 -070092
Colin Cross08dca382020-07-21 20:31:17 -070093 reports android.Paths
94
Colin Crossc0efd1d2020-07-03 11:56:24 -070095 buildModuleReportZip bool
Colin Cross014489c2020-06-02 20:09:13 -070096}
97
98type lintOutputs struct {
Colin Cross08dca382020-07-21 20:31:17 -070099 html android.Path
100 text android.Path
101 xml android.Path
Colin Crossc0efd1d2020-07-03 11:56:24 -0700102
Colin Cross08dca382020-07-21 20:31:17 -0700103 depSets LintDepSets
Colin Crossc0efd1d2020-07-03 11:56:24 -0700104}
105
Colin Cross08dca382020-07-21 20:31:17 -0700106type lintOutputsIntf interface {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700107 lintOutputs() *lintOutputs
108}
109
Spandan Das17854f52022-01-14 21:19:14 +0000110type LintDepSetsIntf interface {
Colin Cross08dca382020-07-21 20:31:17 -0700111 LintDepSets() LintDepSets
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700112
113 // Methods used to propagate strict_updatability_linting values.
Spandan Das17854f52022-01-14 21:19:14 +0000114 GetStrictUpdatabilityLinting() bool
115 SetStrictUpdatabilityLinting(bool)
Colin Cross08dca382020-07-21 20:31:17 -0700116}
117
118type LintDepSets struct {
119 HTML, Text, XML *android.DepSet
120}
121
122type LintDepSetsBuilder struct {
123 HTML, Text, XML *android.DepSetBuilder
124}
125
126func NewLintDepSetBuilder() LintDepSetsBuilder {
127 return LintDepSetsBuilder{
128 HTML: android.NewDepSetBuilder(android.POSTORDER),
129 Text: android.NewDepSetBuilder(android.POSTORDER),
130 XML: android.NewDepSetBuilder(android.POSTORDER),
131 }
132}
133
134func (l LintDepSetsBuilder) Direct(html, text, xml android.Path) LintDepSetsBuilder {
135 l.HTML.Direct(html)
136 l.Text.Direct(text)
137 l.XML.Direct(xml)
138 return l
139}
140
141func (l LintDepSetsBuilder) Transitive(depSets LintDepSets) LintDepSetsBuilder {
142 if depSets.HTML != nil {
143 l.HTML.Transitive(depSets.HTML)
144 }
145 if depSets.Text != nil {
146 l.Text.Transitive(depSets.Text)
147 }
148 if depSets.XML != nil {
149 l.XML.Transitive(depSets.XML)
150 }
151 return l
152}
153
154func (l LintDepSetsBuilder) Build() LintDepSets {
155 return LintDepSets{
156 HTML: l.HTML.Build(),
157 Text: l.Text.Build(),
158 XML: l.XML.Build(),
159 }
160}
161
162func (l *linter) LintDepSets() LintDepSets {
163 return l.outputs.depSets
164}
165
Spandan Das17854f52022-01-14 21:19:14 +0000166func (l *linter) GetStrictUpdatabilityLinting() bool {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700167 return BoolDefault(l.properties.Lint.Strict_updatability_linting, false)
168}
169
Spandan Das17854f52022-01-14 21:19:14 +0000170func (l *linter) SetStrictUpdatabilityLinting(strictLinting bool) {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700171 l.properties.Lint.Strict_updatability_linting = &strictLinting
172}
173
Spandan Das17854f52022-01-14 21:19:14 +0000174var _ LintDepSetsIntf = (*linter)(nil)
Colin Cross08dca382020-07-21 20:31:17 -0700175
176var _ lintOutputsIntf = (*linter)(nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700177
178func (l *linter) lintOutputs() *lintOutputs {
179 return &l.outputs
Colin Cross014489c2020-06-02 20:09:13 -0700180}
181
182func (l *linter) enabled() bool {
183 return BoolDefault(l.properties.Lint.Enabled, true)
184}
185
Colin Cross92e4b462020-06-18 15:56:48 -0700186func (l *linter) deps(ctx android.BottomUpMutatorContext) {
187 if !l.enabled() {
188 return
189 }
190
Colin Cross988dfcc2020-07-16 17:32:17 -0700191 extraCheckModules := l.properties.Lint.Extra_check_modules
192
mattgilbridee17645f2022-11-18 18:20:20 +0000193 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
194 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700195 }
196
197 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
198 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700199}
200
Colin Crossad22bc22021-03-10 09:45:40 -0800201// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
202// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800203type lintPaths struct {
204 projectXML android.WritablePath
205 configXML android.WritablePath
206 cacheDir android.WritablePath
207 homeDir android.WritablePath
208 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800209}
210
Colin Cross9b93af42021-03-10 10:40:58 -0800211func lintRBEExecStrategy(ctx android.ModuleContext) string {
212 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
213}
214
Colin Cross62695b92022-08-12 16:09:24 -0700215func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path) lintPaths {
Colin Cross31972dc2021-03-04 10:44:12 -0800216 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700217 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800218 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
219 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
220 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700221
Colin Cross1661aff2021-03-12 17:56:51 -0800222 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700223 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
224
225 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700226 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700227 FlagWithOutput("--project_out ", projectXMLPath).
228 FlagWithOutput("--config_out ", configXMLPath).
229 FlagWithArg("--name ", ctx.ModuleName())
230
231 if l.library {
232 cmd.Flag("--library")
233 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700234 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700235 cmd.Flag("--test")
236 }
237 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700238 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700239 }
240 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700241 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700242 }
243
Colin Cross5bedfa22021-03-23 17:07:14 -0700244 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
245 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700246 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700247
248 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700249
Colin Cross5bedfa22021-03-23 17:07:14 -0700250 if len(l.resources) > 0 {
251 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
252 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700253 }
254
255 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700256 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700257 }
258
Colin Cross5bedfa22021-03-23 17:07:14 -0700259 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700260
Colin Cross5bedfa22021-03-23 17:07:14 -0700261 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700262
Colin Cross1661aff2021-03-12 17:56:51 -0800263 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700264
265 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
266 // the root dir is not set.
267 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700268
269 cmd.FlagWithInput("@",
270 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
271
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000272 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
Colin Cross014489c2020-06-02 20:09:13 -0700273 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
274 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
275 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
276 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
277
Cole Faust1021ccd2023-02-26 21:15:25 -0800278 // TODO(b/193460475): Re-enable strict updatability linting
279 //if l.GetStrictUpdatabilityLinting() {
280 // // Verify the module does not baseline issues that endanger safe updatability.
281 // if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
282 // cmd.FlagWithInput("--baseline ", baselinePath.Path())
283 // cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
284 // }
285 //}
Jaewoong Jung48de8832021-04-21 16:17:25 -0700286
Colin Cross31972dc2021-03-04 10:44:12 -0800287 return lintPaths{
288 projectXML: projectXMLPath,
289 configXML: configXMLPath,
290 cacheDir: cacheDir,
291 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800292 }
293
Colin Cross014489c2020-06-02 20:09:13 -0700294}
295
Liz Kammer20ebfb42020-07-28 11:32:07 -0700296// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700297// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800298func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700299 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
300
301 rule.Command().Text("(").
302 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
303 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
304 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000305 Textf(`echo " <uses-sdk android:minSdkVersion='%d' android:targetSdkVersion='%d'/>" &&`,
306 l.minSdkVersion, l.targetSdkVersion).
Colin Cross014489c2020-06-02 20:09:13 -0700307 Text(`echo "</manifest>"`).
308 Text(") >").Output(manifestPath)
309
310 return manifestPath
311}
312
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700313func (l *linter) getBaselineFilepath(ctx android.ModuleContext) android.OptionalPath {
314 var lintBaseline android.OptionalPath
315 if lintFilename := proptools.StringDefault(l.properties.Lint.Baseline_filename, "lint-baseline.xml"); lintFilename != "" {
316 if String(l.properties.Lint.Baseline_filename) != "" {
317 // if manually specified, we require the file to exist
318 lintBaseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, lintFilename))
319 } else {
320 lintBaseline = android.ExistentPathForSource(ctx, ctx.ModuleDir(), lintFilename)
321 }
322 }
323 return lintBaseline
324}
325
Colin Cross014489c2020-06-02 20:09:13 -0700326func (l *linter) lint(ctx android.ModuleContext) {
327 if !l.enabled() {
328 return
329 }
330
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000331 if l.minSdkVersion != l.compileSdkVersion {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700332 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100333 // Skip lint warning checks for NewApi warnings for libcore where they come from source
334 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100335 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100336 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
337
338 if len(filtered) != 0 {
339 ctx.PropertyErrorf("lint.warning_checks",
340 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
341 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700342 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100343
344 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700345 if len(filtered) != 0 {
346 ctx.PropertyErrorf("lint.disabled_checks",
347 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
348 }
Cole Faust3f646262022-06-29 14:58:03 -0700349
350 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
351 if ctx.ModuleName() == "PermissionController" {
352 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
353 return s != "NewApi"
354 })
355 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
356 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000357 }
358
Colin Cross92e4b462020-06-18 15:56:48 -0700359 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
360 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Crossdcf71b22021-02-01 13:59:03 -0800361 if ctx.OtherModuleHasProvider(extraLintCheckModule, JavaInfoProvider) {
362 dep := ctx.OtherModuleProvider(extraLintCheckModule, JavaInfoProvider).(JavaInfo)
363 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700364 } else {
365 ctx.PropertyErrorf("lint.extra_check_modules",
366 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
367 }
368 }
369
mattgilbride5aecabe2022-11-29 20:16:36 +0000370 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
371 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
372
Colin Cross1661aff2021-03-12 17:56:51 -0800373 rule := android.NewRuleBuilder(pctx, ctx).
374 Sbox(android.PathForModuleOut(ctx, "lint"),
375 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
376 SandboxInputs()
377
378 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
379 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
380 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
381 rule.Rewrapper(&remoteexec.REParams{
382 Labels: map[string]string{"type": "tool", "name": "lint"},
383 ExecStrategy: lintRBEExecStrategy(ctx),
384 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700385 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800386 })
387 }
Colin Cross014489c2020-06-02 20:09:13 -0700388
389 if l.manifest == nil {
390 manifest := l.generateManifest(ctx, rule)
391 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800392 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700393 }
394
Colin Cross62695b92022-08-12 16:09:24 -0700395 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
396 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
397 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList)
398
399 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700400
Colin Cross1661aff2021-03-12 17:56:51 -0800401 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
402 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
403 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Colin Cross6b76c152021-09-09 09:36:25 -0700404 baseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700405
Colin Cross08dca382020-07-21 20:31:17 -0700406 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700407
408 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000409 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700410 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700411 }
412 })
Colin Cross014489c2020-06-02 20:09:13 -0700413
Colin Cross31972dc2021-03-04 10:44:12 -0800414 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
415 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800416 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700417
Pedro Loureiro18233a22021-06-08 18:11:21 +0000418 var apiVersionsName, apiVersionsPrebuilt string
Pedro Loureiroffb643f2021-07-05 13:53:36 +0000419 if l.compileSdkKind == android.SdkModule || l.compileSdkKind == android.SdkSystemServer {
420 // When compiling an SDK module (or system server) we use the filtered
421 // database because otherwise lint's
Pedro Loureiro18233a22021-06-08 18:11:21 +0000422 // NewApi check produces too many false positives; This database excludes information
423 // about classes created in mainline modules hence removing those false positives.
424 apiVersionsName = "api_versions_public_filtered.xml"
425 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions-filtered.xml"
426 } else {
427 apiVersionsName = "api_versions.xml"
428 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions.xml"
429 }
430
Colin Cross8a6ed372020-07-06 11:45:51 -0700431 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900432 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross8a6ed372020-07-06 11:45:51 -0700433 annotationsZipPath = android.PathForSource(ctx, "prebuilts/sdk/current/public/data/annotations.zip")
Pedro Loureiro18233a22021-06-08 18:11:21 +0000434 apiVersionsXMLPath = android.PathForSource(ctx, apiVersionsPrebuilt)
Colin Cross8a6ed372020-07-06 11:45:51 -0700435 } else {
436 annotationsZipPath = copiedAnnotationsZipPath(ctx)
Pedro Loureiro18233a22021-06-08 18:11:21 +0000437 apiVersionsXMLPath = copiedAPIVersionsXmlPath(ctx, apiVersionsName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700438 }
439
Colin Cross31972dc2021-03-04 10:44:12 -0800440 cmd := rule.Command()
441
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000442 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800443 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700444 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800445 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
446
Colin Cross1661aff2021-03-12 17:56:51 -0800447 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700448 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800449 FlagWithInput("--project ", lintPaths.projectXML).
450 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700451 FlagWithOutput("--html ", html).
452 FlagWithOutput("--text ", text).
453 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000454 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700455 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
456 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
457 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
458 Flag("--exitcode").
Colin Cross62695b92022-08-12 16:09:24 -0700459 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700460 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800461 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700462 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700463
Colin Cross1661aff2021-03-12 17:56:51 -0800464 rule.Temporary(lintPaths.projectXML)
465 rule.Temporary(lintPaths.configXML)
466
Colin Cross988dfcc2020-07-16 17:32:17 -0700467 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
468 cmd.FlagWithArg("--check ", checkOnly)
469 }
470
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700471 lintBaseline := l.getBaselineFilepath(ctx)
472 if lintBaseline.Valid() {
473 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000474 }
475
Colin Cross6b76c152021-09-09 09:36:25 -0700476 cmd.FlagWithOutput("--write-reference-baseline ", baseline)
477
Colin Cross1b9e6832022-10-11 11:22:24 -0700478 cmd.Text("; EXITCODE=$?; ")
479
480 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
481 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
482 // a fatal error.
483 cmd.BuiltTool("soong_zip").
484 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
485 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
486 FlagWithInput("-r ", srcsList)
487
488 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 -0700489
Colin Cross31972dc2021-03-04 10:44:12 -0800490 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700491
Colin Crossee4a8b72021-04-05 18:38:05 -0700492 // The HTML output contains a date, remove it to make the output deterministic.
493 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
494
Colin Crossf1a035e2020-11-16 17:32:30 -0800495 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700496
Colin Crossc0efd1d2020-07-03 11:56:24 -0700497 l.outputs = lintOutputs{
498 html: html,
499 text: text,
500 xml: xml,
Colin Cross014489c2020-06-02 20:09:13 -0700501
Colin Cross08dca382020-07-21 20:31:17 -0700502 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700503 }
Colin Cross014489c2020-06-02 20:09:13 -0700504
Colin Crossc0efd1d2020-07-03 11:56:24 -0700505 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700506 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700507 }
508}
Colin Cross014489c2020-06-02 20:09:13 -0700509
Colin Cross08dca382020-07-21 20:31:17 -0700510func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
511 htmlList := depSets.HTML.ToSortedList()
512 textList := depSets.Text.ToSortedList()
513 xmlList := depSets.XML.ToSortedList()
514
515 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
516 return nil
517 }
518
519 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
520 lintZip(ctx, htmlList, htmlZip)
521
522 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
523 lintZip(ctx, textList, textZip)
524
525 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
526 lintZip(ctx, xmlList, xmlZip)
527
528 return android.Paths{htmlZip, textZip, xmlZip}
529}
530
Colin Cross014489c2020-06-02 20:09:13 -0700531type lintSingleton struct {
532 htmlZip android.WritablePath
533 textZip android.WritablePath
534 xmlZip android.WritablePath
535}
536
537func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
538 l.generateLintReportZips(ctx)
539 l.copyLintDependencies(ctx)
540}
541
Pedro Loureiro18233a22021-06-08 18:11:21 +0000542func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
543 var res android.Module
544 ctx.VisitAllModules(func(m android.Module) {
545 if ctx.ModuleName(m) == moduleName {
546 if res == nil {
547 res = m
548 } else {
549 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
550 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
551 }
552 }
553 })
554 return res
555}
556
Colin Cross014489c2020-06-02 20:09:13 -0700557func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900558 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700559 return
560 }
561
Anton Hansson67cf60e2022-05-09 09:36:22 +0000562 apiVersionsDb := findModuleOrErr(ctx, "api_versions_public")
563 if apiVersionsDb == nil {
Colin Cross014489c2020-06-02 20:09:13 -0700564 if !ctx.Config().AllowMissingDependencies() {
Anton Hansson67cf60e2022-05-09 09:36:22 +0000565 ctx.Errorf("lint: missing module api_versions_public")
Colin Cross014489c2020-06-02 20:09:13 -0700566 }
567 return
568 }
569
Anton Hanssonea17a452022-05-09 09:42:17 +0000570 sdkAnnotations := findModuleOrErr(ctx, "sdk-annotations.zip")
571 if sdkAnnotations == nil {
572 if !ctx.Config().AllowMissingDependencies() {
573 ctx.Errorf("lint: missing module sdk-annotations.zip")
574 }
575 return
576 }
577
Pedro Loureiro18233a22021-06-08 18:11:21 +0000578 filteredDb := findModuleOrErr(ctx, "api-versions-xml-public-filtered")
579 if filteredDb == nil {
580 if !ctx.Config().AllowMissingDependencies() {
581 ctx.Errorf("lint: missing api-versions-xml-public-filtered")
582 }
583 return
584 }
585
Colin Cross014489c2020-06-02 20:09:13 -0700586 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800587 Rule: android.CpIfChanged,
Anton Hanssonea17a452022-05-09 09:42:17 +0000588 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
Colin Cross8a6ed372020-07-06 11:45:51 -0700589 Output: copiedAnnotationsZipPath(ctx),
Colin Cross014489c2020-06-02 20:09:13 -0700590 })
591
592 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800593 Rule: android.CpIfChanged,
Anton Hansson67cf60e2022-05-09 09:36:22 +0000594 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
Pedro Loureiro18233a22021-06-08 18:11:21 +0000595 Output: copiedAPIVersionsXmlPath(ctx, "api_versions.xml"),
596 })
597
598 ctx.Build(pctx, android.BuildParams{
599 Rule: android.CpIfChanged,
600 Input: android.OutputFileForModule(ctx, filteredDb, ""),
601 Output: copiedAPIVersionsXmlPath(ctx, "api_versions_public_filtered.xml"),
Colin Cross014489c2020-06-02 20:09:13 -0700602 })
603}
604
Colin Cross8a6ed372020-07-06 11:45:51 -0700605func copiedAnnotationsZipPath(ctx android.PathContext) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700606 return android.PathForOutput(ctx, "lint", "annotations.zip")
607}
608
Pedro Loureiro18233a22021-06-08 18:11:21 +0000609func copiedAPIVersionsXmlPath(ctx android.PathContext, name string) android.WritablePath {
610 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700611}
612
613func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700614 if ctx.Config().UnbundledBuild() {
615 return
616 }
617
Colin Cross014489c2020-06-02 20:09:13 -0700618 var outputs []*lintOutputs
619 var dirs []string
620 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500621 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700622 return
623 }
624
Colin Cross56a83212020-09-15 18:30:11 -0700625 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
626 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
627 if apexInfo.IsForPlatform() {
628 // There are stray platform variants of modules in apexes that are not available for
629 // the platform, and they sometimes can't be built. Don't depend on them.
630 return
631 }
Colin Cross014489c2020-06-02 20:09:13 -0700632 }
633
Colin Cross08dca382020-07-21 20:31:17 -0700634 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700635 outputs = append(outputs, l.lintOutputs())
636 }
637 })
638
639 dirs = android.SortedUniqueStrings(dirs)
640
641 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
642 var paths android.Paths
643
644 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700645 if p := get(output); p != nil {
646 paths = append(paths, p)
647 }
Colin Cross014489c2020-06-02 20:09:13 -0700648 }
649
Colin Crossc0efd1d2020-07-03 11:56:24 -0700650 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700651 }
652
653 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
654 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
655
656 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
657 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
658
659 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
660 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
661
662 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip)
663}
664
665func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700666 if !ctx.Config().UnbundledBuild() {
667 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip)
668 }
Colin Cross014489c2020-06-02 20:09:13 -0700669}
670
671var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
672
673func init() {
674 android.RegisterSingletonType("lint",
675 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700676
677 registerLintBuildComponents(android.InitRegistrationContext)
678}
679
680func registerLintBuildComponents(ctx android.RegistrationContext) {
681 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
682 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
683 })
Colin Cross014489c2020-06-02 20:09:13 -0700684}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700685
686func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
687 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
688
689 sort.Slice(paths, func(i, j int) bool {
690 return paths[i].String() < paths[j].String()
691 })
692
Colin Crossf1a035e2020-11-16 17:32:30 -0800693 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700694
Colin Crossf1a035e2020-11-16 17:32:30 -0800695 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700696 FlagWithOutput("-o ", outputPath).
697 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800698 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700699
Colin Crossf1a035e2020-11-16 17:32:30 -0800700 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700701}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700702
703// Enforce the strict updatability linting to all applicable transitive dependencies.
704func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
705 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000706 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700707 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000708 if a, ok := d.(LintDepSetsIntf); ok {
709 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700710 }
711 })
712 }
713}