blob: 082cf88b3f45d3cd8ef5e7f23d98ea45a5636a8a [file] [log] [blame]
Dan Willemsena03cf6d2016-09-26 15:45:04 -07001// Copyright 2016 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 cc
16
17import (
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -070018 "fmt"
Chih-Hung Hsieh80783772021-10-11 16:46:56 -070019 "path/filepath"
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -080020 "regexp"
Dan Willemsena03cf6d2016-09-26 15:45:04 -070021 "strings"
22
23 "github.com/google/blueprint/proptools"
24
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -080025 "android/soong/android"
Dan Willemsena03cf6d2016-09-26 15:45:04 -070026 "android/soong/cc/config"
27)
28
29type TidyProperties struct {
30 // whether to run clang-tidy over C-like sources.
31 Tidy *bool
32
33 // Extra flags to pass to clang-tidy
34 Tidy_flags []string
35
36 // Extra checks to enable or disable in clang-tidy
37 Tidy_checks []string
Nikita Ioffe32c49862019-03-26 20:33:49 +000038
39 // Checks that should be treated as errors.
40 Tidy_checks_as_errors []string
Dan Willemsena03cf6d2016-09-26 15:45:04 -070041}
42
43type tidyFeature struct {
44 Properties TidyProperties
45}
46
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -080047var quotedFlagRegexp, _ = regexp.Compile(`^-?-[^=]+=('|").*('|")$`)
48
49// When passing flag -name=value, if user add quotes around 'value',
50// the quotation marks will be preserved by NinjaAndShellEscapeList
51// and the 'value' string with quotes won't work like the intended value.
52// So here we report an error if -*='*' is found.
53func checkNinjaAndShellEscapeList(ctx ModuleContext, prop string, slice []string) []string {
54 for _, s := range slice {
55 if quotedFlagRegexp.MatchString(s) {
56 ctx.PropertyErrorf(prop, "Extra quotes in: %s", s)
57 }
58 }
59 return proptools.NinjaAndShellEscapeList(slice)
60}
61
Dan Willemsena03cf6d2016-09-26 15:45:04 -070062func (tidy *tidyFeature) props() []interface{} {
63 return []interface{}{&tidy.Properties}
64}
65
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -070066// Set this const to true when all -warnings-as-errors in tidy_flags
67// are replaced with tidy_checks_as_errors.
68// Then, that old style usage will be obsolete and an error.
Chih-Hung Hsieh9f876e92022-06-12 20:28:00 -070069const NoWarningsAsErrorsInTidyFlags = true
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -070070
Dan Willemsena03cf6d2016-09-26 15:45:04 -070071func (tidy *tidyFeature) flags(ctx ModuleContext, flags Flags) Flags {
Colin Cross379d2cb2016-12-05 17:11:06 -080072 CheckBadTidyFlags(ctx, "tidy_flags", tidy.Properties.Tidy_flags)
73 CheckBadTidyChecks(ctx, "tidy_checks", tidy.Properties.Tidy_checks)
74
Dan Willemsena03cf6d2016-09-26 15:45:04 -070075 // Check if tidy is explicitly disabled for this module
76 if tidy.Properties.Tidy != nil && !*tidy.Properties.Tidy {
77 return flags
78 }
Chih-Hung Hsieh1a467532022-09-01 17:14:22 -070079 // Some projects like external/* and vendor/* have clang-tidy disabled by default.
80 // They can enable clang-tidy explicitly with the "tidy:true" property.
81 if config.NoClangTidyForDir(ctx.ModuleDir()) && !proptools.Bool(tidy.Properties.Tidy) {
82 return flags
83 }
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080084 // If not explicitly disabled, set flags.Tidy to generate .tidy rules.
85 // Note that libraries and binaries will depend on .tidy files ONLY if
86 // the global WITH_TIDY or module 'tidy' property is true.
Dan Willemsena03cf6d2016-09-26 15:45:04 -070087 flags.Tidy = true
88
Chih-Hung Hsieh104f51f2022-04-20 15:48:41 -070089 // If explicitly enabled, by global WITH_TIDY or local tidy:true property,
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080090 // set flags.NeedTidyFiles to make this module depend on .tidy files.
Chih-Hung Hsieh104f51f2022-04-20 15:48:41 -070091 // Note that locally set tidy:true is ignored if ALLOW_LOCAL_TIDY_TRUE is not set to true.
92 if ctx.Config().IsEnvTrue("WITH_TIDY") || (ctx.Config().IsEnvTrue("ALLOW_LOCAL_TIDY_TRUE") && Bool(tidy.Properties.Tidy)) {
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080093 flags.NeedTidyFiles = true
94 }
95
Chih-Hung Hsieh9e5d8a62018-09-21 15:12:44 -070096 // Add global WITH_TIDY_FLAGS and local tidy_flags.
97 withTidyFlags := ctx.Config().Getenv("WITH_TIDY_FLAGS")
98 if len(withTidyFlags) > 0 {
99 flags.TidyFlags = append(flags.TidyFlags, withTidyFlags)
100 }
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800101 esc := checkNinjaAndShellEscapeList
102 flags.TidyFlags = append(flags.TidyFlags, esc(ctx, "tidy_flags", tidy.Properties.Tidy_flags)...)
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800103 // If TidyFlags does not contain -header-filter, add default header filter.
104 // Find the substring because the flag could also appear as --header-filter=...
105 // and with or without single or double quotes.
106 if !android.SubstringInList(flags.TidyFlags, "-header-filter=") {
107 defaultDirs := ctx.Config().Getenv("DEFAULT_TIDY_HEADER_DIRS")
108 headerFilter := "-header-filter="
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700109 // Default header filter should include only the module directory,
110 // not the out/soong/.../ModuleDir/...
111 // Otherwise, there will be too many warnings from generated files in out/...
112 // If a module wants to see warnings in the generated source files,
113 // it should specify its own -header-filter flag.
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800114 if defaultDirs == "" {
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700115 headerFilter += "^" + ctx.ModuleDir() + "/"
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800116 } else {
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700117 headerFilter += "\"(^" + ctx.ModuleDir() + "/|" + defaultDirs + ")\""
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800118 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700119 flags.TidyFlags = append(flags.TidyFlags, headerFilter)
120 }
Chih-Hung Hsieh63d59eb2022-02-04 17:42:02 -0800121 // Work around RBE bug in parsing clang-tidy flags, replace "--flag" with "-flag".
122 // Some C/C++ modules added local tidy flags like --header-filter= and --extra-arg-before=.
123 doubleDash := regexp.MustCompile("^('?)--(.*)$")
124 for i, s := range flags.TidyFlags {
125 flags.TidyFlags[i] = doubleDash.ReplaceAllString(s, "$1-$2")
126 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700127
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800128 // If clang-tidy is not enabled globally, add the -quiet flag.
129 if !ctx.Config().ClangTidy() {
130 flags.TidyFlags = append(flags.TidyFlags, "-quiet")
Chih-Hung Hsieh669cb912018-01-04 01:41:16 -0800131 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics")
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800132 }
133
George Burgess IV030ccee2018-05-14 16:30:46 -0700134 extraArgFlags := []string{
135 // We might be using the static analyzer through clang tidy.
136 // https://bugs.llvm.org/show_bug.cgi?id=32914
137 "-D__clang_analyzer__",
138
139 // A recent change in clang-tidy (r328258) enabled destructor inlining, which
140 // appears to cause a number of false positives. Until that's resolved, this turns
141 // off the effects of r328258.
142 // https://bugs.llvm.org/show_bug.cgi?id=37459
143 "-Xclang", "-analyzer-config", "-Xclang", "c++-temp-dtor-inlining=false",
144 }
145
146 for _, f := range extraArgFlags {
147 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f)
148 }
George Burgess IV561a3fe2017-05-03 18:13:08 -0700149
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700150 tidyChecks := "-checks="
Colin Cross6510f912017-11-29 00:27:14 -0800151 if checks := ctx.Config().TidyChecks(); len(checks) > 0 {
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700152 tidyChecks += checks
153 } else {
154 tidyChecks += config.TidyChecksForDir(ctx.ModuleDir())
155 }
156 if len(tidy.Properties.Tidy_checks) > 0 {
Chih-Hung Hsieh80e3e032022-06-02 19:55:15 -0700157 // If Tidy_checks contains "-*", ignore all checks before "-*".
158 localChecks := tidy.Properties.Tidy_checks
159 ignoreGlobalChecks := false
160 for n, check := range tidy.Properties.Tidy_checks {
161 if check == "-*" {
162 ignoreGlobalChecks = true
163 localChecks = tidy.Properties.Tidy_checks[n:]
164 }
165 }
166 if ignoreGlobalChecks {
167 tidyChecks = "-checks=" + strings.Join(esc(ctx, "tidy_checks",
168 config.ClangRewriteTidyChecks(localChecks)), ",")
169 } else {
170 tidyChecks = tidyChecks + "," + strings.Join(esc(ctx, "tidy_checks",
171 config.ClangRewriteTidyChecks(localChecks)), ",")
172 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700173 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700174 tidyChecks = tidyChecks + config.TidyGlobalNoChecks()
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800175 if ctx.Windows() {
176 // https://b.corp.google.com/issues/120614316
177 // mingw32 has cert-dcl16-c warning in NO_ERROR,
178 // which is used in many Android files.
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700179 tidyChecks += ",-cert-dcl16-c"
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800180 }
Chih-Hung Hsieh43b920e2022-06-09 17:58:41 -0700181
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700182 flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
183
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700184 // Embedding -warnings-as-errors in tidy_flags is error-prone.
185 // It should be replaced with the tidy_checks_as_errors list.
186 for i, s := range flags.TidyFlags {
187 if strings.Contains(s, "-warnings-as-errors=") {
188 if NoWarningsAsErrorsInTidyFlags {
189 ctx.PropertyErrorf("tidy_flags", "should not contain "+s+"; use tidy_checks_as_errors instead.")
190 } else {
191 fmt.Printf("%s: warning: module %s's tidy_flags should not contain %s, which is replaced with -warnings-as-errors=-*; use tidy_checks_as_errors for your own as-error warnings instead.\n",
192 ctx.BlueprintsFile(), ctx.ModuleName(), s)
193 flags.TidyFlags[i] = "-warnings-as-errors=-*"
Yasin Kilicdere5a8ce132022-06-10 12:18:07 +0000194 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700195 break // there is at most one -warnings-as-errors
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -0800196 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700197 }
198 // Default clang-tidy flags does not contain -warning-as-errors.
199 // If a module has tidy_checks_as_errors, add the list to -warnings-as-errors
200 // and then append the TidyGlobalNoErrorChecks.
201 if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
202 tidyChecksAsErrors := "-warnings-as-errors=" +
203 strings.Join(esc(ctx, "tidy_checks_as_errors", tidy.Properties.Tidy_checks_as_errors), ",") +
204 config.TidyGlobalNoErrorChecks()
Nikita Ioffe32c49862019-03-26 20:33:49 +0000205 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors)
206 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700207 return flags
208}
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700209
210func init() {
211 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton)
212}
213
214// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files.
215func TidyPhonySingleton() android.Singleton {
216 return &tidyPhonySingleton{}
217}
218
219type tidyPhonySingleton struct{}
220
221// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup.
222func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module,
223 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) {
224 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths
225 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths
226 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths
227 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths
228
229 // (1) Collect all obj/tidy files into OS-specific groups.
230 ctx.VisitAllModuleVariants(module, func(variant android.Module) {
231 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) {
232 return
233 }
234 if m, ok := variant.(*Module); ok {
235 osName := variant.Target().Os.Name
236 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups)
237 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups)
238 }
239 })
240
241 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets.
242 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj")
243 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy")
244 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj")
245 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy")
246
247 tidyTargetGroups := make(map[string]android.Path)
248 objTargetGroups := make(map[string]android.Path)
249 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups)
250 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups)
251 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups)
252 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups)
253
254 moduleDir := ctx.ModuleDir(module)
255 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup)
256 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup)
257}
258
259func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) {
260 // For tidy-* directory phony targets, there are different variant groups.
261 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths
262 // of all phony targets to be included into direct dependents of tidy-D_G.
263 tidyModulesInDirGroup := make(map[string]map[string]android.Paths)
264 // Also for obj-* directory phony targets.
265 objModulesInDirGroup := make(map[string]map[string]android.Paths)
266
267 // Collect tidy/obj targets from the 'final' modules.
268 ctx.VisitAllModules(func(module android.Module) {
269 if module == ctx.FinalModule(module) {
270 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup)
271 }
272 })
273
274 suffix := ""
275 if ctx.Config().KatiEnabled() {
276 suffix = "-soong"
277 }
278 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup)
279 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup)
280}
281
282// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy,
283func objTidyModuleGroupName(module android.Module, group string, suffix string) string {
284 if group == "" {
285 return module.Name() + "-" + suffix
286 }
287 return module.Name() + "_" + group + "-" + suffix
288}
289
290// Generate obj-* or tidy-* phony targets.
291func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) {
292 // For each variant group, create a <prefix>-<directory>_group target that
293 // depends on all subdirectories and modules in the directory.
294 for group, modulesInDir := range objTidyModulesInDirGroup {
295 groupSuffix := ""
296 if group != "" {
297 groupSuffix = "_" + group
298 }
299 mmTarget := func(dir string) string {
300 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix
301 }
302 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget)
303 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs.
304 var topDirPaths android.Paths
305 for _, dir := range topDirs {
306 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir)))
307 }
308 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...)
309 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir]
310 for _, dir := range dirs {
311 if dir != "." && dir != "" {
312 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
313 }
314 }
315 }
316}
317
318// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir].
319func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) {
320 for group, phonyPath := range targetGroups {
321 if _, found := modulesInDirGroup[group]; !found {
322 modulesInDirGroup[group] = make(map[string]android.Paths)
323 }
324 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath)
325 }
326}
327
328// Add given files to the OS group and subset group.
329func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) {
330 if len(files) > 0 {
331 subsetName := osName + "_subset"
332 allGroups[osName] = append(allGroups[osName], files...)
333 // Now include only the first variant in the subsetGroups.
334 // If clang and clang-tidy get faster, we might include more variants.
335 if _, found := subsetGroups[subsetName]; !found {
336 subsetGroups[subsetName] = files
337 }
338 }
339}
340
341// Add an all-OS group, with groupName, to include all os-specific phony targets.
342func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) {
343 if len(phonyTargetGroups) > 0 {
344 var targets android.Paths
345 for group, _ := range phonyTargetGroups {
346 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName)))
347 }
348 phonyTargetGroups[groupName] = targets
349 }
350}
351
352// Create one phony targets for each group and add them to the targetGroups.
353func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) {
354 for group, files := range fileGroups {
355 groupName := objTidyModuleGroupName(module, group, objTidyName)
356 ctx.Phony(groupName, files...)
357 targetGroups[group] = android.PathForPhony(ctx, groupName)
358 }
359}