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
41 changes: 32 additions & 9 deletions crates/perry-runtime/src/promise/async_step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,21 +259,21 @@ pub extern "C" fn js_async_step_chain(value: f64, step_closure: ClosurePtr) -> *
// the inner settles; install fulfill/reject thunks
// that will queue the right Task when called.
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) = build_async_step_thunks(step_closure);
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
return js_promise_then(inner, fulfill, reject);
}
}
} else {
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) = build_async_step_thunks(step_closure);
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
let p = js_promise_resolved(value);
return js_promise_then(p, fulfill, reject);
}
} else {
// Pointer-tagged but not a Promise (thenable etc.). Take the
// fully-general path so assimilation runs.
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) = build_async_step_thunks(step_closure);
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
Comment on lines +262 to +276

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Gate the captured trap_next with can_reuse.

Line 262, Line 268, and Line 276 pass the raw ambient trap_next into the resume thunks. When current_step does not match step_closure, that pointer belongs to another activation; capturing it can recreate the cross-activation settlement leak on the pending/thenable fallback paths. Capture null unless the reuse gate passed.

Proposed fix
     let trap = INLINE_TRAP.with(|c| c.get());
     let can_reuse = !trap.trap_next.is_null() && trap.current_step == step_closure as usize;
     let trap_next = trap.trap_next;
+    let activation_trap_next = if can_reuse {
+        trap_next
+    } else {
+        std::ptr::null_mut()
+    };
@@
-                    let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
+                    let (fulfill, reject) =
+                        build_async_step_thunks(step_closure, activation_trap_next);
@@
-            let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
+            let (fulfill, reject) =
+                build_async_step_thunks(step_closure, activation_trap_next);
@@
-        let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
+        let (fulfill, reject) =
+            build_async_step_thunks(step_closure, activation_trap_next);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
return js_promise_then(inner, fulfill, reject);
}
}
} else {
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) = build_async_step_thunks(step_closure);
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
let p = js_promise_resolved(value);
return js_promise_then(p, fulfill, reject);
}
} else {
// Pointer-tagged but not a Promise (thenable etc.). Take the
// fully-general path so assimilation runs.
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) = build_async_step_thunks(step_closure);
let (fulfill, reject) = build_async_step_thunks(step_closure, trap_next);
let trap = INLINE_TRAP.with(|c| c.get());
let can_reuse = !trap.trap_next.is_null() && trap.current_step == step_closure as usize;
let trap_next = trap.trap_next;
let activation_trap_next = if can_reuse {
trap_next
} else {
std::ptr::null_mut()
};
let (fulfill, reject) =
build_async_step_thunks(step_closure, activation_trap_next);
return js_promise_then(inner, fulfill, reject);
}
}
} else {
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) =
build_async_step_thunks(step_closure, activation_trap_next);
let p = js_promise_resolved(value);
return js_promise_then(p, fulfill, reject);
}
} else {
// Pointer-tagged but not a Promise (thenable etc.). Take the
// fully-general path so assimilation runs.
bump(&MT_STEP_CHAIN_REUSE_MISS);
let (fulfill, reject) =
build_async_step_thunks(step_closure, activation_trap_next);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-runtime/src/promise/async_step.rs` around lines 262 - 276, The
issue is that `trap_next` is being passed directly to `build_async_step_thunks`
at three locations without checking the reuse gate, which can cause
cross-activation settlement leaks when `current_step` does not match
`step_closure`. Fix this by modifying each call to `build_async_step_thunks` to
conditionally pass either `trap_next` or `null` based on whether `can_reuse` is
true. Apply this change at all three call sites where
`build_async_step_thunks(step_closure, trap_next)` appears in this block to
ensure the reuse gate properly guards the captured `trap_next` value.

let p = js_promise_resolved(value);
return js_promise_then(p, fulfill, reject);
};
Expand Down Expand Up @@ -485,17 +485,28 @@ pub fn scan_async_step_thunk_cache_mut(visitor: &mut crate::gc::RuntimeRootVisit
/// awaits) while degrading gracefully (no cache overhead beyond the
/// cell read/write) when many distinct step closures interleave (the
/// Promise.all-of-N shape).
fn build_async_step_thunks(step_closure: ClosurePtr) -> (ClosurePtr, ClosurePtr) {
fn build_async_step_thunks(
step_closure: ClosurePtr,
trap_next: *mut Promise,
) -> (ClosurePtr, ClosurePtr) {
use crate::closure::{js_closure_alloc, js_closure_set_capture_ptr};
let key = step_closure as usize;
let cached = LAST_ASYNC_STEP_THUNKS.with(|c| c.get());
if cached.0 == key && !cached.1.is_null() && !cached.2.is_null() {
// #5485: refresh the captured activation `trap_next`. The step
// closure (cache key) is per-activation, so this is normally the
// same pointer; refreshing keeps us correct if the slot is reused.
js_closure_set_capture_ptr(cached.1, 1, trap_next as i64);
js_closure_set_capture_ptr(cached.2, 1, trap_next as i64);
return (cached.1 as ClosurePtr, cached.2 as ClosurePtr);
}
use crate::closure::{js_closure_alloc, js_closure_set_capture_ptr};
let fulfill = js_closure_alloc(async_step_fulfill_thunk as *const u8, 1);
// Capture layout: [step_closure_ptr, activation_trap_next_ptr] (#5485).
let fulfill = js_closure_alloc(async_step_fulfill_thunk as *const u8, 2);
js_closure_set_capture_ptr(fulfill, 0, step_closure as i64);
let reject = js_closure_alloc(async_step_reject_thunk as *const u8, 1);
js_closure_set_capture_ptr(fulfill, 1, trap_next as i64);
let reject = js_closure_alloc(async_step_reject_thunk as *const u8, 2);
js_closure_set_capture_ptr(reject, 0, step_closure as i64);
js_closure_set_capture_ptr(reject, 1, trap_next as i64);
LAST_ASYNC_STEP_THUNKS.with(|c| c.set((key, fulfill, reject)));
(fulfill as ClosurePtr, reject as ClosurePtr)
}
Expand All @@ -508,6 +519,15 @@ extern "C" fn async_step_fulfill_thunk(
) -> f64 {
let step = crate::closure::js_closure_get_capture_ptr(closure, 0)
as *const crate::closure::ClosureHeader;
// #5485: the activation's own trap_next, captured when this thunk was
// built (at the `await`), not the ambient INLINE_TRAP.trap_next at
// resume time — which may belong to an UNRELATED outer activation and,
// preserved here, let this resumed step's js_async_step_done reuse-gate
// settle that outer activation's result promise prematurely with this
// (intermediate await) value. Restoring the captured per-activation
// value keeps same-activation settlement working while preventing the
// cross-activation leak.
let captured_trap_next = crate::closure::js_closure_get_capture_ptr(closure, 1) as *mut Promise;
let false_bits = f64::from_bits(0x7FFC_0000_0000_0003);
// #691 Phase 2: when this thunk is invoked from the pending-Promise
// fallback in js_async_step_chain (await of a still-pending inner),
Expand All @@ -518,7 +538,7 @@ extern "C" fn async_step_fulfill_thunk(
let prev = INLINE_TRAP.with(|c| {
let old = c.get();
c.set(InlineTrap {
trap_next: old.trap_next,
trap_next: captured_trap_next,
current_step: step as usize,
});
old
Expand All @@ -534,13 +554,16 @@ extern "C" fn async_step_reject_thunk(
) -> f64 {
let step = crate::closure::js_closure_get_capture_ptr(closure, 0)
as *const crate::closure::ClosureHeader;
// #5485: restore the captured per-activation trap_next (see
// async_step_fulfill_thunk for the full rationale).
let captured_trap_next = crate::closure::js_closure_get_capture_ptr(closure, 1) as *mut Promise;
let true_bits = f64::from_bits(0x7FFC_0000_0000_0004);
// #691 Phase 2: see async_step_fulfill_thunk — same TLS-setup
// requirement on the rejection path.
let prev = INLINE_TRAP.with(|c| {
let old = c.get();
c.set(InlineTrap {
trap_next: old.trap_next,
trap_next: captured_trap_next,
current_step: step as usize,
});
old
Expand Down
97 changes: 97 additions & 0 deletions crates/perry/tests/issue_5485_async_step_trap_next_leak.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//! Regression test for #5485: an async function must resolve with its own
//! `return` value, not the value of an intermediate `await`.
//!
//! Root cause: `async_step_fulfill_thunk` / `async_step_reject_thunk` (the
//! resume path for `await <pending promise>`) preserved the *ambient*
//! `INLINE_TRAP.trap_next` while pointing `current_step` at the resumed step.
//! When the resumed step belonged to a *nested* activation, its
//! `js_async_step_done` reuse-gate (`current_step == step_closure`) then fired
//! against an *outer* activation's result promise and settled it prematurely
//! with the nested call's (intermediate) value — exactly the hazard
//! `js_async_first_call` already guards against by clearing `trap_next`.
//!
//! Symptom (Hono / Skelpo CMS): `POST /admin/login` returned an empty 200
//! instead of the handler's `302` redirect, because the handler's awaited
//! result resolved to `checkLoginRateLimit()`'s `{ allowed: true }` (the first
//! `await`) instead of the `c.redirect(...)` it actually returned.
//!
//! The fix captures each activation's own `trap_next` as a second closure
//! capture on the resume thunks and restores *that* (not the ambient one).
//!
//! This minimal repro exhibits the leak deterministically via a
//! catch-handler `await` of a nested async fn: on the buggy runtime
//! `tryCatchAwait()` resolves to `{"allowed":true}` (the inner value) instead
//! of `"wrap:{\"allowed\":true}"` (its real return).

use std::path::PathBuf;
use std::process::Command;

fn perry_bin() -> PathBuf {
PathBuf::from(env!("CARGO_BIN_EXE_perry"))
}

#[test]
fn async_fn_returns_its_own_value_not_intermediate_await() {
let dir = tempfile::tempdir().expect("tempdir");
let entry = dir.path().join("main.ts");
let output = dir.path().join("main_bin");

std::fs::write(
&entry,
r#"
const tick = (): Promise<void> => new Promise((r) => setTimeout(() => r(), 0));
async function inner(): Promise<{ allowed: boolean }> {
await tick();
return { allowed: true };
}
// The #5485 leak case: a catch-handler `await` of a nested async fn. The
// enclosing async fn must resolve with its OWN return value ("wrap:{...}"),
// not the inner await's intermediate value ({allowed:true}). On the buggy
// runtime the nested call's `js_async_step_done` settled this fn's result
// promise prematurely with {allowed:true}.
async function tryCatchAwait(): Promise<string> {
try {
await Promise.reject(new Error("e"));
} catch {
const r = await inner();
return "wrap:" + JSON.stringify(r);
}
return "x";
}
async function main(): Promise<void> {
console.log("B=" + (await tryCatchAwait()));
}
void main();
"#,
)
.expect("write entry");

let compile = Command::new(perry_bin())
.current_dir(dir.path())
.arg("compile")
.arg(&entry)
.arg("-o")
.arg(&output)
.output()
.expect("run perry compile");
assert!(
compile.status.success(),
"perry compile failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&compile.stdout),
String::from_utf8_lossy(&compile.stderr)
);

let run = Command::new(&output).output().expect("run compiled binary");
assert!(
run.status.success(),
"compiled binary failed\nstatus: {:?}\nstdout:\n{}\nstderr:\n{}",
run.status,
String::from_utf8_lossy(&run.stdout),
String::from_utf8_lossy(&run.stderr)
);
let stdout = String::from_utf8_lossy(&run.stdout);
assert_eq!(
stdout, "B=wrap:{\"allowed\":true}\n",
"async fn must resolve with its own return value, not an intermediate await (#5485)"
);
}
Loading