diff --git a/CHANGELOG.md b/CHANGELOG.md index 050fb91..cba004c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,25 @@ All notable milestones for the nera project are documented in this file. - The `error_3` fixture checks these calls, argument evaluation and exception control flow natively and on BEAM. +## Uncaught errors include their stacktrace in exit reasons + +- A process started directly with the native spawn BIFs that dies from an + uncaught error now exits with `{Reason, Stacktrace}`, as on BEAM. + Monitors receive it in `'DOWN'` + messages, and linked processes receive the same reason, including a + process trapping exits in an `'EXIT'` message. Previously they received + only `Reason`, so a match on `{Reason, Stack}` could fail. +- The runtime uses the captured exception trace, including a trace supplied + by `erlang:raise/3`. An explicit `exit/1` or `exit/2`, a normal return and + a caught error are unchanged. Uncaught throws and stack-frame ordering + are not changed. +- Processes started through the bundled `proc_lib` spawn wrappers are not + covered: those wrappers catch errors and explicitly exit with the bare + reason. Their behavior is unchanged. +- The `uncaught_error_exit` fixture checks monitor and link delivery, + propagation through a non-trapping link, saved and empty traces, and + explicit-exit controls, natively and on BEAM. + ## Binary comprehensions reject bodies that are not bitstrings - A binary comprehension whose body is not a bitstring now raises diff --git a/crates/nera-runtime/src/ffi/mod.rs b/crates/nera-runtime/src/ffi/mod.rs index 364e450..28cc8bd 100644 --- a/crates/nera-runtime/src/ffi/mod.rs +++ b/crates/nera-runtime/src/ffi/mod.rs @@ -88,6 +88,7 @@ mod misc; pub(crate) use helpers::binary_data; pub use helpers::binary_data_pub; pub use receive::take_pending_resumes; +pub(crate) use exception::nera_rt_get_exception_stacktrace; #[cfg(test)] mod tests { diff --git a/crates/nera-runtime/src/scheduler.rs b/crates/nera-runtime/src/scheduler.rs index e41af29..dff367f 100644 --- a/crates/nera-runtime/src/scheduler.rs +++ b/crates/nera-runtime/src/scheduler.rs @@ -1683,12 +1683,26 @@ fn worker_loop( 2 => "exit", _ => "unknown", }; - exit_reason = crate::term::ErlTerm(proc.context.result); + let reason = crate::term::ErlTerm(proc.context.result); + exit_reason = if proc.context.exception_class == 1 { + // Uncaught errors exit with {Reason, Stacktrace}, as on + // BEAM. Build it before propagation while the dying + // process still owns the reason and captured trace. + // SAFETY: run_slice refreshed the context's heap/trace + // pointers; the process is locked and no GC or compiled + // execution runs before its signals have been copied. + let stack = unsafe { + crate::ffi::nera_rt_get_exception_stacktrace(&mut proc.context) + }; + proc.heap.alloc_tuple(&[reason, crate::term::ErlTerm(stack)]) + } else { + reason + }; let is_exit_class = proc.context.exception_class == 2; if !is_exit_class { // SAFETY: the process guard keeps its heap and borrowed // owners live. Formatting cannot reenter or run moving GC. - let reason_str = unsafe { crate::bif::format_term(exit_reason) }; + let reason_str = unsafe { crate::bif::format_term(reason) }; eprintln!( "Error in process <0.{}.0>: {}:{}", pid, class_name, reason_str diff --git a/tests/README.md b/tests/README.md index 3cd840e..8ab11a6 100644 --- a/tests/README.md +++ b/tests/README.md @@ -352,6 +352,7 @@ These are automatically skipped by the runner and show up as SKIP in output. | `link_normal.erl` | Normal exit through links | ~4 | | `unlink_basic.erl` | Process unlink | ~4 | | `monitor_basic.erl` | Process monitors and DOWN messages | ~8 | +| `uncaught_error_exit.erl` | Uncaught errors send `{Reason, Stacktrace}` in monitor `'DOWN'` and trapped-link `'EXIT'` messages: closure/MFA spawn, runtime errors, tuple reasons, resumed errors, link cascade, saved/empty traces; explicit exits, normal return and caught errors unchanged; also run on BEAM | Table-driven | | `monitor_noproc.erl` | Monitor non-existent process | ~4 | | `demonitor_basic.erl` | demonitor prevents DOWN delivery | ~4 | | `timer_many.erl` | Multiple concurrent timers | ~6 | diff --git a/tests/binary_segment_domain.erl b/tests/binary_segment_domain.erl index d2eb4f4..9fd5c4c 100644 --- a/tests/binary_segment_domain.erl +++ b/tests/binary_segment_domain.erl @@ -1,3 +1,4 @@ +%% EXPECT: binary_segment_domain_ok -module(binary_segment_domain). -export([test/0]). test() -> @@ -20,8 +21,9 @@ test() -> caught = try <<1:(size_value())>>, error(continued_after_invalid) catch error:badarg -> caught end, {Pid, Ref} = spawn_monitor(fun() -> integer(1.5), error(continued_after_invalid) end), - receive {'DOWN', Ref, process, Pid, badarg} -> ok + receive {'DOWN', Ref, process, Pid, {badarg, _Stack}} -> ok after 2000 -> error(missing_binary_error) end, + io:format("binary_segment_domain_ok~n"), ok. integer(N) -> <<1:N>>. compensated(N) -> <<1:N, 2:16>>. diff --git a/tests/list_operator_contracts.erl b/tests/list_operator_contracts.erl index b3fc938..3d0a709 100644 --- a/tests/list_operator_contracts.erl +++ b/tests/list_operator_contracts.erl @@ -1,3 +1,4 @@ +%% EXPECT: list_operator_contracts_ok -module(list_operator_contracts). -export([test/0]). test() -> @@ -30,8 +31,9 @@ test() -> caught = try [1|bad] -- [], error(continued_after_subtract) catch error:badarg -> caught end, {Pid, Monitor} = spawn_monitor(fun() -> append([1|bad], []), error(continued_after_append) end), - receive {'DOWN', Monitor, process, Pid, badarg} -> ok + receive {'DOWN', Monitor, process, Pid, {badarg, _Stack}} -> ok after 2000 -> error(missing_list_error) end, + io:format("list_operator_contracts_ok~n"), ok. append(A,B) -> A ++ B. subtract(A,B) -> A -- B. diff --git a/tests/uncaught_error_exit.erl b/tests/uncaught_error_exit.erl new file mode 100644 index 0000000..4c5e2dc --- /dev/null +++ b/tests/uncaught_error_exit.erl @@ -0,0 +1,124 @@ +%% EXPECT: uncaught_error_exit_ok +%% Uncaught error exits carry {Reason, Stacktrace} to monitors and links, +%% as on BEAM. Explicit exits and caught errors must keep their own shape. +-module(uncaught_error_exit). +-export([test/0, fail/1]). + +test() -> + Old = process_flag(trap_exit, true), + try + %% Closure and MFA spawn entry points both terminate through errors. + foo = monitored(fun() -> error(id(foo)) end), + Payload = {detail, lists:seq(1, 40), <<"heap-owned reason">>}, + Payload = monitored(fun() -> error(Payload) end), + {Pid, Ref} = spawn_monitor(?MODULE, fail, [mfa_error]), + {mfa_error, MfaStack} = down(Pid, Ref), + ok = stack(MfaStack), + true = lists:any(fun({M, F, A, _}) -> + M =:= ?MODULE andalso F =:= fail andalso A =:= 1 + end, MfaStack), + + %% Runtime errors use the same envelope, even if Reason is a tuple. + {badmatch, wrong} = monitored(fun() -> right = id(wrong) end), + badarg = monitored(fun() -> hd(id(not_a_list)) end), + normal = monitored(fun() -> error(id(normal)) end), + kill = monitored(fun() -> error(id(kill)) end), + + %% Monitor a live, waiting child, then let it fail after resuming. + Waiting = spawn(fun() -> receive go -> fail(resumed_error) end end), + WaitingRef = monitor(process, Waiting), + Waiting ! go, + {resumed_error, WaitingStack} = down(Waiting, WaitingRef), + ok = stack(WaitingStack), + + %% The same child supplies identical DOWN and trapped EXIT reasons. + Linked = spawn_link(fun() -> receive go -> fail(linked_error) end end), + LinkedRef = monitor(process, Linked), + Linked ! go, + LinkedReason = down(Linked, LinkedRef), + {linked_error, LinkedStack} = LinkedReason, + ok = stack(LinkedStack), + LinkedReason = exited(Linked), + + %% A non-trapping linked process propagates the original envelope, + %% rather than wrapping it a second time or substituting its own stack. + Parent = self(), + {Relay, RelayRef} = spawn_monitor(fun() -> + Child = spawn_link(fun() -> receive go -> fail(cascade_error) end end), + Parent ! {child, self(), Child}, + receive go -> Child ! go end, + receive never -> ok end + end), + Child = receive {child, Relay, C} -> C end, + ChildRef = monitor(process, Child), + Relay ! go, + CascadeReason = down(Child, ChildRef), + {cascade_error, CascadeStack} = CascadeReason, + ok = stack(CascadeStack), + CascadeReason = down(Relay, RelayRef), + + %% Re-raising a caught error must use its saved trace, not the + %% scheduler's current stack; a deliberately empty trace stays empty. + {Raised, RaisedRef} = spawn_monitor(fun() -> + try fail(reraised_error) + catch error:R:S -> + Parent ! {saved_stack, self(), S}, + erlang:raise(error, R, S) + end + end), + Saved = receive {saved_stack, Raised, S} -> S end, + {reraised_error, Saved} = down(Raised, RaisedRef), + {Empty, EmptyRef} = spawn_monitor(fun() -> erlang:raise(error, foo, []) end), + {foo, []} = down(Empty, EmptyRef), + + %% Only uncaught error-class exceptions acquire the envelope. + lists:foreach(fun(R) -> + {ExitPid, ExitRef} = spawn_opt(fun() -> exit(R) end, [link, monitor]), + R = down(ExitPid, ExitRef), + R = exited(ExitPid) + end, [normal, explicit_exit, {foo, []}]), + {Normal, NormalRef} = spawn_monitor(fun() -> ok end), + normal = down(Normal, NormalRef), + {Caught, CaughtRef} = spawn_monitor(fun() -> + try fail(caught_error) catch error:caught_error -> ok end + end), + normal = down(Caught, CaughtRef), + {Signalled, SignalledRef} = spawn_monitor(fun() -> receive never -> ok end end), + true = exit(Signalled, {external, []}), + {external, []} = down(Signalled, SignalledRef), + {Killed, KilledRef} = spawn_monitor(fun() -> receive never -> ok end end), + true = exit(Killed, kill), + killed = down(Killed, KilledRef), + io:format("uncaught_error_exit_ok~n"), + ok + after + process_flag(trap_exit, Old) + end. + +monitored(F) -> + {Pid, Ref} = spawn_monitor(F), + {Reason, Stack} = down(Pid, Ref), + ok = stack(Stack), + Reason. + +stack([_ | _] = Stack) -> + lists:foreach(fun({M, F, A, Info}) -> + true = is_atom(M), + true = is_atom(F), + true = is_integer(A) orelse is_list(A), + true = is_list(Info) + end, Stack), + ok. + +down(Pid, Ref) -> + receive {'DOWN', Ref, process, Pid, Reason} -> Reason + after 5000 -> error(missing_down) + end. + +exited(Pid) -> + receive {'EXIT', Pid, Reason} -> Reason + after 5000 -> error(missing_exit) + end. + +fail(Reason) -> error(Reason). +id(X) -> X.