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