emscripten-core / emscripten-core/emscripten

cwrap generated functions allocate string args on wasm stack, not good for huge strings

Open
#20,015 9 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

Please include the following in your bug report:

**Version of emscripten/emsdk:**
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.43 (a6b8143cf3c1171db911750359456b15a8deece7)
clang version 17.0.0 (https://github.com/llvm/llvm-project 71513a71cdf380efd6a44be6939e2cb979a62407)
Target: wasm32-unknown-emscripten
Thread model: posix

**Failing command line in full:**
emcc -O3 -o example.js -s EXPORTED_FUNCTIONS=_myFunction,_myFunction2,_myFunction3,_malloc,_free -s ASSERTIONS=1 -s EXPORTED_RUNTIME_METHODS=ccall,cwrap,stringToUTF8 -s ALLOW_MEMORY_GROWTH=1 -pedantic

**Full link command and output with `-v` appended:**
Probably not relevant.

The problem:
I can wrap myFunction via cwrap
```
const myFunction = Module.cwrap(
"myFunction",
"number",
["string"]
);
```

If I attempt to call myFunction with a string argument that is ~1.45MB in size, I get RuntimeError: index out of bounds raised from createExportWrapper. I remember that at some point of my experimenting I was able to see a crash after a function call suggesting that allocation of string was done on stack. So I tried to change the code to allocation on heap
```
const size = lengthBytesUTF8(str) + 1;
const ptr = Module._malloc(size);
Module.stringToUTF8(str, ptr, size);
Module._myFunction(ptr);
Module._free(ptr);
```
And with this change everything works as expected. Unfortunately, I don't have the exact stack trace, so it is still possible that I misread the situation, but the fact that everything works now aligns with the assumption that the problem comes from overflowing the stack.

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.