emscripten-core / emscripten-core/emscripten

withStackSave() is not exception-safe (with patch)

Open
#17,313 10 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

**Version of emscripten/emsdk:**

```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.13 (531257621816c200bc7c3be53129494afd029aec)
clang version 15.0.0 (https://github.com/llvm/llvm-project 5c6ed60c517c47b25b6b25d8ac3666d0e746b0c3)
Target: wasm32-unknown-emscripten
Thread model: posix
```

In the generated JS glue it includes:

```
function withStackSave(f) {
var stack = stackSave();
var ret = f(); // where f() is an arbitrary JS-implemented function
stackRestore(stack);
return ret;
}
```

If f() throws, the stack is potentially left in an undefined state. It "really should" look more like:

```
function withStackSave(f) {
var stack = stackSave();
var ret;
try{ ret = f(); }
finally { stackRestore(stack); }
return ret;
}
```

or, more succinctly:

```
function withStackSave(f) {
var stack = stackSave();
try{ return f(); }
finally { stackRestore(stack); }
}
```

That way, if f() throws then the stack is restored to a known-valid state.

That said: that function is unused in my copy. Perhaps it's used in certain combinations of build flags or expected by clients which use `--pre-js` and/or `--post-js` to add custom JS to the generated output.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.