blob: 7a6e5d9c139f582f70a742f5a10ef205cc7b8a2f [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
Colin Cross1661aff2021-03-12 17:56:51 -0800369 rule := android.NewRuleBuilder(pctx, ctx).
370 Sbox(android.PathForModuleOut(ctx, "lint"),
371 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
372 SandboxInputs()
373
374 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
375 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
376 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
377 rule.Rewrapper(&remoteexec.REParams{
378 Labels: map[string]string{"type": "tool", "name": "lint"},
379 ExecStrategy: lintRBEExecStrategy(ctx),
380 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700381 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800382 })
383 }
Colin Cross014489c2020-06-02 20:09:13 -0700384
385 if l.manifest == nil {
386 manifest := l.generateManifest(ctx, rule)
387 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800388 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700389 }
390
Colin Cross62695b92022-08-12 16:09:24 -0700391 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
392 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
393 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList)
394
395 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700396
Colin Cross1661aff2021-03-12 17:56:51 -0800397 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
398 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
399 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Colin Cross6b76c152021-09-09 09:36:25 -0700400 baseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700401
Colin Cross08dca382020-07-21 20:31:17 -0700402 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700403
404 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000405 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700406 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700407 }
408 })
Colin Cross014489c2020-06-02 20:09:13 -0700409
Colin Cross31972dc2021-03-04 10:44:12 -0800410 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
411 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800412 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700413
Pedro Loureiro18233a22021-06-08 18:11:21 +0000414 var apiVersionsName, apiVersionsPrebuilt string
Pedro Loureiroffb643f2021-07-05 13:53:36 +0000415 if l.compileSdkKind == android.SdkModule || l.compileSdkKind == android.SdkSystemServer {
416 // When compiling an SDK module (or system server) we use the filtered
417 // database because otherwise lint's
Pedro Loureiro18233a22021-06-08 18:11:21 +0000418 // NewApi check produces too many false positives; This database excludes information
419 // about classes created in mainline modules hence removing those false positives.
420 apiVersionsName = "api_versions_public_filtered.xml"
421 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions-filtered.xml"
422 } else {
423 apiVersionsName = "api_versions.xml"
424 apiVersionsPrebuilt = "prebuilts/sdk/current/public/data/api-versions.xml"
425 }
426
Colin Cross8a6ed372020-07-06 11:45:51 -0700427 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900428 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross8a6ed372020-07-06 11:45:51 -0700429 annotationsZipPath = android.PathForSource(ctx, "prebuilts/sdk/current/public/data/annotations.zip")
Pedro Loureiro18233a22021-06-08 18:11:21 +0000430 apiVersionsXMLPath = android.PathForSource(ctx, apiVersionsPrebuilt)
Colin Cross8a6ed372020-07-06 11:45:51 -0700431 } else {
432 annotationsZipPath = copiedAnnotationsZipPath(ctx)
Pedro Loureiro18233a22021-06-08 18:11:21 +0000433 apiVersionsXMLPath = copiedAPIVersionsXmlPath(ctx, apiVersionsName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700434 }
435
Colin Cross31972dc2021-03-04 10:44:12 -0800436 cmd := rule.Command()
437
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000438 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800439 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700440 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800441 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
442
Colin Cross1661aff2021-03-12 17:56:51 -0800443 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700444 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800445 FlagWithInput("--project ", lintPaths.projectXML).
446 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700447 FlagWithOutput("--html ", html).
448 FlagWithOutput("--text ", text).
449 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000450 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700451 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
452 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
453 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
454 Flag("--exitcode").
Colin Cross62695b92022-08-12 16:09:24 -0700455 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700456 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800457 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700458 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700459
Colin Cross1661aff2021-03-12 17:56:51 -0800460 rule.Temporary(lintPaths.projectXML)
461 rule.Temporary(lintPaths.configXML)
462
Colin Cross988dfcc2020-07-16 17:32:17 -0700463 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
464 cmd.FlagWithArg("--check ", checkOnly)
465 }
466
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700467 lintBaseline := l.getBaselineFilepath(ctx)
468 if lintBaseline.Valid() {
469 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000470 }
471
Colin Cross6b76c152021-09-09 09:36:25 -0700472 cmd.FlagWithOutput("--write-reference-baseline ", baseline)
473
Colin Cross1b9e6832022-10-11 11:22:24 -0700474 cmd.Text("; EXITCODE=$?; ")
475
476 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
477 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
478 // a fatal error.
479 cmd.BuiltTool("soong_zip").
480 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
481 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
482 FlagWithInput("-r ", srcsList)
483
484 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 -0700485
Colin Cross31972dc2021-03-04 10:44:12 -0800486 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700487
Colin Crossee4a8b72021-04-05 18:38:05 -0700488 // The HTML output contains a date, remove it to make the output deterministic.
489 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
490
Colin Crossf1a035e2020-11-16 17:32:30 -0800491 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700492
Colin Crossc0efd1d2020-07-03 11:56:24 -0700493 l.outputs = lintOutputs{
494 html: html,
495 text: text,
496 xml: xml,
Colin Cross014489c2020-06-02 20:09:13 -0700497
Colin Cross08dca382020-07-21 20:31:17 -0700498 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700499 }
Colin Cross014489c2020-06-02 20:09:13 -0700500
Colin Crossc0efd1d2020-07-03 11:56:24 -0700501 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700502 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700503 }
504}
Colin Cross014489c2020-06-02 20:09:13 -0700505
Colin Cross08dca382020-07-21 20:31:17 -0700506func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
507 htmlList := depSets.HTML.ToSortedList()
508 textList := depSets.Text.ToSortedList()
509 xmlList := depSets.XML.ToSortedList()
510
511 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
512 return nil
513 }
514
515 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
516 lintZip(ctx, htmlList, htmlZip)
517
518 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
519 lintZip(ctx, textList, textZip)
520
521 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
522 lintZip(ctx, xmlList, xmlZip)
523
524 return android.Paths{htmlZip, textZip, xmlZip}
525}
526
Colin Cross014489c2020-06-02 20:09:13 -0700527type lintSingleton struct {
528 htmlZip android.WritablePath
529 textZip android.WritablePath
530 xmlZip android.WritablePath
531}
532
533func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
534 l.generateLintReportZips(ctx)
535 l.copyLintDependencies(ctx)
536}
537
Pedro Loureiro18233a22021-06-08 18:11:21 +0000538func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
539 var res android.Module
540 ctx.VisitAllModules(func(m android.Module) {
541 if ctx.ModuleName(m) == moduleName {
542 if res == nil {
543 res = m
544 } else {
545 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
546 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
547 }
548 }
549 })
550 return res
551}
552
Colin Cross014489c2020-06-02 20:09:13 -0700553func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900554 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700555 return
556 }
557
Anton Hansson67cf60e2022-05-09 09:36:22 +0000558 apiVersionsDb := findModuleOrErr(ctx, "api_versions_public")
559 if apiVersionsDb == nil {
Colin Cross014489c2020-06-02 20:09:13 -0700560 if !ctx.Config().AllowMissingDependencies() {
Anton Hansson67cf60e2022-05-09 09:36:22 +0000561 ctx.Errorf("lint: missing module api_versions_public")
Colin Cross014489c2020-06-02 20:09:13 -0700562 }
563 return
564 }
565
Anton Hanssonea17a452022-05-09 09:42:17 +0000566 sdkAnnotations := findModuleOrErr(ctx, "sdk-annotations.zip")
567 if sdkAnnotations == nil {
568 if !ctx.Config().AllowMissingDependencies() {
569 ctx.Errorf("lint: missing module sdk-annotations.zip")
570 }
571 return
572 }
573
Pedro Loureiro18233a22021-06-08 18:11:21 +0000574 filteredDb := findModuleOrErr(ctx, "api-versions-xml-public-filtered")
575 if filteredDb == nil {
576 if !ctx.Config().AllowMissingDependencies() {
577 ctx.Errorf("lint: missing api-versions-xml-public-filtered")
578 }
579 return
580 }
581
Colin Cross014489c2020-06-02 20:09:13 -0700582 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800583 Rule: android.CpIfChanged,
Anton Hanssonea17a452022-05-09 09:42:17 +0000584 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
Colin Cross8a6ed372020-07-06 11:45:51 -0700585 Output: copiedAnnotationsZipPath(ctx),
Colin Cross014489c2020-06-02 20:09:13 -0700586 })
587
588 ctx.Build(pctx, android.BuildParams{
Colin Cross00d93b12021-03-04 10:00:09 -0800589 Rule: android.CpIfChanged,
Anton Hansson67cf60e2022-05-09 09:36:22 +0000590 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
Pedro Loureiro18233a22021-06-08 18:11:21 +0000591 Output: copiedAPIVersionsXmlPath(ctx, "api_versions.xml"),
592 })
593
594 ctx.Build(pctx, android.BuildParams{
595 Rule: android.CpIfChanged,
596 Input: android.OutputFileForModule(ctx, filteredDb, ""),
597 Output: copiedAPIVersionsXmlPath(ctx, "api_versions_public_filtered.xml"),
Colin Cross014489c2020-06-02 20:09:13 -0700598 })
599}
600
Colin Cross8a6ed372020-07-06 11:45:51 -0700601func copiedAnnotationsZipPath(ctx android.PathContext) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700602 return android.PathForOutput(ctx, "lint", "annotations.zip")
603}
604
Pedro Loureiro18233a22021-06-08 18:11:21 +0000605func copiedAPIVersionsXmlPath(ctx android.PathContext, name string) android.WritablePath {
606 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700607}
608
609func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700610 if ctx.Config().UnbundledBuild() {
611 return
612 }
613
Colin Cross014489c2020-06-02 20:09:13 -0700614 var outputs []*lintOutputs
615 var dirs []string
616 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500617 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700618 return
619 }
620
Colin Cross56a83212020-09-15 18:30:11 -0700621 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
622 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
623 if apexInfo.IsForPlatform() {
624 // There are stray platform variants of modules in apexes that are not available for
625 // the platform, and they sometimes can't be built. Don't depend on them.
626 return
627 }
Colin Cross014489c2020-06-02 20:09:13 -0700628 }
629
Colin Cross08dca382020-07-21 20:31:17 -0700630 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700631 outputs = append(outputs, l.lintOutputs())
632 }
633 })
634
635 dirs = android.SortedUniqueStrings(dirs)
636
637 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
638 var paths android.Paths
639
640 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700641 if p := get(output); p != nil {
642 paths = append(paths, p)
643 }
Colin Cross014489c2020-06-02 20:09:13 -0700644 }
645
Colin Crossc0efd1d2020-07-03 11:56:24 -0700646 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700647 }
648
649 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
650 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
651
652 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
653 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
654
655 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
656 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
657
658 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip)
659}
660
661func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700662 if !ctx.Config().UnbundledBuild() {
663 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip)
664 }
Colin Cross014489c2020-06-02 20:09:13 -0700665}
666
667var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
668
669func init() {
670 android.RegisterSingletonType("lint",
671 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700672
673 registerLintBuildComponents(android.InitRegistrationContext)
674}
675
676func registerLintBuildComponents(ctx android.RegistrationContext) {
677 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
678 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
679 })
Colin Cross014489c2020-06-02 20:09:13 -0700680}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700681
682func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
683 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
684
685 sort.Slice(paths, func(i, j int) bool {
686 return paths[i].String() < paths[j].String()
687 })
688
Colin Crossf1a035e2020-11-16 17:32:30 -0800689 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700690
Colin Crossf1a035e2020-11-16 17:32:30 -0800691 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700692 FlagWithOutput("-o ", outputPath).
693 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800694 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700695
Colin Crossf1a035e2020-11-16 17:32:30 -0800696 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700697}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700698
699// Enforce the strict updatability linting to all applicable transitive dependencies.
700func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
701 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000702 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700703 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000704 if a, ok := d.(LintDepSetsIntf); ok {
705 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700706 }
707 })
708 }
709}