Repository navigation
Fix #15214, #13957 (misra.py: 2.5 for a macro defined in several files or in an inactive branch) #9059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix #15214, #13957 (misra.py: 2.5 for a macro defined in several files or in an inactive branch) #9059
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1765,30 +1765,163 @@ 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]) | ||
| # a file that defines an expanded macro was read, also when no #include reaches it (--include) | ||
| active_files.update(m.file for m in cfg.macro_usage if m.file in directives_of_file) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AI review This line counts a file as active only when one of its macros is expanded ( printf '#define M 1\n' > h.h
printf '#if 0\n#include "h.h"\n#endif\n#undef M\nint a1(void);\n' > a.c
printf '#include "h.h"\nint b1(void);\n' > b.c
cppcheck -q --template='{file}:{line}:{id}' --addon=misra --enable=style --suppress=misra-c2012-8.4 --suppress=misra-c2012-8.7 --suppress=misra-c2012-20.5 --include=h.h a.c b.cPR: One way to fix it: also count as active the files that define a name that an active
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Two tests now cover it, |
||
| # so is a file that defines a name that an active #undef names | ||
| defining_files = {} | ||
| for directive in cfg.directives: | ||
| res = re.match(r'#\s*define\s+([a-zA-Z_][a-zA-Z_0-9]*)', directive.str) if id(directive) in in_active_branch else None | ||
| if res: | ||
| defining_files.setdefault(res.group(1), set()).add(directive.file) | ||
| 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AI review When the header is not next to the including file, as with printf '#define M 1\n' > inc/config.h
printf '#define M 2\n' > other/config.h
printf '#if 0\n#include "../other/config.h"\n#endif\n#include <config.h>\nint a1(void);\n' > src/a.c
printf '#include <config.h>\nint x = M;\n' > src/b.c
cppcheck -q --template='{file}:{line}:{id}' --addon=misra --enable=style --suppress=misra-c2012-8.4 --suppress=misra-c2012-8.7 -Iinc src/a.c src/b.cPR: This is the #13957 case that the PR is meant to fix. One possible fix: when several candidates match, leave out the files that an inactive |
||
| else: | ||
| res = re.match(r'#\s*undef\s+([a-zA-Z_][a-zA-Z_0-9]*)', directive.str) if id(directive) in in_active_branch else None | ||
| files = defining_files.get(res.group(1), ()) if res else () | ||
| 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: | ||
|
|
@@ -4898,6 +5031,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 = {} | ||
|
|
@@ -4909,19 +5043,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: | ||
|
|
@@ -4937,21 +5124,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'] )): | ||
|
|
@@ -4992,16 +5174,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) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AI review
A header forced with
--includehas no#includedirective in the dump. If its file name is also the name of an#includethat reaches another header, or one that is inactive, the header is treated as inactive and its definitions are left out of this TU's summary. Because macros are now merged by location, this is no longer only a false negative: if another TU includes the same header normally and does not use the macro, the macro is reported as unused.PR:
inc/config.h:1:misra-c2012-2.5. Base: no output.The file of the dump's
macro-usageentries could mark a file as active. That is the definition that was really used, hereinc/config.h:1. Another option is to treat the--includefiles as active.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Two tests now cover it,
test_ctu_macro_forced_header_same_name_as_included_headerandtest_ctu_macro_forced_header_included_in_inactive_branch. Both fail with the previous version of_get_active_directives()(inc/config.h:1:misra-c2012-2.5) and pass with the new one. Fixed in d7a9bd3: a file that defines a macro the source file expands is active.