In my code, I have a for loop where first I am calling dlopen to load a shared object, then calling a function of the loaded library, and then dlclose to unload it. The first iteration of the loop works as expected but during the second iteration (when i=1) dlopen call is causing segmentation fault (core dumped).
void *handle;
char* (*goImg)();
char *error;
int i;
for (i=0; i<5; i++) {
handle = dlopen("mylib.so", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
goImg = dlsym(handle, "writeToFileInWrapper");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1); }
goImg();
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
dlclose(handle);
}
Script to generate mylib.so:
echo "Building golang code to create an archive file."
go build -buildmode=c-archive -o bin/goHelper.a goHelper.go
echo "Building wrapperCodeInC to be consumed as a shared library."
gcc -c -fPIC -o bin/shared/wrapperCodeInC.o -I./bin -I./wrapper wrapper/wrapperCodeInC.c
gcc -s -shared -lpthread -Wl,-Bsymbolic -o bin/mylib.so -Wl,--whole-archive bin/goHelper.a -Wl,--no-whole-archive bin/shared/wrapperCodeInC.o
Here, goHelper.go has few functions written in go language and wrapperCodeInC.c has the wrapper functions to invoke those go functions.
In the first run of the loop dlopen(), goImg(), and dlclose() works as expected but then during the second run (i=1), dlopen is dumping core. Any idea what could be causing this?
Note: If I remove -Wl,-Bsymbolic from the build file, then I get an error similar to this issue: https://github.com/golang/go/issues/30822
If I add flag RTLD_NODELETE in dlopen call (dlopen("mylib.so", RTLD_LAZY | RTLD_NODELETE )), then all the iterations run fine but I am not sure if that is the right thing to do.