blob: 39f9df273397119e9c0c7beae191d158899693ce [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
Cole Faustb765d6b2024-01-04 10:29:27 -080059 // The lint baseline file to use. If specified, lint warnings listed in this file will be
60 // suppressed during lint checks.
Pedro Loureiro5d190cc2021-02-15 15:41:33 +000061 Baseline_filename *string
Jaewoong Jung48de8832021-04-21 16:17:25 -070062
63 // If true, baselining updatability lint checks (e.g. NewApi) is prohibited. Defaults to false.
64 Strict_updatability_linting *bool
Cole Faustd57e8b22022-08-11 11:59:04 -070065
66 // Treat the code in this module as test code for @VisibleForTesting enforcement.
67 // This will be true by default for test module types, false otherwise.
68 // If soong gets support for testonly, this flag should be replaced with that.
69 Test *bool
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +100070
71 // Whether to ignore the exit code of Android lint. This is the --exit_code
72 // option. Defaults to false.
73 Suppress_exit_code *bool
Colin Cross014489c2020-06-02 20:09:13 -070074 }
75}
76
77type linter struct {
Pedro Loureirof4a88b12021-02-25 16:23:22 +000078 name string
79 manifest android.Path
80 mergedManifest android.Path
81 srcs android.Paths
82 srcJars android.Paths
83 resources android.Paths
84 classpath android.Paths
85 classes android.Path
86 extraLintCheckJars android.Paths
Pedro Loureirof4a88b12021-02-25 16:23:22 +000087 library bool
Cole Fauste5bf3fb2022-07-01 19:39:14 +000088 minSdkVersion int
89 targetSdkVersion int
90 compileSdkVersion int
Pedro Loureiro18233a22021-06-08 18:11:21 +000091 compileSdkKind android.SdkKind
Pedro Loureirof4a88b12021-02-25 16:23:22 +000092 javaLanguageLevel string
93 kotlinLanguageLevel string
94 outputs lintOutputs
95 properties LintProperties
96 extraMainlineLintErrors []string
Cole Faustdf1efd72023-12-08 12:27:24 -080097 compile_data android.Paths
Colin Crossc0efd1d2020-07-03 11:56:24 -070098
Colin Cross08dca382020-07-21 20:31:17 -070099 reports android.Paths
100
Colin Crossc0efd1d2020-07-03 11:56:24 -0700101 buildModuleReportZip bool
Colin Cross014489c2020-06-02 20:09:13 -0700102}
103
104type lintOutputs struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800105 html android.Path
106 text android.Path
107 xml android.Path
108 referenceBaseline android.Path
Colin Crossc0efd1d2020-07-03 11:56:24 -0700109
Colin Cross08dca382020-07-21 20:31:17 -0700110 depSets LintDepSets
Colin Crossc0efd1d2020-07-03 11:56:24 -0700111}
112
Colin Cross08dca382020-07-21 20:31:17 -0700113type lintOutputsIntf interface {
Colin Crossc0efd1d2020-07-03 11:56:24 -0700114 lintOutputs() *lintOutputs
115}
116
Spandan Das17854f52022-01-14 21:19:14 +0000117type LintDepSetsIntf interface {
Colin Cross08dca382020-07-21 20:31:17 -0700118 LintDepSets() LintDepSets
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700119
120 // Methods used to propagate strict_updatability_linting values.
Spandan Das17854f52022-01-14 21:19:14 +0000121 GetStrictUpdatabilityLinting() bool
122 SetStrictUpdatabilityLinting(bool)
Colin Cross08dca382020-07-21 20:31:17 -0700123}
124
125type LintDepSets struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700126 HTML, Text, XML *android.DepSet[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700127}
128
129type LintDepSetsBuilder struct {
Colin Crossc85750b2022-04-21 12:50:51 -0700130 HTML, Text, XML *android.DepSetBuilder[android.Path]
Colin Cross08dca382020-07-21 20:31:17 -0700131}
132
133func NewLintDepSetBuilder() LintDepSetsBuilder {
134 return LintDepSetsBuilder{
Colin Crossc85750b2022-04-21 12:50:51 -0700135 HTML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
136 Text: android.NewDepSetBuilder[android.Path](android.POSTORDER),
137 XML: android.NewDepSetBuilder[android.Path](android.POSTORDER),
Colin Cross08dca382020-07-21 20:31:17 -0700138 }
139}
140
141func (l LintDepSetsBuilder) Direct(html, text, xml android.Path) LintDepSetsBuilder {
142 l.HTML.Direct(html)
143 l.Text.Direct(text)
144 l.XML.Direct(xml)
145 return l
146}
147
148func (l LintDepSetsBuilder) Transitive(depSets LintDepSets) LintDepSetsBuilder {
149 if depSets.HTML != nil {
150 l.HTML.Transitive(depSets.HTML)
151 }
152 if depSets.Text != nil {
153 l.Text.Transitive(depSets.Text)
154 }
155 if depSets.XML != nil {
156 l.XML.Transitive(depSets.XML)
157 }
158 return l
159}
160
161func (l LintDepSetsBuilder) Build() LintDepSets {
162 return LintDepSets{
163 HTML: l.HTML.Build(),
164 Text: l.Text.Build(),
165 XML: l.XML.Build(),
166 }
167}
168
Cole Faust69861aa2023-01-31 15:49:07 -0800169type lintDatabaseFiles struct {
170 apiVersionsModule string
171 apiVersionsCopiedName string
172 apiVersionsPrebuiltPath string
173 annotationsModule string
174 annotationCopiedName string
175 annotationPrebuiltpath string
176}
177
178var allLintDatabasefiles = map[android.SdkKind]lintDatabaseFiles{
179 android.SdkPublic: {
180 apiVersionsModule: "api_versions_public",
181 apiVersionsCopiedName: "api_versions_public.xml",
182 apiVersionsPrebuiltPath: "prebuilts/sdk/current/public/data/api-versions.xml",
183 annotationsModule: "sdk-annotations.zip",
184 annotationCopiedName: "annotations-public.zip",
185 annotationPrebuiltpath: "prebuilts/sdk/current/public/data/annotations.zip",
186 },
187 android.SdkSystem: {
188 apiVersionsModule: "api_versions_system",
189 apiVersionsCopiedName: "api_versions_system.xml",
190 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system/data/api-versions.xml",
191 annotationsModule: "sdk-annotations-system.zip",
192 annotationCopiedName: "annotations-system.zip",
193 annotationPrebuiltpath: "prebuilts/sdk/current/system/data/annotations.zip",
194 },
195 android.SdkModule: {
196 apiVersionsModule: "api_versions_module_lib",
197 apiVersionsCopiedName: "api_versions_module_lib.xml",
198 apiVersionsPrebuiltPath: "prebuilts/sdk/current/module-lib/data/api-versions.xml",
199 annotationsModule: "sdk-annotations-module-lib.zip",
200 annotationCopiedName: "annotations-module-lib.zip",
201 annotationPrebuiltpath: "prebuilts/sdk/current/module-lib/data/annotations.zip",
202 },
203 android.SdkSystemServer: {
204 apiVersionsModule: "api_versions_system_server",
205 apiVersionsCopiedName: "api_versions_system_server.xml",
206 apiVersionsPrebuiltPath: "prebuilts/sdk/current/system-server/data/api-versions.xml",
207 annotationsModule: "sdk-annotations-system-server.zip",
208 annotationCopiedName: "annotations-system-server.zip",
209 annotationPrebuiltpath: "prebuilts/sdk/current/system-server/data/annotations.zip",
210 },
211}
212
Colin Cross08dca382020-07-21 20:31:17 -0700213func (l *linter) LintDepSets() LintDepSets {
214 return l.outputs.depSets
215}
216
Spandan Das17854f52022-01-14 21:19:14 +0000217func (l *linter) GetStrictUpdatabilityLinting() bool {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700218 return BoolDefault(l.properties.Lint.Strict_updatability_linting, false)
219}
220
Spandan Das17854f52022-01-14 21:19:14 +0000221func (l *linter) SetStrictUpdatabilityLinting(strictLinting bool) {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700222 l.properties.Lint.Strict_updatability_linting = &strictLinting
223}
224
Spandan Das17854f52022-01-14 21:19:14 +0000225var _ LintDepSetsIntf = (*linter)(nil)
Colin Cross08dca382020-07-21 20:31:17 -0700226
227var _ lintOutputsIntf = (*linter)(nil)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700228
229func (l *linter) lintOutputs() *lintOutputs {
230 return &l.outputs
Colin Cross014489c2020-06-02 20:09:13 -0700231}
232
233func (l *linter) enabled() bool {
234 return BoolDefault(l.properties.Lint.Enabled, true)
235}
236
Colin Cross92e4b462020-06-18 15:56:48 -0700237func (l *linter) deps(ctx android.BottomUpMutatorContext) {
238 if !l.enabled() {
239 return
240 }
241
Colin Cross988dfcc2020-07-16 17:32:17 -0700242 extraCheckModules := l.properties.Lint.Extra_check_modules
243
mattgilbridee17645f2022-11-18 18:20:20 +0000244 if extraCheckModulesEnv := ctx.Config().Getenv("ANDROID_LINT_CHECK_EXTRA_MODULES"); extraCheckModulesEnv != "" {
245 extraCheckModules = append(extraCheckModules, strings.Split(extraCheckModulesEnv, ",")...)
Colin Cross988dfcc2020-07-16 17:32:17 -0700246 }
247
248 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(),
249 extraLintCheckTag, extraCheckModules...)
Colin Cross92e4b462020-06-18 15:56:48 -0700250}
251
Colin Crossad22bc22021-03-10 09:45:40 -0800252// lintPaths contains the paths to lint's inputs and outputs to make it easier to pass them
253// around.
Colin Cross31972dc2021-03-04 10:44:12 -0800254type lintPaths struct {
255 projectXML android.WritablePath
256 configXML android.WritablePath
257 cacheDir android.WritablePath
258 homeDir android.WritablePath
259 srcjarDir android.WritablePath
Colin Cross31972dc2021-03-04 10:44:12 -0800260}
261
Colin Cross9b93af42021-03-10 10:40:58 -0800262func lintRBEExecStrategy(ctx android.ModuleContext) string {
263 return ctx.Config().GetenvWithDefault("RBE_LINT_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
264}
265
Colin Cross62695b92022-08-12 16:09:24 -0700266func (l *linter) writeLintProjectXML(ctx android.ModuleContext, rule *android.RuleBuilder, srcsList android.Path) lintPaths {
Colin Cross31972dc2021-03-04 10:44:12 -0800267 projectXMLPath := android.PathForModuleOut(ctx, "lint", "project.xml")
Colin Cross014489c2020-06-02 20:09:13 -0700268 // Lint looks for a lint.xml file next to the project.xml file, give it one.
Colin Cross31972dc2021-03-04 10:44:12 -0800269 configXMLPath := android.PathForModuleOut(ctx, "lint", "lint.xml")
270 cacheDir := android.PathForModuleOut(ctx, "lint", "cache")
271 homeDir := android.PathForModuleOut(ctx, "lint", "home")
Colin Cross014489c2020-06-02 20:09:13 -0700272
Colin Cross1661aff2021-03-12 17:56:51 -0800273 srcJarDir := android.PathForModuleOut(ctx, "lint", "srcjars")
Colin Cross014489c2020-06-02 20:09:13 -0700274 srcJarList := zipSyncCmd(ctx, rule, srcJarDir, l.srcJars)
275
276 cmd := rule.Command().
Jaewoong Jung5a420252021-04-19 17:58:22 -0700277 BuiltTool("lint_project_xml").
Colin Cross014489c2020-06-02 20:09:13 -0700278 FlagWithOutput("--project_out ", projectXMLPath).
279 FlagWithOutput("--config_out ", configXMLPath).
280 FlagWithArg("--name ", ctx.ModuleName())
281
282 if l.library {
283 cmd.Flag("--library")
284 }
Cole Faustd57e8b22022-08-11 11:59:04 -0700285 if proptools.BoolDefault(l.properties.Lint.Test, false) {
Colin Cross014489c2020-06-02 20:09:13 -0700286 cmd.Flag("--test")
287 }
288 if l.manifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700289 cmd.FlagWithInput("--manifest ", l.manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700290 }
291 if l.mergedManifest != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700292 cmd.FlagWithInput("--merged_manifest ", l.mergedManifest)
Colin Cross014489c2020-06-02 20:09:13 -0700293 }
294
Colin Cross5bedfa22021-03-23 17:07:14 -0700295 // TODO(ccross): some of the files in l.srcs are generated sources and should be passed to
296 // lint separately.
Colin Cross62695b92022-08-12 16:09:24 -0700297 cmd.FlagWithInput("--srcs ", srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700298
299 cmd.FlagWithInput("--generated_srcs ", srcJarList)
Colin Cross014489c2020-06-02 20:09:13 -0700300
Colin Cross5bedfa22021-03-23 17:07:14 -0700301 if len(l.resources) > 0 {
302 resourcesList := android.PathForModuleOut(ctx, "lint-resources.list")
303 cmd.FlagWithRspFileInputList("--resources ", resourcesList, l.resources)
Colin Cross014489c2020-06-02 20:09:13 -0700304 }
305
306 if l.classes != nil {
Colin Cross5bedfa22021-03-23 17:07:14 -0700307 cmd.FlagWithInput("--classes ", l.classes)
Colin Cross014489c2020-06-02 20:09:13 -0700308 }
309
Colin Cross5bedfa22021-03-23 17:07:14 -0700310 cmd.FlagForEachInput("--classpath ", l.classpath)
Colin Cross014489c2020-06-02 20:09:13 -0700311
Colin Cross5bedfa22021-03-23 17:07:14 -0700312 cmd.FlagForEachInput("--extra_checks_jar ", l.extraLintCheckJars)
Colin Cross014489c2020-06-02 20:09:13 -0700313
Colin Cross1661aff2021-03-12 17:56:51 -0800314 cmd.FlagWithArg("--root_dir ", "$PWD")
Colin Crossc31efeb2020-06-23 10:25:26 -0700315
316 // The cache tag in project.xml is relative to the root dir, or the project.xml file if
317 // the root dir is not set.
318 cmd.FlagWithArg("--cache_dir ", cacheDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700319
320 cmd.FlagWithInput("@",
321 android.PathForSource(ctx, "build/soong/java/lint_defaults.txt"))
322
Cole Faust69861aa2023-01-31 15:49:07 -0800323 if l.compileSdkKind == android.SdkPublic {
324 cmd.FlagForEachArg("--error_check ", l.extraMainlineLintErrors)
325 } else {
326 // TODO(b/268261262): Remove this branch. We're demoting NewApi to a warning due to pre-existing issues that need to be fixed.
327 cmd.FlagForEachArg("--warning_check ", l.extraMainlineLintErrors)
328 }
Colin Cross014489c2020-06-02 20:09:13 -0700329 cmd.FlagForEachArg("--disable_check ", l.properties.Lint.Disabled_checks)
330 cmd.FlagForEachArg("--warning_check ", l.properties.Lint.Warning_checks)
331 cmd.FlagForEachArg("--error_check ", l.properties.Lint.Error_checks)
332 cmd.FlagForEachArg("--fatal_check ", l.properties.Lint.Fatal_checks)
333
Cole Faust1021ccd2023-02-26 21:15:25 -0800334 // TODO(b/193460475): Re-enable strict updatability linting
335 //if l.GetStrictUpdatabilityLinting() {
336 // // Verify the module does not baseline issues that endanger safe updatability.
337 // if baselinePath := l.getBaselineFilepath(ctx); baselinePath.Valid() {
338 // cmd.FlagWithInput("--baseline ", baselinePath.Path())
339 // cmd.FlagForEachArg("--disallowed_issues ", updatabilityChecks)
340 // }
341 //}
Jaewoong Jung48de8832021-04-21 16:17:25 -0700342
Colin Cross31972dc2021-03-04 10:44:12 -0800343 return lintPaths{
344 projectXML: projectXMLPath,
345 configXML: configXMLPath,
346 cacheDir: cacheDir,
347 homeDir: homeDir,
Colin Cross31972dc2021-03-04 10:44:12 -0800348 }
349
Colin Cross014489c2020-06-02 20:09:13 -0700350}
351
Liz Kammer20ebfb42020-07-28 11:32:07 -0700352// generateManifest adds a command to the rule to write a simple manifest that contains the
Colin Cross014489c2020-06-02 20:09:13 -0700353// minSdkVersion and targetSdkVersion for modules (like java_library) that don't have a manifest.
Colin Cross1661aff2021-03-12 17:56:51 -0800354func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {
Colin Cross014489c2020-06-02 20:09:13 -0700355 manifestPath := android.PathForModuleOut(ctx, "lint", "AndroidManifest.xml")
356
357 rule.Command().Text("(").
358 Text(`echo "<?xml version='1.0' encoding='utf-8'?>" &&`).
359 Text(`echo "<manifest xmlns:android='http://schemas.android.com/apk/res/android'" &&`).
360 Text(`echo " android:versionCode='1' android:versionName='1' >" &&`).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000361 Textf(`echo " <uses-sdk android:minSdkVersion='%d' android:targetSdkVersion='%d'/>" &&`,
362 l.minSdkVersion, l.targetSdkVersion).
Colin Cross014489c2020-06-02 20:09:13 -0700363 Text(`echo "</manifest>"`).
364 Text(") >").Output(manifestPath)
365
366 return manifestPath
367}
368
369func (l *linter) lint(ctx android.ModuleContext) {
370 if !l.enabled() {
371 return
372 }
373
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000374 if l.minSdkVersion != l.compileSdkVersion {
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700375 l.extraMainlineLintErrors = append(l.extraMainlineLintErrors, updatabilityChecks...)
Orion Hodsonb8166522022-08-15 20:23:38 +0100376 // Skip lint warning checks for NewApi warnings for libcore where they come from source
377 // files that reference the API they are adding (b/208656169).
Orion Hodsonb2d3c8c2022-10-25 16:45:14 +0100378 if !strings.HasPrefix(ctx.ModuleDir(), "libcore") {
Orion Hodsonb8166522022-08-15 20:23:38 +0100379 _, filtered := android.FilterList(l.properties.Lint.Warning_checks, updatabilityChecks)
380
381 if len(filtered) != 0 {
382 ctx.PropertyErrorf("lint.warning_checks",
383 "Can't treat %v checks as warnings if min_sdk_version is different from sdk_version.", filtered)
384 }
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700385 }
Orion Hodsonb8166522022-08-15 20:23:38 +0100386
387 _, filtered := android.FilterList(l.properties.Lint.Disabled_checks, updatabilityChecks)
Jaewoong Jung79e6f6b2021-04-21 14:01:55 -0700388 if len(filtered) != 0 {
389 ctx.PropertyErrorf("lint.disabled_checks",
390 "Can't disable %v checks if min_sdk_version is different from sdk_version.", filtered)
391 }
Cole Faust3f646262022-06-29 14:58:03 -0700392
393 // TODO(b/238784089): Remove this workaround when the NewApi issues have been addressed in PermissionController
394 if ctx.ModuleName() == "PermissionController" {
395 l.extraMainlineLintErrors = android.FilterListPred(l.extraMainlineLintErrors, func(s string) bool {
396 return s != "NewApi"
397 })
398 l.properties.Lint.Warning_checks = append(l.properties.Lint.Warning_checks, "NewApi")
399 }
Pedro Loureirof4a88b12021-02-25 16:23:22 +0000400 }
401
Colin Cross92e4b462020-06-18 15:56:48 -0700402 extraLintCheckModules := ctx.GetDirectDepsWithTag(extraLintCheckTag)
403 for _, extraLintCheckModule := range extraLintCheckModules {
Colin Cross313aa542023-12-13 13:47:44 -0800404 if dep, ok := android.OtherModuleProvider(ctx, extraLintCheckModule, JavaInfoProvider); ok {
Colin Crossdcf71b22021-02-01 13:59:03 -0800405 l.extraLintCheckJars = append(l.extraLintCheckJars, dep.ImplementationAndResourcesJars...)
Colin Cross92e4b462020-06-18 15:56:48 -0700406 } else {
407 ctx.PropertyErrorf("lint.extra_check_modules",
408 "%s is not a java module", ctx.OtherModuleName(extraLintCheckModule))
409 }
410 }
411
mattgilbride5aecabe2022-11-29 20:16:36 +0000412 l.extraLintCheckJars = append(l.extraLintCheckJars, android.PathForSource(ctx,
413 "prebuilts/cmdline-tools/AndroidGlobalLintChecker.jar"))
414
Colin Cross1661aff2021-03-12 17:56:51 -0800415 rule := android.NewRuleBuilder(pctx, ctx).
416 Sbox(android.PathForModuleOut(ctx, "lint"),
417 android.PathForModuleOut(ctx, "lint.sbox.textproto")).
418 SandboxInputs()
419
420 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_LINT") {
421 pool := ctx.Config().GetenvWithDefault("RBE_LINT_POOL", "java16")
422 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
423 rule.Rewrapper(&remoteexec.REParams{
424 Labels: map[string]string{"type": "tool", "name": "lint"},
425 ExecStrategy: lintRBEExecStrategy(ctx),
426 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
Colin Cross95fad7a2021-06-09 12:48:53 -0700427 Platform: map[string]string{remoteexec.PoolKey: pool},
Colin Cross1661aff2021-03-12 17:56:51 -0800428 })
429 }
Colin Cross014489c2020-06-02 20:09:13 -0700430
431 if l.manifest == nil {
432 manifest := l.generateManifest(ctx, rule)
433 l.manifest = manifest
Colin Cross1661aff2021-03-12 17:56:51 -0800434 rule.Temporary(manifest)
Colin Cross014489c2020-06-02 20:09:13 -0700435 }
436
Colin Cross62695b92022-08-12 16:09:24 -0700437 srcsList := android.PathForModuleOut(ctx, "lint", "lint-srcs.list")
438 srcsListRsp := android.PathForModuleOut(ctx, "lint-srcs.list.rsp")
Cole Faustdf1efd72023-12-08 12:27:24 -0800439 rule.Command().Text("cp").FlagWithRspFileInputList("", srcsListRsp, l.srcs).Output(srcsList).Implicits(l.compile_data)
Colin Cross62695b92022-08-12 16:09:24 -0700440
441 lintPaths := l.writeLintProjectXML(ctx, rule, srcsList)
Colin Cross014489c2020-06-02 20:09:13 -0700442
Colin Cross1661aff2021-03-12 17:56:51 -0800443 html := android.PathForModuleOut(ctx, "lint", "lint-report.html")
444 text := android.PathForModuleOut(ctx, "lint", "lint-report.txt")
445 xml := android.PathForModuleOut(ctx, "lint", "lint-report.xml")
Cole Faustdf38f7a2023-03-02 16:43:15 -0800446 referenceBaseline := android.PathForModuleOut(ctx, "lint", "lint-baseline.xml")
Colin Crossc0efd1d2020-07-03 11:56:24 -0700447
Colin Cross08dca382020-07-21 20:31:17 -0700448 depSetsBuilder := NewLintDepSetBuilder().Direct(html, text, xml)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700449
450 ctx.VisitDirectDepsWithTag(staticLibTag, func(dep android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000451 if depLint, ok := dep.(LintDepSetsIntf); ok {
Colin Cross08dca382020-07-21 20:31:17 -0700452 depSetsBuilder.Transitive(depLint.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700453 }
454 })
Colin Cross014489c2020-06-02 20:09:13 -0700455
Colin Cross31972dc2021-03-04 10:44:12 -0800456 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
457 rule.Command().Text("mkdir -p").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross5c113d12021-03-04 10:01:34 -0800458 rule.Command().Text("rm -f").Output(html).Output(text).Output(xml)
Colin Cross014489c2020-06-02 20:09:13 -0700459
Cole Faust69861aa2023-01-31 15:49:07 -0800460 files, ok := allLintDatabasefiles[l.compileSdkKind]
461 if !ok {
462 files = allLintDatabasefiles[android.SdkPublic]
Pedro Loureiro18233a22021-06-08 18:11:21 +0000463 }
Colin Cross8a6ed372020-07-06 11:45:51 -0700464 var annotationsZipPath, apiVersionsXMLPath android.Path
Jeongik Cha816a23a2020-07-08 01:09:23 +0900465 if ctx.Config().AlwaysUsePrebuiltSdks() {
Cole Faust69861aa2023-01-31 15:49:07 -0800466 annotationsZipPath = android.PathForSource(ctx, files.annotationPrebuiltpath)
467 apiVersionsXMLPath = android.PathForSource(ctx, files.apiVersionsPrebuiltPath)
Colin Cross8a6ed372020-07-06 11:45:51 -0700468 } else {
Cole Faust69861aa2023-01-31 15:49:07 -0800469 annotationsZipPath = copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName)
470 apiVersionsXMLPath = copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName)
Colin Cross8a6ed372020-07-06 11:45:51 -0700471 }
472
Colin Cross31972dc2021-03-04 10:44:12 -0800473 cmd := rule.Command()
474
Pedro Loureiro70acc3d2021-04-06 17:49:19 +0000475 cmd.Flag(`JAVA_OPTS="-Xmx3072m --add-opens java.base/java.util=ALL-UNNAMED"`).
Colin Cross31972dc2021-03-04 10:44:12 -0800476 FlagWithArg("ANDROID_SDK_HOME=", lintPaths.homeDir.String()).
Colin Cross8a6ed372020-07-06 11:45:51 -0700477 FlagWithInput("SDK_ANNOTATIONS=", annotationsZipPath).
Colin Cross31972dc2021-03-04 10:44:12 -0800478 FlagWithInput("LINT_OPTS=-DLINT_API_DATABASE=", apiVersionsXMLPath)
479
Colin Cross1661aff2021-03-12 17:56:51 -0800480 cmd.BuiltTool("lint").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "lint.jar")).
Colin Cross014489c2020-06-02 20:09:13 -0700481 Flag("--quiet").
Tor Norbyecabafde2023-12-07 21:57:28 +0000482 Flag("--include-aosp-issues").
Colin Cross31972dc2021-03-04 10:44:12 -0800483 FlagWithInput("--project ", lintPaths.projectXML).
484 FlagWithInput("--config ", lintPaths.configXML).
Colin Crossc0efd1d2020-07-03 11:56:24 -0700485 FlagWithOutput("--html ", html).
486 FlagWithOutput("--text ", text).
487 FlagWithOutput("--xml ", xml).
Cole Fauste5bf3fb2022-07-01 19:39:14 +0000488 FlagWithArg("--compile-sdk-version ", strconv.Itoa(l.compileSdkVersion)).
Colin Cross014489c2020-06-02 20:09:13 -0700489 FlagWithArg("--java-language-level ", l.javaLanguageLevel).
490 FlagWithArg("--kotlin-language-level ", l.kotlinLanguageLevel).
491 FlagWithArg("--url ", fmt.Sprintf(".=.,%s=out", android.PathForOutput(ctx).String())).
Colin Cross62695b92022-08-12 16:09:24 -0700492 Flag("--apply-suggestions"). // applies suggested fixes to files in the sandbox
Colin Cross014489c2020-06-02 20:09:13 -0700493 Flags(l.properties.Lint.Flags).
Colin Cross31972dc2021-03-04 10:44:12 -0800494 Implicit(annotationsZipPath).
Colin Cross5bedfa22021-03-23 17:07:14 -0700495 Implicit(apiVersionsXMLPath)
Colin Cross988dfcc2020-07-16 17:32:17 -0700496
Colin Cross1661aff2021-03-12 17:56:51 -0800497 rule.Temporary(lintPaths.projectXML)
498 rule.Temporary(lintPaths.configXML)
499
ThiƩbaud Weksteen9c0dff92023-09-29 10:21:56 +1000500 suppressExitCode := BoolDefault(l.properties.Lint.Suppress_exit_code, false)
501 if exitCode := ctx.Config().Getenv("ANDROID_LINT_SUPPRESS_EXIT_CODE"); exitCode == "" && !suppressExitCode {
mattgilbrideb597abd2023-03-22 17:44:18 +0000502 cmd.Flag("--exitcode")
503 }
504
Colin Cross988dfcc2020-07-16 17:32:17 -0700505 if checkOnly := ctx.Config().Getenv("ANDROID_LINT_CHECK"); checkOnly != "" {
506 cmd.FlagWithArg("--check ", checkOnly)
507 }
508
Cole Faustb765d6b2024-01-04 10:29:27 -0800509 if l.properties.Lint.Baseline_filename != nil {
510 cmd.FlagWithInput("--baseline ", android.PathForModuleSrc(ctx, *l.properties.Lint.Baseline_filename))
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000511 }
512
Cole Faustdf38f7a2023-03-02 16:43:15 -0800513 cmd.FlagWithOutput("--write-reference-baseline ", referenceBaseline)
Colin Cross6b76c152021-09-09 09:36:25 -0700514
Colin Cross1b9e6832022-10-11 11:22:24 -0700515 cmd.Text("; EXITCODE=$?; ")
516
517 // The sources in the sandbox may have been modified by --apply-suggestions, zip them up and
518 // export them out of the sandbox. Do this before exiting so that the suggestions exit even after
519 // a fatal error.
520 cmd.BuiltTool("soong_zip").
521 FlagWithOutput("-o ", android.PathForModuleOut(ctx, "lint", "suggested-fixes.zip")).
522 FlagWithArg("-C ", cmd.PathForInput(android.PathForSource(ctx))).
523 FlagWithInput("-r ", srcsList)
524
525 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 -0700526
Colin Cross31972dc2021-03-04 10:44:12 -0800527 rule.Command().Text("rm -rf").Flag(lintPaths.cacheDir.String()).Flag(lintPaths.homeDir.String())
Colin Cross014489c2020-06-02 20:09:13 -0700528
Colin Crossee4a8b72021-04-05 18:38:05 -0700529 // The HTML output contains a date, remove it to make the output deterministic.
530 rule.Command().Text(`sed -i.tmp -e 's|Check performed at .*\(</nav>\)|\1|'`).Output(html)
531
Colin Crossf1a035e2020-11-16 17:32:30 -0800532 rule.Build("lint", "lint")
Colin Cross014489c2020-06-02 20:09:13 -0700533
Colin Crossc0efd1d2020-07-03 11:56:24 -0700534 l.outputs = lintOutputs{
Cole Faustdf38f7a2023-03-02 16:43:15 -0800535 html: html,
536 text: text,
537 xml: xml,
538 referenceBaseline: referenceBaseline,
Colin Cross014489c2020-06-02 20:09:13 -0700539
Colin Cross08dca382020-07-21 20:31:17 -0700540 depSets: depSetsBuilder.Build(),
Colin Crossc0efd1d2020-07-03 11:56:24 -0700541 }
Colin Cross014489c2020-06-02 20:09:13 -0700542
Colin Crossc0efd1d2020-07-03 11:56:24 -0700543 if l.buildModuleReportZip {
Colin Cross08dca382020-07-21 20:31:17 -0700544 l.reports = BuildModuleLintReportZips(ctx, l.LintDepSets())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700545 }
546}
Colin Cross014489c2020-06-02 20:09:13 -0700547
Colin Cross08dca382020-07-21 20:31:17 -0700548func BuildModuleLintReportZips(ctx android.ModuleContext, depSets LintDepSets) android.Paths {
Colin Crossc85750b2022-04-21 12:50:51 -0700549 htmlList := android.SortedUniquePaths(depSets.HTML.ToList())
550 textList := android.SortedUniquePaths(depSets.Text.ToList())
551 xmlList := android.SortedUniquePaths(depSets.XML.ToList())
Colin Cross08dca382020-07-21 20:31:17 -0700552
553 if len(htmlList) == 0 && len(textList) == 0 && len(xmlList) == 0 {
554 return nil
555 }
556
557 htmlZip := android.PathForModuleOut(ctx, "lint-report-html.zip")
558 lintZip(ctx, htmlList, htmlZip)
559
560 textZip := android.PathForModuleOut(ctx, "lint-report-text.zip")
561 lintZip(ctx, textList, textZip)
562
563 xmlZip := android.PathForModuleOut(ctx, "lint-report-xml.zip")
564 lintZip(ctx, xmlList, xmlZip)
565
566 return android.Paths{htmlZip, textZip, xmlZip}
567}
568
Colin Cross014489c2020-06-02 20:09:13 -0700569type lintSingleton struct {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800570 htmlZip android.WritablePath
571 textZip android.WritablePath
572 xmlZip android.WritablePath
573 referenceBaselineZip android.WritablePath
Colin Cross014489c2020-06-02 20:09:13 -0700574}
575
576func (l *lintSingleton) GenerateBuildActions(ctx android.SingletonContext) {
577 l.generateLintReportZips(ctx)
578 l.copyLintDependencies(ctx)
579}
580
Pedro Loureiro18233a22021-06-08 18:11:21 +0000581func findModuleOrErr(ctx android.SingletonContext, moduleName string) android.Module {
582 var res android.Module
583 ctx.VisitAllModules(func(m android.Module) {
584 if ctx.ModuleName(m) == moduleName {
585 if res == nil {
586 res = m
587 } else {
588 ctx.Errorf("lint: multiple %s modules found: %s and %s", moduleName,
589 ctx.ModuleSubDir(m), ctx.ModuleSubDir(res))
590 }
591 }
592 })
593 return res
594}
595
Colin Cross014489c2020-06-02 20:09:13 -0700596func (l *lintSingleton) copyLintDependencies(ctx android.SingletonContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900597 if ctx.Config().AlwaysUsePrebuiltSdks() {
Colin Cross014489c2020-06-02 20:09:13 -0700598 return
599 }
600
Cole Faust69861aa2023-01-31 15:49:07 -0800601 for _, sdk := range android.SortedKeys(allLintDatabasefiles) {
602 files := allLintDatabasefiles[sdk]
603 apiVersionsDb := findModuleOrErr(ctx, files.apiVersionsModule)
604 if apiVersionsDb == nil {
605 if !ctx.Config().AllowMissingDependencies() {
606 ctx.Errorf("lint: missing module api_versions_public")
607 }
608 return
Colin Cross014489c2020-06-02 20:09:13 -0700609 }
Colin Cross014489c2020-06-02 20:09:13 -0700610
Cole Faust69861aa2023-01-31 15:49:07 -0800611 sdkAnnotations := findModuleOrErr(ctx, files.annotationsModule)
612 if sdkAnnotations == nil {
613 if !ctx.Config().AllowMissingDependencies() {
614 ctx.Errorf("lint: missing module sdk-annotations.zip")
615 }
616 return
Anton Hanssonea17a452022-05-09 09:42:17 +0000617 }
Cole Faust69861aa2023-01-31 15:49:07 -0800618
619 ctx.Build(pctx, android.BuildParams{
620 Rule: android.CpIfChanged,
621 Input: android.OutputFileForModule(ctx, sdkAnnotations, ""),
622 Output: copiedLintDatabaseFilesPath(ctx, files.annotationCopiedName),
623 })
624
625 ctx.Build(pctx, android.BuildParams{
626 Rule: android.CpIfChanged,
627 Input: android.OutputFileForModule(ctx, apiVersionsDb, ".api_versions.xml"),
628 Output: copiedLintDatabaseFilesPath(ctx, files.apiVersionsCopiedName),
629 })
Anton Hanssonea17a452022-05-09 09:42:17 +0000630 }
Colin Cross014489c2020-06-02 20:09:13 -0700631}
632
Cole Faust69861aa2023-01-31 15:49:07 -0800633func copiedLintDatabaseFilesPath(ctx android.PathContext, name string) android.WritablePath {
Pedro Loureiro18233a22021-06-08 18:11:21 +0000634 return android.PathForOutput(ctx, "lint", name)
Colin Cross014489c2020-06-02 20:09:13 -0700635}
636
637func (l *lintSingleton) generateLintReportZips(ctx android.SingletonContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700638 if ctx.Config().UnbundledBuild() {
639 return
640 }
641
Colin Cross014489c2020-06-02 20:09:13 -0700642 var outputs []*lintOutputs
643 var dirs []string
644 ctx.VisitAllModules(func(m android.Module) {
Jingwen Chencda22c92020-11-23 00:22:30 -0500645 if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
Colin Cross014489c2020-06-02 20:09:13 -0700646 return
647 }
648
Colin Cross56a83212020-09-15 18:30:11 -0700649 if apex, ok := m.(android.ApexModule); ok && apex.NotAvailableForPlatform() {
Colin Cross5a377182023-12-14 14:46:23 -0800650 apexInfo, _ := android.SingletonModuleProvider(ctx, m, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -0700651 if apexInfo.IsForPlatform() {
652 // There are stray platform variants of modules in apexes that are not available for
653 // the platform, and they sometimes can't be built. Don't depend on them.
654 return
655 }
Colin Cross014489c2020-06-02 20:09:13 -0700656 }
657
Colin Cross08dca382020-07-21 20:31:17 -0700658 if l, ok := m.(lintOutputsIntf); ok {
Colin Cross014489c2020-06-02 20:09:13 -0700659 outputs = append(outputs, l.lintOutputs())
660 }
661 })
662
663 dirs = android.SortedUniqueStrings(dirs)
664
665 zip := func(outputPath android.WritablePath, get func(*lintOutputs) android.Path) {
666 var paths android.Paths
667
668 for _, output := range outputs {
Colin Cross08dca382020-07-21 20:31:17 -0700669 if p := get(output); p != nil {
670 paths = append(paths, p)
671 }
Colin Cross014489c2020-06-02 20:09:13 -0700672 }
673
Colin Crossc0efd1d2020-07-03 11:56:24 -0700674 lintZip(ctx, paths, outputPath)
Colin Cross014489c2020-06-02 20:09:13 -0700675 }
676
677 l.htmlZip = android.PathForOutput(ctx, "lint-report-html.zip")
678 zip(l.htmlZip, func(l *lintOutputs) android.Path { return l.html })
679
680 l.textZip = android.PathForOutput(ctx, "lint-report-text.zip")
681 zip(l.textZip, func(l *lintOutputs) android.Path { return l.text })
682
683 l.xmlZip = android.PathForOutput(ctx, "lint-report-xml.zip")
684 zip(l.xmlZip, func(l *lintOutputs) android.Path { return l.xml })
685
Cole Faustdf38f7a2023-03-02 16:43:15 -0800686 l.referenceBaselineZip = android.PathForOutput(ctx, "lint-report-reference-baselines.zip")
687 zip(l.referenceBaselineZip, func(l *lintOutputs) android.Path { return l.referenceBaseline })
688
689 ctx.Phony("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross014489c2020-06-02 20:09:13 -0700690}
691
692func (l *lintSingleton) MakeVars(ctx android.MakeVarsContext) {
Colin Cross8a6ed372020-07-06 11:45:51 -0700693 if !ctx.Config().UnbundledBuild() {
Cole Faustdf38f7a2023-03-02 16:43:15 -0800694 ctx.DistForGoal("lint-check", l.htmlZip, l.textZip, l.xmlZip, l.referenceBaselineZip)
Colin Cross8a6ed372020-07-06 11:45:51 -0700695 }
Colin Cross014489c2020-06-02 20:09:13 -0700696}
697
698var _ android.SingletonMakeVarsProvider = (*lintSingleton)(nil)
699
700func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +0000701 android.RegisterParallelSingletonType("lint",
Colin Cross014489c2020-06-02 20:09:13 -0700702 func() android.Singleton { return &lintSingleton{} })
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700703
704 registerLintBuildComponents(android.InitRegistrationContext)
705}
706
707func registerLintBuildComponents(ctx android.RegistrationContext) {
708 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
709 ctx.TopDown("enforce_strict_updatability_linting", enforceStrictUpdatabilityLintingMutator).Parallel()
710 })
Colin Cross014489c2020-06-02 20:09:13 -0700711}
Colin Crossc0efd1d2020-07-03 11:56:24 -0700712
713func lintZip(ctx android.BuilderContext, paths android.Paths, outputPath android.WritablePath) {
714 paths = android.SortedUniquePaths(android.CopyOfPaths(paths))
715
716 sort.Slice(paths, func(i, j int) bool {
717 return paths[i].String() < paths[j].String()
718 })
719
Colin Crossf1a035e2020-11-16 17:32:30 -0800720 rule := android.NewRuleBuilder(pctx, ctx)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700721
Colin Crossf1a035e2020-11-16 17:32:30 -0800722 rule.Command().BuiltTool("soong_zip").
Colin Crossc0efd1d2020-07-03 11:56:24 -0700723 FlagWithOutput("-o ", outputPath).
724 FlagWithArg("-C ", android.PathForIntermediates(ctx).String()).
Colin Cross70c47412021-03-12 17:48:14 -0800725 FlagWithRspFileInputList("-r ", outputPath.ReplaceExtension(ctx, "rsp"), paths)
Colin Crossc0efd1d2020-07-03 11:56:24 -0700726
Colin Crossf1a035e2020-11-16 17:32:30 -0800727 rule.Build(outputPath.Base(), outputPath.Base())
Colin Crossc0efd1d2020-07-03 11:56:24 -0700728}
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700729
730// Enforce the strict updatability linting to all applicable transitive dependencies.
731func enforceStrictUpdatabilityLintingMutator(ctx android.TopDownMutatorContext) {
732 m := ctx.Module()
Spandan Das17854f52022-01-14 21:19:14 +0000733 if d, ok := m.(LintDepSetsIntf); ok && d.GetStrictUpdatabilityLinting() {
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700734 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
Spandan Das17854f52022-01-14 21:19:14 +0000735 if a, ok := d.(LintDepSetsIntf); ok {
736 a.SetStrictUpdatabilityLinting(true)
Jaewoong Jung476b9d62021-05-10 15:30:00 -0700737 }
738 })
739 }
740}