blob: 07b962912415a84d013c212a2732b1dd35892c44 [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
Spandan Das17854f52022-01-14 21:19:14 +0000278 if l.GetStrictUpdatabilityLinting() {
Jaewoong Jung3c87b1d2021-04-22 11:01:36 -0700279 // Verify the module does not baseline issues that endanger safe updatability.
Jaewoong Jung48de8832021-04-21 16:17:25 -0700280 if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
281 cmd.FlagWithInput("--baseline ", baselinePath.Path())
282 cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
283 }
284 }
285
Colin Cross31972dc2021-03-04 10:44:12 -0800286 return lintPaths{
287 projectXML: projectXMLPath,
288 configXML: configXMLPath,
289 cacheDir: cacheDir,
290 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800291 }
292
Colin Cross014489c2020-06-02 20:09:13 -0700293}
294
Liz Kammer20ebfb42020-07-28 11:32:07 -0700295// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700296// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800297func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700298 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
299
300 rule.Command().Text("(").
301 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
302 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
303 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000304 Textf(`echo " <uses-sdk android:minSdkVersion='%d' android:targetSdkVersion='%d'/>" &&`,
305 l.minSdkVersion, l.targetSdkVersion).
Colin Cross014489c2020-06-02 20:09:13 -0700306 Text(`echo "</manifest>"`).
307 Text(") >").Output(manifestPath)
308
309 return manifestPath
310}
311
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700312func (l *linter) getBaselineFilepath(ctx android.ModuleContext) android.OptionalPath {
313 var lintBaseline android.OptionalPath
314 if lintFilename := proptools.StringDefault(l.properties.Lint.Baseline_filename, "lint-baseline.xml"); lintFilename != "" {
315 if String(l.properties.Lint.Baseline_filename) != "" {
316 // if manually specified, we require the file to exist
317 lintBaseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, lintFilename))
318 } else {
319 lintBaseline = android.ExistentPathForSource(ctx, ctx.ModuleDir(), lintFilename)
320 }
321 }
322 return lintBaseline
323}
324
Colin Cross014489c2020-06-02 20:09:13 -0700325func (l *linter) lint(ctx android.ModuleContext) {
326 if !l.enabled() {
327 return
328 }
329
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000330 if l.minSdkVersion != l.compileSdkVersion {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700331 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100332 // Skip lint warning checks for NewApi warnings for libcore where they come from source
333 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100334 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100335 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
336
337 if len(filtered) != 0 {
338 ctx.PropertyErrorf("lint.warning_checks",
339 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
340 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700341 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100342
343 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700344 if len(filtered) != 0 {
345 ctx.PropertyErrorf("lint.disabled_checks",
346 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
347 }
Cole Faust3f646262022-06-29 14:58:03 -0700348
349 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
350 if ctx.ModuleName() == "PermissionController" {
351 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
352 return s != "NewApi"
353 })
354 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
355 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000356 }
357
Colin Cross92e4b462020-06-18 15:56:48 -0700358 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
359 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Crossdcf71b22021-02-01 13:59:03 -0800360 if ctx.OtherModuleHasProvider(extraLintCheckModule, JavaInfoProvider) {
361 dep := ctx.OtherModuleProvider(extraLintCheckModule, JavaInfoProvider).(JavaInfo)
362 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700363 } else {
364 ctx.PropertyErrorf("lint.extra_check_modules",
365 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
366 }
367 }
368
mattgilbride5aecabe2022-11-29 20:16:36 +0000369 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
370 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
371
Colin Cross1661aff2021-03-12 17:56:51 -0800372 rule := android.NewRuleBuilder(pctx, ctx).
373 Sbox(android.PathForModuleOut(ctx, "lint"),
374 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
375 SandboxInputs()
376
377 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
378 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
379 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
380 rule.Rewrapper(&remoteexec.REParams{
381 Labels: map[string]string{"type": "tool", "name": "lint"},
382 ExecStrategy: lintRBEExecStrategy(ctx),
383 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700384 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800385 })
386 }
Colin Cross014489c2020-06-02 20:09:13 -0700387
388 if l.manifest == nil {
389 manifest := l.generateManifest(ctx, rule)
390 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800391 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700392 }
393
Colin Cross62695b92022-08-12 16:09:24 -0700394 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
395 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
396 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList)
397
398 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700399
Colin Cross1661aff2021-03-12 17:56:51 -0800400 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
401 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
402 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Colin Cross6b76c152021-09-09 09:36:25 -0700403 baseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700404
Colin Cross08dca382020-07-21 20:31:17 -0700405 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700406
407 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000408 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700409 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700410 }
411 })
Colin Cross014489c2020-06-02 20:09:13 -0700412
Colin Cross31972dc2021-03-04 10:44:12 -0800413 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
414 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800415 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700416
Pedro Loureiro18233a22021-06-08 18:11:21 +0000417 var apiVersionsName, apiVersionsPrebuilt string
Pedro Loureiroffb643f2021-07-05 13:53:36 +0000418 if l.compileSdkKind == android.SdkModule || l.compileSdkKind == android.SdkSystemServer {
419 // When compiling an SDK module (or system server) we use the filtered
420 // database because otherwise lint's
Pedro Loureiro18233a22021-06-08 18:11:21 +0000421 // NewApi check produces too many false positives; This database excludes information
422 // about classes created in mainline modules hence removing those false positives.
423 apiVersionsName = "api_versions_public_filtered.xml"
424 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions-filtered.xml"
425 } else {
426 apiVersionsName = "api_versions.xml"
427 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions.xml"
428 }
429
Colin Cross8a6ed372020-07-06 11:45:51 -0700430 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900431 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross8a6ed372020-07-06 11:45:51 -0700432 annotationsZipPath = android.PathForSource(ctx, "prebuilts/sdk/current/public/data/annotations.zip")
Pedro Loureiro18233a22021-06-08 18:11:21 +0000433 apiVersionsXMLPath = android.PathForSource(ctx, apiVersionsPrebuilt)
Colin Cross8a6ed372020-07-06 11:45:51 -0700434 } else {
435 annotationsZipPath = copiedAnnotationsZipPath(ctx)
Pedro Loureiro18233a22021-06-08 18:11:21 +0000436 apiVersionsXMLPath = copiedAPIVersionsXmlPath(ctx, apiVersionsName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700437 }
438
Colin Cross31972dc2021-03-04 10:44:12 -0800439 cmd := rule.Command()
440
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000441 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800442 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700443 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800444 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
445
Colin Cross1661aff2021-03-12 17:56:51 -0800446 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700447 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800448 FlagWithInput("--project ", lintPaths.projectXML).
449 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700450 FlagWithOutput("--html ", html).
451 FlagWithOutput("--text ", text).
452 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000453 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700454 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
455 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
456 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
457 Flag("--exitcode").
Colin Cross62695b92022-08-12 16:09:24 -0700458 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700459 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800460 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700461 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700462
Colin Cross1661aff2021-03-12 17:56:51 -0800463 rule.Temporary(lintPaths.projectXML)
464 rule.Temporary(lintPaths.configXML)
465
Colin Cross988dfcc2020-07-16 17:32:17 -0700466 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
467 cmd.FlagWithArg("--check ", checkOnly)
468 }
469
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700470 lintBaseline := l.getBaselineFilepath(ctx)
471 if lintBaseline.Valid() {
472 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000473 }
474
Colin Cross6b76c152021-09-09 09:36:25 -0700475 cmd.FlagWithOutput("--write-reference-baseline ", baseline)
476
Colin Cross1b9e6832022-10-11 11:22:24 -0700477 cmd.Text("; EXITCODE=$?; ")
478
479 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
480 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
481 // a fatal error.
482 cmd.BuiltTool("soong_zip").
483 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
484 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
485 FlagWithInput("-r ", srcsList)
486
487 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 -0700488
Colin Cross31972dc2021-03-04 10:44:12 -0800489 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700490
Colin Crossee4a8b72021-04-05 18:38:05 -0700491 // The HTML output contains a date, remove it to make the output deterministic.
492 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
493
Colin Crossf1a035e2020-11-16 17:32:30 -0800494 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700495
Colin Crossc0efd1d2020-07-03 11:56:24 -0700496 l.outputs = lintOutputs{
497 html: html,
498 text: text,
499 xml: xml,
Colin Cross014489c2020-06-02 20:09:13 -0700500
Colin Cross08dca382020-07-21 20:31:17 -0700501 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700502 }
Colin Cross014489c2020-06-02 20:09:13 -0700503
Colin Crossc0efd1d2020-07-03 11:56:24 -0700504 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700505 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700506 }
507}
Colin Cross014489c2020-06-02 20:09:13 -0700508
Colin Cross08dca382020-07-21 20:31:17 -0700509func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
510 htmlList := depSets.HTML.ToSortedList()
511 textList := depSets.Text.ToSortedList()
512 xmlList := depSets.XML.ToSortedList()
513
514 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
515 return nil
516 }
517
518 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
519 lintZip(ctx, htmlList, htmlZip)
520
521 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
522 lintZip(ctx, textList, textZip)
523
524 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
525 lintZip(ctx, xmlList, xmlZip)
526
527 return android.Paths{htmlZip, textZip, xmlZip}
528}
529
Colin Cross014489c2020-06-02 20:09:13 -0700530type lintSingleton struct {
531 htmlZip android.WritablePath
532 textZip android.WritablePath
533 xmlZip android.WritablePath
534}
535
536func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
537 l.generateLintReportZips(ctx)
538 l.copyLintDependencies(ctx)
539}
540
Pedro Loureiro18233a22021-06-08 18:11:21 +0000541func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
542 var res android.Module
543 ctx.VisitAllModules(func(m android.Module) {
544 if ctx.ModuleName(m) == moduleName {
545 if res == nil {
546 res = m
547 } else {
548 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
549 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
550 }
551 }
552 })
553 return res
554}
555
Colin Cross014489c2020-06-02 20:09:13 -0700556func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900557 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700558 return
559 }
560
Anton Hansson67cf60e2022-05-09 09:36:22 +0000561 apiVersionsDb := findModuleOrErr(ctx, "api_versions_public")
562 if apiVersionsDb == nil {
Colin Cross014489c2020-06-02 20:09:13 -0700563 if !ctx.Config().AllowMissingDependencies() {
Anton Hansson67cf60e2022-05-09 09:36:22 +0000564 ctx.Errorf("lint: missing module api_versions_public")
Colin Cross014489c2020-06-02 20:09:13 -0700565 }
566 return
567 }
568
Anton Hanssonea17a452022-05-09 09:42:17 +0000569 sdkAnnotations := findModuleOrErr(ctx, "sdk-annotations.zip")
570 if sdkAnnotations == nil {
571 if !ctx.Config().AllowMissingDependencies() {
572 ctx.Errorf("lint: missing module sdk-annotations.zip")
573 }
574 return
575 }
576
Pedro Loureiro18233a22021-06-08 18:11:21 +0000577 filteredDb := findModuleOrErr(ctx, "api-versions-xml-public-filtered")
578 if filteredDb == nil {
579 if !ctx.Config().AllowMissingDependencies() {
580 ctx.Errorf("lint: missing api-versions-xml-public-filtered")
581 }
582 return
583 }
584
Colin Cross014489c2020-06-02 20:09:13 -0700585 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800586 Rule: android.CpIfChanged,
Anton Hanssonea17a452022-05-09 09:42:17 +0000587 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
Colin Cross8a6ed372020-07-06 11:45:51 -0700588 Output: copiedAnnotationsZipPath(ctx),
Colin Cross014489c2020-06-02 20:09:13 -0700589 })
590
591 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800592 Rule: android.CpIfChanged,
Anton Hansson67cf60e2022-05-09 09:36:22 +0000593 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
Pedro Loureiro18233a22021-06-08 18:11:21 +0000594 Output: copiedAPIVersionsXmlPath(ctx, "api_versions.xml"),
595 })
596
597 ctx.Build(pctx, android.BuildParams{
598 Rule: android.CpIfChanged,
599 Input: android.OutputFileForModule(ctx, filteredDb, ""),
600 Output: copiedAPIVersionsXmlPath(ctx, "api_versions_public_filtered.xml"),
Colin Cross014489c2020-06-02 20:09:13 -0700601 })
602}
603
Colin Cross8a6ed372020-07-06 11:45:51 -0700604func copiedAnnotationsZipPath(ctx android.PathContext) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700605 return android.PathForOutput(ctx, "lint", "annotations.zip")
606}
607
Pedro Loureiro18233a22021-06-08 18:11:21 +0000608func copiedAPIVersionsXmlPath(ctx android.PathContext, name string) android.WritablePath {
609 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700610}
611
612func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700613 if ctx.Config().UnbundledBuild() {
614 return
615 }
616
Colin Cross014489c2020-06-02 20:09:13 -0700617 var outputs []*lintOutputs
618 var dirs []string
619 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500620 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700621 return
622 }
623
Colin Cross56a83212020-09-15 18:30:11 -0700624 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
625 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
626 if apexInfo.IsForPlatform() {
627 // There are stray platform variants of modules in apexes that are not available for
628 // the platform, and they sometimes can't be built. Don't depend on them.
629 return
630 }
Colin Cross014489c2020-06-02 20:09:13 -0700631 }
632
Colin Cross08dca382020-07-21 20:31:17 -0700633 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700634 outputs = append(outputs, l.lintOutputs())
635 }
636 })
637
638 dirs = android.SortedUniqueStrings(dirs)
639
640 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
641 var paths android.Paths
642
643 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700644 if p := get(output); p != nil {
645 paths = append(paths, p)
646 }
Colin Cross014489c2020-06-02 20:09:13 -0700647 }
648
Colin Crossc0efd1d2020-07-03 11:56:24 -0700649 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700650 }
651
652 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
653 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
654
655 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
656 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
657
658 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
659 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
660
661 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip)
662}
663
664func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700665 if !ctx.Config().UnbundledBuild() {
666 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip)
667 }
Colin Cross014489c2020-06-02 20:09:13 -0700668}
669
670var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
671
672func init() {
673 android.RegisterSingletonType("lint",
674 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700675
676 registerLintBuildComponents(android.InitRegistrationContext)
677}
678
679func registerLintBuildComponents(ctx android.RegistrationContext) {
680 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
681 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
682 })
Colin Cross014489c2020-06-02 20:09:13 -0700683}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700684
685func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
686 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
687
688 sort.Slice(paths, func(i, j int) bool {
689 return paths[i].String() < paths[j].String()
690 })
691
Colin Crossf1a035e2020-11-16 17:32:30 -0800692 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700693
Colin Crossf1a035e2020-11-16 17:32:30 -0800694 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700695 FlagWithOutput("-o ", outputPath).
696 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800697 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700698
Colin Crossf1a035e2020-11-16 17:32:30 -0800699 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700700}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700701
702// Enforce the strict updatability linting to all applicable transitive dependencies.
703func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
704 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000705 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700706 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000707 if a, ok := d.(LintDepSetsIntf); ok {
708 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700709 }
710 })
711 }
712}