blob: a0f99707a603fdd11f0b1774ed42cdcac5ec1bca [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 {
Cole Faustdf38f7a2023-03-02 16:43:15 -080099 html android.Path
100 text android.Path
101 xml android.Path
102 referenceBaseline android.Path
Colin Crossc0efd1d2020-07-03 11:56:24 -0700103
Colin Cross08dca382020-07-21 20:31:17 -0700104 depSets LintDepSets
Colin Crossc0efd1d2020-07-03 11:56:24 -0700105}
106
Colin Cross08dca382020-07-21 20:31:17 -0700107type lintOutputsIntf interface {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700108 lintOutputs() *lintOutputs
109}
110
Spandan Das17854f52022-01-14 21:19:14 +0000111type LintDepSetsIntf interface {
Colin Cross08dca382020-07-21 20:31:17 -0700112 LintDepSets() LintDepSets
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700113
114 // Methods used to propagate strict_updatability_linting values.
Spandan Das17854f52022-01-14 21:19:14 +0000115 GetStrictUpdatabilityLinting() bool
116 SetStrictUpdatabilityLinting(bool)
Colin Cross08dca382020-07-21 20:31:17 -0700117}
118
119type LintDepSets struct {
120 HTML, Text, XML *android.DepSet
121}
122
123type LintDepSetsBuilder struct {
124 HTML, Text, XML *android.DepSetBuilder
125}
126
127func NewLintDepSetBuilder() LintDepSetsBuilder {
128 return LintDepSetsBuilder{
129 HTML: android.NewDepSetBuilder(android.POSTORDER),
130 Text: android.NewDepSetBuilder(android.POSTORDER),
131 XML: android.NewDepSetBuilder(android.POSTORDER),
132 }
133}
134
135func (l LintDepSetsBuilder) Direct(html, text, xml android.Path) LintDepSetsBuilder {
136 l.HTML.Direct(html)
137 l.Text.Direct(text)
138 l.XML.Direct(xml)
139 return l
140}
141
142func (l LintDepSetsBuilder) Transitive(depSets LintDepSets) LintDepSetsBuilder {
143 if depSets.HTML != nil {
144 l.HTML.Transitive(depSets.HTML)
145 }
146 if depSets.Text != nil {
147 l.Text.Transitive(depSets.Text)
148 }
149 if depSets.XML != nil {
150 l.XML.Transitive(depSets.XML)
151 }
152 return l
153}
154
155func (l LintDepSetsBuilder) Build() LintDepSets {
156 return LintDepSets{
157 HTML: l.HTML.Build(),
158 Text: l.Text.Build(),
159 XML: l.XML.Build(),
160 }
161}
162
Cole Faust69861aa2023-01-31 15:49:07 -0800163type lintDatabaseFiles struct {
164 apiVersionsModule string
165 apiVersionsCopiedName string
166 apiVersionsPrebuiltPath string
167 annotationsModule string
168 annotationCopiedName string
169 annotationPrebuiltpath string
170}
171
172var allLintDatabasefiles = map[android.SdkKind]lintDatabaseFiles{
173 android.SdkPublic: {
174 apiVersionsModule: "api_versions_public",
175 apiVersionsCopiedName: "api_versions_public.xml",
176 apiVersionsPrebuiltPath: "prebuilts/sdk/current/public/data/api-versions.xml",
177 annotationsModule: "sdk-annotations.zip",
178 annotationCopiedName: "annotations-public.zip",
179 annotationPrebuiltpath: "prebuilts/sdk/current/public/data/annotations.zip",
180 },
181 android.SdkSystem: {
182 apiVersionsModule: "api_versions_system",
183 apiVersionsCopiedName: "api_versions_system.xml",
184 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system/data/api-versions.xml",
185 annotationsModule: "sdk-annotations-system.zip",
186 annotationCopiedName: "annotations-system.zip",
187 annotationPrebuiltpath: "prebuilts/sdk/current/system/data/annotations.zip",
188 },
189 android.SdkModule: {
190 apiVersionsModule: "api_versions_module_lib",
191 apiVersionsCopiedName: "api_versions_module_lib.xml",
192 apiVersionsPrebuiltPath: "prebuilts/sdk/current/module-lib/data/api-versions.xml",
193 annotationsModule: "sdk-annotations-module-lib.zip",
194 annotationCopiedName: "annotations-module-lib.zip",
195 annotationPrebuiltpath: "prebuilts/sdk/current/module-lib/data/annotations.zip",
196 },
197 android.SdkSystemServer: {
198 apiVersionsModule: "api_versions_system_server",
199 apiVersionsCopiedName: "api_versions_system_server.xml",
200 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system-server/data/api-versions.xml",
201 annotationsModule: "sdk-annotations-system-server.zip",
202 annotationCopiedName: "annotations-system-server.zip",
203 annotationPrebuiltpath: "prebuilts/sdk/current/system-server/data/annotations.zip",
204 },
205}
206
Colin Cross08dca382020-07-21 20:31:17 -0700207func (l *linter) LintDepSets() LintDepSets {
208 return l.outputs.depSets
209}
210
Spandan Das17854f52022-01-14 21:19:14 +0000211func (l *linter) GetStrictUpdatabilityLinting() bool {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700212 return BoolDefault(l.properties.Lint.Strict_updatability_linting, false)
213}
214
Spandan Das17854f52022-01-14 21:19:14 +0000215func (l *linter) SetStrictUpdatabilityLinting(strictLinting bool) {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700216 l.properties.Lint.Strict_updatability_linting = &strictLinting
217}
218
Spandan Das17854f52022-01-14 21:19:14 +0000219var _ LintDepSetsIntf = (*linter)(nil)
Colin Cross08dca382020-07-21 20:31:17 -0700220
221var _ lintOutputsIntf = (*linter)(nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700222
223func (l *linter) lintOutputs() *lintOutputs {
224 return &l.outputs
Colin Cross014489c2020-06-02 20:09:13 -0700225}
226
227func (l *linter) enabled() bool {
228 return BoolDefault(l.properties.Lint.Enabled, true)
229}
230
Colin Cross92e4b462020-06-18 15:56:48 -0700231func (l *linter) deps(ctx android.BottomUpMutatorContext) {
232 if !l.enabled() {
233 return
234 }
235
Colin Cross988dfcc2020-07-16 17:32:17 -0700236 extraCheckModules := l.properties.Lint.Extra_check_modules
237
mattgilbridee17645f2022-11-18 18:20:20 +0000238 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
239 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700240 }
241
242 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
243 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700244}
245
Colin Crossad22bc22021-03-10 09:45:40 -0800246// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
247// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800248type lintPaths struct {
249 projectXML android.WritablePath
250 configXML android.WritablePath
251 cacheDir android.WritablePath
252 homeDir android.WritablePath
253 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800254}
255
Colin Cross9b93af42021-03-10 10:40:58 -0800256func lintRBEExecStrategy(ctx android.ModuleContext) string {
257 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
258}
259
Colin Cross62695b92022-08-12 16:09:24 -0700260func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path) lintPaths {
Colin Cross31972dc2021-03-04 10:44:12 -0800261 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700262 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800263 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
264 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
265 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700266
Colin Cross1661aff2021-03-12 17:56:51 -0800267 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700268 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
269
270 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700271 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700272 FlagWithOutput("--project_out ", projectXMLPath).
273 FlagWithOutput("--config_out ", configXMLPath).
274 FlagWithArg("--name ", ctx.ModuleName())
275
276 if l.library {
277 cmd.Flag("--library")
278 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700279 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700280 cmd.Flag("--test")
281 }
282 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700283 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700284 }
285 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700286 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700287 }
288
Colin Cross5bedfa22021-03-23 17:07:14 -0700289 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
290 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700291 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700292
293 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700294
Colin Cross5bedfa22021-03-23 17:07:14 -0700295 if len(l.resources) > 0 {
296 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
297 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700298 }
299
300 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700301 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700302 }
303
Colin Cross5bedfa22021-03-23 17:07:14 -0700304 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700305
Colin Cross5bedfa22021-03-23 17:07:14 -0700306 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700307
Colin Cross1661aff2021-03-12 17:56:51 -0800308 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700309
310 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
311 // the root dir is not set.
312 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700313
314 cmd.FlagWithInput("@",
315 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
316
Cole Faust69861aa2023-01-31 15:49:07 -0800317 if l.compileSdkKind == android.SdkPublic {
318 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
319 } else {
320 // TODO(b/268261262): Remove this branch. We're demoting NewApi to a warning due to pre-existing issues that need to be fixed.
321 cmd.FlagForEachArg("--warning_check ", l.extraMainlineLintErrors)
322 }
Colin Cross014489c2020-06-02 20:09:13 -0700323 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
324 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
325 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
326 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
327
Cole Faust1021ccd2023-02-26 21:15:25 -0800328 // TODO(b/193460475): Re-enable strict updatability linting
329 //if l.GetStrictUpdatabilityLinting() {
330 // // Verify the module does not baseline issues that endanger safe updatability.
331 // if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
332 // cmd.FlagWithInput("--baseline ", baselinePath.Path())
333 // cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
334 // }
335 //}
Jaewoong Jung48de8832021-04-21 16:17:25 -0700336
Colin Cross31972dc2021-03-04 10:44:12 -0800337 return lintPaths{
338 projectXML: projectXMLPath,
339 configXML: configXMLPath,
340 cacheDir: cacheDir,
341 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800342 }
343
Colin Cross014489c2020-06-02 20:09:13 -0700344}
345
Liz Kammer20ebfb42020-07-28 11:32:07 -0700346// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700347// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800348func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700349 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
350
351 rule.Command().Text("(").
352 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
353 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
354 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000355 Textf(`echo " <uses-sdk android:minSdkVersion='%d' android:targetSdkVersion='%d'/>" &&`,
356 l.minSdkVersion, l.targetSdkVersion).
Colin Cross014489c2020-06-02 20:09:13 -0700357 Text(`echo "</manifest>"`).
358 Text(") >").Output(manifestPath)
359
360 return manifestPath
361}
362
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700363func (l *linter) getBaselineFilepath(ctx android.ModuleContext) android.OptionalPath {
364 var lintBaseline android.OptionalPath
365 if lintFilename := proptools.StringDefault(l.properties.Lint.Baseline_filename, "lint-baseline.xml"); lintFilename != "" {
366 if String(l.properties.Lint.Baseline_filename) != "" {
367 // if manually specified, we require the file to exist
368 lintBaseline = android.OptionalPathForPath(android.PathForModuleSrc(ctx, lintFilename))
369 } else {
370 lintBaseline = android.ExistentPathForSource(ctx, ctx.ModuleDir(), lintFilename)
371 }
372 }
373 return lintBaseline
374}
375
Colin Cross014489c2020-06-02 20:09:13 -0700376func (l *linter) lint(ctx android.ModuleContext) {
377 if !l.enabled() {
378 return
379 }
380
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000381 if l.minSdkVersion != l.compileSdkVersion {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700382 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100383 // Skip lint warning checks for NewApi warnings for libcore where they come from source
384 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100385 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100386 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
387
388 if len(filtered) != 0 {
389 ctx.PropertyErrorf("lint.warning_checks",
390 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
391 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700392 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100393
394 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700395 if len(filtered) != 0 {
396 ctx.PropertyErrorf("lint.disabled_checks",
397 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
398 }
Cole Faust3f646262022-06-29 14:58:03 -0700399
400 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
401 if ctx.ModuleName() == "PermissionController" {
402 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
403 return s != "NewApi"
404 })
405 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
406 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000407 }
408
Colin Cross92e4b462020-06-18 15:56:48 -0700409 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
410 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Crossdcf71b22021-02-01 13:59:03 -0800411 if ctx.OtherModuleHasProvider(extraLintCheckModule, JavaInfoProvider) {
412 dep := ctx.OtherModuleProvider(extraLintCheckModule, JavaInfoProvider).(JavaInfo)
413 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700414 } else {
415 ctx.PropertyErrorf("lint.extra_check_modules",
416 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
417 }
418 }
419
mattgilbride5aecabe2022-11-29 20:16:36 +0000420 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
421 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
422
Colin Cross1661aff2021-03-12 17:56:51 -0800423 rule := android.NewRuleBuilder(pctx, ctx).
424 Sbox(android.PathForModuleOut(ctx, "lint"),
425 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
426 SandboxInputs()
427
428 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
429 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
430 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
431 rule.Rewrapper(&remoteexec.REParams{
432 Labels: map[string]string{"type": "tool", "name": "lint"},
433 ExecStrategy: lintRBEExecStrategy(ctx),
434 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700435 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800436 })
437 }
Colin Cross014489c2020-06-02 20:09:13 -0700438
439 if l.manifest == nil {
440 manifest := l.generateManifest(ctx, rule)
441 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800442 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700443 }
444
Colin Cross62695b92022-08-12 16:09:24 -0700445 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
446 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
447 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList)
448
449 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700450
Colin Cross1661aff2021-03-12 17:56:51 -0800451 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
452 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
453 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Cole Faustdf38f7a2023-03-02 16:43:15 -0800454 referenceBaseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700455
Colin Cross08dca382020-07-21 20:31:17 -0700456 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700457
458 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000459 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700460 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700461 }
462 })
Colin Cross014489c2020-06-02 20:09:13 -0700463
Colin Cross31972dc2021-03-04 10:44:12 -0800464 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
465 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800466 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700467
Cole Faust69861aa2023-01-31 15:49:07 -0800468 files, ok := allLintDatabasefiles[l.compileSdkKind]
469 if !ok {
470 files = allLintDatabasefiles[android.SdkPublic]
Pedro Loureiro18233a22021-06-08 18:11:21 +0000471 }
Colin Cross8a6ed372020-07-06 11:45:51 -0700472 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900473 if ctx.Config().AlwaysUsePrebuiltSdks() {
Cole Faust69861aa2023-01-31 15:49:07 -0800474 annotationsZipPath = android.PathForSource(ctx, files.annotationPrebuiltpath)
475 apiVersionsXMLPath = android.PathForSource(ctx, files.apiVersionsPrebuiltPath)
Colin Cross8a6ed372020-07-06 11:45:51 -0700476 } else {
Cole Faust69861aa2023-01-31 15:49:07 -0800477 annotationsZipPath = copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName)
478 apiVersionsXMLPath = copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700479 }
480
Colin Cross31972dc2021-03-04 10:44:12 -0800481 cmd := rule.Command()
482
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000483 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800484 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700485 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800486 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
487
Colin Cross1661aff2021-03-12 17:56:51 -0800488 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700489 Flag("--quiet").
Colin Cross31972dc2021-03-04 10:44:12 -0800490 FlagWithInput("--project ", lintPaths.projectXML).
491 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700492 FlagWithOutput("--html ", html).
493 FlagWithOutput("--text ", text).
494 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000495 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700496 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
497 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
498 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
Colin Cross62695b92022-08-12 16:09:24 -0700499 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700500 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800501 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700502 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700503
Colin Cross1661aff2021-03-12 17:56:51 -0800504 rule.Temporary(lintPaths.projectXML)
505 rule.Temporary(lintPaths.configXML)
506
mattgilbrideb597abd2023-03-22 17:44:18 +0000507 if exitCode := ctx.Config().Getenv("ANDROID_LINT_SUPPRESS_EXIT_CODE"); exitCode == "" {
508 cmd.Flag("--exitcode")
509 }
510
Colin Cross988dfcc2020-07-16 17:32:17 -0700511 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
512 cmd.FlagWithArg("--check ", checkOnly)
513 }
514
Jaewoong Jung302c5b82021-04-19 08:54:36 -0700515 lintBaseline := l.getBaselineFilepath(ctx)
516 if lintBaseline.Valid() {
517 cmd.FlagWithInput("--baseline ", lintBaseline.Path())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000518 }
519
Cole Faustdf38f7a2023-03-02 16:43:15 -0800520 cmd.FlagWithOutput("--write-reference-baseline ", referenceBaseline)
Colin Cross6b76c152021-09-09 09:36:25 -0700521
Colin Cross1b9e6832022-10-11 11:22:24 -0700522 cmd.Text("; EXITCODE=$?; ")
523
524 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
525 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
526 // a fatal error.
527 cmd.BuiltTool("soong_zip").
528 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
529 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
530 FlagWithInput("-r ", srcsList)
531
532 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 -0700533
Colin Cross31972dc2021-03-04 10:44:12 -0800534 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700535
Colin Crossee4a8b72021-04-05 18:38:05 -0700536 // The HTML output contains a date, remove it to make the output deterministic.
537 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
538
Colin Crossf1a035e2020-11-16 17:32:30 -0800539 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700540
Colin Crossc0efd1d2020-07-03 11:56:24 -0700541 l.outputs = lintOutputs{
Cole Faustdf38f7a2023-03-02 16:43:15 -0800542 html: html,
543 text: text,
544 xml: xml,
545 referenceBaseline: referenceBaseline,
Colin Cross014489c2020-06-02 20:09:13 -0700546
Colin Cross08dca382020-07-21 20:31:17 -0700547 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700548 }
Colin Cross014489c2020-06-02 20:09:13 -0700549
Colin Crossc0efd1d2020-07-03 11:56:24 -0700550 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700551 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700552 }
553}
Colin Cross014489c2020-06-02 20:09:13 -0700554
Colin Cross08dca382020-07-21 20:31:17 -0700555func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
556 htmlList := depSets.HTML.ToSortedList()
557 textList := depSets.Text.ToSortedList()
558 xmlList := depSets.XML.ToSortedList()
559
560 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
561 return nil
562 }
563
564 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
565 lintZip(ctx, htmlList, htmlZip)
566
567 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
568 lintZip(ctx, textList, textZip)
569
570 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
571 lintZip(ctx, xmlList, xmlZip)
572
573 return android.Paths{htmlZip, textZip, xmlZip}
574}
575
Colin Cross014489c2020-06-02 20:09:13 -0700576type lintSingleton struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800577 htmlZip android.WritablePath
578 textZip android.WritablePath
579 xmlZip android.WritablePath
580 referenceBaselineZip android.WritablePath
Colin Cross014489c2020-06-02 20:09:13 -0700581}
582
583func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
584 l.generateLintReportZips(ctx)
585 l.copyLintDependencies(ctx)
586}
587
Pedro Loureiro18233a22021-06-08 18:11:21 +0000588func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
589 var res android.Module
590 ctx.VisitAllModules(func(m android.Module) {
591 if ctx.ModuleName(m) == moduleName {
592 if res == nil {
593 res = m
594 } else {
595 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
596 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
597 }
598 }
599 })
600 return res
601}
602
Colin Cross014489c2020-06-02 20:09:13 -0700603func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900604 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700605 return
606 }
607
Cole Faust69861aa2023-01-31 15:49:07 -0800608 for _, sdk := range android.SortedKeys(allLintDatabasefiles) {
609 files := allLintDatabasefiles[sdk]
610 apiVersionsDb := findModuleOrErr(ctx, files.apiVersionsModule)
611 if apiVersionsDb == nil {
612 if !ctx.Config().AllowMissingDependencies() {
613 ctx.Errorf("lint: missing module api_versions_public")
614 }
615 return
Colin Cross014489c2020-06-02 20:09:13 -0700616 }
Colin Cross014489c2020-06-02 20:09:13 -0700617
Cole Faust69861aa2023-01-31 15:49:07 -0800618 sdkAnnotations := findModuleOrErr(ctx, files.annotationsModule)
619 if sdkAnnotations == nil {
620 if !ctx.Config().AllowMissingDependencies() {
621 ctx.Errorf("lint: missing module sdk-annotations.zip")
622 }
623 return
Anton Hanssonea17a452022-05-09 09:42:17 +0000624 }
Cole Faust69861aa2023-01-31 15:49:07 -0800625
626 ctx.Build(pctx, android.BuildParams{
627 Rule: android.CpIfChanged,
628 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
629 Output: copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName),
630 })
631
632 ctx.Build(pctx, android.BuildParams{
633 Rule: android.CpIfChanged,
634 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
635 Output: copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName),
636 })
Anton Hanssonea17a452022-05-09 09:42:17 +0000637 }
Colin Cross014489c2020-06-02 20:09:13 -0700638}
639
Cole Faust69861aa2023-01-31 15:49:07 -0800640func copiedLintDatabaseFilesPath(ctx android.PathContext, name string) android.WritablePath {
Pedro Loureiro18233a22021-06-08 18:11:21 +0000641 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700642}
643
644func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700645 if ctx.Config().UnbundledBuild() {
646 return
647 }
648
Colin Cross014489c2020-06-02 20:09:13 -0700649 var outputs []*lintOutputs
650 var dirs []string
651 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500652 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700653 return
654 }
655
Colin Cross56a83212020-09-15 18:30:11 -0700656 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
657 apexInfo := ctx.ModuleProvider(m, android.ApexInfoProvider).(android.ApexInfo)
658 if apexInfo.IsForPlatform() {
659 // There are stray platform variants of modules in apexes that are not available for
660 // the platform, and they sometimes can't be built. Don't depend on them.
661 return
662 }
Colin Cross014489c2020-06-02 20:09:13 -0700663 }
664
Colin Cross08dca382020-07-21 20:31:17 -0700665 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700666 outputs = append(outputs, l.lintOutputs())
667 }
668 })
669
670 dirs = android.SortedUniqueStrings(dirs)
671
672 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
673 var paths android.Paths
674
675 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700676 if p := get(output); p != nil {
677 paths = append(paths, p)
678 }
Colin Cross014489c2020-06-02 20:09:13 -0700679 }
680
Colin Crossc0efd1d2020-07-03 11:56:24 -0700681 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700682 }
683
684 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
685 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
686
687 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
688 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
689
690 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
691 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
692
Cole Faustdf38f7a2023-03-02 16:43:15 -0800693 l.referenceBaselineZip = android.PathForOutput(ctx, "lint-report-reference-baselines.zip")
694 zip(l.referenceBaselineZip, func(l *lintOutputs) android.Path { return l.referenceBaseline })
695
696 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross014489c2020-06-02 20:09:13 -0700697}
698
699func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700700 if !ctx.Config().UnbundledBuild() {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800701 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross8a6ed372020-07-06 11:45:51 -0700702 }
Colin Cross014489c2020-06-02 20:09:13 -0700703}
704
705var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
706
707func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +0000708 android.RegisterParallelSingletonType("lint",
Colin Cross014489c2020-06-02 20:09:13 -0700709 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700710
711 registerLintBuildComponents(android.InitRegistrationContext)
712}
713
714func registerLintBuildComponents(ctx android.RegistrationContext) {
715 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
716 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
717 })
Colin Cross014489c2020-06-02 20:09:13 -0700718}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700719
720func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
721 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
722
723 sort.Slice(paths, func(i, j int) bool {
724 return paths[i].String() < paths[j].String()
725 })
726
Colin Crossf1a035e2020-11-16 17:32:30 -0800727 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700728
Colin Crossf1a035e2020-11-16 17:32:30 -0800729 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700730 FlagWithOutput("-o ", outputPath).
731 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800732 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700733
Colin Crossf1a035e2020-11-16 17:32:30 -0800734 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700735}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700736
737// Enforce the strict updatability linting to all applicable transitive dependencies.
738func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
739 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000740 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700741 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000742 if a, ok := d.(LintDepSetsIntf); ok {
743 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700744 }
745 })
746 }
747}