1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
3 #include "kwsysPrivate.h"
4 #include KWSYS_HEADER(Process.h)
5 #include KWSYS_HEADER(System.h)
6 
7 /* Work-around CMake dependency scanning limitation.  This must
8    duplicate the above list of headers.  */
9 #if 0
10 #  include "Process.h.in"
11 #  include "System.h.in"
12 #endif
13 
14 /*
15 
16 Implementation for UNIX
17 
18 On UNIX, a child process is forked to exec the program.  Three output
19 pipes are read by the parent process using a select call to block
20 until data are ready.  Two of the pipes are stdout and stderr for the
21 child.  The third is a special pipe populated by a signal handler to
22 indicate that a child has terminated.  This is used in conjunction
23 with the timeout on the select call to implement a timeout for program
24 even when it closes stdout and stderr and at the same time avoiding
25 races.
26 
27 */
28 
29 /*
30 
31 TODO:
32 
33 We cannot create the pipeline of processes in suspended states.  How
34 do we cleanup processes already started when one fails to load?  Right
35 now we are just killing them, which is probably not the right thing to
36 do.
37 
38 */
39 
40 #if defined(__CYGWIN__)
41 /* Increase the file descriptor limit for select() before including
42    related system headers. (Default: 64) */
43 #  define FD_SETSIZE 16384
44 #endif
45 
46 #include <assert.h>    /* assert */
47 #include <ctype.h>     /* isspace */
48 #include <dirent.h>    /* DIR, dirent */
49 #include <errno.h>     /* errno */
50 #include <fcntl.h>     /* fcntl */
51 #include <signal.h>    /* sigaction */
52 #include <stddef.h>    /* ptrdiff_t */
53 #include <stdio.h>     /* snprintf */
54 #include <stdlib.h>    /* malloc, free */
55 #include <string.h>    /* strdup, strerror, memset */
56 #include <sys/stat.h>  /* open mode */
57 #include <sys/time.h>  /* struct timeval */
58 #include <sys/types.h> /* pid_t, fd_set */
59 #include <sys/wait.h>  /* waitpid */
60 #include <time.h>      /* gettimeofday */
61 #include <unistd.h>    /* pipe, close, fork, execvp, select, _exit */
62 
63 #if defined(__VMS)
64 #  define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
65 #else
66 #  define KWSYSPE_VMS_NONBLOCK
67 #endif
68 
69 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
70 typedef ptrdiff_t kwsysProcess_ptrdiff_t;
71 #else
72 typedef int kwsysProcess_ptrdiff_t;
73 #endif
74 
75 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
76 typedef ssize_t kwsysProcess_ssize_t;
77 #else
78 typedef int kwsysProcess_ssize_t;
79 #endif
80 
81 #if defined(__BEOS__) && !defined(__ZETA__)
82 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
83 #  include <be/kernel/OS.h>
kwsysProcess_usleep(unsigned int msec)84 static inline void kwsysProcess_usleep(unsigned int msec)
85 {
86   snooze(msec);
87 }
88 #else
89 #  define kwsysProcess_usleep usleep
90 #endif
91 
92 /*
93  * BeOS's select() works like WinSock: it's for networking only, and
94  * doesn't work with Unix file handles...socket and file handles are
95  * different namespaces (the same descriptor means different things in
96  * each context!)
97  *
98  * So on Unix-like systems where select() is flakey, we'll set the
99  * pipes' file handles to be non-blocking and just poll them directly
100  * without select().
101  */
102 #if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__) &&            \
103   !defined(KWSYSPE_USE_SELECT)
104 #  define KWSYSPE_USE_SELECT 1
105 #endif
106 
107 /* Some platforms do not have siginfo on their signal handlers.  */
108 #if defined(SA_SIGINFO) && !defined(__BEOS__)
109 #  define KWSYSPE_USE_SIGINFO 1
110 #endif
111 
112 /* The number of pipes for the child's output.  The standard stdout
113    and stderr pipes are the first two.  One more pipe is used to
114    detect when the child process has terminated.  The third pipe is
115    not given to the child process, so it cannot close it until it
116    terminates.  */
117 #define KWSYSPE_PIPE_COUNT 3
118 #define KWSYSPE_PIPE_STDOUT 0
119 #define KWSYSPE_PIPE_STDERR 1
120 #define KWSYSPE_PIPE_SIGNAL 2
121 
122 /* The maximum amount to read from a pipe at a time.  */
123 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
124 
125 /* Keep track of times using a signed representation.  Switch to the
126    native (possibly unsigned) representation only when calling native
127    functions.  */
128 typedef struct timeval kwsysProcessTimeNative;
129 typedef struct kwsysProcessTime_s kwsysProcessTime;
130 struct kwsysProcessTime_s
131 {
132   long tv_sec;
133   long tv_usec;
134 };
135 
136 typedef struct kwsysProcessCreateInformation_s
137 {
138   int StdIn;
139   int StdOut;
140   int StdErr;
141   int ErrorPipe[2];
142 } kwsysProcessCreateInformation;
143 
144 static void kwsysProcessVolatileFree(volatile void* p);
145 static int kwsysProcessInitialize(kwsysProcess* cp);
146 static void kwsysProcessCleanup(kwsysProcess* cp, int error);
147 static void kwsysProcessCleanupDescriptor(int* pfd);
148 static void kwsysProcessClosePipes(kwsysProcess* cp);
149 static int kwsysProcessSetNonBlocking(int fd);
150 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
151                               kwsysProcessCreateInformation* si);
152 static void kwsysProcessDestroy(kwsysProcess* cp);
153 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
154 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
155 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
156                                       kwsysProcessTime* timeoutTime);
157 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
158                                       double* userTimeout,
159                                       kwsysProcessTimeNative* timeoutLength,
160                                       int zeroIsExpired);
161 static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
162 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
163 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
164 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
165 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
166                                             kwsysProcessTime in2);
167 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
168                                                  kwsysProcessTime in2);
169 static void kwsysProcessSetExitExceptionByIndex(kwsysProcess* cp, int sig,
170                                                 int idx);
171 static void kwsysProcessChildErrorExit(int errorPipe);
172 static void kwsysProcessRestoreDefaultSignalHandlers(void);
173 static pid_t kwsysProcessFork(kwsysProcess* cp,
174                               kwsysProcessCreateInformation* si);
175 static void kwsysProcessKill(pid_t process_id);
176 #if defined(__VMS)
177 static int kwsysProcessSetVMSFeature(const char* name, int value);
178 #endif
179 static int kwsysProcessesAdd(kwsysProcess* cp);
180 static void kwsysProcessesRemove(kwsysProcess* cp);
181 #if KWSYSPE_USE_SIGINFO
182 static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
183                                         void* ucontext);
184 #else
185 static void kwsysProcessesSignalHandler(int signum);
186 #endif
187 
188 /* A structure containing results data for each process.  */
189 typedef struct kwsysProcessResults_s kwsysProcessResults;
190 struct kwsysProcessResults_s
191 {
192   /* The status of the child process. */
193   int State;
194 
195   /* The exceptional behavior that terminated the process, if any.  */
196   int ExitException;
197 
198   /* The process exit code.  */
199   int ExitCode;
200 
201   /* The process return code, if any.  */
202   int ExitValue;
203 
204   /* Description for the ExitException.  */
205   char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
206 };
207 
208 /* Structure containing data used to implement the child's execution.  */
209 struct kwsysProcess_s
210 {
211   /* The command lines to execute.  */
212   char*** Commands;
213   volatile int NumberOfCommands;
214 
215   /* Descriptors for the read ends of the child's output pipes and
216      the signal pipe. */
217   int PipeReadEnds[KWSYSPE_PIPE_COUNT];
218 
219   /* Descriptors for the child's ends of the pipes.
220      Used temporarily during process creation.  */
221   int PipeChildStd[3];
222 
223   /* Write descriptor for child termination signal pipe.  */
224   int SignalPipe;
225 
226   /* Buffer for pipe data.  */
227   char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
228 
229   /* Process IDs returned by the calls to fork.  Everything is volatile
230      because the signal handler accesses them.  You must be very careful
231      when reaping PIDs or modifying this array to avoid race conditions.  */
232   volatile pid_t* volatile ForkPIDs;
233 
234   /* Flag for whether the children were terminated by a failed select.  */
235   int SelectError;
236 
237   /* The timeout length.  */
238   double Timeout;
239 
240   /* The working directory for the process. */
241   char* WorkingDirectory;
242 
243   /* Whether to create the child as a detached process.  */
244   int OptionDetach;
245 
246   /* Whether the child was created as a detached process.  */
247   int Detached;
248 
249   /* Whether to treat command lines as verbatim.  */
250   int Verbatim;
251 
252   /* Whether to merge stdout/stderr of the child.  */
253   int MergeOutput;
254 
255   /* Whether to create the process in a new process group.  */
256   volatile sig_atomic_t CreateProcessGroup;
257 
258   /* Time at which the child started.  Negative for no timeout.  */
259   kwsysProcessTime StartTime;
260 
261   /* Time at which the child will timeout.  Negative for no timeout.  */
262   kwsysProcessTime TimeoutTime;
263 
264   /* Flag for whether the timeout expired.  */
265   int TimeoutExpired;
266 
267   /* The number of pipes left open during execution.  */
268   int PipesLeft;
269 
270 #if KWSYSPE_USE_SELECT
271   /* File descriptor set for call to select.  */
272   fd_set PipeSet;
273 #endif
274 
275   /* The number of children still executing.  */
276   int CommandsLeft;
277 
278   /* The status of the process structure.  Must be atomic because
279      the signal handler checks this to avoid a race.  */
280   volatile sig_atomic_t State;
281 
282   /* Whether the process was killed.  */
283   volatile sig_atomic_t Killed;
284 
285   /* Buffer for error message in case of failure.  */
286   char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
287 
288   /* process results.  */
289   kwsysProcessResults* ProcessResults;
290 
291   /* The exit codes of each child process in the pipeline.  */
292   int* CommandExitCodes;
293 
294   /* Name of files to which stdin and stdout pipes are attached.  */
295   char* PipeFileSTDIN;
296   char* PipeFileSTDOUT;
297   char* PipeFileSTDERR;
298 
299   /* Whether each pipe is shared with the parent process.  */
300   int PipeSharedSTDIN;
301   int PipeSharedSTDOUT;
302   int PipeSharedSTDERR;
303 
304   /* Native pipes provided by the user.  */
305   int PipeNativeSTDIN[2];
306   int PipeNativeSTDOUT[2];
307   int PipeNativeSTDERR[2];
308 
309   /* The real working directory of this process.  */
310   int RealWorkingDirectoryLength;
311   char* RealWorkingDirectory;
312 };
313 
kwsysProcess_New(void)314 kwsysProcess* kwsysProcess_New(void)
315 {
316   /* Allocate a process control structure.  */
317   kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
318   if (!cp) {
319     return 0;
320   }
321   memset(cp, 0, sizeof(kwsysProcess));
322 
323   /* Share stdin with the parent process by default.  */
324   cp->PipeSharedSTDIN = 1;
325 
326   /* No native pipes by default.  */
327   cp->PipeNativeSTDIN[0] = -1;
328   cp->PipeNativeSTDIN[1] = -1;
329   cp->PipeNativeSTDOUT[0] = -1;
330   cp->PipeNativeSTDOUT[1] = -1;
331   cp->PipeNativeSTDERR[0] = -1;
332   cp->PipeNativeSTDERR[1] = -1;
333 
334   /* Set initial status.  */
335   cp->State = kwsysProcess_State_Starting;
336 
337   return cp;
338 }
339 
kwsysProcess_Delete(kwsysProcess * cp)340 void kwsysProcess_Delete(kwsysProcess* cp)
341 {
342   /* Make sure we have an instance.  */
343   if (!cp) {
344     return;
345   }
346 
347   /* If the process is executing, wait for it to finish.  */
348   if (cp->State == kwsysProcess_State_Executing) {
349     if (cp->Detached) {
350       kwsysProcess_Disown(cp);
351     } else {
352       kwsysProcess_WaitForExit(cp, 0);
353     }
354   }
355 
356   /* Free memory.  */
357   kwsysProcess_SetCommand(cp, 0);
358   kwsysProcess_SetWorkingDirectory(cp, 0);
359   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
360   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
361   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
362   free(cp->CommandExitCodes);
363   free(cp->ProcessResults);
364   free(cp);
365 }
366 
kwsysProcess_SetCommand(kwsysProcess * cp,char const * const * command)367 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
368 {
369   int i;
370   if (!cp) {
371     return 0;
372   }
373   for (i = 0; i < cp->NumberOfCommands; ++i) {
374     char** c = cp->Commands[i];
375     while (*c) {
376       free(*c++);
377     }
378     free(cp->Commands[i]);
379   }
380   cp->NumberOfCommands = 0;
381   if (cp->Commands) {
382     free(cp->Commands);
383     cp->Commands = 0;
384   }
385   if (command) {
386     return kwsysProcess_AddCommand(cp, command);
387   }
388   return 1;
389 }
390 
kwsysProcess_AddCommand(kwsysProcess * cp,char const * const * command)391 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
392 {
393   int newNumberOfCommands;
394   char*** newCommands;
395 
396   /* Make sure we have a command to add.  */
397   if (!cp || !command || !*command) {
398     return 0;
399   }
400 
401   /* Allocate a new array for command pointers.  */
402   newNumberOfCommands = cp->NumberOfCommands + 1;
403   if (!(newCommands =
404           (char***)malloc(sizeof(char**) * (size_t)(newNumberOfCommands)))) {
405     /* Out of memory.  */
406     return 0;
407   }
408 
409   /* Copy any existing commands into the new array.  */
410   {
411     int i;
412     for (i = 0; i < cp->NumberOfCommands; ++i) {
413       newCommands[i] = cp->Commands[i];
414     }
415   }
416 
417   /* Add the new command.  */
418   if (cp->Verbatim) {
419     /* In order to run the given command line verbatim we need to
420        parse it.  */
421     newCommands[cp->NumberOfCommands] =
422       kwsysSystem_Parse_CommandForUnix(*command, 0);
423     if (!newCommands[cp->NumberOfCommands] ||
424         !newCommands[cp->NumberOfCommands][0]) {
425       /* Out of memory or no command parsed.  */
426       free(newCommands);
427       return 0;
428     }
429   } else {
430     /* Copy each argument string individually.  */
431     char const* const* c = command;
432     kwsysProcess_ptrdiff_t n = 0;
433     kwsysProcess_ptrdiff_t i = 0;
434     while (*c++)
435       ;
436     n = c - command - 1;
437     newCommands[cp->NumberOfCommands] =
438       (char**)malloc((size_t)(n + 1) * sizeof(char*));
439     if (!newCommands[cp->NumberOfCommands]) {
440       /* Out of memory.  */
441       free(newCommands);
442       return 0;
443     }
444     for (i = 0; i < n; ++i) {
445       assert(command[i]); /* Quiet Clang scan-build. */
446       newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
447       if (!newCommands[cp->NumberOfCommands][i]) {
448         break;
449       }
450     }
451     if (i < n) {
452       /* Out of memory.  */
453       for (; i > 0; --i) {
454         free(newCommands[cp->NumberOfCommands][i - 1]);
455       }
456       free(newCommands);
457       return 0;
458     }
459     newCommands[cp->NumberOfCommands][n] = 0;
460   }
461 
462   /* Successfully allocated new command array.  Free the old array. */
463   free(cp->Commands);
464   cp->Commands = newCommands;
465   cp->NumberOfCommands = newNumberOfCommands;
466 
467   return 1;
468 }
469 
kwsysProcess_SetTimeout(kwsysProcess * cp,double timeout)470 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
471 {
472   if (!cp) {
473     return;
474   }
475   cp->Timeout = timeout;
476   if (cp->Timeout < 0) {
477     cp->Timeout = 0;
478   }
479   // Force recomputation of TimeoutTime.
480   cp->TimeoutTime.tv_sec = -1;
481 }
482 
kwsysProcess_SetWorkingDirectory(kwsysProcess * cp,const char * dir)483 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
484 {
485   if (!cp) {
486     return 0;
487   }
488   if (cp->WorkingDirectory == dir) {
489     return 1;
490   }
491   if (cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0) {
492     return 1;
493   }
494   if (cp->WorkingDirectory) {
495     free(cp->WorkingDirectory);
496     cp->WorkingDirectory = 0;
497   }
498   if (dir) {
499     cp->WorkingDirectory = strdup(dir);
500     if (!cp->WorkingDirectory) {
501       return 0;
502     }
503   }
504   return 1;
505 }
506 
kwsysProcess_SetPipeFile(kwsysProcess * cp,int prPipe,const char * file)507 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
508 {
509   char** pfile;
510   if (!cp) {
511     return 0;
512   }
513   switch (prPipe) {
514     case kwsysProcess_Pipe_STDIN:
515       pfile = &cp->PipeFileSTDIN;
516       break;
517     case kwsysProcess_Pipe_STDOUT:
518       pfile = &cp->PipeFileSTDOUT;
519       break;
520     case kwsysProcess_Pipe_STDERR:
521       pfile = &cp->PipeFileSTDERR;
522       break;
523     default:
524       return 0;
525   }
526   if (*pfile) {
527     free(*pfile);
528     *pfile = 0;
529   }
530   if (file) {
531     *pfile = strdup(file);
532     if (!*pfile) {
533       return 0;
534     }
535   }
536 
537   /* If we are redirecting the pipe, do not share it or use a native
538      pipe.  */
539   if (*pfile) {
540     kwsysProcess_SetPipeNative(cp, prPipe, 0);
541     kwsysProcess_SetPipeShared(cp, prPipe, 0);
542   }
543   return 1;
544 }
545 
kwsysProcess_SetPipeShared(kwsysProcess * cp,int prPipe,int shared)546 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
547 {
548   if (!cp) {
549     return;
550   }
551 
552   switch (prPipe) {
553     case kwsysProcess_Pipe_STDIN:
554       cp->PipeSharedSTDIN = shared ? 1 : 0;
555       break;
556     case kwsysProcess_Pipe_STDOUT:
557       cp->PipeSharedSTDOUT = shared ? 1 : 0;
558       break;
559     case kwsysProcess_Pipe_STDERR:
560       cp->PipeSharedSTDERR = shared ? 1 : 0;
561       break;
562     default:
563       return;
564   }
565 
566   /* If we are sharing the pipe, do not redirect it to a file or use a
567      native pipe.  */
568   if (shared) {
569     kwsysProcess_SetPipeFile(cp, prPipe, 0);
570     kwsysProcess_SetPipeNative(cp, prPipe, 0);
571   }
572 }
573 
kwsysProcess_SetPipeNative(kwsysProcess * cp,int prPipe,int p[2])574 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
575 {
576   int* pPipeNative = 0;
577 
578   if (!cp) {
579     return;
580   }
581 
582   switch (prPipe) {
583     case kwsysProcess_Pipe_STDIN:
584       pPipeNative = cp->PipeNativeSTDIN;
585       break;
586     case kwsysProcess_Pipe_STDOUT:
587       pPipeNative = cp->PipeNativeSTDOUT;
588       break;
589     case kwsysProcess_Pipe_STDERR:
590       pPipeNative = cp->PipeNativeSTDERR;
591       break;
592     default:
593       return;
594   }
595 
596   /* Copy the native pipe descriptors provided.  */
597   if (p) {
598     pPipeNative[0] = p[0];
599     pPipeNative[1] = p[1];
600   } else {
601     pPipeNative[0] = -1;
602     pPipeNative[1] = -1;
603   }
604 
605   /* If we are using a native pipe, do not share it or redirect it to
606      a file.  */
607   if (p) {
608     kwsysProcess_SetPipeFile(cp, prPipe, 0);
609     kwsysProcess_SetPipeShared(cp, prPipe, 0);
610   }
611 }
612 
kwsysProcess_GetOption(kwsysProcess * cp,int optionId)613 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
614 {
615   if (!cp) {
616     return 0;
617   }
618 
619   switch (optionId) {
620     case kwsysProcess_Option_Detach:
621       return cp->OptionDetach;
622     case kwsysProcess_Option_MergeOutput:
623       return cp->MergeOutput;
624     case kwsysProcess_Option_Verbatim:
625       return cp->Verbatim;
626     case kwsysProcess_Option_CreateProcessGroup:
627       return cp->CreateProcessGroup;
628     default:
629       return 0;
630   }
631 }
632 
kwsysProcess_SetOption(kwsysProcess * cp,int optionId,int value)633 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
634 {
635   if (!cp) {
636     return;
637   }
638 
639   switch (optionId) {
640     case kwsysProcess_Option_Detach:
641       cp->OptionDetach = value;
642       break;
643     case kwsysProcess_Option_MergeOutput:
644       cp->MergeOutput = value;
645       break;
646     case kwsysProcess_Option_Verbatim:
647       cp->Verbatim = value;
648       break;
649     case kwsysProcess_Option_CreateProcessGroup:
650       cp->CreateProcessGroup = value;
651       break;
652     default:
653       break;
654   }
655 }
656 
kwsysProcess_GetState(kwsysProcess * cp)657 int kwsysProcess_GetState(kwsysProcess* cp)
658 {
659   return cp ? cp->State : kwsysProcess_State_Error;
660 }
661 
kwsysProcess_GetExitException(kwsysProcess * cp)662 int kwsysProcess_GetExitException(kwsysProcess* cp)
663 {
664   return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
665     ? cp->ProcessResults[cp->NumberOfCommands - 1].ExitException
666     : kwsysProcess_Exception_Other;
667 }
668 
kwsysProcess_GetExitCode(kwsysProcess * cp)669 int kwsysProcess_GetExitCode(kwsysProcess* cp)
670 {
671   return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
672     ? cp->ProcessResults[cp->NumberOfCommands - 1].ExitCode
673     : 0;
674 }
675 
kwsysProcess_GetExitValue(kwsysProcess * cp)676 int kwsysProcess_GetExitValue(kwsysProcess* cp)
677 {
678   return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
679     ? cp->ProcessResults[cp->NumberOfCommands - 1].ExitValue
680     : -1;
681 }
682 
kwsysProcess_GetErrorString(kwsysProcess * cp)683 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
684 {
685   if (!cp) {
686     return "Process management structure could not be allocated";
687   } else if (cp->State == kwsysProcess_State_Error) {
688     return cp->ErrorMessage;
689   }
690   return "Success";
691 }
692 
kwsysProcess_GetExceptionString(kwsysProcess * cp)693 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
694 {
695   if (!(cp && cp->ProcessResults && (cp->NumberOfCommands > 0))) {
696     return "GetExceptionString called with NULL process management structure";
697   } else if (cp->State == kwsysProcess_State_Exception) {
698     return cp->ProcessResults[cp->NumberOfCommands - 1].ExitExceptionString;
699   }
700   return "No exception";
701 }
702 
703 /* the index should be in array bound. */
704 #define KWSYSPE_IDX_CHK(RET)                                                  \
705   if (!cp || idx >= cp->NumberOfCommands || idx < 0) {                        \
706     return RET;                                                               \
707   }
708 
kwsysProcess_GetStateByIndex(kwsysProcess * cp,int idx)709 int kwsysProcess_GetStateByIndex(kwsysProcess* cp, int idx)
710 {
711   KWSYSPE_IDX_CHK(kwsysProcess_State_Error)
712   return cp->ProcessResults[idx].State;
713 }
714 
kwsysProcess_GetExitExceptionByIndex(kwsysProcess * cp,int idx)715 int kwsysProcess_GetExitExceptionByIndex(kwsysProcess* cp, int idx)
716 {
717   KWSYSPE_IDX_CHK(kwsysProcess_Exception_Other)
718   return cp->ProcessResults[idx].ExitException;
719 }
720 
kwsysProcess_GetExitValueByIndex(kwsysProcess * cp,int idx)721 int kwsysProcess_GetExitValueByIndex(kwsysProcess* cp, int idx)
722 {
723   KWSYSPE_IDX_CHK(-1)
724   return cp->ProcessResults[idx].ExitValue;
725 }
726 
kwsysProcess_GetExitCodeByIndex(kwsysProcess * cp,int idx)727 int kwsysProcess_GetExitCodeByIndex(kwsysProcess* cp, int idx)
728 {
729   KWSYSPE_IDX_CHK(-1)
730   return cp->CommandExitCodes[idx];
731 }
732 
kwsysProcess_GetExceptionStringByIndex(kwsysProcess * cp,int idx)733 const char* kwsysProcess_GetExceptionStringByIndex(kwsysProcess* cp, int idx)
734 {
735   KWSYSPE_IDX_CHK("GetExceptionString called with NULL process management "
736                   "structure or index out of bound")
737   if (cp->ProcessResults[idx].State == kwsysProcess_StateByIndex_Exception) {
738     return cp->ProcessResults[idx].ExitExceptionString;
739   }
740   return "No exception";
741 }
742 
743 #undef KWSYSPE_IDX_CHK
744 
kwsysProcess_Execute(kwsysProcess * cp)745 void kwsysProcess_Execute(kwsysProcess* cp)
746 {
747   int i;
748 
749   /* Do not execute a second copy simultaneously.  */
750   if (!cp || cp->State == kwsysProcess_State_Executing) {
751     return;
752   }
753 
754   /* Make sure we have something to run.  */
755   if (cp->NumberOfCommands < 1) {
756     strcpy(cp->ErrorMessage, "No command");
757     cp->State = kwsysProcess_State_Error;
758     return;
759   }
760 
761   /* Initialize the control structure for a new process.  */
762   if (!kwsysProcessInitialize(cp)) {
763     strcpy(cp->ErrorMessage, "Out of memory");
764     cp->State = kwsysProcess_State_Error;
765     return;
766   }
767 
768 #if defined(__VMS)
769   /* Make sure pipes behave like streams on VMS.  */
770   if (!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1)) {
771     kwsysProcessCleanup(cp, 1);
772     return;
773   }
774 #endif
775 
776   /* Save the real working directory of this process and change to
777      the working directory for the child processes.  This is needed
778      to make pipe file paths evaluate correctly.  */
779   if (cp->WorkingDirectory) {
780     int r;
781     if (!getcwd(cp->RealWorkingDirectory,
782                 (size_t)(cp->RealWorkingDirectoryLength))) {
783       kwsysProcessCleanup(cp, 1);
784       return;
785     }
786 
787     /* Some platforms specify that the chdir call may be
788        interrupted.  Repeat the call until it finishes.  */
789     while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR))
790       ;
791     if (r < 0) {
792       kwsysProcessCleanup(cp, 1);
793       return;
794     }
795   }
796 
797   /* If not running a detached child, add this object to the global
798      set of process objects that wish to be notified when a child
799      exits.  */
800   if (!cp->OptionDetach) {
801     if (!kwsysProcessesAdd(cp)) {
802       kwsysProcessCleanup(cp, 1);
803       return;
804     }
805   }
806 
807   /* Setup the stdin pipe for the first process.  */
808   if (cp->PipeFileSTDIN) {
809     /* Open a file for the child's stdin to read.  */
810     cp->PipeChildStd[0] = open(cp->PipeFileSTDIN, O_RDONLY);
811     if (cp->PipeChildStd[0] < 0) {
812       kwsysProcessCleanup(cp, 1);
813       return;
814     }
815 
816     /* Set close-on-exec flag on the pipe's end.  */
817     if (fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0) {
818       kwsysProcessCleanup(cp, 1);
819       return;
820     }
821   } else if (cp->PipeSharedSTDIN) {
822     cp->PipeChildStd[0] = 0;
823   } else if (cp->PipeNativeSTDIN[0] >= 0) {
824     cp->PipeChildStd[0] = cp->PipeNativeSTDIN[0];
825 
826     /* Set close-on-exec flag on the pipe's ends.  The read end will
827        be dup2-ed into the stdin descriptor after the fork but before
828        the exec.  */
829     if ((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
830         (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0)) {
831       kwsysProcessCleanup(cp, 1);
832       return;
833     }
834   } else {
835     cp->PipeChildStd[0] = -1;
836   }
837 
838   /* Create the output pipe for the last process.
839      We always create this so the pipe can be passed to select even if
840      it will report closed immediately.  */
841   {
842     /* Create the pipe.  */
843     int p[2];
844     if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
845       kwsysProcessCleanup(cp, 1);
846       return;
847     }
848 
849     /* Store the pipe.  */
850     cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
851     cp->PipeChildStd[1] = p[1];
852 
853     /* Set close-on-exec flag on the pipe's ends.  */
854     if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
855         (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
856       kwsysProcessCleanup(cp, 1);
857       return;
858     }
859 
860     /* Set to non-blocking in case select lies, or for the polling
861        implementation.  */
862     if (!kwsysProcessSetNonBlocking(p[0])) {
863       kwsysProcessCleanup(cp, 1);
864       return;
865     }
866   }
867 
868   if (cp->PipeFileSTDOUT) {
869     /* Use a file for stdout.  */
870     if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
871                                          cp->PipeFileSTDOUT)) {
872       kwsysProcessCleanup(cp, 1);
873       return;
874     }
875   } else if (cp->PipeSharedSTDOUT) {
876     /* Use the parent stdout.  */
877     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[1]);
878     cp->PipeChildStd[1] = 1;
879   } else if (cp->PipeNativeSTDOUT[1] >= 0) {
880     /* Use the given descriptor for stdout.  */
881     if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
882                                            cp->PipeNativeSTDOUT)) {
883       kwsysProcessCleanup(cp, 1);
884       return;
885     }
886   }
887 
888   /* Create stderr pipe to be shared by all processes in the pipeline.
889      We always create this so the pipe can be passed to select even if
890      it will report closed immediately.  */
891   {
892     /* Create the pipe.  */
893     int p[2];
894     if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
895       kwsysProcessCleanup(cp, 1);
896       return;
897     }
898 
899     /* Store the pipe.  */
900     cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
901     cp->PipeChildStd[2] = p[1];
902 
903     /* Set close-on-exec flag on the pipe's ends.  */
904     if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
905         (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
906       kwsysProcessCleanup(cp, 1);
907       return;
908     }
909 
910     /* Set to non-blocking in case select lies, or for the polling
911        implementation.  */
912     if (!kwsysProcessSetNonBlocking(p[0])) {
913       kwsysProcessCleanup(cp, 1);
914       return;
915     }
916   }
917 
918   if (cp->PipeFileSTDERR) {
919     /* Use a file for stderr.  */
920     if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
921                                          cp->PipeFileSTDERR)) {
922       kwsysProcessCleanup(cp, 1);
923       return;
924     }
925   } else if (cp->PipeSharedSTDERR) {
926     /* Use the parent stderr.  */
927     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[2]);
928     cp->PipeChildStd[2] = 2;
929   } else if (cp->PipeNativeSTDERR[1] >= 0) {
930     /* Use the given handle for stderr.  */
931     if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
932                                            cp->PipeNativeSTDERR)) {
933       kwsysProcessCleanup(cp, 1);
934       return;
935     }
936   }
937 
938   /* The timeout period starts now.  */
939   cp->StartTime = kwsysProcessTimeGetCurrent();
940   cp->TimeoutTime.tv_sec = -1;
941   cp->TimeoutTime.tv_usec = -1;
942 
943   /* Create the pipeline of processes.  */
944   {
945     kwsysProcessCreateInformation si = { -1, -1, -1, { -1, -1 } };
946     int nextStdIn = cp->PipeChildStd[0];
947     for (i = 0; i < cp->NumberOfCommands; ++i) {
948       /* Setup the process's pipes.  */
949       si.StdIn = nextStdIn;
950       if (i == cp->NumberOfCommands - 1) {
951         nextStdIn = -1;
952         si.StdOut = cp->PipeChildStd[1];
953       } else {
954         /* Create a pipe to sit between the children.  */
955         int p[2] = { -1, -1 };
956         if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
957           if (nextStdIn != cp->PipeChildStd[0]) {
958             kwsysProcessCleanupDescriptor(&nextStdIn);
959           }
960           kwsysProcessCleanup(cp, 1);
961           return;
962         }
963 
964         /* Set close-on-exec flag on the pipe's ends.  */
965         if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
966             (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
967           close(p[0]);
968           close(p[1]);
969           if (nextStdIn != cp->PipeChildStd[0]) {
970             kwsysProcessCleanupDescriptor(&nextStdIn);
971           }
972           kwsysProcessCleanup(cp, 1);
973           return;
974         }
975         nextStdIn = p[0];
976         si.StdOut = p[1];
977       }
978       si.StdErr = cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
979 
980       {
981         int res = kwsysProcessCreate(cp, i, &si);
982 
983         /* Close our copies of pipes used between children.  */
984         if (si.StdIn != cp->PipeChildStd[0]) {
985           kwsysProcessCleanupDescriptor(&si.StdIn);
986         }
987         if (si.StdOut != cp->PipeChildStd[1]) {
988           kwsysProcessCleanupDescriptor(&si.StdOut);
989         }
990         if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput) {
991           kwsysProcessCleanupDescriptor(&si.StdErr);
992         }
993 
994         if (!res) {
995           kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
996           kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
997           if (nextStdIn != cp->PipeChildStd[0]) {
998             kwsysProcessCleanupDescriptor(&nextStdIn);
999           }
1000           kwsysProcessCleanup(cp, 1);
1001           return;
1002         }
1003       }
1004     }
1005   }
1006 
1007   /* The parent process does not need the child's pipe ends.  */
1008   for (i = 0; i < 3; ++i) {
1009     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
1010   }
1011 
1012   /* Restore the working directory. */
1013   if (cp->RealWorkingDirectory) {
1014     /* Some platforms specify that the chdir call may be
1015        interrupted.  Repeat the call until it finishes.  */
1016     while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
1017       ;
1018     free(cp->RealWorkingDirectory);
1019     cp->RealWorkingDirectory = 0;
1020   }
1021 
1022   /* All the pipes are now open.  */
1023   cp->PipesLeft = KWSYSPE_PIPE_COUNT;
1024 
1025   /* The process has now started.  */
1026   cp->State = kwsysProcess_State_Executing;
1027   cp->Detached = cp->OptionDetach;
1028 }
1029 
kwsysProcess_Disown(kwsysProcess * cp)1030 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
1031 {
1032   /* Make sure a detached child process is running.  */
1033   if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
1034       cp->TimeoutExpired || cp->Killed) {
1035     return;
1036   }
1037 
1038   /* Close all the pipes safely.  */
1039   kwsysProcessClosePipes(cp);
1040 
1041   /* We will not wait for exit, so cleanup now.  */
1042   kwsysProcessCleanup(cp, 0);
1043 
1044   /* The process has been disowned.  */
1045   cp->State = kwsysProcess_State_Disowned;
1046 }
1047 
1048 typedef struct kwsysProcessWaitData_s
1049 {
1050   int Expired;
1051   int PipeId;
1052   int User;
1053   double* UserTimeout;
1054   kwsysProcessTime TimeoutTime;
1055 } kwsysProcessWaitData;
1056 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1057                                    kwsysProcessWaitData* wd);
1058 
kwsysProcess_WaitForData(kwsysProcess * cp,char ** data,int * length,double * userTimeout)1059 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
1060                              double* userTimeout)
1061 {
1062   kwsysProcessTime userStartTime = { 0, 0 };
1063   kwsysProcessWaitData wd = { 0, kwsysProcess_Pipe_None, 0, 0, { 0, 0 } };
1064   wd.UserTimeout = userTimeout;
1065   /* Make sure we are executing a process.  */
1066   if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
1067       cp->TimeoutExpired) {
1068     return kwsysProcess_Pipe_None;
1069   }
1070 
1071   /* Record the time at which user timeout period starts.  */
1072   if (userTimeout) {
1073     userStartTime = kwsysProcessTimeGetCurrent();
1074   }
1075 
1076   /* Calculate the time at which a timeout will expire, and whether it
1077      is the user or process timeout.  */
1078   wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout, &wd.TimeoutTime);
1079 
1080   /* Data can only be available when pipes are open.  If the process
1081      is not running, cp->PipesLeft will be 0.  */
1082   while (cp->PipesLeft > 0 &&
1083          !kwsysProcessWaitForPipe(cp, data, length, &wd)) {
1084   }
1085 
1086   /* Update the user timeout.  */
1087   if (userTimeout) {
1088     kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
1089     kwsysProcessTime difference =
1090       kwsysProcessTimeSubtract(userEndTime, userStartTime);
1091     double d = kwsysProcessTimeToDouble(difference);
1092     *userTimeout -= d;
1093     if (*userTimeout < 0) {
1094       *userTimeout = 0;
1095     }
1096   }
1097 
1098   /* Check what happened.  */
1099   if (wd.PipeId) {
1100     /* Data are ready on a pipe.  */
1101     return wd.PipeId;
1102   } else if (wd.Expired) {
1103     /* A timeout has expired.  */
1104     if (wd.User) {
1105       /* The user timeout has expired.  It has no time left.  */
1106       return kwsysProcess_Pipe_Timeout;
1107     } else {
1108       /* The process timeout has expired.  Kill the children now.  */
1109       kwsysProcess_Kill(cp);
1110       cp->Killed = 0;
1111       cp->TimeoutExpired = 1;
1112       return kwsysProcess_Pipe_None;
1113     }
1114   } else {
1115     /* No pipes are left open.  */
1116     return kwsysProcess_Pipe_None;
1117   }
1118 }
1119 
kwsysProcessWaitForPipe(kwsysProcess * cp,char ** data,int * length,kwsysProcessWaitData * wd)1120 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1121                                    kwsysProcessWaitData* wd)
1122 {
1123   int i;
1124   kwsysProcessTimeNative timeoutLength;
1125 
1126 #if KWSYSPE_USE_SELECT
1127   int numReady = 0;
1128   int max = -1;
1129   kwsysProcessTimeNative* timeout = 0;
1130 
1131   /* Check for any open pipes with data reported ready by the last
1132      call to select.  According to "man select_tut" we must deal
1133      with all descriptors reported by a call to select before
1134      passing them to another select call.  */
1135   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1136     if (cp->PipeReadEnds[i] >= 0 &&
1137         FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
1138       kwsysProcess_ssize_t n;
1139 
1140       /* We are handling this pipe now.  Remove it from the set.  */
1141       FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1142 
1143       /* The pipe is ready to read without blocking.  Keep trying to
1144          read until the operation is not interrupted.  */
1145       while (((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1146                         KWSYSPE_PIPE_BUFFER_SIZE)) < 0) &&
1147              (errno == EINTR))
1148         ;
1149       if (n > 0) {
1150         /* We have data on this pipe.  */
1151         if (i == KWSYSPE_PIPE_SIGNAL) {
1152           /* A child process has terminated.  */
1153           kwsysProcessDestroy(cp);
1154         } else if (data && length) {
1155           /* Report this data.  */
1156           *data = cp->PipeBuffer;
1157           *length = (int)(n);
1158           switch (i) {
1159             case KWSYSPE_PIPE_STDOUT:
1160               wd->PipeId = kwsysProcess_Pipe_STDOUT;
1161               break;
1162             case KWSYSPE_PIPE_STDERR:
1163               wd->PipeId = kwsysProcess_Pipe_STDERR;
1164               break;
1165           }
1166           return 1;
1167         }
1168       } else if (n < 0 && errno == EAGAIN) {
1169         /* No data are really ready.  The select call lied.  See the
1170            "man select" page on Linux for cases when this occurs.  */
1171       } else {
1172         /* We are done reading from this pipe.  */
1173         kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1174         --cp->PipesLeft;
1175       }
1176     }
1177   }
1178 
1179   /* If we have data, break early.  */
1180   if (wd->PipeId) {
1181     return 1;
1182   }
1183 
1184   /* Make sure the set is empty (it should always be empty here
1185      anyway).  */
1186   FD_ZERO(&cp->PipeSet);
1187 
1188   /* Setup a timeout if required.  */
1189   if (wd->TimeoutTime.tv_sec < 0) {
1190     timeout = 0;
1191   } else {
1192     timeout = &timeoutLength;
1193   }
1194   if (kwsysProcessGetTimeoutLeft(
1195         &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 0)) {
1196     /* Timeout has already expired.  */
1197     wd->Expired = 1;
1198     return 1;
1199   }
1200 
1201   /* Add the pipe reading ends that are still open.  */
1202   max = -1;
1203   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1204     if (cp->PipeReadEnds[i] >= 0) {
1205       FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1206       if (cp->PipeReadEnds[i] > max) {
1207         max = cp->PipeReadEnds[i];
1208       }
1209     }
1210   }
1211 
1212   /* Make sure we have a non-empty set.  */
1213   if (max < 0) {
1214     /* All pipes have closed.  Child has terminated.  */
1215     return 1;
1216   }
1217 
1218   /* Run select to block until data are available.  Repeat call
1219      until it is not interrupted.  */
1220   while (((numReady = select(max + 1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1221          (errno == EINTR))
1222     ;
1223 
1224   /* Check result of select.  */
1225   if (numReady == 0) {
1226     /* Select's timeout expired.  */
1227     wd->Expired = 1;
1228     return 1;
1229   } else if (numReady < 0) {
1230     /* Select returned an error.  Leave the error description in the
1231        pipe buffer.  */
1232     strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1233 
1234     /* Kill the children now.  */
1235     kwsysProcess_Kill(cp);
1236     cp->Killed = 0;
1237     cp->SelectError = 1;
1238   }
1239 
1240   return 0;
1241 #else
1242   /* Poll pipes for data since we do not have select.  */
1243   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1244     if (cp->PipeReadEnds[i] >= 0) {
1245       const int fd = cp->PipeReadEnds[i];
1246       int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1247       if (n > 0) {
1248         /* We have data on this pipe.  */
1249         if (i == KWSYSPE_PIPE_SIGNAL) {
1250           /* A child process has terminated.  */
1251           kwsysProcessDestroy(cp);
1252         } else if (data && length) {
1253           /* Report this data.  */
1254           *data = cp->PipeBuffer;
1255           *length = n;
1256           switch (i) {
1257             case KWSYSPE_PIPE_STDOUT:
1258               wd->PipeId = kwsysProcess_Pipe_STDOUT;
1259               break;
1260             case KWSYSPE_PIPE_STDERR:
1261               wd->PipeId = kwsysProcess_Pipe_STDERR;
1262               break;
1263           };
1264         }
1265         return 1;
1266       } else if (n == 0) /* EOF */
1267       {
1268 /* We are done reading from this pipe.  */
1269 #  if defined(__VMS)
1270         if (!cp->CommandsLeft)
1271 #  endif
1272         {
1273           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1274           --cp->PipesLeft;
1275         }
1276       } else if (n < 0) /* error */
1277       {
1278 #  if defined(__VMS)
1279         if (!cp->CommandsLeft) {
1280           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1281           --cp->PipesLeft;
1282         } else
1283 #  endif
1284           if ((errno != EINTR) && (errno != EAGAIN)) {
1285           strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1286           /* Kill the children now.  */
1287           kwsysProcess_Kill(cp);
1288           cp->Killed = 0;
1289           cp->SelectError = 1;
1290           return 1;
1291         }
1292       }
1293     }
1294   }
1295 
1296   /* If we have data, break early.  */
1297   if (wd->PipeId) {
1298     return 1;
1299   }
1300 
1301   if (kwsysProcessGetTimeoutLeft(
1302         &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 1)) {
1303     /* Timeout has already expired.  */
1304     wd->Expired = 1;
1305     return 1;
1306   }
1307 
1308   /* Sleep a little, try again. */
1309   {
1310     unsigned int msec =
1311       ((timeoutLength.tv_sec * 1000) + (timeoutLength.tv_usec / 1000));
1312     if (msec > 100000) {
1313       msec = 100000; /* do not sleep more than 100 milliseconds at a time */
1314     }
1315     kwsysProcess_usleep(msec);
1316   }
1317   return 0;
1318 #endif
1319 }
1320 
kwsysProcess_WaitForExit(kwsysProcess * cp,double * userTimeout)1321 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1322 {
1323   int prPipe = 0;
1324 
1325   /* Make sure we are executing a process.  */
1326   if (!cp || cp->State != kwsysProcess_State_Executing) {
1327     return 1;
1328   }
1329 
1330   /* Wait for all the pipes to close.  Ignore all data.  */
1331   while ((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) {
1332     if (prPipe == kwsysProcess_Pipe_Timeout) {
1333       return 0;
1334     }
1335   }
1336 
1337   /* Check if there was an error in one of the waitpid calls.  */
1338   if (cp->State == kwsysProcess_State_Error) {
1339     /* The error message is already in its buffer.  Tell
1340        kwsysProcessCleanup to not create it.  */
1341     kwsysProcessCleanup(cp, 0);
1342     return 1;
1343   }
1344 
1345   /* Check whether the child reported an error invoking the process.  */
1346   if (cp->SelectError) {
1347     /* The error message is already in its buffer.  Tell
1348        kwsysProcessCleanup to not create it.  */
1349     kwsysProcessCleanup(cp, 0);
1350     cp->State = kwsysProcess_State_Error;
1351     return 1;
1352   }
1353   /* Determine the outcome.  */
1354   if (cp->Killed) {
1355     /* We killed the child.  */
1356     cp->State = kwsysProcess_State_Killed;
1357   } else if (cp->TimeoutExpired) {
1358     /* The timeout expired.  */
1359     cp->State = kwsysProcess_State_Expired;
1360   } else {
1361     /* The children exited.  Report the outcome of the child processes.  */
1362     for (prPipe = 0; prPipe < cp->NumberOfCommands; ++prPipe) {
1363       cp->ProcessResults[prPipe].ExitCode = cp->CommandExitCodes[prPipe];
1364       if (WIFEXITED(cp->ProcessResults[prPipe].ExitCode)) {
1365         /* The child exited normally.  */
1366         cp->ProcessResults[prPipe].State = kwsysProcess_StateByIndex_Exited;
1367         cp->ProcessResults[prPipe].ExitException = kwsysProcess_Exception_None;
1368         cp->ProcessResults[prPipe].ExitValue =
1369           (int)WEXITSTATUS(cp->ProcessResults[prPipe].ExitCode);
1370       } else if (WIFSIGNALED(cp->ProcessResults[prPipe].ExitCode)) {
1371         /* The child received an unhandled signal.  */
1372         cp->ProcessResults[prPipe].State = kwsysProcess_State_Exception;
1373         kwsysProcessSetExitExceptionByIndex(
1374           cp, (int)WTERMSIG(cp->ProcessResults[prPipe].ExitCode), prPipe);
1375       } else {
1376         /* Error getting the child return code.  */
1377         strcpy(cp->ProcessResults[prPipe].ExitExceptionString,
1378                "Error getting child return code.");
1379         cp->ProcessResults[prPipe].State = kwsysProcess_StateByIndex_Error;
1380       }
1381     }
1382     /* support legacy state status value */
1383     cp->State = cp->ProcessResults[cp->NumberOfCommands - 1].State;
1384   }
1385   /* Normal cleanup.  */
1386   kwsysProcessCleanup(cp, 0);
1387   return 1;
1388 }
1389 
kwsysProcess_Interrupt(kwsysProcess * cp)1390 void kwsysProcess_Interrupt(kwsysProcess* cp)
1391 {
1392   int i;
1393   /* Make sure we are executing a process.  */
1394   if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
1395       cp->Killed) {
1396     return;
1397   }
1398 
1399   /* Interrupt the children.  */
1400   if (cp->CreateProcessGroup) {
1401     if (cp->ForkPIDs) {
1402       for (i = 0; i < cp->NumberOfCommands; ++i) {
1403         /* Make sure the PID is still valid. */
1404         if (cp->ForkPIDs[i]) {
1405           /* The user created a process group for this process.  The group ID
1406              is the process ID for the original process in the group.  */
1407           kill(-cp->ForkPIDs[i], SIGINT);
1408         }
1409       }
1410     }
1411   } else {
1412     /* No process group was created.  Kill our own process group.
1413        NOTE:  While one could argue that we could call kill(cp->ForkPIDs[i],
1414        SIGINT) as a way to still interrupt the process even though it's not in
1415        a special group, this is not an option on Windows.  Therefore, we kill
1416        the current process group for consistency with Windows.  */
1417     kill(0, SIGINT);
1418   }
1419 }
1420 
kwsysProcess_Kill(kwsysProcess * cp)1421 void kwsysProcess_Kill(kwsysProcess* cp)
1422 {
1423   int i;
1424 
1425   /* Make sure we are executing a process.  */
1426   if (!cp || cp->State != kwsysProcess_State_Executing) {
1427     return;
1428   }
1429 
1430   /* First close the child exit report pipe write end to avoid causing a
1431      SIGPIPE when the child terminates and our signal handler tries to
1432      report it after we have already closed the read end.  */
1433   kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1434 
1435 #if !defined(__APPLE__)
1436   /* Close all the pipe read ends.  Do this before killing the
1437      children because Cygwin has problems killing processes that are
1438      blocking to wait for writing to their output pipes.  */
1439   kwsysProcessClosePipes(cp);
1440 #endif
1441 
1442   /* Kill the children.  */
1443   cp->Killed = 1;
1444   for (i = 0; i < cp->NumberOfCommands; ++i) {
1445     int status;
1446     if (cp->ForkPIDs[i]) {
1447       /* Kill the child.  */
1448       kwsysProcessKill(cp->ForkPIDs[i]);
1449 
1450       /* Reap the child.  Keep trying until the call is not
1451          interrupted.  */
1452       while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR))
1453         ;
1454     }
1455   }
1456 
1457 #if defined(__APPLE__)
1458   /* Close all the pipe read ends.  Do this after killing the
1459      children because OS X has problems closing pipe read ends whose
1460      pipes are full and still have an open write end.  */
1461   kwsysProcessClosePipes(cp);
1462 #endif
1463 
1464   cp->CommandsLeft = 0;
1465 }
1466 
1467 /* Call the free() function with a pointer to volatile without causing
1468    compiler warnings.  */
kwsysProcessVolatileFree(volatile void * p)1469 static void kwsysProcessVolatileFree(volatile void* p)
1470 {
1471 /* clang has made it impossible to free memory that points to volatile
1472    without first using special pragmas to disable a warning...  */
1473 #if defined(__clang__) && !defined(__INTEL_COMPILER)
1474 #  pragma clang diagnostic push
1475 #  pragma clang diagnostic ignored "-Wcast-qual"
1476 #endif
1477   free((void*)p); /* The cast will silence most compilers, but not clang.  */
1478 #if defined(__clang__) && !defined(__INTEL_COMPILER)
1479 #  pragma clang diagnostic pop
1480 #endif
1481 }
1482 
1483 /* Initialize a process control structure for kwsysProcess_Execute.  */
kwsysProcessInitialize(kwsysProcess * cp)1484 static int kwsysProcessInitialize(kwsysProcess* cp)
1485 {
1486   int i;
1487   volatile pid_t* oldForkPIDs;
1488   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1489     cp->PipeReadEnds[i] = -1;
1490   }
1491   for (i = 0; i < 3; ++i) {
1492     cp->PipeChildStd[i] = -1;
1493   }
1494   cp->SignalPipe = -1;
1495   cp->SelectError = 0;
1496   cp->StartTime.tv_sec = -1;
1497   cp->StartTime.tv_usec = -1;
1498   cp->TimeoutTime.tv_sec = -1;
1499   cp->TimeoutTime.tv_usec = -1;
1500   cp->TimeoutExpired = 0;
1501   cp->PipesLeft = 0;
1502   cp->CommandsLeft = 0;
1503 #if KWSYSPE_USE_SELECT
1504   FD_ZERO(&cp->PipeSet);
1505 #endif
1506   cp->State = kwsysProcess_State_Starting;
1507   cp->Killed = 0;
1508   cp->ErrorMessage[0] = 0;
1509 
1510   oldForkPIDs = cp->ForkPIDs;
1511   cp->ForkPIDs = (volatile pid_t*)malloc(sizeof(volatile pid_t) *
1512                                          (size_t)(cp->NumberOfCommands));
1513   kwsysProcessVolatileFree(oldForkPIDs);
1514   if (!cp->ForkPIDs) {
1515     return 0;
1516   }
1517   for (i = 0; i < cp->NumberOfCommands; ++i) {
1518     cp->ForkPIDs[i] = 0; /* can't use memset due to volatile */
1519   }
1520 
1521   free(cp->CommandExitCodes);
1522   cp->CommandExitCodes =
1523     (int*)malloc(sizeof(int) * (size_t)(cp->NumberOfCommands));
1524   if (!cp->CommandExitCodes) {
1525     return 0;
1526   }
1527   memset(cp->CommandExitCodes, 0,
1528          sizeof(int) * (size_t)(cp->NumberOfCommands));
1529 
1530   /* Allocate process result information for each process.  */
1531   free(cp->ProcessResults);
1532   cp->ProcessResults = (kwsysProcessResults*)malloc(
1533     sizeof(kwsysProcessResults) * (size_t)(cp->NumberOfCommands));
1534   if (!cp->ProcessResults) {
1535     return 0;
1536   }
1537   memset(cp->ProcessResults, 0,
1538          sizeof(kwsysProcessResults) * (size_t)(cp->NumberOfCommands));
1539   for (i = 0; i < cp->NumberOfCommands; i++) {
1540     cp->ProcessResults[i].ExitException = kwsysProcess_Exception_None;
1541     cp->ProcessResults[i].State = kwsysProcess_StateByIndex_Starting;
1542     cp->ProcessResults[i].ExitCode = 1;
1543     cp->ProcessResults[i].ExitValue = 1;
1544     strcpy(cp->ProcessResults[i].ExitExceptionString, "No exception");
1545   }
1546 
1547   /* Allocate memory to save the real working directory.  */
1548   if (cp->WorkingDirectory) {
1549 #if defined(MAXPATHLEN)
1550     cp->RealWorkingDirectoryLength = MAXPATHLEN;
1551 #elif defined(PATH_MAX)
1552     cp->RealWorkingDirectoryLength = PATH_MAX;
1553 #else
1554     cp->RealWorkingDirectoryLength = 4096;
1555 #endif
1556     cp->RealWorkingDirectory =
1557       (char*)malloc((size_t)(cp->RealWorkingDirectoryLength));
1558     if (!cp->RealWorkingDirectory) {
1559       return 0;
1560     }
1561   }
1562 
1563   return 1;
1564 }
1565 
1566 /* Free all resources used by the given kwsysProcess instance that were
1567    allocated by kwsysProcess_Execute.  */
kwsysProcessCleanup(kwsysProcess * cp,int error)1568 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1569 {
1570   int i;
1571 
1572   if (error) {
1573     /* We are cleaning up due to an error.  Report the error message
1574        if one has not been provided already.  */
1575     if (cp->ErrorMessage[0] == 0) {
1576       strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1577     }
1578 
1579     /* Set the error state.  */
1580     cp->State = kwsysProcess_State_Error;
1581 
1582     /* Kill any children already started.  */
1583     if (cp->ForkPIDs) {
1584       int status;
1585       for (i = 0; i < cp->NumberOfCommands; ++i) {
1586         if (cp->ForkPIDs[i]) {
1587           /* Kill the child.  */
1588           kwsysProcessKill(cp->ForkPIDs[i]);
1589 
1590           /* Reap the child.  Keep trying until the call is not
1591              interrupted.  */
1592           while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1593                  (errno == EINTR))
1594             ;
1595         }
1596       }
1597     }
1598 
1599     /* Restore the working directory.  */
1600     if (cp->RealWorkingDirectory) {
1601       while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
1602         ;
1603     }
1604   }
1605 
1606   /* If not creating a detached child, remove this object from the
1607      global set of process objects that wish to be notified when a
1608      child exits.  */
1609   if (!cp->OptionDetach) {
1610     kwsysProcessesRemove(cp);
1611   }
1612 
1613   /* Free memory.  */
1614   if (cp->ForkPIDs) {
1615     kwsysProcessVolatileFree(cp->ForkPIDs);
1616     cp->ForkPIDs = 0;
1617   }
1618   if (cp->RealWorkingDirectory) {
1619     free(cp->RealWorkingDirectory);
1620     cp->RealWorkingDirectory = 0;
1621   }
1622 
1623   /* Close pipe handles.  */
1624   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1625     kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1626   }
1627   for (i = 0; i < 3; ++i) {
1628     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
1629   }
1630 }
1631 
1632 /* Close the given file descriptor if it is open.  Reset its value to -1.  */
kwsysProcessCleanupDescriptor(int * pfd)1633 static void kwsysProcessCleanupDescriptor(int* pfd)
1634 {
1635   if (pfd && *pfd > 2) {
1636     /* Keep trying to close until it is not interrupted by a
1637      * signal.  */
1638     while ((close(*pfd) < 0) && (errno == EINTR))
1639       ;
1640     *pfd = -1;
1641   }
1642 }
1643 
kwsysProcessClosePipes(kwsysProcess * cp)1644 static void kwsysProcessClosePipes(kwsysProcess* cp)
1645 {
1646   int i;
1647 
1648   /* Close any pipes that are still open.  */
1649   for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
1650     if (cp->PipeReadEnds[i] >= 0) {
1651 #if KWSYSPE_USE_SELECT
1652       /* If the pipe was reported by the last call to select, we must
1653          read from it.  This is needed to satisfy the suggestions from
1654          "man select_tut" and is not needed for the polling
1655          implementation.  Ignore the data.  */
1656       if (FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
1657         /* We are handling this pipe now.  Remove it from the set.  */
1658         FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1659 
1660         /* The pipe is ready to read without blocking.  Keep trying to
1661            read until the operation is not interrupted.  */
1662         while ((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1663                      KWSYSPE_PIPE_BUFFER_SIZE) < 0) &&
1664                (errno == EINTR))
1665           ;
1666       }
1667 #endif
1668 
1669       /* We are done reading from this pipe.  */
1670       kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1671       --cp->PipesLeft;
1672     }
1673   }
1674 }
1675 
kwsysProcessSetNonBlocking(int fd)1676 static int kwsysProcessSetNonBlocking(int fd)
1677 {
1678   int flags = fcntl(fd, F_GETFL);
1679   if (flags >= 0) {
1680     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1681   }
1682   return flags >= 0;
1683 }
1684 
1685 #if defined(__VMS)
1686 int decc$set_child_standard_streams(int fd1, int fd2, int fd3);
1687 #endif
1688 
kwsysProcessCreate(kwsysProcess * cp,int prIndex,kwsysProcessCreateInformation * si)1689 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1690                               kwsysProcessCreateInformation* si)
1691 {
1692   sigset_t mask, old_mask;
1693   int pgidPipe[2];
1694   char tmp;
1695   ssize_t readRes;
1696 
1697   /* Create the error reporting pipe.  */
1698   if (pipe(si->ErrorPipe) < 0) {
1699     return 0;
1700   }
1701 
1702   /* Create a pipe for detecting that the child process has created a process
1703      group and session.  */
1704   if (pipe(pgidPipe) < 0) {
1705     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1706     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1707     return 0;
1708   }
1709 
1710   /* Set close-on-exec flag on the pipe's write end.  */
1711   if (fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
1712       fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0) {
1713     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1714     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1715     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
1716     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
1717     return 0;
1718   }
1719 
1720   /* Block SIGINT / SIGTERM while we start.  The purpose is so that our signal
1721      handler doesn't get called from the child process after the fork and
1722      before the exec, and subsequently start kill()'ing PIDs from ForkPIDs. */
1723   sigemptyset(&mask);
1724   sigaddset(&mask, SIGINT);
1725   sigaddset(&mask, SIGTERM);
1726   if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
1727     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1728     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1729     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
1730     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
1731     return 0;
1732   }
1733 
1734 /* Fork off a child process.  */
1735 #if defined(__VMS)
1736   /* VMS needs vfork and execvp to be in the same function because
1737      they use setjmp/longjmp to run the child startup code in the
1738      parent!  TODO: OptionDetach.  Also
1739      TODO:  CreateProcessGroup.  */
1740   cp->ForkPIDs[prIndex] = vfork();
1741 #else
1742   cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1743 #endif
1744   if (cp->ForkPIDs[prIndex] < 0) {
1745     sigprocmask(SIG_SETMASK, &old_mask, 0);
1746     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1747     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1748     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
1749     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
1750     return 0;
1751   }
1752 
1753   if (cp->ForkPIDs[prIndex] == 0) {
1754 #if defined(__VMS)
1755     /* Specify standard pipes for child process.  */
1756     decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
1757 #else
1758     /* Close the read end of the error reporting / process group
1759        setup pipe.  */
1760     close(si->ErrorPipe[0]);
1761     close(pgidPipe[0]);
1762 
1763     /* Setup the stdin, stdout, and stderr pipes.  */
1764     if (si->StdIn > 0) {
1765       dup2(si->StdIn, 0);
1766     } else if (si->StdIn < 0) {
1767       close(0);
1768     }
1769     if (si->StdOut != 1) {
1770       dup2(si->StdOut, 1);
1771     }
1772     if (si->StdErr != 2) {
1773       dup2(si->StdErr, 2);
1774     }
1775 
1776     /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1777        All other pipe handles will be closed when exec succeeds.  */
1778     fcntl(0, F_SETFD, 0);
1779     fcntl(1, F_SETFD, 0);
1780     fcntl(2, F_SETFD, 0);
1781 
1782     /* Restore all default signal handlers. */
1783     kwsysProcessRestoreDefaultSignalHandlers();
1784 
1785     /* Now that we have restored default signal handling and created the
1786        process group, restore mask.  */
1787     sigprocmask(SIG_SETMASK, &old_mask, 0);
1788 
1789     /* Create new process group.  We use setsid instead of setpgid to avoid
1790        the child getting hung up on signals like SIGTTOU.  (In the real world,
1791        this has been observed where "git svn" ends up calling the "resize"
1792        program which opens /dev/tty.  */
1793     if (cp->CreateProcessGroup && setsid() < 0) {
1794       kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1795     }
1796 #endif
1797 
1798     /* Execute the real process.  If successful, this does not return.  */
1799     execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1800     /* TODO: What does VMS do if the child fails to start?  */
1801     /* TODO: On VMS, how do we put the process in a new group?  */
1802 
1803     /* Failure.  Report error to parent and terminate.  */
1804     kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1805   }
1806 
1807 #if defined(__VMS)
1808   /* Restore the standard pipes of this process.  */
1809   decc$set_child_standard_streams(0, 1, 2);
1810 #endif
1811 
1812   /* We are done with the error reporting pipe and process group setup pipe
1813      write end.  */
1814   kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1815   kwsysProcessCleanupDescriptor(&pgidPipe[1]);
1816 
1817   /* Make sure the child is in the process group before we proceed.  This
1818      avoids race conditions with calls to the kill function that we make for
1819      signalling process groups.  */
1820   while ((readRes = read(pgidPipe[0], &tmp, 1)) > 0)
1821     ;
1822   if (readRes < 0) {
1823     sigprocmask(SIG_SETMASK, &old_mask, 0);
1824     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1825     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
1826     return 0;
1827   }
1828   kwsysProcessCleanupDescriptor(&pgidPipe[0]);
1829 
1830   /* Unmask signals.  */
1831   if (sigprocmask(SIG_SETMASK, &old_mask, 0) < 0) {
1832     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1833     return 0;
1834   }
1835 
1836   /* A child has been created.  */
1837   ++cp->CommandsLeft;
1838 
1839   /* Block until the child's exec call succeeds and closes the error
1840      pipe or writes data to the pipe to report an error.  */
1841   {
1842     kwsysProcess_ssize_t total = 0;
1843     kwsysProcess_ssize_t n = 1;
1844     /* Read the entire error message up to the length of our buffer.  */
1845     while (total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0) {
1846       /* Keep trying to read until the operation is not interrupted.  */
1847       while (((n = read(si->ErrorPipe[0], cp->ErrorMessage + total,
1848                         (size_t)(KWSYSPE_PIPE_BUFFER_SIZE - total))) < 0) &&
1849              (errno == EINTR))
1850         ;
1851       if (n > 0) {
1852         total += n;
1853       }
1854     }
1855 
1856     /* We are done with the error reporting pipe read end.  */
1857     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1858 
1859     if (total > 0) {
1860       /* The child failed to execute the process.  */
1861       return 0;
1862     }
1863   }
1864 
1865   return 1;
1866 }
1867 
kwsysProcessDestroy(kwsysProcess * cp)1868 static void kwsysProcessDestroy(kwsysProcess* cp)
1869 {
1870   /* A child process has terminated.  Reap it if it is one handled by
1871      this object.  */
1872   int i;
1873   /* Temporarily disable signals that access ForkPIDs.  We don't want them to
1874      read a reaped PID, and writes to ForkPIDs are not atomic.  */
1875   sigset_t mask, old_mask;
1876   sigemptyset(&mask);
1877   sigaddset(&mask, SIGINT);
1878   sigaddset(&mask, SIGTERM);
1879   if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
1880     return;
1881   }
1882 
1883   for (i = 0; i < cp->NumberOfCommands; ++i) {
1884     if (cp->ForkPIDs[i]) {
1885       int result;
1886       while (((result = waitpid(cp->ForkPIDs[i], &cp->CommandExitCodes[i],
1887                                 WNOHANG)) < 0) &&
1888              (errno == EINTR))
1889         ;
1890       if (result > 0) {
1891         /* This child has termianted.  */
1892         cp->ForkPIDs[i] = 0;
1893         if (--cp->CommandsLeft == 0) {
1894           /* All children have terminated.  Close the signal pipe
1895              write end so that no more notifications are sent to this
1896              object.  */
1897           kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1898 
1899           /* TODO: Once the children have terminated, switch
1900              WaitForData to use a non-blocking read to get the
1901              rest of the data from the pipe.  This is needed when
1902              grandchildren keep the output pipes open.  */
1903         }
1904       } else if (result < 0 && cp->State != kwsysProcess_State_Error) {
1905         /* Unexpected error.  Report the first time this happens.  */
1906         strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1907         cp->State = kwsysProcess_State_Error;
1908       }
1909     }
1910   }
1911 
1912   /* Re-enable signals.  */
1913   sigprocmask(SIG_SETMASK, &old_mask, 0);
1914 }
1915 
kwsysProcessSetupOutputPipeFile(int * p,const char * name)1916 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1917 {
1918   int fout;
1919   if (!name) {
1920     return 1;
1921   }
1922 
1923   /* Close the existing descriptor.  */
1924   kwsysProcessCleanupDescriptor(p);
1925 
1926   /* Open a file for the pipe to write.  */
1927   if ((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
1928     return 0;
1929   }
1930 
1931   /* Set close-on-exec flag on the pipe's end.  */
1932   if (fcntl(fout, F_SETFD, FD_CLOEXEC) < 0) {
1933     close(fout);
1934     return 0;
1935   }
1936 
1937   /* Assign the replacement descriptor.  */
1938   *p = fout;
1939   return 1;
1940 }
1941 
kwsysProcessSetupOutputPipeNative(int * p,int des[2])1942 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1943 {
1944   /* Close the existing descriptor.  */
1945   kwsysProcessCleanupDescriptor(p);
1946 
1947   /* Set close-on-exec flag on the pipe's ends.  The proper end will
1948      be dup2-ed into the standard descriptor number after fork but
1949      before exec.  */
1950   if ((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1951       (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0)) {
1952     return 0;
1953   }
1954 
1955   /* Assign the replacement descriptor.  */
1956   *p = des[1];
1957   return 1;
1958 }
1959 
1960 /* Get the time at which either the process or user timeout will
1961    expire.  Returns 1 if the user timeout is first, and 0 otherwise.  */
kwsysProcessGetTimeoutTime(kwsysProcess * cp,double * userTimeout,kwsysProcessTime * timeoutTime)1962 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1963                                       kwsysProcessTime* timeoutTime)
1964 {
1965   /* The first time this is called, we need to calculate the time at
1966      which the child will timeout.  */
1967   if (cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0) {
1968     kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1969     cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1970   }
1971 
1972   /* Start with process timeout.  */
1973   *timeoutTime = cp->TimeoutTime;
1974 
1975   /* Check if the user timeout is earlier.  */
1976   if (userTimeout) {
1977     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1978     kwsysProcessTime userTimeoutLength =
1979       kwsysProcessTimeFromDouble(*userTimeout);
1980     kwsysProcessTime userTimeoutTime =
1981       kwsysProcessTimeAdd(currentTime, userTimeoutLength);
1982     if (timeoutTime->tv_sec < 0 ||
1983         kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) {
1984       *timeoutTime = userTimeoutTime;
1985       return 1;
1986     }
1987   }
1988   return 0;
1989 }
1990 
1991 /* Get the length of time before the given timeout time arrives.
1992    Returns 1 if the time has already arrived, and 0 otherwise.  */
kwsysProcessGetTimeoutLeft(kwsysProcessTime * timeoutTime,double * userTimeout,kwsysProcessTimeNative * timeoutLength,int zeroIsExpired)1993 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1994                                       double* userTimeout,
1995                                       kwsysProcessTimeNative* timeoutLength,
1996                                       int zeroIsExpired)
1997 {
1998   if (timeoutTime->tv_sec < 0) {
1999     /* No timeout time has been requested.  */
2000     return 0;
2001   } else {
2002     /* Calculate the remaining time.  */
2003     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
2004     kwsysProcessTime timeLeft =
2005       kwsysProcessTimeSubtract(*timeoutTime, currentTime);
2006     if (timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0) {
2007       /* Caller has explicitly requested a zero timeout.  */
2008       timeLeft.tv_sec = 0;
2009       timeLeft.tv_usec = 0;
2010     }
2011 
2012     if (timeLeft.tv_sec < 0 ||
2013         (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) {
2014       /* Timeout has already expired.  */
2015       return 1;
2016     } else {
2017       /* There is some time left.  */
2018       timeoutLength->tv_sec = timeLeft.tv_sec;
2019       timeoutLength->tv_usec = timeLeft.tv_usec;
2020       return 0;
2021     }
2022   }
2023 }
2024 
kwsysProcessTimeGetCurrent(void)2025 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
2026 {
2027   kwsysProcessTime current;
2028   kwsysProcessTimeNative current_native;
2029 #if KWSYS_C_HAS_CLOCK_GETTIME_MONOTONIC
2030   struct timespec current_timespec;
2031   clock_gettime(CLOCK_MONOTONIC, &current_timespec);
2032 
2033   current_native.tv_sec = current_timespec.tv_sec;
2034   current_native.tv_usec = current_timespec.tv_nsec / 1000;
2035 #else
2036   gettimeofday(&current_native, 0);
2037 #endif
2038   current.tv_sec = (long)current_native.tv_sec;
2039   current.tv_usec = (long)current_native.tv_usec;
2040   return current;
2041 }
2042 
kwsysProcessTimeToDouble(kwsysProcessTime t)2043 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
2044 {
2045   return (double)t.tv_sec + (double)(t.tv_usec) * 0.000001;
2046 }
2047 
kwsysProcessTimeFromDouble(double d)2048 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
2049 {
2050   kwsysProcessTime t;
2051   t.tv_sec = (long)d;
2052   t.tv_usec = (long)((d - (double)(t.tv_sec)) * 1000000);
2053   return t;
2054 }
2055 
kwsysProcessTimeLess(kwsysProcessTime in1,kwsysProcessTime in2)2056 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
2057 {
2058   return ((in1.tv_sec < in2.tv_sec) ||
2059           ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
2060 }
2061 
kwsysProcessTimeAdd(kwsysProcessTime in1,kwsysProcessTime in2)2062 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
2063                                             kwsysProcessTime in2)
2064 {
2065   kwsysProcessTime out;
2066   out.tv_sec = in1.tv_sec + in2.tv_sec;
2067   out.tv_usec = in1.tv_usec + in2.tv_usec;
2068   if (out.tv_usec >= 1000000) {
2069     out.tv_usec -= 1000000;
2070     out.tv_sec += 1;
2071   }
2072   return out;
2073 }
2074 
kwsysProcessTimeSubtract(kwsysProcessTime in1,kwsysProcessTime in2)2075 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
2076                                                  kwsysProcessTime in2)
2077 {
2078   kwsysProcessTime out;
2079   out.tv_sec = in1.tv_sec - in2.tv_sec;
2080   out.tv_usec = in1.tv_usec - in2.tv_usec;
2081   if (out.tv_usec < 0) {
2082     out.tv_usec += 1000000;
2083     out.tv_sec -= 1;
2084   }
2085   return out;
2086 }
2087 
2088 #define KWSYSPE_CASE(type, str)                                               \
2089   cp->ProcessResults[idx].ExitException = kwsysProcess_Exception_##type;      \
2090   strcpy(cp->ProcessResults[idx].ExitExceptionString, str)
kwsysProcessSetExitExceptionByIndex(kwsysProcess * cp,int sig,int idx)2091 static void kwsysProcessSetExitExceptionByIndex(kwsysProcess* cp, int sig,
2092                                                 int idx)
2093 {
2094   switch (sig) {
2095 #ifdef SIGSEGV
2096     case SIGSEGV:
2097       KWSYSPE_CASE(Fault, "Segmentation fault");
2098       break;
2099 #endif
2100 #ifdef SIGBUS
2101 #  if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2102     case SIGBUS:
2103       KWSYSPE_CASE(Fault, "Bus error");
2104       break;
2105 #  endif
2106 #endif
2107 #ifdef SIGFPE
2108     case SIGFPE:
2109       KWSYSPE_CASE(Numerical, "Floating-point exception");
2110       break;
2111 #endif
2112 #ifdef SIGILL
2113     case SIGILL:
2114       KWSYSPE_CASE(Illegal, "Illegal instruction");
2115       break;
2116 #endif
2117 #ifdef SIGINT
2118     case SIGINT:
2119       KWSYSPE_CASE(Interrupt, "User interrupt");
2120       break;
2121 #endif
2122 #ifdef SIGABRT
2123     case SIGABRT:
2124       KWSYSPE_CASE(Other, "Child aborted");
2125       break;
2126 #endif
2127 #ifdef SIGKILL
2128     case SIGKILL:
2129       KWSYSPE_CASE(Other, "Child killed");
2130       break;
2131 #endif
2132 #ifdef SIGTERM
2133     case SIGTERM:
2134       KWSYSPE_CASE(Other, "Child terminated");
2135       break;
2136 #endif
2137 #ifdef SIGHUP
2138     case SIGHUP:
2139       KWSYSPE_CASE(Other, "SIGHUP");
2140       break;
2141 #endif
2142 #ifdef SIGQUIT
2143     case SIGQUIT:
2144       KWSYSPE_CASE(Other, "SIGQUIT");
2145       break;
2146 #endif
2147 #ifdef SIGTRAP
2148     case SIGTRAP:
2149       KWSYSPE_CASE(Other, "SIGTRAP");
2150       break;
2151 #endif
2152 #ifdef SIGIOT
2153 #  if !defined(SIGABRT) || SIGIOT != SIGABRT
2154     case SIGIOT:
2155       KWSYSPE_CASE(Other, "SIGIOT");
2156       break;
2157 #  endif
2158 #endif
2159 #ifdef SIGUSR1
2160     case SIGUSR1:
2161       KWSYSPE_CASE(Other, "SIGUSR1");
2162       break;
2163 #endif
2164 #ifdef SIGUSR2
2165     case SIGUSR2:
2166       KWSYSPE_CASE(Other, "SIGUSR2");
2167       break;
2168 #endif
2169 #ifdef SIGPIPE
2170     case SIGPIPE:
2171       KWSYSPE_CASE(Other, "SIGPIPE");
2172       break;
2173 #endif
2174 #ifdef SIGALRM
2175     case SIGALRM:
2176       KWSYSPE_CASE(Other, "SIGALRM");
2177       break;
2178 #endif
2179 #ifdef SIGSTKFLT
2180     case SIGSTKFLT:
2181       KWSYSPE_CASE(Other, "SIGSTKFLT");
2182       break;
2183 #endif
2184 #ifdef SIGCHLD
2185     case SIGCHLD:
2186       KWSYSPE_CASE(Other, "SIGCHLD");
2187       break;
2188 #elif defined(SIGCLD)
2189     case SIGCLD:
2190       KWSYSPE_CASE(Other, "SIGCLD");
2191       break;
2192 #endif
2193 #ifdef SIGCONT
2194     case SIGCONT:
2195       KWSYSPE_CASE(Other, "SIGCONT");
2196       break;
2197 #endif
2198 #ifdef SIGSTOP
2199     case SIGSTOP:
2200       KWSYSPE_CASE(Other, "SIGSTOP");
2201       break;
2202 #endif
2203 #ifdef SIGTSTP
2204     case SIGTSTP:
2205       KWSYSPE_CASE(Other, "SIGTSTP");
2206       break;
2207 #endif
2208 #ifdef SIGTTIN
2209     case SIGTTIN:
2210       KWSYSPE_CASE(Other, "SIGTTIN");
2211       break;
2212 #endif
2213 #ifdef SIGTTOU
2214     case SIGTTOU:
2215       KWSYSPE_CASE(Other, "SIGTTOU");
2216       break;
2217 #endif
2218 #ifdef SIGURG
2219     case SIGURG:
2220       KWSYSPE_CASE(Other, "SIGURG");
2221       break;
2222 #endif
2223 #ifdef SIGXCPU
2224     case SIGXCPU:
2225       KWSYSPE_CASE(Other, "SIGXCPU");
2226       break;
2227 #endif
2228 #ifdef SIGXFSZ
2229     case SIGXFSZ:
2230       KWSYSPE_CASE(Other, "SIGXFSZ");
2231       break;
2232 #endif
2233 #ifdef SIGVTALRM
2234     case SIGVTALRM:
2235       KWSYSPE_CASE(Other, "SIGVTALRM");
2236       break;
2237 #endif
2238 #ifdef SIGPROF
2239     case SIGPROF:
2240       KWSYSPE_CASE(Other, "SIGPROF");
2241       break;
2242 #endif
2243 #ifdef SIGWINCH
2244     case SIGWINCH:
2245       KWSYSPE_CASE(Other, "SIGWINCH");
2246       break;
2247 #endif
2248 #ifdef SIGPOLL
2249     case SIGPOLL:
2250       KWSYSPE_CASE(Other, "SIGPOLL");
2251       break;
2252 #endif
2253 #ifdef SIGIO
2254 #  if !defined(SIGPOLL) || SIGIO != SIGPOLL
2255     case SIGIO:
2256       KWSYSPE_CASE(Other, "SIGIO");
2257       break;
2258 #  endif
2259 #endif
2260 #ifdef SIGPWR
2261     case SIGPWR:
2262       KWSYSPE_CASE(Other, "SIGPWR");
2263       break;
2264 #endif
2265 #ifdef SIGSYS
2266     case SIGSYS:
2267       KWSYSPE_CASE(Other, "SIGSYS");
2268       break;
2269 #endif
2270 #ifdef SIGUNUSED
2271 #  if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2272     case SIGUNUSED:
2273       KWSYSPE_CASE(Other, "SIGUNUSED");
2274       break;
2275 #  endif
2276 #endif
2277     default:
2278       cp->ProcessResults[idx].ExitException = kwsysProcess_Exception_Other;
2279       sprintf(cp->ProcessResults[idx].ExitExceptionString, "Signal %d", sig);
2280       break;
2281   }
2282 }
2283 #undef KWSYSPE_CASE
2284 
2285 /* When the child process encounters an error before its program is
2286    invoked, this is called to report the error to the parent and
2287    exit.  */
kwsysProcessChildErrorExit(int errorPipe)2288 static void kwsysProcessChildErrorExit(int errorPipe)
2289 {
2290   /* Construct the error message.  */
2291   char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2292   kwsysProcess_ssize_t result;
2293   strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2294   buffer[KWSYSPE_PIPE_BUFFER_SIZE - 1] = '\0';
2295 
2296   /* Report the error to the parent through the special pipe.  */
2297   result = write(errorPipe, buffer, strlen(buffer));
2298   (void)result;
2299 
2300   /* Terminate without cleanup.  */
2301   _exit(1);
2302 }
2303 
2304 /* Restores all signal handlers to their default values.  */
kwsysProcessRestoreDefaultSignalHandlers(void)2305 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2306 {
2307   struct sigaction act;
2308   memset(&act, 0, sizeof(struct sigaction));
2309   act.sa_handler = SIG_DFL;
2310 #ifdef SIGHUP
2311   sigaction(SIGHUP, &act, 0);
2312 #endif
2313 #ifdef SIGINT
2314   sigaction(SIGINT, &act, 0);
2315 #endif
2316 #ifdef SIGQUIT
2317   sigaction(SIGQUIT, &act, 0);
2318 #endif
2319 #ifdef SIGILL
2320   sigaction(SIGILL, &act, 0);
2321 #endif
2322 #ifdef SIGTRAP
2323   sigaction(SIGTRAP, &act, 0);
2324 #endif
2325 #ifdef SIGABRT
2326   sigaction(SIGABRT, &act, 0);
2327 #endif
2328 #ifdef SIGIOT
2329   sigaction(SIGIOT, &act, 0);
2330 #endif
2331 #ifdef SIGBUS
2332   sigaction(SIGBUS, &act, 0);
2333 #endif
2334 #ifdef SIGFPE
2335   sigaction(SIGFPE, &act, 0);
2336 #endif
2337 #ifdef SIGUSR1
2338   sigaction(SIGUSR1, &act, 0);
2339 #endif
2340 #ifdef SIGSEGV
2341   sigaction(SIGSEGV, &act, 0);
2342 #endif
2343 #ifdef SIGUSR2
2344   sigaction(SIGUSR2, &act, 0);
2345 #endif
2346 #ifdef SIGPIPE
2347   sigaction(SIGPIPE, &act, 0);
2348 #endif
2349 #ifdef SIGALRM
2350   sigaction(SIGALRM, &act, 0);
2351 #endif
2352 #ifdef SIGTERM
2353   sigaction(SIGTERM, &act, 0);
2354 #endif
2355 #ifdef SIGSTKFLT
2356   sigaction(SIGSTKFLT, &act, 0);
2357 #endif
2358 #ifdef SIGCLD
2359   sigaction(SIGCLD, &act, 0);
2360 #endif
2361 #ifdef SIGCHLD
2362   sigaction(SIGCHLD, &act, 0);
2363 #endif
2364 #ifdef SIGCONT
2365   sigaction(SIGCONT, &act, 0);
2366 #endif
2367 #ifdef SIGTSTP
2368   sigaction(SIGTSTP, &act, 0);
2369 #endif
2370 #ifdef SIGTTIN
2371   sigaction(SIGTTIN, &act, 0);
2372 #endif
2373 #ifdef SIGTTOU
2374   sigaction(SIGTTOU, &act, 0);
2375 #endif
2376 #ifdef SIGURG
2377   sigaction(SIGURG, &act, 0);
2378 #endif
2379 #ifdef SIGXCPU
2380   sigaction(SIGXCPU, &act, 0);
2381 #endif
2382 #ifdef SIGXFSZ
2383   sigaction(SIGXFSZ, &act, 0);
2384 #endif
2385 #ifdef SIGVTALRM
2386   sigaction(SIGVTALRM, &act, 0);
2387 #endif
2388 #ifdef SIGPROF
2389   sigaction(SIGPROF, &act, 0);
2390 #endif
2391 #ifdef SIGWINCH
2392   sigaction(SIGWINCH, &act, 0);
2393 #endif
2394 #ifdef SIGPOLL
2395   sigaction(SIGPOLL, &act, 0);
2396 #endif
2397 #ifdef SIGIO
2398   sigaction(SIGIO, &act, 0);
2399 #endif
2400 #ifdef SIGPWR
2401   sigaction(SIGPWR, &act, 0);
2402 #endif
2403 #ifdef SIGSYS
2404   sigaction(SIGSYS, &act, 0);
2405 #endif
2406 #ifdef SIGUNUSED
2407   sigaction(SIGUNUSED, &act, 0);
2408 #endif
2409 }
2410 
kwsysProcessExit(void)2411 static void kwsysProcessExit(void)
2412 {
2413   _exit(0);
2414 }
2415 
2416 #if !defined(__VMS)
kwsysProcessFork(kwsysProcess * cp,kwsysProcessCreateInformation * si)2417 static pid_t kwsysProcessFork(kwsysProcess* cp,
2418                               kwsysProcessCreateInformation* si)
2419 {
2420   /* Create a detached process if requested.  */
2421   if (cp->OptionDetach) {
2422     /* Create an intermediate process.  */
2423     pid_t middle_pid = fork();
2424     if (middle_pid < 0) {
2425       /* Fork failed.  Return as if we were not detaching.  */
2426       return middle_pid;
2427     } else if (middle_pid == 0) {
2428       /* This is the intermediate process.  Create the real child.  */
2429       pid_t child_pid = fork();
2430       if (child_pid == 0) {
2431         /* This is the real child process.  There is nothing to do here.  */
2432         return 0;
2433       } else {
2434         /* Use the error pipe to report the pid to the real parent.  */
2435         while ((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2436                (errno == EINTR))
2437           ;
2438 
2439         /* Exit without cleanup.  The parent holds all resources.  */
2440         kwsysProcessExit();
2441         return 0; /* Never reached, but avoids SunCC warning.  */
2442       }
2443     } else {
2444       /* This is the original parent process.  The intermediate
2445          process will use the error pipe to report the pid of the
2446          detached child.  */
2447       pid_t child_pid;
2448       int status;
2449       while ((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2450              (errno == EINTR))
2451         ;
2452 
2453       /* Wait for the intermediate process to exit and clean it up.  */
2454       while ((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR))
2455         ;
2456       return child_pid;
2457     }
2458   } else {
2459     /* Not creating a detached process.  Use normal fork.  */
2460     return fork();
2461   }
2462 }
2463 #endif
2464 
2465 /* We try to obtain process information by invoking the ps command.
2466    Here we define the command to call on each platform and the
2467    corresponding parsing format string.  The parsing format should
2468    have two integers to store: the pid and then the ppid.  */
2469 #if defined(__linux__) || defined(__APPLE__) || (defined(__FreeBSD__)||defined(__DragonFly__)) ||       \
2470   defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
2471 #  define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2472 #  define KWSYSPE_PS_FORMAT "%d %d\n"
2473 #elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */
2474 #  define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
2475 #  define KWSYSPE_PS_FORMAT "%d %d\n"
2476 #elif defined(__hpux) || defined(__sun__) || defined(__sgi) ||                \
2477   defined(_AIX) || defined(__sparc)
2478 #  define KWSYSPE_PS_COMMAND "ps -ef"
2479 #  define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2480 #elif defined(__QNX__)
2481 #  define KWSYSPE_PS_COMMAND "ps -Af"
2482 #  define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
2483 #elif defined(__CYGWIN__)
2484 #  define KWSYSPE_PS_COMMAND "ps aux"
2485 #  define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2486 #endif
2487 
kwsysProcess_KillPID(unsigned long process_id)2488 void kwsysProcess_KillPID(unsigned long process_id)
2489 {
2490   kwsysProcessKill((pid_t)process_id);
2491 }
2492 
kwsysProcessKill(pid_t process_id)2493 static void kwsysProcessKill(pid_t process_id)
2494 {
2495 #if defined(__linux__) || defined(__CYGWIN__)
2496   DIR* procdir;
2497 #endif
2498 
2499   /* Suspend the process to be sure it will not create more children.  */
2500   kill(process_id, SIGSTOP);
2501 
2502 #if defined(__CYGWIN__)
2503   /* Some Cygwin versions seem to need help here.  Give up our time slice
2504      so that the child can process SIGSTOP before we send SIGKILL.  */
2505   usleep(1);
2506 #endif
2507 
2508 /* Kill all children if we can find them.  */
2509 #if defined(__linux__) || defined(__CYGWIN__)
2510   /* First try using the /proc filesystem.  */
2511   if ((procdir = opendir("/proc")) != NULL) {
2512 #  if defined(MAXPATHLEN)
2513     char fname[MAXPATHLEN];
2514 #  elif defined(PATH_MAX)
2515     char fname[PATH_MAX];
2516 #  else
2517     char fname[4096];
2518 #  endif
2519     char buffer[KWSYSPE_PIPE_BUFFER_SIZE + 1];
2520     struct dirent* d;
2521 
2522     /* Each process has a directory in /proc whose name is the pid.
2523        Within this directory is a file called stat that has the
2524        following format:
2525 
2526          pid (command line) status ppid ...
2527 
2528        We want to get the ppid for all processes.  Those that have
2529        process_id as their parent should be recursively killed.  */
2530     for (d = readdir(procdir); d; d = readdir(procdir)) {
2531       int pid;
2532       if (sscanf(d->d_name, "%d", &pid) == 1 && pid != 0) {
2533         struct stat finfo;
2534         sprintf(fname, "/proc/%d/stat", pid);
2535         if (stat(fname, &finfo) == 0) {
2536           FILE* f = fopen(fname, "r");
2537           if (f) {
2538             size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2539             fclose(f);
2540             buffer[nread] = '\0';
2541             if (nread > 0) {
2542               const char* rparen = strrchr(buffer, ')');
2543               int ppid;
2544               if (rparen && (sscanf(rparen + 1, "%*s %d", &ppid) == 1)) {
2545                 if (ppid == process_id) {
2546                   /* Recursively kill this child and its children.  */
2547                   kwsysProcessKill(pid);
2548                 }
2549               }
2550             }
2551           }
2552         }
2553       }
2554     }
2555     closedir(procdir);
2556   } else
2557 #endif
2558   {
2559 #if defined(KWSYSPE_PS_COMMAND)
2560     /* Try running "ps" to get the process information.  */
2561     FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2562 
2563     /* Make sure the process started and provided a valid header.  */
2564     if (ps && fscanf(ps, "%*[^\n]\n") != EOF) {
2565       /* Look for processes whose parent is the process being killed.  */
2566       int pid, ppid;
2567       while (fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2) {
2568         if (ppid == process_id) {
2569           /* Recursively kill this child and its children.  */
2570           kwsysProcessKill(pid);
2571         }
2572       }
2573     }
2574 
2575     /* We are done with the ps process.  */
2576     if (ps) {
2577       pclose(ps);
2578     }
2579 #endif
2580   }
2581 
2582   /* Kill the process.  */
2583   kill(process_id, SIGKILL);
2584 
2585 #if defined(__APPLE__)
2586   /* On OS X 10.3 the above SIGSTOP occasionally prevents the SIGKILL
2587      from working.  Just in case, we resume the child and kill it
2588      again.  There is a small race condition in this obscure case.  If
2589      the child manages to fork again between these two signals, we
2590      will not catch its children.  */
2591   kill(process_id, SIGCONT);
2592   kill(process_id, SIGKILL);
2593 #endif
2594 }
2595 
2596 #if defined(__VMS)
2597 int decc$feature_get_index(const char* name);
2598 int decc$feature_set_value(int index, int mode, int value);
kwsysProcessSetVMSFeature(const char * name,int value)2599 static int kwsysProcessSetVMSFeature(const char* name, int value)
2600 {
2601   int i;
2602   errno = 0;
2603   i = decc$feature_get_index(name);
2604   return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
2605 }
2606 #endif
2607 
2608 /* Global set of executing processes for use by the signal handler.
2609    This global instance will be zero-initialized by the compiler.  */
2610 typedef struct kwsysProcessInstances_s
2611 {
2612   int Count;
2613   int Size;
2614   kwsysProcess** Processes;
2615 } kwsysProcessInstances;
2616 static kwsysProcessInstances kwsysProcesses;
2617 
2618 /* The old SIGCHLD / SIGINT / SIGTERM handlers.  */
2619 static struct sigaction kwsysProcessesOldSigChldAction;
2620 static struct sigaction kwsysProcessesOldSigIntAction;
2621 static struct sigaction kwsysProcessesOldSigTermAction;
2622 
kwsysProcessesUpdate(kwsysProcessInstances * newProcesses)2623 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2624 {
2625   /* Block signals while we update the set of pipes to check.
2626      TODO: sigprocmask is undefined for threaded apps.  See
2627      pthread_sigmask.  */
2628   sigset_t newset;
2629   sigset_t oldset;
2630   sigemptyset(&newset);
2631   sigaddset(&newset, SIGCHLD);
2632   sigaddset(&newset, SIGINT);
2633   sigaddset(&newset, SIGTERM);
2634   sigprocmask(SIG_BLOCK, &newset, &oldset);
2635 
2636   /* Store the new set in that seen by the signal handler.  */
2637   kwsysProcesses = *newProcesses;
2638 
2639   /* Restore the signal mask to the previous setting.  */
2640   sigprocmask(SIG_SETMASK, &oldset, 0);
2641 }
2642 
kwsysProcessesAdd(kwsysProcess * cp)2643 static int kwsysProcessesAdd(kwsysProcess* cp)
2644 {
2645   /* Create a pipe through which the signal handler can notify the
2646      given process object that a child has exited.  */
2647   {
2648     /* Create the pipe.  */
2649     int p[2];
2650     if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
2651       return 0;
2652     }
2653 
2654     /* Store the pipes now to be sure they are cleaned up later.  */
2655     cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2656     cp->SignalPipe = p[1];
2657 
2658     /* Switch the pipe to non-blocking mode so that reading a byte can
2659        be an atomic test-and-set.  */
2660     if (!kwsysProcessSetNonBlocking(p[0]) ||
2661         !kwsysProcessSetNonBlocking(p[1])) {
2662       return 0;
2663     }
2664 
2665     /* The children do not need this pipe.  Set close-on-exec flag on
2666        the pipe's ends.  */
2667     if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2668         (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
2669       return 0;
2670     }
2671   }
2672 
2673   /* Attempt to add the given signal pipe to the signal handler set.  */
2674   {
2675 
2676     /* Make sure there is enough space for the new signal pipe.  */
2677     kwsysProcessInstances oldProcesses = kwsysProcesses;
2678     kwsysProcessInstances newProcesses = oldProcesses;
2679     if (oldProcesses.Count == oldProcesses.Size) {
2680       /* Start with enough space for a small number of process instances
2681          and double the size each time more is needed.  */
2682       newProcesses.Size = oldProcesses.Size ? oldProcesses.Size * 2 : 4;
2683 
2684       /* Try allocating the new block of memory.  */
2685       if ((newProcesses.Processes = ((kwsysProcess**)malloc(
2686              (size_t)(newProcesses.Size) * sizeof(kwsysProcess*))))) {
2687         /* Copy the old pipe set to the new memory.  */
2688         if (oldProcesses.Count > 0) {
2689           memcpy(newProcesses.Processes, oldProcesses.Processes,
2690                  ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
2691         }
2692       } else {
2693         /* Failed to allocate memory for the new signal pipe set.  */
2694         return 0;
2695       }
2696     }
2697 
2698     /* Append the new signal pipe to the set.  */
2699     newProcesses.Processes[newProcesses.Count++] = cp;
2700 
2701     /* Store the new set in that seen by the signal handler.  */
2702     kwsysProcessesUpdate(&newProcesses);
2703 
2704     /* Free the original pipes if new ones were allocated.  */
2705     if (newProcesses.Processes != oldProcesses.Processes) {
2706       free(oldProcesses.Processes);
2707     }
2708 
2709     /* If this is the first process, enable the signal handler.  */
2710     if (newProcesses.Count == 1) {
2711       /* Install our handler for SIGCHLD.  Repeat call until it is not
2712          interrupted.  */
2713       struct sigaction newSigAction;
2714       memset(&newSigAction, 0, sizeof(struct sigaction));
2715 #if KWSYSPE_USE_SIGINFO
2716       newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
2717       newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2718 #  ifdef SA_RESTART
2719       newSigAction.sa_flags |= SA_RESTART;
2720 #  endif
2721 #else
2722       newSigAction.sa_handler = kwsysProcessesSignalHandler;
2723       newSigAction.sa_flags = SA_NOCLDSTOP;
2724 #endif
2725       sigemptyset(&newSigAction.sa_mask);
2726       while ((sigaction(SIGCHLD, &newSigAction,
2727                         &kwsysProcessesOldSigChldAction) < 0) &&
2728              (errno == EINTR))
2729         ;
2730 
2731       /* Install our handler for SIGINT / SIGTERM.  Repeat call until
2732          it is not interrupted.  */
2733       sigemptyset(&newSigAction.sa_mask);
2734       sigaddset(&newSigAction.sa_mask, SIGTERM);
2735       while ((sigaction(SIGINT, &newSigAction,
2736                         &kwsysProcessesOldSigIntAction) < 0) &&
2737              (errno == EINTR))
2738         ;
2739 
2740       sigemptyset(&newSigAction.sa_mask);
2741       sigaddset(&newSigAction.sa_mask, SIGINT);
2742       while ((sigaction(SIGTERM, &newSigAction,
2743                         &kwsysProcessesOldSigIntAction) < 0) &&
2744              (errno == EINTR))
2745         ;
2746     }
2747   }
2748 
2749   return 1;
2750 }
2751 
kwsysProcessesRemove(kwsysProcess * cp)2752 static void kwsysProcessesRemove(kwsysProcess* cp)
2753 {
2754   /* Attempt to remove the given signal pipe from the signal handler set.  */
2755   {
2756     /* Find the given process in the set.  */
2757     kwsysProcessInstances newProcesses = kwsysProcesses;
2758     int i;
2759     for (i = 0; i < newProcesses.Count; ++i) {
2760       if (newProcesses.Processes[i] == cp) {
2761         break;
2762       }
2763     }
2764     if (i < newProcesses.Count) {
2765       /* Remove the process from the set.  */
2766       --newProcesses.Count;
2767       for (; i < newProcesses.Count; ++i) {
2768         newProcesses.Processes[i] = newProcesses.Processes[i + 1];
2769       }
2770 
2771       /* If this was the last process, disable the signal handler.  */
2772       if (newProcesses.Count == 0) {
2773         /* Restore the signal handlers.  Repeat call until it is not
2774            interrupted.  */
2775         while ((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2776                (errno == EINTR))
2777           ;
2778         while ((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
2779                (errno == EINTR))
2780           ;
2781         while ((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
2782                (errno == EINTR))
2783           ;
2784 
2785         /* Free the table of process pointers since it is now empty.
2786            This is safe because the signal handler has been removed.  */
2787         newProcesses.Size = 0;
2788         free(newProcesses.Processes);
2789         newProcesses.Processes = 0;
2790       }
2791 
2792       /* Store the new set in that seen by the signal handler.  */
2793       kwsysProcessesUpdate(&newProcesses);
2794     }
2795   }
2796 
2797   /* Close the pipe through which the signal handler may have notified
2798      the given process object that a child has exited.  */
2799   kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2800 }
2801 
kwsysProcessesSignalHandler(int signum,siginfo_t * info,void * ucontext)2802 static void kwsysProcessesSignalHandler(int signum
2803 #if KWSYSPE_USE_SIGINFO
2804                                         ,
2805                                         siginfo_t* info, void* ucontext
2806 #endif
2807 )
2808 {
2809   int i, j, procStatus, old_errno = errno;
2810 #if KWSYSPE_USE_SIGINFO
2811   (void)info;
2812   (void)ucontext;
2813 #endif
2814 
2815   /* Signal all process objects that a child has terminated.  */
2816   switch (signum) {
2817     case SIGCHLD:
2818       for (i = 0; i < kwsysProcesses.Count; ++i) {
2819         /* Set the pipe in a signalled state.  */
2820         char buf = 1;
2821         kwsysProcess* cp = kwsysProcesses.Processes[i];
2822         kwsysProcess_ssize_t pipeStatus =
2823           read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2824         (void)pipeStatus;
2825         pipeStatus = write(cp->SignalPipe, &buf, 1);
2826         (void)pipeStatus;
2827       }
2828       break;
2829     case SIGINT:
2830     case SIGTERM:
2831       /* Signal child processes that are running in new process groups.  */
2832       for (i = 0; i < kwsysProcesses.Count; ++i) {
2833         kwsysProcess* cp = kwsysProcesses.Processes[i];
2834         /* Check Killed to avoid data race condition when killing.
2835            Check State to avoid data race condition in kwsysProcessCleanup
2836            when there is an error (it leaves a reaped PID).  */
2837         if (cp->CreateProcessGroup && !cp->Killed &&
2838             cp->State != kwsysProcess_State_Error && cp->ForkPIDs) {
2839           for (j = 0; j < cp->NumberOfCommands; ++j) {
2840             /* Make sure the PID is still valid. */
2841             if (cp->ForkPIDs[j]) {
2842               /* The user created a process group for this process.  The group
2843                  ID
2844                  is the process ID for the original process in the group.  */
2845               kill(-cp->ForkPIDs[j], SIGINT);
2846             }
2847           }
2848         }
2849       }
2850 
2851       /* Wait for all processes to terminate.  */
2852       while (wait(&procStatus) >= 0 || errno != ECHILD) {
2853       }
2854 
2855       /* Terminate the process, which is now in an inconsistent state
2856          because we reaped all the PIDs that it may have been reaping
2857          or may have reaped in the future.  Reraise the signal so that
2858          the proper exit code is returned.  */
2859       {
2860         /* Install default signal handler.  */
2861         struct sigaction defSigAction;
2862         sigset_t unblockSet;
2863         memset(&defSigAction, 0, sizeof(defSigAction));
2864         defSigAction.sa_handler = SIG_DFL;
2865         sigemptyset(&defSigAction.sa_mask);
2866         while ((sigaction(signum, &defSigAction, 0) < 0) && (errno == EINTR))
2867           ;
2868         /* Unmask the signal.  */
2869         sigemptyset(&unblockSet);
2870         sigaddset(&unblockSet, signum);
2871         sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
2872         /* Raise the signal again.  */
2873         raise(signum);
2874         /* We shouldn't get here... but if we do... */
2875         _exit(1);
2876       }
2877       /* break omitted to silence unreachable code clang compiler warning.  */
2878   }
2879 
2880 #if !KWSYSPE_USE_SIGINFO
2881   /* Re-Install our handler.  Repeat call until it is not interrupted.  */
2882   {
2883     struct sigaction newSigAction;
2884     struct sigaction& oldSigAction;
2885     memset(&newSigAction, 0, sizeof(struct sigaction));
2886     newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2887     newSigChldAction.sa_flags = SA_NOCLDSTOP;
2888     sigemptyset(&newSigAction.sa_mask);
2889     switch (signum) {
2890       case SIGCHLD:
2891         oldSigAction = &kwsysProcessesOldSigChldAction;
2892         break;
2893       case SIGINT:
2894         sigaddset(&newSigAction.sa_mask, SIGTERM);
2895         oldSigAction = &kwsysProcessesOldSigIntAction;
2896         break;
2897       case SIGTERM:
2898         sigaddset(&newSigAction.sa_mask, SIGINT);
2899         oldSigAction = &kwsysProcessesOldSigTermAction;
2900         break;
2901       default:
2902         return 0;
2903     }
2904     while ((sigaction(signum, &newSigAction, oldSigAction) < 0) &&
2905            (errno == EINTR))
2906       ;
2907   }
2908 #endif
2909 
2910   errno = old_errno;
2911 }
2912 
kwsysProcess_ResetStartTime(kwsysProcess * cp)2913 void kwsysProcess_ResetStartTime(kwsysProcess* cp)
2914 {
2915   if (!cp) {
2916     return;
2917   }
2918   /* Reset start time. */
2919   cp->StartTime = kwsysProcessTimeGetCurrent();
2920 }
2921