blob: 94b10c2d6ca4aae9669b01fa8c3cb5a7ee17602b [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.
69const NoWarningsAsErrorsInTidyFlags = false
70
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 }
79
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080080 // If not explicitly disabled, set flags.Tidy to generate .tidy rules.
81 // Note that libraries and binaries will depend on .tidy files ONLY if
82 // the global WITH_TIDY or module 'tidy' property is true.
Dan Willemsena03cf6d2016-09-26 15:45:04 -070083 flags.Tidy = true
84
Chih-Hung Hsieh104f51f2022-04-20 15:48:41 -070085 // If explicitly enabled, by global WITH_TIDY or local tidy:true property,
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080086 // set flags.NeedTidyFiles to make this module depend on .tidy files.
Chih-Hung Hsieh104f51f2022-04-20 15:48:41 -070087 // Note that locally set tidy:true is ignored if ALLOW_LOCAL_TIDY_TRUE is not set to true.
88 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 -080089 flags.NeedTidyFiles = true
90 }
91
Chih-Hung Hsieh9e5d8a62018-09-21 15:12:44 -070092 // Add global WITH_TIDY_FLAGS and local tidy_flags.
93 withTidyFlags := ctx.Config().Getenv("WITH_TIDY_FLAGS")
94 if len(withTidyFlags) > 0 {
95 flags.TidyFlags = append(flags.TidyFlags, withTidyFlags)
96 }
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -080097 esc := checkNinjaAndShellEscapeList
98 flags.TidyFlags = append(flags.TidyFlags, esc(ctx, "tidy_flags", tidy.Properties.Tidy_flags)...)
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -080099 // If TidyFlags does not contain -header-filter, add default header filter.
100 // Find the substring because the flag could also appear as --header-filter=...
101 // and with or without single or double quotes.
102 if !android.SubstringInList(flags.TidyFlags, "-header-filter=") {
103 defaultDirs := ctx.Config().Getenv("DEFAULT_TIDY_HEADER_DIRS")
104 headerFilter := "-header-filter="
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700105 // Default header filter should include only the module directory,
106 // not the out/soong/.../ModuleDir/...
107 // Otherwise, there will be too many warnings from generated files in out/...
108 // If a module wants to see warnings in the generated source files,
109 // it should specify its own -header-filter flag.
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800110 if defaultDirs == "" {
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700111 headerFilter += "^" + ctx.ModuleDir() + "/"
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800112 } else {
Chih-Hung Hsieh5fe637a2022-05-09 11:02:25 -0700113 headerFilter += "\"(^" + ctx.ModuleDir() + "/|" + defaultDirs + ")\""
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -0800114 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700115 flags.TidyFlags = append(flags.TidyFlags, headerFilter)
116 }
Chih-Hung Hsieh63d59eb2022-02-04 17:42:02 -0800117 // Work around RBE bug in parsing clang-tidy flags, replace "--flag" with "-flag".
118 // Some C/C++ modules added local tidy flags like --header-filter= and --extra-arg-before=.
119 doubleDash := regexp.MustCompile("^('?)--(.*)$")
120 for i, s := range flags.TidyFlags {
121 flags.TidyFlags[i] = doubleDash.ReplaceAllString(s, "$1-$2")
122 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700123
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800124 // If clang-tidy is not enabled globally, add the -quiet flag.
125 if !ctx.Config().ClangTidy() {
126 flags.TidyFlags = append(flags.TidyFlags, "-quiet")
Chih-Hung Hsieh669cb912018-01-04 01:41:16 -0800127 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics")
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800128 }
129
George Burgess IV030ccee2018-05-14 16:30:46 -0700130 extraArgFlags := []string{
131 // We might be using the static analyzer through clang tidy.
132 // https://bugs.llvm.org/show_bug.cgi?id=32914
133 "-D__clang_analyzer__",
134
135 // A recent change in clang-tidy (r328258) enabled destructor inlining, which
136 // appears to cause a number of false positives. Until that's resolved, this turns
137 // off the effects of r328258.
138 // https://bugs.llvm.org/show_bug.cgi?id=37459
139 "-Xclang", "-analyzer-config", "-Xclang", "c++-temp-dtor-inlining=false",
140 }
141
142 for _, f := range extraArgFlags {
143 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f)
144 }
George Burgess IV561a3fe2017-05-03 18:13:08 -0700145
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700146 tidyChecks := "-checks="
Colin Cross6510f912017-11-29 00:27:14 -0800147 if checks := ctx.Config().TidyChecks(); len(checks) > 0 {
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700148 tidyChecks += checks
149 } else {
150 tidyChecks += config.TidyChecksForDir(ctx.ModuleDir())
151 }
152 if len(tidy.Properties.Tidy_checks) > 0 {
Chih-Hung Hsieh80e3e032022-06-02 19:55:15 -0700153 // If Tidy_checks contains "-*", ignore all checks before "-*".
154 localChecks := tidy.Properties.Tidy_checks
155 ignoreGlobalChecks := false
156 for n, check := range tidy.Properties.Tidy_checks {
157 if check == "-*" {
158 ignoreGlobalChecks = true
159 localChecks = tidy.Properties.Tidy_checks[n:]
160 }
161 }
162 if ignoreGlobalChecks {
163 tidyChecks = "-checks=" + strings.Join(esc(ctx, "tidy_checks",
164 config.ClangRewriteTidyChecks(localChecks)), ",")
165 } else {
166 tidyChecks = tidyChecks + "," + strings.Join(esc(ctx, "tidy_checks",
167 config.ClangRewriteTidyChecks(localChecks)), ",")
168 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700169 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700170 tidyChecks = tidyChecks + config.TidyGlobalNoChecks()
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800171 if ctx.Windows() {
172 // https://b.corp.google.com/issues/120614316
173 // mingw32 has cert-dcl16-c warning in NO_ERROR,
174 // which is used in many Android files.
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700175 tidyChecks += ",-cert-dcl16-c"
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800176 }
Chih-Hung Hsieh43b920e2022-06-09 17:58:41 -0700177
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700178 flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
179
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700180 // Embedding -warnings-as-errors in tidy_flags is error-prone.
181 // It should be replaced with the tidy_checks_as_errors list.
182 for i, s := range flags.TidyFlags {
183 if strings.Contains(s, "-warnings-as-errors=") {
184 if NoWarningsAsErrorsInTidyFlags {
185 ctx.PropertyErrorf("tidy_flags", "should not contain "+s+"; use tidy_checks_as_errors instead.")
186 } else {
187 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",
188 ctx.BlueprintsFile(), ctx.ModuleName(), s)
189 flags.TidyFlags[i] = "-warnings-as-errors=-*"
Yasin Kilicdere5a8ce132022-06-10 12:18:07 +0000190 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700191 break // there is at most one -warnings-as-errors
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -0800192 }
Chih-Hung Hsieh794b81d2022-06-11 18:10:58 -0700193 }
194 // Default clang-tidy flags does not contain -warning-as-errors.
195 // If a module has tidy_checks_as_errors, add the list to -warnings-as-errors
196 // and then append the TidyGlobalNoErrorChecks.
197 if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
198 tidyChecksAsErrors := "-warnings-as-errors=" +
199 strings.Join(esc(ctx, "tidy_checks_as_errors", tidy.Properties.Tidy_checks_as_errors), ",") +
200 config.TidyGlobalNoErrorChecks()
Nikita Ioffe32c49862019-03-26 20:33:49 +0000201 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors)
202 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700203 return flags
204}
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700205
206func init() {
207 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton)
208}
209
210// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files.
211func TidyPhonySingleton() android.Singleton {
212 return &tidyPhonySingleton{}
213}
214
215type tidyPhonySingleton struct{}
216
217// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup.
218func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module,
219 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) {
220 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths
221 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths
222 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths
223 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths
224
225 // (1) Collect all obj/tidy files into OS-specific groups.
226 ctx.VisitAllModuleVariants(module, func(variant android.Module) {
227 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) {
228 return
229 }
230 if m, ok := variant.(*Module); ok {
231 osName := variant.Target().Os.Name
232 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups)
233 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups)
234 }
235 })
236
237 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets.
238 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj")
239 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy")
240 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj")
241 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy")
242
243 tidyTargetGroups := make(map[string]android.Path)
244 objTargetGroups := make(map[string]android.Path)
245 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups)
246 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups)
247 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups)
248 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups)
249
250 moduleDir := ctx.ModuleDir(module)
251 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup)
252 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup)
253}
254
255func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) {
256 // For tidy-* directory phony targets, there are different variant groups.
257 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths
258 // of all phony targets to be included into direct dependents of tidy-D_G.
259 tidyModulesInDirGroup := make(map[string]map[string]android.Paths)
260 // Also for obj-* directory phony targets.
261 objModulesInDirGroup := make(map[string]map[string]android.Paths)
262
263 // Collect tidy/obj targets from the 'final' modules.
264 ctx.VisitAllModules(func(module android.Module) {
265 if module == ctx.FinalModule(module) {
266 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup)
267 }
268 })
269
270 suffix := ""
271 if ctx.Config().KatiEnabled() {
272 suffix = "-soong"
273 }
274 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup)
275 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup)
276}
277
278// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy,
279func objTidyModuleGroupName(module android.Module, group string, suffix string) string {
280 if group == "" {
281 return module.Name() + "-" + suffix
282 }
283 return module.Name() + "_" + group + "-" + suffix
284}
285
286// Generate obj-* or tidy-* phony targets.
287func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) {
288 // For each variant group, create a <prefix>-<directory>_group target that
289 // depends on all subdirectories and modules in the directory.
290 for group, modulesInDir := range objTidyModulesInDirGroup {
291 groupSuffix := ""
292 if group != "" {
293 groupSuffix = "_" + group
294 }
295 mmTarget := func(dir string) string {
296 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix
297 }
298 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget)
299 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs.
300 var topDirPaths android.Paths
301 for _, dir := range topDirs {
302 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir)))
303 }
304 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...)
305 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir]
306 for _, dir := range dirs {
307 if dir != "." && dir != "" {
308 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
309 }
310 }
311 }
312}
313
314// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir].
315func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) {
316 for group, phonyPath := range targetGroups {
317 if _, found := modulesInDirGroup[group]; !found {
318 modulesInDirGroup[group] = make(map[string]android.Paths)
319 }
320 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath)
321 }
322}
323
324// Add given files to the OS group and subset group.
325func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) {
326 if len(files) > 0 {
327 subsetName := osName + "_subset"
328 allGroups[osName] = append(allGroups[osName], files...)
329 // Now include only the first variant in the subsetGroups.
330 // If clang and clang-tidy get faster, we might include more variants.
331 if _, found := subsetGroups[subsetName]; !found {
332 subsetGroups[subsetName] = files
333 }
334 }
335}
336
337// Add an all-OS group, with groupName, to include all os-specific phony targets.
338func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) {
339 if len(phonyTargetGroups) > 0 {
340 var targets android.Paths
341 for group, _ := range phonyTargetGroups {
342 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName)))
343 }
344 phonyTargetGroups[groupName] = targets
345 }
346}
347
348// Create one phony targets for each group and add them to the targetGroups.
349func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) {
350 for group, files := range fileGroups {
351 groupName := objTidyModuleGroupName(module, group, objTidyName)
352 ctx.Phony(groupName, files...)
353 targetGroups[group] = android.PathForPhony(ctx, groupName)
354 }
355}