WebAssembly / WebAssembly/wasi-libc

C++, no exceptions, and OOM in `operator new`

Open
#406 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C
Stars
1k
Forks
251
Avg merge
7h 15m
Merged PRs (30d)
3

Description

This example program is intended to allocate 4 wasm pages of memory:

#include <vector>
#include <stdio.h>

int main() {
  std::vector<int> v;
  for (int i = 0; i < 65536; i++) {
    v.push_back(4);
  }
}

This can be compiled to have a max wasm memory size of 2 pages, though, which will cause the program to OOM at runtime:

$ clang++ foo.cpp -o foo.wasm -O2 -Wl,--stack-first,--max-memory=131072 -fno-exceptions

which produces foo.wasm.gz.

When run:

$ wasmtime run ./foo.wasm

this program will (currently for me) infinite loop.

The issue seems to be that when compiled with -fno-exceptions, which I believe is currently required of C++ code compiled with wasi-libc to wasm since __cxa_throw isn't otherwise defined, then the operator new operator is defined to return NULL for failed allocations. For a native platform this is fine because it probably faults quickly when accessing this address. For Wasm, however, this is a valid address so the program keeps going.

This was, for me, an unfortunately slow way for me to discover that the original program I was working with was OOM-ing and needed a --max-memory argument to be passed that was larger than the base. I'm not sure how best to improve this, though, since I suspect aborting on failure would not be spec-compliant with C++.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the failure with the provided C++ example, clang++ command, and wasmtime invocation. Start by tracing operator new under -fno-exceptions and the interaction with __cxa_throw, then determine a standards-compliant failure behavior for WebAssembly. Done means the OOM case no longer loops indefinitely and has a regression test covering the constrained-memory example.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, wasm
Domain
operating-systems
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.