merge with master and fix 4 conflicts by hand
[ardour.git] / libs / pbd / system_exec.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Copyright (C) 2010-2014 Robin Gareus <robin@gareus.org>
4     Copyright (C) 2005-2008 Lennart Poettering
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <algorithm>
27
28 #include <assert.h>
29
30 #ifndef COMPILER_MSVC
31 #include <dirent.h>
32 #endif
33
34 #ifdef PLATFORM_WINDOWS
35 #include <windows.h>
36 #else
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/socket.h>
41 #include <sys/ioctl.h>
42 #include <sys/time.h>
43 #include <sys/resource.h>
44 #endif
45
46
47 #define USE_VFORK
48
49 #include "pbd/system_exec.h"
50
51 using namespace std;
52 using namespace PBD;
53
54 static void * interposer_thread (void *arg);
55 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
56
57 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
58 /*
59  * This function was part of libasyncns.
60  * LGPL v2.1
61  * Copyright 2005-2008 Lennart Poettering
62  */
63 static int close_allv(const int except_fds[]) {
64         struct rlimit rl;
65         int fd;
66
67 #ifdef __linux__
68
69         DIR *d;
70
71         assert(except_fds);
72
73         if ((d = opendir("/proc/self/fd"))) {
74                 struct dirent *de;
75
76                 while ((de = readdir(d))) {
77                         int found;
78                         long l;
79                         char *e = NULL;
80                         int i;
81
82                         if (de->d_name[0] == '.')
83                                         continue;
84
85                         errno = 0;
86                         l = strtol(de->d_name, &e, 10);
87                         if (errno != 0 || !e || *e) {
88                                 closedir(d);
89                                 errno = EINVAL;
90                                 return -1;
91                         }
92
93                         fd = (int) l;
94
95                         if ((long) fd != l) {
96                                 closedir(d);
97                                 errno = EINVAL;
98                                 return -1;
99                         }
100
101                         if (fd < 3)
102                                 continue;
103
104                         if (fd == dirfd(d))
105                                 continue;
106
107                         found = 0;
108                         for (i = 0; except_fds[i] >= 0; i++)
109                                 if (except_fds[i] == fd) {
110                                                 found = 1;
111                                                 break;
112                                 }
113
114                         if (found) continue;
115
116                         if (close(fd) < 0) {
117                                 int saved_errno;
118
119                                 saved_errno = errno;
120                                 closedir(d);
121                                 errno = saved_errno;
122
123                                 return -1;
124                         }
125                 }
126
127                 closedir(d);
128                 return 0;
129         }
130
131 #endif
132
133         if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
134                 return -1;
135
136         for (fd = 0; fd < (int) rl.rlim_max; fd++) {
137                 int i;
138
139                 if (fd <= 3)
140                                 continue;
141
142                 for (i = 0; except_fds[i] >= 0; i++)
143                         if (except_fds[i] == fd)
144                                 continue;
145
146                 if (close(fd) < 0 && errno != EBADF)
147                         return -1;
148         }
149
150         return 0;
151 }
152 #endif /* not on windows, nor vfork */
153
154 void
155 SystemExec::init ()
156 {
157         pthread_mutex_init(&write_lock, NULL);
158         thread_active=false;
159         pid = 0;
160         pin[1] = -1;
161         nicelevel = 0;
162         envp = NULL;
163 #ifdef PLATFORM_WINDOWS
164         stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
165         stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
166         stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
167 #endif
168 }
169
170 SystemExec::SystemExec (std::string c, std::string a)
171         : cmd(c)
172 {
173         init ();
174
175         argp = NULL;
176         make_envp();
177         make_argp(a);
178 }
179
180 SystemExec::SystemExec (std::string c, char **a)
181         : cmd(c) , argp(a)
182 {
183         init ();
184
185 #ifdef PLATFORM_WINDOWS
186         make_wargs(a);
187 #endif
188         make_envp();
189 }
190
191 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
192 {
193         init ();
194         make_argp_escaped(command, subs);
195         cmd = argp[0];
196         // cmd = strdup(argp[0]);
197         make_envp();
198 }
199
200 void
201 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
202 {
203
204         int inquotes = 0;
205         int n = 0;
206         size_t i = 0;
207         std::string arg = "";
208
209         argp = (char **) malloc(sizeof(char *));
210
211         for (i = 0; i <= command.length(); i++) { // include terminating '\0'
212                 char c = command.c_str()[i];
213                 if (inquotes) {
214                         if (c == '"') {
215                                 inquotes = 0;
216                         } else {
217                                 // still in quotes - just copy
218                                 arg += c;
219                         }
220                 } else switch (c) {
221                         case '%' :
222                                 c = command.c_str()[++i];
223                                 if (c == '%' || c == '\0') {
224                                         // "%%", "%" at end-of-string => "%"
225                                         arg += '%';
226                                 } else {
227                                         // search subs for string to substitute for char
228                                         std::map<char, std::string>::const_iterator s = subs.find(c);
229                                         if (s != subs.end()) {
230                                                 // found substitution
231                                                 arg += s->second;
232                                         } else {
233                                                 // not a valid substitution, just copy
234                                                 arg += '%';
235                                                 arg += c;
236                                         }
237                                 }
238                                 break;
239                         case '\\':
240                                 c = command.c_str()[++i];
241                                 switch (c) {
242                                         case ' ' :
243                                         case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
244                                         case '\0': 
245                                         case '\\': arg += '\\'; break;
246                                         default  : arg += '\\'; arg += c; break;
247                                 }
248                                 break;
249                         case '"' :
250                                 inquotes = 1;
251                                 break;
252                         case ' ' :
253                         case '\t':
254                         case '\0':
255                                 if (arg.length() > 0) {
256                                         // if there wasn't already a space or tab, start a new parameter
257                                         argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
258                                         argp[n++] = strdup (arg.c_str());
259                                         arg = "";
260                                 }
261                                 break;
262                         default :
263                                 arg += c;
264                                 break;
265                 }
266         }
267         argp[n] = NULL;
268
269         char *p = argp[0];
270         n = 0;
271 }
272
273 SystemExec::~SystemExec ()
274 {
275         terminate ();
276         if (envp) {
277                 for (int i=0;envp[i];++i) {
278                   free(envp[i]);
279                 }
280                 free (envp);
281         }
282         if (argp) {
283                 for (int i=0;argp[i];++i) {
284                   free(argp[i]);
285                 }
286                 free (argp);
287         }
288 #ifdef PLATFORM_WINDOWS
289         if (w_args) free(w_args);
290 #endif
291         pthread_mutex_destroy(&write_lock);
292 }
293
294 static void *
295 interposer_thread (void *arg) {
296         SystemExec *sex = static_cast<SystemExec *>(arg);
297         sex->output_interposer();
298         pthread_exit(0);
299         return 0;
300 }
301
302 #ifdef PLATFORM_WINDOWS /* Windows Process */
303
304 /* HELPER FUNCTIONS */
305
306 static void create_pipe (HANDLE *pipe, bool in) {
307         SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
308         HANDLE tmpHandle;
309         if (in) {
310                 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
311                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
312         } else {
313                 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
314                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
315         }
316         CloseHandle(tmpHandle);
317 }
318
319 static void destroy_pipe (HANDLE pipe[2]) {
320         if (pipe[0] != INVALID_HANDLE_VALUE) {
321                 CloseHandle(pipe[0]);
322                 pipe[0] = INVALID_HANDLE_VALUE;
323         }
324         if (pipe[1] != INVALID_HANDLE_VALUE) {
325                 CloseHandle(pipe[1]);
326                 pipe[1] = INVALID_HANDLE_VALUE;
327         }
328 }
329
330 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
331 {
332         DWORD currentProcId = 0;
333         GetWindowThreadProcessId(hwnd, &currentProcId);
334         if (currentProcId == (DWORD)procId)
335                 PostMessage(hwnd, WM_CLOSE, 0, 0);
336         return TRUE;
337 }
338
339 /* PROCESS API */
340
341 void
342 SystemExec::make_envp() {
343         ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
344 }
345
346 void
347 SystemExec::make_wargs(char **a) {
348         std::string wa = cmd;
349         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
350         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
351         char **tmp = ++a;
352         while (tmp && *tmp) {
353                 wa.append(" \"");
354                 std::string arg(*tmp);
355                 size_t start_pos = 0;
356                 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
357                         arg.replace(start_pos, 1, "\\\\");
358                         start_pos += 2;
359                 }
360                 wa.append(arg);
361                 wa.append("\"");
362                 tmp++;
363         }
364         w_args = strdup(wa.c_str());
365 }
366
367 void
368 SystemExec::make_argp(std::string args) {
369         std::string wa = cmd;
370         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
371         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
372         wa.append(" ");
373         wa.append(args);
374         w_args = strdup(wa.c_str());
375 }
376
377 void
378 SystemExec::terminate ()
379 {
380         ::pthread_mutex_lock(&write_lock);
381
382         close_stdin();
383
384         if (pid) {
385                 /* terminate */
386                 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
387                 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
388
389                 /* kill ! */
390                 TerminateProcess(pid->hProcess, 0xf291);
391
392                 CloseHandle(pid->hThread);
393                 CloseHandle(pid->hProcess);
394                 destroy_pipe(stdinP);
395                 destroy_pipe(stdoutP);
396                 destroy_pipe(stderrP);
397                 delete pid;
398                 pid=0;
399         }
400         ::pthread_mutex_unlock(&write_lock);
401 }
402
403 int
404 SystemExec::wait (int options)
405 {
406         while (is_running()) {
407                 WaitForSingleObject(pid->hProcess, INFINITE);
408                 Sleep(20);
409         }
410         return 0;
411 }
412
413 bool
414 SystemExec::is_running ()
415 {
416         return pid?true:false;
417 }
418
419 int
420 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
421 {
422         char* working_dir = 0;
423
424         if (pid) { return 0; }
425
426         pid = new PROCESS_INFORMATION;
427         memset(pid, 0, sizeof(PROCESS_INFORMATION));
428
429         create_pipe(stdinP, true);
430         create_pipe(stdoutP, false);
431
432         if (stderr_mode == 2) {
433         /* merge stout & stderr */
434                 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
435         } else if (stderr_mode == 1) {
436                 //TODO read/flush this pipe or close it...
437                 create_pipe(stderrP, false);
438         } else {
439                 //TODO: keep stderr of this process mode.
440         }
441
442         bool success = false;
443         STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
444                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
445                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
446                 0, 0, 0,
447                 STARTF_USESTDHANDLES,
448                 0, 0, 0,
449                 stdinP[0], stdoutP[1], stderrP[1]
450         };
451
452         success = CreateProcess(0, w_args,
453                 0, 0, /* bInheritHandles = */ TRUE,
454                 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
455                 /*env = */ 0,
456                 working_dir,
457                 &startupInfo, pid);
458
459         if (stdinP[0] != INVALID_HANDLE_VALUE) {
460                 CloseHandle(stdinP[0]);
461                 stdinP[0] = INVALID_HANDLE_VALUE;
462         }
463         if (stdoutP[1] != INVALID_HANDLE_VALUE) {
464                 CloseHandle(stdoutP[1]);
465                 stdoutP[1] = INVALID_HANDLE_VALUE;
466         }
467         if (stderrP[1] != INVALID_HANDLE_VALUE) {
468                 CloseHandle(stderrP[1]);
469                 stderrP[1] = INVALID_HANDLE_VALUE;
470         }
471
472         if (!success) {
473                 CloseHandle(pid->hThread);
474                 CloseHandle(pid->hProcess);
475                 destroy_pipe(stdinP);
476                 destroy_pipe(stdoutP);
477                 destroy_pipe(stderrP);
478                 delete pid;
479                 pid=0;
480                 return -1;
481         }
482
483         int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
484         thread_active=true;
485         if (rv) {
486                 thread_active=false;
487                 terminate();
488                 return -2;
489         }
490         Sleep(20);
491         return 0;
492 }
493
494 void
495 SystemExec::output_interposer()
496 {
497         DWORD bytesRead = 0;
498         char data[BUFSIZ];
499 #if 0 // untested code to set up nonblocking
500         unsigned long l = 1;
501         ioctlsocket(stdoutP[0], FIONBIO, &l);
502 #endif
503         while(1) {
504 #if 0 // for non-blocking pipes..
505                 DWORD bytesAvail = 0;
506                 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
507                 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
508 #endif
509                 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
510                 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
511                         DWORD err =  GetLastError();
512                         if (err == ERROR_IO_PENDING) continue;
513                         break;
514                 }
515                 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
516                 data[bytesRead] = 0;
517                 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
518         }
519         Terminated();/* EMIT SIGNAL */
520 }
521
522 void
523 SystemExec::close_stdin()
524 {
525         if (stdinP[0]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[0]);
526         if (stdinP[1]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[1]);
527         Sleep(200);
528         destroy_pipe(stdinP);
529 }
530
531 int
532 SystemExec::write_to_stdin(std::string d, size_t len)
533 {
534         const char *data;
535         DWORD r,c;
536
537         ::pthread_mutex_lock(&write_lock);
538
539         data=d.c_str();
540         if (len == 0) {
541                 len=(d.length());
542         }
543         c=0;
544         while (c < len) {
545                 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
546                         if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
547                                 Sleep(100);
548                                 continue;
549                         } else {
550                                 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
551                                 break;
552                         }
553                 }
554                 c += r;
555         }
556         ::pthread_mutex_unlock(&write_lock);
557         return c;
558 }
559
560
561 /* end windows process */
562 #else
563 /* UNIX/POSIX process */
564
565 extern char **environ;
566 void
567 SystemExec::make_envp() {
568         int i=0;
569         envp = (char **) calloc(1, sizeof(char*));
570         /* copy current environment */
571         for (i=0;environ[i];++i) {
572           envp[i] = strdup(environ[i]);
573           envp = (char **) realloc(envp, (i+2) * sizeof(char*));
574         }
575         envp[i] = 0;
576 }
577
578 void
579 SystemExec::make_argp(std::string args) {
580         int argn = 1;
581         char *cp1;
582         char *cp2;
583
584         char *carg = strdup(args.c_str());
585
586         argp = (char **) malloc((argn + 1) * sizeof(char *));
587         if (argp == (char **) 0) {
588                 free(carg);
589                 return; // FATAL
590         }
591
592         argp[0] = strdup(cmd.c_str());
593
594         /* TODO: quotations and escapes
595          * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
596          *
597          * It's actually not needed. All relevant invocations specify 'argp' directly.
598          * Only 'xjadeo -L -R' uses this function and that uses neither quotations
599          * nor arguments with white-space.
600          */
601         for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
602                 if (*cp2 == ' ') {
603                         *cp2 = '\0';
604                         argp[argn++] = strdup(cp1);
605                         cp1 = cp2 + 1;
606                         argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
607                 }
608         }
609         if (cp2 != cp1) {
610                 argp[argn++] = strdup(cp1);
611                 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
612         }
613         argp[argn] = (char *) 0;
614         free(carg);
615 }
616
617
618
619 void
620 SystemExec::terminate ()
621 {
622         ::pthread_mutex_lock(&write_lock);
623
624         /* close stdin in an attempt to get the child to exit cleanly.
625          */
626
627         close_stdin();
628
629         if (pid) {
630                 ::usleep(50000);
631                 sched_yield();
632                 wait(WNOHANG);
633         }
634
635         /* if pid is non-zero, the child task is still executing (i.e. it did
636          * not exit in response to stdin being closed). try to kill it.
637          */
638         
639         if (pid) {
640                 ::kill(pid, SIGTERM);
641                 usleep(50000);
642                 sched_yield();
643                 wait(WNOHANG);
644         }
645
646         /* if pid is non-zero, the child task is STILL executing after being
647          * sent SIGTERM. Act tough ... send SIGKILL
648          */
649
650         if (pid) {
651                 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
652                 ::kill(pid, SIGKILL);
653         }
654
655         wait();
656         if (thread_active) pthread_join(thread_id_tt, NULL);
657         thread_active = false;
658         ::pthread_mutex_unlock(&write_lock);
659 }
660
661 int
662 SystemExec::wait (int options)
663 {
664         int status=0;
665         int ret;
666
667         if (pid==0) return -1;
668
669         ret = waitpid (pid, &status, options);
670
671         if (ret == pid) {
672                 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
673                         pid=0;
674                 }
675         } else {
676                 if (ret != 0) {
677                         if (errno == ECHILD) {
678                                 /* no currently running children, reset pid */
679                                 pid=0;
680                         }
681                 } /* else the process is still running */
682         }
683         return status;
684 }
685
686 bool
687 SystemExec::is_running ()
688 {
689         int status=0;
690         if (pid==0) return false;
691         if (::waitpid(pid, &status, WNOHANG)==0) return true;
692         return false;
693 }
694
695 int
696 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
697 {
698         if (is_running()) {
699                 return 0; // mmh what to return here?
700         }
701         int r;
702
703         if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
704                 /* Something unexpected went wrong creating a pipe. */
705                 return -1;
706         }
707
708 #ifndef NO_VFORK
709         r = ::vfork();
710 #else
711         r = ::fork();
712 #endif
713         if (r < 0) {
714                 /* failed to fork */
715                 return -2;
716         }
717
718         if (r > 0) {
719                 /* main */
720                 pid=r;
721
722                 /* check if execve was successful. */
723                 close_fd(pok[1]);
724                 char buf;
725                 for ( ;; ) {
726                         ssize_t n = ::read(pok[0], &buf, 1 );
727                         if ( n==1 ) {
728                                 /* child process returned from execve */
729                                 pid=0;
730                                 close_fd(pok[0]);
731                                 close_fd(pok[1]);
732                                 close_fd(pin[1]);
733                                 close_fd(pin[0]);
734                                 close_fd(pout[1]);
735                                 close_fd(pout[0]);
736                                 return -3;
737                         } else if ( n==-1 ) {
738                                  if ( errno==EAGAIN || errno==EINTR )
739                                          continue;
740                         }
741                         break;
742                 }
743                 close_fd(pok[0]);
744                 /* child started successfully */
745
746                 close_fd(pout[1]);
747                 close_fd(pin[0]);
748                 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
749
750                 thread_active=true;
751                 if (rv) {
752                         thread_active=false;
753                         terminate();
754                         return -2;
755                 }
756                 return 0; /* all systems go - return to main */
757         }
758
759 #ifdef NO_VFORK
760         /* child process - exec external process */
761         close_fd(pok[0]);
762         ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
763
764         close_fd(pin[1]);
765         if (pin[0] != STDIN_FILENO) {
766           ::dup2(pin[0], STDIN_FILENO);
767         }
768         close_fd(pin[0]);
769         close_fd(pout[0]);
770         if (pout[1] != STDOUT_FILENO) {
771                 ::dup2(pout[1], STDOUT_FILENO);
772         }
773
774         if (stderr_mode == 2) {
775                 /* merge STDERR into output */
776                 if (pout[1] != STDERR_FILENO) {
777                         ::dup2(pout[1], STDERR_FILENO);
778                 }
779         } else if (stderr_mode == 1) {
780                 /* ignore STDERR */
781                 ::close(STDERR_FILENO);
782         } else {
783                 /* keep STDERR */
784         }
785
786         if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
787                 close_fd(pout[1]);
788         }
789
790         if (nicelevel !=0) {
791                 ::nice(nicelevel);
792         }
793
794 #ifdef HAVE_SIGSET
795         sigset(SIGPIPE, SIG_DFL);
796 #else
797         signal(SIGPIPE, SIG_DFL);
798 #endif
799
800         int good_fds[2] = { pok[1],  -1 };
801         close_allv(good_fds);
802
803         ::execve(argp[0], argp, envp);
804         /* if we reach here something went wrong.. */
805         char buf = 0;
806         (void) ::write(pok[1], &buf, 1 );
807         close_fd(pok[1]);
808         exit(-1);
809         return -1;
810 #else
811
812         /* XXX this should be done before vfork()
813          * calling malloc here only increases the time vfork() blocks
814          */
815         int argn = 0;
816         for (int i=0;argp[i];++i) { argn++; }
817         char **argx = (char **) malloc((argn + 10) * sizeof(char *));
818         argx[0] = strdup(vfork_exec_wrapper); // XXX
819
820 #define FDARG(NUM, FDN) \
821         argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
822
823         FDARG(1, pok[0])
824         FDARG(2, pok[1])
825         FDARG(3, pin[0])
826         FDARG(4, pin[1])
827         FDARG(5, pout[0])
828         FDARG(6, pout[1])
829         FDARG(7, stderr_mode)
830         FDARG(8, nicelevel)
831
832         for (int i=0;argp[i];++i) {
833                 argx[9+i] = argp[i];
834         }
835         argx[argn+9] = NULL;
836
837         ::execve(argx[0], argx, envp);
838
839         /* if we reach here something went wrong.. */
840         char buf = 0;
841         (void) ::write(pok[1], &buf, 1 );
842         close_fd(pok[1]);
843         exit(-1);
844         return -1;
845 #endif
846 }
847
848 void
849 SystemExec::output_interposer()
850 {
851         int rfd=pout[0];
852         char buf[BUFSIZ];
853         ssize_t r;
854         unsigned long l = 1;
855
856         ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
857
858         for (;fcntl(rfd, F_GETFL)!=-1;) {
859                 r = read(rfd, buf, sizeof(buf));
860                 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
861                         ::usleep(1000);
862                         continue;
863                 }
864                 if (r <= 0) {
865                         break;
866                 }
867                 buf[r]=0;
868                 std::string rv = std::string(buf,r); // TODO: check allocation strategy
869                 ReadStdout(rv, r);/* EMIT SIGNAL */
870         }
871         Terminated();/* EMIT SIGNAL */
872 }
873
874 void
875 SystemExec::close_stdin()
876 {
877         if (pin[1]<0) return;
878         close_fd(pin[0]);
879         close_fd(pin[1]);
880         close_fd(pout[0]);
881         close_fd(pout[1]);
882 }
883
884 int
885 SystemExec::write_to_stdin(std::string d, size_t len)
886 {
887         const char *data;
888         ssize_t r;
889         size_t c;
890         ::pthread_mutex_lock(&write_lock);
891
892         data=d.c_str();
893         if (len == 0) {
894                 len=(d.length());
895         }
896         c=0;
897         while (c < len) {
898                 for (;;) {
899                         r=::write(pin[1], data+c, len-c);
900                         if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
901                                 sleep(1);
902                                 continue;
903                         }
904                         if ((size_t) r != (len-c)) {
905                                 ::pthread_mutex_unlock(&write_lock);
906                                 return c;
907                         }
908                         break;
909                 }
910                 c += r;
911         }
912         fsync(pin[1]);
913         ::pthread_mutex_unlock(&write_lock);
914         return c;
915 }
916
917 #endif // end UNIX process