emscripten-core / emscripten-core/emscripten

mmap doesn't work as expected when mapping multiple pointers with MAP_SHARED to the same fd

Open
#21,706 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 version: 3.1.54; node version: v21.7.0

**Failing command line in full:**
`emcc test_mmap.cpp -o main.js; node main.js`

**Full link command and output with `-v` appended:**

Hi, I tried to use `mmap` with `MAP_SHARED` to map 2 pointers using the same file descriptor got by `shm_open`, expecting to share the memory between the pointers. However, when I tried to write something with one of these 2 pointer and read the other one, it seemed the result wasn't as expected. Here's a code example:

```cpp
// test_mmap.cpp
#include
#include
#include
#include
#include

int main() {
const char* name = "/shared_file";
int len = 10 * sizeof(int);
int offset = 0;
int fd = shm_open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
exit(0);
}
ftruncate(fd, off_t(len));
int* ptr_1 = (int*) mmap(nullptr, len, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, offset);
int* ptr_2 = (int*) mmap(nullptr, len, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, offset);

ptr_2[0] = 10;

std::cout << "ptr1[0] is: " << ptr_1[0] << ", ptr2[0] is: " << ptr_2[0] << std::endl;
shm_unlink(name);
return 0;
}
```
If I compiled it natively with gcc, i.e., `g++ test_mmap.cpp -o main; ./main`, then the result should be:
```
ptr1[0] is: 10, ptr2[0] is: 10
```
which is the expected result.

However, If I compile and run with `emcc test_mmap.cpp -o main.js; node main.js`, I get the result:
```
ptr1[0] is: 0, ptr2[0] is: 10
```
Meaning the sharing doesn't work as expected.

I found a related issue https://github.com/emscripten-core/emscripten/issues/5928, but I believe the case of ***issue #5928 and mine are different***.
In the issue https://github.com/emscripten-core/emscripten/issues/5928, it tried to use `shm_open` to get 2 file descriptors of one file and use `mmap` to map them respectively, and I also tried the code shown in issue https://github.com/emscripten-core/emscripten/issues/5928 and I found it's already fixed in emcc version 3.1.54.
However, in my case, I tried to use `mmap` to map 2 pointers to one specific file descriptor, so it's quite a different issue, and I believe it is worth discussing.

Thank you very much!

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.