blob: 97418fe17d1afdb79facd13a2cccab4a25c3b880 [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 Hsieh80783772021-10-11 16:46:56 -070018 "path/filepath"
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -080019 "regexp"
Dan Willemsena03cf6d2016-09-26 15:45:04 -070020 "strings"
21
22 "github.com/google/blueprint/proptools"
23
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -080024 "android/soong/android"
Dan Willemsena03cf6d2016-09-26 15:45:04 -070025 "android/soong/cc/config"
26)
27
28type TidyProperties struct {
29 // whether to run clang-tidy over C-like sources.
30 Tidy *bool
31
32 // Extra flags to pass to clang-tidy
33 Tidy_flags []string
34
35 // Extra checks to enable or disable in clang-tidy
36 Tidy_checks []string
Nikita Ioffe32c49862019-03-26 20:33:49 +000037
38 // Checks that should be treated as errors.
39 Tidy_checks_as_errors []string
Dan Willemsena03cf6d2016-09-26 15:45:04 -070040}
41
42type tidyFeature struct {
43 Properties TidyProperties
44}
45
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -080046var quotedFlagRegexp, _ = regexp.Compile(`^-?-[^=]+=('|").*('|")$`)
47
48// When passing flag -name=value, if user add quotes around 'value',
49// the quotation marks will be preserved by NinjaAndShellEscapeList
50// and the 'value' string with quotes won't work like the intended value.
51// So here we report an error if -*='*' is found.
52func checkNinjaAndShellEscapeList(ctx ModuleContext, prop string, slice []string) []string {
53 for _, s := range slice {
54 if quotedFlagRegexp.MatchString(s) {
55 ctx.PropertyErrorf(prop, "Extra quotes in: %s", s)
56 }
57 }
58 return proptools.NinjaAndShellEscapeList(slice)
59}
60
Dan Willemsena03cf6d2016-09-26 15:45:04 -070061func (tidy *tidyFeature) props() []interface{} {
62 return []interface{}{&tidy.Properties}
63}
64
Dan Willemsena03cf6d2016-09-26 15:45:04 -070065func (tidy *tidyFeature) flags(ctx ModuleContext, flags Flags) Flags {
Colin Cross379d2cb2016-12-05 17:11:06 -080066 CheckBadTidyFlags(ctx, "tidy_flags", tidy.Properties.Tidy_flags)
67 CheckBadTidyChecks(ctx, "tidy_checks", tidy.Properties.Tidy_checks)
68
Dan Willemsena03cf6d2016-09-26 15:45:04 -070069 // Check if tidy is explicitly disabled for this module
70 if tidy.Properties.Tidy != nil && !*tidy.Properties.Tidy {
71 return flags
72 }
73
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080074 // If not explicitly disabled, set flags.Tidy to generate .tidy rules.
75 // Note that libraries and binaries will depend on .tidy files ONLY if
76 // the global WITH_TIDY or module 'tidy' property is true.
Dan Willemsena03cf6d2016-09-26 15:45:04 -070077 flags.Tidy = true
78
Chih-Hung Hsieh7540a782022-01-08 19:56:09 -080079 // If explicitly enabled, by global default or local tidy property,
80 // set flags.NeedTidyFiles to make this module depend on .tidy files.
81 if ctx.Config().ClangTidy() || Bool(tidy.Properties.Tidy) {
82 flags.NeedTidyFiles = true
83 }
84
Chih-Hung Hsieh9e5d8a62018-09-21 15:12:44 -070085 // Add global WITH_TIDY_FLAGS and local tidy_flags.
86 withTidyFlags := ctx.Config().Getenv("WITH_TIDY_FLAGS")
87 if len(withTidyFlags) > 0 {
88 flags.TidyFlags = append(flags.TidyFlags, withTidyFlags)
89 }
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -080090 esc := checkNinjaAndShellEscapeList
91 flags.TidyFlags = append(flags.TidyFlags, esc(ctx, "tidy_flags", tidy.Properties.Tidy_flags)...)
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -080092 // If TidyFlags does not contain -header-filter, add default header filter.
93 // Find the substring because the flag could also appear as --header-filter=...
94 // and with or without single or double quotes.
95 if !android.SubstringInList(flags.TidyFlags, "-header-filter=") {
96 defaultDirs := ctx.Config().Getenv("DEFAULT_TIDY_HEADER_DIRS")
97 headerFilter := "-header-filter="
98 if defaultDirs == "" {
99 headerFilter += ctx.ModuleDir() + "/"
100 } else {
101 headerFilter += "\"(" + ctx.ModuleDir() + "/|" + defaultDirs + ")\""
102 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700103 flags.TidyFlags = append(flags.TidyFlags, headerFilter)
104 }
105
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800106 // If clang-tidy is not enabled globally, add the -quiet flag.
107 if !ctx.Config().ClangTidy() {
108 flags.TidyFlags = append(flags.TidyFlags, "-quiet")
Chih-Hung Hsieh669cb912018-01-04 01:41:16 -0800109 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics")
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800110 }
111
George Burgess IV030ccee2018-05-14 16:30:46 -0700112 extraArgFlags := []string{
113 // We might be using the static analyzer through clang tidy.
114 // https://bugs.llvm.org/show_bug.cgi?id=32914
115 "-D__clang_analyzer__",
116
117 // A recent change in clang-tidy (r328258) enabled destructor inlining, which
118 // appears to cause a number of false positives. Until that's resolved, this turns
119 // off the effects of r328258.
120 // https://bugs.llvm.org/show_bug.cgi?id=37459
121 "-Xclang", "-analyzer-config", "-Xclang", "c++-temp-dtor-inlining=false",
122 }
123
124 for _, f := range extraArgFlags {
125 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f)
126 }
George Burgess IV561a3fe2017-05-03 18:13:08 -0700127
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700128 tidyChecks := "-checks="
Colin Cross6510f912017-11-29 00:27:14 -0800129 if checks := ctx.Config().TidyChecks(); len(checks) > 0 {
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700130 tidyChecks += checks
131 } else {
132 tidyChecks += config.TidyChecksForDir(ctx.ModuleDir())
133 }
134 if len(tidy.Properties.Tidy_checks) > 0 {
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800135 tidyChecks = tidyChecks + "," + strings.Join(esc(ctx, "tidy_checks",
Dan Albertd12afec2020-08-14 16:53:21 -0700136 config.ClangRewriteTidyChecks(tidy.Properties.Tidy_checks)), ",")
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700137 }
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800138 if ctx.Windows() {
139 // https://b.corp.google.com/issues/120614316
140 // mingw32 has cert-dcl16-c warning in NO_ERROR,
141 // which is used in many Android files.
142 tidyChecks = tidyChecks + ",-cert-dcl16-c"
143 }
Chih-Hung Hsieh3d3df822020-04-08 10:42:16 -0700144 // https://b.corp.google.com/issues/153464409
145 // many local projects enable cert-* checks, which
146 // trigger bugprone-reserved-identifier.
Yabin Cui70ba0e22020-04-09 16:28:24 -0700147 tidyChecks = tidyChecks + ",-bugprone-reserved-identifier*,-cert-dcl51-cpp,-cert-dcl37-c"
Yabin Cui8ec05ff2020-04-10 13:36:41 -0700148 // http://b/153757728
149 tidyChecks = tidyChecks + ",-readability-qualified-auto"
150 // http://b/155034563
151 tidyChecks = tidyChecks + ",-bugprone-signed-char-misuse"
152 // http://b/155034972
153 tidyChecks = tidyChecks + ",-bugprone-branch-clone"
Yabin Cui10bf3b82021-08-10 15:42:10 +0000154 // http://b/193716442
155 tidyChecks = tidyChecks + ",-bugprone-implicit-widening-of-multiplication-result"
Yi Konge8273292021-08-31 14:04:18 +0800156 // Too many existing functions trigger this rule, and fixing it requires large code
157 // refactoring. The cost of maintaining this tidy rule outweighs the benefit it brings.
158 tidyChecks = tidyChecks + ",-bugprone-easily-swappable-parameters"
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700159 flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
160
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -0800161 if ctx.Config().IsEnvTrue("WITH_TIDY") {
162 // WITH_TIDY=1 enables clang-tidy globally. There could be many unexpected
163 // warnings from new checks and many local tidy_checks_as_errors and
164 // -warnings-as-errors can break a global build.
165 // So allow all clang-tidy warnings.
166 inserted := false
167 for i, s := range flags.TidyFlags {
168 if strings.Contains(s, "-warnings-as-errors=") {
169 // clang-tidy accepts only one -warnings-as-errors
170 // replace the old one
171 re := regexp.MustCompile(`'?-?-warnings-as-errors=[^ ]* *`)
172 newFlag := re.ReplaceAllString(s, "")
173 if newFlag == "" {
174 flags.TidyFlags[i] = "-warnings-as-errors=-*"
175 } else {
176 flags.TidyFlags[i] = newFlag + " -warnings-as-errors=-*"
177 }
178 inserted = true
179 break
180 }
181 }
182 if !inserted {
183 flags.TidyFlags = append(flags.TidyFlags, "-warnings-as-errors=-*")
184 }
185 } else if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800186 tidyChecksAsErrors := "-warnings-as-errors=" + strings.Join(esc(ctx, "tidy_checks_as_errors", tidy.Properties.Tidy_checks_as_errors), ",")
Nikita Ioffe32c49862019-03-26 20:33:49 +0000187 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors)
188 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700189 return flags
190}
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700191
192func init() {
193 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton)
194}
195
196// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files.
197func TidyPhonySingleton() android.Singleton {
198 return &tidyPhonySingleton{}
199}
200
201type tidyPhonySingleton struct{}
202
203// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup.
204func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module,
205 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) {
206 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths
207 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths
208 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths
209 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths
210
211 // (1) Collect all obj/tidy files into OS-specific groups.
212 ctx.VisitAllModuleVariants(module, func(variant android.Module) {
213 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) {
214 return
215 }
216 if m, ok := variant.(*Module); ok {
217 osName := variant.Target().Os.Name
218 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups)
219 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups)
220 }
221 })
222
223 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets.
224 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj")
225 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy")
226 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj")
227 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy")
228
229 tidyTargetGroups := make(map[string]android.Path)
230 objTargetGroups := make(map[string]android.Path)
231 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups)
232 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups)
233 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups)
234 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups)
235
236 moduleDir := ctx.ModuleDir(module)
237 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup)
238 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup)
239}
240
241func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) {
242 // For tidy-* directory phony targets, there are different variant groups.
243 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths
244 // of all phony targets to be included into direct dependents of tidy-D_G.
245 tidyModulesInDirGroup := make(map[string]map[string]android.Paths)
246 // Also for obj-* directory phony targets.
247 objModulesInDirGroup := make(map[string]map[string]android.Paths)
248
249 // Collect tidy/obj targets from the 'final' modules.
250 ctx.VisitAllModules(func(module android.Module) {
251 if module == ctx.FinalModule(module) {
252 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup)
253 }
254 })
255
256 suffix := ""
257 if ctx.Config().KatiEnabled() {
258 suffix = "-soong"
259 }
260 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup)
261 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup)
262}
263
264// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy,
265func objTidyModuleGroupName(module android.Module, group string, suffix string) string {
266 if group == "" {
267 return module.Name() + "-" + suffix
268 }
269 return module.Name() + "_" + group + "-" + suffix
270}
271
272// Generate obj-* or tidy-* phony targets.
273func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) {
274 // For each variant group, create a <prefix>-<directory>_group target that
275 // depends on all subdirectories and modules in the directory.
276 for group, modulesInDir := range objTidyModulesInDirGroup {
277 groupSuffix := ""
278 if group != "" {
279 groupSuffix = "_" + group
280 }
281 mmTarget := func(dir string) string {
282 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix
283 }
284 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget)
285 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs.
286 var topDirPaths android.Paths
287 for _, dir := range topDirs {
288 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir)))
289 }
290 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...)
291 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir]
292 for _, dir := range dirs {
293 if dir != "." && dir != "" {
294 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
295 }
296 }
297 }
298}
299
300// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir].
301func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) {
302 for group, phonyPath := range targetGroups {
303 if _, found := modulesInDirGroup[group]; !found {
304 modulesInDirGroup[group] = make(map[string]android.Paths)
305 }
306 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath)
307 }
308}
309
310// Add given files to the OS group and subset group.
311func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) {
312 if len(files) > 0 {
313 subsetName := osName + "_subset"
314 allGroups[osName] = append(allGroups[osName], files...)
315 // Now include only the first variant in the subsetGroups.
316 // If clang and clang-tidy get faster, we might include more variants.
317 if _, found := subsetGroups[subsetName]; !found {
318 subsetGroups[subsetName] = files
319 }
320 }
321}
322
323// Add an all-OS group, with groupName, to include all os-specific phony targets.
324func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) {
325 if len(phonyTargetGroups) > 0 {
326 var targets android.Paths
327 for group, _ := range phonyTargetGroups {
328 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName)))
329 }
330 phonyTargetGroups[groupName] = targets
331 }
332}
333
334// Create one phony targets for each group and add them to the targetGroups.
335func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) {
336 for group, files := range fileGroups {
337 groupName := objTidyModuleGroupName(module, group, objTidyName)
338 ctx.Phony(groupName, files...)
339 targetGroups[group] = android.PathForPhony(ctx, groupName)
340 }
341}