emscripten-core / emscripten-core/emscripten
Heap memory area corruption error when using "--in-memory flag" with multi-threaded application
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 6h
- Merged PRs (30d)
- 109
Description
@sbc100
In the documentation [Module Splitting](https://emscripten.org/docs/optimizing/Module-Splitting.html?highlight=split_module), it is mention that when doing module splitting with multi-threaded, the flag "--in-memory" and "-sGLOBALBASE=N" is required in order to capture all profile data from all the threads.
I tested adding the flag "--in-memory" under the argument for generating the instrument build [link](https://github.com/emscripten-core/emscripten/blob/de7cbc56c3ac38b83cc3e8bbc17ac5fbb6b3bbd7/emcc.py#L782) with the following flags
`-O0 -s ASSERTIONS=1 -s SAFE_HEAP=0 -pthread -s PROXY_TO_PTHREAD -s SPLIT_MODULE=1`
The build resulted in the following error:

The error was due to a failure in heap check [runtime_stack_check.js](https://github.com/emscripten-core/emscripten/blob/de7cbc56c3ac38b83cc3e8bbc17ac5fbb6b3bbd7/src/runtime_stack_check.js#L53)
` if (HEAPU32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');`
Printing the HEAPU32[0] values in `initRunTime` shows that the values changes after `__RELOC_FUNCS__`, which equates to Module["asm"]["__wasm_apply_data_relocs"]

Looking into the implementation of "__wasm_apply_data_relocs" in wat for instrument build, the function "__wasm_apply_data_relocs" is being marked via in the location i32 atomic.store8 offset=2
> (func $__wasm_apply_data_relocs (type 5)
i32.const 0
i32.const 1
i32.atomic.store8 offset=2
block ;; label = @1
i32.const 21844
global.get $__memory_base
i32.add
global.get $__memory_base
i32.const 6640
In the function `writeStackCookie()` in `runtime_stack_check.js`, `HEAPU32[0] = 0x63736d65; /* 'emsc' */`
0x63736d65 = 1668509029
The instrumentated build doing a store8 of value 1 by offsetting 2
0x63016d65 = 1661037925
Which equals to the value after `__RELOC_FUNCS__`,
This means that the flag "--in-memory" is using the start of heap to store the profile data, which resulted in overwriting the values in `HEAPU32[0]`.
Building the app with `-s SAFE_HEAP=1`, would result in no errors or corruption of heap.
Hence wish to check if this behaviour is intended and if there is any potential issue with the usage of `--in-memory` flag using the start of `HEAPU32` for profile data.
Tested with emsdk 3.1.34
Contributor guide
Assessment
This issue has not been assessed yet.