NO-OP: <tab> after <space> fixes in libs
[ardour.git] / libs / pbd / system_exec.cc
index 0102323505cf651336b2900987ef09e3868fc9f3..0a17cce56079de8364f10ce3f8700a1cff41bdb2 100644 (file)
 #include <sys/resource.h>
 #endif
 
+#include <glibmm/miscutils.h>
 
-#define USE_VFORK
-
+#include "pbd/file_utils.h"
+#include "pbd/search_path.h"
 #include "pbd/system_exec.h"
 
 using namespace std;
 using namespace PBD;
 
 static void * interposer_thread (void *arg);
+
+#ifndef PLATFORM_WINDOWS /* POSIX Process only */
 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
+#endif
 
 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
 /*
@@ -151,22 +155,31 @@ static int close_allv(const int except_fds[]) {
 }
 #endif /* not on windows, nor vfork */
 
-
-SystemExec::SystemExec (std::string c, std::string a)
-       : cmd(c)
+void
+SystemExec::init ()
 {
-       pthread_mutex_init(&write_lock, NULL);
-       thread_active=false;
+       pthread_mutex_init (&write_lock, NULL);
+       thread_active = false;
        pid = 0;
        pin[1] = -1;
        nicelevel = 0;
        envp = NULL;
-       argp = NULL;
 #ifdef PLATFORM_WINDOWS
        stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
        stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
        stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
+       w_args = NULL;
+#elif !defined NO_VFORK
+       argx = NULL;
 #endif
+}
+
+SystemExec::SystemExec (std::string c, std::string a)
+       : cmd(c)
+{
+       init ();
+
+       argp = NULL;
        make_envp();
        make_argp(a);
 }
@@ -174,43 +187,187 @@ SystemExec::SystemExec (std::string c, std::string a)
 SystemExec::SystemExec (std::string c, char **a)
        : cmd(c) , argp(a)
 {
-       pthread_mutex_init(&write_lock, NULL);
-       thread_active=false;
-       pid = 0;
-       pin[1] = -1;
-       nicelevel = 0;
-       envp = NULL;
+       init ();
+
 #ifdef PLATFORM_WINDOWS
-       stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
-       stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
-       stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
        make_wargs(a);
 #endif
        make_envp();
 }
 
+SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
+{
+       init ();
+       make_argp_escaped(command, subs);
+
+#ifdef PLATFORM_WINDOWS
+       if (argp[0] && strlen (argp[0]) > 0) {
+               std::string wa = argp[0];
+               // only add quotes to command if required..
+               if (argp[0][0] != '"'
+                               && argp[0][strlen(argp[0])-1] != '"'
+                               && strchr(argp[0], ' ')) {
+                       wa = "\"";
+                       wa += argp[0];
+                       wa += "\"";
+               }
+               // ...but always quote all args
+               for (int i = 1; argp[i]; ++i) {
+                       std::string tmp (argp[i]);
+                       while (tmp.find("\"") != std::string::npos)
+                               tmp.replace(tmp.find("\""), 1, "\\\"");
+                       wa += " \"";
+                       wa += tmp;
+                       wa += '"';
+               }
+               w_args = strdup(wa.c_str());
+       }
+#else
+       if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
+               // argp[0] exists in $PATH` - set it to the actual path where it was found
+               free (argp[0]);
+               argp[0] = strdup(cmd.c_str ());
+       }
+       // else argp[0] not found in path - leave it as-is, it might be an absolute path
+
+       // Glib::find_program_in_path () is only available in Glib >= 2.28
+       // cmd = Glib::find_program_in_path (argp[0]);
+#endif
+       make_envp();
+}
+
+char*
+SystemExec::format_key_value_parameter (std::string key, std::string value)
+{
+       size_t start_pos = 0;
+       std::string v1 = value;
+       while((start_pos = v1.find_first_not_of(
+                       "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789(),.\"'",
+                       start_pos)) != std::string::npos)
+       {
+               v1.replace(start_pos, 1, "_");
+               start_pos += 1;
+       }
+
+#ifdef PLATFORM_WINDOWS
+       /* SystemExec::make_wargs() adds quotes around the complete argument
+        * windows uses CreateProcess() with a parameter string
+        * (and not an array list of separate arguments like Unix)
+        * so quotes need to be escaped.
+        */
+       start_pos = 0;
+       while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
+               v1.replace(start_pos, 1, "\\\"");
+               start_pos += 2;
+       }
+#endif
+
+       size_t len = key.length() + v1.length() + 2;
+       char *mds = (char*) calloc(len, sizeof(char));
+       snprintf(mds, len, "%s=%s", key.c_str(), v1.c_str());
+       return mds;
+}
+
+void
+SystemExec::make_argp_escaped (std::string command, const std::map<char, std::string> subs)
+{
+
+       int inquotes = 0;
+       int n = 0;
+       size_t i = 0;
+       std::string arg = "";
+
+       argp = (char**) malloc (sizeof(char*));
+
+       for (i = 0; i <= command.length(); i++) { // include terminating '\0'
+               char c = command.c_str()[i];
+               if (inquotes) {
+                       if (c == '"') {
+                               inquotes = 0;
+                       } else {
+                               // still in quotes - just copy
+                               arg += c;
+                       }
+               } else switch (c) {
+                       case '%' :
+                               c = command.c_str()[++i];
+                               if (c == '%' || c == '\0') {
+                                       // "%%", "%" at end-of-string => "%"
+                                       arg += '%';
+                               } else {
+                                       // search subs for string to substitute for char
+                                       std::map<char, std::string>::const_iterator s = subs.find(c);
+                                       if (s != subs.end()) {
+                                               // found substitution
+                                               arg += s->second;
+                                       } else {
+                                               // not a valid substitution, just copy
+                                               arg += '%';
+                                               arg += c;
+                                       }
+                               }
+                               break;
+                       case '\\':
+                               c = command.c_str()[++i];
+                               switch (c) {
+                                       case ' ' :
+                                       case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
+                                       case '\0':
+                                       case '\\': arg += '\\'; break;
+                                       default  : arg += '\\'; arg += c; break;
+                               }
+                               break;
+                       case '"' :
+                               inquotes = 1;
+                               break;
+                       case ' ' :
+                       case '\t':
+                       case '\0':
+                               if (arg.length() > 0) {
+                                       // if there wasn't already a space or tab, start a new parameter
+                                       argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
+                                       argp[n++] = strdup (arg.c_str());
+                                       arg = "";
+                               }
+                               break;
+                       default :
+                               arg += c;
+                               break;
+               }
+       }
+       argp[n] = NULL;
+}
+
 SystemExec::~SystemExec ()
 {
        terminate ();
        if (envp) {
-               for (int i=0;envp[i];++i) {
-                 free(envp[i]);
+               for (int i = 0; envp[i]; ++i) {
+                       free (envp[i]);
                }
                free (envp);
        }
        if (argp) {
-               for (int i=0;argp[i];++i) {
-                 free(argp[i]);
+               for (int i = 0; argp[i]; ++i) {
+                       free (argp[i]);
                }
                free (argp);
        }
 #ifdef PLATFORM_WINDOWS
        if (w_args) free(w_args);
+#elif !defined NO_VFORK
+       if (argx) {
+               /* argx[0 .. 8] are fixed parameters to vfork-exec-wrapper */
+               for (int i = 0; i < 9; ++i) {
+                       free (argx[i]);
+               }
+               free (argx);
+       }
 #endif
        pthread_mutex_destroy(&write_lock);
 }
 
-static void *
+static void*
 interposer_thread (void *arg) {
        SystemExec *sex = static_cast<SystemExec *>(arg);
        sex->output_interposer();
@@ -218,12 +375,40 @@ interposer_thread (void *arg) {
        return 0;
 }
 
+string
+SystemExec::to_s () const
+{
+#ifdef PLATFORM_WINDOWS
+       return string (w_args ? w_args : "");
+#else
+       stringstream out;
+       if (argp) {
+               for (int i = 0; argp[i]; ++i) {
+                       out << argp[i] << " ";
+               }
+       }
+       return out.str();
+#endif
+}
+
+size_t
+SystemExec::write_to_stdin (std::string const& d, size_t len)
+{
+       const char *data = d.c_str();
+       if (len == 0) {
+               len = d.length();
+       }
+       return write_to_stdin ((const void*)data, len);
+}
+
 #ifdef PLATFORM_WINDOWS /* Windows Process */
 
 /* HELPER FUNCTIONS */
 
-static void create_pipe (HANDLE *pipe, bool in) {
-       SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
+static void
+create_pipe (HANDLE *pipe, bool in)
+{
+       SECURITY_ATTRIBUTES secAtt = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
        HANDLE tmpHandle;
        if (in) {
                if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
@@ -235,7 +420,9 @@ static void create_pipe (HANDLE *pipe, bool in) {
        CloseHandle(tmpHandle);
 }
 
-static void destroy_pipe (HANDLE pipe[2]) {
+static void
+destroy_pipe (HANDLE pipe[2])
+{
        if (pipe[0] != INVALID_HANDLE_VALUE) {
                CloseHandle(pipe[0]);
                pipe[0] = INVALID_HANDLE_VALUE;
@@ -246,7 +433,8 @@ static void destroy_pipe (HANDLE pipe[2]) {
        }
 }
 
-static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
+static BOOL
+CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
 {
        DWORD currentProcId = 0;
        GetWindowThreadProcessId(hwnd, &currentProcId);
@@ -258,25 +446,24 @@ static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
 /* PROCESS API */
 
 void
-SystemExec::make_envp() {
-       ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
+SystemExec::make_envp()
+{
+       ; /* environemt is copied over with CreateProcess(...,env=0 ,..) */
 }
 
 void
-SystemExec::make_wargs(char **a) {
+SystemExec::make_wargs (char** a)
+{
        std::string wa = cmd;
        if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
        std::replace(cmd.begin(), cmd.end(), '/', '\\' );
        char **tmp = ++a;
        while (tmp && *tmp) {
                wa.append(" \"");
-               std::string arg(*tmp);
-               size_t start_pos = 0;
-               while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
-                       arg.replace(start_pos, 1, "\\\\");
-                       start_pos += 2;
+               wa.append(*tmp);
+               if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
+                       wa.append("\\");
                }
-               wa.append(arg);
                wa.append("\"");
                tmp++;
        }
@@ -284,7 +471,8 @@ SystemExec::make_wargs(char **a) {
 }
 
 void
-SystemExec::make_argp(std::string args) {
+SystemExec::make_argp (std::string args)
+{
        std::string wa = cmd;
        if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
        std::replace(cmd.begin(), cmd.end(), '/', '\\' );
@@ -323,8 +511,7 @@ int
 SystemExec::wait (int options)
 {
        while (is_running()) {
-               WaitForSingleObject(pid->hProcess, INFINITE);
-               Sleep(20);
+               WaitForSingleObject(pid->hProcess, 40);
        }
        return 0;
 }
@@ -332,11 +519,16 @@ SystemExec::wait (int options)
 bool
 SystemExec::is_running ()
 {
-       return pid?true:false;
+       if (!pid) return false;
+       DWORD exit_code;
+       if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
+               if (exit_code == STILL_ACTIVE) return true;
+       }
+       return false;
 }
 
 int
-SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
+SystemExec::start (StdErrMode stderr_mode, const char * /*vfork_exec_wrapper*/)
 {
        char* working_dir = 0;
 
@@ -348,10 +540,10 @@ SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
        create_pipe(stdinP, true);
        create_pipe(stdoutP, false);
 
-       if (stderr_mode == 2) {
+       if (stderr_mode == MergeWithStdin) {
        /* merge stout & stderr */
                DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
-       } else if (stderr_mode == 1) {
+       } else if (stderr_mode == IgnoreAndClose) {
                //TODO read/flush this pipe or close it...
                create_pipe(stderrP, false);
        } else {
@@ -359,7 +551,7 @@ SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
        }
 
        bool success = false;
-       STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
+       STARTUPINFOA startupInfo = { sizeof(STARTUPINFO), 0, 0, 0,
                (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
                (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
                0, 0, 0,
@@ -399,7 +591,7 @@ SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
                return -1;
        }
 
-       int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
+       int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
        thread_active=true;
        if (rv) {
                thread_active=false;
@@ -426,42 +618,38 @@ SystemExec::output_interposer()
                if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
 #endif
                if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
-               if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
+               if (!ReadFile(stdoutP[0], data, BUFSIZ - 1, &bytesRead, 0)) {
                        DWORD err =  GetLastError();
                        if (err == ERROR_IO_PENDING) continue;
                        break;
                }
                if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
                data[bytesRead] = 0;
-               ReadStdout(data, bytesRead);/* EMIT SIGNAL */
+               ReadStdout(data, bytesRead); /* EMIT SIGNAL */
        }
-       Terminated();/* EMIT SIGNAL */
+       Terminated(); /* EMIT SIGNAL */
+       pthread_exit(0);
 }
 
 void
 SystemExec::close_stdin()
 {
-       if (stdinP[0]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[0]);
-       if (stdinP[1]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[1]);
+       if (stdinP[0] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[0]);
+       if (stdinP[1] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[1]);
        Sleep(200);
-       destroy_pipe(stdinP);
+       destroy_pipe (stdinP);
 }
 
-int
-SystemExec::write_to_stdin(std::string d, size_t len)
+size_t
+SystemExec::write_to_stdin (const void* data, size_t bytes)
 {
-       const char *data;
-       DWORD r,c;
+       DWORD r, c;
 
-       ::pthread_mutex_lock(&write_lock);
+       ::pthread_mutex_lock (&write_lock);
 
-       data=d.c_str();
-       if (len == 0) {
-               len=(d.length());
-       }
        c=0;
-       while (c < len) {
-               if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
+       while (c < bytes) {
+               if (!WriteFile (stdinP[1], &((const char*)data)[c], bytes - c, &r, NULL)) {
                        if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
                                Sleep(100);
                                continue;
@@ -482,12 +670,14 @@ SystemExec::write_to_stdin(std::string d, size_t len)
 /* UNIX/POSIX process */
 
 extern char **environ;
+
 void
-SystemExec::make_envp() {
-       int i=0;
+SystemExec::make_envp()
+{
+       int i = 0;
        envp = (char **) calloc(1, sizeof(char*));
        /* copy current environment */
-       for (i=0;environ[i];++i) {
+       for (i = 0; environ[i]; ++i) {
          envp[i] = strdup(environ[i]);
          envp = (char **) realloc(envp, (i+2) * sizeof(char*));
        }
@@ -495,7 +685,8 @@ SystemExec::make_envp() {
 }
 
 void
-SystemExec::make_argp(std::string args) {
+SystemExec::make_argp(std::string args)
+{
        int argn = 1;
        char *cp1;
        char *cp2;
@@ -522,7 +713,7 @@ SystemExec::make_argp(std::string args) {
                        *cp2 = '\0';
                        argp[argn++] = strdup(cp1);
                        cp1 = cp2 + 1;
-           argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
+                       argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
                }
        }
        if (cp2 != cp1) {
@@ -533,8 +724,6 @@ SystemExec::make_argp(std::string args) {
        free(carg);
 }
 
-
-
 void
 SystemExec::terminate ()
 {
@@ -546,7 +735,7 @@ SystemExec::terminate ()
        close_stdin();
 
        if (pid) {
-               ::usleep(50000);
+               ::usleep(200000);
                sched_yield();
                wait(WNOHANG);
        }
@@ -554,10 +743,10 @@ SystemExec::terminate ()
        /* if pid is non-zero, the child task is still executing (i.e. it did
         * not exit in response to stdin being closed). try to kill it.
         */
-       
+
        if (pid) {
                ::kill(pid, SIGTERM);
-               usleep(50000);
+               ::usleep(250000);
                sched_yield();
                wait(WNOHANG);
        }
@@ -574,16 +763,17 @@ SystemExec::terminate ()
        wait();
        if (thread_active) pthread_join(thread_id_tt, NULL);
        thread_active = false;
+       assert(pid == 0);
        ::pthread_mutex_unlock(&write_lock);
 }
 
 int
 SystemExec::wait (int options)
 {
-       int status=0;
+       int status = 0;
        int ret;
 
-       if (pid==0) return -1;
+       if (pid == 0) return -1;
 
        ret = waitpid (pid, &status, options);
 
@@ -605,18 +795,23 @@ SystemExec::wait (int options)
 bool
 SystemExec::is_running ()
 {
-       int status=0;
-       if (pid==0) return false;
-       if (::waitpid(pid, &status, WNOHANG)==0) return true;
+       int status = 0;
+       if (pid == 0) {
+               return false;
+       }
+       if (::waitpid (pid, &status, WNOHANG)==0) {
+               return true;
+       }
        return false;
 }
 
 int
-SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
+SystemExec::start (StdErrMode stderr_mode, const char *vfork_exec_wrapper)
 {
-       if (is_running()) {
-               return 0; // mmh what to return here?
+       if (is_running ()) {
+               return 0;
        }
+
        int r;
 
        if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
@@ -636,37 +831,40 @@ SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
 
        if (r > 0) {
                /* main */
-               pid=r;
+               pid = r;
 
                /* check if execve was successful. */
-               close_fd(pok[1]);
+               close_fd (pok[1]);
                char buf;
-               for ( ;; ) {
-                       ssize_t n = ::read(pok[0], &buf, 1 );
-                       if ( n==1 ) {
+               for (;;) {
+                       ssize_t n = ::read (pok[0], &buf, 1);
+                       if (n == 1) {
                                /* child process returned from execve */
                                pid=0;
-                               close_fd(pok[0]);
-                               close_fd(pok[1]);
-                               close_fd(pin[1]);
-                               close_fd(pin[0]);
-                               close_fd(pout[1]);
-                               close_fd(pout[0]);
+                               close_fd (pok[0]);
+                               close_fd (pok[1]);
+                               close_fd (pin[1]);
+                               close_fd (pin[0]);
+                               close_fd (pout[1]);
+                               close_fd (pout[0]);
                                return -3;
-                       } else if ( n==-1 ) {
-                                if ( errno==EAGAIN || errno==EINTR )
-                                        continue;
+                       } else if (n == -1) {
+                               if (errno==EAGAIN || errno==EINTR) {
+                                       continue;
+                               }
                        }
                        break;
                }
-               close_fd(pok[0]);
+
+               close_fd (pok[0]);
                /* child started successfully */
 
-               close_fd(pout[1]);
-               close_fd(pin[0]);
-               int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
+               close_fd (pout[1]);
+               close_fd (pin[0]);
 
+               int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
                thread_active=true;
+
                if (rv) {
                        thread_active=false;
                        terminate();
@@ -677,29 +875,33 @@ SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
 
 #ifdef NO_VFORK
        /* child process - exec external process */
-       close_fd(pok[0]);
-       ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
+       close_fd (pok[0]);
+       ::fcntl (pok[1], F_SETFD, FD_CLOEXEC);
 
-       close_fd(pin[1]);
+       close_fd (pin[1]);
        if (pin[0] != STDIN_FILENO) {
-         ::dup2(pin[0], STDIN_FILENO);
+         ::dup2 (pin[0], STDIN_FILENO);
        }
-       close_fd(pin[0]);
-       close_fd(pout[0]);
+       close_fd (pin[0]);
+       close_fd (pout[0]);
        if (pout[1] != STDOUT_FILENO) {
-               ::dup2(pout[1], STDOUT_FILENO);
+               ::dup2 (pout[1], STDOUT_FILENO);
        }
 
-       if (stderr_mode == 2) {
+       if (stderr_mode == MergeWithStdin) {
                /* merge STDERR into output */
                if (pout[1] != STDERR_FILENO) {
                        ::dup2(pout[1], STDERR_FILENO);
                }
-       } else if (stderr_mode == 1) {
+       } else if (stderr_mode == IgnoreAndClose) {
                /* ignore STDERR */
                ::close(STDERR_FILENO);
-       } else {
+       } else { /* stderr_mode == ShareWithParent */
                /* keep STDERR */
+#if defined __APPLE__&& defined ASL_LOG_DESCRIPTOR_WRITE
+               ::close(STDERR_FILENO);
+               stderr_mode = IgnoreAndClose; // for vfork
+#endif
        }
 
        if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
@@ -711,116 +913,123 @@ SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
        }
 
 #ifdef HAVE_SIGSET
-       sigset(SIGPIPE, SIG_DFL);
+       sigset (SIGPIPE, SIG_DFL);
 #else
-       signal(SIGPIPE, SIG_DFL);
+       signal (SIGPIPE, SIG_DFL);
 #endif
+       if (!vfork_exec_wrapper) {
+               error << _("Cannot start external process, no vfork wrapper") << endmsg;
+               return -1;
+       }
 
        int good_fds[2] = { pok[1],  -1 };
        close_allv(good_fds);
 
        ::execve(argp[0], argp, envp);
-       /* if we reach here something went wrong.. */
-       char buf = 0;
-       (void) ::write(pok[1], &buf, 1 );
-       close_fd(pok[1]);
-       exit(-1);
-       return -1;
-#else
+
+#else /* ! NO_VFORK */
 
        /* XXX this should be done before vfork()
         * calling malloc here only increases the time vfork() blocks
         */
        int argn = 0;
-       for (int i=0;argp[i];++i) { argn++; }
-       char **argx = (char **) malloc((argn + 10) * sizeof(char *));
-       argx[0] = strdup(vfork_exec_wrapper); // XXX
+       for (int i = 0; argp[i]; ++i) { argn++; }
+
+       argx = (char **) malloc ((argn + 10) * sizeof(char*));
+       argx[0] = strdup (vfork_exec_wrapper);
 
 #define FDARG(NUM, FDN) \
        argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
 
-       FDARG(1, pok[0])
-       FDARG(2, pok[1])
-       FDARG(3, pin[0])
-       FDARG(4, pin[1])
-       FDARG(5, pout[0])
-       FDARG(6, pout[1])
-       FDARG(7, stderr_mode)
-       FDARG(8, nicelevel)
+       FDARG (1, pok[0])
+       FDARG (2, pok[1])
+       FDARG (3, pin[0])
+       FDARG (4, pin[1])
+       FDARG (5, pout[0])
+       FDARG (6, pout[1])
+       FDARG (7, stderr_mode)
+       FDARG (8, nicelevel)
 
-       for (int i=0;argp[i];++i) {
+       for (int i = 0; argp[i]; ++i) {
                argx[9+i] = argp[i];
        }
        argx[argn+9] = NULL;
 
-       ::execve(argx[0], argx, envp);
+       ::execve (argx[0], argx, envp);
+#endif
 
        /* if we reach here something went wrong.. */
        char buf = 0;
-       (void) ::write(pok[1], &buf, 1 );
-       close_fd(pok[1]);
-       exit(-1);
+       (void) ::write (pok[1], &buf, 1);
+       close_fd (pok[1]);
+       exit (-1);
        return -1;
-#endif
 }
 
 void
-SystemExec::output_interposer()
+SystemExec::output_interposer ()
 {
-       int rfd=pout[0];
+       int rfd = pout[0];
        char buf[BUFSIZ];
        ssize_t r;
        unsigned long l = 1;
 
-       ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
+       ioctl (rfd, FIONBIO, &l); // set non-blocking I/O
 
-       for (;fcntl(rfd, F_GETFL)!=-1;) {
-               r = read(rfd, buf, sizeof(buf));
+       for (;fcntl (rfd, F_GETFL) != -1;) {
+               r = read (rfd, buf, BUFSIZ - 1);
                if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
-                       ::usleep(1000);
+                       fd_set rfds;
+                       struct timeval tv;
+                       FD_ZERO (&rfds);
+                       FD_SET (rfd, &rfds);
+                       tv.tv_sec = 0;
+                       tv.tv_usec = 10000;
+                       int rv = select (1, &rfds, NULL, NULL, &tv);
+                       if (rv == -1) {
+                               break;
+                       }
                        continue;
                }
                if (r <= 0) {
                        break;
                }
                buf[r]=0;
-               std::string rv = std::string(buf,r); // TODO: check allocation strategy
-               ReadStdout(rv, r);/* EMIT SIGNAL */
+               std::string rv = std::string (buf, r);
+               ReadStdout (rv, r); /* EMIT SIGNAL */
        }
-       Terminated();/* EMIT SIGNAL */
+       Terminated (); /* EMIT SIGNAL */
+       pthread_exit (0);
 }
 
 void
 SystemExec::close_stdin()
 {
-       if (pin[1]<0) return;
-       close_fd(pin[0]);
-       close_fd(pin[1]);
-       close_fd(pout[0]);
-       close_fd(pout[1]);
+       if (pin[1] < 0) {
+               return;
+       }
+       close_fd (pin[0]);
+       close_fd (pin[1]);
+       close_fd (pout[0]);
+       close_fd (pout[1]);
 }
 
-int
-SystemExec::write_to_stdin(std::string d, size_t len)
+size_t
+SystemExec::write_to_stdin (const void* data, size_t bytes)
 {
-       const char *data;
        ssize_t r;
        size_t c;
-       ::pthread_mutex_lock(&write_lock);
+       ::pthread_mutex_lock (&write_lock);
 
-       data=d.c_str();
-       if (len == 0) {
-               len=(d.length());
-       }
-       c=0;
-       while (c < len) {
+       c = 0;
+       while (c < bytes) {
                for (;;) {
-                       r=::write(pin[1], data+c, len-c);
+                       r = ::write (pin[1], &((const char*)data)[c], bytes - c);
                        if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
                                sleep(1);
                                continue;
                        }
-                       if ((size_t) r != (len-c)) {
+                       if ((size_t) r != (bytes-c)) {
                                ::pthread_mutex_unlock(&write_lock);
                                return c;
                        }
@@ -828,7 +1037,7 @@ SystemExec::write_to_stdin(std::string d, size_t len)
                }
                c += r;
        }
-       fsync(pin[1]);
+       fsync (pin[1]);
        ::pthread_mutex_unlock(&write_lock);
        return c;
 }