Skip to content

Commit db0c4fe

Browse files
authored
Merge pull request #195 from CoreTrace/174-header-diagnostic-file
fix(diagnostics): report a header function's diagnostics in its header
2 parents daaf4cd + 10d4695 commit db0c4fe

4 files changed

Lines changed: 89 additions & 0 deletions

File tree

‎include/analyzer/DiagnosticEmitter.hpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,9 @@ namespace ctrace::stack::analyzer
116116
appendResourceLifetimeDiagnostics(AnalysisResult& result,
117117
const std::vector<analysis::ResourceLifetimeIssue>& issues);
118118

119+
// Gives each diagnostic whose rule named no file the file of its function, so that a
120+
// function defined in a header is reported there, not in the file that includes it. A file
121+
// a rule already named is kept.
122+
void assignFunctionFilesToDiagnostics(AnalysisResult& result);
123+
119124
} // namespace ctrace::stack::analyzer

‎run_test.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4158,6 +4158,68 @@ def check_diagnostic_paths_follow_the_input() -> bool:
41584158
return ok
41594159

41604160

4161+
def check_header_function_diagnostics_name_the_header() -> bool:
4162+
"""
4163+
#174: a diagnostic in a function defined in a header names that header, at the line it has
4164+
there, whether its rule sets a file itself (signed overflow) or not (const parameter,
4165+
duplicate if). The including file used to be reported, at the header's line.
4166+
"""
4167+
print("=== Testing diagnostics of header functions name the header ===")
4168+
sources = {
4169+
"reader.hpp": "#pragma once\n\ntemplate <typename T>\nT first(T* values)\n{\n"
4170+
" return values[0];\n}\n",
4171+
"main.cpp": '#include "reader.hpp"\n\nint use(int* values)\n{\n'
4172+
" return first(values);\n}\n",
4173+
"pick.hpp": "#pragma once\n\ninline int pick(int x)\n{\n if (x > 3)\n {\n"
4174+
" return 1;\n }\n else if (x > 3)\n {\n return 2;\n }\n"
4175+
" return 0;\n}\n",
4176+
"pick.cpp": '#include "pick.hpp"\n\nint callPick(int x)\n{\n return pick(x);\n}\n',
4177+
"sum.h": "#pragma once\n\nstatic int sum(int* values)\n{\n"
4178+
" return values[0] + values[1];\n}\n",
4179+
"sum.c": '#include "sum.h"\n\nint callSum(int* values)\n{\n return sum(values);\n}\n',
4180+
}
4181+
# (label, analyzed source, expected (rule, file, line) of every diagnostic).
4182+
cases = [
4183+
("template", "main.cpp", {("ConstParameterNotModified.Pointer", "reader.hpp", 4)}),
4184+
("inline function", "pick.cpp", {("DuplicateIfCondition", "pick.hpp", 9)}),
4185+
(
4186+
"static C function",
4187+
"sum.c",
4188+
{
4189+
("IntegerOverflow.SignedArithmetic", "sum.h", 5),
4190+
("ConstParameterNotModified.Pointer", "sum.h", 3),
4191+
},
4192+
),
4193+
]
4194+
ok = True
4195+
with tempfile.TemporaryDirectory(prefix="ct_header_diagnostics_") as tmp:
4196+
root = Path(tmp).resolve()
4197+
for name, text in sources.items():
4198+
(root / name).write_text(text)
4199+
for label, source, expected in cases:
4200+
result = run_analyzer([str(root / source), "--format=json"])
4201+
try:
4202+
payload = json.loads(result.stdout or "")
4203+
except json.JSONDecodeError:
4204+
ok = fail_check(f"{label}: no JSON output", (result.stdout or "") + (result.stderr or ""))
4205+
continue
4206+
observed = {
4207+
(
4208+
d.get("ruleId"),
4209+
str(Path(d.get("location", {}).get("file", "")).resolve()),
4210+
d.get("location", {}).get("startLine"),
4211+
)
4212+
for d in payload.get("diagnostics", [])
4213+
}
4214+
wanted = {(rule, str(root / file), line) for rule, file, line in expected}
4215+
if observed != wanted:
4216+
ok = fail_check(f"{label}: expected {sorted(wanted)}, got {sorted(observed)}")
4217+
continue
4218+
print(f" ✅ {label}: {', '.join(f'{file}:{line}' for _, file, line in sorted(expected))}")
4219+
print()
4220+
return ok
4221+
4222+
41614223
def check_calls_through_aliases() -> bool:
41624224
"""
41634225
#179: on ELF targets, clang calls a constructor or a destructor defined out of its class
@@ -5343,6 +5405,7 @@ def record_ok(ok: bool):
53435405
check_diagnostic_rule_coverage_regression,
53445406
check_diagnostic_cwe_coverage,
53455407
check_diagnostic_paths_follow_the_input,
5408+
check_header_function_diagnostics_name_the_header,
53465409
check_const_param_abi_split_struct,
53475410
check_calls_through_aliases,
53485411
check_resource_cache_rebuilds_alias_summaries,

‎src/analyzer/AnalysisPipeline.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,7 @@ namespace ctrace::stack::analyzer
852852
<< ", independent=" << independentInstructionVisits << "\n";
853853
}
854854

855+
assignFunctionFilesToDiagnostics(data.result);
855856
return data.result;
856857
}
857858

‎src/analyzer/DiagnosticEmitter.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <map>
1010
#include <sstream>
1111
#include <string_view>
12+
#include <unordered_map>
1213

1314
#include <llvm/IR/DebugInfoMetadata.h>
1415
#include <llvm/IR/Function.h>
@@ -1405,4 +1406,23 @@ namespace ctrace::stack::analyzer
14051406
}
14061407
}
14071408

1409+
void assignFunctionFilesToDiagnostics(AnalysisResult& result)
1410+
{
1411+
// Names are LLVM symbols, unique in a module: overloads and template instances differ.
1412+
std::unordered_map<std::string_view, std::string_view> fileOfFunction;
1413+
for (const FunctionResult& function : result.functions)
1414+
fileOfFunction.emplace(function.name, function.filePath);
1415+
1416+
for (Diagnostic& diagnostic : result.diagnostics)
1417+
{
1418+
if (!diagnostic.filePath.empty())
1419+
continue;
1420+
if (const auto it = fileOfFunction.find(diagnostic.funcName);
1421+
it != fileOfFunction.end())
1422+
{
1423+
diagnostic.filePath = it->second;
1424+
}
1425+
}
1426+
}
1427+
14081428
} // namespace ctrace::stack::analyzer

0 commit comments

Comments
 (0)