Search code examples
cheader-filesdlsym

C typedef for function prototype dlsym


I am writing a shared library to LD_PRELOAD and intercept some calls from an existing library (in linux).

I have about 50+ different function prototypes and attribute declaration to write and I want to keep the code as short as possible because the function prototypes are very large.

The issue I am having is the following: lets say I want to intercept all calls to doStuff(int, void*)

I have the following code:

Header file:

typedef int (*doStuffPrototype) (int, void*);
extern doStuffPrototype dlSym_doStuff;
extern int doStuff(int, void*);

C file

doStuffPrototype dlSym_doStuff;
__attribute__((constructor)) void libSomething() {
    void* lib_ptr;
    dlerror();
    lib_ptr = dlopen(LIB_NAME, RTLD_LAZY);
    ...
    // Loading all references to the real library
    dlSym_doStuff = (doStuffPrototype) dlSym(lib_ptr, "doStuff");
}

Ok now this works fine but I'd like to replace the following line in the header:

extern int doStuff(int, void*);

with something like:

extern doStuffPrototype doStuff;

But then I get

'doStuff' redeclared as different kind of symbol

Since it is declared in the real library...but...it has no problem with the current syntax...the one I have to write the arguments all over again... If I take the dereferencing off the typedef:

typedef int (doStuffPrototype) (int, void*);

Then extern doStuffPrototype doStuff; works but the dlSym_doStuff = (doStuffPrototype) dlSym(lib_ptr, "doStuff"); does not compile...

I have tried many things: is this possible?


Solution

  • It's clear that

    typedef int (*doStuffPrototype) (int, void*);
    

    and

    typedef int (doStuffPrototype) (int, void*);
    

    create slightly different typedefs.

    My suggestion is to create two different typedefs and use each one appropriately.

    typedef int (doStuffPrototype) (int, void*);
    typedef doStuffPrototype* doStuffPrototypePtr
    

    And use them like:

    extern doStuffPrototypePtr dlSym_doStuff;
    extern doStuffPrototype doStuff;
    
    ...
    
    
    dlSym_doStuff = (doStuffPrototypePtr) dlSym(lib_ptr, "doStuff");