From 23e7915e0c4123cffc2383dfcac209657cace293 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 1/8] feat(ownership): judge each release from the stabilised states judgeReleases reads, at every Release event and every parameter of a Call that releases an owned resource without uncertainty, what the released location may hold just before it. It returns one verdict per instruction and location. Detected: the location holds one resource that may be released (the filter of releasedUses), or several possibilities, each released on every path where it exists. Checked: it holds null only, or resources that are only owned and certain, and nothing unknown. Unknown: anything else, and everything when the solve is incomplete. The parameters of one call are judged on the state before the call: argument order is not execution order. When two of them hold exactly the same single resource and the callee releases both on every normal exit, the later one is Detected. When their targets only overlap, or a release is only possible, a Checked verdict becomes Unknown. Copies of one release on the edges of an invoke must agree. Nothing uses the verdicts yet. --- .../analysis/ownership/OwnershipEngine.hpp | 36 ++ src/analysis/ownership/OwnershipEngine.cpp | 180 ++++++++++ test/unit/ownership_engine_unit_tests.cpp | 328 ++++++++++++++++++ 3 files changed, 544 insertions(+) diff --git a/include/analysis/ownership/OwnershipEngine.hpp b/include/analysis/ownership/OwnershipEngine.hpp index d8a79d1..549cdb0 100644 --- a/include/analysis/ownership/OwnershipEngine.hpp +++ b/include/analysis/ownership/OwnershipEngine.hpp @@ -62,6 +62,42 @@ namespace ctrace::stack::analysis::ownership std::vector 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. + std::vector judgeReleases(const OwnershipFacts& facts, + const OwnershipResult& result); + /// Union of t[s] over the states s in `in`. StateSet applyTransformer(const ParamTransformer& t, StateSet in); diff --git a/src/analysis/ownership/OwnershipEngine.cpp b/src/analysis/ownership/OwnershipEngine.cpp index fd6dbf3..c2df5a0 100644 --- a/src/analysis/ownership/OwnershipEngine.cpp +++ b/src/analysis/ownership/OwnershipEngine.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -349,6 +350,185 @@ namespace ctrace::stack::analysis::ownership return found; } + namespace + { + constexpr StateSet kOwnedInput = StateSet::of(OwnState::Owned); + + /// A parameter that releases an owned resource on some normal exit, knowingly. + bool releasesOwned(const ParamTransformer& t) + { + return t[static_cast(OwnState::Owned)].has(OwnState::Released) && + !t.isUncertain(kOwnedInput); + } + + /// A parameter that releases an owned resource on every normal exit, knowingly. + bool alwaysReleasesOwned(const ParamTransformer& t) + { + return t[static_cast(OwnState::Owned)].isOnly(OwnState::Released) && + !t.isUncertain(kOwnedInput); + } + + /// A parameter through which an owned resource may be released, even by unknown code. + bool mayReleaseOwned(const ParamTransformer& t) + { + return t[static_cast(OwnState::Owned)].has(OwnState::Released) || + t.isUncertain(kOwnedInput); + } + + /// The states of `r` on the paths where it exists. + StateSet existingStates(const AbstractState& s, ResourceId r) + { + StateSet st = s.resources[r]; + st.bits &= static_cast(~StateSet::of(OwnState::NotOwned).bits); + return st; + } + + ReleaseOutcome judgeContents(const AbstractState& s, const Contents& held) + { + if (held.resources.empty()) + return held.mayNull && !held.mayUnknown ? ReleaseOutcome::Checked + : ReleaseOutcome::Unknown; + const auto releasedEverywhere = [&](ResourceId r) + { return existingStates(s, r).isOnly(OwnState::Released); }; + const auto owned = [&](ResourceId r) + { return existingStates(s, r).isOnly(OwnState::Owned) && !s.uncertain[r]; }; + if (held.resources.size() == 1 && !held.mayNull && !held.mayUnknown) + { + // One possible target: "may be Released" means some path releases it twice (or + // a correlation the engine does not follow, #105). Same filter as releasedUses. + const ResourceId r = held.resources.front(); + if (s.resources[r].has(OwnState::Released) && + (!s.uncertain[r] || releasedEverywhere(r))) + return ReleaseOutcome::Detected; + return owned(r) ? ReleaseOutcome::Checked : ReleaseOutcome::Unknown; + } + // Several possibilities: the join may pair "released" with "the location holds + // something else", so every resource must be released wherever it exists. + if (std::all_of(held.resources.begin(), held.resources.end(), releasedEverywhere)) + return ReleaseOutcome::Detected; + if (!held.mayUnknown && + std::all_of(held.resources.begin(), held.resources.end(), owned)) + return ReleaseOutcome::Checked; + return ReleaseOutcome::Unknown; + } + + bool shareResource(const Contents& a, const Contents& b) + { + return std::any_of(a.resources.begin(), a.resources.end(), + [&](ResourceId r) { return b.holds(r); }); + } + } // namespace + + std::vector judgeReleases(const OwnershipFacts& facts, + const OwnershipResult& result) + { + std::vector verdicts; + if (result.incomplete) + return verdicts; + + // One verdict per (instruction, location): copies of a release must agree. + std::map, std::size_t> indexOf; + const auto record = [&](std::uint32_t instruction, LocationId loc, ReleaseOutcome outcome, + const Contents& held) + { + const auto [it, inserted] = indexOf.try_emplace({instruction, loc}, verdicts.size()); + if (inserted) + { + ReleaseVerdict v; + v.instructionIndex = instruction; + v.location = loc; + // Detected: every resource held is released, the first one names them. + v.resource = held.resources.empty() ? 0 : held.resources.front(); + v.outcome = outcome; + verdicts.push_back(v); + } + else if (verdicts[it->second].outcome != outcome) + { + verdicts[it->second].outcome = ReleaseOutcome::Unknown; + } + }; + + // Every parameter of a call is judged on the state before the call: a per-parameter + // summary does not tell whether two possible releases happen on the same path. + const auto judgeCall = [&](const Event& e, const AbstractState& s) + { + const auto& params = e.call.params; + std::vector> outcome(params.size()); + for (std::size_t k = 0; k < params.size(); ++k) + { + if (releasesOwned(params[k].second)) + outcome[k] = judgeContents(s, s.locations[params[k].first]); + } + for (std::size_t k = 0; k < params.size(); ++k) + { + if (!outcome[k]) + continue; + const Contents& mine = s.locations[params[k].first]; + for (std::size_t j = 0; j < params.size(); ++j) + { + const Contents& theirs = s.locations[params[j].first]; + if (j == k || !shareResource(mine, theirs)) + continue; + // Overlapping targets are not the same target on the same path + // (`if (c) { x = a; y = b; } else { x = b; y = a; }`): only one exact + // resource, held by both, is. + const bool sameTarget = mine.resources.size() == 1 && + mine.isExactly(mine.resources.front()) && + theirs.isExactly(mine.resources.front()); + if (sameTarget && outcome[j] && alwaysReleasesOwned(params[k].second) && + alwaysReleasesOwned(params[j].second)) + { + // Both always run on the same resource: the call releases it twice. + // The later parameter carries it (the order inside the callee is + // unknown). + if (k > j) + outcome[k] = ReleaseOutcome::Detected; + } + else if (mayReleaseOwned(params[j].second) && + *outcome[k] == ReleaseOutcome::Checked) + { + // A second release of the same resource by this call is neither + // established nor excluded: no verdict either way. + outcome[k] = ReleaseOutcome::Unknown; + } + } + } + for (std::size_t k = 0; k < params.size(); ++k) + { + if (outcome[k]) + record(e.instructionIndex, params[k].first, *outcome[k], + s.locations[params[k].first]); + } + }; + + const auto step = [&](const Event& e, AbstractState& s) + { + if (e.kind == Event::Kind::Release) + record(e.instructionIndex, e.src, judgeContents(s, s.locations[e.src]), + s.locations[e.src]); + else if (e.kind == Event::Kind::Call) + judgeCall(e, s); + applyEvent(facts, e, s); + }; + for (std::uint32_t block = 0; block < facts.blocks.size(); ++block) + { + if (block >= result.in.size() || !result.in[block].reached) + continue; + AbstractState state = result.in[block]; + for (const Event& e : facts.blocks[block].events) + step(e, state); + for (const Edge& edge : facts.edges) + { + if (edge.from != block) + continue; + AbstractState along = state; + for (const Event& e : edge.events) + step(e, along); + } + } + return verdicts; + } + OwnershipResult solve(const OwnershipFacts& facts, const AbstractState& entry, unsigned iterationLimit) { diff --git a/test/unit/ownership_engine_unit_tests.cpp b/test/unit/ownership_engine_unit_tests.cpp index 360c6c2..89b43f6 100644 --- a/test/unit/ownership_engine_unit_tests.cpp +++ b/test/unit/ownership_engine_unit_tests.cpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace { @@ -1182,6 +1183,332 @@ namespace } return r.failures == 0; } + + Event releaseAt(LocationId src, std::uint32_t id, Certainty c = Certainty::Guaranteed) + { + Event e = release(src, c); + e.instructionIndex = id; + return e; + } + /// A summarised parameter whose Owned input becomes `imageOfOwned`. + ParamTransformer releasing(StateSet imageOfOwned, bool uncertain = false) + { + ParamTransformer t = identityTransformer(); + t[static_cast(OwnState::Owned)] = imageOfOwned; + if (uncertain) + t.uncertainInputs = StateSet::of(OwnState::Owned); + return t; + } + Event callAt(std::uint32_t id, std::vector> params) + { + Event e; + e.kind = Event::Kind::Call; + e.instructionIndex = id; + e.call.params = std::move(params); + return e; + } + + // DoubleRelease verdicts, one per released location and instruction. + bool testReleaseVerdicts(TestReport& r) + { + using Outcome = ReleaseOutcome; + using Verdicts = std::map, Outcome>; + const StateSet released = StateSet::of(OwnState::Released); + const StateSet mayRelease = StateSet::of(OwnState::Owned) | released; + const StateSet handedToUnknown = released | StateSet::of(OwnState::Escaped); + const auto judged = [](const OwnershipFacts& f, unsigned limit = 0) + { + const OwnershipResult res = solve(f, entryOf(f), limit); + Verdicts out; + for (const ReleaseVerdict& v : judgeReleases(f, res)) + out[{v.instructionIndex, v.location}] = v.outcome; + return out; + }; + const auto is = [](const Verdicts& v, std::uint32_t id, LocationId loc, Outcome o) + { + const auto it = v.find({id, loc}); + return it != v.end() && it->second == o; + }; + const auto none = [](const Verdicts& v, std::uint32_t id, LocationId loc) + { return v.find({id, loc}) == v.end(); }; + + // ---- one possible resource --------------------------------------------------------- + { + OwnershipFacts f = facts(1, {}, 1, 1); + f.blocks[0].events = {acquire(0, 0), releaseAt(0, 1), releaseAt(0, 2), exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 2, 0, Outcome::Detected), + "Verdicts: the first release is checked, the second detected"); + // Site 1, whose resource id is not 0. + OwnershipFacts g = facts(1, {}, 1, 2); + g.blocks[0].events = {acquire(1, 0), releaseAt(0, 1), releaseAt(0, 2), exit()}; + bool named = false; + for (const ReleaseVerdict& verdict : judgeReleases(g, solve(g, entryOf(g)))) + { + named = named || + (verdict.instructionIndex == 2 && verdict.outcome == Outcome::Detected && + verdict.resource == newInstanceOf(1)); + } + r.expect(named, "Verdicts: a detected release names the resource released before"); + } + { + // 0 → 1 (release) → 3, 0 → 2 → 3; 3: release. + OwnershipFacts f = + facts(4, {edge(0, 1, {releaseAt(0, 1)}), edge(0, 2), edge(1, 3), edge(2, 3)}, 1, 1); + f.blocks[0].events = {acquire(0, 0)}; + f.blocks[3].events = {releaseAt(0, 2), exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 2, 0, Outcome::Detected), + "Verdicts: a release on one path, then on every path, is detected"); + } + { + OwnershipFacts f = facts(4, {edge(0, 1), edge(0, 2), edge(1, 3), edge(2, 3)}, 1, 1); + f.blocks[0].events = {acquire(0, 0)}; + f.blocks[1].events = {releaseAt(0, 1)}; + f.blocks[2].events = {releaseAt(0, 2)}; + f.blocks[3].events = {exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 2, 0, Outcome::Checked), + "Verdicts: releases on mutually exclusive paths are both checked"); + } + { + OwnershipFacts f = facts(1, {}, 1, 1); + f.blocks[0].events = {acquire(0, 0), addressEscape(0), releaseAt(0, 1), exit()}; + r.expect(is(judged(f), 1, 0, Outcome::Unknown), + "Verdicts: a resource unknown code may hold is unknown"); + Event unknown; + unknown.kind = Event::Kind::UnknownCall; + unknown.args = {0}; + f.blocks[0].events = {acquire(0, 0), unknown, releaseAt(0, 1), releaseAt(0, 2), exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Unknown) && is(v, 2, 0, Outcome::Detected), + "Verdicts: an uncertain resource is unknown, then detected once certainly " + "released"); + } + { + // global = p; free(p). Location 1 is a global. + OwnershipFacts f = facts(1, {}, 2, 1); + f.locations[1].kind = LocationKind::NonLocal; + f.blocks[0].events = {acquire(0, 0), copy(1, 0), releaseAt(0, 1), exit()}; + r.expect(is(judged(f), 1, 0, Outcome::Unknown), + "Verdicts: a resource handed over to someone else is unknown"); + } + + // ---- null, unknown, nothing tracked ---------------------------------------------- + { + OwnershipFacts f = facts(1, {}, 1, 1); + f.blocks[0].events = {acquire(0, 0), releaseAt(0, 1), overwrite(0), releaseAt(0, 2), + exit()}; + r.expect(is(judged(f), 2, 0, Outcome::Checked), + "Verdicts: releasing a location that holds only null is checked"); + f.blocks[0].events = {acquire(0, 0), releaseAt(0, 1), overwrite(0, /*unknown=*/true), + releaseAt(0, 2), exit()}; + r.expect(is(judged(f), 2, 0, Outcome::Unknown), + "Verdicts: releasing an unknown pointer is unknown"); + } + { + OwnershipFacts f = facts(1, {}, 1, 0); + f.blocks[0].events = {releaseAt(0, 1), overwrite(0), releaseAt(0, 2), exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Unknown) && is(v, 2, 0, Outcome::Checked), + "Verdicts: without acquisitions, nothing tracked is unknown, null is checked"); + } + { + // free(p); if (c) p = NULL; free(p). + OwnershipFacts f = + facts(4, {edge(0, 1, {overwrite(0)}), edge(0, 2), edge(1, 3), edge(2, 3)}, 1, 1); + f.blocks[0].events = {acquire(0, 0), releaseAt(0, 1)}; + f.blocks[3].events = {releaseAt(0, 2), exit()}; + r.expect(is(judged(f), 2, 0, Outcome::Detected), + "Verdicts: null or a resource released on every path is detected"); + } + { + // if (err) goto fail; free(p); p = NULL; fail: free(p). + OwnershipFacts f = facts( + 4, + {edge(0, 1), edge(0, 2, {releaseAt(0, 1), overwrite(0)}), edge(1, 3), edge(2, 3)}, + 1, 1); + f.blocks[0].events = {acquire(0, 0)}; + f.blocks[3].events = {releaseAt(0, 2), exit()}; + r.expect(is(judged(f), 2, 0, Outcome::Unknown), + "Verdicts: null or a resource released on some paths only is unknown"); + } + + // ---- several possible resources -------------------------------------------------- + { + // a, b acquired; [free(a); free(b);] p = c ? a : b; free(p). + const auto choice = [&](bool releaseA, bool releaseB) + { + OwnershipFacts f = facts( + 4, {edge(0, 1, {copy(2, 0)}), edge(0, 2, {copy(2, 1)}), edge(1, 3), edge(2, 3)}, + 3, 2); + f.blocks[0].events = {acquire(0, 0), acquire(1, 1)}; + if (releaseA) + f.blocks[0].events.push_back(releaseAt(0, 1)); + if (releaseB) + f.blocks[0].events.push_back(releaseAt(1, 2)); + f.blocks[3].events = {releaseAt(2, 3), exit()}; + return judged(f); + }; + r.expect(is(choice(true, true), 3, 2, Outcome::Detected), + "Verdicts: both possible resources already released is detected"); + r.expect(is(choice(true, false), 3, 2, Outcome::Unknown), + "Verdicts: one possible resource released, the other live, is unknown"); + r.expect(is(choice(false, false), 3, 2, Outcome::Checked), + "Verdicts: both possible resources live is checked"); + } + { + // [free(a);] q = c ? a : unknown_ptr(); free(q). + const auto orUnknown = [&](bool releaseA) + { + OwnershipFacts f = + facts(4, + {edge(0, 1, {copy(1, 0)}), edge(0, 2, {overwrite(1, /*unknown=*/true)}), + edge(1, 3), edge(2, 3)}, + 2, 1); + f.blocks[0].events = {acquire(0, 0)}; + if (releaseA) + f.blocks[0].events.push_back(releaseAt(0, 1)); + f.blocks[3].events = {releaseAt(1, 2), exit()}; + return judged(f); + }; + r.expect(is(orUnknown(true), 2, 1, Outcome::Detected), + "Verdicts: an unknown pointer or a resource released everywhere is detected"); + r.expect(is(orUnknown(false), 2, 1, Outcome::Unknown), + "Verdicts: an unknown pointer or a live resource is unknown"); + } + + // ---- several releases at one instruction ------------------------------------------- + { + // release_both(p, q) with q = p: both parameters released on every normal exit. + OwnershipFacts f = facts(1, {}, 2, 1); + f.blocks[0].events = {acquire(0, 0), copy(1, 0), + callAt(1, {{0, releasing(released)}, {1, releasing(released)}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 1, 1, Outcome::Detected), + "Verdicts: a call that always releases one resource twice is detected once"); + } + { + // if (c) { x = a; y = b; } else { x = b; y = a; } release_both(x, y): both may hold + // a or b, but never the same one; each allocation is released exactly once. + OwnershipFacts f = facts(4, + {edge(0, 1, {copy(2, 0), copy(3, 1)}), + edge(0, 2, {copy(2, 1), copy(3, 0)}), edge(1, 3), edge(2, 3)}, + 4, 2); + f.blocks[0].events = {acquire(0, 0), acquire(1, 1)}; + f.blocks[3].events = {callAt(1, {{2, releasing(released)}, {3, releasing(released)}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 2, Outcome::Unknown) && is(v, 1, 3, Outcome::Unknown), + "Verdicts: overlapping targets of two parameters are not the same target: " + "unknown, not detected"); + } + { + // Three parameters always released, all naming one resource. + OwnershipFacts f = facts(1, {}, 3, 1); + f.blocks[0].events = {acquire(0, 0), copy(1, 0), copy(2, 0), + callAt(1, {{0, releasing(released)}, + {1, releasing(released)}, + {2, releasing(released)}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 1, 1, Outcome::Detected) && + is(v, 1, 2, Outcome::Detected), + "Verdicts: each later parameter of a triple release is detected"); + } + { + // release_one(p, q, c) with q = p: each parameter released on some exits only. + OwnershipFacts f = facts(1, {}, 2, 1); + f.blocks[0].events = { + acquire(0, 0), copy(1, 0), + callAt(1, {{0, releasing(mayRelease)}, {1, releasing(mayRelease)}}), exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Unknown) && is(v, 1, 1, Outcome::Unknown), + "Verdicts: possible releases of one resource by two parameters are unknown, " + "not a sequence"); + f.blocks[0].events = { + acquire(0, 0), copy(1, 0), releaseAt(0, 1), + callAt(2, {{0, releasing(mayRelease)}, {1, releasing(mayRelease)}}), exit()}; + const Verdicts after = judged(f); + r.expect(is(after, 2, 0, Outcome::Detected) && is(after, 2, 1, Outcome::Detected), + "Verdicts: a resource released before the call stays detected"); + } + { + // Parameter 1 names the same resource and hands it to unknown code. + OwnershipFacts f = facts(1, {}, 2, 1); + f.blocks[0].events = { + acquire(0, 0), copy(1, 0), + callAt(1, {{0, releasing(released)}, {1, releasing(handedToUnknown, true)}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Unknown) && none(v, 1, 1), + "Verdicts: a parameter that may release through unknown code makes another " + "unknown, and is not judged itself"); + } + { + // Parameter 1 names the same resource and only uses it. + OwnershipFacts f = facts(1, {}, 2, 1); + f.blocks[0].events = {acquire(0, 0), copy(1, 0), + callAt(1, {{0, releasing(released)}, {1, identityTransformer()}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && none(v, 1, 1), + "Verdicts: a parameter that does not release changes nothing"); + } + { + OwnershipFacts f = facts(1, {}, 2, 2); + f.blocks[0].events = {acquire(0, 0), acquire(1, 1), + callAt(1, {{0, releasing(released)}, {1, releasing(released)}}), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 1, 1, Outcome::Checked), + "Verdicts: a call releasing two distinct resources checks both"); + } + { + // Two model-rule releases of one instruction share the rule's condition. + OwnershipFacts f = facts(1, {}, 2, 1); + f.blocks[0].events = {acquire(0, 0), copy(1, 0), releaseAt(0, 1), releaseAt(1, 1), + exit()}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Checked) && is(v, 1, 1, Outcome::Detected), + "Verdicts: model-rule releases of one instruction are played in order"); + } + + // ---- copies, loops, incomplete solves ------------------------------------------------ + { + OwnershipFacts f = facts(3, + {edge(0, 1, {releaseAt(0, 1)}), + edge(0, 2, {releaseAt(0, 1, Certainty::Conditional)})}, + 1, 1); + f.blocks[0].events = {acquire(0, 0)}; + f.blocks[1].events = {exit()}; + f.blocks[2].events = {exit(true)}; + r.expect(is(judged(f), 1, 0, Outcome::Checked), + "Verdicts: copies of one release that agree give one verdict"); + f.edges[1].events = {releaseAt(0, 9), releaseAt(0, 1, Certainty::Conditional)}; + const Verdicts v = judged(f); + r.expect(is(v, 1, 0, Outcome::Unknown) && is(v, 9, 0, Outcome::Checked), + "Verdicts: copies of one release that disagree are unknown"); + } + { + OwnershipFacts f = facts(3, {edge(0, 1), edge(1, 1), edge(1, 2)}, 1, 1); + f.blocks[0].events = {acquire(0, 0)}; + f.blocks[1].events = {releaseAt(0, 1)}; + f.blocks[2].events = {exit()}; + r.expect(is(judged(f), 1, 0, Outcome::Detected), + "Verdicts: the engine itself has no loop rule (the analysis applies it)"); + r.expect(judged(f, /*limit=*/1).empty(), "Verdicts: nothing from an incomplete solve"); + } + { + // keep(p): the callee may release p through unknown code. + OwnershipFacts f = facts(1, {}, 1, 1); + f.blocks[0].events = {acquire(0, 0), callAt(1, {{0, releasing(handedToUnknown, true)}}), + exit()}; + r.expect(none(judged(f), 1, 0), "Verdicts: an uncertain release is not judged"); + } + return r.failures == 0; + } } // namespace int main(int, char**) @@ -1191,6 +1518,7 @@ int main(int, char**) (void)testEngine(report); (void)testUses(report); (void)testUsedArgs(report); + (void)testReleaseVerdicts(report); (void)testContracts(report); (void)testEdgeExits(report); (void)testExitUncertainty(report); From 197af4d544d31fa2400144ed4c8dcca677cd9140 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 2/8] feat(ownership): start untracked values unknown for release verdicts The fact collector leaves a location empty when it holds a value the engine does not follow: the result of an unknown call, an argument, untracked memory, a slot not written yet. A join then forgets the empty path, so `h = NULL; if (c) h = unknown_ptr(); free(h);` looks like a release of null only. withUnknownAtEntry writes "unknown" at entry into every storage location and every SSA value that no event writes. The release verdicts are meant to be read off these facts; UseAfterRelease, MissingRelease and ReferenceLost keep solving the collector's facts. The second solve is a transition until untracked values get an explicit representation for every rule (#281). --- .../analysis/ownership/OwnershipEngine.hpp | 11 +++- src/analysis/ownership/OwnershipEngine.cpp | 49 ++++++++++++++ test/unit/ownership_engine_unit_tests.cpp | 65 +++++++++++++++++++ 3 files changed, 124 insertions(+), 1 deletion(-) diff --git a/include/analysis/ownership/OwnershipEngine.hpp b/include/analysis/ownership/OwnershipEngine.hpp index 549cdb0..0521d7a 100644 --- a/include/analysis/ownership/OwnershipEngine.hpp +++ b/include/analysis/ownership/OwnershipEngine.hpp @@ -94,10 +94,19 @@ namespace ctrace::stack::analysis::ownership /// 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. + /// Unknown. Empty when incomplete. Meant to be read off withUnknownAtEntry(facts). std::vector 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& isSlot); + /// Union of t[s] over the states s in `in`. StateSet applyTransformer(const ParamTransformer& t, StateSet in); diff --git a/src/analysis/ownership/OwnershipEngine.cpp b/src/analysis/ownership/OwnershipEngine.cpp index c2df5a0..4e3ffcd 100644 --- a/src/analysis/ownership/OwnershipEngine.cpp +++ b/src/analysis/ownership/OwnershipEngine.cpp @@ -419,6 +419,55 @@ namespace ctrace::stack::analysis::ownership } } // namespace + OwnershipFacts withUnknownAtEntry(const OwnershipFacts& facts, const std::vector& isSlot) + { + OwnershipFacts prepared = facts; + std::vector written(facts.locations.size(), false); + const auto markWritten = [&written](const Event& e) + { + switch (e.kind) + { + case Event::Kind::Acquire: + case Event::Kind::Copy: + case Event::Kind::Overwrite: + written[e.dst] = true; + break; + case Event::Kind::Call: + if (e.call.retDest) + written[*e.call.retDest] = true; + for (const auto& [loc, certainty] : e.call.outArgs) + written[loc] = true; + break; + default: + break; + } + }; + for (const Block& block : facts.blocks) + std::for_each(block.events.begin(), block.events.end(), markWritten); + for (const Edge& edge : facts.edges) + std::for_each(edge.events.begin(), edge.events.end(), markWritten); + + std::vector unknownAtEntry; + for (LocationId loc = 0; loc < facts.locations.size(); ++loc) + { + const LocationKind kind = facts.locations[loc].kind; + const bool slot = loc < isSlot.size() && isSlot[loc]; + // An SSA value is written once, before any use, by the event that defines it. + const bool definedValue = kind == LocationKind::Local && !slot && written[loc]; + if (kind == LocationKind::Return || definedValue) + continue; + Event e; + e.kind = Event::Kind::Overwrite; + e.dst = loc; + e.unknownValue = true; + unknownAtEntry.push_back(e); + } + if (!prepared.blocks.empty()) + prepared.blocks[0].events.insert(prepared.blocks[0].events.begin(), + unknownAtEntry.begin(), unknownAtEntry.end()); + return prepared; + } + std::vector judgeReleases(const OwnershipFacts& facts, const OwnershipResult& result) { diff --git a/test/unit/ownership_engine_unit_tests.cpp b/test/unit/ownership_engine_unit_tests.cpp index 89b43f6..18142de 100644 --- a/test/unit/ownership_engine_unit_tests.cpp +++ b/test/unit/ownership_engine_unit_tests.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -1208,6 +1209,69 @@ namespace return e; } + // The facts the DoubleRelease verdicts are read off: what the engine does not follow starts + // unknown, so that a join cannot forget it. + bool testUnknownAtEntry(TestReport& r) + { + using Outcome = ReleaseOutcome; + const auto verdictAt = [](const OwnershipFacts& f, std::uint32_t id, LocationId loc) + { + const OwnershipResult res = solve(f, entryOf(f)); + for (const ReleaseVerdict& v : judgeReleases(f, res)) + { + if (v.instructionIndex == id && v.location == loc) + return std::optional(v.outcome); + } + return std::optional(); + }; + { + // h = NULL; if (c) h = untracked(); free(h). Location 1 is a value no event writes. + OwnershipFacts f = + facts(4, {edge(0, 1, {copy(0, 1)}), edge(0, 2), edge(1, 3), edge(2, 3)}, 2, 0); + f.blocks[0].events = {overwrite(0)}; + f.blocks[3].events = {releaseAt(0, 1), exit()}; + const std::vector isSlot = {true, false}; + r.expect(verdictAt(f, 1, 0) == Outcome::Checked, + "UnknownAtEntry: on the collector's facts, the untracked path is forgotten"); + r.expect(verdictAt(withUnknownAtEntry(f, isSlot), 1, 0) == Outcome::Unknown, + "UnknownAtEntry: an untracked value joined with null is unknown"); + r.expect(f.blocks[0].events.size() == 1, + "UnknownAtEntry: the collector's facts are left as they are"); + } + { + // char *h; if (c) h = NULL; free(h): the slot is not written on one path. + OwnershipFacts f = + facts(4, {edge(0, 1, {overwrite(0)}), edge(0, 2), edge(1, 3), edge(2, 3)}, 1, 0); + f.blocks[3].events = {releaseAt(0, 1), exit()}; + r.expect(verdictAt(withUnknownAtEntry(f, {true}), 1, 0) == Outcome::Unknown, + "UnknownAtEntry: a slot not written on one path is unknown"); + f.blocks[0].events = {overwrite(0)}; + r.expect(verdictAt(withUnknownAtEntry(f, {true}), 1, 0) == Outcome::Checked, + "UnknownAtEntry: a slot written on every path keeps what was written"); + } + { + // An SSA value defined by an acquisition keeps it: free(v); free(v). + OwnershipFacts f = facts(1, {}, 1, 1); + f.blocks[0].events = {acquire(0, 0), releaseAt(0, 1), releaseAt(0, 2), exit()}; + const OwnershipFacts g = withUnknownAtEntry(f, {false}); + r.expect(verdictAt(g, 1, 0) == Outcome::Checked && + verdictAt(g, 2, 0) == Outcome::Detected, + "UnknownAtEntry: a value written by its definition keeps it"); + } + { + // p = malloc(8) into a slot whose address leaves the function (weak writes). + OwnershipFacts f = facts(1, {}, 2, 1); + f.locations[1].strongUpdatable = false; + f.blocks[0].events = {acquire(0, 0), copy(1, 0), releaseAt(1, 1), exit()}; + const std::vector isSlot = {false, true}; + r.expect(verdictAt(f, 1, 1) == Outcome::Checked, + "UnknownAtEntry: on the collector's facts, the weak slot looks owned"); + r.expect(verdictAt(withUnknownAtEntry(f, isSlot), 1, 1) == Outcome::Unknown, + "UnknownAtEntry: a slot written weakly keeps unknown"); + } + return r.failures == 0; + } + // DoubleRelease verdicts, one per released location and instruction. bool testReleaseVerdicts(TestReport& r) { @@ -1519,6 +1583,7 @@ int main(int, char**) (void)testUses(report); (void)testUsedArgs(report); (void)testReleaseVerdicts(report); + (void)testUnknownAtEntry(report); (void)testContracts(report); (void)testEdgeExits(report); (void)testExitUncertainty(report); From f177a5b57822bb7a82d78f0d4f0b011571d81421 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 3/8] feat(resource-lifetime): record the argument each judged release comes from CollectedFunction gains releaseEffects. For every release the engine may judge, it records the event, the released location, the argument path it comes from (a model rule's argument, a summarised parameter passed by value, or a summarised pointee) and the slot the released pointer was read from, to name it. A call whose summary is incomplete records none. --- .../ownership/ResourceFactCollector.hpp | 15 +++++ .../ownership/ResourceFactCollector.cpp | 64 +++++++++++++++++-- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/include/analysis/ownership/ResourceFactCollector.hpp b/include/analysis/ownership/ResourceFactCollector.hpp index f6dc6b0..65e54cd 100644 --- a/include/analysis/ownership/ResourceFactCollector.hpp +++ b/include/analysis/ownership/ResourceFactCollector.hpp @@ -7,6 +7,7 @@ #include "analysis/ResourceModel.hpp" #include "analysis/ownership/OwnershipFacts.hpp" +#include #include #include #include @@ -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; @@ -30,6 +44,7 @@ namespace ctrace::stack::analysis::ownership std::vector siteInstructions; // by site id std::vector siteKinds; // resource kind by site id std::vector blockOf; // by block id + std::vector releaseEffects; // in collection order }; struct SummaryLookup diff --git a/src/analysis/ownership/ResourceFactCollector.cpp b/src/analysis/ownership/ResourceFactCollector.cpp index bcdb257..3fa7bf5 100644 --- a/src/analysis/ownership/ResourceFactCollector.cpp +++ b/src/analysis/ownership/ResourceFactCollector.cpp @@ -774,6 +774,47 @@ namespace ctrace::stack::analysis::ownership return t[static_cast(OwnState::Owned)].has(OwnState::Released); } + static ArgPath byValue(unsigned argIndex) + { + ArgPath path; + path.argIndex = argIndex; + return path; + } + + /// The location to name a released pointer by: the slot it was just loaded from. + LocationId nameOf(const llvm::Value* arg, LocationId fallback) const + { + if (const auto* load = llvm::dyn_cast(arg->stripPointerCasts())) + { + if (const auto it = loadedFrom_.find(load); it != loadedFrom_.end()) + return it->second; + } + return fallback; + } + + void recordRelease(std::uint32_t instructionIndex, LocationId loc, const ArgPath& path, + bool pointee, LocationId nameLocation) + { + ReleaseEffect effect; + effect.path = path; + effect.instructionIndex = instructionIndex; + effect.location = loc; + effect.nameLocation = nameLocation; + effect.pointee = pointee; + out_.releaseEffects.push_back(effect); + } + + /// A summarised parameter the engine may judge for DoubleRelease: a release the + /// callee claims knowingly, in a summary that can be trusted. + void recordSummaryRelease(const FunctionOwnershipSummary& summary, const Event& e, + LocationId loc, const ArgPath& path, bool pointee, + LocationId nameLocation, const ParamTransformer& t) + { + if (!summary.incomplete && releases(t) && + !t.isUncertain(StateSet::of(OwnState::Owned))) + recordRelease(e.instructionIndex, loc, path, pointee, nameLocation); + } + /// Arguments this call may release as passed (model rule or summary). With /// `knownOnly`, a summary counts only where that release is not uncertain: a callee /// that hands the argument to unknown code may also use it. @@ -950,6 +991,10 @@ namespace ctrace::stack::analysis::ownership return std::nullopt; Event e = make(Event::Kind::Release, call); e.src = valueLocation(call.getArgOperand(rule.argIndex)); + ArgPath path; + path.argIndex = rule.argIndex; + recordRelease(e.instructionIndex, e.src, path, false, + nameOf(call.getArgOperand(rule.argIndex), e.src)); return e; } case RuleAction::NoEffect: @@ -984,13 +1029,18 @@ namespace ctrace::stack::analysis::ownership if (argIndex >= call.arg_size() || !call.getArgOperand(argIndex)->getType()->isPointerTy()) continue; - e.call.params.push_back( - {valueLocation(call.getArgOperand(argIndex)), transformer}); + const LocationId loc = valueLocation(call.getArgOperand(argIndex)); + e.call.params.push_back({loc, transformer}); + recordSummaryRelease(summary, e, loc, byValue(argIndex), false, + nameOf(call.getArgOperand(argIndex), loc), transformer); } for (const auto& [path, transformer] : t.pointeeParams) { if (const auto slot = slotOfArgPath(call, path)) + { e.call.params.push_back({*slot, transformer}); + recordSummaryRelease(summary, e, *slot, path, true, *slot, transformer); + } } if (t.returns.certainty != Certainty::Unknown && call.getType()->isPointerTy()) { @@ -1030,13 +1080,19 @@ namespace ctrace::stack::analysis::ownership if (argIndex >= call.arg_size() || !call.getArgOperand(argIndex)->getType()->isPointerTy()) continue; - x.call.params.push_back( - {valueLocation(call.getArgOperand(argIndex)), transformer}); + const LocationId loc = valueLocation(call.getArgOperand(argIndex)); + x.call.params.push_back({loc, transformer}); + recordSummaryRelease(summary, x, loc, byValue(argIndex), false, + nameOf(call.getArgOperand(argIndex), loc), + transformer); } for (const auto& [path, transformer] : summary.exceptional.pointeeParams) { if (const auto slot = slotOfArgPath(call, path)) + { x.call.params.push_back({*slot, transformer}); + recordSummaryRelease(summary, x, *slot, path, true, *slot, transformer); + } } for (const auto& [path, fresh] : summary.exceptional.outArgs) { From f438973bc5889db302600b85ebb2c8937b4af2d3 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 4/8] feat(resource-lifetime): judge every release before the counters The ownership engine now runs once per function before the counters, and also in a function that releases without acquiring anything, so that freeing a null pointer does not depend on an unrelated allocation. Its verdicts are mapped to the call and argument they belong to, read off withUnknownAtEntry, and a release inside a CFG cycle is never Detected: the engine cannot tell a loop that repeats a release from a guard that runs it once (#275). `--verbose` prints each verdict as `[DR-VERDICT] file:line:column function effect verdict`, and the work of the extra solve as `[DR-COST]`. Diagnostics do not change. --- src/analysis/ResourceLifetimeAnalysis.cpp | 193 ++++++++++++++++++++-- 1 file changed, 183 insertions(+), 10 deletions(-) diff --git a/src/analysis/ResourceLifetimeAnalysis.cpp b/src/analysis/ResourceLifetimeAnalysis.cpp index 34ec304..d6348c1 100644 --- a/src/analysis/ResourceLifetimeAnalysis.cpp +++ b/src/analysis/ResourceLifetimeAnalysis.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -21,9 +22,12 @@ #include #include +#include #include #include #include +#include +#include #include #include #include @@ -2256,22 +2260,189 @@ namespace ctrace::stack::analysis namespace { - /// Runs the ownership engine on one function and turns its stabilised states into - /// UseAfterRelease / MissingRelease / ReferenceLost / AnalysisIncomplete issues (spec §8). - void analyzeWithOwnershipEngine(const llvm::Function& F, const ResourceModel& model, + /// The engine's DoubleRelease verdict on one release, keyed as the counters see a + /// release: the call and the argument (or pointee) it releases. + struct ReleaseJudgement + { + const llvm::Instruction* inst = nullptr; + ownership::ArgPath path; + std::string resourceKind; // Detected: the kind of the released resource + std::string handleName; // the slot the released pointer was read from + bool pointee = false; + ownership::ReleaseOutcome outcome = ownership::ReleaseOutcome::Unknown; + std::uint8_t reservedPadding[6] = {}; + }; + + /// Verdicts per release, in block/event order, read off `facts` (withUnknownAtEntry) and its + /// result. Copies of one release (an invoke's edges, an exceptional summary) must agree, + /// else Unknown. Inside a CFG cycle, a release is never Detected: the engine cannot tell + /// a loop that repeats it from a guard that runs it once (#275), so the counters keep + /// deciding there. + std::vector + judgeReleaseEffects(const llvm::Function& F, const ownership::CollectedFunction& collected, + const ownership::OwnershipFacts& facts, + const ownership::OwnershipResult& result) + { + using namespace ownership; + std::vector judgements; + if (collected.releaseEffects.empty()) + return judgements; + + std::map, std::vector> + effectsAt; + for (const ReleaseEffect& effect : collected.releaseEffects) + effectsAt[{effect.instructionIndex, effect.location}].push_back(&effect); + + std::unordered_set cyclic; + bool cyclesComputed = false; + const auto inCycle = [&](const llvm::Instruction* inst) + { + if (!cyclesComputed) + { + for (auto scc = llvm::scc_begin(&F); !scc.isAtEnd(); ++scc) + { + if (scc.hasCycle()) + cyclic.insert((*scc).begin(), (*scc).end()); + } + cyclesComputed = true; + } + return cyclic.count(inst->getParent()) != 0; + }; + + std::map, std::size_t> indexOf; + for (const ReleaseVerdict& verdict : judgeReleases(facts, result)) + { + const auto it = effectsAt.find({verdict.instructionIndex, verdict.location}); + if (it == effectsAt.end()) + continue; // not a release the engine may judge (e.g. an incomplete summary) + const llvm::Instruction* inst = + collected.eventInstructions[verdict.instructionIndex]; + // One location released for two arguments at once cannot be told apart. + ReleaseOutcome outcome = + it->second.size() == 1 ? verdict.outcome : ReleaseOutcome::Unknown; + if (outcome == ReleaseOutcome::Detected && inCycle(inst)) + outcome = ReleaseOutcome::Unknown; + for (const ReleaseEffect* effect : it->second) + { + const auto [slot, inserted] = indexOf.try_emplace( + std::make_tuple(inst, effect->path, effect->pointee), judgements.size()); + if (inserted) + { + ReleaseJudgement judgement; + judgement.inst = inst; + judgement.path = effect->path; + judgement.pointee = effect->pointee; + judgement.outcome = outcome; + const std::uint32_t site = verdict.resource / 2u; + if (site < collected.siteKinds.size()) + judgement.resourceKind = collected.siteKinds[site]; + judgement.handleName = collected.locationIsSlot[effect->nameLocation] + ? collected.locationNames[effect->nameLocation] + : std::string(""); + judgements.push_back(std::move(judgement)); + } + else if (judgements[slot->second].outcome != outcome) + { + judgements[slot->second].outcome = ReleaseOutcome::Unknown; + } + } + } + return judgements; + } + + /// `[DR-VERDICT] file:line:column function effect verdict`, at Debug level (--verbose): + /// the engine's verdicts, read directly on the analysed programs. + void traceReleaseJudgements(const llvm::Function& F, + const std::vector& judgements) + { + for (const ReleaseJudgement& judgement : judgements) + { + std::string file = ""; + unsigned line = 0; + unsigned column = 0; + if (const llvm::DILocation* loc = judgement.inst->getDebugLoc().get()) + { + file = loc->getFilename().str(); + line = loc->getLine(); + column = loc->getColumn(); + } + std::string effect = judgement.pointee ? "*arg" : "arg"; + effect += std::to_string(judgement.path.argIndex); + if (judgement.path.offset != 0) + effect += "+" + std::to_string(judgement.path.offset); + if (judgement.path.viaPointerSlot) + effect += "(via)"; + const char* verdict = "Unknown"; + if (judgement.outcome == ownership::ReleaseOutcome::Checked) + verdict = "Checked"; + else if (judgement.outcome == ownership::ReleaseOutcome::Detected) + verdict = "Detected"; + coretrace::log(coretrace::Level::Debug, "[DR-VERDICT] {}:{}:{} {} {} {}\n", file, + line, column, F.getName().str(), effect, verdict); + } + } + + /// One function's ownership engine run: the collected facts, the main solve (when the + /// function acquires something) and the DoubleRelease verdicts (when it releases + /// something). + struct OwnershipRun + { + ownership::CollectedFunction collected; + std::optional result; + std::vector judgements; + }; + + OwnershipRun runOwnershipEngine(const llvm::Function& F, const ResourceModel& model, const ownership::SummaryLookup& summaries, - const llvm::DataLayout& DL, - std::vector& issues) + const llvm::DataLayout& DL) { using namespace ownership; + OwnershipRun run; + run.collected = collectOwnershipFacts(F, model, summaries, DL); + const CollectedFunction& collected = run.collected; + const bool acquires = !collected.siteInstructions.empty(); + if (!acquires && collected.releaseEffects.empty()) + return run; // nothing acquired or released here - const CollectedFunction collected = collectOwnershipFacts(F, model, summaries, DL); - if (collected.siteInstructions.empty()) - return; // nothing acquired here: nothing to leak + const AbstractState entry = AbstractState::entry(2u * collected.facts.siteCount, + collected.facts.locations.size()); + // A release is judged even where nothing is acquired: freeing a null pointer must + // not depend on an unrelated allocation in the same function. + std::uint64_t judgeVisits = 0; + if (!collected.releaseEffects.empty()) + { + const OwnershipFacts judged = + withUnknownAtEntry(collected.facts, collected.locationIsSlot); + const OwnershipResult judgedResult = solve(judged, entry); + judgeVisits = judgedResult.blockVisits; + run.judgements = judgeReleaseEffects(F, collected, judged, judgedResult); + traceReleaseJudgements(F, run.judgements); + } + std::uint64_t mainVisits = 0; + if (acquires) + { + run.result = solve(collected.facts, entry); + mainVisits = run.result->blockVisits; + } + // The cost of the separate DoubleRelease solve (block visits), for measurement only. + coretrace::log(coretrace::Level::Debug, "[DR-COST] {} blocks={} main={} judge={}\n", + F.getName().str(), collected.facts.blocks.size(), mainVisits, + judgeVisits); + return run; + } + /// Turns the main solve of `run` into UseAfterRelease / MissingRelease / ReferenceLost / + /// AnalysisIncomplete issues (spec §8). Nothing when the function acquires nothing. + void reportOwnershipIssues(const llvm::Function& F, const OwnershipRun& run, + std::vector& issues) + { + using namespace ownership; + if (!run.result) + return; // nothing acquired here: nothing to leak or to use after a release + const CollectedFunction& collected = run.collected; + const OwnershipResult& result = *run.result; const AbstractState entry = AbstractState::entry(2u * collected.facts.siteCount, collected.facts.locations.size()); - const OwnershipResult result = solve(collected.facts, entry); const auto issueFor = [&](ResourceId r, ResourceLifetimeIssueKind kind) { @@ -2498,6 +2669,8 @@ namespace ctrace::stack::analysis std::unordered_map unknownAcquireEscapeCache; std::unordered_set interprocUncertaintyReported; std::unordered_set releasedEscapeReported; + // The ownership engine runs first: it judges every release (--verbose traces it). + const OwnershipRun ownershipRun = runOwnershipEngine(F, model, ownershipLookup, DL); auto trackAcquire = [&](const StorageKey& storage, const std::string& resourceKind, const llvm::Instruction* anchorInst) { @@ -2887,7 +3060,7 @@ namespace ctrace::stack::analysis // UseAfterRelease and MissingRelease come from the ownership engine (spec §8); the // counters above keep serving the other rules. - analyzeWithOwnershipEngine(F, model, ownershipLookup, DL, issues); + reportOwnershipIssues(F, ownershipRun, issues); if (methodInfo.isDtor && !methodInfo.className.empty()) { From 882cb4fae7da37e37c3b65a4927568dac856bd1d Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 5/8] fix(resource-lifetime): let the engine's verdict decide each DoubleRelease The DoubleRelease counters still count and deduplicate as before. At a release with a verdict, the verdict decides what they emit there: Checked emits nothing, Detected emits one DoubleRelease (their own text when they had one), and Unknown emits what they emitted before. A Detected release for which the counters keep no local handle is reported by the engine alone. Releases on mutually exclusive paths, after a reset to NULL, or of another allocation held by an alias no longer give a DoubleRelease or IncompleteInterproc warning. A second release through an alias, also one passed to a release wrapper, and a release of a pointer whose possible allocations were all released before, are now potential double releases. The "released without a matching acquire" check stays as the fallback where the engine has no verdict. Part of #104. --- src/analysis/ResourceLifetimeAnalysis.cpp | 192 ++++++++++++++-------- 1 file changed, 124 insertions(+), 68 deletions(-) diff --git a/src/analysis/ResourceLifetimeAnalysis.cpp b/src/analysis/ResourceLifetimeAnalysis.cpp index d6348c1..dee221d 100644 --- a/src/analysis/ResourceLifetimeAnalysis.cpp +++ b/src/analysis/ResourceLifetimeAnalysis.cpp @@ -2273,6 +2273,15 @@ namespace ctrace::stack::analysis std::uint8_t reservedPadding[6] = {}; }; + /// The engine's verdict on one release as the counters see it (a call and an argument + /// index and offset): the agreed outcome of the judgements it stands for, else Unknown. + struct EffectVerdict + { + std::vector judgements; + ownership::ReleaseOutcome outcome = ownership::ReleaseOutcome::Unknown; + std::uint8_t reservedPadding[7] = {}; + }; + /// Verdicts per release, in block/event order, read off `facts` (withUnknownAtEntry) and its /// result. Copies of one release (an invoke's edges, an exceptional summary) must agree, /// else Unknown. Inside a CFG cycle, a release is never Detected: the engine cannot tell @@ -2669,8 +2678,35 @@ namespace ctrace::stack::analysis std::unordered_map unknownAcquireEscapeCache; std::unordered_set interprocUncertaintyReported; std::unordered_set releasedEscapeReported; - // The ownership engine runs first: it judges every release (--verbose traces it). + // DoubleRelease: the engine judges every release first. The counters below count as + // before; at a release with a verdict, the verdict decides what they emit there. const OwnershipRun ownershipRun = runOwnershipEngine(F, model, ownershipLookup, DL); + std::map, + std::vector> + judgementsAt; + for (std::size_t index = 0; index < ownershipRun.judgements.size(); ++index) + { + const ReleaseJudgement& judgement = ownershipRun.judgements[index]; + judgementsAt[{judgement.inst, judgement.path.argIndex, judgement.path.offset}] + .push_back(index); + } + std::vector judgementHandled(ownershipRun.judgements.size(), false); + const auto verdictFor = + [&](const llvm::Instruction* inst, unsigned argIndex, std::uint64_t offset) + { + EffectVerdict verdict; + const auto it = judgementsAt.find({inst, argIndex, offset}); + if (it == judgementsAt.end()) + return verdict; + verdict.judgements = it->second; + verdict.outcome = ownershipRun.judgements[it->second.front()].outcome; + for (const std::size_t index : it->second) + { + if (ownershipRun.judgements[index].outcome != verdict.outcome) + verdict.outcome = ownership::ReleaseOutcome::Unknown; + } + return verdict; + }; auto trackAcquire = [&](const StorageKey& storage, const std::string& resourceKind, const llvm::Instruction* anchorInst) { @@ -2743,7 +2779,8 @@ namespace ctrace::stack::analysis }; auto trackRelease = [&](const StorageKey& storage, const std::string& resourceKind, - const llvm::Instruction* anchorInst, bool fromSummary) + const llvm::Instruction* anchorInst, bool fromSummary, + const EffectVerdict& verdict) { if (!storage.valid()) return; @@ -2781,32 +2818,28 @@ namespace ctrace::stack::analysis state.funcName = F.getName().str(); } + // What the counters report here. They count and deduplicate exactly as before, + // whatever the engine says. + std::optional counted; state.releases += 1; if (state.releases > state.acquires) { + counted = ResourceLifetimeIssueKind::DoubleRelease; if (state.acquires == 0 && state.storage.localAlloca) { const bool shouldReportInterproc = shouldReportIncompleteInterprocOnLocalStorage(state.storage); - auto emitIncompleteInterproc = [&](const char* debugPath) + const auto incompleteInterproc = + [&](const char* debugPath) -> std::optional { - if (!shouldReportInterproc) - return; - if (interprocUncertaintyReported.insert(stateKey).second) - { - coretrace::log(coretrace::Level::Info, - "[DEBUG-INTERPROC] PATH={} func={} handle={}\n", - debugPath, F.getName().str(), storage.displayName); - ResourceLifetimeIssue issue; - issue.funcName = F.getName().str(); - issue.resourceKind = resourceKind; - issue.handleName = storage.displayName.empty() - ? std::string("") - : storage.displayName; - issue.inst = anchorInst; - issue.kind = ResourceLifetimeIssueKind::IncompleteInterproc; - issues.push_back(std::move(issue)); - } + state.ownership = OwnershipState::Unknown; + if (!shouldReportInterproc || + !interprocUncertaintyReported.insert(stateKey).second) + return std::nullopt; + coretrace::log(coretrace::Level::Info, + "[DEBUG-INTERPROC] PATH={} func={} handle={}\n", + debugPath, F.getName().str(), storage.displayName); + return ResourceLifetimeIssueKind::IncompleteInterproc; }; // Parameter shadow slots often appear as local allocas under optnone. @@ -2814,59 +2847,43 @@ namespace ctrace::stack::analysis // acquires tracked, treat release as forwarding ownership, not double release. if (resolveAllocaArgumentShadow(*state.storage.localAlloca, false) != nullptr) - return; - - if (localStorageHasExplicitExternalStore(F, *state.storage.localAlloca, - state.storage.offset, DL)) { - emitIncompleteInterproc("externalStore"); - state.ownership = OwnershipState::Unknown; - return; + counted.reset(); } - - auto cacheIt = unknownAcquireEscapeCache.find(state.storage.localAlloca); - if (cacheIt == unknownAcquireEscapeCache.end()) + else if (localStorageHasExplicitExternalStore(F, *state.storage.localAlloca, + state.storage.offset, DL)) { - const bool mayEscapeToUnknownAcquire = - localAddressEscapesToUnmodeledCall( - F, *state.storage.localAlloca, model, functionSummaries, - externalMap.empty() ? nullptr : &externalMap, DL, - shouldAnalyze); - cacheIt = - unknownAcquireEscapeCache - .emplace(state.storage.localAlloca, mayEscapeToUnknownAcquire) - .first; + counted = incompleteInterproc("externalStore"); } - - // If address of this local may be handed to an unmodeled call, we cannot - // prove absence of acquisition. Keep diagnostics conservative and avoid a - // hard double-release error in this case. - if (cacheIt->second) + else { - emitIncompleteInterproc("escapeUnmodeled"); - state.ownership = OwnershipState::Unknown; - return; - } + auto cacheIt = + unknownAcquireEscapeCache.find(state.storage.localAlloca); + if (cacheIt == unknownAcquireEscapeCache.end()) + { + const bool mayEscapeToUnknownAcquire = + localAddressEscapesToUnmodeledCall( + F, *state.storage.localAlloca, model, functionSummaries, + externalMap.empty() ? nullptr : &externalMap, DL, + shouldAnalyze); + cacheIt = unknownAcquireEscapeCache + .emplace(state.storage.localAlloca, + mayEscapeToUnknownAcquire) + .first; + } - // Summary-originated releases are conservative by nature. - // If no concrete unknown-acquire evidence is found and this local - // is not a handle-like slot, suppress non-actionable noise. - if (fromSummary) - { - emitIncompleteInterproc("fromSummary"); - state.ownership = OwnershipState::Unknown; - return; + // If address of this local may be handed to an unmodeled call, we + // cannot prove absence of acquisition. Keep diagnostics conservative + // and avoid a hard double-release error in this case. + if (cacheIt->second) + counted = incompleteInterproc("escapeUnmodeled"); + // Summary-originated releases are conservative by nature. + // If no concrete unknown-acquire evidence is found and this local + // is not a handle-like slot, suppress non-actionable noise. + else if (fromSummary) + counted = incompleteInterproc("fromSummary"); } } - - ResourceLifetimeIssue issue; - issue.funcName = F.getName().str(); - issue.resourceKind = resourceKind; - issue.handleName = storage.displayName.empty() ? std::string("") - : storage.displayName; - issue.inst = anchorInst; - issue.kind = ResourceLifetimeIssueKind::DoubleRelease; - issues.push_back(std::move(issue)); } else if (state.releases == state.acquires) { @@ -2876,6 +2893,26 @@ namespace ctrace::stack::analysis { state.ownership = OwnershipState::Owned; } + + // The engine's verdict on this very release: Checked, it frees nothing released + // before (nothing is emitted here); Detected, one DoubleRelease here, whatever the + // counters said; Unknown, the counters decide, as before. + for (const std::size_t index : verdict.judgements) + judgementHandled[index] = true; + if (verdict.outcome == ownership::ReleaseOutcome::Checked) + return; + if (verdict.outcome == ownership::ReleaseOutcome::Detected) + counted = ResourceLifetimeIssueKind::DoubleRelease; + if (!counted) + return; + ResourceLifetimeIssue issue; + issue.funcName = F.getName().str(); + issue.resourceKind = resourceKind; + issue.handleName = + storage.displayName.empty() ? std::string("") : storage.displayName; + issue.inst = anchorInst; + issue.kind = *counted; + issues.push_back(std::move(issue)); }; for (llvm::BasicBlock& BB : F) @@ -2930,7 +2967,8 @@ namespace ctrace::stack::analysis break; const llvm::Value* handleArg = CB->getArgOperand(rule.argIndex); StorageKey storage = resolveHandleStorage(handleArg, F, DL, methodInfo); - trackRelease(storage, rule.resourceKind, &I, false); + trackRelease(storage, rule.resourceKind, &I, false, + verdictFor(&I, rule.argIndex, 0)); reportReleasedHandleEscapesIfNeeded(handleArg, rule.resourceKind, &I); break; } @@ -3004,12 +3042,30 @@ namespace ctrace::stack::analysis } else if (effect.action == RuleAction::ReleaseArg) { - trackRelease(storage, effect.resourceKind, &I, true); + trackRelease(storage, effect.resourceKind, &I, true, + verdictFor(&I, effect.argIndex, effect.offset)); } } } } + // A double release the engine detects where the counters keep no local handle (a + // field, a global, a summary they do not have): reported by the engine alone. + for (std::size_t index = 0; index < ownershipRun.judgements.size(); ++index) + { + const ReleaseJudgement& judgement = ownershipRun.judgements[index]; + if (judgement.outcome != ownership::ReleaseOutcome::Detected || + judgementHandled[index]) + continue; + ResourceLifetimeIssue issue; + issue.funcName = F.getName().str(); + issue.resourceKind = judgement.resourceKind; + issue.handleName = judgement.handleName; + issue.inst = judgement.inst; + issue.kind = ResourceLifetimeIssueKind::DoubleRelease; + issues.push_back(std::move(issue)); + } + for (const llvm::BasicBlock& BB : F) { for (const llvm::Instruction& I : BB) @@ -3059,7 +3115,7 @@ namespace ctrace::stack::analysis } // UseAfterRelease and MissingRelease come from the ownership engine (spec §8); the - // counters above keep serving the other rules. + // counters above keep serving the other rules, DoubleRelease filtered by its verdicts. reportOwnershipIssues(F, ownershipRun, issues); if (methodInfo.isDtor && !methodInfo.className.empty()) From 8f0ce118ad3519f12c3b8c13dd2e3a240f5b889d Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 6/8] test(resource-lifetime): cover DoubleRelease decided by the ownership engine Eight fixtures with a strict count pin double releases through aliases, several possible allocations, wrappers, unknown calls, loops and C++ catches, and their absence on exclusive paths, after a reset to NULL and for two releases of distinct allocations in one call. Two fixtures only pin the absence of a double release, without a strict count. In double-release-exclusive-aliases.c, x and y may each hold a or b but never the same one; the fallback warnings it still gets are tracked in #277. In double-release-delete-reset.cpp, deleting a pointer reset to nullptr deletes nothing; its false ReferenceLost is tracked in #282. check_double_release_cross_tu runs wrappers defined in another file in memory, over three runs sharing a summary cache, with Z3, and then the caller alone, where the wrappers are unknown. --- run_test.py | 72 ++++++++++++ .../cross-tu-double-release-def.c | 27 +++++ .../cross-tu-double-release-use.c | 90 ++++++++++++++ test/resource-lifetime/double-release-alias.c | 107 +++++++++++++++++ .../double-release-delete-reset.cpp | 17 +++ .../double-release-exceptions.cpp | 55 +++++++++ .../double-release-exclusive-aliases.c | 57 +++++++++ .../double-release-exclusive-paths.c | 71 +++++++++++ test/resource-lifetime/double-release-loop.c | 98 ++++++++++++++++ .../double-release-null-reset.c | 111 ++++++++++++++++++ .../double-release-several-args.c | 80 +++++++++++++ .../double-release-unknown.c | 45 +++++++ .../double-release-wrapper.c | 78 ++++++++++++ 13 files changed, 908 insertions(+) create mode 100644 test/resource-lifetime/cross-tu-double-release-def.c create mode 100644 test/resource-lifetime/cross-tu-double-release-use.c create mode 100644 test/resource-lifetime/double-release-alias.c create mode 100644 test/resource-lifetime/double-release-delete-reset.cpp create mode 100644 test/resource-lifetime/double-release-exceptions.cpp create mode 100644 test/resource-lifetime/double-release-exclusive-aliases.c create mode 100644 test/resource-lifetime/double-release-exclusive-paths.c create mode 100644 test/resource-lifetime/double-release-loop.c create mode 100644 test/resource-lifetime/double-release-null-reset.c create mode 100644 test/resource-lifetime/double-release-several-args.c create mode 100644 test/resource-lifetime/double-release-unknown.c create mode 100644 test/resource-lifetime/double-release-wrapper.c diff --git a/run_test.py b/run_test.py index a14c5f6..a841933 100755 --- a/run_test.py +++ b/run_test.py @@ -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 ===") @@ -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, diff --git a/test/resource-lifetime/cross-tu-double-release-def.c b/test/resource-lifetime/cross-tu-double-release-def.c new file mode 100644 index 0000000..b7dc0b4 --- /dev/null +++ b/test/resource-lifetime/cross-tu-double-release-def.c @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 +// Release wrappers for cross-tu-double-release-use.c (check_double_release_cross_tu). +#include + +// strict-diagnostic-count: false + +void xtu_free(void* p) +{ + free(p); +} + +void xtu_maybe_free(void* p, int c) +{ + if (c) + free(p); +} + +void xtu_free_chain(void* p) +{ + xtu_free(p); +} + +void xtu_release_both(void* a, void* b) +{ + free(a); + free(b); +} diff --git a/test/resource-lifetime/cross-tu-double-release-use.c b/test/resource-lifetime/cross-tu-double-release-use.c new file mode 100644 index 0000000..900cd22 --- /dev/null +++ b/test/resource-lifetime/cross-tu-double-release-use.c @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 +// Callers of the wrappers in cross-tu-double-release-def.c (check_double_release_cross_tu): +// double releases through wrappers defined in another file, judged on their summaries. +#include + +extern void xtu_free(void* p); +extern void xtu_maybe_free(void* p, int c); +extern void xtu_free_chain(void* p); +extern void xtu_release_both(void* a, void* b); + +// strict-diagnostic-count: false + +void wrapper_twice(void) +{ + char* twice = malloc(8); + xtu_free(twice); + xtu_free(twice); +} + +void direct_then_wrapper(void) +{ + char* mixed = malloc(8); + free(mixed); + xtu_free(mixed); +} + +void wrapper_then_direct(void) +{ + char* swapped = malloc(8); + xtu_free(swapped); + free(swapped); +} + +void released_then_maybe(int c) +{ + char* maybe = malloc(8); + free(maybe); + xtu_maybe_free(maybe, c); +} + +void alias_through_wrapper(void) +{ + char* owner = malloc(8); + char* copy = owner; + xtu_free(owner); + xtu_free(copy); +} + +void chain_twice(void) +{ + char* chained = malloc(8); + xtu_free_chain(chained); + xtu_free_chain(chained); +} + +void same_allocation_twice(void) +{ + char* same = malloc(8); + xtu_release_both(same, same); +} + +void wrapper_on_each_branch(int c) +{ + char* branch = malloc(8); + if (c) + xtu_free(branch); + else + xtu_free(branch); +} + +void wrapper_reset(void) +{ + char* reset = malloc(8); + xtu_free(reset); + reset = NULL; + xtu_free(reset); +} + +void wrapper_once(void) +{ + char* single = malloc(8); + xtu_free(single); +} + +void two_allocations(void) +{ + char* left = malloc(8); + char* right = malloc(8); + xtu_release_both(left, right); +} diff --git a/test/resource-lifetime/double-release-alias.c b/test/resource-lifetime/double-release-alias.c new file mode 100644 index 0000000..47eaf95 --- /dev/null +++ b/test/resource-lifetime/double-release-alias.c @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +extern char* unknown_ptr(void); + +// resource-model: models/resource-lifetime/generic.txt +// A second release through an alias of the same allocation is a double release; a single +// release through an alias is not. + +void alias_twice(void) +{ + char* alias_p = malloc(8); + char* alias_q = alias_p; + free(alias_p); + free(alias_q); +} + +void alias_reverse(void) +{ + char* rev_p = malloc(8); + char* rev_q = rev_p; + free(rev_q); + free(rev_p); +} + +void alias_once(void) +{ + char* once_p = malloc(8); + char* once_q = once_p; + free(once_q); +} + +void alias_chain(void) +{ + char* chain_p = malloc(8); + char* chain_q = chain_p; + char* chain_r = chain_q; + free(chain_p); + free(chain_r); +} + +struct box +{ + char* ptr; +}; + +void alias_field(void) +{ + char* field_p = malloc(8); + struct box b; + b.ptr = field_p; + free(field_p); + free(b.ptr); +} + +// Both allocations the pointer may hold are already released: a double release either way. +void both_released(int c) +{ + char* first = malloc(8); + char* second = malloc(8); + free(first); + free(second); + char* pick = c ? first : second; + free(pick); +} + +// Released, or null: a potential double release on the path where it is the allocation. +void released_or_null(int c) +{ + char* maybe = malloc(8); + free(maybe); + char* after_null = c ? maybe : NULL; + free(after_null); +} + +// Released, or an unknown pointer: a potential double release on the first path. +void released_or_unknown(int c) +{ + char* gone = malloc(8); + free(gone); + char* after_unknown = c ? gone : unknown_ptr(); + free(after_unknown); +} + +// not contains: inter-procedural resource analysis incomplete +// not contains: handle 'once_q' + +// at line 15, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'alias_q' is released without a matching acquire in this function + +// at line 23, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'rev_p' is released without a matching acquire in this function + +// at line 39, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'chain_r' is released without a matching acquire in this function + +// at line 53, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'b' is released without a matching acquire in this function + +// at line 64, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'pick' is released without a matching acquire in this function + +// at line 73, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'after_null' is released without a matching acquire in this function + +// at line 82, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'after_unknown' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-delete-reset.cpp b/test/resource-lifetime/double-release-delete-reset.cpp new file mode 100644 index 0000000..000a16e --- /dev/null +++ b/test/resource-lifetime/double-release-delete-reset.cpp @@ -0,0 +1,17 @@ +// 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 + +void delete_reset_delete() +{ + int* resetp = new int(1); + delete resetp; + resetp = nullptr; + delete resetp; +} + +// not contains: potential double release: 'CppHeap' handle 'resetp' diff --git a/test/resource-lifetime/double-release-exceptions.cpp b/test/resource-lifetime/double-release-exceptions.cpp new file mode 100644 index 0000000..0ca69d8 --- /dev/null +++ b/test/resource-lifetime/double-release-exceptions.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +typedef void* handle_t; +extern void acquire_handle(handle_t* out) noexcept; +extern void release_handle(handle_t handle) noexcept; +extern void may_throw(); + +// resource-model: models/resource-lifetime/generic.txt +// The path through a catch that releases and returns does not reach the release after the try; +// a catch that releases and falls through does. A delete on each branch deletes once. + +void catch_returns() +{ + handle_t returned; + acquire_handle(&returned); + try + { + may_throw(); + } + catch (...) + { + release_handle(returned); + return; + } + release_handle(returned); +} + +void catch_falls_through() +{ + handle_t fallen; + acquire_handle(&fallen); + try + { + may_throw(); + } + catch (...) + { + release_handle(fallen); + } + release_handle(fallen); +} + +void delete_on_each_branch(int c) +{ + int* branchp = new int(1); + if (c) + delete branchp; + else + delete branchp; +} + +// not contains: handle 'returned' +// not contains: handle 'branchp' + +// at line 39, column 5 +// [!!!Error] potential double release: 'GenericHandle' handle 'fallen' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-exclusive-aliases.c b/test/resource-lifetime/double-release-exclusive-aliases.c new file mode 100644 index 0000000..9e94a53 --- /dev/null +++ b/test/resource-lifetime/double-release-exclusive-aliases.c @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +// resource-model: models/resource-lifetime/generic.txt +// After the branch, x and y may each hold a or b, but never the same one: release_both(x, y) +// releases each allocation exactly once. Overlapping target sets are not one target, so no +// double release. release_both(p, p) does release one allocation twice. +// The fallback counters still report x and y as possibly acquired by an unmodeled callee, and +// the per-parameter summaries leave a and b possibly owned on exit (#277): only the double +// releases are pinned here. +// strict-diagnostic-count: false + +void release_both(int* x, int* y) +{ + free(x); + free(y); +} + +void exclusive_aliases(int c) +{ + int* a = malloc(sizeof *a); + int* b = malloc(sizeof *b); + if (!a || !b) + { + free(a); + free(b); + return; + } + int *x, *y; + if (c) + { + x = a; + y = b; + } + else + { + x = b; + y = a; + } + release_both(x, y); +} + +void same_pointer(void) +{ + int* p = malloc(sizeof *p); + if (!p) + return; + release_both(p, p); +} + +// not contains: potential double release: 'HeapAlloc' handle 'x' +// not contains: potential double release: 'HeapAlloc' handle 'y' +// not contains: potential double release: 'HeapAlloc' handle 'a' +// not contains: potential double release: 'HeapAlloc' handle 'b' + +// at line 48, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'p' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-exclusive-paths.c b/test/resource-lifetime/double-release-exclusive-paths.c new file mode 100644 index 0000000..7bf725c --- /dev/null +++ b/test/resource-lifetime/double-release-exclusive-paths.c @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +// resource-model: models/resource-lifetime/generic.txt +// Releases on mutually exclusive paths release the allocation once on each path: no double +// release. A release on one path followed by one on every path is a double release. + +void if_else(int c) +{ + char* branch = malloc(8); + if (c) + free(branch); + else + free(branch); +} + +void early_return(int c) +{ + char* early = malloc(8); + if (c) + { + free(early); + return; + } + free(early); +} + +void each_case(int c) +{ + char* cased = malloc(8); + switch (c) + { + case 0: + free(cased); + break; + case 1: + free(cased); + break; + default: + free(cased); + break; + } +} + +int cleanup_label(int c) +{ + char* labelled = malloc(8); + if (c) + goto out; + free(labelled); + return 0; +out: + free(labelled); + return 1; +} + +void conditional_then_always(int c) +{ + char* twice = malloc(8); + if (c) + free(twice); + free(twice); +} + +// not contains: handle 'branch' +// not contains: handle 'early' +// not contains: handle 'cased' +// not contains: handle 'labelled' + +// at line 62, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'twice' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-loop.c b/test/resource-lifetime/double-release-loop.c new file mode 100644 index 0000000..5329a32 --- /dev/null +++ b/test/resource-lifetime/double-release-loop.c @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +// resource-model: models/resource-lifetime/generic.txt +// Inside a loop, the ownership engine only clears releases: a release the loop may repeat is +// left to the counters (the guarded release in guarded_once runs once). After the loop, and +// within one iteration, double releases are reported. + +void each_iteration(int n) +{ + for (int i = 0; i < n; ++i) + { + char* fresh = malloc(8); + free(fresh); + } +} + +void guarded_once(int n) +{ + char* guarded = malloc(8); + for (int i = 0; i < n; ++i) + { + if (i == 0) + free(guarded); + } + free(guarded); +} + +void reset_in_loop(int n) +{ + char* cleared = NULL; + for (int i = 0; i < n; ++i) + { + cleared = malloc(8); + free(cleared); + cleared = NULL; + } + free(cleared); +} + +void released_before_loop(int n) +{ + char* early = malloc(8); + free(early); + for (int i = 0; i < n; ++i) + free(early); +} + +void twice_in_one_iteration(int n) +{ + for (int i = 0; i < n; ++i) + { + char* doubled = malloc(8); + free(doubled); + free(doubled); + } +} + +void exclusive_in_loop(int n, int c) +{ + for (int i = 0; i < n; ++i) + { + char* either = malloc(8); + if (c) + free(either); + else + free(either); + } +} + +void alias_after_loop(int n) +{ + char* origin = malloc(8); + char* later = origin; + for (int i = 0; i < n; ++i) + { + if (i == 0) + free(origin); + } + free(later); +} + +// not contains: handle 'fresh' +// not contains: handle 'cleared' +// not contains: handle 'either' +// not contains: handle 'origin' + +// at line 26, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'guarded' is released without a matching acquire in this function + +// at line 46, column 9 +// [!!!Error] potential double release: 'HeapAlloc' handle 'early' is released without a matching acquire in this function + +// at line 55, column 9 +// [!!!Error] potential double release: 'HeapAlloc' handle 'doubled' is released without a matching acquire in this function + +// at line 80, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'later' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-null-reset.c b/test/resource-lifetime/double-release-null-reset.c new file mode 100644 index 0000000..abc9bc9 --- /dev/null +++ b/test/resource-lifetime/double-release-null-reset.c @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +extern void acquire_handle(void** out); +extern void release_handle(void* h); +extern char* unknown_ptr(void); + +// resource-model: models/resource-lifetime/generic.txt +// Releasing a pointer reset to NULL releases nothing, with or without another allocation in the +// function. A pointer reset on one path only is still released twice on the other. + +void reacquired(void) +{ + char* again = malloc(8); + free(again); + again = malloc(8); + free(again); +} + +void reset_then_release(void) +{ + char* reset = malloc(8); + free(reset); + reset = NULL; + free(reset); +} + +void handle_reset_then_release(void) +{ + void* handle; + acquire_handle(&handle); + release_handle(handle); + handle = NULL; + release_handle(handle); +} + +void moved_then_reset(int err, void** arr) +{ + void* moved; + acquire_handle(&moved); + arr[0] = moved; + moved = NULL; + if (err) + release_handle(moved); +} + +int reset_before_cleanup(int err) +{ + char* cleaned = malloc(8); + free(cleaned); + cleaned = NULL; + if (err) + goto fail; + return 0; +fail: + free(cleaned); + return 1; +} + +void null_with_allocation(void) +{ + char* other = malloc(8); + free(other); + char* nothing = NULL; + free(nothing); +} + +void null_without_allocation(void) +{ + char* none = NULL; + free(none); +} + +void parameter_reset(char* param) +{ + param = NULL; + free(param); +} + +void reset_on_one_path(int c) +{ + char* partly = malloc(8); + free(partly); + if (c) + partly = NULL; + free(partly); +} + +// Null, or a pointer from unknown code: the release cannot be checked, the warning stays. +void null_or_unknown(int c) +{ + char* unsure = NULL; + if (c) + unsure = unknown_ptr(); + free(unsure); +} + +// not contains: handle 'again' +// not contains: handle 'reset' +// not contains: handle 'handle' +// not contains: handle 'moved' +// not contains: handle 'cleaned' +// not contains: handle 'nothing' +// not contains: handle 'none' +// not contains: handle 'param' + +// at line 86, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'partly' is released without a matching acquire in this function + +// at line 95, column 5 +// [ !!Warn ] inter-procedural resource analysis incomplete: handle 'unsure' may be acquired by an unmodeled/external callee before release diff --git a/test/resource-lifetime/double-release-several-args.c b/test/resource-lifetime/double-release-several-args.c new file mode 100644 index 0000000..bac1311 --- /dev/null +++ b/test/resource-lifetime/double-release-several-args.c @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +extern char* unknown_ptr(void); + +// resource-model: models/resource-lifetime/generic.txt +// A call with several release effects: argument order is not an execution order. Both +// parameters of release_both always run, so release_both(p, p) releases one allocation twice; +// two distinct allocations, or one released before the call, are judged on what each holds. + +static void release_both(void* a, void* b) +{ + free(a); + free(b); +} + +static void release_one(void* a, void* b, int c) +{ + if (c) + free(a); + else + free(b); +} + +void two_allocations(void) +{ + char* left = malloc(8); + char* right = malloc(8); + release_both(left, right); +} + +void same_allocation_twice(void) +{ + char* same = malloc(8); + release_both(same, same); +} + +void released_before_both(void) +{ + char* before = malloc(8); + char* other = malloc(8); + free(before); + release_both(before, other); +} + +void released_before_one(int c) +{ + char* prior = malloc(8); + free(prior); + release_one(prior, prior, c); +} + +// One argument checked, the other from unknown code: the verdict on one does not silence the +// warning on the other. +void one_unknown(void) +{ + char* known = malloc(8); + char* foreign = unknown_ptr(); + release_both(known, foreign); +} + +// not contains: handle 'left' +// not contains: handle 'right' +// not contains: handle 'other' +// not contains: handle 'known' + +// at line 35, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'same' is released without a matching acquire in this function + +// at line 43, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'before' is released without a matching acquire in this function + +// at line 50, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'prior' is released without a matching acquire in this function + +// at line 50, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'prior' is released without a matching acquire in this function + +// at line 59, column 5 +// [ !!Warn ] inter-procedural resource analysis incomplete: handle 'foreign' may be acquired by an unmodeled/external callee before release diff --git a/test/resource-lifetime/double-release-unknown.c b/test/resource-lifetime/double-release-unknown.c new file mode 100644 index 0000000..db46864 --- /dev/null +++ b/test/resource-lifetime/double-release-unknown.c @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +extern void unknown_sink(void* p); +extern void unknown_out(void** pp); + +// resource-model: models/resource-lifetime/generic.txt +// Unknown code cannot make a released pointer live again; a release it may have done makes the +// next release unknown, and the one after it a double release. + +void unknown_between(void) +{ + char* between = malloc(8); + free(between); + unknown_sink(between); + free(between); +} + +void unknown_before(void) +{ + char* handed = malloc(8); + unknown_sink(handed); + free(handed); + free(handed); +} + +void address_escapes_before(void) +{ + char* escaped = malloc(8); + unknown_out((void**)&escaped); + free(escaped); + free(escaped); +} + +// at line 15, column 18 +// [!!!Error] potential use-after-release: 'HeapAlloc' handle 'between' is used after a release in this function + +// at line 16, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'between' is released without a matching acquire in this function + +// at line 24, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'handed' is released without a matching acquire in this function + +// at line 32, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'escaped' is released without a matching acquire in this function diff --git a/test/resource-lifetime/double-release-wrapper.c b/test/resource-lifetime/double-release-wrapper.c new file mode 100644 index 0000000..c943e36 --- /dev/null +++ b/test/resource-lifetime/double-release-wrapper.c @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +// resource-model: models/resource-lifetime/generic.txt +// Wrappers defined in the same file release through their summary: a second release through a +// wrapper is a double release, including through an alias; a single one is not. + +static void my_free(void* p) +{ + free(p); +} + +static void maybe_free(void* p, int c) +{ + if (c) + free(p); +} + +void wrapper_twice(void) +{ + char* wrapped = malloc(8); + my_free(wrapped); + my_free(wrapped); +} + +void direct_then_wrapper(void) +{ + char* mixed = malloc(8); + free(mixed); + my_free(mixed); +} + +void wrapper_then_direct(void) +{ + char* swapped = malloc(8); + my_free(swapped); + free(swapped); +} + +void released_then_maybe(int c) +{ + char* maybe = malloc(8); + free(maybe); + maybe_free(maybe, c); +} + +void wrapper_once(void) +{ + char* single = malloc(8); + my_free(single); +} + +void alias_through_wrapper(void) +{ + char* owner = malloc(8); + char* copy = owner; + my_free(owner); + my_free(copy); +} + +// not contains: inter-procedural resource analysis incomplete +// not contains: handle 'single' +// not contains: handle 'owner' + +// at line 23, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'wrapped' is released without a matching acquire in this function + +// at line 30, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'mixed' is released without a matching acquire in this function + +// at line 37, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'swapped' is released without a matching acquire in this function + +// at line 44, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'maybe' is released without a matching acquire in this function + +// at line 58, column 5 +// [!!!Error] potential double release: 'HeapAlloc' handle 'copy' is released without a matching acquire in this function From 38cd323957d8e3db807df52e123fe78363d9ed36 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 7/8] test(resource-lifetime): restore the strict count of three resource fixtures release-all-paths-no-leak.c, cpp-exception-paths.cpp and alias-keeps-old-resource-no-leak.c opted out of the strict count because of a false DoubleRelease or IncompleteInterproc warning. Both are gone: the files get their strict count back, with negative assertions on the warnings they used to get. --- test/resource-lifetime/alias-keeps-old-resource-no-leak.c | 5 +++-- test/resource-lifetime/cpp-exception-paths.cpp | 8 +++----- test/resource-lifetime/release-all-paths-no-leak.c | 4 ++-- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/test/resource-lifetime/alias-keeps-old-resource-no-leak.c b/test/resource-lifetime/alias-keeps-old-resource-no-leak.c index 672780f..9bd3cd1 100644 --- a/test/resource-lifetime/alias-keeps-old-resource-no-leak.c +++ b/test/resource-lifetime/alias-keeps-old-resource-no-leak.c @@ -6,8 +6,7 @@ extern void release_handle(handle_t handle); extern int check(void); // resource-model: models/resource-lifetime/generic.txt -// Only MissingRelease is pinned here; other rules keep their (counter-based) behaviour. -// strict-diagnostic-count: false +// `saved` keeps the first resource and `h` the second: each is released once. void alias_keeps_old(void) { handle_t h; @@ -21,3 +20,5 @@ void alias_keeps_old(void) // not contains: potential resource leak // not contains: overwritten while still owned +// not contains: inter-procedural resource analysis incomplete +// not contains: potential double release diff --git a/test/resource-lifetime/cpp-exception-paths.cpp b/test/resource-lifetime/cpp-exception-paths.cpp index a9c6f03..70e09c2 100644 --- a/test/resource-lifetime/cpp-exception-paths.cpp +++ b/test/resource-lifetime/cpp-exception-paths.cpp @@ -6,12 +6,9 @@ extern void may_throw(); extern void never_throws() noexcept; // resource-model: models/resource-lifetime/generic.txt -// Only MissingRelease is pinned here. The two `release_handle(h)` calls sit on -// mutually exclusive paths, which the counter-based DoubleRelease rule (out of -// scope for the ownership engine) still reports; hence no strict count. -// strict-diagnostic-count: false // The catch releases: neither the normal nor the exceptional path of -// may_throw() leaves h owned. +// may_throw() leaves h owned. The two `release_handle(h)` calls sit on +// mutually exclusive paths: no double release. void caught_and_released() { handle_t h; @@ -29,3 +26,4 @@ void caught_and_released() } // not contains: potential resource leak +// not contains: potential double release diff --git a/test/resource-lifetime/release-all-paths-no-leak.c b/test/resource-lifetime/release-all-paths-no-leak.c index b8f8f16..6399171 100644 --- a/test/resource-lifetime/release-all-paths-no-leak.c +++ b/test/resource-lifetime/release-all-paths-no-leak.c @@ -6,8 +6,7 @@ extern void release_handle(handle_t handle); extern int check(void); // resource-model: models/resource-lifetime/generic.txt -// Only MissingRelease is pinned here; other rules keep their (counter-based) behaviour. -// strict-diagnostic-count: false +// Each path releases h once: no leak and no double release. void release_all_paths(int c) { handle_t h; @@ -19,3 +18,4 @@ void release_all_paths(int c) } // not contains: potential resource leak +// not contains: potential double release From 917decb869b2f943a29c66461280802ddb71dd38 Mon Sep 17 00:00:00 2001 From: Hugo Date: Sun, 15 Nov 2026 23:23:50 +0100 Subject: [PATCH 8/8] docs(changelog): describe DoubleRelease decided by the ownership engine --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2ad54f..737fd7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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