use cpp_code_analysis::{
CompilerConfig, DiagnosticCode, Finding, MemoryFiles, OpenDocuments, Session, SessionFiles,
WatchFilter,
};
fn findings_of(source: &str) -> Vec<Finding> {
let path = "/p/lifetime.cpp";
let files = MemoryFiles::new().with_file(path, source);
let providers = SessionFiles::new(OpenDocuments::new(), files);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from(path)]);
session.want_cooked_reading(std::path::Path::new(path));
session.index_everything();
session
.diagnostics(std::path::Path::new(path))
.map(|found| found.checks)
.unwrap_or_default()
}
fn dangling(source: &str) -> Vec<String> {
findings_of(source)
.into_iter()
.filter(|finding| finding.code == DiagnosticCode::DanglingReturn)
.map(|finding| finding.message)
.collect()
}
fn assert_one(source: &str, expected: &str) {
let messages = dangling(source);
assert_eq!(messages.len(), 1, "one finding expected: {messages:?}");
assert!(
messages[0].contains(expected),
"`{expected}` missing from `{}`",
messages[0]
);
}
#[test]
fn a_function_returns_a_reference_to_its_own_local() {
assert_one("int& f() { int x = 0; return x; }", "is a local");
}
#[test]
fn a_view_outlives_the_string_it_refers_to() {
assert_one(
"std::string_view f() { std::string s; return s; }",
"refers to `s`",
);
}
#[test]
fn a_reference_to_a_temporary_is_reported() {
assert_one(
"const std::string& f() { return std::string(\"x\"); }",
"temporary",
);
}
#[test]
fn a_pointer_into_a_local_is_reported() {
assert_one(
"const char* f() { std::string s; return s.c_str(); }",
"`c_str()` returns a pointer into `s`",
);
}
#[test]
fn the_address_of_a_local_is_reported() {
assert_one("int* f() { int x = 0; return &x; }", "address of `&x`");
}
#[test]
fn a_local_in_an_inner_block_is_still_the_functions_own() {
assert_one("int& f() { { int x = 0; return x; } }", "is a local");
}
#[test]
fn a_span_of_a_local_vector_is_reported() {
assert_one(
"std::span<int> f() { std::vector<int> v; return v; }",
"refers to `v`",
);
}
#[test]
fn a_moved_local_is_still_the_functions_own() {
assert_one(
"std::string_view f() { std::string s; return std::move(s); }",
"refers to `s`",
);
}
fn use_after_free(source: &str) -> Vec<String> {
findings_of(source)
.into_iter()
.filter(|finding| finding.code == DiagnosticCode::UseAfterFree)
.map(|finding| finding.message)
.collect()
}
#[test]
fn a_pointer_read_after_delete_is_reported() {
let messages =
use_after_free("struct T { int x; }; void f() { T* p = new T(); delete p; p->x; }");
assert_eq!(messages.len(), 1, "{messages:?}");
assert!(messages[0].contains("p"), "{}", messages[0]);
}
#[test]
fn a_pointer_read_after_a_helper_frees_it_is_reported() {
let messages = use_after_free(
"struct T { int x; }; void release(T* p) { delete p; } void f() { T* p = new T(); release(p); p->x; }",
);
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn a_pointer_read_after_a_headers_helper_frees_it_is_reported() {
let root = std::env::temp_dir().join(format!("cppls_use_after_free_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("a directory to write the fixture into");
std::fs::write(
root.join("release.h"),
"struct T { int x; };\nvoid release(T* p) { delete p; }\n",
)
.expect("the header");
let source = "#include \"release.h\"\nvoid f() { T* p = new T(); release(p); p->x; }\n";
std::fs::write(root.join("a.cpp"), source).expect("the source");
let mut session = cpp_code_analysis::Session::open(
root.clone(),
SessionFiles::new(OpenDocuments::new(), cpp_code_analysis::DiskFiles),
WatchFilter::new(&root),
);
session.add_project_files([root.join("a.cpp"), root.join("release.h")]);
session.index_everything();
for _ in 0..2 {
let mut steps = 0;
while session.pending_work() > 0 && steps < 20_000 {
session.advance(64);
steps += 1;
}
session.cook(root.join("a.cpp").as_path());
}
let findings = session
.diagnostics(root.join("a.cpp").as_path())
.map(|found| found.checks)
.unwrap_or_default();
let messages: Vec<String> = findings
.into_iter()
.filter(|finding| finding.code == DiagnosticCode::UseAfterFree)
.map(|finding| finding.message)
.collect();
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn a_pointer_read_after_free_is_reported() {
let messages = use_after_free("void f() { int* p = (int*)malloc(4); free(p); *p; }");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn a_smart_pointers_pointee_read_after_reset_is_reported() {
let messages =
use_after_free("void f() { std::unique_ptr<int> u(new int(1)); u.reset(); *u; }");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn a_parameter_read_after_delete_is_reported() {
let messages = use_after_free("struct T { int x; }; void g(T* p) { delete p; p->x; }");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn an_array_read_after_delete_is_reported() {
let messages = use_after_free("void f() { int* a = new int[4]; delete[] a; a[0]; }");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn the_safe_free_shapes_are_silent() {
let safe = [
"struct T { int x; }; void f() { T* p = new T(); p->x; delete p; }",
"struct T { int x; }; void f(int c) { T* p = new T(); if (c) delete p; p->x; }",
"struct T { int x; }; void f() { T* p = new T(); delete p; p = new T(); p->x; }",
"struct T { int x; }; void maybe(T* p, bool c) { if (c) delete p; } void f() { T* p = new T(); maybe(p, true); p->x; }",
"struct T { int x; }; void touch(T* p) { } void f() { T* p = new T(); touch(p); p->x; }",
"struct T { int x; }; void f() { T* p = new T(); T* q = new T(); delete p; q->x; }",
"struct T { int x; }; void f() { T* p = new T(); delete p; }",
"void f() { std::unique_ptr<int> u(new int(1)); u.reset(); u = nullptr; }",
];
for source in safe {
let messages = use_after_free(source);
assert!(messages.is_empty(), "`{source}` reported {messages:?}");
}
}
fn dangling_fields(source: &str) -> Vec<String> {
findings_of(source)
.into_iter()
.filter(|finding| finding.code == DiagnosticCode::DanglingField)
.map(|finding| finding.message)
.collect()
}
#[test]
fn a_view_member_of_a_by_value_parameter_is_reported() {
let messages = dangling_fields("struct S { std::string_view v; S(std::string s) : v(s) {} };");
assert_eq!(messages.len(), 1, "{messages:?}");
assert!(messages[0].contains("parameter"), "{}", messages[0]);
}
#[test]
fn a_view_member_of_a_temporary_is_reported() {
let messages = dangling_fields("struct S { std::string_view v = std::string(\"x\"); };");
assert_eq!(messages.len(), 1, "{messages:?}");
assert!(messages[0].contains("temporary"), "{}", messages[0]);
}
#[test]
fn a_reference_member_of_a_temporary_is_reported() {
let messages =
dangling_fields("struct S { const std::string& v; S() : v(std::string(\"x\")) {} };");
assert_eq!(messages.len(), 1, "{messages:?}");
assert!(messages[0].contains("reference"), "{}", messages[0]);
}
#[test]
fn a_pointer_member_of_a_parameters_buffer_is_reported() {
let messages =
dangling_fields("struct S { const char* p; S(std::string s) : p(s.c_str()) {} };");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn a_span_member_of_a_by_value_vector_is_reported() {
let messages =
dangling_fields("struct S { std::span<int> v; S(std::vector<int> vec) : v(vec) {} };");
assert_eq!(messages.len(), 1, "{messages:?}");
}
#[test]
fn the_safe_field_shapes_are_silent() {
let safe = [
"struct S { std::string v; S(std::string s) : v(s) {} };",
"struct S { std::string_view v; S(const std::string& s) : v(s) {} };",
"struct S { std::string_view v; S(std::string&& s) : v(s) {} };",
"struct S { std::string s; std::string_view v; S() : v(s) {} };",
"struct S { static const std::string name; std::string_view v; S() : v(name) {} };",
"struct S { std::string_view v; S() : v(\"literal\") {} };",
"struct S { std::string_view v = \"literal\"; };",
"struct S { int* p; S(int* q) : p(q) {} };",
"struct S { std::string_view v; S() {} };",
];
for source in safe {
let messages = dangling_fields(source);
assert!(messages.is_empty(), "`{source}` reported {messages:?}");
}
}
#[test]
fn the_safe_shapes_are_silent() {
let safe = [
"std::string f() { std::string s; return s; }",
"int& f(int& x) { return x; }",
"std::string_view f(const std::string& s) { return s; }",
"const std::string& f(const std::string& s) { return s; }",
"struct S { std::string name; }; std::string_view f(const S& s) { return s.name; }",
"int& f() { static int x = 0; return x; }",
"std::string_view f() { static std::string s; return s; }",
"const char* f() { static const char* p = \"x\"; return p; }",
"std::string_view f() { return \"literal\"; }",
"int* f() { return nullptr; }",
"int* p = nullptr; int& f() { return *p; }",
"struct S { std::string name; std::string_view get() { return name; } };",
"std::string_view f() { std::string_view v; return v; }",
"std::string_view g(); std::string_view f() { std::string_view s = g(); return s.substr(0, 1); }",
"std::string_view g(); std::string_view f() { std::string_view s = g(); return s; }",
"int& f(); int& g() { return f(); }",
];
for source in safe {
let messages = dangling(source);
assert!(messages.is_empty(), "`{source}` reported {messages:?}");
}
}
#[test]
fn a_lambda_return_is_not_this_rules_business() {
assert!(dangling("void g() { auto l = []() -> int& { int x = 0; return x; }; }").is_empty());
}
#[test]
fn a_return_is_reported_once() {
assert_eq!(dangling("int& f() { int x = 0; return x; }").len(), 1);
}