Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/smoke.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Smoke

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
CARGO_TERM_COLOR: always

jobs:
smoke:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
# rust-toolchain.toml pins the nightly toolchain + rustc-dev components;
# rustup installs them on first use.
- name: Build pn
run: cargo build --bin pn --verbose
- name: Run pipeline smoke tests (async + sync regression baselines)
run: ./scripts/smoke.sh
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ bench/**

.vscode
.DS_Store
tmp/
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ Default flags when none are given:
-m deadlock --pn-analysis-dir=<repo>/tmp
```

### Run smoke tests

`./scripts/smoke.sh` builds `pn`, analyzes the benchmark crates, and asserts each deadlock report's `Bug count` (and the lock-group count for async cases). It guards the async modeling (`bench/deadlock/async-deadlock` expects 1 bug / 2 lock groups; `bench/deadlock/async-no-deadlock` expects 0 bugs / 1 lock group) and the sync regression baselines. The same script runs in CI (`.github/workflows/smoke.yml`).

```bash
./scripts/smoke.sh # builds pn, runs all cases
PN_BIN=target/debug/pn ./scripts/smoke.sh # reuse an existing binary
```

## Common flags

| Flag | Meaning |
Expand Down
10 changes: 10 additions & 0 deletions bench/deadlock/async-no-deadlock/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "async-no-deadlock"
version = "0.1.0"
edition = "2021"

[workspace]

[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] }
parking_lot = { version = "0.12", features = ["send_guard"] }
30 changes: 30 additions & 0 deletions bench/deadlock/async-no-deadlock/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Async false-positive guard: two spawned tasks share a single mutex and hold
// it across an `.await` suspend point. There is no lock-order cycle (only one
// lock exists), so every interleaving can make progress and the analyzer must
// report zero deadlocks. Exercises suspend/resume semantics (C-007/T-003),
// cross-instance `Arc<Mutex>` alias merging (C-006), and spawn/join wiring
// (C-001..C-004) without a bug to find.
use std::sync::Arc;

use parking_lot::Mutex;

async fn task1(m: Arc<Mutex<i32>>) {
let mut _guard = m.lock();
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
*_guard += 1;
}

async fn task2(m: Arc<Mutex<i32>>) {
let mut _guard = m.lock();
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
*_guard += 2;
}

#[tokio::main]
async fn main() {
let m = Arc::new(Mutex::new(0));
let h1 = tokio::spawn(task1(m.clone()));
let h2 = tokio::spawn(task2(m.clone()));
let _ = h1.await;
let _ = h2.await;
}
110 changes: 110 additions & 0 deletions scripts/smoke.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env bash
#
# Petri-net pipeline smoke tests (todolist T-001).
#
# Builds `pn` (unless PN_BIN is set), analyzes the benchmark crates listed
# below, and asserts the deadlock report's `Bug count` — and, for the async
# cases, the number of lock groups discovered (`[lockgroup-detail]` log lines).
# These assertions guard the async modeling (C-001..C-012, T-003) and the
# sync regression baseline promised in the todolist "engineering constraints".
#
# Usage:
# ./scripts/smoke.sh # build pn + run all cases
# PN_BIN=target/debug/pn ./scripts/smoke.sh # reuse an existing binary
#
# Environment:
# PN_BIN pn binary to use (default: build target/debug/pn)
# PN_SMOKE_DIR scratch directory for reports/logs (default: <repo>/tmp/smoke)
# PN_LOG log level for pn (default: warn; lock-group lines need warn)

set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

PN_BIN="${PN_BIN:-}"
if [[ -z "$PN_BIN" ]]; then
echo "==> building pn"
cargo build --manifest-path "$DIR/Cargo.toml" --bin pn
PN_BIN="$DIR/target/debug/pn"
fi
[[ -x "$PN_BIN" ]] || { echo "pn binary not found/executable: $PN_BIN" >&2; exit 1; }

# pn links dynamically against the active toolchain's librustc_driver.
RUSTC_SYSROOT="$(rustc --print sysroot)"
export LD_LIBRARY_PATH="${RUSTC_SYSROOT}/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
export PN_LOG="${PN_LOG:-warn}"

TMP="${PN_SMOKE_DIR:-$DIR/tmp/smoke}"
rm -rf "$TMP"
mkdir -p "$TMP"

failures=0

# run_case <bench-dir> <crate-name> <expected-bugs> [expected-lock-groups|-]
run_case() {
local bench="$1" crate="$2" expect_bugs="$3" expect_groups="${4:--}"
local log="$TMP/$crate.log"
local out="$TMP/$crate"

local label="bugs=$expect_bugs"
if [[ "$expect_groups" != "-" ]]; then
label="$label groups=$expect_groups"
fi
echo "==> $bench (expect $label)"
if ! RUSTC_WRAPPER="$PN_BIN" \
PN_FLAGS="-m deadlock -p $crate --pn-analysis-dir=$out" \
CARGO_TARGET_DIR="$TMP/target" \
cargo build --manifest-path "$DIR/bench/$bench/Cargo.toml" >"$log" 2>&1; then
echo "FAIL: $crate: build/analysis failed (see $log)"
tail -n 5 "$log"
failures=$((failures + 1))
return
fi

local report="$out/$crate/deadlock_report.txt"
if [[ ! -f "$report" ]]; then
echo "FAIL: $crate: missing report $report"
failures=$((failures + 1))
return
fi

local bugs groups ok=1
bugs="$(sed -nE 's/^Bug count *: *([0-9]+).*/\1/p' "$report")"
if [[ "$bugs" != "$expect_bugs" ]]; then
echo "FAIL: $crate: bug count '$bugs' != expected '$expect_bugs'"
ok=0
fi

if [[ "$expect_groups" != "-" ]]; then
groups="$(grep -c '\[lockgroup-detail\] group' "$log" || true)"
if [[ "$groups" != "$expect_groups" ]]; then
echo "FAIL: $crate: lock groups '$groups' != expected '$expect_groups'"
ok=0
fi
fi

if ((ok)); then
echo "PASS: $crate (bugs=$bugs)"
else
failures=$((failures + 1))
fi
}

# --- async corpus (T-001): suspend/resume, spawn/join, lock-group merging ---
run_case deadlock/async-deadlock async_deadlock 1 2
run_case deadlock/async-no-deadlock async_no_deadlock 0 1

# --- sync regression baseline (todolist "engineering constraints") ---
run_case deadlock/intra intra 4
run_case deadlock/inter inter 4
run_case deadlock/conflict-inter conflict_inter 1
run_case deadlock/lock-closure lock_closure 1
run_case deadlock/static-ref static_ref 1
run_case deadlock/condvar-closure condvar_closure 6

echo
if ((failures > 0)); then
echo "smoke: $failures case(s) FAILED"
exit 1
fi
echo "smoke: all cases passed"
12 changes: 6 additions & 6 deletions src/memory/pta/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,12 +591,12 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> {
) {
let empty = self.arena.empty_path();

// 为闭包/协程环境创建一个 heap
// Create a heap for the closure/coroutine environment
self.call_counter += 1;
let clo_heap = self.arena.heap(
AllocSite {
func: self.func,
bb: 0, // 闭包定义不是 call site,用 0
bb: 0, // A closure definition is not a call site; use 0
idx: self.call_counter,
},
empty,
Expand All @@ -607,7 +607,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> {
// be constructed at several sites; all recorded heaps are unioned.
self.closure_envs.entry(def_id).or_default().push(clo_heap);

// 字段级 Copy: clo_heap.field_i ⊇ upvar_value_i
// Field-level Copy: clo_heap.field_i ⊇ upvar_value_i
for (i, op) in fields.iter_enumerated() {
let Some(value) = self.operand_value(op) else {
continue;
Expand Down Expand Up @@ -655,7 +655,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> {
}
}
}
// 如果 upvar 是引用类型,还需要 AddressOf
// If the upvar is a reference type, also add an AddressOf constraint
let upvar_ty = upvar_tys.get(i.as_usize());
if let Some(upvar_ty) = upvar_ty {
if upvar_ty.is_ref() {
Expand All @@ -674,7 +674,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> {
}
}

// 将 dst_local (闭包变量) 指向这个 heap
// Point dst_local (the closure variable) at this heap
let dst_slot = self
.arena
.var_ctx(self.ctx.clone(), self.func, dst_local, empty);
Expand Down Expand Up @@ -757,7 +757,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> {
self.arena
.var_ctx(self.ctx.clone(), self.func, u32::MAX - i as u32, empty);

// 字段级 Copy: clo_heap.field_j ⊇ upvar_value_j
// Field-level Copy: clo_heap.field_j ⊇ upvar_value_j
for (j, upvar_loc) in arg_nodes.iter().enumerate() {
if let Some(upvar_loc) = upvar_loc {
let field_path = self.arena.extend_path(empty, ProjElem::Field(j as u32));
Expand Down
93 changes: 89 additions & 4 deletions src/translate/mir_to_pn/terminator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ impl<'translate, 'analysis, 'tcx> BodyToPetriNet<'translate, 'analysis, 'tcx> {
// (the poll-switch's other target).
if self.tcx.is_coroutine(self.instance.def_id()) && self.block_sets_poll_pending(bb_idx) {
if let Some(cont) = self.find_suspend_continuation(bb_idx) {
log::debug!(
"[async] structured suspend detection matched bb{} -> continuation bb{}",
bb_idx.index(),
cont.index()
);
self.handle_fallthrough(bb_idx, &cont, name, "suspend");
}
return;
Expand Down Expand Up @@ -229,16 +234,96 @@ impl<'translate, 'analysis, 'tcx> BodyToPetriNet<'translate, 'analysis, 'tcx> {

/// Whether the return block sets `_0` to `Poll::Pending` (a coroutine
/// suspend) rather than `Poll::Ready` (completion).
///
/// Structured detection (no debug-string rendering): the `Pending` variant
/// of the body's `Poll`-shaped return type is located by variant name, and
/// every `_0`-writing statement is matched against it —
/// `SetDiscriminant { _0, v }`, `_0 = Aggregate(Adt(.., v, ..))`, or
/// `_0 = const` (variant `DefId` for unevaluated consts, discriminant bits
/// for evaluated ones). The last recognized `_0` write in the block decides.
fn block_sets_poll_pending(&self, bb_idx: BasicBlock) -> bool {
use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind};

let Some(pending_idx) = self.poll_pending_variant() else {
return false;
};

let bb = &self.body.basic_blocks[bb_idx];
let mut sets_pending = false;
for stmt in &bb.statements {
if let rustc_middle::mir::StatementKind::Assign(box (place, _)) = &stmt.kind {
if place.local.index() == 0 {
return format!("{:?}", stmt.kind).contains("Pending");
match &stmt.kind {
StatementKind::SetDiscriminant {
place,
variant_index,
} if place.local == RETURN_PLACE && place.projection.is_empty() => {
sets_pending = *variant_index == pending_idx;
}
StatementKind::Assign(box (place, rvalue))
if place.local == RETURN_PLACE && place.projection.is_empty() =>
{
let variant = match rvalue {
Rvalue::Use(Operand::Constant(constant), _) => {
self.const_poll_variant(constant.const_)
}
Rvalue::Aggregate(box AggregateKind::Adt(_, variant_index, _, _, _), _) => {
Some(*variant_index)
}
_ => None,
};
if let Some(variant) = variant {
sets_pending = variant == pending_idx;
}
}
_ => {}
}
}
sets_pending
}

/// The `Pending` variant of the body's return type when it is a
/// `Poll`-shaped enum (has both `Ready` and `Pending` variants).
fn poll_pending_variant(&self) -> Option<rustc_abi::VariantIdx> {
let adt_def = self.body.return_ty().ty_adt_def()?;
if !adt_def.is_enum() {
return None;
}
let mut pending = None;
let mut has_ready = false;
for (idx, variant) in adt_def.variants().iter_enumerated() {
match variant.name.as_str() {
"Pending" => pending = Some(idx),
"Ready" => has_ready = true,
_ => {}
}
}
has_ready.then_some(pending).flatten()
}

/// Resolve a constant `Poll` value to its enum variant without rendering:
/// fieldless variants may stay unevaluated and reference the variant's
/// `DefId`; evaluated consts carry the discriminant bits, matched against
/// the ADT's discriminant table.
fn const_poll_variant(
&self,
constant: rustc_middle::mir::Const<'tcx>,
) -> Option<rustc_abi::VariantIdx> {
use rustc_middle::mir::Const;

let adt_def = self.body.return_ty().ty_adt_def()?;
match constant {
Const::Unevaluated(unevaluated, _) => adt_def
.variants()
.iter_enumerated()
.find(|(_, variant)| variant.def_id == unevaluated.def)
.map(|(idx, _)| idx),
evaluated => {
let scalar = evaluated.try_to_scalar_int()?;
let bits = scalar.to_bits(scalar.size());
adt_def
.discriminants(self.tcx)
.find_map(|(idx, discr)| (discr.val == bits).then_some(idx))
}
}
false
}

/// Find the block a coroutine suspend resumes to: the poll switch that
Expand Down
Loading
Loading