emscripten-core / emscripten-core/emscripten

Opening files packaged with `--preload-file` fails in wasm workers

Open
#18,241 0 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

The issue happens only in wasm workers, but not in pthreads.
Test code:
```c++
#include

#ifdef __EMSCRIPTEN_WASM_WORKERS__
#include
#elif __EMSCRIPTEN_PTHREADS__
#include
#endif

#include
#include
#include

void readFile(const std::string& path) {
std::ifstream ifs(path, std::ios::binary);
if (!ifs.good()) {
EM_ASM({console.error('open failed')});
return;
}

ifs.seekg(0, std::ios::end);
auto fSize = ifs.tellg();
ifs.seekg(0, std::ios::beg);

std::vector f(fSize);
ifs.read(reinterpret_cast(f.data()), fSize);
if (ifs.fail()) {
EM_ASM({console.error('file read failed')});
return;
}

EM_ASM({console.log('file read ok')});
}

void worker() {
static bool initialized = false;
if (!initialized) {
EM_ASM({console.log('worker reading preloaded file')});
readFile("asset.txt");

initialized = true;
}
}

void main_loop() {
#ifdef __EMSCRIPTEN_PTHREADS__
static std::thread t;
#endif

static bool initialized = false;
if (!initialized) {
EM_ASM({console.log('main reading preloaded file')});
readFile("asset.txt");

#ifdef __EMSCRIPTEN_WASM_WORKERS__
auto w = emscripten_malloc_wasm_worker(65536);
emscripten_wasm_worker_post_function_v(w, &worker);
#elif __EMSCRIPTEN_PTHREADS__
t = std::thread(&worker);
t.detach();
#endif

initialized = true;
}
}

int main() {
emscripten_set_main_loop(main_loop, 1, 1);
return 0;
}
```
Build command line:
```
em++ -sWASM_WORKERS=1 --preload-file asset.txt preload.cpp -o preload.html
```

Emscripten version:
```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.27-git (8b26b01ad12201559e2b0889a319841dc3764ed1)
clang version 16.0.0 (https://github.com/llvm/llvm-project.git f530e6e34ee19cfc6f08179879dab64207d51237)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /home/valerio/opt/emsdk/llvm/git/build_main_64/bin
```

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.