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 #ifdef HAVE_SYS_WAIT_H
48 #include "libiberty.h"
49 #include "safe-ctype.h"
51 /* stdin file number. */
52 #define STDIN_FILE_NO 0
54 /* stdout file number. */
55 #define STDOUT_FILE_NO 1
57 /* value of `pipe': port index for reading. */
60 /* value of `pipe': port index for writing. */
63 static char *install_error_msg = "installation problem, cannot exec `%s'";
65 /* pexecute: execute a program.
67 PROGRAM and ARGV are the arguments to execv/execvp.
69 THIS_PNAME is name of the calling program (i.e. argv[0]).
71 TEMP_BASE is the path name, sans suffix, of a temporary file to use
72 if needed. This is currently only needed for MSDOS ports that don't use
73 GO32 (do any still exist?). Ports that don't need it can pass NULL.
75 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
76 (??? It's not clear that GCC passes this flag correctly).
77 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
78 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
79 FIRST_LAST could be simplified to only mark the last of a chain of processes
80 but that requires the caller to always mark the last one (and not give up
81 early if some error occurs). It's more robust to require the caller to
82 mark both ends of the chain.
84 The result is the pid on systems like Unix where we fork/exec and on systems
85 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
88 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
91 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
92 message with an optional argument (if not needed, ERRMSG_ARG is set to
93 NULL), and -1 is returned. `errno' is available to the caller to use.
95 pwait: cover function for wait.
97 PID is the process id of the task to wait for.
98 STATUS is the `status' argument to wait.
99 FLAGS is currently unused (allows future enhancement without breaking
100 upward compatibility). Pass 0 for now.
102 The result is the pid of the child reaped,
103 or -1 for failure (errno says why).
105 On systems that don't support waiting for a particular child, PID is
106 ignored. On systems like MSDOS that don't really multitask pwait
107 is just a mechanism to provide a consistent interface for the caller.
109 pfinish: finish generation of script
111 pfinish is necessary for systems like MPW where a script is generated that
112 runs the requested programs.
117 /* MSDOS doesn't multitask, but for the sake of a consistent interface
118 the code behaves like it does. pexecute runs the program, tucks the
119 exit code away, and returns a "pid". pwait must be called to fetch the
124 /* For communicating information from pexecute to pwait. */
125 static int last_pid = 0;
126 static int last_status = 0;
127 static int last_reaped = 0;
130 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
133 const char *this_pname;
134 const char *temp_base;
135 char **errmsg_fmt, **errmsg_arg;
144 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
148 /* ??? What are the possible return values from spawnv? */
149 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (P_WAIT, program, argv);
153 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
156 temp_base = choose_temp_base ();
157 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
158 rf = scmd + strlen(program) + 2 + el;
159 sprintf (scmd, "%s%s @%s.gp", program,
160 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
161 argfile = fopen (rf, "w");
164 int errno_save = errno;
167 *errmsg_fmt = "cannot open `%s.gp'";
168 *errmsg_arg = temp_base;
172 for (i=1; argv[i]; i++)
175 for (cp = argv[i]; *cp; cp++)
177 if (*cp == '"' || *cp == '\'' || *cp == '\\' || ISSPACE (*cp))
178 fputc ('\\', argfile);
179 fputc (*cp, argfile);
181 fputc ('\n', argfile);
188 int errno_save = errno;
197 *errmsg_fmt = install_error_msg;
198 *errmsg_arg = (char *)program;
202 /* Tuck the status away for pwait, and return a "pid". */
203 last_status = rc << 8;
207 /* Use ECHILD if available, otherwise use EINVAL. */
209 #define PWAIT_ERROR ECHILD
211 #define PWAIT_ERROR EINVAL
215 pwait (pid, status, flags)
220 /* On MSDOS each pexecute must be followed by it's associated pwait. */
222 /* Called twice for the same child? */
223 || pid == last_reaped)
228 /* ??? Here's an opportunity to canonicalize the values in STATUS.
231 *status = (last_status >> 8);
233 *status = last_status;
235 last_reaped = last_pid;
241 #if defined (_WIN32) && ! defined (_UWIN)
247 #define fix_argv(argvec) (argvec)
249 extern int _spawnv ();
250 extern int _spawnvp ();
252 #else /* ! __CYGWIN__ */
254 /* This is a kludge to get around the Microsoft C spawn functions' propensity
255 to remove the outermost set of double quotes from all arguments. */
263 for (i = 1; argvec[i] != 0; i++)
266 char *temp, *newtemp;
270 for (j = 0; j < len; j++)
274 newtemp = xmalloc (len + 2);
275 strncpy (newtemp, temp, j);
277 strncpy (&newtemp [j+1], &temp [j], len-j);
288 for (i = 0; argvec[i] != 0; i++)
290 if (strpbrk (argvec[i], " \t"))
292 int len, trailing_backslash;
295 len = strlen (argvec[i]);
296 trailing_backslash = 0;
298 /* There is an added complication when an arg with embedded white
299 space ends in a backslash (such as in the case of -iprefix arg
300 passed to cpp). The resulting quoted strings gets misinterpreted
301 by the command interpreter -- it thinks that the ending quote
302 is escaped by the trailing backslash and things get confused.
303 We handle this case by escaping the trailing backslash, provided
304 it was not escaped in the first place. */
306 && argvec[i][len-1] == '\\'
307 && argvec[i][len-2] != '\\')
309 trailing_backslash = 1;
310 ++len; /* to escape the final backslash. */
313 len += 2; /* and for the enclosing quotes. */
315 temp = xmalloc (len + 1);
317 strcpy (temp + 1, argvec[i]);
318 if (trailing_backslash)
327 return (const char * const *) argvec;
329 #endif /* __CYGWIN__ */
335 /* mingw32 headers may not define the following. */
340 # define _P_OVERLAY 2
341 # define _P_NOWAITO 3
344 # define WAIT_CHILD 0
345 # define WAIT_GRANDCHILD 1
348 /* Win32 supports pipes */
350 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
353 const char *this_pname;
354 const char *temp_base;
355 char **errmsg_fmt, **errmsg_arg;
359 int pdes[2], org_stdin, org_stdout;
360 int input_desc, output_desc;
361 int retries, sleep_interval;
363 /* Pipe waiting from last process, to be used as input for the next one.
364 Value is STDIN_FILE_NO if no pipe is waiting
365 (i.e. the next command is the first of a group). */
366 static int last_pipe_input;
368 /* If this is the first process, initialize. */
369 if (flags & PEXECUTE_FIRST)
370 last_pipe_input = STDIN_FILE_NO;
372 input_desc = last_pipe_input;
374 /* If this isn't the last process, make a pipe for its output,
375 and record it as waiting to be the input to the next process. */
376 if (! (flags & PEXECUTE_LAST))
378 if (_pipe (pdes, 256, O_BINARY) < 0)
380 *errmsg_fmt = "pipe";
384 output_desc = pdes[WRITE_PORT];
385 last_pipe_input = pdes[READ_PORT];
390 output_desc = STDOUT_FILE_NO;
391 last_pipe_input = STDIN_FILE_NO;
394 if (input_desc != STDIN_FILE_NO)
396 org_stdin = dup (STDIN_FILE_NO);
397 dup2 (input_desc, STDIN_FILE_NO);
401 if (output_desc != STDOUT_FILE_NO)
403 org_stdout = dup (STDOUT_FILE_NO);
404 dup2 (output_desc, STDOUT_FILE_NO);
408 pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv)
409 (_P_NOWAIT, program, fix_argv(argv));
411 if (input_desc != STDIN_FILE_NO)
413 dup2 (org_stdin, STDIN_FILE_NO);
417 if (output_desc != STDOUT_FILE_NO)
419 dup2 (org_stdout, STDOUT_FILE_NO);
425 *errmsg_fmt = install_error_msg;
426 *errmsg_arg = program;
433 /* MS CRTDLL doesn't return enough information in status to decide if the
434 child exited due to a signal or not, rather it simply returns an
435 integer with the exit code of the child; eg., if the child exited with
436 an abort() call and didn't have a handler for SIGABRT, it simply returns
437 with status = 3. We fix the status code to conform to the usual WIF*
438 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
441 pwait (pid, status, flags)
447 return wait (status);
451 pid = _cwait (&termstat, pid, WAIT_CHILD);
453 /* ??? Here's an opportunity to canonicalize the values in STATUS.
456 /* cwait returns the child process exit code in termstat.
457 A value of 3 indicates that the child caught a signal, but not
458 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
463 *status = (((termstat) & 0xff) << 8);
466 #endif /* __CYGWIN__ */
469 #endif /* _WIN32 && ! _UWIN */
473 /* ??? Does OS2 have process.h? */
474 extern int spawnv ();
475 extern int spawnvp ();
478 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
481 const char *this_pname;
482 const char *temp_base;
483 char **errmsg_fmt, **errmsg_arg;
488 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
490 /* ??? Presumably 1 == _P_NOWAIT. */
491 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
494 *errmsg_fmt = install_error_msg;
495 *errmsg_arg = program;
502 pwait (pid, status, flags)
507 /* ??? Here's an opportunity to canonicalize the values in STATUS.
509 int pid = wait (status);
517 /* MPW pexecute doesn't actually run anything; instead, it writes out
518 script commands that, when run, will do the actual executing.
520 For example, in GCC's case, GCC will write out several script commands:
527 and then exit. None of the above programs will have run yet. The task
528 that called GCC will then execute the script and cause cpp,etc. to run.
529 The caller must invoke pfinish before calling exit. This adds
530 the finishing touches to the generated script. */
532 static int first_time = 1;
535 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
538 const char *this_pname;
539 const char *temp_base;
540 char **errmsg_fmt, **errmsg_arg;
543 char tmpprogram[255];
547 mpwify_filename (program, tmpprogram);
550 printf ("Set Failed 0\n");
554 fputs ("If {Failed} == 0\n", stdout);
555 /* If being verbose, output a copy of the command. It should be
556 accurate enough and escaped enough to be "clickable". */
557 if (flags & PEXECUTE_VERBOSE)
559 fputs ("\tEcho ", stdout);
560 fputc ('\'', stdout);
561 fputs (tmpprogram, stdout);
562 fputc ('\'', stdout);
564 for (i=1; argv[i]; i++)
566 fputc ('\'', stdout);
567 /* See if we have an argument that needs fixing. */
568 if (strchr(argv[i], '/'))
570 tmpname = (char *) xmalloc (256);
571 mpwify_filename (argv[i], tmpname);
574 for (cp = argv[i]; *cp; cp++)
576 /* Write an Option-d escape char in front of special chars. */
577 if (strchr("'+", *cp))
578 fputc ('\266', stdout);
581 fputc ('\'', stdout);
584 fputs ("\n", stdout);
586 fputs ("\t", stdout);
587 fputs (tmpprogram, stdout);
590 for (i=1; argv[i]; i++)
592 /* See if we have an argument that needs fixing. */
593 if (strchr(argv[i], '/'))
595 tmpname = (char *) xmalloc (256);
596 mpwify_filename (argv[i], tmpname);
599 if (strchr (argv[i], ' '))
600 fputc ('\'', stdout);
601 for (cp = argv[i]; *cp; cp++)
603 /* Write an Option-d escape char in front of special chars. */
604 if (strchr("'+", *cp))
605 fputc ('\266', stdout);
608 if (strchr (argv[i], ' '))
609 fputc ('\'', stdout);
613 fputs ("\n", stdout);
615 /* Output commands that arrange to clean up and exit if a failure occurs.
616 We have to be careful to collect the status from the program that was
617 run, rather than some other script command. Also, we don't exit
618 immediately, since necessary cleanups are at the end of the script. */
619 fputs ("\tSet TmpStatus {Status}\n", stdout);
620 fputs ("\tIf {TmpStatus} != 0\n", stdout);
621 fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
622 fputs ("\tEnd\n", stdout);
623 fputs ("End\n", stdout);
625 /* We're just composing a script, can't fail here. */
630 pwait (pid, status, flags)
639 /* Write out commands that will exit with the correct error code
640 if something in the script failed. */
645 printf ("\tExit \"{Failed}\"\n");
650 /* include for Unix-like environments but not for Dos-like environments */
651 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
652 && ! (defined (_WIN32) && ! defined (_UWIN))
655 extern int execvp ();
658 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
661 const char *this_pname;
662 const char *temp_base ATTRIBUTE_UNUSED;
663 char **errmsg_fmt, **errmsg_arg;
666 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
669 int input_desc, output_desc;
670 int retries, sleep_interval;
671 /* Pipe waiting from last process, to be used as input for the next one.
672 Value is STDIN_FILE_NO if no pipe is waiting
673 (i.e. the next command is the first of a group). */
674 static int last_pipe_input;
676 /* If this is the first process, initialize. */
677 if (flags & PEXECUTE_FIRST)
678 last_pipe_input = STDIN_FILE_NO;
680 input_desc = last_pipe_input;
682 /* If this isn't the last process, make a pipe for its output,
683 and record it as waiting to be the input to the next process. */
684 if (! (flags & PEXECUTE_LAST))
688 *errmsg_fmt = "pipe";
692 output_desc = pdes[WRITE_PORT];
693 last_pipe_input = pdes[READ_PORT];
698 output_desc = STDOUT_FILE_NO;
699 last_pipe_input = STDIN_FILE_NO;
702 /* Fork a subprocess; wait and retry if it fails. */
705 for (retries = 0; retries < 4; retries++)
710 sleep (sleep_interval);
717 *errmsg_fmt = "fork";
722 /* Move the input and output pipes into place, if necessary. */
723 if (input_desc != STDIN_FILE_NO)
725 close (STDIN_FILE_NO);
729 if (output_desc != STDOUT_FILE_NO)
731 close (STDOUT_FILE_NO);
736 /* Close the parent's descs that aren't wanted here. */
737 if (last_pipe_input != STDIN_FILE_NO)
738 close (last_pipe_input);
740 /* Exec the program. */
741 (*func) (program, argv);
743 fprintf (stderr, "%s: ", this_pname);
744 fprintf (stderr, install_error_msg, program);
745 fprintf (stderr, ": %s\n", xstrerror (errno));
751 /* In the parent, after forking.
752 Close the descriptors that we made for this child. */
753 if (input_desc != STDIN_FILE_NO)
755 if (output_desc != STDOUT_FILE_NO)
758 /* Return child's process number. */
764 pwait (pid, status, flags)
767 int flags ATTRIBUTE_UNUSED;
769 /* ??? Here's an opportunity to canonicalize the values in STATUS.
772 pid = waitpid (-1, status, 0);
779 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! (_WIN32 && ! _UWIN) */