title: Wrapping a variadic function
body: <p>I am trying to wrap the <code>open</code> function. I do not know how to pass the optional third argument to the real <code>open</code>. As I understand there is no way to validate the <code>va_list</code>, so the <code>if (mode)</code> is not correct int he below example. Is there a way to call <code>open</code> with the proper number of arguments?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdarg.h&gt;
  
  extern "C" 
  {
  
  int shouldWrap = 0;
  
  int willCallRealOpen(const char * path, int flags, va_list args);
  int __real_open(const char * path, int flags, ...);
  
  int __wrap_open(const char * path, int flags, ...) {
      if(shouldWrap != 0){
          printf("Fake called\n");
          return 0;
      }
      else {
          printf("Real called\n");
          va_list args;
              va_start(args, flags);
              int res = willCallRealOpen(path, flags, args);
          va_end(args);
          return res;
      }
  }
  
  int willCallRealOpen(const char * path, int flags, va_list args) {
      mode_t mode = va_arg(args, mode_t);
      if (mode) {
          printf("3 args\n");
          return __real_open(path, flags, mode);
      }
      else {
          printf("2 args\n");
          return __real_open(path, flags);
      }
  }   
  
  }
  
  int main() {
      //int fd = open("temp.txt", O_CREAT | O_WRONLY, S_IRUSR);
      int fd = open("temp.txt", O_CREAT | O_WRONLY);
  }
  </code></pre>