mirror of
https://github.com/llvm/llvm-project.git
synced 2025-04-26 00:46:06 +00:00

This is a follow-up patch to #96475 to detect dangling assignments for C++ pointer-like objects (classes annotated with the `[[gsl::Pointer]]`). Fixes #63310. Similar to the behavior for built-in pointer types, if a temporary owner (`[[gsl::Owner]]`) object is assigned to a pointer-like class object, and this temporary object is destroyed at the end of the full assignment expression, the assignee pointer is considered dangling. In such cases, clang will emit a warning: ``` /tmp/t.cpp:7:20: warning: object backing the pointer my_string_view will be destroyed at the end of the full-expression [-Wdangling-assignment-gsl] 7 | my_string_view = CreateString(); | ^~~~~~~~~~~~~~ 1 warning generated. ``` This new warning is `-Wdangling-assignment-gsl`. It is initially disabled, but I intend to enable it by default in clang 20. I have initially tested this patch on our internal codebase, and it has identified many use-after-free bugs, primarily related to `string_view`.
28 lines
617 B
C++
28 lines
617 B
C++
// RUN: %clang_cc1 -fsyntax-only -Wno-dangling-gsl -Wreturn-stack-address -verify %s
|
|
|
|
struct [[gsl::Owner(int)]] MyIntOwner {
|
|
MyIntOwner();
|
|
int &operator*();
|
|
};
|
|
|
|
struct [[gsl::Pointer(int)]] MyIntPointer {
|
|
MyIntPointer(int *p = nullptr);
|
|
MyIntPointer(const MyIntOwner &);
|
|
int &operator*();
|
|
MyIntOwner toOwner();
|
|
};
|
|
|
|
int &f() {
|
|
int i;
|
|
return i; // expected-warning {{reference to stack memory associated with local variable 'i' returned}}
|
|
}
|
|
|
|
MyIntPointer g() {
|
|
MyIntOwner o;
|
|
return o; // No warning, it is disabled.
|
|
}
|
|
|
|
void h(MyIntPointer p) {
|
|
p = MyIntOwner(); // No warning, it is disabled.
|
|
}
|