1// 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 ( 18 "fmt" 19 "path/filepath" 20 "regexp" 21 "strings" 22 23 "github.com/google/blueprint/proptools" 24 25 "android/soong/android" 26 "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 38 39 // Checks that should be treated as errors. 40 Tidy_checks_as_errors []string 41} 42 43type tidyFeature struct { 44 Properties TidyProperties 45} 46 47var 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 62func (tidy *tidyFeature) props() []interface{} { 63 return []interface{}{&tidy.Properties} 64} 65 66// 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 = true 70 71// keep this up to date with https://cs.android.com/android/platform/superproject/+/master:build/bazel/rules/cc/clang_tidy.bzl 72func (tidy *tidyFeature) flags(ctx ModuleContext, flags Flags) Flags { 73 CheckBadTidyFlags(ctx, "tidy_flags", tidy.Properties.Tidy_flags) 74 CheckBadTidyChecks(ctx, "tidy_checks", tidy.Properties.Tidy_checks) 75 76 // Check if tidy is explicitly disabled for this module 77 if tidy.Properties.Tidy != nil && !*tidy.Properties.Tidy { 78 return flags 79 } 80 // Some projects like external/* and vendor/* have clang-tidy disabled by default, 81 // unless they are enabled explicitly with the "tidy:true" property or 82 // when TIDY_EXTERNAL_VENDOR is set to true. 83 if !proptools.Bool(tidy.Properties.Tidy) && 84 config.NoClangTidyForDir( 85 ctx.Config().IsEnvTrue("TIDY_EXTERNAL_VENDOR"), 86 ctx.ModuleDir()) { 87 return flags 88 } 89 // If not explicitly disabled, set flags.Tidy to generate .tidy rules. 90 // Note that libraries and binaries will depend on .tidy files ONLY if 91 // the global WITH_TIDY or module 'tidy' property is true. 92 flags.Tidy = true 93 94 // If explicitly enabled, by global WITH_TIDY or local tidy:true property, 95 // set flags.NeedTidyFiles to make this module depend on .tidy files. 96 // Note that locally set tidy:true is ignored if ALLOW_LOCAL_TIDY_TRUE is not set to true. 97 if ctx.Config().IsEnvTrue("WITH_TIDY") || (ctx.Config().IsEnvTrue("ALLOW_LOCAL_TIDY_TRUE") && Bool(tidy.Properties.Tidy)) { 98 flags.NeedTidyFiles = true 99 } 100 101 // Add global WITH_TIDY_FLAGS and local tidy_flags. 102 withTidyFlags := ctx.Config().Getenv("WITH_TIDY_FLAGS") 103 if len(withTidyFlags) > 0 { 104 flags.TidyFlags = append(flags.TidyFlags, withTidyFlags) 105 } 106 esc := checkNinjaAndShellEscapeList 107 flags.TidyFlags = append(flags.TidyFlags, esc(ctx, "tidy_flags", tidy.Properties.Tidy_flags)...) 108 // If TidyFlags does not contain -header-filter, add default header filter. 109 // Find the substring because the flag could also appear as --header-filter=... 110 // and with or without single or double quotes. 111 if !android.SubstringInList(flags.TidyFlags, "-header-filter=") { 112 defaultDirs := ctx.Config().Getenv("DEFAULT_TIDY_HEADER_DIRS") 113 headerFilter := "-header-filter=" 114 // Default header filter should include only the module directory, 115 // not the out/soong/.../ModuleDir/... 116 // Otherwise, there will be too many warnings from generated files in out/... 117 // If a module wants to see warnings in the generated source files, 118 // it should specify its own -header-filter flag. 119 if defaultDirs == "" { 120 headerFilter += "^" + ctx.ModuleDir() + "/" 121 } else { 122 headerFilter += "\"(^" + ctx.ModuleDir() + "/|" + defaultDirs + ")\"" 123 } 124 flags.TidyFlags = append(flags.TidyFlags, headerFilter) 125 } 126 // Work around RBE bug in parsing clang-tidy flags, replace "--flag" with "-flag". 127 // Some C/C++ modules added local tidy flags like --header-filter= and --extra-arg-before=. 128 doubleDash := regexp.MustCompile("^('?)--(.*)$") 129 for i, s := range flags.TidyFlags { 130 flags.TidyFlags[i] = doubleDash.ReplaceAllString(s, "$1-$2") 131 } 132 133 // If clang-tidy is not enabled globally, add the -quiet flag. 134 if !ctx.Config().ClangTidy() { 135 flags.TidyFlags = append(flags.TidyFlags, "-quiet") 136 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics") 137 } 138 139 for _, f := range config.TidyExtraArgFlags() { 140 flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f) 141 } 142 143 tidyChecks := "-checks=" 144 if checks := ctx.Config().TidyChecks(); len(checks) > 0 { 145 tidyChecks += checks 146 } else { 147 tidyChecks += config.TidyChecksForDir(ctx.ModuleDir()) 148 } 149 if len(tidy.Properties.Tidy_checks) > 0 { 150 // If Tidy_checks contains "-*", ignore all checks before "-*". 151 localChecks := tidy.Properties.Tidy_checks 152 ignoreGlobalChecks := false 153 for n, check := range tidy.Properties.Tidy_checks { 154 if check == "-*" { 155 ignoreGlobalChecks = true 156 localChecks = tidy.Properties.Tidy_checks[n:] 157 } 158 } 159 if ignoreGlobalChecks { 160 tidyChecks = "-checks=" + strings.Join(esc(ctx, "tidy_checks", 161 config.ClangRewriteTidyChecks(localChecks)), ",") 162 } else { 163 tidyChecks = tidyChecks + "," + strings.Join(esc(ctx, "tidy_checks", 164 config.ClangRewriteTidyChecks(localChecks)), ",") 165 } 166 } 167 tidyChecks = tidyChecks + config.TidyGlobalNoChecks() 168 if ctx.Windows() { 169 // https://b.corp.google.com/issues/120614316 170 // mingw32 has cert-dcl16-c warning in NO_ERROR, 171 // which is used in many Android files. 172 tidyChecks += ",-cert-dcl16-c" 173 } 174 175 flags.TidyFlags = append(flags.TidyFlags, tidyChecks) 176 177 // Embedding -warnings-as-errors in tidy_flags is error-prone. 178 // It should be replaced with the tidy_checks_as_errors list. 179 for i, s := range flags.TidyFlags { 180 if strings.Contains(s, "-warnings-as-errors=") { 181 if NoWarningsAsErrorsInTidyFlags { 182 ctx.PropertyErrorf("tidy_flags", "should not contain "+s+"; use tidy_checks_as_errors instead.") 183 } else { 184 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", 185 ctx.BlueprintsFile(), ctx.ModuleName(), s) 186 flags.TidyFlags[i] = "-warnings-as-errors=-*" 187 } 188 break // there is at most one -warnings-as-errors 189 } 190 } 191 // Default clang-tidy flags does not contain -warning-as-errors. 192 // If a module has tidy_checks_as_errors, add the list to -warnings-as-errors 193 // and then append the TidyGlobalNoErrorChecks. 194 if len(tidy.Properties.Tidy_checks_as_errors) > 0 { 195 tidyChecksAsErrors := "-warnings-as-errors=" + 196 strings.Join(esc(ctx, "tidy_checks_as_errors", tidy.Properties.Tidy_checks_as_errors), ",") + 197 config.TidyGlobalNoErrorChecks() 198 flags.TidyFlags = append(flags.TidyFlags, tidyChecksAsErrors) 199 } 200 return flags 201} 202 203func init() { 204 android.RegisterSingletonType("tidy_phony_targets", TidyPhonySingleton) 205} 206 207// This TidyPhonySingleton generates both tidy-* and obj-* phony targets for C/C++ files. 208func TidyPhonySingleton() android.Singleton { 209 return &tidyPhonySingleton{} 210} 211 212type tidyPhonySingleton struct{} 213 214// Given a final module, add its tidy/obj phony targets to tidy/objModulesInDirGroup. 215func collectTidyObjModuleTargets(ctx android.SingletonContext, module android.Module, 216 tidyModulesInDirGroup, objModulesInDirGroup map[string]map[string]android.Paths) { 217 allObjFileGroups := make(map[string]android.Paths) // variant group name => obj file Paths 218 allTidyFileGroups := make(map[string]android.Paths) // variant group name => tidy file Paths 219 subsetObjFileGroups := make(map[string]android.Paths) // subset group name => obj file Paths 220 subsetTidyFileGroups := make(map[string]android.Paths) // subset group name => tidy file Paths 221 222 // (1) Collect all obj/tidy files into OS-specific groups. 223 ctx.VisitAllModuleVariants(module, func(variant android.Module) { 224 if ctx.Config().KatiEnabled() && android.ShouldSkipAndroidMkProcessing(variant) { 225 return 226 } 227 if m, ok := variant.(*Module); ok { 228 osName := variant.Target().Os.Name 229 addToOSGroup(osName, m.objFiles, allObjFileGroups, subsetObjFileGroups) 230 addToOSGroup(osName, m.tidyFiles, allTidyFileGroups, subsetTidyFileGroups) 231 } 232 }) 233 234 // (2) Add an all-OS group, with "" or "subset" name, to include all os-specific phony targets. 235 addAllOSGroup(ctx, module, allObjFileGroups, "", "obj") 236 addAllOSGroup(ctx, module, allTidyFileGroups, "", "tidy") 237 addAllOSGroup(ctx, module, subsetObjFileGroups, "subset", "obj") 238 addAllOSGroup(ctx, module, subsetTidyFileGroups, "subset", "tidy") 239 240 tidyTargetGroups := make(map[string]android.Path) 241 objTargetGroups := make(map[string]android.Path) 242 genObjTidyPhonyTargets(ctx, module, "obj", allObjFileGroups, objTargetGroups) 243 genObjTidyPhonyTargets(ctx, module, "obj", subsetObjFileGroups, objTargetGroups) 244 genObjTidyPhonyTargets(ctx, module, "tidy", allTidyFileGroups, tidyTargetGroups) 245 genObjTidyPhonyTargets(ctx, module, "tidy", subsetTidyFileGroups, tidyTargetGroups) 246 247 moduleDir := ctx.ModuleDir(module) 248 appendToModulesInDirGroup(tidyTargetGroups, moduleDir, tidyModulesInDirGroup) 249 appendToModulesInDirGroup(objTargetGroups, moduleDir, objModulesInDirGroup) 250} 251 252func (m *tidyPhonySingleton) GenerateBuildActions(ctx android.SingletonContext) { 253 // For tidy-* directory phony targets, there are different variant groups. 254 // tidyModulesInDirGroup[G][D] is for group G, directory D, with Paths 255 // of all phony targets to be included into direct dependents of tidy-D_G. 256 tidyModulesInDirGroup := make(map[string]map[string]android.Paths) 257 // Also for obj-* directory phony targets. 258 objModulesInDirGroup := make(map[string]map[string]android.Paths) 259 260 // Collect tidy/obj targets from the 'final' modules. 261 ctx.VisitAllModules(func(module android.Module) { 262 if module == ctx.FinalModule(module) { 263 collectTidyObjModuleTargets(ctx, module, tidyModulesInDirGroup, objModulesInDirGroup) 264 } 265 }) 266 267 suffix := "" 268 if ctx.Config().KatiEnabled() { 269 suffix = "-soong" 270 } 271 generateObjTidyPhonyTargets(ctx, suffix, "obj", objModulesInDirGroup) 272 generateObjTidyPhonyTargets(ctx, suffix, "tidy", tidyModulesInDirGroup) 273} 274 275// The name for an obj/tidy module variant group phony target is Name_group-obj/tidy, 276func objTidyModuleGroupName(module android.Module, group string, suffix string) string { 277 if group == "" { 278 return module.Name() + "-" + suffix 279 } 280 return module.Name() + "_" + group + "-" + suffix 281} 282 283// Generate obj-* or tidy-* phony targets. 284func generateObjTidyPhonyTargets(ctx android.SingletonContext, suffix string, prefix string, objTidyModulesInDirGroup map[string]map[string]android.Paths) { 285 // For each variant group, create a <prefix>-<directory>_group target that 286 // depends on all subdirectories and modules in the directory. 287 for group, modulesInDir := range objTidyModulesInDirGroup { 288 groupSuffix := "" 289 if group != "" { 290 groupSuffix = "_" + group 291 } 292 mmTarget := func(dir string) string { 293 return prefix + "-" + strings.Replace(filepath.Clean(dir), "/", "-", -1) + groupSuffix 294 } 295 dirs, topDirs := android.AddAncestors(ctx, modulesInDir, mmTarget) 296 // Create a <prefix>-soong_group target that depends on all <prefix>-dir_group of top level dirs. 297 var topDirPaths android.Paths 298 for _, dir := range topDirs { 299 topDirPaths = append(topDirPaths, android.PathForPhony(ctx, mmTarget(dir))) 300 } 301 ctx.Phony(prefix+suffix+groupSuffix, topDirPaths...) 302 // Create a <prefix>-dir_group target that depends on all targets in modulesInDir[dir] 303 for _, dir := range dirs { 304 if dir != "." && dir != "" { 305 ctx.Phony(mmTarget(dir), modulesInDir[dir]...) 306 } 307 } 308 } 309} 310 311// Append (obj|tidy)TargetGroups[group] into (obj|tidy)ModulesInDirGroups[group][moduleDir]. 312func appendToModulesInDirGroup(targetGroups map[string]android.Path, moduleDir string, modulesInDirGroup map[string]map[string]android.Paths) { 313 for group, phonyPath := range targetGroups { 314 if _, found := modulesInDirGroup[group]; !found { 315 modulesInDirGroup[group] = make(map[string]android.Paths) 316 } 317 modulesInDirGroup[group][moduleDir] = append(modulesInDirGroup[group][moduleDir], phonyPath) 318 } 319} 320 321// Add given files to the OS group and subset group. 322func addToOSGroup(osName string, files android.Paths, allGroups, subsetGroups map[string]android.Paths) { 323 if len(files) > 0 { 324 subsetName := osName + "_subset" 325 allGroups[osName] = append(allGroups[osName], files...) 326 // Now include only the first variant in the subsetGroups. 327 // If clang and clang-tidy get faster, we might include more variants. 328 if _, found := subsetGroups[subsetName]; !found { 329 subsetGroups[subsetName] = files 330 } 331 } 332} 333 334// Add an all-OS group, with groupName, to include all os-specific phony targets. 335func addAllOSGroup(ctx android.SingletonContext, module android.Module, phonyTargetGroups map[string]android.Paths, groupName string, objTidyName string) { 336 if len(phonyTargetGroups) > 0 { 337 var targets android.Paths 338 for group, _ := range phonyTargetGroups { 339 targets = append(targets, android.PathForPhony(ctx, objTidyModuleGroupName(module, group, objTidyName))) 340 } 341 phonyTargetGroups[groupName] = targets 342 } 343} 344 345// Create one phony targets for each group and add them to the targetGroups. 346func genObjTidyPhonyTargets(ctx android.SingletonContext, module android.Module, objTidyName string, fileGroups map[string]android.Paths, targetGroups map[string]android.Path) { 347 for group, files := range fileGroups { 348 groupName := objTidyModuleGroupName(module, group, objTidyName) 349 ctx.Phony(groupName, files...) 350 targetGroups[group] = android.PathForPhony(ctx, groupName) 351 } 352} 353