1 /*
   2  * This file and its contents are supplied under the terms of the
   3  * Common Development and Distribution License ("CDDL"), version 1.0.
   4  * You may only use this file in accordance with the terms of version
   5  * 1.0 of the CDDL.
   6  *
   7  * A full copy of the text of the CDDL should have accompanied this
   8  * source.  A copy of the CDDL is also available via the Internet at
   9  * http://www.illumos.org/license/CDDL.
  10  */
  11 
  12 /*
  13  * Copyright 2014 Garrett D'Amore <garrett@damore.org>
  14  */
  15 
  16 #include "lint.h"
  17 #include <stdio.h>
  18 #include <unistd.h>
  19 #include <fcntl.h>
  20 #include <errno.h>
  21 #include <assert.h>
  22 
  23 #define FDFILE  "/dev/fd/%u"
  24 
  25 /*
  26  * fexecve.c - implements the fexecve function.
  27  *
  28  * We implement in terms of the execve() system call, but use the path
  29  * /dev/fd/<fd>.  This depends on special handling in the execve system
  30  * call; note that /dev/fd files are not normally directly executable.
  31  * This does not actually use the fd filesystem mounted on /dev/fd.
  32  */
  33 int
  34 fexecve(int fd, char *const argv[], char *const envp[])
  35 {
  36         char path[32];  /* 8 for "/dev/fd/", 10 for %u, + \0 == 19 */
  37 
  38         if (fcntl(fd, F_GETFL) < 0) {
  39                 /* This will have the effect of returning EBADF */
  40                 return (-1);
  41         }
  42         assert(snprintf(NULL, 0, FDFILE, fd) < (sizeof (path) - 1));
  43         (void) snprintf(path, sizeof (path), FDFILE, fd);
  44         return (execve(path, argv, envp));
  45 }