blob: 78a791faf1bd1d03b739cee72dc80ee3739e35b0 [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
74 // If not explicitly set, check the global tidy flag
Colin Cross6510f912017-11-29 00:27:14 -080075 if tidy.Properties.Tidy == nil && !ctx.Config().ClangTidy() {
Dan Willemsena03cf6d2016-09-26 15:45:04 -070076 return flags
77 }
78
Dan Willemsena03cf6d2016-09-26 15:45:04 -070079 flags.Tidy = true
80
Chih-Hung Hsieh9e5d8a62018-09-21 15:12:44 -070081 // Add global WITH_TIDY_FLAGS and local tidy_flags.
82 withTidyFlags := ctx.Config().Getenv("WITH_TIDY_FLAGS")
83 if len(withTidyFlags) > 0 {
84 flags.TidyFlags = append(flags.TidyFlags, withTidyFlags)
85 }
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -080086 esc := checkNinjaAndShellEscapeList
87 flags.TidyFlags = append(flags.TidyFlags, esc(ctx, "tidy_flags", tidy.Properties.Tidy_flags)...)
Chih-Hung Hsieh9f94c362021-02-10 21:56:03 -080088 // If TidyFlags does not contain -header-filter, add default header filter.
89 // Find the substring because the flag could also appear as --header-filter=...
90 // and with or without single or double quotes.
91 if !android.SubstringInList(flags.TidyFlags, "-header-filter=") {
92 defaultDirs := ctx.Config().Getenv("DEFAULT_TIDY_HEADER_DIRS")
93 headerFilter := "-header-filter="
94 if defaultDirs == "" {
95 headerFilter += ctx.ModuleDir() + "/"
96 } else {
97 headerFilter += "\"(" + ctx.ModuleDir() + "/|" + defaultDirs + ")\""
98 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -070099 flags.TidyFlags = append(flags.TidyFlags, headerFilter)
100 }
101
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800102 // If clang-tidy is not enabled globally, add the -quiet flag.
103 if !ctx.Config().ClangTidy() {
104 flags.TidyFlags = append(flags.TidyFlags, "-quiet")
Chih-Hung Hsieh669cb912018-01-04 01:41:16 -0800105 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics")
Chih-Hung Hsiehdc0c0302017-12-15 20:57:48 -0800106 }
107
George Burgess IV030ccee2018-05-14 16:30:46 -0700108 extraArgFlags := []string{
109 // We might be using the static analyzer through clang tidy.
110 // https://bugs.llvm.org/show_bug.cgi?id=32914
111 "-D__clang_analyzer__",
112
113 // A recent change in clang-tidy (r328258) enabled destructor inlining, which
114 // appears to cause a number of false positives. Until that's resolved, this turns
115 // off the effects of r328258.
116 // https://bugs.llvm.org/show_bug.cgi?id=37459
117 "-Xclang", "-analyzer-config", "-Xclang", "c++-temp-dtor-inlining=false",
118 }
119
120 for _, f := range extraArgFlags {
121 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f)
122 }
George Burgess IV561a3fe2017-05-03 18:13:08 -0700123
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700124 tidyChecks := "-checks="
Colin Cross6510f912017-11-29 00:27:14 -0800125 if checks := ctx.Config().TidyChecks(); len(checks) > 0 {
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700126 tidyChecks += checks
127 } else {
128 tidyChecks += config.TidyChecksForDir(ctx.ModuleDir())
129 }
130 if len(tidy.Properties.Tidy_checks) > 0 {
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800131 tidyChecks = tidyChecks + "," + strings.Join(esc(ctx, "tidy_checks",
Dan Albertd12afec2020-08-14 16:53:21 -0700132 config.ClangRewriteTidyChecks(tidy.Properties.Tidy_checks)), ",")
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700133 }
Chih-Hung Hsieh327b6f02018-12-10 16:28:56 -0800134 if ctx.Windows() {
135 // https://b.corp.google.com/issues/120614316
136 // mingw32 has cert-dcl16-c warning in NO_ERROR,
137 // which is used in many Android files.
138 tidyChecks = tidyChecks + ",-cert-dcl16-c"
139 }
Chih-Hung Hsieh3d3df822020-04-08 10:42:16 -0700140 // https://b.corp.google.com/issues/153464409
141 // many local projects enable cert-* checks, which
142 // trigger bugprone-reserved-identifier.
Yabin Cui70ba0e22020-04-09 16:28:24 -0700143 tidyChecks = tidyChecks + ",-bugprone-reserved-identifier*,-cert-dcl51-cpp,-cert-dcl37-c"
Yabin Cui8ec05ff2020-04-10 13:36:41 -0700144 // http://b/153757728
145 tidyChecks = tidyChecks + ",-readability-qualified-auto"
146 // http://b/155034563
147 tidyChecks = tidyChecks + ",-bugprone-signed-char-misuse"
148 // http://b/155034972
149 tidyChecks = tidyChecks + ",-bugprone-branch-clone"
Yabin Cui10bf3b82021-08-10 15:42:10 +0000150 // http://b/193716442
151 tidyChecks = tidyChecks + ",-bugprone-implicit-widening-of-multiplication-result"
Yi Konge8273292021-08-31 14:04:18 +0800152 // Too many existing functions trigger this rule, and fixing it requires large code
153 // refactoring. The cost of maintaining this tidy rule outweighs the benefit it brings.
154 tidyChecks = tidyChecks + ",-bugprone-easily-swappable-parameters"
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700155 flags.TidyFlags = append(flags.TidyFlags, tidyChecks)
156
Chih-Hung Hsieh1b4934a2021-01-14 15:45:25 -0800157 if ctx.Config().IsEnvTrue("WITH_TIDY") {
158 // WITH_TIDY=1 enables clang-tidy globally. There could be many unexpected
159 // warnings from new checks and many local tidy_checks_as_errors and
160 // -warnings-as-errors can break a global build.
161 // So allow all clang-tidy warnings.
162 inserted := false
163 for i, s := range flags.TidyFlags {
164 if strings.Contains(s, "-warnings-as-errors=") {
165 // clang-tidy accepts only one -warnings-as-errors
166 // replace the old one
167 re := regexp.MustCompile(`'?-?-warnings-as-errors=[^ ]* *`)
168 newFlag := re.ReplaceAllString(s, "")
169 if newFlag == "" {
170 flags.TidyFlags[i] = "-warnings-as-errors=-*"
171 } else {
172 flags.TidyFlags[i] = newFlag + " -warnings-as-errors=-*"
173 }
174 inserted = true
175 break
176 }
177 }
178 if !inserted {
179 flags.TidyFlags = append(flags.TidyFlags, "-warnings-as-errors=-*")
180 }
181 } else if len(tidy.Properties.Tidy_checks_as_errors) > 0 {
Chih-Hung Hsieh217e09a2021-02-22 17:03:15 -0800182 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 +0000183 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors)
184 }
Dan Willemsena03cf6d2016-09-26 15:45:04 -0700185 return flags
186}
Chih-Hung Hsieh80783772021-10-11 16:46:56 -0700187
188func init() {
189 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton)
190}
191
192// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files.
193func TidyPhonySingleton() android.Singleton {
194 return &tidyPhonySingleton{}
195}
196
197type tidyPhonySingleton struct{}
198
199// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup.
200func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module,
201 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) {
202 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths
203 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths
204 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths
205 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths
206
207 // (1) Collect all obj/tidy files into OS-specific groups.
208 ctx.VisitAllModuleVariants(module, func(variant android.Module) {
209 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) {
210 return
211 }
212 if m, ok := variant.(*Module); ok {
213 osName := variant.Target().Os.Name
214 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups)
215 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups)
216 }
217 })
218
219 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets.
220 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj")
221 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy")
222 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj")
223 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy")
224
225 tidyTargetGroups := make(map[string]android.Path)
226 objTargetGroups := make(map[string]android.Path)
227 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups)
228 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups)
229 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups)
230 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups)
231
232 moduleDir := ctx.ModuleDir(module)
233 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup)
234 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup)
235}
236
237func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) {
238 // For tidy-* directory phony targets, there are different variant groups.
239 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths
240 // of all phony targets to be included into direct dependents of tidy-D_G.
241 tidyModulesInDirGroup := make(map[string]map[string]android.Paths)
242 // Also for obj-* directory phony targets.
243 objModulesInDirGroup := make(map[string]map[string]android.Paths)
244
245 // Collect tidy/obj targets from the 'final' modules.
246 ctx.VisitAllModules(func(module android.Module) {
247 if module == ctx.FinalModule(module) {
248 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup)
249 }
250 })
251
252 suffix := ""
253 if ctx.Config().KatiEnabled() {
254 suffix = "-soong"
255 }
256 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup)
257 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup)
258}
259
260// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy,
261func objTidyModuleGroupName(module android.Module, group string, suffix string) string {
262 if group == "" {
263 return module.Name() + "-" + suffix
264 }
265 return module.Name() + "_" + group + "-" + suffix
266}
267
268// Generate obj-* or tidy-* phony targets.
269func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) {
270 // For each variant group, create a <prefix>-<directory>_group target that
271 // depends on all subdirectories and modules in the directory.
272 for group, modulesInDir := range objTidyModulesInDirGroup {
273 groupSuffix := ""
274 if group != "" {
275 groupSuffix = "_" + group
276 }
277 mmTarget := func(dir string) string {
278 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix
279 }
280 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget)
281 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs.
282 var topDirPaths android.Paths
283 for _, dir := range topDirs {
284 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir)))
285 }
286 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...)
287 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir]
288 for _, dir := range dirs {
289 if dir != "." && dir != "" {
290 ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
291 }
292 }
293 }
294}
295
296// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir].
297func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) {
298 for group, phonyPath := range targetGroups {
299 if _, found := modulesInDirGroup[group]; !found {
300 modulesInDirGroup[group] = make(map[string]android.Paths)
301 }
302 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath)
303 }
304}
305
306// Add given files to the OS group and subset group.
307func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) {
308 if len(files) > 0 {
309 subsetName := osName + "_subset"
310 allGroups[osName] = append(allGroups[osName], files...)
311 // Now include only the first variant in the subsetGroups.
312 // If clang and clang-tidy get faster, we might include more variants.
313 if _, found := subsetGroups[subsetName]; !found {
314 subsetGroups[subsetName] = files
315 }
316 }
317}
318
319// Add an all-OS group, with groupName, to include all os-specific phony targets.
320func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) {
321 if len(phonyTargetGroups) > 0 {
322 var targets android.Paths
323 for group, _ := range phonyTargetGroups {
324 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName)))
325 }
326 phonyTargetGroups[groupName] = targets
327 }
328}
329
330// Create one phony targets for each group and add them to the targetGroups.
331func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) {
332 for group, files := range fileGroups {
333 groupName := objTidyModuleGroupName(module, group, objTidyName)
334 ctx.Phony(groupName, files...)
335 targetGroups[group] = android.PathForPhony(ctx, groupName)
336 }
337}