1 /* Utilities to execute a program in a subprocess (possibly linked by pipes
2 with other subprocesses), and wait for it.
3 Copyright (C) 1996-2000 Free Software Foundation, Inc.
5 This file is part of the libiberty library.
6 Libiberty is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
11 Libiberty is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with libiberty; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* This file exports two functions: pexecute and pwait. */
23 /* This file lives in at least two places: libiberty and gcc.
24 Don't change one without the other. */
32 #ifdef NEED_DECLARATION_ERRNO
44 #define ISSPACE (x) isspace(x)
45 #ifdef HAVE_SYS_WAIT_H
49 #ifdef vfork /* Autoconf may define this to fork for us. */
50 # define VFORK_STRING "fork"
52 # define VFORK_STRING "vfork"
58 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
59 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
62 #include "libiberty.h"
64 /* stdin file number. */
65 #define STDIN_FILE_NO 0
67 /* stdout file number. */
68 #define STDOUT_FILE_NO 1
70 /* value of `pipe': port index for reading. */
73 /* value of `pipe': port index for writing. */
76 static char *install_error_msg = "installation problem, cannot exec `%s'";
78 /* pexecute: execute a program.
80 PROGRAM and ARGV are the arguments to execv/execvp.
82 THIS_PNAME is name of the calling program (i.e. argv[0]).
84 TEMP_BASE is the path name, sans suffix, of a temporary file to use
85 if needed. This is currently only needed for MSDOS ports that don't use
86 GO32 (do any still exist?). Ports that don't need it can pass NULL.
88 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
89 (??? It's not clear that GCC passes this flag correctly).
90 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
91 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
92 FIRST_LAST could be simplified to only mark the last of a chain of processes
93 but that requires the caller to always mark the last one (and not give up
94 early if some error occurs). It's more robust to require the caller to
95 mark both ends of the chain.
97 The result is the pid on systems like Unix where we fork/exec and on systems
98 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
101 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
104 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
105 message with an optional argument (if not needed, ERRMSG_ARG is set to
106 NULL), and -1 is returned. `errno' is available to the caller to use.
108 pwait: cover function for wait.
110 PID is the process id of the task to wait for.
111 STATUS is the `status' argument to wait.
112 FLAGS is currently unused (allows future enhancement without breaking
113 upward compatibility). Pass 0 for now.
115 The result is the pid of the child reaped,
116 or -1 for failure (errno says why).
118 On systems that don't support waiting for a particular child, PID is
119 ignored. On systems like MSDOS that don't really multitask pwait
120 is just a mechanism to provide a consistent interface for the caller.
122 pfinish: finish generation of script
124 pfinish is necessary for systems like MPW where a script is generated that
125 runs the requested programs.
130 /* MSDOS doesn't multitask, but for the sake of a consistent interface
131 the code behaves like it does. pexecute runs the program, tucks the
132 exit code away, and returns a "pid". pwait must be called to fetch the
137 /* For communicating information from pexecute to pwait. */
138 static int last_pid = 0;
139 static int last_status = 0;
140 static int last_reaped = 0;
143 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
146 const char *this_pname;
147 const char *temp_base;
148 char **errmsg_fmt, **errmsg_arg;
157 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
161 /* ??? What are the possible return values from spawnv? */
162 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
166 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
169 temp_base = choose_temp_base ();
170 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
171 rf = scmd + strlen(program) + 2 + el;
172 sprintf (scmd, "%s%s @%s.gp", program,
173 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
174 argfile = fopen (rf, "w");
177 int errno_save = errno;
180 *errmsg_fmt = "cannot open `%s.gp'";
181 *errmsg_arg = temp_base;
185 for (i=1; argv[i]; i++)
188 for (cp = argv[i]; *cp; cp++)
190 if (*cp == '"' || *cp == '\'' || *cp == '\\' || ISSPACE (*cp))
191 fputc ('\\', argfile);
192 fputc (*cp, argfile);
194 fputc ('\n', argfile);
201 int errno_save = errno;
210 *errmsg_fmt = install_error_msg;
211 *errmsg_arg = program;
215 /* Tuck the status away for pwait, and return a "pid". */
216 last_status = rc << 8;
221 pwait (pid, status, flags)
226 /* On MSDOS each pexecute must be followed by it's associated pwait. */
228 /* Called twice for the same child? */
229 || pid == last_reaped)
231 /* ??? ECHILD would be a better choice. Can we use it here? */
235 /* ??? Here's an opportunity to canonicalize the values in STATUS.
237 *status = last_status;
238 last_reaped = last_pid;
244 #if defined (_WIN32) && ! defined (_UWIN)
250 #define fix_argv(argvec) (argvec)
252 extern int _spawnv ();
253 extern int _spawnvp ();
255 #else /* ! __CYGWIN__ */
257 /* This is a kludge to get around the Microsoft C spawn functions' propensity
258 to remove the outermost set of double quotes from all arguments. */
266 for (i = 1; argvec[i] != 0; i++)
269 char *temp, *newtemp;
273 for (j = 0; j < len; j++)
277 newtemp = xmalloc (len + 2);
278 strncpy (newtemp, temp, j);
280 strncpy (&newtemp [j+1], &temp [j], len-j);
291 for (i = 0; argvec[i] != 0; i++)
293 if (strpbrk (argvec[i], " \t"))
295 int len, trailing_backslash;
298 len = strlen (argvec[i]);
299 trailing_backslash = 0;
301 /* There is an added complication when an arg with embedded white
302 space ends in a backslash (such as in the case of -iprefix arg
303 passed to cpp). The resulting quoted strings gets misinterpreted
304 by the command interpreter -- it thinks that the ending quote
305 is escaped by the trailing backslash and things get confused.
306 We handle this case by escaping the trailing backslash, provided
307 it was not escaped in the first place. */
309 && argvec[i][len-1] == '\\'
310 && argvec[i][len-2] != '\\')
312 trailing_backslash = 1;
313 ++len; /* to escape the final backslash. */
316 len += 2; /* and for the enclosing quotes. */
318 temp = xmalloc (len + 1);
320 strcpy (temp + 1, argvec[i]);
321 if (trailing_backslash)
330 return (const char * const *) argvec;
332 #endif /* __CYGWIN__ */
338 /* mingw32 headers may not define the following. */
343 # define _P_OVERLAY 2
344 # define _P_NOWAITO 3
347 # define WAIT_CHILD 0
348 # define WAIT_GRANDCHILD 1
351 /* Win32 supports pipes */
353 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
356 const char *this_pname;
357 const char *temp_base;
358 char **errmsg_fmt, **errmsg_arg;
362 int pdes[2], org_stdin, org_stdout;
363 int input_desc, output_desc;
364 int retries, sleep_interval;
366 /* Pipe waiting from last process, to be used as input for the next one.
367 Value is STDIN_FILE_NO if no pipe is waiting
368 (i.e. the next command is the first of a group). */
369 static int last_pipe_input;
371 /* If this is the first process, initialize. */
372 if (flags & PEXECUTE_FIRST)
373 last_pipe_input = STDIN_FILE_NO;
375 input_desc = last_pipe_input;
377 /* If this isn't the last process, make a pipe for its output,
378 and record it as waiting to be the input to the next process. */
379 if (! (flags & PEXECUTE_LAST))
381 if (_pipe (pdes, 256, O_BINARY) < 0)
383 *errmsg_fmt = "pipe";
387 output_desc = pdes[WRITE_PORT];
388 last_pipe_input = pdes[READ_PORT];
393 output_desc = STDOUT_FILE_NO;
394 last_pipe_input = STDIN_FILE_NO;
397 if (input_desc != STDIN_FILE_NO)
399 org_stdin = dup (STDIN_FILE_NO);
400 dup2 (input_desc, STDIN_FILE_NO);
404 if (output_desc != STDOUT_FILE_NO)
406 org_stdout = dup (STDOUT_FILE_NO);
407 dup2 (output_desc, STDOUT_FILE_NO);
411 pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv)
412 (_P_NOWAIT, program, fix_argv(argv));
414 if (input_desc != STDIN_FILE_NO)
416 dup2 (org_stdin, STDIN_FILE_NO);
420 if (output_desc != STDOUT_FILE_NO)
422 dup2 (org_stdout, STDOUT_FILE_NO);
428 *errmsg_fmt = install_error_msg;
429 *errmsg_arg = program;
436 /* MS CRTDLL doesn't return enough information in status to decide if the
437 child exited due to a signal or not, rather it simply returns an
438 integer with the exit code of the child; eg., if the child exited with
439 an abort() call and didn't have a handler for SIGABRT, it simply returns
440 with status = 3. We fix the status code to conform to the usual WIF*
441 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
444 pwait (pid, status, flags)
450 return wait (status);
454 pid = _cwait (&termstat, pid, WAIT_CHILD);
456 /* ??? Here's an opportunity to canonicalize the values in STATUS.
459 /* cwait returns the child process exit code in termstat.
460 A value of 3 indicates that the child caught a signal, but not
461 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
466 *status = (((termstat) & 0xff) << 8);
469 #endif /* __CYGWIN__ */
472 #endif /* _WIN32 && ! _UWIN */
476 /* ??? Does OS2 have process.h? */
477 extern int spawnv ();
478 extern int spawnvp ();
481 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
484 const char *this_pname;
485 const char *temp_base;
486 char **errmsg_fmt, **errmsg_arg;
491 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
493 /* ??? Presumably 1 == _P_NOWAIT. */
494 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
497 *errmsg_fmt = install_error_msg;
498 *errmsg_arg = program;
505 pwait (pid, status, flags)
510 /* ??? Here's an opportunity to canonicalize the values in STATUS.
512 int pid = wait (status);
520 /* MPW pexecute doesn't actually run anything; instead, it writes out
521 script commands that, when run, will do the actual executing.
523 For example, in GCC's case, GCC will write out several script commands:
530 and then exit. None of the above programs will have run yet. The task
531 that called GCC will then execute the script and cause cpp,etc. to run.
532 The caller must invoke pfinish before calling exit. This adds
533 the finishing touches to the generated script. */
535 static int first_time = 1;
538 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
541 const char *this_pname;
542 const char *temp_base;
543 char **errmsg_fmt, **errmsg_arg;
546 char tmpprogram[255];
550 mpwify_filename (program, tmpprogram);
553 printf ("Set Failed 0\n");
557 fputs ("If {Failed} == 0\n", stdout);
558 /* If being verbose, output a copy of the command. It should be
559 accurate enough and escaped enough to be "clickable". */
560 if (flags & PEXECUTE_VERBOSE)
562 fputs ("\tEcho ", stdout);
563 fputc ('\'', stdout);
564 fputs (tmpprogram, stdout);
565 fputc ('\'', stdout);
567 for (i=1; argv[i]; i++)
569 fputc ('\'', stdout);
570 /* See if we have an argument that needs fixing. */
571 if (strchr(argv[i], '/'))
573 tmpname = (char *) xmalloc (256);
574 mpwify_filename (argv[i], tmpname);
577 for (cp = argv[i]; *cp; cp++)
579 /* Write an Option-d escape char in front of special chars. */
580 if (strchr("'+", *cp))
581 fputc ('\266', stdout);
584 fputc ('\'', stdout);
587 fputs ("\n", stdout);
589 fputs ("\t", stdout);
590 fputs (tmpprogram, stdout);
593 for (i=1; argv[i]; i++)
595 /* See if we have an argument that needs fixing. */
596 if (strchr(argv[i], '/'))
598 tmpname = (char *) xmalloc (256);
599 mpwify_filename (argv[i], tmpname);
602 if (strchr (argv[i], ' '))
603 fputc ('\'', stdout);
604 for (cp = argv[i]; *cp; cp++)
606 /* Write an Option-d escape char in front of special chars. */
607 if (strchr("'+", *cp))
608 fputc ('\266', stdout);
611 if (strchr (argv[i], ' '))
612 fputc ('\'', stdout);
616 fputs ("\n", stdout);
618 /* Output commands that arrange to clean up and exit if a failure occurs.
619 We have to be careful to collect the status from the program that was
620 run, rather than some other script command. Also, we don't exit
621 immediately, since necessary cleanups are at the end of the script. */
622 fputs ("\tSet TmpStatus {Status}\n", stdout);
623 fputs ("\tIf {TmpStatus} != 0\n", stdout);
624 fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
625 fputs ("\tEnd\n", stdout);
626 fputs ("End\n", stdout);
628 /* We're just composing a script, can't fail here. */
633 pwait (pid, status, flags)
642 /* Write out commands that will exit with the correct error code
643 if something in the script failed. */
648 printf ("\tExit \"{Failed}\"\n");
653 /* include for Unix-like environments but not for Dos-like environments */
654 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
655 && ! (defined (_WIN32) && ! defined (_UWIN))
658 extern int execvp ();
661 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
664 const char *this_pname;
665 const char *temp_base ATTRIBUTE_UNUSED;
666 char **errmsg_fmt, **errmsg_arg;
669 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
672 int input_desc, output_desc;
673 int retries, sleep_interval;
674 /* Pipe waiting from last process, to be used as input for the next one.
675 Value is STDIN_FILE_NO if no pipe is waiting
676 (i.e. the next command is the first of a group). */
677 static int last_pipe_input;
679 /* If this is the first process, initialize. */
680 if (flags & PEXECUTE_FIRST)
681 last_pipe_input = STDIN_FILE_NO;
683 input_desc = last_pipe_input;
685 /* If this isn't the last process, make a pipe for its output,
686 and record it as waiting to be the input to the next process. */
687 if (! (flags & PEXECUTE_LAST))
691 *errmsg_fmt = "pipe";
695 output_desc = pdes[WRITE_PORT];
696 last_pipe_input = pdes[READ_PORT];
701 output_desc = STDOUT_FILE_NO;
702 last_pipe_input = STDIN_FILE_NO;
705 /* Fork a subprocess; wait and retry if it fails. */
707 for (retries = 0; retries < 4; retries++)
712 sleep (sleep_interval);
720 *errmsg_fmt = VFORK_STRING;
726 /* Move the input and output pipes into place, if necessary. */
727 if (input_desc != STDIN_FILE_NO)
729 close (STDIN_FILE_NO);
733 if (output_desc != STDOUT_FILE_NO)
735 close (STDOUT_FILE_NO);
740 /* Close the parent's descs that aren't wanted here. */
741 if (last_pipe_input != STDIN_FILE_NO)
742 close (last_pipe_input);
744 /* Exec the program. */
745 (*func) (program, argv);
747 /* Note: Calling fprintf and exit here doesn't seem right for vfork. */
748 fprintf (stderr, "%s: ", this_pname);
749 fprintf (stderr, install_error_msg, program);
750 fprintf (stderr, ": %s\n", xstrerror (errno));
756 /* In the parent, after forking.
757 Close the descriptors that we made for this child. */
758 if (input_desc != STDIN_FILE_NO)
760 if (output_desc != STDOUT_FILE_NO)
763 /* Return child's process number. */
769 pwait (pid, status, flags)
772 int flags ATTRIBUTE_UNUSED;
774 /* ??? Here's an opportunity to canonicalize the values in STATUS.
777 pid = waitpid (-1, status, 0);
784 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! (_WIN32 && ! _UWIN) */