blob: ce9ca60808b8ac82034d574009ed8d0878eb847c [file] [log] [blame]
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02001#!/usr/bin/env python
2
Valentin Rothbergb1a3f242015-03-16 12:16:14 +01003"""Find Kconfig symbols that are referenced but not defined."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02004
Valentin Rothberg208d5112015-02-25 15:15:23 +01005# (c) 2014-2015 Valentin Rothberg <Valentin.Rothberg@lip6.fr>
Valentin Rothbergcc641d52014-11-08 20:56:35 +01006# (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02007#
Valentin Rothbergcc641d52014-11-08 20:56:35 +01008# Licensed under the terms of the GNU GPL License version 2
Valentin Rothberg24fe1f02014-09-27 16:30:45 +02009
10
11import os
12import re
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010013import sys
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020014from subprocess import Popen, PIPE, STDOUT
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010015from optparse import OptionParser
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020016
Valentin Rothbergcc641d52014-11-08 20:56:35 +010017
18# regex expressions
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020019OPERATORS = r"&|\(|\)|\||\!"
Valentin Rothbergcc641d52014-11-08 20:56:35 +010020FEATURE = r"(?:\w*[A-Z0-9]\w*){2,}"
21DEF = r"^\s*(?:menu){,1}config\s+(" + FEATURE + r")\s*"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020022EXPR = r"(?:" + OPERATORS + r"|\s|" + FEATURE + r")+"
23STMT = r"^\s*(?:if|select|depends\s+on)\s+" + EXPR
Valentin Rothbergcc641d52014-11-08 20:56:35 +010024SOURCE_FEATURE = r"(?:\W|\b)+[D]{,1}CONFIG_(" + FEATURE + r")"
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020025
Valentin Rothbergcc641d52014-11-08 20:56:35 +010026# regex objects
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020027REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
28REGEX_FEATURE = re.compile(r"(" + FEATURE + r")")
Valentin Rothbergcc641d52014-11-08 20:56:35 +010029REGEX_SOURCE_FEATURE = re.compile(SOURCE_FEATURE)
30REGEX_KCONFIG_DEF = re.compile(DEF)
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020031REGEX_KCONFIG_EXPR = re.compile(EXPR)
32REGEX_KCONFIG_STMT = re.compile(STMT)
33REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
34REGEX_FILTER_FEATURES = re.compile(r"[A-Za-z0-9]$")
35
36
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010037def parse_options():
38 """The user interface of this module."""
39 usage = "%prog [options]\n\n" \
40 "Run this tool to detect Kconfig symbols that are referenced but " \
41 "not defined in\nKconfig. The output of this tool has the " \
42 "format \'Undefined symbol\\tFile list\'\n\n" \
43 "If no option is specified, %prog will default to check your\n" \
44 "current tree. Please note that specifying commits will " \
45 "\'git reset --hard\'\nyour current tree! You may save " \
46 "uncommitted changes to avoid losing data."
47
48 parser = OptionParser(usage=usage)
49
50 parser.add_option('-c', '--commit', dest='commit', action='store',
51 default="",
52 help="Check if the specified commit (hash) introduces "
53 "undefined Kconfig symbols.")
54
55 parser.add_option('-d', '--diff', dest='diff', action='store',
56 default="",
57 help="Diff undefined symbols between two commits. The "
58 "input format bases on Git log's "
59 "\'commmit1..commit2\'.")
60
61 parser.add_option('', '--force', dest='force', action='store_true',
62 default=False,
63 help="Reset current Git tree even when it's dirty.")
64
65 (opts, _) = parser.parse_args()
66
67 if opts.commit and opts.diff:
68 sys.exit("Please specify only one option at once.")
69
70 if opts.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", opts.diff):
71 sys.exit("Please specify valid input in the following format: "
72 "\'commmit1..commit2\'")
73
74 if opts.commit or opts.diff:
75 if not opts.force and tree_is_dirty():
76 sys.exit("The current Git tree is dirty (see 'git status'). "
77 "Running this script may\ndelete important data since it "
78 "calls 'git reset --hard' for some performance\nreasons. "
79 " Please run this script in a clean Git tree or pass "
80 "'--force' if you\nwant to ignore this warning and "
81 "continue.")
82
83 return opts
84
85
Valentin Rothberg24fe1f02014-09-27 16:30:45 +020086def main():
87 """Main function of this module."""
Valentin Rothbergb1a3f242015-03-16 12:16:14 +010088 opts = parse_options()
89
90 if opts.commit or opts.diff:
91 head = get_head()
92
93 # get commit range
94 commit_a = None
95 commit_b = None
96 if opts.commit:
97 commit_a = opts.commit + "~"
98 commit_b = opts.commit
99 elif opts.diff:
100 split = opts.diff.split("..")
101 commit_a = split[0]
102 commit_b = split[1]
103 undefined_a = {}
104 undefined_b = {}
105
106 # get undefined items before the commit
107 execute("git reset --hard %s" % commit_a)
108 undefined_a = check_symbols()
109
110 # get undefined items for the commit
111 execute("git reset --hard %s" % commit_b)
112 undefined_b = check_symbols()
113
114 # report cases that are present for the commit but not before
115 for feature in undefined_b:
116 # feature has not been undefined before
117 if not feature in undefined_a:
118 files = undefined_b.get(feature)
119 print "%s\t%s" % (feature, ", ".join(files))
120 # check if there are new files that reference the undefined feature
121 else:
122 files = undefined_b.get(feature) - undefined_a.get(feature)
123 if files:
124 print "%s\t%s" % (feature, ", ".join(files))
125
126 # reset to head
127 execute("git reset --hard %s" % head)
128
129 # default to check the entire tree
130 else:
131 undefined = check_symbols()
132 for feature in undefined:
133 files = undefined.get(feature)
134
135
136def execute(cmd):
137 """Execute %cmd and return stdout. Exit in case of error."""
138 pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
139 (stdout, _) = pop.communicate() # wait until finished
140 if pop.returncode != 0:
141 sys.exit(stdout)
142 return stdout
143
144
145def tree_is_dirty():
146 """Return true if the current working tree is dirty (i.e., if any file has
147 been added, deleted, modified, renamed or copied but not committed)."""
148 stdout = execute("git status --porcelain")
149 for line in stdout:
150 if re.findall(r"[URMADC]{1}", line[:2]):
151 return True
152 return False
153
154
155def get_head():
156 """Return commit hash of current HEAD."""
157 stdout = execute("git rev-parse HEAD")
158 return stdout.strip('\n')
159
160
161def check_symbols():
162 """Find undefined Kconfig symbols and return a dict with the symbol as key
163 and a list of referencing files as value."""
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200164 source_files = []
165 kconfig_files = []
166 defined_features = set()
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100167 referenced_features = dict() # {feature: [files]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200168
169 # use 'git ls-files' to get the worklist
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100170 stdout = execute("git ls-files")
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200171 if len(stdout) > 0 and stdout[-1] == "\n":
172 stdout = stdout[:-1]
173
174 for gitfile in stdout.rsplit("\n"):
Valentin Rothberg208d5112015-02-25 15:15:23 +0100175 if ".git" in gitfile or "ChangeLog" in gitfile or \
176 ".log" in gitfile or os.path.isdir(gitfile) or \
177 gitfile.startswith("tools/"):
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200178 continue
179 if REGEX_FILE_KCONFIG.match(gitfile):
180 kconfig_files.append(gitfile)
181 else:
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100182 # all non-Kconfig files are checked for consistency
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200183 source_files.append(gitfile)
184
185 for sfile in source_files:
186 parse_source_file(sfile, referenced_features)
187
188 for kfile in kconfig_files:
189 parse_kconfig_file(kfile, defined_features, referenced_features)
190
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100191 undefined = {} # {feature: [files]}
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200192 for feature in sorted(referenced_features):
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100193 # filter some false positives
194 if feature == "FOO" or feature == "BAR" or \
195 feature == "FOO_BAR" or feature == "XXX":
196 continue
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200197 if feature not in defined_features:
198 if feature.endswith("_MODULE"):
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100199 # avoid false positives for kernel modules
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200200 if feature[:-len("_MODULE")] in defined_features:
201 continue
Valentin Rothbergb1a3f242015-03-16 12:16:14 +0100202 undefined[feature] = referenced_features.get(feature)
203 return undefined
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200204
205
206def parse_source_file(sfile, referenced_features):
207 """Parse @sfile for referenced Kconfig features."""
208 lines = []
209 with open(sfile, "r") as stream:
210 lines = stream.readlines()
211
212 for line in lines:
213 if not "CONFIG_" in line:
214 continue
215 features = REGEX_SOURCE_FEATURE.findall(line)
216 for feature in features:
217 if not REGEX_FILTER_FEATURES.search(feature):
218 continue
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100219 sfiles = referenced_features.get(feature, set())
220 sfiles.add(sfile)
221 referenced_features[feature] = sfiles
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200222
223
224def get_features_in_line(line):
225 """Return mentioned Kconfig features in @line."""
226 return REGEX_FEATURE.findall(line)
227
228
229def parse_kconfig_file(kfile, defined_features, referenced_features):
230 """Parse @kfile and update feature definitions and references."""
231 lines = []
232 skip = False
233
234 with open(kfile, "r") as stream:
235 lines = stream.readlines()
236
237 for i in range(len(lines)):
238 line = lines[i]
239 line = line.strip('\n')
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100240 line = line.split("#")[0] # ignore comments
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200241
242 if REGEX_KCONFIG_DEF.match(line):
243 feature_def = REGEX_KCONFIG_DEF.findall(line)
244 defined_features.add(feature_def[0])
245 skip = False
246 elif REGEX_KCONFIG_HELP.match(line):
247 skip = True
248 elif skip:
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100249 # ignore content of help messages
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200250 pass
251 elif REGEX_KCONFIG_STMT.match(line):
252 features = get_features_in_line(line)
Valentin Rothbergcc641d52014-11-08 20:56:35 +0100253 # multi-line statements
Valentin Rothberg24fe1f02014-09-27 16:30:45 +0200254 while line.endswith("\\"):
255 i += 1
256 line = lines[i]
257 line = line.strip('\n')
258 features.extend(get_features_in_line(line))
259 for feature in set(features):
260 paths = referenced_features.get(feature, set())
261 paths.add(kfile)
262 referenced_features[feature] = paths
263
264
265if __name__ == "__main__":
266 main()