Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
251 changes: 220 additions & 31 deletions addons/misra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1765,30 +1765,154 @@ def misra_2_3(self, dumpfile, typedefInfo):
def misra_2_4(self, dumpfile, cfg):
self._save_ctu_summary_tagnames(dumpfile, cfg)

@staticmethod
def _get_active_directives(cfg):
# a condition evaluated in several inclusions of a file can have both results
results = {}
for cond in cfg.preprocessor_if_conditions:
results.setdefault((cond.file, cond.linenr), set()).add(cond.result != 0)

directives_of_file = {}
for directive in cfg.directives:
directives_of_file.setdefault(directive.file, []).append(directive)

in_active_branch = set()
for directives in directives_of_file.values():
stack = []
active = True
for directive in directives:
res = re.match(r'#\s*([a-z]*)', directive.str)
kind = res.group(1) if res else ''
if kind in ('if', 'ifdef', 'ifndef'):
values = results.get((directive.file, directive.linenr), {False, True})
stack.append([active, active and False in values])
active = active and True in values
elif kind in ('elif', 'elifdef', 'elifndef', 'else') and stack:
fallthrough = stack[-1][1]
values = {True} if kind == 'else' else results.get((directive.file, directive.linenr), {False, True})
active = fallthrough and True in values
stack[-1][1] = fallthrough and False in values
elif kind == 'endif' and stack:
active = stack.pop()[0]
elif active:
in_active_branch.add(id(directive))

def file_name(path):
return os.path.normcase(os.path.basename(path))

def included_path(directive):
# '' for an #include that does not name its file (#include MACRO)
res = re.match(r'#\s*include\b\s*(?:["<]([^">]+)[">])?', directive.str)
if not res:
return None
return res.group(1) or ''

def included_name(directive):
path = included_path(directive)
return file_name(path) if path else path

def components(path):
return os.path.normcase(os.path.normpath(path)).replace('\\', '/').split('/')

def same_end(file, path):
# the path of the dump and the path of the #include end with the same components ('..' excluded)
a = components(file)
b = [part for part in components(path) if part != '..']
n = min(len(a), len(b))
return a[-n:] == b[-n:]

found_paths = {}

def is_named(file, name):
# the dump names a header after its first inclusion, another name can reach it (hard link)
path = os.path.join(os.path.dirname(file), name)
if path not in found_paths:
found_paths[path] = os.path.exists(path)
try:
return found_paths[path] and os.path.samefile(path, file)
except OSError:
return False

dirs_of_entry = {}

def dirs_having(name):
if not dirs_of_entry:
for directory in files_of_dir:
try:
for entry in os.listdir(directory or '.'):
dirs_of_entry.setdefault(os.path.normcase(entry), []).append(directory)
except OSError:
pass
return dirs_of_entry.get(name, [])

files_of_name = {}
files_named = {}
files_of_dir = {}
for file in directives_of_file:
files_of_name.setdefault(file_name(file), []).append(file)
files_of_dir.setdefault(os.path.dirname(file), []).append(file)
included_names = set(filter(None, (included_name(directive) for directive in cfg.directives)))
active_files = set(file for file in directives_of_file if file_name(file) not in included_names)
# the directives of the source file come first
active_files.update(directive.file for directive in cfg.directives[:1])
pending = list(active_files)
while pending:
for directive in directives_of_file[pending.pop()]:
name = included_name(directive) if id(directive) in in_active_branch else None
if name == '':
files = list(directives_of_file)
elif name:
files = files_of_name.get(name)
if not files:
# a name that no file of the dump has: look once per name, in the directories of the dump only
if name not in files_named:
files_named[name] = [file for directory in dirs_having(name)
for file in files_of_dir[directory] if is_named(file, name)]
files = files_named[name]
if len(files) > 1:
# several headers of this file name: the one next to the including file for #include "...",
# else those whose path ends like the path of the #include
path = included_path(directive)
here = components(os.path.join(os.path.dirname(directive.file), path))
files = ([file for file in files if '"' in directive.str and components(file) == here] or
[file for file in files if same_end(file, path)] or files)
else:
files = []
for file in files:
if file not in active_files:
active_files.add(file)
pending.append(file)

return [directive for directive in cfg.directives if directive.file in active_files and id(directive) in in_active_branch]

def misra_2_5(self, dumpfile, cfg):
used_macros = []
unused_macro = {}
for m in cfg.macro_usage:
used_macros.append(m.name)
for directive in cfg.directives:
for directive in self._get_active_directives(cfg):
res_define = re.match(r'#define[ \t]+([a-zA-Z_][a-zA-Z_0-9]*).*', directive.str)
res_undef = re.match(r'#undef[ \t]+([a-zA-Z_][a-zA-Z_0-9]*).*', directive.str)
if res_define:
macro_name = res_define.group(1)
unused_macro[macro_name] = {'name': macro_name, 'used': (macro_name in used_macros),
'file': directive.file, 'line': directive.linenr, 'column': directive.column}
unused_macro.setdefault(macro_name, []).append({'name': macro_name, 'used': (macro_name in used_macros),
'file': directive.file, 'line': directive.linenr, 'column': directive.column})
elif res_undef:
macro_name = res_undef.group(1)
# assuming that if we have #undef, we also have #define somewhere
if macro_name in unused_macro:
unused_macro[macro_name]['used'] = True
# The definitions before an already used one are used too
for macro in reversed(unused_macro[macro_name]):
if macro['used']:
break
macro['used'] = True
else:
unused_macro[macro_name] = {'name': macro_name, 'used': True, 'file': directive.file,
'line': directive.linenr, 'column': directive.column}
unused_macro[macro_name] = [{'name': macro_name, 'used': True, 'file': directive.file,
'line': directive.linenr, 'column': directive.column}]
used_macros.append(macro_name)

if unused_macro:
cppcheckdata.reportSummary(dumpfile, 'MisraMacro', list(unused_macro.values()))
cppcheckdata.reportSummary(dumpfile, 'MisraMacro', [m for ms in unused_macro.values() for m in ms])

def misra_2_7(self, data):
for func in data.functions:
Expand Down Expand Up @@ -4898,6 +5022,7 @@ def analyse_ctu_info(self, ctu_info_files):
all_typedef_info = {}
all_tagname_info = {}
all_macro_info = {}
last_macros = {}
all_external_identifiers_decl = {}
all_external_identifiers_def = {}
all_internal_identifiers = {}
Expand All @@ -4909,19 +5034,72 @@ def analyse_ctu_info(self, ctu_info_files):
def is_different_location(loc1, loc2):
return loc1['file'] != loc2['file'] or loc1['line'] != loc2['line']

real_paths = {}

def real_path(path):
if path not in real_paths:
real_paths[path] = os.path.realpath(path)
return real_paths[path]

def is_different_file(loc1, loc2):
return loc1['file'] != loc2['file']

def add_declaration(all_info, new_info, num1, num2):
declarations = all_info.setdefault(new_info['name'], [])
for info in declarations:
if not is_different_location(info, new_info):
info['used'] = info['used'] or new_info['used']
return
if declarations:
self.reportError(Location(declarations[0]), num1, num2)
self.reportError(Location(new_info), num1, num2)
declarations.append(new_info)
def links(path):
# Numbers of components of the absolute path that are links or Windows 8.3 names, and that are in another case
count = cases = 0
p = os.path.abspath(path)
parent, name = os.path.split(p)
while name:
real = real_path(p)
if os.path.normcase(real) != os.path.normcase(os.path.join(real_path(parent), name)):
count += 1
try:
entries = os.listdir(parent)
except OSError:
entries = [name]
if name not in entries and os.path.normcase(name) in map(os.path.normcase, entries):
cases += 1
elif os.path.basename(real) != name:
cases += 1
p = parent
parent, name = os.path.split(p)
return count, cases

spelling_orders = {}

def spelling_order(path):
# The spelling with the fewest links first, then an absolute one, then the shortest, then the fewest components in another case
if path not in spelling_orders:
count, cases = links(path)
spelling_orders[path] = (count, not os.path.isabs(path), len(path), cases, path)
return spelling_orders[path]

def add_declarations(all_info, summary_data):
path = real = None
for new_info in summary_data:
# The declarations of a summary are usually grouped by file
if new_info['file'] != path:
path = new_info['file']
real = real_path(path)
key = (real, new_info['line'])
declarations = all_info.get(new_info['name'])
if declarations is None:
all_info[new_info['name']] = {key: new_info}
continue
info = declarations.get(key)
if info is None:
declarations[key] = new_info
continue
if new_info['used']:
info['used'] = True
if info['file'] != new_info['file'] and spelling_order(new_info['file']) < spelling_order(info['file']):
info['file'] = new_info['file']

def report_declarations(all_info, num1, num2):
for declarations in all_info.values():
if len(declarations) > 1:
for info in declarations.values():
self.reportError(Location(info), num1, num2)

def read_lines(filename):
with open(filename, 'rt') as f:
Expand All @@ -4937,21 +5115,16 @@ def read_lines(filename):
summary_data = s.get('data', None)

if summary_type == 'MisraTypedefInfo':
for new_typedef_info in summary_data:
add_declaration(all_typedef_info, new_typedef_info, 5, 6)
add_declarations(all_typedef_info, summary_data)

if summary_type == 'MisraTagName':
for new_tagname_info in summary_data:
add_declaration(all_tagname_info, new_tagname_info, 5, 7)
add_declarations(all_tagname_info, summary_data)

if summary_type == 'MisraMacro':
for new_macro in summary_data:
key = new_macro['name']
existing_macro = all_macro_info.get(key, None)
if existing_macro:
existing_macro['used'] = existing_macro['used'] or new_macro['used']
else:
all_macro_info[key] = new_macro
# The last definition of each name in a summary, as they were grouped by name before
for m in {m['name']: m for m in summary_data}.values():
last_macros.setdefault(m['name'], []).append(dict(m))
add_declarations(all_macro_info, summary_data)

if summary_type == 'MisraExternalIdentifiers':
for s in sorted(summary_data, key=lambda d: "%s %s %s" %(d['file'],d['line'], d['column'] )):
Expand Down Expand Up @@ -4992,16 +5165,32 @@ def read_lines(filename):

except FileNotFoundError:
return
finally:
report_declarations(all_typedef_info, 5, 6)
report_declarations(all_tagname_info, 5, 7)

unused_typedefs = [tdi for tdis in all_typedef_info.values() for tdi in tdis if not tdi['used']]
unused_typedefs = [tdi for tdis in all_typedef_info.values() for tdi in tdis.values() if not tdi['used']]
for tdi in unused_typedefs:
self.reportError(Location(tdi), 2, 3)

unused_tags = [tag for tags in all_tagname_info.values() for tag in tags if not tag['used']]
unused_tags = [tag for tags in all_tagname_info.values() for tag in tags.values() if not tag['used']]
for tag in unused_tags:
self.reportError(Location(tag), 2, 4)

unused_macros = [m for m in all_macro_info.values() if not m['used']]
found_paths = {}

def path_found(path):
if path not in found_paths:
found_paths[path] = os.path.exists(path)
return found_paths[path]

unused_macros = []
for name, macros in all_macro_info.items():
if all(path_found(real) for real, _ in macros):
unused_macros += [m for m in macros.values() if not m['used']]
elif not any(m['used'] for m in last_macros[name]):
# A path not found from here, for example with --relative-paths: the definitions are grouped by name as before
unused_macros.append(min(last_macros[name], key=lambda m: (spelling_order(m['file']), m['line'])))
for m in unused_macros:
self.reportError(Location(m), 2, 5)

Expand Down
Loading
Loading