[project @ 2005-07-22 10:18:51 by simonmar]
[haskell-directory.git] / cbits / runProcess.c
1 /* ----------------------------------------------------------------------------
2    (c) The University of Glasgow 2004
3    
4    Support for System.Process
5    ------------------------------------------------------------------------- */
6
7 #include "HsBase.h"
8
9 #if defined(mingw32_HOST_OS)
10 #include <windows.h>
11 #include <stdlib.h>
12 #endif
13
14 #ifdef HAVE_VFORK_H
15 #include <vfork.h>
16 #endif
17
18 #ifdef HAVE_VFORK
19 #define fork vfork
20 #endif
21
22 #ifdef HAVE_SIGNAL_H
23 #include <signal.h>
24 #endif
25
26 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
27 /* ----------------------------------------------------------------------------
28    UNIX versions
29    ------------------------------------------------------------------------- */
30
31 ProcHandle
32 runProcess (char *const args[], char *workingDirectory, char **environment, 
33             int fdStdInput, int fdStdOutput, int fdStdError,
34             int set_inthandler, long inthandler, 
35             int set_quithandler, long quithandler)
36 {
37     int pid;
38     struct sigaction dfl;
39
40     switch(pid = fork())
41     {
42     case -1:
43         return -1;
44         
45     case 0:
46     {
47         pPrPr_disableITimers();
48         
49         if (workingDirectory) {
50             if (chdir (workingDirectory) < 0) {
51                 return -1;
52             }
53         }
54         
55         /* Set the SIGINT/SIGQUIT signal handlers in the child, if requested 
56          */
57         (void)sigemptyset(&dfl.sa_mask);
58         dfl.sa_flags = 0;
59         if (set_inthandler) {
60             dfl.sa_handler = (void *)inthandler;
61             (void)sigaction(SIGINT, &dfl, NULL);
62         }
63         if (set_quithandler) {
64             dfl.sa_handler = (void *)quithandler;
65             (void)sigaction(SIGQUIT,  &dfl, NULL);
66         }
67
68         dup2 (fdStdInput,  STDIN_FILENO);
69         dup2 (fdStdOutput, STDOUT_FILENO);
70         dup2 (fdStdError,  STDERR_FILENO);
71         
72         if (environment) {
73             execvpe(args[0], args, environment);
74         } else {
75             execvp(args[0], args);
76         }
77     }
78     _exit(127);
79     }
80     
81     return pid;
82 }
83
84 ProcHandle
85 runInteractiveProcess (char *const args[], 
86                        char *workingDirectory, char **environment,
87                        int *pfdStdInput, int *pfdStdOutput, int *pfdStdError)
88 {
89     int pid;
90     int fdStdInput[2], fdStdOutput[2], fdStdError[2];
91
92     pipe(fdStdInput);
93     pipe(fdStdOutput);
94     pipe(fdStdError);
95
96     switch(pid = fork())
97     {
98     case -1:
99         close(fdStdInput[0]);
100         close(fdStdInput[1]);
101         close(fdStdOutput[0]);
102         close(fdStdOutput[1]);
103         close(fdStdError[0]);
104         close(fdStdError[1]);
105         return -1;
106         
107     case 0:
108     {
109         pPrPr_disableITimers();
110         
111         if (workingDirectory) {
112             if (chdir (workingDirectory) < 0) {
113                 return -1;
114             }
115         }
116         
117         dup2 (fdStdInput[0], STDIN_FILENO);
118         dup2 (fdStdOutput[1], STDOUT_FILENO);
119         dup2 (fdStdError[1], STDERR_FILENO);
120         
121         close(fdStdInput[0]);
122         close(fdStdInput[1]);
123         close(fdStdOutput[0]);
124         close(fdStdOutput[1]);
125         close(fdStdError[0]);
126         close(fdStdError[1]);
127         
128         /* the child */
129         if (environment) {
130             execvpe(args[0], args, environment);
131         } else {
132             execvp(args[0], args);
133         }
134     }
135     _exit(127);
136     
137     default:
138         close(fdStdInput[0]);
139         close(fdStdOutput[1]);
140         close(fdStdError[1]);
141         
142         *pfdStdInput  = fdStdInput[1];
143         *pfdStdOutput = fdStdOutput[0];
144         *pfdStdError  = fdStdError[0];
145         break;
146     }
147     
148     return pid;
149 }
150
151 int
152 terminateProcess (ProcHandle handle)
153 {
154     return (kill(handle, SIGTERM) == 0);
155 }
156
157 int
158 getProcessExitCode (ProcHandle handle, int *pExitCode)
159 {
160     int wstat, res;
161     
162     *pExitCode = 0;
163     
164     if ((res = waitpid(handle, &wstat, WNOHANG)) > 0)
165     {
166         if (WIFEXITED(wstat))
167         {
168             *pExitCode = WEXITSTATUS(wstat);
169             return 1;
170         }
171         else
172             if (WIFSIGNALED(wstat))
173             {
174                 errno = EINTR;
175                 return -1;
176             }
177             else
178             {
179                 /* This should never happen */
180             }
181     }
182     
183     if (res == 0) return 0;
184
185     if (errno == ECHILD) 
186     {
187             *pExitCode = 0;
188             return 1;
189     }
190
191     return -1;
192 }
193
194 int waitForProcess (ProcHandle handle)
195 {
196     int wstat;
197     
198     while (waitpid(handle, &wstat, 0) < 0)
199     {
200         if (errno != EINTR)
201         {
202             return -1;
203         }
204     }
205     
206     if (WIFEXITED(wstat))
207         return WEXITSTATUS(wstat);
208     else
209         if (WIFSIGNALED(wstat))
210         {
211             errno = EINTR;
212         }
213         else
214         {
215             /* This should never happen */
216         }
217     
218     return -1;
219 }
220
221 #else
222 /* ----------------------------------------------------------------------------
223    Win32 versions
224    ------------------------------------------------------------------------- */
225
226 /* -------------------- WINDOWS VERSION --------------------- */
227
228 /* This is the error table that defines the mapping between OS error
229    codes and errno values */
230
231 struct errentry {
232         unsigned long oscode;           /* OS return value */
233         int errnocode;  /* System V error code */
234 };
235
236 static struct errentry errtable[] = {
237         {  ERROR_INVALID_FUNCTION,       EINVAL    },  /* 1 */
238         {  ERROR_FILE_NOT_FOUND,         ENOENT    },  /* 2 */
239         {  ERROR_PATH_NOT_FOUND,         ENOENT    },  /* 3 */
240         {  ERROR_TOO_MANY_OPEN_FILES,    EMFILE    },  /* 4 */
241         {  ERROR_ACCESS_DENIED,          EACCES    },  /* 5 */
242         {  ERROR_INVALID_HANDLE,         EBADF     },  /* 6 */
243         {  ERROR_ARENA_TRASHED,          ENOMEM    },  /* 7 */
244         {  ERROR_NOT_ENOUGH_MEMORY,      ENOMEM    },  /* 8 */
245         {  ERROR_INVALID_BLOCK,          ENOMEM    },  /* 9 */
246         {  ERROR_BAD_ENVIRONMENT,        E2BIG     },  /* 10 */
247         {  ERROR_BAD_FORMAT,             ENOEXEC   },  /* 11 */
248         {  ERROR_INVALID_ACCESS,         EINVAL    },  /* 12 */
249         {  ERROR_INVALID_DATA,           EINVAL    },  /* 13 */
250         {  ERROR_INVALID_DRIVE,          ENOENT    },  /* 15 */
251         {  ERROR_CURRENT_DIRECTORY,      EACCES    },  /* 16 */
252         {  ERROR_NOT_SAME_DEVICE,        EXDEV     },  /* 17 */
253         {  ERROR_NO_MORE_FILES,          ENOENT    },  /* 18 */
254         {  ERROR_LOCK_VIOLATION,         EACCES    },  /* 33 */
255         {  ERROR_BAD_NETPATH,            ENOENT    },  /* 53 */
256         {  ERROR_NETWORK_ACCESS_DENIED,  EACCES    },  /* 65 */
257         {  ERROR_BAD_NET_NAME,           ENOENT    },  /* 67 */
258         {  ERROR_FILE_EXISTS,            EEXIST    },  /* 80 */
259         {  ERROR_CANNOT_MAKE,            EACCES    },  /* 82 */
260         {  ERROR_FAIL_I24,               EACCES    },  /* 83 */
261         {  ERROR_INVALID_PARAMETER,      EINVAL    },  /* 87 */
262         {  ERROR_NO_PROC_SLOTS,          EAGAIN    },  /* 89 */
263         {  ERROR_DRIVE_LOCKED,           EACCES    },  /* 108 */
264         {  ERROR_BROKEN_PIPE,            EPIPE     },  /* 109 */
265         {  ERROR_DISK_FULL,              ENOSPC    },  /* 112 */
266         {  ERROR_INVALID_TARGET_HANDLE,  EBADF     },  /* 114 */
267         {  ERROR_INVALID_HANDLE,         EINVAL    },  /* 124 */
268         {  ERROR_WAIT_NO_CHILDREN,       ECHILD    },  /* 128 */
269         {  ERROR_CHILD_NOT_COMPLETE,     ECHILD    },  /* 129 */
270         {  ERROR_DIRECT_ACCESS_HANDLE,   EBADF     },  /* 130 */
271         {  ERROR_NEGATIVE_SEEK,          EINVAL    },  /* 131 */
272         {  ERROR_SEEK_ON_DEVICE,         EACCES    },  /* 132 */
273         {  ERROR_DIR_NOT_EMPTY,          ENOTEMPTY },  /* 145 */
274         {  ERROR_NOT_LOCKED,             EACCES    },  /* 158 */
275         {  ERROR_BAD_PATHNAME,           ENOENT    },  /* 161 */
276         {  ERROR_MAX_THRDS_REACHED,      EAGAIN    },  /* 164 */
277         {  ERROR_LOCK_FAILED,            EACCES    },  /* 167 */
278         {  ERROR_ALREADY_EXISTS,         EEXIST    },  /* 183 */
279         {  ERROR_FILENAME_EXCED_RANGE,   ENOENT    },  /* 206 */
280         {  ERROR_NESTING_NOT_ALLOWED,    EAGAIN    },  /* 215 */
281         {  ERROR_NOT_ENOUGH_QUOTA,       ENOMEM    }    /* 1816 */
282 };
283
284 /* size of the table */
285 #define ERRTABLESIZE (sizeof(errtable)/sizeof(errtable[0]))
286
287 /* The following two constants must be the minimum and maximum
288    values in the (contiguous) range of Exec Failure errors. */
289 #define MIN_EXEC_ERROR ERROR_INVALID_STARTING_CODESEG
290 #define MAX_EXEC_ERROR ERROR_INFLOOP_IN_RELOC_CHAIN
291
292 /* These are the low and high value in the range of errors that are
293    access violations */
294 #define MIN_EACCES_RANGE ERROR_WRITE_PROTECT
295 #define MAX_EACCES_RANGE ERROR_SHARING_BUFFER_EXCEEDED
296
297 static void maperrno (void)
298 {
299         int i;
300         DWORD dwErrorCode;
301
302         dwErrorCode = GetLastError();
303
304         /* check the table for the OS error code */
305         for (i = 0; i < ERRTABLESIZE; ++i)
306         {
307                 if (dwErrorCode == errtable[i].oscode)
308                 {
309                         errno = errtable[i].errnocode;
310                         return;
311                 }
312         }
313
314         /* The error code wasn't in the table.  We check for a range of */
315         /* EACCES errors or exec failure errors (ENOEXEC).  Otherwise   */
316         /* EINVAL is returned.                                          */
317
318         if (dwErrorCode >= MIN_EACCES_RANGE && dwErrorCode <= MAX_EACCES_RANGE)
319                 errno = EACCES;
320         else
321                 if (dwErrorCode >= MIN_EXEC_ERROR && dwErrorCode <= MAX_EXEC_ERROR)
322                         errno = ENOEXEC;
323                 else
324                         errno = EINVAL;
325 }
326
327 /*
328  * Function: mkAnonPipe
329  *
330  * Purpose:  create an anonymous pipe with read and write ends being
331  *           optionally (non-)inheritable.
332  */
333 static BOOL
334 mkAnonPipe (HANDLE* pHandleIn, BOOL isInheritableIn, 
335             HANDLE* pHandleOut, BOOL isInheritableOut)
336 {
337         HANDLE hTemporaryIn  = NULL;
338         HANDLE hTemporaryOut = NULL;
339         BOOL status;
340         SECURITY_ATTRIBUTES sec_attrs;
341
342         /* Create inheritable security attributes */
343         sec_attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
344         sec_attrs.lpSecurityDescriptor = NULL;
345         sec_attrs.bInheritHandle = TRUE;
346
347         /* Create the anon pipe with both ends inheritable */
348         if (!CreatePipe(&hTemporaryIn, &hTemporaryOut, &sec_attrs, 0))
349         {
350                 maperrno();
351                 *pHandleIn  = NULL;
352                 *pHandleOut = NULL;
353                 return FALSE;
354         }
355
356         if (isInheritableIn)
357                 *pHandleIn = hTemporaryIn;
358         else
359         {
360                 /* Make the read end non-inheritable */
361                 status = DuplicateHandle(GetCurrentProcess(), hTemporaryIn,
362                               GetCurrentProcess(), pHandleIn,
363                               0,
364                               FALSE, /* non-inheritable */
365                               DUPLICATE_SAME_ACCESS);
366                 CloseHandle(hTemporaryIn);
367                 if (!status)
368                 {
369                         maperrno();
370                         *pHandleIn  = NULL;
371                         *pHandleOut = NULL;
372                         CloseHandle(hTemporaryOut);
373                         return FALSE;
374                 }
375         }
376
377         if (isInheritableOut)
378                 *pHandleOut = hTemporaryOut;
379         else
380         {
381                 /* Make the write end non-inheritable */
382                 status = DuplicateHandle(GetCurrentProcess(), hTemporaryOut,
383                               GetCurrentProcess(), pHandleOut,
384                               0,
385                               FALSE, /* non-inheritable */
386                               DUPLICATE_SAME_ACCESS);
387                 CloseHandle(hTemporaryOut);
388                 if (!status)
389                 {
390                         maperrno();
391                         *pHandleIn  = NULL;
392                         *pHandleOut = NULL;
393                         CloseHandle(*pHandleIn);
394                 return FALSE;
395         }
396         }
397
398         return TRUE;
399 }
400
401 ProcHandle
402 runProcess (char *cmd, char *workingDirectory, void *environment,
403             int fdStdInput, int fdStdOutput, int fdStdError)
404 {
405         STARTUPINFO sInfo;
406         PROCESS_INFORMATION pInfo;
407         DWORD flags;
408         char buffer[256];
409
410         ZeroMemory(&sInfo, sizeof(sInfo));
411         sInfo.cb = sizeof(sInfo);       
412         sInfo.hStdInput = (HANDLE) _get_osfhandle(fdStdInput);
413         sInfo.hStdOutput= (HANDLE) _get_osfhandle(fdStdOutput);
414         sInfo.hStdError = (HANDLE) _get_osfhandle(fdStdError);
415
416         if (sInfo.hStdInput == INVALID_HANDLE_VALUE)
417                 sInfo.hStdInput = NULL;
418         if (sInfo.hStdOutput == INVALID_HANDLE_VALUE)
419                 sInfo.hStdOutput = NULL;
420         if (sInfo.hStdError == INVALID_HANDLE_VALUE)
421                 sInfo.hStdError = NULL;
422
423         if (sInfo.hStdInput || sInfo.hStdOutput || sInfo.hStdError)
424                 sInfo.dwFlags = STARTF_USESTDHANDLES;
425
426         if (sInfo.hStdInput  != GetStdHandle(STD_INPUT_HANDLE)  &&
427             sInfo.hStdOutput != GetStdHandle(STD_OUTPUT_HANDLE) &&
428             sInfo.hStdError  != GetStdHandle(STD_ERROR_HANDLE))
429                 flags = CREATE_NO_WINDOW;   // Run without console window only when both output and error are redirected
430         else
431                 flags = 0;
432
433         if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, flags, environment, workingDirectory, &sInfo, &pInfo))
434         {
435                 maperrno();
436                 return -1;
437         }
438
439         CloseHandle(pInfo.hThread);
440         return (ProcHandle)pInfo.hProcess;
441 }
442
443 ProcHandle
444 runInteractiveProcess (char *cmd, char *workingDirectory, void *environment,
445                        int *pfdStdInput, int *pfdStdOutput, int *pfdStdError)
446 {
447         STARTUPINFO sInfo;
448         PROCESS_INFORMATION pInfo;
449         HANDLE hStdInputRead,  hStdInputWrite;
450         HANDLE hStdOutputRead, hStdOutputWrite;
451         HANDLE hStdErrorRead,  hStdErrorWrite;
452
453         if (!mkAnonPipe(&hStdInputRead,  TRUE, &hStdInputWrite,  FALSE))
454                 return -1;
455
456         if (!mkAnonPipe(&hStdOutputRead, FALSE, &hStdOutputWrite, TRUE))
457         {
458                 CloseHandle(hStdInputRead);
459                 CloseHandle(hStdInputWrite);
460                 return -1;
461         }
462
463         if (!mkAnonPipe(&hStdErrorRead,  FALSE, &hStdErrorWrite,  TRUE))
464         {
465                 CloseHandle(hStdInputRead);
466                 CloseHandle(hStdInputWrite);
467                 CloseHandle(hStdOutputRead);
468                 CloseHandle(hStdOutputWrite);
469                 return -1;
470         }
471
472         ZeroMemory(&sInfo, sizeof(sInfo));
473         sInfo.cb = sizeof(sInfo);
474         sInfo.dwFlags = STARTF_USESTDHANDLES;
475         sInfo.hStdInput = hStdInputRead;
476         sInfo.hStdOutput= hStdOutputWrite;
477         sInfo.hStdError = hStdErrorWrite;
478
479         if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, environment, workingDirectory, &sInfo, &pInfo))
480         {
481                 maperrno();
482                 CloseHandle(hStdInputRead);
483                 CloseHandle(hStdInputWrite);
484                 CloseHandle(hStdOutputRead);
485                 CloseHandle(hStdOutputWrite);
486                 CloseHandle(hStdErrorRead);
487                 CloseHandle(hStdErrorWrite);
488                 return -1;
489         }
490         CloseHandle(pInfo.hThread);
491
492         // Close the ends of the pipes that were inherited by the
493         // child process.  This is important, otherwise we won't see
494         // EOF on these pipes when the child process exits.
495         CloseHandle(hStdInputRead);
496         CloseHandle(hStdOutputWrite);
497         CloseHandle(hStdErrorWrite);
498
499         *pfdStdInput  = _open_osfhandle((intptr_t) hStdInputWrite, _O_WRONLY);
500         *pfdStdOutput = _open_osfhandle((intptr_t) hStdOutputRead, _O_RDONLY);
501         *pfdStdError  = _open_osfhandle((intptr_t) hStdErrorRead, _O_RDONLY);
502
503         return (int) pInfo.hProcess;
504 }
505
506 int
507 terminateProcess (ProcHandle handle)
508 {
509     if (!TerminateProcess((HANDLE) handle, 1)) {
510         maperrno();
511         return -1;
512     }
513
514     CloseHandle((HANDLE) handle);
515     return 0;
516 }
517
518 int
519 getProcessExitCode (ProcHandle handle, int *pExitCode)
520 {
521     *pExitCode = 0;
522
523     if (WaitForSingleObject((HANDLE) handle, 1) == WAIT_OBJECT_0)
524     {
525         if (GetExitCodeProcess((HANDLE) handle, (DWORD *) pExitCode) == 0)
526         {
527             maperrno();
528             return -1;
529         }
530         
531         CloseHandle((HANDLE) handle);
532         return 1;
533     }
534     
535     return 0;
536 }
537
538 int
539 waitForProcess (ProcHandle handle)
540 {
541     DWORD retCode;
542
543     if (WaitForSingleObject((HANDLE) handle, INFINITE) == WAIT_OBJECT_0)
544     {
545         if (GetExitCodeProcess((HANDLE) handle, &retCode) == 0)
546         {
547             maperrno();
548             return -1;
549         }
550         
551         CloseHandle((HANDLE) handle);
552         return retCode;
553     }
554     
555     maperrno();
556     return -1;
557 }
558
559 #endif /* Win32 */