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
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions crates/nera-runtime/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 16 additions & 2 deletions crates/nera-runtime/src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 3 additions & 1 deletion tests/binary_segment_domain.erl
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
%% EXPECT: binary_segment_domain_ok
-module(binary_segment_domain).
-export([test/0]).
test() ->
Expand All @@ -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>>.
Expand Down
4 changes: 3 additions & 1 deletion tests/list_operator_contracts.erl
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
%% EXPECT: list_operator_contracts_ok
-module(list_operator_contracts).
-export([test/0]).
test() ->
Expand Down Expand Up @@ -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.
Expand Down
124 changes: 124 additions & 0 deletions tests/uncaught_error_exit.erl
Original file line number Diff line number Diff line change
@@ -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.
Loading