emscripten-core / emscripten-core/emscripten
Dynamic linking problem
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
I am trying to port a game written in C. Game engine uses (API) libraries that are loaded at startup depending on the system on which it is running. Engine uses function "GetAPI" that returns "handles" to functions from that specific library (eg. R_Init). The problem is that engine have own R_Init function too and when tries to run retrieved R_Init function from library, the engine function is called.
Example/Reproduction:
**main.c**
```c
#include
#include
#if __EMSCRIPTEN__
#define LIB_NAME "test.wasm"
#else
#define LIB_NAME "test.so"
#endif
typedef int (*R_Init_FN)();
typedef void (*GetAPI_FN)(R_Init_FN*);
int R_Init(){
return 1;
}
int main(){
void* handle;
GetAPI_FN GetAPI;
R_Init_FN Test_R_Init = NULL;
handle = dlopen(LIB_NAME, RTLD_NOW);
GetAPI = dlsym(handle, "GetAPI");
GetAPI(&Test_R_Init);
printf("[Main] R_Init(): %d\n", Test_R_Init());
return 0;
}
```
**test.c**
```c
typedef int (*R_Init_FN)();
int R_Init(){
return 2;
}
void GetAPI(R_Init_FN* fnc) {
*fnc = R_Init;
}
```
**Emscripten compilation commands**
```
emcc -sMAIN_MODULE=1 -g -fPIC main.c -ldl -o main.html
emcc -sSIDE_MODULE=1 -g -fPIC test.c -o test.wasm
```
Also need to add `Module.dynamicLibraries` to main.html to preload "test.wasm" library.
```javascript
Module.dynamicLibraries = [
'test.wasm'
];
```
**Output**
```
[Main] R_Init(): 1
```
Wrong. Should be 2.
Also I'm tried it under linux:
```
gcc -g -fPIC main.c -ldl -o main
gcc -g -fPIC -shared test.c -o test.so
```
**Output**
```
$ LD_LIBRARY_PATH=. ./main
[Main] R_Init(): 2
```
Good
**Version of emscripten/emsdk:**
```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.8-git (eea4056bb71493ae388a1cc22b2bda07cc4932ef)
clang version 15.0.0 (https://github.com/llvm/llvm-project.git 3807583b8f879e4ecfc63b268622aee399fbe05a)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /code/tools/emsdk/llvm/git/build_main_64/bin
```
Contributor guide
Assessment
This issue has not been assessed yet.