Skip to content

Commit 83d67ac

Browse files
committed
fix(runtime): list raising functions first in captured stacktraces
1 parent fc58ac2 commit 83d67ac

7 files changed

Lines changed: 113 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,19 @@ All notable milestones for the nera project are documented in this file.
1616
- The `error_3` fixture checks these calls, argument evaluation and exception
1717
control flow natively and on BEAM.
1818

19+
## Stacktraces list the raising function first
20+
21+
- Captured exception stacktraces now list the raising function before its
22+
callers, as on BEAM. Previously they listed the outermost caller first,
23+
so `hd(Stack)` in `try ... catch Class:Reason:Stack` identified the wrong
24+
function. This also corrects captured traces carried in `{Reason, Stack}`
25+
exit reasons, such as a failed `gen_server` start.
26+
- `erlang:raise/3` keeps the supplied stacktrace's order, including when it
27+
re-raises a captured exception.
28+
- The `stacktrace_order` fixture checks caught errors, throws, exits and
29+
failed matches, re-raises and stack-bearing exit reasons on native Nera
30+
and BEAM.
31+
1932
## Binary comprehensions reject bodies that are not bitstrings
2033

2134
- A binary comprehension whose body is not a bitstring now raises

‎FEATURES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ and known differences from BEAM.
5959
| Implicit string concatenation | ✅ | Adjacent strings merged |
6060
| Record index (#rec.field) | ✅ | Returns 1-based field index |
6161
| Named funs (fun Name(...) -> ... end) | ✅ | With self-recursion |
62-
| 3-part catch (Class:Reason:Stacktrace) | ✅ | OTP 21+ stacktrace binding |
62+
| 3-part catch (Class:Reason:Stacktrace) | ✅ | OTP 21+ binding; raising function first, then callers, as on BEAM |
6363
| maybe expression (OTP 25+) | ✅ | `?=` cond match, else clauses |
6464
| Map comprehensions (OTP 26+) | ❌ | |
6565
| Sigils / triple-quoted strings (OTP 27+) | ❌ | |

‎crates/nera-runtime/src/ffi/helpers.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,8 @@ where
132132
/// Snapshot the current call stack into `ctx.exception_trace_ptr`.
133133
/// Reads compact frames from the cursor-based stack and reconstructs
134134
/// full StackFrames using the global func_info_table. Falls back to
135-
/// stack_ptr (Vec<StackFrame>) for tests and legacy callers (nera_rt_raise).
135+
/// stack_ptr (Vec<StackFrame>) for tests and legacy callers. Captured traces
136+
/// are innermost-first, like Erlang stacktrace lists supplied to raise/3.
136137
/// # Safety
137138
/// The context and the pointees accessed by this operation must be live and
138139
/// exclusively accessible on this thread; no competing process execution or
@@ -169,10 +170,10 @@ enum TraceFrames<'a> {
169170
fn fill_exception_trace(trace: &mut Vec<crate::process::StackFrame>, frames: TraceFrames<'_>) {
170171
trace.clear();
171172
match frames {
172-
TraceFrames::Full(frames) => trace.extend_from_slice(frames),
173+
TraceFrames::Full(frames) => trace.extend(frames.iter().rev().copied()),
173174
TraceFrames::Compact(frames) => {
174175
let info_table = crate::entry::global_func_info_table();
175-
trace.extend(frames.iter().map(|cf| {
176+
trace.extend(frames.iter().rev().map(|cf| {
176177
let (module, function, arity) = info_table
177178
.get(cf.func_index as usize)
178179
.copied()

‎crates/nera-runtime/src/ffi/mod.rs‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ mod tests {
122122

123123
#[test]
124124
fn exception_capture_snapshots_and_clears_trace() {
125+
// Legacy FFI stack hooks mirror the real non-tail callers in
126+
// tests/stacktrace_order.erl; native execution covers compact frames.
127+
let atoms = crate::atom_table::global_atom_table();
128+
let module = ErlTerm::atom(atoms.intern("stacktrace_order"));
129+
let outer = ErlTerm::atom(atoms.intern("outer"));
130+
let inner = ErlTerm::atom(atoms.intern("inner"));
125131
let mut stack = Vec::new();
126132
let mut trace = Vec::new();
127133
let mut ctx = ProcessContext::new(crate::process::ProcessId::new(1));
@@ -130,18 +136,16 @@ mod tests {
130136

131137
// SAFETY: ctx points to a valid ProcessContext with valid stack/trace pointers.
132138
unsafe {
133-
nera_rt_stack_push(&mut ctx, ErlTerm::atom(100).0, ErlTerm::atom(200).0, 1, 0);
134-
nera_rt_stack_push(&mut ctx, ErlTerm::atom(100).0, ErlTerm::atom(201).0, 2, 0);
139+
nera_rt_stack_push(&mut ctx, module.0, outer.0, 1, 0);
140+
nera_rt_stack_push(&mut ctx, module.0, inner.0, 1, 0);
135141
}
136-
let reason = ErlTerm::small_int(42).0;
142+
let reason = ErlTerm::atom(atoms.intern("boom")).0;
137143
// SAFETY: ctx points to a valid ProcessContext with valid stack/trace pointers.
138144
let _ = unsafe { nera_rt_error(&mut ctx, reason) };
139145

140146
assert_eq!(ctx.status, STATUS_EXCEPTION);
141147
assert_eq!(ctx.result, reason);
142-
assert_eq!(trace.len(), 2);
143-
assert_eq!(trace[0].function, 200);
144-
assert_eq!(trace[1].function, 201);
148+
assert_eq!(trace, stack.iter().rev().copied().collect::<Vec<_>>());
145149

146150
// SAFETY: ctx points to a valid ProcessContext with valid stack/trace pointers.
147151
unsafe {

‎crates/nera-runtime/src/process.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1234,7 +1234,8 @@ pub struct Process {
12341234
/// Compact call stack used by compiled code (func_index + line).
12351235
/// Pre-allocated to STACK_DEPTH_LIMIT for cursor-based addressing.
12361236
pub compact_stack: Vec<CompactFrame>,
1237-
/// Captured stack trace for the last raised exception in this process.
1237+
/// Stack trace for the last raised exception, innermost (raising) frame first.
1238+
/// Captures and traces supplied to erlang:raise/3 use the same order.
12381239
pub exception_trace: Vec<StackFrame>,
12391240
/// Long-lived OTP-oriented state (waiting reason, links, monitors,
12401241
/// registration hooks, timer ownership).

‎tests/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ These are automatically skipped by the runner and show up as SKIP in output.
224224
| `branch_export_reads.erl` | Names bound in `begin...end` or every `case`/`if`/`receive` branch, read afterwards: bodies, nested and scrutinee exports, call arguments, `try ... of`, fun-head and generator keys and sizes, construction sizes, guards, captures, later patterns and binary tails; funs in record field defaults; fun heads and generators still shadow, and a comprehension's first generator source keeps its bindings local; a binary tail read in a comprehension source or `maybe` block stays readable after it; a name local to an earlier fun does not stop a later read; a generator source or `catch` operand reads its own exports; a sibling clause, fun clause or receive timeout may reuse the name; also run on BEAM | 71 |
225225
| `receive_timeout_bindings.erl` | Names bound in a `receive`'s `after` timeout expression, read after the `receive`: the timeout and message paths, a block timeout, binary tails, later patterns, guards, fun captures and fun-head map keys; also run on BEAM | 6 |
226226
| `exception_basic.erl` | try/catch/throw/error/exit | ~12 |
227+
| `stacktrace_order.erl` | Raising function before non-tail callers: caught error/throw/exit/badmatch, full and shortened real traces through raise/3, monitored {Reason, Stack} exits and failed gen_server starts; also run on BEAM | Table-driven |
227228
| `try_of.erl` | try...of clause | ~6 |
228229
| `try_catch_bound_vars.erl` | Bound names in try-of and catch class/reason patterns: exact equality, guards, fresh names, binary tails and re-raise; also run on BEAM | Table-driven |
229230
| `try_after_reraise.erl` | `try ... after` as the only handler in its function: the after body runs once when the body, an `of` clause or a catch clause raises, then the same class, reason and stacktrace reach the caller; a normal return keeps the body's value; an exception from the after body replaces the held one; an after body that waits, times out and collects garbage; an uncaught exit; also run on BEAM | 28 |

‎tests/stacktrace_order.erl‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
%% EXPECT: stacktrace_order_ok
2+
%% Stacktraces identify the raising function before its non-tail callers,
3+
%% including re-raises and {Reason, Stack} exit reasons. Run on Nera and BEAM.
4+
-module(stacktrace_order).
5+
-export([test/0, init/1]).
6+
7+
test() ->
8+
{outer, {middle, ok}} = outer(ok),
9+
lists:foreach(fun check_caught/1, [error, throw, exit, badmatch]),
10+
lists:foreach(fun check_reraised/1, [error, throw, exit, badmatch]),
11+
ok = check_exit_reason(),
12+
ok = check_failed_start(),
13+
io:format("stacktrace_order_ok~n"),
14+
ok.
15+
16+
check_caught(Mode) ->
17+
{Class, Reason, Stack} = captured(Mode),
18+
{Class, Reason} = expected(Mode),
19+
ok = check_order(Stack),
20+
io:format("caught ~p: ~p~n", [Mode, first_calls(Stack)]).
21+
22+
captured(Mode) ->
23+
try outer(Mode)
24+
catch Class:Reason:Stack -> {Class, Reason, Stack}
25+
end.
26+
27+
%% Keep each call non-tail: BEAM may omit tail callers from a stacktrace.
28+
outer(Mode) -> {outer, middle(Mode)}.
29+
middle(Mode) -> {middle, inner(Mode)}.
30+
inner(error) -> erlang:error(boom);
31+
inner(throw) -> throw(boom);
32+
inner(exit) -> exit(boom);
33+
inner(badmatch) -> 1 = id(2), ok;
34+
inner(ok) -> ok.
35+
36+
expected(error) -> {error, boom};
37+
expected(throw) -> {throw, boom};
38+
expected(exit) -> {exit, boom};
39+
expected(badmatch) -> {error, {badmatch, 2}}.
40+
41+
check_order(Stack) ->
42+
[{?MODULE, inner, 1, _}, {?MODULE, middle, 1, _},
43+
{?MODULE, outer, 1, _} | _] = Stack,
44+
ok.
45+
46+
first_calls(Stack) ->
47+
[{M, F, A} || {M, F, A, _} <- lists:sublist(Stack, 3)].
48+
49+
check_reraised(Mode) ->
50+
{Class, Reason, Original} = captured(Mode),
51+
%% Also supply a shortened, real trace: raise/3 must keep list order,
52+
%% rather than capture the re-raising function's current call stack.
53+
lists:foreach(fun(Stack) ->
54+
Raised = try erlang:raise(Class, Reason, Stack)
55+
catch Class:Reason:Caught -> Caught
56+
end,
57+
Stack = Raised,
58+
ok = check_order(Raised)
59+
end, [Original, lists:sublist(Original, 3)]),
60+
io:format("reraised ~p: ~p~n", [Mode, first_calls(Original)]).
61+
62+
check_exit_reason() ->
63+
{Pid, Ref} = spawn_monitor(fun() ->
64+
{error, Reason, Stack} = captured(error),
65+
exit({Reason, Stack})
66+
end),
67+
receive
68+
{'DOWN', Ref, process, Pid, {boom, Stack}} ->
69+
ok = check_order(Stack),
70+
io:format("exit reason: ~p~n", [first_calls(Stack)])
71+
after 5000 -> error(missing_exit_reason)
72+
end.
73+
74+
check_failed_start() ->
75+
Previous = process_flag(trap_exit, true),
76+
{error, {boom, Stack}} = gen_server:start_link(?MODULE, [], []),
77+
process_flag(trap_exit, Previous),
78+
ok = check_order(Stack),
79+
io:format("failed start: ~p~n", [first_calls(Stack)]).
80+
81+
init([]) -> {ok, outer(error)}.
82+
id(X) -> X.

0 commit comments

Comments
 (0)