emscripten-core / emscripten-core/emscripten
Fun with function pointers and runtime linking
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
So to the best of my knowledge, the following code does not work in Emscripten. I am working with 3.1.39, however, I suspect this is also applies the tip of the tree since I think the problem is just a limitation of using workers for pthread emulation.
```c++
#include
#include
#include
int main() {
int (*symbol)() = nullptr;
try {
auto f2 = std::async(std::launch::async, [] () {
void* handle = dlopen("/libtest.so", RTLD_LAZY);
if(!handle) {
throw std::runtime_error("can not open libtest.so");
}
int (*symbol)() = reinterpret_cast(dlsym(handle, "symbol"));
char* error = dlerror();
if (error) {
throw std::runtime_error("can not get \"symbol\" from libtest.so");
}
std::cerr << "run-time linking/loading thread: symbol() = " << (*symbol)() << std::endl;
return symbol;
});
symbol = f2.get();
}
catch(const std::runtime_error& err) {
std::cerr << "runtime error: " << err.what() << std::endl;
exit(1);
}
/* use that function pointer on the main thread */
std::cerr << "run-time linking/main thread: symbol() = " << (*symbol)() << std::endl;
/* transfer that function pointer to another thread and run it */
auto f3 = std::async(std::launch::async, [symbol] () {
std::cerr << "run-time linking/secondary thread: symbol() = " << (*symbol)() << std::endl;
});
f3.wait();
return 0;
}
```
This code crashes on the line `std::cerr << "run-time linking/main thread: symbol() = " << (*symbol)() << std::endl;` with a table index out of bounds exception. As I understand the problem, the issue is that a worker has called `dlsym` and updates its indirect function table, however, since that function pointer is then immediately used to the main thread, the main worker (which was waiting for the thread to finish in `emscripten_futex_wait` (I think)) never has a chance to update its indirect function table. Is this correct or am I missing something here?
Contributor guide
Assessment
This issue has not been assessed yet.