Skip to content

Raise out_of_memory when list_to_binary cannot allocate its result - #2495

Open
gabrielmancini wants to merge 1 commit into
atomvm:release-0.7from
iobee-io:fix-literal-binary-oom
Open

gabrielmancini wants to merge 1 commit into
atomvm:release-0.7from
iobee-io:fix-literal-binary-oom

Conversation

@gabrielmancini

Copy link
Copy Markdown

term_from_literal_binary copies the data into the binary that term_create_uninitialized_binary returns, but for a refc binary that is an invalid term when the buffer cannot be malloc'd, so the copy writes through a NULL pointer (term_binary_data of the invalid term).

list_to_binary/1 (and iolist_to_binary/1, which calls it) hits this whenever the heap has no block for the result: it already holds a temporary buffer of the same size, so on a fragmented ESP32 heap a result of half the largest free block can be enough. We saw it on an ESP32 without PSRAM when gen_tcp_socket flattened a ~14 KB HTTP reply:

Unable to allocate 14442 bytes for refc_binary.
Guru Meditation Error: Core  0 panic'ed (StoreProhibited). Exception was unhandled.

This skips the copy for an invalid term, and makes list_to_binary/1 raise out_of_memory in that case, so the calling process crashes instead of the VM.

Field check, same board (ESP32, no PSRAM), asking a spawned process for iolist_to_binary/1 of 64 one-KB chunks:

request largest free block result
65,536 bytes 34,816 the process exits with out_of_memory; VM keeps running
16,384 bytes 34,816 ok

Before the fix, the first one is the panic above.

No test: the failure needs a malloc that fails for the second buffer only, which neither generic_unix nor the QEMU test app gives us deterministically. Happy to add one if there is an allocation-failure hook I missed. CHANGELOG entry under Fixed.

@petermm

petermm commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

AMP code: (human me doesn't entirely understand all of this)

PR #2495 review

Recommendation: keep the OOM fix, but limit it to list_to_binary/1 and iolist_to_binary/1 for release-0.7. The patch correctly raises error:out_of_memory for those two functions. Its change to a shared helper also lets unrelated callers continue with an invalid term that they do not check.

Reviewed the last commit, 810ede42, against its parent. Local HEAD matches the PR head. Oracle independently identified the same caller-handling gap.

P2 · Unchecked callers can publish an invalid term

term_from_literal_binary() now returns the invalid-term sentinel on refcounted allocation failure. The new check in list_to_binary/1 correctly frees the temporary buffer before raising, and iolist_to_binary/1 delegates list input to that code. Other callers do not all handle the new return value:

The failed allocation itself is pre-existing, and these callers already hit an invalid copy on the parent commit. What changes is the failure mode: they can now return malformed results or enter exception handling without an exception set by the failing NIF. This is not a regression on successful allocations.

Suggested fix: keep the checked allocation in the shared NIF

The two hunks below apply to the reviewed commit. Use the already-fallible allocator in list_to_binary/1, copy only on success, and leave the shared helper unchanged from the parent. If the shared helper is made fallible instead, audit every caller that can request a refcounted binary before landing that change; adding checks only to the examples above would leave the same gap elsewhere.

diff --git a/src/libAtomVM/nifs.c b/src/libAtomVM/nifs.c
--- a/src/libAtomVM/nifs.c
+++ b/src/libAtomVM/nifs.c
@@ -3071,11 +3071,12 @@ static term nif_erlang_list_to_binary_1(Context *ctx, int argc, term argv[])
         free(alloc_ptr);
         RAISE_ERROR(OUT_OF_MEMORY_ATOM);
     }
-    term bin_res = term_from_literal_binary(bin_buf, bin_size, &ctx->heap, ctx->global);
-
-    free(alloc_ptr);
+    term bin_res = term_create_uninitialized_binary(bin_size, &ctx->heap, ctx->global);
     if (UNLIKELY(term_is_invalid_term(bin_res))) {
+        free(alloc_ptr);
         RAISE_ERROR(OUT_OF_MEMORY_ATOM);
     }
+    memcpy((void *) term_binary_data(bin_res), bin_buf, bin_size);
+    free(alloc_ptr);
     return bin_res;
 }
diff --git a/src/libAtomVM/term.h b/src/libAtomVM/term.h
--- a/src/libAtomVM/term.h
+++ b/src/libAtomVM/term.h
@@ -2124,13 +2124,11 @@ static inline term term_create_uninitialized_binary(size_t size, Heap *heap, Glo
  * @param size size of binary data buffer.
  * @param heap the heap to allocate the binary in
  * @param glb the global context as refc binaries are global
- * @return a term pointing to the boxed binary pointer, or an invalid term if the binary could not be allocated.
+ * @return a term pointing to the boxed binary pointer.
  */
 static inline term term_from_literal_binary(const void *data, size_t size, Heap *heap, GlobalContext *glb)
 {
     term binary = term_create_uninitialized_binary(size, heap, glb);
-    if (LIKELY(!term_is_invalid_term(binary))) {
-        memcpy((void *) term_binary_data(binary), data, size);
-    }
+    memcpy((void *) term_binary_data(binary), data, size);
     return binary;
 }

Regression coverage

The conversion tests cover small and empty results and badarg, but do not cover failure to allocate the refcounted result. ALLOC_RANDOM_FAILURE exists, but it is a random allocator shim, not a targeted failure hook. If a targeted hook becomes available, test that both functions raise error:out_of_memory and that the calling process can catch the exception and keep running. The ESP32 field results are reported by the PR author; this review did not rerun them or run the VM test suite.

term_alloc_refc_binary returns an invalid term when the refc buffer
cannot be malloc'd, but list_to_binary/1 copied the data into it
through term_from_literal_binary anyway, writing through a NULL
pointer. On ESP32 with a fragmented heap, erlang:iolist_to_binary/1 of
a ~14 KB iolist (gen_tcp_socket flattening an HTTP reply) panicked
with StoreProhibited right after 'Unable to allocate 14442 bytes for
refc_binary'.

Allocate the result with term_create_uninitialized_binary, check it,
and copy only on success, so list_to_binary/1 and iolist_to_binary/1
raise out_of_memory and only the calling process crashes. The shared
term_from_literal_binary is left as it was, since its other callers do
not check for an invalid term.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
@gabrielmancini gabrielmancini changed the title Raise out_of_memory when a literal binary cannot be allocated Raise out_of_memory when list_to_binary cannot allocate its result Nov 26, 2026
@gabrielmancini

Copy link
Copy Markdown
Author

Thanks for the review. Applied your suggestion in 8da2743: list_to_binary/1 now allocates with term_create_uninitialized_binary, checks it and copies only on success, and term_from_literal_binary is back to what it was, so its other callers are unchanged. I updated the title and commit message to match. test-erlang passes on generic unix.

There is still no regression test, since there is no targeted allocation-failure hook. The proof is the ESP32 field case: iolist_to_binary/1 larger than the largest free block now raises out_of_memory, only that process crashes, and the VM keeps running.

gabrielmancini added a commit to iobee-io/AtomVM-petermm that referenced this pull request Nov 26, 2026
As atomvm#2495 after review: list_to_binary/1 allocates with
term_create_uninitialized_binary, checks it and copies only on success,
and the shared term_from_literal_binary is left as upstream has it,
since its other callers do not check for an invalid term.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
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.

3 participants