Search code examples
cvariadic-functionsdynamic-linkingld-preloaddlsym

How to wrap variadic functions using LD_PRELOAD?


I have to perform dynamic linking on a variadic function of following format:

int foo(char *args, const char *f, ...)

Here the number of arguments are variable. What I want to achieve is that I want to pass the obtained arguments to the original function which I am resolving using dlsym. If I do not pass all the arguments I keep getting segmentation fault. Thanks in advance.


Solution

  • I think your problem is not related to LD_PRELOAD or dlopen/dlsym: you simply want to call a variadic function from a variadic function, eg:

    int printf (const char *fmt, ...) {
        return fprintf (stdout, fmt, my_variadic_parameters);
    }
    

    As far as I know, it is not possible, but in carefully designed libraries (which is obviously a minority of them), every variadic function has a counterpart that uses va_list parameter, like printf and vprintf, fprintf and vfprintf:

    int printf (const char *fmt, ...) {
        va_list ap;
        int retval;
    
        va_start (ap, fmt);
        retval= vfprintf (stdout, fmt, ap);
        va_end (ap);
        return retval;
    }
    
    int vmyprintf (const char *fmt, va_list pap) {
        va_list ap;
        int retval;
    
        va_copy (ap, pap);
        retval= vfprintf (stdout, fmt, ap);
        va_end (ap);
        return retval;
    }
    

    So you should ask the creator of 'foo' to create a 'vfoo':

    int vfoo (char *args, const char *f, va_list v)