Back to home page

LXR

 
 

    


0001 #!/usr/bin/env python3
0002 
0003 """Find Kconfig symbols that are referenced but not defined."""
0004 
0005 # (c) 2014-2016 Valentin Rothberg <valentinrothberg@gmail.com>
0006 # (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
0007 #
0008 # Licensed under the terms of the GNU GPL License version 2
0009 
0010 
0011 import argparse
0012 import difflib
0013 import os
0014 import re
0015 import signal
0016 import subprocess
0017 import sys
0018 from multiprocessing import Pool, cpu_count
0019 
0020 
0021 # regex expressions
0022 OPERATORS = r"&|\(|\)|\||\!"
0023 SYMBOL = r"(?:\w*[A-Z0-9]\w*){2,}"
0024 DEF = r"^\s*(?:menu){,1}config\s+(" + SYMBOL + r")\s*"
0025 EXPR = r"(?:" + OPERATORS + r"|\s|" + SYMBOL + r")+"
0026 DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
0027 STMT = r"^\s*(?:if|select|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
0028 SOURCE_SYMBOL = r"(?:\W|\b)+[D]{,1}CONFIG_(" + SYMBOL + r")"
0029 
0030 # regex objects
0031 REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
0032 REGEX_SYMBOL = re.compile(r'(?!\B)' + SYMBOL + r'(?!\B)')
0033 REGEX_SOURCE_SYMBOL = re.compile(SOURCE_SYMBOL)
0034 REGEX_KCONFIG_DEF = re.compile(DEF)
0035 REGEX_KCONFIG_EXPR = re.compile(EXPR)
0036 REGEX_KCONFIG_STMT = re.compile(STMT)
0037 REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
0038 REGEX_FILTER_SYMBOLS = re.compile(r"[A-Za-z0-9]$")
0039 REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
0040 REGEX_QUOTES = re.compile("(\"(.*?)\")")
0041 
0042 
0043 def parse_options():
0044     """The user interface of this module."""
0045     usage = "Run this tool to detect Kconfig symbols that are referenced but " \
0046             "not defined in Kconfig.  If no option is specified, "             \
0047             "checkkconfigsymbols defaults to check your current tree.  "       \
0048             "Please note that specifying commits will 'git reset --hard\' "    \
0049             "your current tree!  You may save uncommitted changes to avoid "   \
0050             "losing data."
0051 
0052     parser = argparse.ArgumentParser(description=usage)
0053 
0054     parser.add_argument('-c', '--commit', dest='commit', action='store',
0055                         default="",
0056                         help="check if the specified commit (hash) introduces "
0057                              "undefined Kconfig symbols")
0058 
0059     parser.add_argument('-d', '--diff', dest='diff', action='store',
0060                         default="",
0061                         help="diff undefined symbols between two commits "
0062                              "(e.g., -d commmit1..commit2)")
0063 
0064     parser.add_argument('-f', '--find', dest='find', action='store_true',
0065                         default=False,
0066                         help="find and show commits that may cause symbols to be "
0067                              "missing (required to run with --diff)")
0068 
0069     parser.add_argument('-i', '--ignore', dest='ignore', action='store',
0070                         default="",
0071                         help="ignore files matching this Python regex "
0072                              "(e.g., -i '.*defconfig')")
0073 
0074     parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
0075                         help="print a list of max. 10 string-similar symbols")
0076 
0077     parser.add_argument('--force', dest='force', action='store_true',
0078                         default=False,
0079                         help="reset current Git tree even when it's dirty")
0080 
0081     parser.add_argument('--no-color', dest='color', action='store_false',
0082                         default=True,
0083                         help="don't print colored output (default when not "
0084                              "outputting to a terminal)")
0085 
0086     args = parser.parse_args()
0087 
0088     if args.commit and args.diff:
0089         sys.exit("Please specify only one option at once.")
0090 
0091     if args.diff and not re.match(r"^[\w\-\.\^]+\.\.[\w\-\.\^]+$", args.diff):
0092         sys.exit("Please specify valid input in the following format: "
0093                  "\'commit1..commit2\'")
0094 
0095     if args.commit or args.diff:
0096         if not args.force and tree_is_dirty():
0097             sys.exit("The current Git tree is dirty (see 'git status').  "
0098                      "Running this script may\ndelete important data since it "
0099                      "calls 'git reset --hard' for some performance\nreasons. "
0100                      " Please run this script in a clean Git tree or pass "
0101                      "'--force' if you\nwant to ignore this warning and "
0102                      "continue.")
0103 
0104     if args.commit:
0105         args.find = False
0106 
0107     if args.ignore:
0108         try:
0109             re.match(args.ignore, "this/is/just/a/test.c")
0110         except:
0111             sys.exit("Please specify a valid Python regex.")
0112 
0113     return args
0114 
0115 
0116 def main():
0117     """Main function of this module."""
0118     args = parse_options()
0119 
0120     global COLOR
0121     COLOR = args.color and sys.stdout.isatty()
0122 
0123     if args.sim and not args.commit and not args.diff:
0124         sims = find_sims(args.sim, args.ignore)
0125         if sims:
0126             print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
0127         else:
0128             print("%s: no similar symbols found" % yel("Similar symbols"))
0129         sys.exit(0)
0130 
0131     # dictionary of (un)defined symbols
0132     defined = {}
0133     undefined = {}
0134 
0135     if args.commit or args.diff:
0136         head = get_head()
0137 
0138         # get commit range
0139         commit_a = None
0140         commit_b = None
0141         if args.commit:
0142             commit_a = args.commit + "~"
0143             commit_b = args.commit
0144         elif args.diff:
0145             split = args.diff.split("..")
0146             commit_a = split[0]
0147             commit_b = split[1]
0148             undefined_a = {}
0149             undefined_b = {}
0150 
0151         # get undefined items before the commit
0152         reset(commit_a)
0153         undefined_a, _ = check_symbols(args.ignore)
0154 
0155         # get undefined items for the commit
0156         reset(commit_b)
0157         undefined_b, defined = check_symbols(args.ignore)
0158 
0159         # report cases that are present for the commit but not before
0160         for symbol in sorted(undefined_b):
0161             # symbol has not been undefined before
0162             if symbol not in undefined_a:
0163                 files = sorted(undefined_b.get(symbol))
0164                 undefined[symbol] = files
0165             # check if there are new files that reference the undefined symbol
0166             else:
0167                 files = sorted(undefined_b.get(symbol) -
0168                                undefined_a.get(symbol))
0169                 if files:
0170                     undefined[symbol] = files
0171 
0172         # reset to head
0173         reset(head)
0174 
0175     # default to check the entire tree
0176     else:
0177         undefined, defined = check_symbols(args.ignore)
0178 
0179     # now print the output
0180     for symbol in sorted(undefined):
0181         print(red(symbol))
0182 
0183         files = sorted(undefined.get(symbol))
0184         print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
0185 
0186         sims = find_sims(symbol, args.ignore, defined)
0187         sims_out = yel("Similar symbols")
0188         if sims:
0189             print("%s: %s" % (sims_out, ', '.join(sims)))
0190         else:
0191             print("%s: %s" % (sims_out, "no similar symbols found"))
0192 
0193         if args.find:
0194             print("%s:" % yel("Commits changing symbol"))
0195             commits = find_commits(symbol, args.diff)
0196             if commits:
0197                 for commit in commits:
0198                     commit = commit.split(" ", 1)
0199                     print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
0200             else:
0201                 print("\t- no commit found")
0202         print()  # new line
0203 
0204 
0205 def reset(commit):
0206     """Reset current git tree to %commit."""
0207     execute(["git", "reset", "--hard", commit])
0208 
0209 
0210 def yel(string):
0211     """
0212     Color %string yellow.
0213     """
0214     return "\033[33m%s\033[0m" % string if COLOR else string
0215 
0216 
0217 def red(string):
0218     """
0219     Color %string red.
0220     """
0221     return "\033[31m%s\033[0m" % string if COLOR else string
0222 
0223 
0224 def execute(cmd):
0225     """Execute %cmd and return stdout.  Exit in case of error."""
0226     try:
0227         stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
0228         stdout = stdout.decode(errors='replace')
0229     except subprocess.CalledProcessError as fail:
0230         exit(fail)
0231     return stdout
0232 
0233 
0234 def find_commits(symbol, diff):
0235     """Find commits changing %symbol in the given range of %diff."""
0236     commits = execute(["git", "log", "--pretty=oneline",
0237                        "--abbrev-commit", "-G",
0238                        symbol, diff])
0239     return [x for x in commits.split("\n") if x]
0240 
0241 
0242 def tree_is_dirty():
0243     """Return true if the current working tree is dirty (i.e., if any file has
0244     been added, deleted, modified, renamed or copied but not committed)."""
0245     stdout = execute(["git", "status", "--porcelain"])
0246     for line in stdout:
0247         if re.findall(r"[URMADC]{1}", line[:2]):
0248             return True
0249     return False
0250 
0251 
0252 def get_head():
0253     """Return commit hash of current HEAD."""
0254     stdout = execute(["git", "rev-parse", "HEAD"])
0255     return stdout.strip('\n')
0256 
0257 
0258 def partition(lst, size):
0259     """Partition list @lst into eveni-sized lists of size @size."""
0260     return [lst[i::size] for i in range(size)]
0261 
0262 
0263 def init_worker():
0264     """Set signal handler to ignore SIGINT."""
0265     signal.signal(signal.SIGINT, signal.SIG_IGN)
0266 
0267 
0268 def find_sims(symbol, ignore, defined=[]):
0269     """Return a list of max. ten Kconfig symbols that are string-similar to
0270     @symbol."""
0271     if defined:
0272         return sorted(difflib.get_close_matches(symbol, set(defined), 10))
0273 
0274     pool = Pool(cpu_count(), init_worker)
0275     kfiles = []
0276     for gitfile in get_files():
0277         if REGEX_FILE_KCONFIG.match(gitfile):
0278             kfiles.append(gitfile)
0279 
0280     arglist = []
0281     for part in partition(kfiles, cpu_count()):
0282         arglist.append((part, ignore))
0283 
0284     for res in pool.map(parse_kconfig_files, arglist):
0285         defined.extend(res[0])
0286 
0287     return sorted(difflib.get_close_matches(symbol, set(defined), 10))
0288 
0289 
0290 def get_files():
0291     """Return a list of all files in the current git directory."""
0292     # use 'git ls-files' to get the worklist
0293     stdout = execute(["git", "ls-files"])
0294     if len(stdout) > 0 and stdout[-1] == "\n":
0295         stdout = stdout[:-1]
0296 
0297     files = []
0298     for gitfile in stdout.rsplit("\n"):
0299         if ".git" in gitfile or "ChangeLog" in gitfile or      \
0300                 ".log" in gitfile or os.path.isdir(gitfile) or \
0301                 gitfile.startswith("tools/"):
0302             continue
0303         files.append(gitfile)
0304     return files
0305 
0306 
0307 def check_symbols(ignore):
0308     """Find undefined Kconfig symbols and return a dict with the symbol as key
0309     and a list of referencing files as value.  Files matching %ignore are not
0310     checked for undefined symbols."""
0311     pool = Pool(cpu_count(), init_worker)
0312     try:
0313         return check_symbols_helper(pool, ignore)
0314     except KeyboardInterrupt:
0315         pool.terminate()
0316         pool.join()
0317         sys.exit(1)
0318 
0319 
0320 def check_symbols_helper(pool, ignore):
0321     """Helper method for check_symbols().  Used to catch keyboard interrupts in
0322     check_symbols() in order to properly terminate running worker processes."""
0323     source_files = []
0324     kconfig_files = []
0325     defined_symbols = []
0326     referenced_symbols = dict()  # {file: [symbols]}
0327 
0328     for gitfile in get_files():
0329         if REGEX_FILE_KCONFIG.match(gitfile):
0330             kconfig_files.append(gitfile)
0331         else:
0332             if ignore and not re.match(ignore, gitfile):
0333                 continue
0334             # add source files that do not match the ignore pattern
0335             source_files.append(gitfile)
0336 
0337     # parse source files
0338     arglist = partition(source_files, cpu_count())
0339     for res in pool.map(parse_source_files, arglist):
0340         referenced_symbols.update(res)
0341 
0342     # parse kconfig files
0343     arglist = []
0344     for part in partition(kconfig_files, cpu_count()):
0345         arglist.append((part, ignore))
0346     for res in pool.map(parse_kconfig_files, arglist):
0347         defined_symbols.extend(res[0])
0348         referenced_symbols.update(res[1])
0349     defined_symbols = set(defined_symbols)
0350 
0351     # inverse mapping of referenced_symbols to dict(symbol: [files])
0352     inv_map = dict()
0353     for _file, symbols in referenced_symbols.items():
0354         for symbol in symbols:
0355             inv_map[symbol] = inv_map.get(symbol, set())
0356             inv_map[symbol].add(_file)
0357     referenced_symbols = inv_map
0358 
0359     undefined = {}  # {symbol: [files]}
0360     for symbol in sorted(referenced_symbols):
0361         # filter some false positives
0362         if symbol == "FOO" or symbol == "BAR" or \
0363                 symbol == "FOO_BAR" or symbol == "XXX":
0364             continue
0365         if symbol not in defined_symbols:
0366             if symbol.endswith("_MODULE"):
0367                 # avoid false positives for kernel modules
0368                 if symbol[:-len("_MODULE")] in defined_symbols:
0369                     continue
0370             undefined[symbol] = referenced_symbols.get(symbol)
0371     return undefined, defined_symbols
0372 
0373 
0374 def parse_source_files(source_files):
0375     """Parse each source file in @source_files and return dictionary with source
0376     files as keys and lists of references Kconfig symbols as values."""
0377     referenced_symbols = dict()
0378     for sfile in source_files:
0379         referenced_symbols[sfile] = parse_source_file(sfile)
0380     return referenced_symbols
0381 
0382 
0383 def parse_source_file(sfile):
0384     """Parse @sfile and return a list of referenced Kconfig symbols."""
0385     lines = []
0386     references = []
0387 
0388     if not os.path.exists(sfile):
0389         return references
0390 
0391     with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
0392         lines = stream.readlines()
0393 
0394     for line in lines:
0395         if "CONFIG_" not in line:
0396             continue
0397         symbols = REGEX_SOURCE_SYMBOL.findall(line)
0398         for symbol in symbols:
0399             if not REGEX_FILTER_SYMBOLS.search(symbol):
0400                 continue
0401             references.append(symbol)
0402 
0403     return references
0404 
0405 
0406 def get_symbols_in_line(line):
0407     """Return mentioned Kconfig symbols in @line."""
0408     return REGEX_SYMBOL.findall(line)
0409 
0410 
0411 def parse_kconfig_files(args):
0412     """Parse kconfig files and return tuple of defined and references Kconfig
0413     symbols.  Note, @args is a tuple of a list of files and the @ignore
0414     pattern."""
0415     kconfig_files = args[0]
0416     ignore = args[1]
0417     defined_symbols = []
0418     referenced_symbols = dict()
0419 
0420     for kfile in kconfig_files:
0421         defined, references = parse_kconfig_file(kfile)
0422         defined_symbols.extend(defined)
0423         if ignore and re.match(ignore, kfile):
0424             # do not collect references for files that match the ignore pattern
0425             continue
0426         referenced_symbols[kfile] = references
0427     return (defined_symbols, referenced_symbols)
0428 
0429 
0430 def parse_kconfig_file(kfile):
0431     """Parse @kfile and update symbol definitions and references."""
0432     lines = []
0433     defined = []
0434     references = []
0435     skip = False
0436 
0437     if not os.path.exists(kfile):
0438         return defined, references
0439 
0440     with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
0441         lines = stream.readlines()
0442 
0443     for i in range(len(lines)):
0444         line = lines[i]
0445         line = line.strip('\n')
0446         line = line.split("#")[0]  # ignore comments
0447 
0448         if REGEX_KCONFIG_DEF.match(line):
0449             symbol_def = REGEX_KCONFIG_DEF.findall(line)
0450             defined.append(symbol_def[0])
0451             skip = False
0452         elif REGEX_KCONFIG_HELP.match(line):
0453             skip = True
0454         elif skip:
0455             # ignore content of help messages
0456             pass
0457         elif REGEX_KCONFIG_STMT.match(line):
0458             line = REGEX_QUOTES.sub("", line)
0459             symbols = get_symbols_in_line(line)
0460             # multi-line statements
0461             while line.endswith("\\"):
0462                 i += 1
0463                 line = lines[i]
0464                 line = line.strip('\n')
0465                 symbols.extend(get_symbols_in_line(line))
0466             for symbol in set(symbols):
0467                 if REGEX_NUMERIC.match(symbol):
0468                     # ignore numeric values
0469                     continue
0470                 references.append(symbol)
0471 
0472     return defined, references
0473 
0474 
0475 if __name__ == "__main__":
0476     main()