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
52 changes: 52 additions & 0 deletions crates/perry-hir/src/destructuring/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,58 @@

use super::*;

/// Returns `Some("fetch")` when `expr` is a bare-`Ident` fetch-like call —
/// `fetch(url)` / `fetchWithAuth(...)` / `fetchPostWithAuth(...)`. The caller
/// registers the binding as a fetch `Response` native instance.
///
/// Closes #644: all three return the same Response handle, so they must
/// register under module="fetch". The codegen dispatch in
/// `lower_fetch_native_method` gates on `module == "fetch"` — pre-fix,
/// registering under "fetchWithAuth"/"fetchPostWithAuth" missed the gate so a
/// post-narrowing `r.status` lowered as a NativeMethodCall with
/// module="fetchWithAuth" and fell through to a generic 0.0-returning arm.
/// (Without narrowing the access went through generic PropertyGet → handle
/// dispatch → js_fetch_response_status, so the bug only surfaced inside an
/// `if r !== null/undefined` block.)
pub(crate) fn get_fetch_module(expr: &ast::Expr) -> Option<&'static str> {
if let ast::Expr::Call(call_expr) = expr {
if let ast::Callee::Expr(callee_expr) = &call_expr.callee {
if let ast::Expr::Ident(ident) = callee_expr.as_ref() {
return match ident.sym.as_ref() {
"fetch" | "fetchWithAuth" | "fetchPostWithAuth" => Some("fetch"),
_ => None,
};
}
}
}
None
}

/// #5432: true when `expr` is a member-call `.fetch(...)` (optionally awaited) —
/// `app.fetch(req)` / `await app.fetch(req)`, the Fetch-API / WinterCG
/// server-handler convention (Hono, itty-router, Cloudflare Workers) that
/// returns a native fetch `Response`. Used to populate
/// `fetch_call_response_locals` so `res.headers.<m>()` routes through the
/// Headers FFI instead of being folded into `js_array_forEach` on a handle id.
pub(crate) fn is_member_fetch_call(expr: &ast::Expr) -> bool {
let call = match expr {
ast::Expr::Await(a) => match a.arg.as_ref() {
ast::Expr::Call(c) => c,
_ => return false,
},
ast::Expr::Call(c) => c,
_ => return false,
};
if let ast::Callee::Expr(callee) = &call.callee {
if let ast::Expr::Member(member) = callee.as_ref() {
if let ast::MemberProp::Ident(prop) = &member.prop {
return prop.sym.as_ref() == "fetch";
}
}
}
false
}

/// Recognize the ink-shape `useState(initial)` pattern when the
/// callee is a perry/tui-imported `useState`. Returns a rewritten
/// HIR expression that calls `useStateTuple` instead — returning a
Expand Down
5 changes: 4 additions & 1 deletion crates/perry-hir/src/destructuring/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ pub(crate) use assignment_expr::lower_destructuring_assignment;
pub(crate) use assignment_stmt::{
lower_destructuring_assignment_stmt, lower_destructuring_assignment_stmt_from_local,
};
pub(crate) use helpers::{ast_expr_contains_function_expr, rewrite_use_state_tuple};
pub(crate) use helpers::{
ast_expr_contains_function_expr, get_fetch_module, is_member_fetch_call,
rewrite_use_state_tuple,
};
pub(crate) use pattern_binding::{lower_pattern_binding, lower_pattern_binding_into};
pub(crate) use var_decl::lower_var_decl_with_destructuring;
pub(crate) use var_decl_sources::{
Expand Down
44 changes: 11 additions & 33 deletions crates/perry-hir/src/destructuring/var_decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -875,39 +875,6 @@ pub(crate) fn lower_var_decl_with_destructuring(

// Check if this is assigning from fetch() or await fetch() - register as fetch Response
if let Some(init_expr) = &decl.init {
// Helper to check if an expression is a fetch-like call
// Returns the module name if it matches fetch/fetchWithAuth/fetchPostWithAuth
fn get_fetch_module(expr: &ast::Expr) -> Option<&'static str> {
if let ast::Expr::Call(call_expr) = expr {
if let ast::Callee::Expr(callee_expr) = &call_expr.callee {
if let ast::Expr::Ident(ident) = callee_expr.as_ref() {
// Closes #644: all three return the same
// Response handle, so they must register
// under module="fetch". The codegen dispatch
// in `lower_fetch_native_method` gates on
// `module == "fetch"` — pre-fix, registering
// under "fetchWithAuth"/"fetchPostWithAuth"
// missed the gate so a post-narrowing
// `r.status` lowered as a NativeMethodCall
// with module="fetchWithAuth" and fell
// through to a generic 0.0-returning arm.
// (Without narrowing the access went through
// generic PropertyGet → handle dispatch →
// js_fetch_response_status, so the bug only
// surfaced inside an `if r !== null/undefined`
// block.)
return match ident.sym.as_ref() {
"fetch" | "fetchWithAuth" | "fetchPostWithAuth" => {
Some("fetch")
}
_ => None,
};
}
}
}
None
}

if crate::lower_types::is_node_readable_static_factory_call(ctx, init_expr) {
let readable = "Readable".to_string();
ty = Type::Named(readable.clone());
Expand All @@ -933,6 +900,17 @@ pub(crate) fn lower_var_decl_with_destructuring(
}
}

// #5432: `const res = app.fetch(req)` / `await app.fetch(req)` —
// a member-call `.fetch(...)` is the Fetch-API server-handler
// convention (Hono `app.fetch`, itty-router, Cloudflare
// Workers) and yields a native fetch Response. Record it in a
// narrow set (NOT `register_native_instance`, which would hijack
// every method on `res`) so only `res.headers.<m>()` bails the
// array-method fold. See `fetch_call_response_locals`.
if is_member_fetch_call(init_expr) {
ctx.fetch_call_response_locals.insert(name.clone());
}
Comment on lines +903 to +912

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

Propagate fetch-response local tracking across simple aliases.

fetch_call_response_locals is only set for direct .fetch(...) initializers. A follow-up alias (const alias = res) is not tracked, so alias.headers.forEach/entries can still miss the intended headers path.

Proposed patch
                 if is_member_fetch_call(init_expr) {
                     ctx.fetch_call_response_locals.insert(name.clone());
+                } else if let ast::Expr::Ident(src_ident) = init_expr.as_ref() {
+                    if ctx
+                        .fetch_call_response_locals
+                        .contains(src_ident.sym.as_ref())
+                    {
+                        ctx.fetch_call_response_locals.insert(name.clone());
+                    }
                 }
📝 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
// #5432: `const res = app.fetch(req)` / `await app.fetch(req)` —
// a member-call `.fetch(...)` is the Fetch-API server-handler
// convention (Hono `app.fetch`, itty-router, Cloudflare
// Workers) and yields a native fetch Response. Record it in a
// narrow set (NOT `register_native_instance`, which would hijack
// every method on `res`) so only `res.headers.<m>()` bails the
// array-method fold. See `fetch_call_response_locals`.
fn is_member_fetch_call(expr: &ast::Expr) -> bool {
let call = match expr {
ast::Expr::Await(a) => match a.arg.as_ref() {
ast::Expr::Call(c) => c,
_ => return false,
},
ast::Expr::Call(c) => c,
_ => return false,
};
if let ast::Callee::Expr(callee) = &call.callee {
if let ast::Expr::Member(member) = callee.as_ref() {
if let ast::MemberProp::Ident(prop) = &member.prop {
return prop.sym.as_ref() == "fetch";
}
}
}
false
}
if is_member_fetch_call(init_expr) {
ctx.fetch_call_response_locals.insert(name.clone());
}
// `#5432`: `const res = app.fetch(req)` / `await app.fetch(req)` —
// a member-call `.fetch(...)` is the Fetch-API server-handler
// convention (Hono `app.fetch`, itty-router, Cloudflare
// Workers) and yields a native fetch Response. Record it in a
// narrow set (NOT `register_native_instance`, which would hijack
// every method on `res`) so only `res.headers.<m>()` bails the
// array-method fold. See `fetch_call_response_locals`.
fn is_member_fetch_call(expr: &ast::Expr) -> bool {
let call = match expr {
ast::Expr::Await(a) => match a.arg.as_ref() {
ast::Expr::Call(c) => c,
_ => return false,
},
ast::Expr::Call(c) => c,
_ => return false,
};
if let ast::Callee::Expr(callee) = &call.callee {
if let ast::Expr::Member(member) = callee.as_ref() {
if let ast::MemberProp::Ident(prop) = &member.prop {
return prop.sym.as_ref() == "fetch";
}
}
}
false
}
if is_member_fetch_call(init_expr) {
ctx.fetch_call_response_locals.insert(name.clone());
} else if let ast::Expr::Ident(src_ident) = init_expr.as_ref() {
if ctx
.fetch_call_response_locals
.contains(src_ident.sym.as_ref())
{
ctx.fetch_call_response_locals.insert(name.clone());
}
}
🤖 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-hir/src/destructuring/var_decl.rs` around lines 936 - 963, The
`is_member_fetch_call` function only marks direct `.fetch(...)` calls, but it
does not handle simple variable aliases. When a variable is initialized with
another variable that was already marked as a fetch response local (like `const
alias = res`), the alias should also be added to
`ctx.fetch_call_response_locals`. Add a check after the `is_member_fetch_call`
condition: if `init_expr` is a simple identifier reference and that identifier
is already in `ctx.fetch_call_response_locals`, then insert the current `name`
into the set as well. This ensures aliases to fetch responses maintain the
tracking through the scope.


// Web Fetch API: new Response(...) / new Headers(...) /
// new Request(...) / new FormData(...)
// Also handle Response.json(...) and Response.redirect(...) static factories.
Expand Down
1 change: 1 addition & 0 deletions crates/perry-hir/src/lower/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ impl LoweringContext {
weakmap_locals: HashSet::new(),
weakset_locals: HashSet::new(),
namespace_import_locals: HashSet::new(),
fetch_call_response_locals: HashSet::new(),
namespace_import_sources: std::collections::HashMap::new(),
generator_func_names: HashSet::new(),
async_generator_func_names: HashSet::new(),
Expand Down
11 changes: 9 additions & 2 deletions crates/perry-hir/src/lower/expr_call/array_only_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,13 +412,20 @@ pub(super) fn try_array_only_methods(
// `crates/perry-codegen/src/lower_call.rs:1313`, which
// routes `.forEach` / `.get` / `.has` / `.keys` /
// `.values` / `.entries` through the Headers FFI.
// #5432: `res.headers.<m>()` where `res` came from a
// member-call `app.fetch(req)` (Hono / WinterCG). It
// is not a `register_native_instance` binding (that
// would hijack every method on `res`), so consult the
// narrow `fetch_call_response_locals` set too.
let is_fetch_headers = prop_ident.sym.as_ref() == "headers"
&& matches!(
&& (matches!(
ctx.lookup_native_instance(obj_ident.sym.as_ref()),
Some(("fetch", _))
| Some(("Request", _))
| Some(("Headers", _))
);
) || ctx
.fetch_call_response_locals
.contains(obj_ident.sym.as_ref()));
if is_fetch_headers {
true
} else {
Expand Down
15 changes: 15 additions & 0 deletions crates/perry-hir/src/lower/lowering_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,21 @@ pub struct LoweringContext {
/// default imports of actual classes (`import { MongoClient }`) are NOT in
/// this set and keep the static-method path.
pub(crate) namespace_import_locals: HashSet<String>,
/// #5432: locals initialized from a member-call `.fetch(...)` — the
/// Fetch-API / WinterCG convention every server framework exposes (Hono
/// `app.fetch`, itty-router, Cloudflare Workers handlers) returns a native
/// fetch `Response` whose `.headers` is a Headers handle. This set is
/// consulted ONLY by the `is_fetch_headers` guard in
/// `array_only_methods.rs` so `res.headers.forEach(cb)` /
/// `res.headers.entries()` bail the static array-method fold and route
/// through the Headers FFI instead of dispatching `js_array_forEach` on a
/// handle id (a SIGSEGV). It deliberately does NOT use
/// `register_native_instance`, which would hijack EVERY method/property
/// access on the local (e.g. a Bookshelf/Backbone `repo.fetch()` returning
/// a real array would then mis-route `.map`/`.forEach`). The narrow scope —
/// only `<name>.headers.<method>()` is affected — keeps the false-positive
/// surface to nil.
pub(crate) fetch_call_response_locals: HashSet<String>,
/// Maps a namespace-import local (`import * as z from "src"`) to its source
/// module. Used so a later bare `export { z }` re-export of that local routes
/// to `Export::NamespaceReExport` (equivalent to `export * as z from "src"`)
Expand Down
20 changes: 19 additions & 1 deletion crates/perry-runtime/src/array/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,16 @@ pub(crate) fn clean_arr_ptr(arr: *const ArrayHeader) -> *const ArrayHeader {
}
arr
};
// #5432: reject small-handle ids (fetch/zlib/proxy/common-registry) that
// reached an array helper as the receiver. On non-macOS hosts HEAP_MIN is
// 0x1000 — below the handle band — so a handle like a fetch Headers id
// (0x40000) passes the window check above, and the forwarding-chain /
// obj_type derefs below (`cleaned - 8`) would read unmapped low memory and
// SIGSEGV. Magnitude-classify before any deref and null it (safe
// empty-result no-op), mirroring the addr_class band-map contract.
if crate::value::addr_class::is_handle_band(cleaned as usize) {
return std::ptr::null();
}
// Issue #233: follow GC_FLAG_FORWARDED forwarding chains. When
// an array grows (js_array_grow) we install a forwarding pointer
// at the OLD location so any stale reference — e.g. an async
Expand Down Expand Up @@ -661,7 +671,15 @@ pub(crate) fn normalize_array_receiver(arr: *const ArrayHeader) -> *const ArrayH
} else {
bits as usize
};
if raw_addr >= crate::gc::GC_HEADER_SIZE + 0x1000 {
// Reject the small-handle band (fetch/zlib/proxy/registry ids, #5432)
// BEFORE any GcHeader deref. A folded `headersHandle.forEach(cb)` can reach
// here with a fetch Headers handle (0x40000 band) when the static
// array-method fold mis-claimed the receiver; `0x40000 - 8` is unmapped low
// memory, so the stale `0x1008` floor used to SIGSEGV (the addr_class.rs
// band-map documents this exact #4665/#4800/#5432 shape). Treat any
// handle-band payload as "not an array" and fall through to clean_arr_ptr,
// which nulls it — a safe empty-result no-op instead of a crash.
if crate::value::addr_class::is_above_handle_band(raw_addr) {
// Hot path first: read the GC-header obj_type byte. A genuine Array is
// GC_TYPE_ARRAY and falls straight through to `clean_arr_ptr` — the
// only added cost for `[1,2,3].map(...)` etc. is this one byte read and
Expand Down
35 changes: 35 additions & 0 deletions test-files/test_issue_5432_fetch_headers_foreach.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// #5432: `.forEach()` / `.entries()` on the Headers of a Response returned by a
// member-call `app.fetch(req)` (the Fetch-API / WinterCG server-handler shape
// Hono, itty-router, and Cloudflare Workers all use) SIGSEGV'd in
// js_array_forEach: the unregistered receiver let the static array-method fold
// rewrite `res.headers.forEach(cb)` into `Expr::ArrayForEach` and codegen
// dispatched `js_array_forEach` on the Headers handle id (0x40000 band).
// `app.fetch` is modeled here without hono so the test needs no npm package —
// the crash is the member-`.fetch()` call returning a native Response, not hono
// itself. The assertions filter to the explicit `x-` headers so the test does
// not depend on whether a default `content-type` is derived from the body.
class App {
fetch(_req: Request): Response {
return new Response("ok", { headers: { "x-a": "1", "x-b": "2" } });
}
}

const app = new App();
const res = app.fetch(new Request("http://h/x"));
console.log("status:", res.status);

// forEach must iterate (used to SIGSEGV).
const seen: string[] = [];
res.headers.forEach((value: string, key: string) => {
if (key.startsWith("x-")) seen.push(key + "=" + value);
});
seen.sort();
console.log("forEach:", JSON.stringify(seen));

// entries() must yield the same pairs (used to silently yield 0).
const ents: string[] = [];
for (const [k, v] of res.headers.entries()) {
if (k.startsWith("x-")) ents.push(k + "=" + v);
}
ents.sort();
console.log("entries:", JSON.stringify(ents));
Loading