Skip to content

[analyzer] Fix false double free when including 3rd-party headers with overloaded delete operator as system headers #85224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1096,12 +1096,15 @@ static bool isStandardNewDelete(const FunctionDecl *FD) {
Kind != OO_Array_Delete)
return false;

bool HasBody = FD->hasBody(); // Prefer using the definition.

// This is standard if and only if it's not defined in a user file.
SourceLocation L = FD->getLocation();

// If the header for operator delete is not included, it's still defined
// in an invalid source location. Check to make sure we don't crash.
return !L.isValid() ||
FD->getASTContext().getSourceManager().isInSystemHeader(L);
const auto &SM = FD->getASTContext().getSourceManager();
return L.isInvalid() || (!HasBody && SM.isInSystemHeader(L));
}

//===----------------------------------------------------------------------===//
Expand Down
18 changes: 18 additions & 0 deletions clang/test/Analysis/Inputs/overloaded-delete-in-header.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#ifndef OVERLOADED_DELETE_IN_HEADER
#define OVERLOADED_DELETE_IN_HEADER

struct DeleteInHeader {
int data;
static void operator delete(void *ptr);
};

void DeleteInHeader::operator delete(void *ptr) {
DeleteInHeader *self = (DeleteInHeader *)ptr;
self->data = 1; // no-warning: Still alive.

::operator delete(ptr);

self->data = 2; // expected-warning {{Use of memory after it is freed [cplusplus.NewDelete]}}
}

#endif // OVERLOADED_DELETE_IN_SYSTEM_HEADER
9 changes: 9 additions & 0 deletions clang/test/Analysis/overloaded-delete-in-system-header.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// RUN: %clang_analyze_cc1 -isystem %S/Inputs/ -verify %s \
// RUN: -analyzer-checker=core,unix.Malloc,cplusplus.NewDelete

// RUN: %clang_analyze_cc1 -I %S/Inputs/ -verify %s \
// RUN: -analyzer-checker=core,unix.Malloc,cplusplus.NewDelete

#include "overloaded-delete-in-header.h"

void deleteInHeader(DeleteInHeader *p) { delete p; }