Skip to content
Draft
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
57 changes: 39 additions & 18 deletions src/analysis/ownership/ResourceFactCollector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

#include "../ResourceLifetimeInternal.hpp"
#include "analysis/AnalyzerUtils.hpp"
#include "analysis/FunctionFacts.hpp"
#include "analysis/IRValueUtils.hpp"

#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/PostOrderIterator.h>
#include <llvm/Analysis/MemorySSA.h>
#include <llvm/Analysis/ValueTracking.h>
#include <llvm/IR/Argument.h>
#include <llvm/IR/BasicBlock.h>
Expand All @@ -32,6 +34,10 @@ namespace ctrace::stack::analysis::ownership
using lifetime_detail::StorageKey;
using lifetime_detail::StorageScope;

/// Bounds the walk through reloads; a -O0 copy chain such as `q = p` needs one level
/// per copy.
constexpr unsigned kMaxReloadDepth = 16;

class Collector
{
public:
Expand Down Expand Up @@ -115,33 +121,47 @@ namespace ctrace::stack::analysis::ownership
if (!llvm::isa<llvm::ConstantPointerNull>(other))
return nullptr;
}
// -O0 reloads the pointer from its slot before the test.
// -O0 reloads the pointer from its slot before the test, and a copy such as
// `q = p` goes through slots too: follow each reload to the value written by the
// store it reads, whatever other stores write the slot elsewhere.
const llvm::Value* origin = ptr;
if (const auto* load = llvm::dyn_cast<llvm::LoadInst>(ptr))
for (unsigned depth = 0; depth < kMaxReloadDepth; ++depth)
{
if (const auto* slot = llvm::dyn_cast<llvm::AllocaInst>(
load->getPointerOperand()->stripPointerCasts()))
{
const llvm::StoreInst* unique = nullptr;
for (const llvm::User* u : slot->users())
{
if (const auto* st = llvm::dyn_cast<llvm::StoreInst>(u))
{
if (unique)
return nullptr;
unique = st;
}
}
if (unique)
origin = unique->getValueOperand();
}
const auto* load = llvm::dyn_cast<llvm::LoadInst>(origin);
const llvm::StoreInst* store = load ? storeReadBy(*load) : nullptr;
if (!store)
break;
origin = store->getValueOperand();
}
if (!llvm::isKnownNonZero(origin, DL_))
return nullptr;
// eq null → true edge dead; ne null → false edge dead.
return br->getSuccessor(icmp->getPredicate() == llvm::CmpInst::ICMP_EQ ? 0 : 1);
}

/// The store whose value `load` reads: its MemorySSA clobber, when that clobber
/// stores the loaded type to the loaded pointer. Null for any other clobber, such
/// as a merge of stores from several paths, a call or the function entry.
const llvm::StoreInst* storeReadBy(const llvm::LoadInst& load)
{
if (!load.isSimple())
return nullptr;
if (!facts_)
facts_.emplace(const_cast<llvm::Function&>(F_));
const auto* def =
llvm::dyn_cast_or_null<llvm::MemoryDef>(facts_->clobberingAccess(load));
const auto* store =
def ? llvm::dyn_cast_or_null<llvm::StoreInst>(def->getMemoryInst()) : nullptr;
if (!store || !store->isSimple() ||
store->getPointerOperand()->stripPointerCasts() !=
load.getPointerOperand()->stripPointerCasts() ||
store->getValueOperand()->getType() != load.getType())
{
return nullptr;
}
return store;
}

/// Several source `return`s are usually merged into one `ret` block that only
/// reloads a return slot. Its events are moved onto every incoming edge so each
/// path is judged with its own state instead of the join (spec §6: the
Expand Down Expand Up @@ -1181,6 +1201,7 @@ namespace ctrace::stack::analysis::ownership
llvm::DenseMap<const llvm::Value*, LocationId> valueIds_;
llvm::DenseMap<const llvm::LoadInst*, LocationId> loadedFrom_; // the slot read
std::map<const llvm::CallBase*, Event> exceptionalSummaryEvents_;
std::optional<FunctionFacts> facts_; // built on the first null test of a reload
std::optional<LocationId> unknownTarget_;
LocationId returnLocation_ = 0;
bool mayUnwind_ = false;
Expand Down
7 changes: 2 additions & 5 deletions test/resource-lifetime/double-release-delete-reset.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// resource-model: models/resource-lifetime/generic.txt
// Deleting a pointer reset to nullptr deletes nothing: no double release. The function also gets
// a false resource-leak warning ("may be overwritten while still owned"): the null check clang
// emits around `delete` is taken as feasible once the variable is written twice. That warning is
// tracked in #282 and deliberately not pinned here, hence no strict count.
// strict-diagnostic-count: false
// Deleting a pointer reset to nullptr deletes nothing: no double release, and no leak (#282).

void delete_reset_delete()
{
Expand All @@ -15,3 +11,4 @@ void delete_reset_delete()
}

// not contains: potential double release: 'CppHeap' handle 'resetp'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'resetp'
30 changes: 30 additions & 0 deletions test/resource-lifetime/malloc-null-check-reassigned-variable.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: Apache-2.0
// resource-model: models/resource-lifetime/generic.txt
// #282: malloc may return NULL, so a null test of its result keeps both edges, also when the
// variable is written again.
#include <stdlib.h>

void checked_free_then_reset(void)
{
int* checked = malloc(sizeof *checked);
if (checked)
free(checked);
checked = NULL;
}

void early_return_then_reset(void)
{
int* first = malloc(sizeof *first);
int* second = malloc(sizeof *second);
if (first == NULL)
return;
free(first);
first = NULL;
free(second);
}

// not contains: potential resource leak: 'HeapAlloc' acquired in handle 'checked'
// not contains: potential resource leak: 'HeapAlloc' acquired in handle 'first'

// at line 18, column 19
// [ !!Warn ] potential resource leak: 'HeapAlloc' acquired in handle 'second' may leave the function without being released
112 changes: 112 additions & 0 deletions test/resource-lifetime/new-delete-reassigned-variable.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// SPDX-License-Identifier: Apache-2.0
// resource-model: models/resource-lifetime/generic.txt
// #282: clang tests the pointer against null before `delete p`. When `p` holds the result of a
// throwing new, the null edge is never taken, also when the variable is written again, as in
// `delete p; p = nullptr;`. A leak after an overwrite stays reported.

void delete_once()
{
int* once = new int(1);
delete once;
}

void delete_then_reset()
{
int* reset = new int(1);
delete reset;
reset = nullptr;
}

void delete_reset_delete()
{
int* again = new int(1);
delete again;
again = nullptr;
delete again;
}

void delete_then_reuse_slot()
{
int* slot = new int(1);
delete slot;
slot = new int(2);
delete slot;
}

void delete_copy_then_reset()
{
int* owner = new int(1);
int* alias = owner;
delete alias;
alias = nullptr;
}

void user_check_then_reset()
{
int* checked = new int(1);
if (checked == nullptr)
return;
delete checked;
checked = nullptr;
}

void overwrite_without_delete()
{
int* lost = new int(1);
lost = new int(2);
delete lost;
}

void delete_on_one_branch(bool release)
{
int* maybe = new int(1);
if (release)
delete maybe;
maybe = new int(2);
delete maybe;
}

void reuse_without_second_delete()
{
int* reused = new int(1);
delete reused;
reused = new int(2);
}

void reset_without_delete()
{
int* dropped = new int(1);
dropped = nullptr;
}

void reset_then_delete()
{
int* late = new int(1);
late = nullptr;
delete late;
}

// not contains: potential resource leak: 'CppHeap' acquired in handle 'once'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'reset'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'again'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'slot'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'owner'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'checked'
// not contains: potential resource leak: 'CppHeap' acquired in handle 'lost' may leave the function without being released
// not contains: potential resource leak: 'CppHeap' acquired in handle 'maybe' may leave the function without being released
// not contains: potential resource leak: 'CppHeap' acquired in handle 'reused' may be overwritten while still owned

// at line 55, column 17
// [ !!Warn ] potential resource leak: 'CppHeap' acquired in handle 'lost' is overwritten while still owned

// at line 62, column 18
// [ !!Warn ] potential resource leak: 'CppHeap' acquired in handle 'maybe' may be overwritten while still owned

// at line 73, column 14
// [ !!Warn ] potential resource leak: 'CppHeap' acquired in handle 'reused' is not released in this function

// at line 78, column 20
// [ !!Warn ] potential resource leak: 'CppHeap' acquired in handle 'dropped' is overwritten while still owned

// at line 84, column 17
// [ !!Warn ] potential resource leak: 'CppHeap' acquired in handle 'late' is overwritten while still owned
Loading