Search code examples
shared-librariesddlopen

Shared Object not loading, gives segmentation fault on dlopen


I have a lot of code that was written on 32 bit machine. Now I've upgraded to 64 bit, and it won't load shared objects. The shared object is compiled for 32 bit (using -m32 flag for DMD), and so is the host application. This is the shared library:

module lib;

export extern(C) int abcd(){
    return 4;
}

it is compiled using dmd -shared -m32 lib.d, and the output is lib.so And this is the code for the loader:

module loader;

import std.stdio;
import core.sys.posix.dlfcn;

alias func = extern(C) int function();

void main(string[] args){
    writeln("reached 0, press enter");readln;
    void* so = dlopen("/home/nafees/Desktop/temp/lib.so",RTLD_LAZY);
    writeln("reached 1, press enter");readln;
    func f = cast(func)dlsym(so,"abcd");
    writeln((*f)());
}

This one is compiled using dmd -m32 loader.d. It compiles fine, but when I run it, it runs fine till the dlopen, then causes a segmentation fault(core dumped). This used to work fine on 32 bit.

What is wrong in this code, why won't it work?

P.S: I don't want to compile it for 64 bit, so if a solution requires removing -m32, I need another one.

EDIT: I have a program compiled (also written in D), that loads a shared object (which is also written in D), using dlopen. That program would run fine in 32 bit, but not on my 64 bit machine.

EDIT2: I now tried compiling the loader without -m32, it now dlerror is saying this: /home/nafees/Desktop/temp/lib.so: wrong ELF class: ELFCLASS32


Solution

  • Instead of dlopen try to use loadLibrary.

    UPDATE:

    Use -fPIC flags for compile lib.d: dmd -m32 -fPIC -shared lib.d