Forward an invocation of a variadic function in C

In C, is it possible to forward the invocation of a variadic function? As in,

int my_printf(char *fmt, ...) {
  fprintf(stderr, "Calling printf with fmt %s", fmt);
  return SOMEHOW_INVOKE_LIBC_PRINTF;
}

Forwarding the invocation in the manner above obviously isn’t strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I’m working on requires the wrapper to do some actual work, and doesn’t have (and can’t have added) a helper function akin to vfprintf.

[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function’s definition.]

Passing an ellipsis to another variadic function [duplicate]

This question already has an answer here: Forward an invocation of a variadic function in C 10 answers I have approximately 30 variadic functions. Each one accepts a path as the final argument,

Forward variadic function arguments to variadic function using C++11

I want to forward calls to a library which has a variadic method. The simplest example I could come up with to replicate the problem is this: void Bar(int useless, …) { //Does something } template&l

How to write c function which invoke `super`’s implementation in Objective-C? [duplicate]

This question already has an answer here: Forward an invocation of a variadic function in C 10 answers I need to implement a universal C function which will invoke super’s implementation and re

Passing variable arguments to makecontext function [duplicate]

Possible Duplicate: Forward an invocation of a variadic function in C I want to pass variable arguments to makecontext function as follows. void a(…) { …. makecontext( &stack, &func, ?,

Variadic Adding Function C

I’m writing a simple variadic function that adds together a series of ints and returns the sum. I’m having a bit of trouble understanding how it works and my code doesn’t seem to work though I feel I’

Interoperability of C variadic function and Fortran

Is there a way to declare a C variadic function and call it from Fortran? I need to call this function to compute some dot products between vectors labeled with a string. My idea was to declare someth

variadic function in C

1) Why code under /* test1 */ chunk do not print out anything, but code under /* test2 */ print correctly? 2) How to use va_arg(va, char*) in /* test 1 */ code chunk. void rdfDBG(int dbglevel, const c

Nested variadic function in C++

I’m trying to make wrapper using variadic function. However, I got operand of sizeof may not be a function error from func_t func = va_arg(args, func_t); in Visual studio 2013. Nesting variadic functi

C++ variadic function templates

The concept of variadic templates is quite confusing to me and I want to make it a bit more complex (well I think…). Let us consider the following code: template <typename T> class base { temp

C Variadic function in a C++ wrapper

I am rewriting a C wrapper around a C Python API (Python 1.5) and I noticed that the function Py_VaBuildValue uses variadic number of args. I wondered if I have to use the same in my C++ function wrap

Answers

Use vfprintf:

int my_printf(char *fmt, ...) {
    va_list va;
    int ret;

    va_start(va, fmt);
    ret = vfprintf(stderr, fmt, va);
    va_end(va);
    return ret;
}

Almost, using the facilities available in <stdarg.h>:

#include <stdarg.h>
int my_printf(char *format, ...)
{
   va_list args;
   va_start(args, format);
   int r = vprintf(format, args);
   va_end(args);
   return r;
}

Note that you will need to use the vprintf version rather than plain printf. There isn’t a way to directly call a variadic function in this situation without using va_list.

There’s no way to forward such function calls because the only location where you can retrieve raw stack elements is in my_print(). The usual way to wrap calls like that is to have two functions, one that just converts the arguments into the various varargs structs, and another that actually operates upon those structs. Using such a double-function model, you can (for example) wrap printf() by initializing the structs in my_printf() with va_start(), and then pass them to vfprintf().

If you don’t have a function analogous to vfprintf that takes a va_list instead of a variable number of arguments, you can’t do it. See http://c-faq.com/varargs/handoff.html.

Not directly, however it is common (and you will find almost universally the case in the standard library) for variadic functions to come in pairs with a varargs style alternative function. e.g. printf/vprintf

The v… functions take a va_list parameter, the implementation of which is often done with compiler specific ‘macro magic’, but you are guaranteed that calling the v… style function from a variadic function like this will work:

int m_printf(char *fmt, ...)
{
    int ret;

    /* Declare a va_list type variable */
    va_list myargs;

    /* Initialise the va_list variable with the ... after fmt */

    va_start(myargs, fmt);

    /* Forward the '...' to vprintf */
    ret = vprintf(fmt, myargs);

    /* Clean up the va_list */
    va_end(myargs);

    return ret;
}

This should give you the effect that you are looking for.

If you are considering writing a variadic library function you should also consider making a va_list style companion available as part of the library. As you can see from your question, it can be prove useful for your users.

C99 supports macros with variadic arguments; depending on your compiler, you might be able to declare a macro that does what you want:

#define my_printf(format, ...) /
    do { /
        fprintf(stderr, "Calling printf with fmt %s/n", fmt); /
        some_other_variadac_function(format, ##__VA_ARGS__); /
    } while(0)

In general, though, the best solution is to use the va_list form of the function you’re trying to wrap, should one exist.

Sorry for the off-topic rant, but:

The meta-problem is that the varargs interface in C has been fundamentally broken from the very beginning. It is an invitation to buffer overflows and invalid memory accesses because the end of the argument list can not be found without an explicit end signal (which nobody really uses out of laziness). And it always relied on esoteric implementation-specific macros, with the vital va_copy() macro only supported on some architectures.

Yes you can do it, but it is somewhat ugly and you have to know the maximal number of arguments. Furthermore if you are on an architecture where the arguments aren’t passed on the stack like the x86 (for instance, PowerPC), you will have to know if “special” types (double, floats, altivec etc.) are used and if so, deal with them accordingly. It can be painful quickly but if you are on x86 or if the original function has a well defined and limited perimeter, it can work. It still will be a hack, use it for debugging purpose. Do not build you software around that. Anyway, here’s a working example on x86:

#include <stdio.h>
#include <stdarg.h>

int old_variadic_function(int n, ...)
{
  va_list args;
  int i = 0;

  va_start(args, n);

  if(i++<n) printf("arg %d is 0x%x/n", i, va_arg(args, int));
  if(i++<n) printf("arg %d is %g/n",   i, va_arg(args, double));
  if(i++<n) printf("arg %d is %g/n",   i, va_arg(args, double));

  va_end(args);

  return n;
}

int old_variadic_function_wrapper(int n, ...)
{
  va_list args;
  int a1;
  int a2;
  int a3;
  int a4;
  int a5;
  int a6;
  int a7;
  int a8;

  /* Do some work, possibly with another va_list to access arguments */

  /* Work done */

  va_start(args, n);

  a1 = va_arg(args, int);
  a2 = va_arg(args, int);
  a3 = va_arg(args, int);
  a4 = va_arg(args, int);
  a5 = va_arg(args, int);
  a6 = va_arg(args, int);
  a7 = va_arg(args, int);

  va_end(args);

  return old_variadic_function(n, a1, a2, a3, a4, a5, a6, a7, a8);
}

int main(void)
{
  printf("Call 1: 1, 0x123/n");
  old_variadic_function(1, 0x123);
  printf("Call 2: 2, 0x456, 1.234/n");
  old_variadic_function(2, 0x456, 1.234);
  printf("Call 3: 3, 0x456, 4.456, 7.789/n");
  old_variadic_function(3, 0x456, 4.456, 7.789);
  printf("Wrapped call 1: 1, 0x123/n");
  old_variadic_function_wrapper(1, 0x123);
  printf("Wrapped call 2: 2, 0x456, 1.234/n");
  old_variadic_function_wrapper(2, 0x456, 1.234);
  printf("Wrapped call 3: 3, 0x456, 4.456, 7.789/n");
  old_variadic_function_wrapper(3, 0x456, 4.456, 7.789);

  return 0;
}

For some reason, you can’t use floats with va_arg, gcc says they are converted to double but the program crashes. That alone demonstrates that this solution is a hack and that there is no general solution. In my example I assumed that the maximum number of arguments was 8, but you can increase that number. The wrapped function also only used integers but it works the same way with other ‘normal’ parameters since they always cast to integers. The target function will know their types but your intermediary wrapper doesn’t need to. The wrapper also doesn’t need to know the right number of arguments since the target function will also know it. To do useful work (except just logging the call), you probably will have to know both though.

As it is not really possible to forward such calls in a nice way, we worked around this by setting up a new stack frame with a copy of the original stack frame. However this is highly unportable and makes all kinds of assumptions, e.g. that the code uses frame pointers and the ‘standard’ calling conventions.

This header file allows to wrap variadic functions for x86_64 and i386 (GCC). It doesn’t work for floating-point arguments, but should be straight forward to extend for supporting those.

#ifndef _VA_ARGS_WRAPPER_H
#define _VA_ARGS_WRAPPER_H
#include <limits.h>
#include <stdint.h>
#include <alloca.h>
#include <inttypes.h>
#include <string.h>

/* This macros allow wrapping variadic functions.
 * Currently we don't care about floating point arguments and
 * we assume that the standard calling conventions are used.
 *
 * The wrapper function has to start with VA_WRAP_PROLOGUE()
 * and the original function can be called by
 * VA_WRAP_CALL(function, ret), whereas the return value will
 * be stored in ret.  The caller has to provide ret
 * even if the original function was returning void.
 */

#define __VA_WRAP_CALL_FUNC __attribute__ ((noinline))

#define VA_WRAP_CALL_COMMON()                                        /
    uintptr_t va_wrap_this_bp,va_wrap_old_bp;                        /
    va_wrap_this_bp  = va_wrap_get_bp();                             /
    va_wrap_old_bp   = *(uintptr_t *) va_wrap_this_bp;               /
    va_wrap_this_bp += 2 * sizeof(uintptr_t);                        /
    size_t volatile va_wrap_size = va_wrap_old_bp - va_wrap_this_bp; /
    uintptr_t *va_wrap_stack = alloca(va_wrap_size);                 /
    memcpy((void *) va_wrap_stack,                                   /
        (void *)(va_wrap_this_bp), va_wrap_size);


#if ( __WORDSIZE == 64 )

/* System V AMD64 AB calling convention */

static inline uintptr_t __attribute__((always_inline)) 
va_wrap_get_bp()
{
    uintptr_t ret;
    asm volatile ("mov %%rbp, %0":"=r"(ret));
    return ret;
}


#define VA_WRAP_PROLOGUE()           /
    uintptr_t va_wrap_ret;           /
    uintptr_t va_wrap_saved_args[7]; /
    asm volatile  (                  /
    "mov %%rsi,     (%%rax)/n/t"     /
    "mov %%rdi,  0x8(%%rax)/n/t"     /
    "mov %%rdx, 0x10(%%rax)/n/t"     /
    "mov %%rcx, 0x18(%%rax)/n/t"     /
    "mov %%r8,  0x20(%%rax)/n/t"     /
    "mov %%r9,  0x28(%%rax)/n/t"     /
    :                                /
    :"a"(va_wrap_saved_args)         /
    );

#define VA_WRAP_CALL(func, ret)            /
    VA_WRAP_CALL_COMMON();                 /
    va_wrap_saved_args[6] = (uintptr_t)va_wrap_stack;  /
    asm volatile (                         /
    "mov      (%%rax), %%rsi /n/t"         /
    "mov   0x8(%%rax), %%rdi /n/t"         /
    "mov  0x10(%%rax), %%rdx /n/t"         /
    "mov  0x18(%%rax), %%rcx /n/t"         /
    "mov  0x20(%%rax),  %%r8 /n/t"         /
    "mov  0x28(%%rax),  %%r9 /n/t"         /
    "mov           $0, %%rax /n/t"         /
    "call             *%%rbx /n/t"         /
    : "=a" (va_wrap_ret)                   /
    : "b" (func), "a" (va_wrap_saved_args) /
    :  "%rcx", "%rdx",                     /
      "%rsi", "%rdi", "%r8", "%r9",        /
      "%r10", "%r11", "%r12", "%r14",      /
      "%r15"                               /
    );                                     /
    ret = (typeof(ret)) va_wrap_ret;

#else

/* x86 stdcall */

static inline uintptr_t __attribute__((always_inline))
va_wrap_get_bp()
{
    uintptr_t ret;
    asm volatile ("mov %%ebp, %0":"=a"(ret));
    return ret;
}

#define VA_WRAP_PROLOGUE() /
    uintptr_t va_wrap_ret;

#define VA_WRAP_CALL(func, ret)        /
    VA_WRAP_CALL_COMMON();             /
    asm volatile (                     /
    "mov    %2, %%esp /n/t"            /
    "call  *%1        /n/t"            /
    : "=a"(va_wrap_ret)                /
    : "r" (func),                      /
      "r"(va_wrap_stack)               /
    : "%ebx", "%ecx", "%edx"   /
    );                                 /
    ret = (typeof(ret))va_wrap_ret;
#endif

#endif

In the end you can wrap calls like this:

int __VA_WRAP_CALL_FUNC wrap_printf(char *str, ...)
{
    VA_WRAP_PROLOGUE();
    int ret;
    VA_WRAP_CALL(printf, ret);
    printf("printf returned with %d /n", ret);
    return ret;
}

There are essentially three options.

One is to not pass it on but to use the variadic implementation of your target function and not pass on the ellipses. The other one is to use a variadic macro. The third option is all the stuff i am missing.

I usually go with option one since i feel like this is really easy to handle. Option two has a drawback because there are some limitations to calling variadic macros.

Here is some example code:

#include <stdio.h>
#include <stdarg.h>

#define Option_VariadicMacro(f, ...)/
    printf("printing using format: %s", f);/
    printf(f, __VA_ARGS__)

int Option_ResolveVariadicAndPassOn(const char * f, ... )
{
    int r;
    va_list args;

    printf("printing using format: %s", f);
    va_start(args, f);
    r = vprintf(f, args);
    va_end(args);
    return r;
}

void main()
{
    const char * f = "%s %s %s/n";
    const char * a = "One";
    const char * b = "Two";
    const char * c = "Three";
    printf("---- Normal Print ----/n");
    printf(f, a, b, c);
    printf("/n");
    printf("---- Option_VariadicMacro ----/n");
    Option_VariadicMacro(f, a, b, c);
    printf("/n");
    printf("---- Option_ResolveVariadicAndPassOn ----/n");
    Option_ResolveVariadicAndPassOn(f, a, b, c);
    printf("/n");
}