Skip to content

Keep the exception class when the raw stacktrace cannot be allocated - #2500

Open
gabrielmancini wants to merge 3 commits into
atomvm:release-0.7from
iobee-io:fix-oom-rethrow
Open

gabrielmancini wants to merge 3 commits into
atomvm:release-0.7from
iobee-io:fix-oom-rethrow

Conversation

@gabrielmancini

Copy link
Copy Markdown

When there is no memory for the raw stacktrace, stacktrace_create_raw_mfa returns the atom out_of_memory in its place (and undefined when collecting the line locations fails). A later raise instruction reads the exception class from that term, for example in the rethrow of a try expression with no matching clause. stacktrace_exception_class asserts that it is a tuple, so the VM aborts:

WARNING: Unable to allocate heap space for raw stacktrace
assert failed: stacktrace_exception_class stacktrace.c:348 (term_is_tuple(stack_info) && term_get_tuple_arity(stack_info) >= 6)

With this change the five failure returns give the exception class instead, as the build without AVM_CREATE_STACKTRACES already does, and stacktrace_exception_class returns an atom as it is. Such an exception keeps its class and reason, and stacktrace_build gives undefined for its stacktrace.

#2252 fixed a different path into the same assert (erlang:raise/3 with a built stacktrace).

Field data: our serial logs have this assert 17 times between 27 October and 23 November, on ESP32 boards without PSRAM.

Tests: test_oom_rethrow fills a heap bounded by max_heap_size with 0 to 255 cells before raising through such a try, so that some runs fail exactly at the stacktrace allocation.

  • generic_unix, Linux x86_64: without the fix it aborts with the assert above, 5 of 5 runs; with it, passes 5 of 5. The whole test-erlang suite passes, and the module also returns 0 on BEAM.
  • ESP32 on QEMU, with the module temporarily added to the ESP32 test app: aborts with the same assert without the fix, passes with it. The only failure in that run is test_socket, which also fails on release-0.7 without this change.

The test workers are deliberately neither monitored nor linked. A monitored process that dies with a full heap hits a different abort (Cannot handle out of memory. in context_monitors_handle_terminate, where the DOWN message is built on the dying process's heap). This PR does not change that.

When there was no memory for the raw stacktrace,
stacktrace_create_raw_mfa returned the atom out_of_memory (or undefined)
in its place. A later raise instruction, as in the rethrow of a try
expression with no matching clause, reads the class from that term:
stacktrace_exception_class asserted that it was a tuple and the VM
aborted.

Return the exception class instead, as the build without stacktraces
does, and have stacktrace_exception_class return an atom as it is. Such
an exception keeps its class and reason and has an undefined stacktrace.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
Under valgrind the test polled every millisecond and the runs of the
valgrind step took over 30 minutes, timing out on CI.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
@gabrielmancini

Copy link
Copy Markdown
Author

About the test_eth failure on the ESP32 QEMU jobs: I could reproduce it locally on esp32s3 (QEMU, memory checks): 3 of 13 runs with this change, 0 of 13 without it. I then built with a print on each of the five changed failure returns and on the new atom check in stacktrace_exception_class: in 18 runs, two of which failed test_eth, none of them was reached. So the changed behaviour does not run in the failing tests. I don't know whether the different binary shifts the timing of the test or whether it is a rare flake on release-0.7 too. In the failing runs test_eth returns error about 10 ms after ETHERNET_EVENT_CONNECTED, before getting an IP.

@petermm petermm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AMP code:

PR review: preserve exception class on raw-stacktrace OOM

Reviewed 628762b75 and 4cff31e40, including an independent oracle review. No newly introduced production blocker found. Returning the exception class as the raw-stacktrace fallback matches the stacktrace-disabled representation. The interpreter and JIT can both read it on rethrow, while building a user-visible trace from it yields undefined. The polling backoff does not change the failure check.

P2 — The regression can pass without observing a successful rethrow

test_oom_rethrow.erl:48–93

The parent treats worker death without wrong_exception as success. A worker that dies during fill/2 or while allocating {Class, Reason} in the outer catch therefore counts the same as one that caught error:boom. The test still detects a VM-wide abort when the sweep hits that path, but it can pass if the sweep stops hitting it or no worker ever recovers. It also only raises error, so a fallback hard-coded to error would go undetected.

Small improvement: match in the catch without creating a result tuple and require at least one acknowledgement that the original exception was caught. Keep tolerating workers that run out of heap before reporting. The existing selective receives still check wrong_exception for every worker; they leave rethrow_seen for start/0.

diff --git a/tests/erlang_tests/test_oom_rethrow.erl b/tests/erlang_tests/test_oom_rethrow.erl
--- a/tests/erlang_tests/test_oom_rethrow.erl
+++ b/tests/erlang_tests/test_oom_rethrow.erl
@@ -35,7 +35,10 @@
 -define(MAX_HEAP, 256).
 
 start() ->
     ok = sweep(0),
-    0.
+    receive
+        rethrow_seen -> 0
+    after 0 -> error(no_successful_rethrow)
+    end.
 
 sweep(?MAX_HEAP) ->
@@ -65,12 +68,8 @@ no_wrong_exception() ->
     end.
 
 worker({Parent, Cells}) ->
     Data = fill(Cells, []),
-    case rethrow(Data) of
-        {error, boom} -> ok;
-        {error, out_of_memory} -> ok;
-        _ -> Parent ! wrong_exception
-    end,
+    rethrow(Data, Parent),
     % Data stays alive across the raise.
     Cells = length(Data),
     ok.
@@ -80,15 +79,19 @@ fill(N, Acc) -> fill(N - 1, [N | Acc]).
 
 % The inner try only catches throws: the compiler rethrows anything else
 % with the raise instruction, which reads the class from the stacktrace.
-rethrow(Data) ->
+rethrow(Data, Parent) ->
     try
         try
             ?MODULE:fail(Data)
         catch
             throw:_ -> thrown
         end
+    of
+        _ -> Parent ! wrong_exception
     catch
-        Class:Reason -> {Class, Reason}
+        error:boom -> Parent ! rethrow_seen;
+        error:out_of_memory -> ok;
+        _:_ -> Parent ! wrong_exception
     end.
 
 fail(_Data) ->

That patch confirms a successful rethrow somewhere in the sweep, not necessarily after raw-stacktrace allocation failed. To assert the actual fallback, a stacktrace-enabled AtomVM test should require a worker to catch the original reason with Trace =:= undefined, using a normal-heap control that catches it with a list trace. Don't require that missing-trace observation on BEAM or on AtomVM built without stacktraces. Cover throw and exit as well, with an inner catch that deliberately does not match the class being tested.

P1 follow-up (pre-existing) — Failed shrink can leave a stale exception reason

stacktrace.c:118–133, stacktrace.c:250–256

memory_ensure_free_with_roots can move the heap and update the X-register roots, then return an error if a second, shrinking allocation fails. Both raw-stacktrace allocation branches return before copying the relocated reason back to ctx->exception_reason. The error handler then overwrites X1 with the stale term. If the reason was heap-allocated, a subsequent catch or exit handler can read freed memory. The two reviewed commits do not introduce this ordering, but preserving the class does not address it. The bounded-heap test rejects over-limit allocations before GC and uses the immediate atom boom, so it doesn't cover this case.

Small follow-up: restore the rooted fields before handling the allocation result. Verify it separately by fault-injecting failure of the shrink after a successful moving GC, with a heap-allocated reason.

diff --git a/src/libAtomVM/stacktrace.c b/src/libAtomVM/stacktrace.c
--- a/src/libAtomVM/stacktrace.c
+++ b/src/libAtomVM/stacktrace.c
@@ -123,11 +123,12 @@
         ctx->x[0] = ctx->exception_stacktrace;
         ctx->x[1] = ctx->exception_reason;
         // NOLINT(term-use-after-gc) exception_class is always an atom
-        if (UNLIKELY(memory_ensure_free_with_roots(ctx, TUPLE_SIZE(6), 2, ctx->x, MEMORY_CAN_SHRINK)
-                != MEMORY_GC_OK)) {
+        enum MemoryGCResult result = memory_ensure_free_with_roots(
+            ctx, TUPLE_SIZE(6), 2, ctx->x, MEMORY_CAN_SHRINK);
+        ctx->exception_stacktrace = ctx->x[0];
+        ctx->exception_reason = ctx->x[1];
+        if (UNLIKELY(result != MEMORY_GC_OK)) {
             fprintf(stderr, "WARNING: Unable to allocate heap space for raw stacktrace\n");
             return exception_class;
         }
-        ctx->exception_stacktrace = ctx->x[0];
-        ctx->exception_reason = ctx->x[1];
         term built_stacktrace = ctx->exception_stacktrace;
@@ -250,9 +251,11 @@
     ctx->x[live_x_regs - 1] = ctx->exception_reason;
     // NOLINT(term-use-after-gc) exception_class is always an atom
-    if (UNLIKELY(memory_ensure_free_with_roots(ctx, requested_size, live_x_regs, ctx->x, MEMORY_CAN_SHRINK) != MEMORY_GC_OK)) {
+    enum MemoryGCResult result = memory_ensure_free_with_roots(
+        ctx, requested_size, live_x_regs, ctx->x, MEMORY_CAN_SHRINK);
+    ctx->exception_reason = ctx->x[live_x_regs - 1];
+    if (UNLIKELY(result != MEMORY_GC_OK)) {
         fprintf(stderr, "WARNING: Unable to allocate heap space for raw stacktrace\n");
         return exception_class;
     }
-    ctx->exception_reason = ctx->x[live_x_regs - 1];
 
     term raw_stacktrace = term_nil();

Verification

Rebuilt the stacktrace-enabled, non-JIT runtime on macOS arm64 and ran the checked-in test as a standalone BEAM module compiled with OTP 29. AtomVM returned 0 and emitted 157 raw-stacktrace allocation warnings during the sweep. This confirms allocation denial was exercised on this build; it does not show which workers recovered.

Both suggested diffs pass git apply --check. The test-only suggestion was also applied to a scratch copy and passed on the rebuilt AtomVM interpreter and on OTP 29 BEAM. JIT integration was inspected in source; JIT, Valgrind timing, and allocator fault injection were not run.

A worker that ran out of memory before catching anything counted the same
as one that caught the original error, so the test could pass without any
successful rethrow. Require at least one worker to catch error:boom.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
@gabrielmancini

Copy link
Copy Markdown
Author

Thanks! Applied the test change so at least one worker must catch the original error:boom. The pre-existing failed-shrink issue in stacktrace.c I'd handle in a separate PR, with fault injection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants