diff --git a/addons/misra.py b/addons/misra.py index b337d2dfa5f..001795a6bb8 100755 --- a/addons/misra.py +++ b/addons/misra.py @@ -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: @@ -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 = {} @@ -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: @@ -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'] )): @@ -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) diff --git a/addons/test/misra_test.py b/addons/test/misra_test.py index 1ff63879efe..55e88773f04 100644 --- a/addons/test/misra_test.py +++ b/addons/test/misra_test.py @@ -7,6 +7,10 @@ import sys import os import json +import subprocess +import ctypes +from types import SimpleNamespace +from unittest import mock from .util import dump_create, dump_remove, convert_json_output from addons.misra import C11_STDLIB_IDENTIFIERS, C99_STDLIB_IDENTIFIERS,C90_STDLIB_IDENTIFIERS, isStdLibId, isKeyword @@ -192,10 +196,15 @@ def test_read_ctu_info_line(checker): ('MisraTypedefInfo', 203, False), ('MisraTypedefInfo', 203, True), ('MisraTagName', 204, False), - ('MisraTagName', 204, True) + ('MisraTagName', 204, True), + ('MisraMacro', 205, False), + ('MisraMacro', 205, True) ]) -def test_ctu_unused_declaration(checker, tmp_path, summary, rule, used_first): +def test_ctu_unused_declaration(checker, tmp_path, monkeypatch, summary, rule, used_first): # The same name declared in two files, unused in a.c and used in b.c + (tmp_path / 'a.c').write_text('') + (tmp_path / 'b.c').write_text('') + monkeypatch.chdir(str(tmp_path)) unused = {'name': 'X', 'file': 'a.c', 'line': 1, 'column': 13, 'used': False} used = {'name': 'X', 'file': 'b.c', 'line': 1, 'column': 13, 'used': True} ctu_info = tmp_path / 'test.ctu-info' @@ -206,6 +215,938 @@ def test_ctu_unused_declaration(checker, tmp_path, summary, rule, used_first): assert 'a.c-1-13-%d' % rule in checker.existing_violations assert 'b.c-1-13-%d' % rule not in checker.existing_violations +@pytest.mark.parametrize('summary', ['MisraTypedefInfo', 'MisraTagName', 'MisraMacro']) +def test_ctu_declaration_path_spelling(checker, tmp_path, summary): + # The same declaration in h.h, reached through a relative and an absolute path + unused = {'name': 'X', 'file': 'h.h', 'line': 1, 'column': 13, 'used': False} + used = {'name': 'X', 'file': os.path.abspath('h.h'), 'line': 1, 'column': 13, 'used': True} + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for declaration in [unused, used]: + f.write(json.dumps({'summary': summary, 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert not checker.existing_violations + +@pytest.mark.parametrize('summary,rule', [('MisraTypedefInfo', 203), ('MisraTagName', 204), ('MisraMacro', 205)]) +@pytest.mark.parametrize('relative_first', [True, False]) +def test_ctu_declaration_path_spelling_reported(checker, tmp_path, summary, rule, relative_first): + # The absolute spelling of h.h is reported, whatever the order of the ctu-info lines + paths = ['h.h', os.path.abspath('h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if relative_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': summary, 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-%d' % (os.path.abspath('h.h'), rule)} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('relative_first', [True, False]) +def test_ctu_declaration_other_case_reported(checker, tmp_path, monkeypatch, relative_first): + # The absolute spelling of inc/h.h with another case is reported + (tmp_path / 'inc').mkdir() + monkeypatch.chdir(str(tmp_path)) + paths = ['inc/h.h', str(tmp_path / 'INC' / 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if relative_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[1]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('real_name,other_name', [('h.h', 'H.h'), ('H.h', 'h.h')]) +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported(checker, tmp_path, real_name, other_name, real_first): + # Two absolute spellings of a header that differ only by case, the real case is reported + (tmp_path / real_name).write_text('') + real = os.path.realpath(str(tmp_path / real_name)) + paths = [real, os.path.join(os.path.dirname(real), other_name)] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % real} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported_relative(checker, tmp_path, monkeypatch, real_first): + # Two relative spellings of inc/h.h that differ only by case + (tmp_path / 'inc').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + paths = ['inc/h.h', 'INC/h.h'] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('short_first', [True, False]) +def test_ctu_declaration_shortest_before_real_case_reported(checker, tmp_path, monkeypatch, short_first): + # Two relative spellings of inc/h.h, the shorter one in another case is reported before the longer one in the real case + (tmp_path / 'inc').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + paths = ['INC/h.h', './inc/h.h'] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if short_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported_lower_case_drive_absolute(checker, tmp_path, real_first): + # Two absolute spellings of inc/h.h that differ only by case, the real one with a lower case drive letter + (tmp_path / 'inc').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('') + d = os.path.realpath(str(tmp_path)) + paths = [os.path.join(d[0].lower() + d[1:], 'inc', 'h.h'), os.path.join(d, 'INC', 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported_through_junction(checker, tmp_path, real_first): + # Two spellings of inc/h.h through the same junction that differ only by case + (tmp_path / 'real' / 'inc').mkdir(parents=True) + (tmp_path / 'real' / 'inc' / 'h.h').write_text('') + (tmp_path / 'sub').mkdir() + subprocess.run(['cmd', '/c', 'mklink', '/J', str(tmp_path / 'sub' / 'j'), str(tmp_path / 'real')], check=True, stdout=subprocess.DEVNULL) + paths = [str(tmp_path / 'sub' / 'j' / 'inc' / 'h.h'), str(tmp_path / 'sub' / 'j' / 'INC' / 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported_through_junction_parent_case(checker, tmp_path, real_first): + # The directory of the junction and the one of its target differ only by case + (tmp_path / 'Src' / 'lib' / 'inc').mkdir(parents=True) + (tmp_path / 'Src' / 'lib' / 'inc' / 'h.h').write_text('') + (tmp_path / 'w' / 'SRC').mkdir(parents=True) + subprocess.run(['cmd', '/c', 'mklink', '/J', str(tmp_path / 'w' / 'SRC' / 'lib'), str(tmp_path / 'Src' / 'lib')], check=True, stdout=subprocess.DEVNULL) + paths = [str(tmp_path / 'w' / 'SRC' / 'lib' / 'inc' / 'h.h'), str(tmp_path / 'w' / 'SRC' / 'lib' / 'INC' / 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('junction,target', [('l', 'inc'), (os.path.join('w', 'k'), os.path.join('deep', 'x', 'inc'))]) +@pytest.mark.parametrize('real_first', [True, False]) +def test_ctu_declaration_real_case_reported_junction_name(checker, tmp_path, junction, target, real_first): + # Two spellings of h.h through a junction that differ only by the case of their first component + (tmp_path / target).mkdir(parents=True) + (tmp_path / target / 'h.h').write_text('') + (tmp_path / junction).parent.mkdir(exist_ok=True) + subprocess.run(['cmd', '/c', 'mklink', '/J', str(tmp_path / junction), str(tmp_path / target)], check=True, stdout=subprocess.DEVNULL) + paths = [str(tmp_path / junction / 'h.h'), str(tmp_path / (junction[0].upper() + junction[1:]) / 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if real_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +@pytest.mark.parametrize('component', ['directory', 'file']) +@pytest.mark.parametrize('short_first', [True, False]) +def test_ctu_declaration_8dot3_spelling_reported(checker, tmp_path, component, short_first): + # The same header through a Windows 8.3 name (directory or file) and through its long name, the long name is reported + (tmp_path / 'include_directory').mkdir() + (tmp_path / 'include_directory' / 'long_header_name.h').write_text('') + real = os.path.join(os.path.realpath(str(tmp_path)), 'include_directory', 'long_header_name.h') + long_name = os.path.dirname(real) if component == 'directory' else real + buf = ctypes.create_unicode_buffer(32768) + ctypes.windll.kernel32.GetShortPathNameW(long_name, buf, len(buf)) + if not os.path.exists(buf.value) or buf.value.lower() == long_name.lower(): + pytest.skip('8.3 names are not available') + short = os.path.join(buf.value, 'long_header_name.h') if component == 'directory' else buf.value + paths = [short, real] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for p in (paths if short_first else reversed(paths)): + data = [{'name': 'X', 'file': p, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % real} + +@pytest.mark.parametrize('order', [(0, 1, 2), (1, 2, 0), (2, 0, 1)]) +def test_ctu_declaration_conflict_path_spelling(checker, tmp_path, order): + # A typedef declared in h.h, reached through two spellings, and in other.h + paths = ['h.h', os.path.abspath('h.h'), 'other.h'] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for i in order: + data = [{'name': 'X', 'file': paths[i], 'line': 1, 'column': 13, 'used': True}] + f.write(json.dumps({'summary': 'MisraTypedefInfo', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-506' % os.path.abspath('h.h'), 'other.h-1-13-506'} + +@pytest.mark.parametrize('summary,rule', [('MisraTypedefInfo', 506), ('MisraTagName', 507)]) +def test_ctu_declaration_conflict_missing_ctu_info(checker, tmp_path, summary, rule): + # The same name declared in a.c and in b.c, then a ctu-info file that does not exist + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in ['a.c', 'b.c']: + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': True}] + f.write(json.dumps({'summary': summary, 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info), str(tmp_path / 'missing.ctu-info')]) + assert checker.existing_violations == {'a.c-1-13-%d' % rule, 'b.c-1-13-%d' % rule} + +def test_ctu_declaration_symlink(checker, tmp_path): + # The same declaration in h.h, reached through a symbolic link + header = tmp_path / 'h.h' + header.write_text('') + try: + os.symlink(str(header), str(tmp_path / 'link.h')) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + unused = {'name': 'X', 'file': str(header), 'line': 1, 'column': 13, 'used': False} + used = {'name': 'X', 'file': str(tmp_path / 'link.h'), 'line': 1, 'column': 13, 'used': True} + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for declaration in [unused, used]: + f.write(json.dumps({'summary': 'MisraMacro', 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert not checker.existing_violations + +@pytest.mark.parametrize('summary', ['MisraTypedefInfo', 'MisraTagName', 'MisraMacro']) +def test_ctu_declaration_link_spelling(checker, tmp_path, monkeypatch, summary): + # h.h reached through inc and through the link l, used through inc only + real = str(tmp_path / 'inc' / 'h.h') + link = str(tmp_path / 'l' / 'h.h') + monkeypatch.setattr(os.path, 'realpath', lambda path: real if path == link else path) + used = {'name': 'X', 'file': real, 'line': 1, 'column': 13, 'used': True} + unused = {'name': 'X', 'file': link, 'line': 1, 'column': 13, 'used': False} + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for declaration in [used, unused]: + f.write(json.dumps({'summary': summary, 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert not checker.existing_violations + +@pytest.mark.parametrize('summary,rule', [('MisraTypedefInfo', 203), ('MisraTagName', 204), ('MisraMacro', 205)]) +@pytest.mark.parametrize('link_first', [True, False]) +def test_ctu_declaration_link_spelling_reported(checker, tmp_path, monkeypatch, summary, rule, link_first): + # h.h reached through a link shorter than its real path, the real path is reported + real = str(tmp_path / 'inc' / 'h.h') + link = str(tmp_path / 'l' / 'h.h') + monkeypatch.setattr(os.path, 'realpath', lambda path: real if path == link else path) + paths = [link, real] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if link_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': summary, 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-%d' % (real, rule)} + +@pytest.mark.parametrize('short_first', [True, False]) +def test_ctu_declaration_shortest_spelling_reported(checker, tmp_path, short_first): + # Two relative spellings of h.h, the shortest is reported + paths = ['h.h', os.path.join('a', '..', 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if short_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'h.h-1-13-205'} + +@pytest.mark.parametrize('a_first', [True, False]) +def test_ctu_declaration_same_length_spelling_reported(checker, tmp_path, a_first): + # Two relative spellings of h.h of the same length, the same one is reported whatever their order + paths = [os.path.join('a', '..', 'h.h'), os.path.join('b', '..', 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if a_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[0]} + +@pytest.mark.parametrize('link_first', [True, False]) +def test_ctu_declaration_relative_real_spelling_reported(checker, tmp_path, monkeypatch, link_first): + # h.h reached through an absolute link and a relative spelling of its real path, the relative one is reported + link = str(tmp_path / 'l' / 'h.h') + monkeypatch.setattr(os.path, 'realpath', lambda path: os.path.abspath('h.h') if path in (link, 'h.h') else path) + paths = [link, 'h.h'] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if link_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'h.h-1-13-205'} + +@pytest.mark.parametrize('link_first', [True, False]) +def test_ctu_declaration_link_spelling_reported_linked_directory(checker, tmp_path, monkeypatch, link_first): + # h.h reached through top/inc and through the shorter top/l, where top and l are links, top/inc/h.h is reported + top = str(tmp_path / 'top') + real = str(tmp_path) + def fake_realpath(path): + if path.startswith(top): + path = real + path[len(top):] + return path.replace(os.path.join(real, 'l'), os.path.join(real, 'inc')) + monkeypatch.setattr(os.path, 'realpath', fake_realpath) + paths = [os.path.join(top, 'l', 'h.h'), os.path.join(top, 'inc', 'h.h')] + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for path in (paths if link_first else reversed(paths)): + data = [{'name': 'X', 'file': path, 'line': 1, 'column': 13, 'used': False}] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-1-13-205' % paths[1]} + +def test_ctu_realpath_called_once_per_path(checker, tmp_path, monkeypatch): + # The same macros in h.h reached from 20 translation units + (tmp_path / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + calls = [] + def counting_realpath(path): + calls.append(path) + return path + monkeypatch.setattr(os.path, 'realpath', counting_realpath) + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for _ in range(20): + data = [{'name': 'M%d' % i, 'file': 'h.h', 'line': i + 1, 'column': 9, 'used': False} for i in range(10)] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert len(checker.existing_violations) == 10 + assert calls == ['h.h'] + +def test_ctu_macro_header_name_looked_up_once(checker, tmp_path, monkeypatch): + # 100 headers include , which exists but is not in the dump + (tmp_path / 'stdint.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + n = 100 + directives = [SimpleNamespace(file='a.c', linenr=i + 1, column=1, str='#include "h%d.h"' % i) for i in range(n)] + for i in range(n): + directives.append(SimpleNamespace(file='h%d.h' % i, linenr=1, column=1, str='#include ')) + directives.append(SimpleNamespace(file='h%d.h' % i, linenr=2, column=1, str='#define H%d 1' % i)) + samefile = mock.Mock(wraps=os.path.samefile) + monkeypatch.setattr(os.path, 'samefile', samefile) + cfg = SimpleNamespace(directives=directives, preprocessor_if_conditions=[]) + active = checker._get_active_directives(cfg) + assert len([d for d in active if d.str.startswith('#define')]) == n + assert samefile.call_count <= 2 * n + +def test_ctu_macro_absent_header_names_looked_up_once(checker, tmp_path, monkeypatch): + # 100 headers of one directory, each including a header of its own that is not in the dump + monkeypatch.chdir(str(tmp_path)) + n = 100 + directives = [SimpleNamespace(file='a.c', linenr=i + 1, column=1, str='#include "h%d.h"' % i) for i in range(n)] + for i in range(n): + directives.append(SimpleNamespace(file='h%d.h' % i, linenr=1, column=1, str='#include ' % i)) + directives.append(SimpleNamespace(file='h%d.h' % i, linenr=2, column=1, str='#define H%d 1' % i)) + join = mock.Mock(wraps=os.path.join) + monkeypatch.setattr(os.path, 'join', join) + cfg = SimpleNamespace(directives=directives, preprocessor_if_conditions=[]) + active = checker._get_active_directives(cfg) + assert len([d for d in active if d.str.startswith('#define')]) == n + assert join.call_count <= 3 * n + +def test_ctu_macro_absent_header_names_many_directories(checker, tmp_path, monkeypatch): + # 100 headers in as many directories, each including a header of its own that is not in the dump + monkeypatch.chdir(str(tmp_path)) + n = 100 + directives = [SimpleNamespace(file='a.c', linenr=i + 1, column=1, str='#include "d%d/h%d.h"' % (i, i)) for i in range(n)] + for i in range(n): + (tmp_path / ('d%d' % i)).mkdir() + (tmp_path / ('d%d' % i) / ('h%d.h' % i)).write_text('') + directives.append(SimpleNamespace(file='d%d/h%d.h' % (i, i), linenr=1, column=1, str='#include ' % i)) + directives.append(SimpleNamespace(file='d%d/h%d.h' % (i, i), linenr=2, column=1, str='#define H%d 1' % i)) + exists = mock.Mock(wraps=os.path.exists) + monkeypatch.setattr(os.path, 'exists', exists) + cfg = SimpleNamespace(directives=directives, preprocessor_if_conditions=[]) + active = checker._get_active_directives(cfg) + assert len([d for d in active if d.str.startswith('#define')]) == n + assert exists.call_count <= 3 * n + +def test_ctu_macro_several_definitions(checker, tmp_path): + config_h = SimpleNamespace(str='#define BUFSIZE 2', file='config.h', linenr=1, column=1) + defaults_h = SimpleNamespace(str='#define BUFSIZE 5', file='defaults.h', linenr=2, column=1) + a = SimpleNamespace(macro_usage=[SimpleNamespace(name='BUFSIZE')], directives=[config_h, defaults_h], preprocessor_if_conditions=[]) + b = SimpleNamespace(macro_usage=[], directives=[config_h], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), a) + checker.misra_2_5(str(tmp_path / 'b.c.dump'), b) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info'), str(tmp_path / 'b.c.ctu-info')]) + assert not checker.existing_violations + +def test_ctu_macro_unused(checker, tmp_path): + unused = SimpleNamespace(str='#define UNUSED 1', file='h.h', linenr=3, column=9) + cfg = SimpleNamespace(macro_usage=[], directives=[unused], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h.h-3-9-205'} + +def test_ctu_macro_same_name_source_and_header(checker, tmp_path, monkeypatch): + # a.c defines M and includes h.h, which defines M too, the directives of a.c come first + (tmp_path / 'a.c').write_text('') + (tmp_path / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + defined_a = SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9) + defined_h = SimpleNamespace(str='#define M 1', file='h.h', linenr=1, column=9) + cfg = SimpleNamespace(macro_usage=[], directives=[defined_a, defined_h], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-2-9-205', 'h.h-1-9-205'} + +@pytest.mark.parametrize('exists', [True, False]) +def test_ctu_macro_undef_counts_as_use(checker, tmp_path, monkeypatch, exists): + # The result is the same when h1.h and h2.h are not found from the current directory, for example with --relative-paths + if exists: + for name in ('h1.h', 'h2.h', 'a.c'): + (tmp_path / name).write_text('') + monkeypatch.chdir(str(tmp_path)) + defined_1 = SimpleNamespace(str='#define X 1', file='h1.h', linenr=1, column=9) + defined_2 = SimpleNamespace(str='#define X 2', file='h2.h', linenr=1, column=9) + undefined = SimpleNamespace(str='#undef X', file='a.c', linenr=3, column=8) + cfg = SimpleNamespace(macro_usage=[], directives=[defined_1, defined_2, undefined], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +@pytest.mark.parametrize('exists', [True, False]) +def test_ctu_macro_undef_before_define(checker, tmp_path, monkeypatch, exists): + # The directives of a.c can come before those of the headers it includes + if exists: + for name in ('a.c', 'h.h'): + (tmp_path / name).write_text('') + monkeypatch.chdir(str(tmp_path)) + undefined = SimpleNamespace(str='#undef X', file='a.c', linenr=2, column=8) + defined = SimpleNamespace(str='#define X 1', file='h.h', linenr=1, column=9) + cfg = SimpleNamespace(macro_usage=[], directives=[undefined, defined], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +@pytest.mark.parametrize('exists', [True, False]) +def test_ctu_macro_defined_again_after_undef(checker, tmp_path, monkeypatch, exists): + # h.h not found from the current directory, for example with --relative-paths, gives the same finding + if exists: + (tmp_path / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + defined_1 = SimpleNamespace(str='#define X 1', file='h.h', linenr=1, column=9) + undefined_1 = SimpleNamespace(str='#undef X', file='h.h', linenr=2, column=8) + defined_2 = SimpleNamespace(str='#define X 2', file='h.h', linenr=3, column=9) + undefined_2 = SimpleNamespace(str='#undef X', file='h.h', linenr=4, column=8) + defined_3 = SimpleNamespace(str='#define X 3', file='h.h', linenr=5, column=9) + cfg = SimpleNamespace(macro_usage=[], directives=[defined_1, undefined_1, defined_2, undefined_2, defined_3], preprocessor_if_conditions=[]) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h.h-5-9-205'} + +@pytest.mark.parametrize('result,line', [(1, 2), (0, 4)]) +def test_ctu_macro_inactive_branch(checker, tmp_path, monkeypatch, result, line): + (tmp_path / 'a.c').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='#else', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define M 2', file='a.c', linenr=4, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=5, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=result)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-%d-9-205' % line} + +@pytest.mark.parametrize('nested', [ + ['#if 1', '#define M 1', '#endif'], + ['#if 1', '#endif', '#define M 1'], + ['#if 1', '#else', '#define M 1', '#endif']]) +def test_ctu_macro_nested_in_inactive_branch(checker, tmp_path, nested): + # the condition of a nested #if in an inactive branch is not evaluated, its #endif and #else do not make the branch active + lines = ['#if 0'] + nested + ['#endif'] + directives = [SimpleNamespace(str=line, file='a.c', linenr=i + 1, column=9) for i, line in enumerate(lines)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +def test_ctu_macro_else_nested_in_inactive_branch(checker, tmp_path): + # #if 0 / #ifdef A / #define N1 / #else / #define N2 / #endif / #else / #define N3 / #endif: only N3 is active + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#ifdef A', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#define N1 1', file='a.c', linenr=3, column=9), + SimpleNamespace(str='#else', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define N2 1', file='a.c', linenr=5, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=6, column=1), + SimpleNamespace(str='#else', file='a.c', linenr=7, column=1), + SimpleNamespace(str='#define N3 1', file='a.c', linenr=8, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=9, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-8-9-205'} + +def test_ctu_macro_after_nested_endif_in_inactive_branch(checker, tmp_path): + # #if 0 / #ifdef A / #endif / #define N1 / #endif / #define N2: N1 is still inactive after the nested #endif + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#ifdef A', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define N1 1', file='a.c', linenr=4, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define N2 1', file='a.c', linenr=6, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-6-9-205'} + +@pytest.mark.parametrize('results,line', [([1], 2), ([0, 1], 4), ([0, 0, 1], 6), ([0, 0, 0], 8)]) +def test_ctu_macro_elifdef_branch(checker, tmp_path, results, line): + # the dump has no result for the conditions after the first one that is true + directives = [SimpleNamespace(str='#ifdef A', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='#elifdef B', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define M 2', file='a.c', linenr=4, column=9), + SimpleNamespace(str='#elifndef C', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 3', file='a.c', linenr=6, column=9), + SimpleNamespace(str='#else', file='a.c', linenr=7, column=1), + SimpleNamespace(str='#define M 4', file='a.c', linenr=8, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=9, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=linenr, result=result) for linenr, result in zip([1, 3, 5], results)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-%d-9-205' % line} + +def test_ctu_macro_spaced_directives(checker, tmp_path): + # the dump keeps the space of '# if' and '# include' + directives = [SimpleNamespace(str='# if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='# include "h.h"', file='a.c', linenr=3, column=1), + SimpleNamespace(str='# endif', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define H 1', file='h.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +@pytest.mark.parametrize('result', [1, 0]) +def test_ctu_macro_header_included_in_branch(checker, tmp_path, result): + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define H 1', file='h.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=result)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == ({'h.h-1-9-205'} if result else set()) + +@pytest.mark.parametrize('result,reported', [(1, {'x/config.h-1-9-205'}), (0, {'y/config.h-1-9-205'})]) +def test_ctu_macro_header_same_file_name_in_branch(checker, tmp_path, monkeypatch, result, reported): + # x/config.h is included in the #ifdef X branch, y/config.h in the #else branch + for name in ('x', 'y'): + (tmp_path / name).mkdir() + (tmp_path / name / 'config.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "x/config.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#else', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "y/config.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='x/config.h', linenr=1, column=9), + SimpleNamespace(str='#define M 2', file='y/config.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=result)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == reported + +@pytest.mark.parametrize('result,reported', [(1, {'x/cfg.h-1-9-205'}), (0, {'y/cfg.h-1-9-205'})]) +def test_ctu_macro_nested_header_same_file_name_in_branch(checker, tmp_path, monkeypatch, result, reported): + # x/inc.h and y/inc.h both include "cfg.h", next to them + for name in ('x', 'y'): + (tmp_path / name).mkdir() + (tmp_path / name / 'inc.h').write_text('') + (tmp_path / name / 'cfg.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "x/inc.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#else', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "y/inc.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#include "cfg.h"', file='x/inc.h', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='x/cfg.h', linenr=1, column=9), + SimpleNamespace(str='#include "cfg.h"', file='y/inc.h', linenr=1, column=1), + SimpleNamespace(str='#define M 2', file='y/cfg.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=result)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == reported + +@pytest.mark.parametrize('include,path,source', [('x/config.h', os.path.join('inc', 'x'), 'a.c'), + ('../x/config.h', os.path.join('p', 'x'), os.path.join('p', 'src', 'a.c'))]) +@pytest.mark.parametrize('result', [1, 0]) +def test_ctu_macro_header_same_file_name_in_branch_include_dir(checker, tmp_path, monkeypatch, include, path, source, result): + # and are found through an include directory + y = os.path.join(os.path.dirname(path), 'y') + for name in (path, y): + (tmp_path / name).mkdir(parents=True) + (tmp_path / name / 'config.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file=source, linenr=1, column=1), + SimpleNamespace(str='#include <%s>' % include, file=source, linenr=2, column=1), + SimpleNamespace(str='#else', file=source, linenr=3, column=1), + SimpleNamespace(str='#include <%s>' % include.replace('x/', 'y/'), file=source, linenr=4, column=1), + SimpleNamespace(str='#endif', file=source, linenr=5, column=1), + SimpleNamespace(str='#define M 1', file=os.path.join(path, 'config.h'), linenr=1, column=9), + SimpleNamespace(str='#define M 2', file=os.path.join(y, 'config.h'), linenr=1, column=9)] + conditions = [SimpleNamespace(file=source, linenr=1, result=result)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'%s-1-9-205' % os.path.join(path if result else y, 'config.h')} + +def test_ctu_macro_header_same_file_name_quote_and_angle(checker, tmp_path, monkeypatch): + # "config.h" next to a.c is included in the inactive branch, in the active one, both are checked + (tmp_path / 'inc').mkdir() + (tmp_path / 'config.h').write_text('') + (tmp_path / 'inc' / 'config.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "config.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#else', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include ', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='config.h', linenr=1, column=9), + SimpleNamespace(str='#define M 2', file=os.path.join('inc', 'config.h'), linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert '%s-1-9-205' % os.path.join('inc', 'config.h') in checker.existing_violations + +@pytest.mark.parametrize('kind,lines', [('if', [2, 4]), ('elif', [2, 4, 6])]) +def test_ctu_macro_header_condition_not_evaluated(checker, tmp_path, monkeypatch, kind, lines): + # y/config.h is not included, but its path ends like the path of : the dump has no result for its conditions + for name in ('x', 'y'): + (tmp_path / name).mkdir() + (tmp_path / name / 'config.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + y = {'if': ['#ifdef Z', '#define M 1', '#else', '#define M 2', '#endif'], + 'elif': ['#ifdef Z', '#define M 1', '#elif defined(V)', '#define M 2', '#else', '#define M 3', '#endif']}[kind] + directives = [SimpleNamespace(str='#ifdef Y', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include ', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include ', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define N 1', file='x/config.h', linenr=1, column=9)] + directives += [SimpleNamespace(str=s, file='y/config.h', linenr=i + 1, column=9) for i, s in enumerate(y)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'x/config.h-1-9-205'} | {'y/config.h-%d-9-205' % line for line in lines} + +@pytest.mark.parametrize('results', [[1, 0], [0, 1]]) +def test_ctu_macro_condition_evaluated_twice(checker, tmp_path, results): + # h.h included twice, its include guard is true then false, or false then true + directives = [SimpleNamespace(str='#ifndef H', file='h.h', linenr=1, column=1), + SimpleNamespace(str='#define G 1', file='h.h', linenr=2, column=9), + SimpleNamespace(str='#endif', file='h.h', linenr=3, column=1)] + conditions = [SimpleNamespace(file='h.h', linenr=1, result=result) for result in results] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h.h-2-9-205'} + +@pytest.mark.parametrize('first,second', [('if A', 'elif B'), ('ifdef A', 'elifdef B'), ('ifndef A', 'elifndef B')]) +@pytest.mark.parametrize('results,line', [([1], 2), ([0, 1], 4), ([0, 0], 6)]) +def test_ctu_macro_elif_branch(checker, tmp_path, monkeypatch, first, second, results, line): + (tmp_path / 'a.c').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#' + first, file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='#' + second, file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define M 2', file='a.c', linenr=4, column=9), + SimpleNamespace(str='#else', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 3', file='a.c', linenr=6, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=7, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=linenr, result=result) for linenr, result in zip([1, 3], results)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-%d-9-205' % line} + +def test_ctu_macro_source_file_name_in_inactive_include(checker, tmp_path): + # the source file is active even when an inactive #include names it + directives = [SimpleNamespace(str='#define M 1', file='a.c', linenr=1, column=9), + SimpleNamespace(str='#if 0', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#include "a.c"', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=4, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=2, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-1-9-205'} + +def test_ctu_macro_header_included_by_macro(checker, tmp_path): + # an #include that does not name its file can include any header + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#define HDR "h.h"', file='a.c', linenr=4, column=9), + SimpleNamespace(str='#include HDR', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='h.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[SimpleNamespace(name='HDR')], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h.h-1-9-205'} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +def test_ctu_macro_header_included_in_other_case(checker, tmp_path): + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "H.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define M 1', file='h.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h.h-1-9-205'} + +def test_ctu_macro_header_included_in_branch_hard_link(checker, tmp_path, monkeypatch): + # h.h is included as h2.h, a hard link, in an inactive branch first, the dump names it after this inclusion + (tmp_path / 'h.h').write_text('') + os.link(str(tmp_path / 'h.h'), str(tmp_path / 'h2.h')) + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "h2.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define H 1', file='h2.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'h2.h-1-9-205'} + +def test_ctu_macro_header_included_in_branch_hard_link_in_subdirectory(checker, tmp_path, monkeypatch): + # x/h2.h is a hard link of x/h.h, which the dump names after the inactive inclusion + (tmp_path / 'x').mkdir() + (tmp_path / 'x' / 'h.h').write_text('') + os.link(str(tmp_path / 'x' / 'h.h'), str(tmp_path / 'x' / 'h2.h')) + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "x/h.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "x/h2.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define H 1', file=os.path.join('x', 'h.h'), linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'%s-1-9-205' % os.path.join('x', 'h.h')} + +def test_ctu_macro_header_included_through_link(checker, tmp_path): + # y/config.h is first included in the inactive branch, then reached by the link l: no header has a path that ends like l/config.h + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "y/config.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#include "x/config.h"', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#include "l/config.h"', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='x/config.h', linenr=1, column=9), + SimpleNamespace(str='#define N 1', file='y/config.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert 'y/config.h-1-9-205' in checker.existing_violations + +def test_ctu_macro_header_included_from_parent_directory(checker, tmp_path): + # h.h next to a.c is included in an inactive branch, ../h.h in the active one + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "../h.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define M 1', file='h.h', linenr=1, column=9), + SimpleNamespace(str='#define M 2', file=os.path.join('..', 'h.h'), linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'%s-1-9-205' % os.path.join('..', 'h.h')} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +def test_ctu_macro_header_same_file_name_other_case(checker, tmp_path, monkeypatch): + # x/config.h is included as "x/config.h" and "x/Config.h", y/config.h in an inactive branch + for name in ('x', 'y'): + (tmp_path / name).mkdir() + (tmp_path / name / 'config.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef Y', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "y/config.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "x/config.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#include "x/Config.h"', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='x/config.h', linenr=1, column=9), + SimpleNamespace(str='#define N 1', file='y/config.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'x/config.h-1-9-205'} + +@pytest.mark.skipif(sys.platform != 'win32', reason='requires Windows') +def test_ctu_macro_header_same_file_name_in_other_directory_case(checker, tmp_path): + # X/config.h is x/config.h, y/config.h is included in the inactive branch only + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "x/config.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#include "y/config.h"', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#include "X/config.h"', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 1', file='x/config.h', linenr=1, column=9), + SimpleNamespace(str='#define M 2', file='y/config.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'x/config.h-1-9-205'} + +def test_ctu_macro_header_included_in_branch_other_file(checker, tmp_path, monkeypatch): + # h.h, without directives, is next to g.h, which is included in an inactive branch only + (tmp_path / 'h.h').write_text('') + (tmp_path / 'g.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#include "g.h"', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#include "h.h"', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#define G 1', file='g.h', linenr=1, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +def test_ctu_macro_undef_in_inactive_branch(checker, tmp_path): + directives = [SimpleNamespace(str='#define M 1', file='a.c', linenr=1, column=9), + SimpleNamespace(str='#if 0', file='a.c', linenr=2, column=1), + SimpleNamespace(str='#undef M', file='a.c', linenr=3, column=8), + SimpleNamespace(str='#endif', file='a.c', linenr=4, column=1)] + conditions = [SimpleNamespace(file='a.c', linenr=2, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-1-9-205'} + +def test_ctu_macro_undef_after_inactive_define(checker, tmp_path): + # the #undef follows only an inactive #define, so it comes before every #define and M 2 counts as used + directives = [SimpleNamespace(str='#if 0', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=3, column=1), + SimpleNamespace(str='#undef M', file='a.c', linenr=4, column=8), + SimpleNamespace(str='#define M 2', file='a.c', linenr=5, column=9)] + conditions = [SimpleNamespace(file='a.c', linenr=1, result=0)] + cfg = SimpleNamespace(macro_usage=[], directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert not checker.existing_violations + +def test_ctu_macro_used_in_other_configuration(checker, tmp_path, monkeypatch): + # M 2 is unused in the configuration where it is defined + (tmp_path / 'a.c').write_text('') + monkeypatch.chdir(str(tmp_path)) + directives = [SimpleNamespace(str='#ifdef X', file='a.c', linenr=1, column=1), + SimpleNamespace(str='#define M 1', file='a.c', linenr=2, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=4, column=1), + SimpleNamespace(str='#ifndef X', file='a.c', linenr=5, column=1), + SimpleNamespace(str='#define M 2', file='a.c', linenr=6, column=9), + SimpleNamespace(str='#endif', file='a.c', linenr=7, column=1)] + for result, macro_usage in ((1, [SimpleNamespace(name='M')]), (0, [])): + conditions = [SimpleNamespace(file='a.c', linenr=1, result=result), SimpleNamespace(file='a.c', linenr=5, result=1 - result)] + cfg = SimpleNamespace(macro_usage=macro_usage, directives=directives, preprocessor_if_conditions=conditions) + checker.misra_2_5(str(tmp_path / 'a.c.dump'), cfg) + checker.analyse_ctu_info([str(tmp_path / 'a.c.ctu-info')]) + assert checker.existing_violations == {'a.c-6-9-205'} + +@pytest.mark.parametrize('exists,reported', [(True, {'h.h-1-9-205', 'h.h-5-9-205'}), (False, {'h.h-1-9-205'})]) +def test_ctu_macro_same_name_same_file_two_lines(checker, tmp_path, monkeypatch, exists, reported): + # h.h not found from the current directory, for example with --relative-paths: the smallest line is reported + if exists: + (tmp_path / 'h.h').write_text('') + monkeypatch.chdir(str(tmp_path)) + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for line in (5, 1): + declaration = {'name': 'X', 'file': 'h.h', 'line': line, 'column': 9, 'used': False} + f.write(json.dumps({'summary': 'MisraMacro', 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == reported + +@pytest.mark.parametrize('used,reported', [(True, set()), (False, {'%s-1-9-205' % os.path.join('l', 'h.h')})]) +@pytest.mark.parametrize('inc_first', [True, False]) +def test_ctu_macro_path_not_found(checker, tmp_path, monkeypatch, used, reported, inc_first): + # Two spellings of h.h that cannot be found from the current directory, for example with --relative-paths + monkeypatch.chdir(str(tmp_path)) + ctu_info = tmp_path / 'test.ctu-info' + spellings = [(os.path.join('inc', 'h.h'), used), (os.path.join('l', 'h.h'), False)] + with open(ctu_info, 'wt') as f: + for path, path_used in (spellings if inc_first else reversed(spellings)): + declaration = {'name': 'X', 'file': path, 'line': 1, 'column': 9, 'used': path_used} + f.write(json.dumps({'summary': 'MisraMacro', 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == reported + +@pytest.mark.parametrize('a_first', [True, False]) +def test_ctu_macro_path_not_found_first_path_then_smallest_line(checker, tmp_path, monkeypatch, a_first): + # Two headers that cannot be found from the current directory: the first path is reported, not the smallest line + monkeypatch.chdir(str(tmp_path)) + ctu_info = tmp_path / 'test.ctu-info' + definitions = [(os.path.join('a', 'h.h'), 5), (os.path.join('b', 'h.h'), 1)] + with open(ctu_info, 'wt') as f: + for path, line in (definitions if a_first else reversed(definitions)): + declaration = {'name': 'X', 'file': path, 'line': line, 'column': 9, 'used': False} + f.write(json.dumps({'summary': 'MisraMacro', 'data': [declaration]}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'%s-5-9-205' % os.path.join('a', 'h.h')} + +def test_ctu_macro_path_not_found_undef_in_other_summary(checker, tmp_path, monkeypatch): + # h.h:3 is the last definition of X in the first summary, in the second one g.h #undef's it and defines X again + monkeypatch.chdir(str(tmp_path)) + ctu_info = tmp_path / 'test.ctu-info' + with open(ctu_info, 'wt') as f: + for summary in ([('h.h', 3, False)], [('h.h', 3, True), ('g.h', 2, False)]): + data = [{'name': 'X', 'file': path, 'line': line, 'column': 9, 'used': used} for path, line, used in summary] + f.write(json.dumps({'summary': 'MisraMacro', 'data': data}) + '\n') + checker.analyse_ctu_info([str(ctu_info)]) + assert checker.existing_violations == {'g.h-2-9-205'} + def test_platform(checker): test_file = os.path.join('addons','test','misra','misra-test.c') dump_create(test_file, "--language=c++") diff --git a/test/cli/whole-program_test.py b/test/cli/whole-program_test.py index aee2d2abafb..463d02493d3 100644 --- a/test/cli/whole-program_test.py +++ b/test/cli/whole-program_test.py @@ -247,6 +247,334 @@ def test_addon_no_artifacts(tmp_path, builddir): assert ' '.join(files) == 'whole1.c whole2.c' +@pytest.mark.parametrize('sources', [['a.c', 'b.c'], ['b.c', 'a.c']]) +def test_addon_misra_2_5_same_name_two_files(tmp_path, sources): + (tmp_path / 'a.c').write_text('#define M 1\nvoid fa(void);\n') + (tmp_path / 'b.c').write_text('#define M 2\nextern int gb[M];\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}'] + sources + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert 'a.c:1:misra-c2012-2.5' in stderr.splitlines() + assert 'b.c:1:misra-c2012-2.5' not in stderr.splitlines() + + +def test_addon_misra_2_5_source_and_header(tmp_path): + # a.c and the header it includes both define M, neither is used + (tmp_path / 'h.h').write_text('#define M 1\n') + (tmp_path / 'a.c').write_text('#include "h.h"\n#define M 1\nvoid fa(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert sorted(l for l in stderr.splitlines() if l.endswith('2.5')) == ['a.c:2:misra-c2012-2.5', 'h.h:1:misra-c2012-2.5'] + + +@pytest.mark.parametrize('option,line', [('-DX', 2), ('-UX', 4)]) +def test_addon_misra_2_5_inactive_branch(tmp_path, option, line): + (tmp_path / 'a.c').write_text('#ifdef X\n#define M 1\n#else\n#define M 2\n#endif\nint f(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + option, + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['a.c:%d:misra-c2012-2.5' % line] + + +def test_addon_misra_2_5_undef_in_inactive_branch(tmp_path): + (tmp_path / 'a.c').write_text('#define M 1\n#if 0\n#undef M\n#endif\nvoid fa(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--suppress=misra-c2012-20.5', + '--template={file}:{line}:{id}', + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['a.c:1:misra-c2012-2.5'] + + +def test_addon_misra_2_5_used_in_other_configuration(tmp_path): + (tmp_path / 'a.c').write_text('#ifdef X\n#define M 1\nextern int ga[M];\n#endif\n#ifndef X\n#define M 2\n#endif\nvoid fa(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['a.c:6:misra-c2012-2.5'] + + +def test_addon_misra_2_5_header_in_inactive_branch(tmp_path): + (tmp_path / 'h.h').write_text('#define M 1\n') + (tmp_path / 'a.c').write_text('#if 0\n#include "h.h"\n#endif\nvoid fa(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == [] + + +def test_addon_misra_2_5_fallback_definition(tmp_path): + (tmp_path / 'config.h').write_text('#define BUFSIZE 2\n') + (tmp_path / 'defaults.h').write_text('#ifndef BUFSIZE\n#define BUFSIZE 5\n#endif\n') + (tmp_path / 'a.c').write_text('#include "config.h"\n#include "defaults.h"\nint x = BUFSIZE;\n') + (tmp_path / 'b.c').write_text('#include "config.h"\nint b1(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={id}', + 'a.c', + 'b.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert 'internalError' not in stderr + assert 'misra-c2012-2.5' not in stderr + + +def test_addon_misra_2_5_header_path_spelling(tmp_path): + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('#define HM 3\n') + (tmp_path / 'src' / 'a.c').write_text('#include "h.h"\nint a1(void);\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../inc/h.h"\nint b1 = HM;\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={id}', + '-I' + str(tmp_path / 'inc'), + 'src/a.c', + 'src/b.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert 'internalError' not in stderr + assert 'misra-c2012-2.5' not in stderr + + +def test_addon_misra_2_5_header_relative_paths(tmp_path): + # The header paths of the dump are relative to the -rp directory, not to the current one + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('#define HM 3\n') + (tmp_path / 'src' / 'a.c').write_text('#include "h.h"\nint a1(void);\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../inc/h.h"\nint b1 = HM;\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={id}', + '-I' + str(tmp_path / 'inc'), + '-rp=' + str(tmp_path), + 'a.c', + 'b.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path / 'src')) + assert 'internalError' not in stderr + assert 'misra-c2012-2.5' not in stderr + + +def test_addon_misra_2_5_header_relative_paths_defined_again(tmp_path): + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('#define HM 1\n#undef HM\n#define HM 2\n') + (tmp_path / 'src' / 'a.c').write_text('#include "h.h"\nint a1(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={line}:{id}', + '-I' + str(tmp_path / 'inc'), + '-rp=' + str(tmp_path), + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path / 'src')) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['3:misra-c2012-2.5'] + + +@pytest.mark.parametrize('suppression,reported', [ + ([], True), + (['--suppress=misra-c2012-2.5:inc/h.h'], False), + (['--suppress=misra-c2012-2.5:l/h.h'], True)]) +@pytest.mark.parametrize('sources', [['src/a.c', 'src/b.c'], ['src/b.c', 'src/a.c']]) +def test_addon_misra_2_5_header_link_spelling(tmp_path, sources, suppression, reported): + # a.c reaches inc/h.h through the link l, b.c directly: the path through no link is reported, in any file order + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('#define M 1\n') + (tmp_path / 'src' / 'a.c').write_text('#include "../l/h.h"\nvoid fa(void);\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../inc/h.h"\nvoid fb(void);\n') + try: + os.symlink('inc', str(tmp_path / 'l'), target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '--error-exitcode=1'] + suppression + sources + ret, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == (['%s:1:misra-c2012-2.5' % os.path.join('inc', 'h.h')] if reported else []) + assert ret == (1 if reported else 0) + + +@pytest.mark.parametrize('sources', [['a.c', 'b.c'], ['b.c', 'a.c']]) +def test_addon_misra_2_5_header_dotdot_spelling(tmp_path, sources): + # a.c reaches inc/h.h through the absolute -I, b.c through ../inc/h.h: the absolute path is reported, ../inc/h.h does not match it + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('#define HM 3\n') + (tmp_path / 'src' / 'a.c').write_text('#include "h.h"\nint a1(void);\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../inc/h.h"\nint b1(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '-I' + str(tmp_path / 'inc'), + '--suppress=misra-c2012-2.5:../inc/h.h'] + sources + _, _, stderr = cppcheck(args, cwd=str(tmp_path / 'src')) + lines = [l for l in stderr.splitlines() if l.endswith('2.5')] + assert len(lines) == 1 + assert os.path.isabs(lines[0]) + assert lines[0].replace('\\', '/').endswith('/inc/h.h:1:misra-c2012-2.5') + + +@pytest.mark.parametrize('sources', [['p/src/a.c', 'p/src/b.c'], ['p/src/b.c', 'p/src/a.c']]) +def test_addon_misra_2_5_header_link_spelling_relative_paths(tmp_path, sources): + # The header paths of the dump are relative to the -rp directory, not to the current one: no link is counted for them + (tmp_path / 'p' / 'inc').mkdir(parents=True) + (tmp_path / 'p' / 'src').mkdir() + (tmp_path / 'p' / 'inc' / 'h.h').write_text('#define M 1\n') + (tmp_path / 'p' / 'src' / 'a.c').write_text('#include "../l/h.h"\nvoid fa(void);\n') + (tmp_path / 'p' / 'src' / 'b.c').write_text('#include "../inc/h.h"\nvoid fb(void);\n') + try: + os.symlink('inc', str(tmp_path / 'p' / 'l'), target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '-rp=p'] + sources + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['%s:1:misra-c2012-2.5' % os.path.join('l', 'h.h')] + + +@pytest.mark.parametrize('sources', [['a.c', 'b.c'], ['b.c', 'a.c']]) +def test_addon_misra_2_5_header_relative_paths_first_path_smallest_line(tmp_path, sources): + # Two headers with the same name that define HM, unused. Their paths in the dump are relative to -rp, + # so they are not found from src: the first path is reported, not the smallest line + (tmp_path / 'a').mkdir() + (tmp_path / 'b').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'a' / 'h.h').write_text('\n\n\n\n#define HM 1\n') + (tmp_path / 'b' / 'h.h').write_text('#define HM 1\n') + (tmp_path / 'src' / 'a.c').write_text('#include "a/h.h"\nint a1(void);\n') + (tmp_path / 'src' / 'b.c').write_text('#include "b/h.h"\nint b1(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '-I' + str(tmp_path), + '-rp=' + str(tmp_path)] + sources + _, _, stderr = cppcheck(args, cwd=str(tmp_path / 'src')) + assert 'internalError' not in stderr + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['%s:5:misra-c2012-2.5' % os.path.join('a', 'h.h')] + + +def test_addon_misra_2_5_header_rp_shorter_than_include(tmp_path): + # -rp strips inc/sub: the dump names the active header config.h while the #include writes sub/config.h + (tmp_path / 'inc' / 'sub').mkdir(parents=True) + (tmp_path / 'other').mkdir() + (tmp_path / 'inc' / 'sub' / 'config.h').write_text('#define N1 1\n') + (tmp_path / 'other' / 'config.h').write_text('#define N2 1\n') + (tmp_path / 'a.c').write_text('#if 0\n#include "other/config.h"\n#endif\n#include \nint f(void);\n') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '-Iinc', + '-rp=inc/sub', + 'a.c'] + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if l.endswith('2.5')] == ['config.h:1:misra-c2012-2.5'] + + +@pytest.mark.parametrize('sources', [['src/a.c', 'src/b.c'], ['src/b.c', 'src/a.c']]) +def test_addon_misra_5_6_header_link_spelling(tmp_path, sources): + # T is used in a.c, b.c reaches the typedef through the link l + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('typedef int T;\n') + (tmp_path / 'src' / 'a.c').write_text('#include "../inc/h.h"\nextern T ta;\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../l/h.h"\nvoid fb(void);\n') + try: + os.symlink('inc', str(tmp_path / 'l'), target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + args = [ + '--addon=misra', + '--enable=style', + '--template={file}:{line}:{id}', + '--error-exitcode=1'] + sources + ret, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert [l for l in stderr.splitlines() if 'misra-c2012-' in l] == [] + assert ret == 0 + + +@pytest.mark.parametrize('suppression,reported', [ + ([], True), + (['--suppress=misra-c2012-5.7:inc/other.h', '--error-exitcode=1'], False)]) +@pytest.mark.parametrize('sources', [['src/a.c', 'src/b.c', 'src/c.c'], ['src/c.c', 'src/b.c', 'src/a.c']]) +def test_addon_misra_unmatched_suppression_header_link_spelling(tmp_path, sources, suppression, reported): + # The 5.7 of h.h is reported under inc/h.h only, so the inline suppression read through l/h.h matches nothing + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('// cppcheck-suppress misra-c2012-5.7\nstruct S { int x; };\n') + (tmp_path / 'inc' / 'other.h').write_text('struct S { long y; };\n') + (tmp_path / 'src' / 'a.c').write_text('#include "../inc/h.h"\nextern struct S a1;\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../l/h.h"\nextern struct S b1;\n') + (tmp_path / 'src' / 'c.c').write_text('#include "../inc/other.h"\nextern struct S c1;\n') + try: + os.symlink('inc', str(tmp_path / 'l'), target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + args = [ + '--addon=misra', + '--enable=information,style', + '--inline-suppr', + '--suppress=checkersReport', + '--template={file}:{line}:{id}'] + suppression + sources + ret, _, stderr = cppcheck(args, cwd=str(tmp_path)) + expected = ['%s:2:unmatchedSuppression' % os.path.join('l', 'h.h')] + if reported: + expected.insert(0, '%s:1:misra-c2012-5.7' % os.path.join('inc', 'other.h')) + assert stderr.splitlines() == expected + assert ret == (0 if reported else 1) + + +@pytest.mark.parametrize('sources', [['src/a.c', 'src/b.c'], ['src/b.c', 'src/a.c']]) +def test_addon_misra_unmatched_suppression_link_spelling(tmp_path, sources): + # The two suppressions matched the false 2.3 and 5.6 of h.h under l/h.h, there is no finding left for them + (tmp_path / 'inc').mkdir() + (tmp_path / 'src').mkdir() + (tmp_path / 'inc' / 'h.h').write_text('typedef int T;\n') + (tmp_path / 'src' / 'a.c').write_text('#include "../inc/h.h"\nextern T ta;\n') + (tmp_path / 'src' / 'b.c').write_text('#include "../l/h.h"\nvoid fb(void);\n') + try: + os.symlink('inc', str(tmp_path / 'l'), target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip('symbolic links are not available') + args = [ + '--addon=misra', + '--enable=information,style', + '--suppress=checkersReport', + '--suppress=misra-c2012-2.3', + '--suppress=misra-c2012-5.6', + '--template={file}:{line}:{id}'] + sources + _, _, stderr = cppcheck(args, cwd=str(tmp_path)) + assert stderr.splitlines() == ['nofile:0:unmatchedSuppression'] + + def __test_checkclass(extra_args): args = [ '-q',