3 """Find Kconfig symbols that are referenced but not defined."""
5 # (c) 2014-2015 Valentin Rothberg <valentinrothberg@gmail.com>
6 # (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
8 # Licensed under the terms of the GNU GPL License version 2
15 from multiprocessing import Pool, cpu_count
16 from optparse import OptionParser
17 from subprocess import Popen, PIPE, STDOUT
21 OPERATORS = r"&|\(|\)|\||\!"
22 FEATURE = r"(?:\w*[A-Z0-9]\w*){2,}"
23 DEF = r"^\s*(?:menu){,1}config\s+(" + FEATURE + r")\s*"
24 EXPR = r"(?:" + OPERATORS + r"|\s|" + FEATURE + r")+"
25 DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
26 STMT = r"^\s*(?:if|select|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
27 SOURCE_FEATURE = r"(?:\W|\b)+[D]{,1}CONFIG_(" + FEATURE + r")"
30 REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
31 REGEX_FEATURE = re.compile(r'(?!\B)' + FEATURE + r'(?!\B)')
32 REGEX_SOURCE_FEATURE = re.compile(SOURCE_FEATURE)
33 REGEX_KCONFIG_DEF = re.compile(DEF)
34 REGEX_KCONFIG_EXPR = re.compile(EXPR)
35 REGEX_KCONFIG_STMT = re.compile(STMT)
36 REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
37 REGEX_FILTER_FEATURES = re.compile(r"[A-Za-z0-9]$")
38 REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
39 REGEX_QUOTES = re.compile("(\"(.*?)\")")
43 """The user interface of this module."""
44 usage = "%prog [options]\n\n" \
45 "Run this tool to detect Kconfig symbols that are referenced but " \
46 "not defined in\nKconfig. The output of this tool has the " \
47 "format \'Undefined symbol\\tFile list\'\n\n" \
48 "If no option is specified, %prog will default to check your\n" \
49 "current tree. Please note that specifying commits will " \
50 "\'git reset --hard\'\nyour current tree! You may save " \
51 "uncommitted changes to avoid losing data."
53 parser = OptionParser(usage=usage)
55 parser.add_option('-c', '--commit', dest='commit', action='store',
57 help="Check if the specified commit (hash) introduces "
58 "undefined Kconfig symbols.")
60 parser.add_option('-d', '--diff', dest='diff', action='store',
62 help="Diff undefined symbols between two commits. The "
63 "input format bases on Git log's "
64 "\'commmit1..commit2\'.")
66 parser.add_option('-f', '--find', dest='find', action='store_true',
68 help="Find and show commits that may cause symbols to be "
69 "missing. Required to run with --diff.")
71 parser.add_option('-i', '--ignore', dest='ignore', action='store',
73 help="Ignore files matching this pattern. Note that "
74 "the pattern needs to be a Python regex. To "
75 "ignore defconfigs, specify -i '.*defconfig'.")
77 parser.add_option('', '--force', dest='force', action='store_true',
79 help="Reset current Git tree even when it's dirty.")
81 (opts, _) = parser.parse_args()
83 if opts.commit and opts.diff:
84 sys.exit("Please specify only one option at once.")
86 if opts.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", opts.diff):
87 sys.exit("Please specify valid input in the following format: "
88 "\'commmit1..commit2\'")
90 if opts.commit or opts.diff:
91 if not opts.force and tree_is_dirty():
92 sys.exit("The current Git tree is dirty (see 'git status'). "
93 "Running this script may\ndelete important data since it "
94 "calls 'git reset --hard' for some performance\nreasons. "
95 " Please run this script in a clean Git tree or pass "
96 "'--force' if you\nwant to ignore this warning and "
104 re.match(opts.ignore, "this/is/just/a/test.c")
106 sys.exit("Please specify a valid Python regex.")
112 """Main function of this module."""
113 opts = parse_options()
115 if opts.commit or opts.diff:
122 commit_a = opts.commit + "~"
123 commit_b = opts.commit
125 split = opts.diff.split("..")
131 # get undefined items before the commit
132 execute("git reset --hard %s" % commit_a)
133 undefined_a = check_symbols(opts.ignore)
135 # get undefined items for the commit
136 execute("git reset --hard %s" % commit_b)
137 undefined_b = check_symbols(opts.ignore)
139 # report cases that are present for the commit but not before
140 for feature in sorted(undefined_b):
141 # feature has not been undefined before
142 if not feature in undefined_a:
143 files = sorted(undefined_b.get(feature))
144 print "%s\t%s" % (yel(feature), ", ".join(files))
146 commits = find_commits(feature, opts.diff)
148 # check if there are new files that reference the undefined feature
150 files = sorted(undefined_b.get(feature) -
151 undefined_a.get(feature))
153 print "%s\t%s" % (yel(feature), ", ".join(files))
155 commits = find_commits(feature, opts.diff)
159 execute("git reset --hard %s" % head)
161 # default to check the entire tree
163 undefined = check_symbols(opts.ignore)
164 for feature in sorted(undefined):
165 files = sorted(undefined.get(feature))
166 print "%s\t%s" % (yel(feature), ", ".join(files))
171 Color %string yellow.
173 return "\033[33m%s\033[0m" % string
180 return "\033[31m%s\033[0m" % string
184 """Execute %cmd and return stdout. Exit in case of error."""
185 pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
186 (stdout, _) = pop.communicate() # wait until finished
187 if pop.returncode != 0:
192 def find_commits(symbol, diff):
193 """Find commits changing %symbol in the given range of %diff."""
194 commits = execute("git log --pretty=oneline --abbrev-commit -G %s %s"
200 """Return true if the current working tree is dirty (i.e., if any file has
201 been added, deleted, modified, renamed or copied but not committed)."""
202 stdout = execute("git status --porcelain")
204 if re.findall(r"[URMADC]{1}", line[:2]):
210 """Return commit hash of current HEAD."""
211 stdout = execute("git rev-parse HEAD")
212 return stdout.strip('\n')
215 def partition(lst, size):
216 """Partition list @lst into eveni-sized lists of size @size."""
217 return [lst[i::size] for i in xrange(size)]
221 """Set signal handler to ignore SIGINT."""
222 signal.signal(signal.SIGINT, signal.SIG_IGN)
225 def check_symbols(ignore):
226 """Find undefined Kconfig symbols and return a dict with the symbol as key
227 and a list of referencing files as value. Files matching %ignore are not
228 checked for undefined symbols."""
229 pool = Pool(cpu_count(), init_worker)
231 return check_symbols_helper(pool, ignore)
232 except KeyboardInterrupt:
238 def check_symbols_helper(pool, ignore):
239 """Helper method for check_symbols(). Used to catch keyboard interrupts in
240 check_symbols() in order to properly terminate running worker processes."""
243 defined_features = []
244 referenced_features = dict() # {file: [features]}
246 # use 'git ls-files' to get the worklist
247 stdout = execute("git ls-files")
248 if len(stdout) > 0 and stdout[-1] == "\n":
251 for gitfile in stdout.rsplit("\n"):
252 if ".git" in gitfile or "ChangeLog" in gitfile or \
253 ".log" in gitfile or os.path.isdir(gitfile) or \
254 gitfile.startswith("tools/"):
256 if REGEX_FILE_KCONFIG.match(gitfile):
257 kconfig_files.append(gitfile)
259 if ignore and not re.match(ignore, gitfile):
261 # add source files that do not match the ignore pattern
262 source_files.append(gitfile)
265 arglist = partition(source_files, cpu_count())
266 for res in pool.map(parse_source_files, arglist):
267 referenced_features.update(res)
270 # parse kconfig files
272 for part in partition(kconfig_files, cpu_count()):
273 arglist.append((part, ignore))
274 for res in pool.map(parse_kconfig_files, arglist):
275 defined_features.extend(res[0])
276 referenced_features.update(res[1])
277 defined_features = set(defined_features)
279 # inverse mapping of referenced_features to dict(feature: [files])
281 for _file, features in referenced_features.iteritems():
282 for feature in features:
283 inv_map[feature] = inv_map.get(feature, set())
284 inv_map[feature].add(_file)
285 referenced_features = inv_map
287 undefined = {} # {feature: [files]}
288 for feature in sorted(referenced_features):
289 # filter some false positives
290 if feature == "FOO" or feature == "BAR" or \
291 feature == "FOO_BAR" or feature == "XXX":
293 if feature not in defined_features:
294 if feature.endswith("_MODULE"):
295 # avoid false positives for kernel modules
296 if feature[:-len("_MODULE")] in defined_features:
298 undefined[feature] = referenced_features.get(feature)
302 def parse_source_files(source_files):
303 """Parse each source file in @source_files and return dictionary with source
304 files as keys and lists of references Kconfig symbols as values."""
305 referenced_features = dict()
306 for sfile in source_files:
307 referenced_features[sfile] = parse_source_file(sfile)
308 return referenced_features
311 def parse_source_file(sfile):
312 """Parse @sfile and return a list of referenced Kconfig features."""
316 if not os.path.exists(sfile):
319 with open(sfile, "r") as stream:
320 lines = stream.readlines()
323 if not "CONFIG_" in line:
325 features = REGEX_SOURCE_FEATURE.findall(line)
326 for feature in features:
327 if not REGEX_FILTER_FEATURES.search(feature):
329 references.append(feature)
334 def get_features_in_line(line):
335 """Return mentioned Kconfig features in @line."""
336 return REGEX_FEATURE.findall(line)
339 def parse_kconfig_files(args):
340 """Parse kconfig files and return tuple of defined and references Kconfig
341 symbols. Note, @args is a tuple of a list of files and the @ignore
343 kconfig_files = args[0]
345 defined_features = []
346 referenced_features = dict()
348 for kfile in kconfig_files:
349 defined, references = parse_kconfig_file(kfile)
350 defined_features.extend(defined)
351 if ignore and re.match(ignore, kfile):
352 # do not collect references for files that match the ignore pattern
354 referenced_features[kfile] = references
355 return (defined_features, referenced_features)
358 def parse_kconfig_file(kfile):
359 """Parse @kfile and update feature definitions and references."""
365 if not os.path.exists(kfile):
366 return defined, references
368 with open(kfile, "r") as stream:
369 lines = stream.readlines()
371 for i in range(len(lines)):
373 line = line.strip('\n')
374 line = line.split("#")[0] # ignore comments
376 if REGEX_KCONFIG_DEF.match(line):
377 feature_def = REGEX_KCONFIG_DEF.findall(line)
378 defined.append(feature_def[0])
380 elif REGEX_KCONFIG_HELP.match(line):
383 # ignore content of help messages
385 elif REGEX_KCONFIG_STMT.match(line):
386 line = REGEX_QUOTES.sub("", line)
387 features = get_features_in_line(line)
388 # multi-line statements
389 while line.endswith("\\"):
392 line = line.strip('\n')
393 features.extend(get_features_in_line(line))
394 for feature in set(features):
395 if REGEX_NUMERIC.match(feature):
396 # ignore numeric values
398 references.append(feature)
400 return defined, references
403 if __name__ == "__main__":