Skip to content
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
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@ Notable changes are grouped by release. See [all releases](https://github.com/Co

## Unreleased

- `ResourceLifetime.DoubleRelease` is decided release by release by the ownership engine where
it can. A release of a pointer that holds only NULL or a resource still owned no longer gets a
report: a release on each branch of an `if`/`else` or `switch`, in a `catch` that returns,
after `p = NULL`, or of a null pointer in a function that allocates nothing. A potential
double release is now also reported through an alias, including one passed to a release
wrapper (`q = p; free(p); free(q);` only got the "inter-procedural resource analysis
incomplete" warning), and when every allocation a pointer may hold was released before. The
double releases already reported stay, such as a second call to a release wrapper in the same
or another file, or `release_both(p, p)` when the callee always releases both parameters.
Where the engine cannot decide (a pointer from unknown code, a resource unknown code may hold,
a release inside a loop, two releases in one call that may not run together, or may release
different allocations), the previous counters decide as before, including the
"released without a matching acquire" check. The message is unchanged; `--verbose` prints the
engine's verdict on each release (`[DR-VERDICT]`). Still not handled: conditions correlated
across branches (#105), a release repeated by a loop (#275), a reset to NULL joined with a path
where the resource is live (#276), a variable given an unrelated pointer (#277), and a callee
that resets `*pp` to NULL (#278).
- An index-bounds pilot bounds `buf[i]` on a stack array, indexed directly rather than through
a pointer, with ScalarEvolution. It works on a copy of the function whose local variables live
in registers; the analyzed IR is unchanged. An index the copy proves in bounds no longer gets a
Expand Down
45 changes: 45 additions & 0 deletions include/analysis/ownership/OwnershipEngine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,51 @@ namespace ctrace::stack::analysis::ownership
std::vector<ReleasedUse> releasedUses(const OwnershipFacts& facts,
const OwnershipResult& result);

/// What the engine can tell about one release (DoubleRelease).
enum class ReleaseOutcome : std::uint8_t
{
Unknown, // the engine cannot decide: the caller keeps its own checks
Checked, // everything the released location may hold is null or a resource still owned
Detected, // the location may hold a resource released before: a potential double release
};

/// The verdict on the location released at one instruction, by a Release event or by a
/// parameter of a Call event that releases an owned resource without uncertainty.
struct ReleaseVerdict
{
std::uint32_t instructionIndex = 0;
LocationId location = 0;
ResourceId resource = 0; // Detected: one of the released resources the location holds
ReleaseOutcome outcome = ReleaseOutcome::Unknown;
std::uint8_t reservedPadding[3] = {};
};

/// Every release reached in the stabilised states (edges included), in block/event order,
/// judged on the state just before it:
/// - one possible resource and nothing else: Detected when it may be Released (the
/// releasedUses filter), Checked when it is only Owned and certain;
/// - several possibilities (resources, null, unknown): Detected when each resource is
/// Released on every path where it exists, Checked when each is only Owned and certain
/// and nothing is unknown;
/// - null only: Checked; unknown only or nothing tracked: Unknown.
/// The parameters of one Call are all judged on the state before the call: argument order is
/// not execution order. When two of them hold exactly the same single resource and both
/// release it on every normal exit, the later one in argument order is Detected. When their
/// targets merely overlap, or the other one may release only on some exits, a Checked
/// verdict becomes Unknown. Copies of one release (the edges of an invoke) must agree, else
/// Unknown. Empty when incomplete. Meant to be read off withUnknownAtEntry(facts).
std::vector<ReleaseVerdict> judgeReleases(const OwnershipFacts& facts,
const OwnershipResult& result);

/// `facts` with "unknown" written at entry into every location that may hold a value the
/// engine does not follow: every storage location (`isSlot[loc]`, or a location that is not
/// Local) and every SSA value that no event writes (the result of an unknown call, an
/// argument, untracked memory). Such a location is otherwise empty, and a join forgets an
/// empty path: joined with a null path it would look "null only". Transitional: only the
/// DoubleRelease verdicts solve these facts; the other rules still read an empty location as
/// holding nothing.
OwnershipFacts withUnknownAtEntry(const OwnershipFacts& facts, const std::vector<bool>& isSlot);

/// Union of t[s] over the states s in `in`.
StateSet applyTransformer(const ParamTransformer& t, StateSet in);

Expand Down
15 changes: 15 additions & 0 deletions include/analysis/ownership/ResourceFactCollector.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "analysis/ResourceModel.hpp"
#include "analysis/ownership/OwnershipFacts.hpp"

#include <cstdint>
#include <functional>
#include <string>
#include <vector>
Expand All @@ -21,6 +22,19 @@ namespace llvm

namespace ctrace::stack::analysis::ownership
{
/// A release the engine judges for DoubleRelease: the location released by one event, and
/// the argument path it comes from (a model rule's argument, a summarised parameter passed
/// by value, or a summarised pointee). Calls whose summary is incomplete give none.
struct ReleaseEffect
{
ArgPath path;
std::uint32_t instructionIndex = 0; // the event's Event::instructionIndex
LocationId location = 0;
LocationId nameLocation = 0; // the slot the released pointer was read from, to name it
bool pointee = false; // the release is of what the argument points to, not of the argument
std::uint8_t reservedPadding[3] = {};
};

struct CollectedFunction
{
OwnershipFacts facts;
Expand All @@ -30,6 +44,7 @@ namespace ctrace::stack::analysis::ownership
std::vector<const llvm::Instruction*> siteInstructions; // by site id
std::vector<std::string> siteKinds; // resource kind by site id
std::vector<const llvm::BasicBlock*> blockOf; // by block id
std::vector<ReleaseEffect> releaseEffects; // in collection order
};

struct SummaryLookup
Expand Down
72 changes: 72 additions & 0 deletions run_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2486,6 +2486,77 @@ def check_ownership_cross_tu() -> bool:
return ok


def check_double_release_cross_tu() -> bool:
"""
DoubleRelease through release wrappers defined in another file, judged by the ownership
engine on their summaries: a second release through a wrapper, an alias passed to one, or
release_both(p, p) is reported; wrappers on exclusive branches, after a reset to NULL, or on
distinct allocations are not. Same result in memory, over three runs sharing a summary cache
(the third reads every summary from it), and with Z3. Alone, the caller sees unknown callees
and reports no double release.
"""
print("=== Testing DoubleRelease through cross-TU release wrappers ===")
model = "models/resource-lifetime/generic.txt"
fixtures = RUN_CONFIG.test_dir / "resource-lifetime"
files = [
str(fixtures / "cross-tu-double-release-def.c"),
str(fixtures / "cross-tu-double-release-use.c"),
]
reported = ((17, "twice"), (24, "mixed"), (31, "swapped"), (38, "maybe"), (46, "copy"),
(53, "chained"), (59, "same"))
expected = [
f"at line {line}, column 5\n\t[!!!Error] potential double release: 'HeapAlloc' handle '{handle}'"
for line, handle in reported
]
lines = ", ".join(str(line) for line, _ in reported)
smt_args = [
"--smt=on",
"--smt-backend=z3",
"--smt-mode=single",
f"--smt-rules={','.join(_all_smt_rules())}",
f"--smt-timeout-ms={SMT_FIXTURE_TIMEOUT_MS}",
]

def as_expected(output: str) -> bool:
return (
output.count("potential double release") == len(expected)
and all(text in output for text in expected)
and "inter-procedural resource analysis incomplete" not in output
)

ok = True
with tempfile.TemporaryDirectory(prefix="ct_double_release_cross_tu_") as tmp:
tmpdir = Path(tmp)
common = [
f"--resource-model={model}",
"--warnings-only",
f"--compile-ir-cache-dir={tmpdir / 'compile-ir-cache'}",
]
runs = [("memory only", files + common + ["--resource-summary-cache-memory-only"])]
for mode, extra in (("default", []), ("smt-z3", smt_args)):
cache = tmpdir / f"summaries-{mode}"
for run in ("first", "second", "third"):
runs.append((f"{mode} ({run})",
files + common + [f"--resource-summary-cache-dir={cache}"] + extra))
for label, args in runs:
result = run_analyzer_uncached(args)
output = result.stdout or ""
if result.returncode != 0 or not as_expected(output):
print(f" ❌ {label}: expected exactly the double releases of lines {lines}")
print(output + (result.stderr or ""))
ok = False
result = run_analyzer_uncached(
[files[1]] + common + ["--resource-summary-cache-memory-only"])
output = result.stdout or ""
if result.returncode != 0 or "potential double release" in output:
print(" ❌ caller alone: the wrappers are unknown, no double release expected")
print(output + (result.stderr or ""))
ok = False
if ok:
print(" ✅ DoubleRelease through cross-TU wrappers OK\n")
return ok


def check_ownership_wrapper_metadata() -> bool:
"""Wrappers preserve uncertainty and conditional acquisitions, including cached summaries."""
print("=== Testing ownership wrapper metadata ===")
Expand Down Expand Up @@ -5872,6 +5943,7 @@ def record_ok(ok: bool):
check_resource_lifetime_cross_tu,
check_resource_model_across_compile_directories,
check_ownership_cross_tu,
check_double_release_cross_tu,
check_ownership_wrapper_metadata,
check_uninitialized_cross_tu,
check_uninitialized_cross_tu_no_effect,
Expand Down
Loading
Loading