blob: 1f5f56d5b8deb4a506c45ee41f824f572b6a3073 [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"
Pirama Arumuga Nainar5fc137b2022-01-25 15:42:39 -0800159 // http://b/216364337 - TODO: Follow-up after compiler update to
160 // disable or fix individual instances.
161 tidyChecks = tidyChecks + ",-cert-err33-c"
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700162 flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
163
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -0800164 if ctx.Config().IsEnvTrue("WITH_TIDY") {
165 // WITH_TIDY=1 enables clang-tidy globally. There could be many unexpected
166 // warnings from new checks and many local tidy_checks_as_errors and
167 // -warnings-as-errors can break a global build.
168 // So allow all clang-tidy warnings.
169 inserted := false
170 for i, s := range flags.TidyFlags {
171 if strings.Contains(s, "-warnings-as-errors=") {
172 // clang-tidy accepts only one -warnings-as-errors
173 // replace the old one
174 re := regexp.MustCompile(`'?-?-warnings-as-errors=[^ ]* *`)
175 newFlag := re.ReplaceAllString(s, "")
176 if newFlag == "" {
177 flags.TidyFlags[i] = "-warnings-as-errors=-*"
178 } else {
179 flags.TidyFlags[i] = newFlag + " -warnings-as-errors=-*"
180 }
181 inserted = true
182 break
183 }
184 }
185 if !inserted {
186 flags.TidyFlags = append(flags.TidyFlags, "-warnings-as-errors=-*")
187 }
188 } else if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800189 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 +0000190 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors)
191 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700192 return flags
193}
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700194
195func init() {
196 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton)
197}
198
199// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files.
200func TidyPhonySingleton() android.Singleton {
201 return &tidyPhonySingleton{}
202}
203
204type tidyPhonySingleton struct{}
205
206// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup.
207func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module,
208 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) {
209 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths
210 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths
211 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths
212 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths
213
214 // (1) Collect all obj/tidy files into OS-specific groups.
215 ctx.VisitAllModuleVariants(module, func(variant android.Module) {
216 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) {
217 return
218 }
219 if m, ok := variant.(*Module); ok {
220 osName := variant.Target().Os.Name
221 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups)
222 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups)
223 }
224 })
225
226 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets.
227 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj")
228 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy")
229 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj")
230 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy")
231
232 tidyTargetGroups := make(map[string]android.Path)
233 objTargetGroups := make(map[string]android.Path)
234 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups)
235 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups)
236 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups)
237 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups)
238
239 moduleDir := ctx.ModuleDir(module)
240 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup)
241 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup)
242}
243
244func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) {
245 // For tidy-* directory phony targets, there are different variant groups.
246 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths
247 // of all phony targets to be included into direct dependents of tidy-D_G.
248 tidyModulesInDirGroup := make(map[string]map[string]android.Paths)
249 // Also for obj-* directory phony targets.
250 objModulesInDirGroup := make(map[string]map[string]android.Paths)
251
252 // Collect tidy/obj targets from the 'final' modules.
253 ctx.VisitAllModules(func(module android.Module) {
254 if module == ctx.FinalModule(module) {
255 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup)
256 }
257 })
258
259 suffix := ""
260 if ctx.Config().KatiEnabled() {
261 suffix = "-soong"
262 }
263 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup)
264 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup)
265}
266
267// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy,
268func objTidyModuleGroupName(module android.Module, group string, suffix string) string {
269 if group == "" {
270 return module.Name() + "-" + suffix
271 }
272 return module.Name() + "_" + group + "-" + suffix
273}
274
275// Generate obj-* or tidy-* phony targets.
276func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) {
277 // For each variant group, create a <prefix>-<directory>_group target that
278 // depends on all subdirectories and modules in the directory.
279 for group, modulesInDir := range objTidyModulesInDirGroup {
280 groupSuffix := ""
281 if group != "" {
282 groupSuffix = "_" + group
283 }
284 mmTarget := func(dir string) string {
285 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix
286 }
287 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget)
288 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs.
289 var topDirPaths android.Paths
290 for _, dir := range topDirs {
291 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir)))
292 }
293 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...)
294 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir]
295 for _, dir := range dirs {
296 if dir != "." && dir != "" {
297 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
298 }
299 }
300 }
301}
302
303// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir].
304func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) {
305 for group, phonyPath := range targetGroups {
306 if _, found := modulesInDirGroup[group]; !found {
307 modulesInDirGroup[group] = make(map[string]android.Paths)
308 }
309 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath)
310 }
311}
312
313// Add given files to the OS group and subset group.
314func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) {
315 if len(files) > 0 {
316 subsetName := osName + "_subset"
317 allGroups[osName] = append(allGroups[osName], files...)
318 // Now include only the first variant in the subsetGroups.
319 // If clang and clang-tidy get faster, we might include more variants.
320 if _, found := subsetGroups[subsetName]; !found {
321 subsetGroups[subsetName] = files
322 }
323 }
324}
325
326// Add an all-OS group, with groupName, to include all os-specific phony targets.
327func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) {
328 if len(phonyTargetGroups) > 0 {
329 var targets android.Paths
330 for group, _ := range phonyTargetGroups {
331 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName)))
332 }
333 phonyTargetGroups[groupName] = targets
334 }
335}
336
337// Create one phony targets for each group and add them to the targetGroups.
338func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) {
339 for group, files := range fileGroups {
340 groupName := objTidyModuleGroupName(module, group, objTidyName)
341 ctx.Phony(groupName, files...)
342 targetGroups[group] = android.PathForPhony(ctx, groupName)
343 }
344}