* config.bfd (hppa*64*-*-hpux11*): New target triplet.
[binutils.git] / libiberty / pexecute.c
blob56ddec78dd838908d1a7fc9306e7ea96016198e6
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. */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
30 #include <stdio.h>
31 #include <errno.h>
32 #ifdef HAVE_STRING_H
33 #include <string.h>
34 #endif
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #define ISSPACE (x) isspace(x)
39 #ifdef HAVE_SYS_WAIT_H
40 #include <sys/wait.h>
41 #endif
43 #ifdef vfork /* Autoconf may define this to fork for us. */
44 # define VFORK_STRING "fork"
45 #else
46 # define VFORK_STRING "vfork"
47 #endif
48 #ifdef HAVE_VFORK_H
49 #include <vfork.h>
50 #endif
51 #ifdef VMS
52 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
53 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
54 #endif /* VMS */
56 #include "libiberty.h"
58 /* stdin file number. */
59 #define STDIN_FILE_NO 0
61 /* stdout file number. */
62 #define STDOUT_FILE_NO 1
64 /* value of `pipe': port index for reading. */
65 #define READ_PORT 0
67 /* value of `pipe': port index for writing. */
68 #define WRITE_PORT 1
70 static char *install_error_msg = "installation problem, cannot exec `%s'";
72 /* pexecute: execute a program.
74 PROGRAM and ARGV are the arguments to execv/execvp.
76 THIS_PNAME is name of the calling program (i.e. argv[0]).
78 TEMP_BASE is the path name, sans suffix, of a temporary file to use
79 if needed. This is currently only needed for MSDOS ports that don't use
80 GO32 (do any still exist?). Ports that don't need it can pass NULL.
82 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
83 (??? It's not clear that GCC passes this flag correctly).
84 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
85 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
86 FIRST_LAST could be simplified to only mark the last of a chain of processes
87 but that requires the caller to always mark the last one (and not give up
88 early if some error occurs). It's more robust to require the caller to
89 mark both ends of the chain.
91 The result is the pid on systems like Unix where we fork/exec and on systems
92 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
93 the child.
95 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
96 for the child here.
98 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
99 message with an optional argument (if not needed, ERRMSG_ARG is set to
100 NULL), and -1 is returned. `errno' is available to the caller to use.
102 pwait: cover function for wait.
104 PID is the process id of the task to wait for.
105 STATUS is the `status' argument to wait.
106 FLAGS is currently unused (allows future enhancement without breaking
107 upward compatibility). Pass 0 for now.
109 The result is the pid of the child reaped,
110 or -1 for failure (errno says why).
112 On systems that don't support waiting for a particular child, PID is
113 ignored. On systems like MSDOS that don't really multitask pwait
114 is just a mechanism to provide a consistent interface for the caller.
116 pfinish: finish generation of script
118 pfinish is necessary for systems like MPW where a script is generated that
119 runs the requested programs.
122 #ifdef __MSDOS__
124 /* MSDOS doesn't multitask, but for the sake of a consistent interface
125 the code behaves like it does. pexecute runs the program, tucks the
126 exit code away, and returns a "pid". pwait must be called to fetch the
127 exit code. */
129 #include <process.h>
131 /* For communicating information from pexecute to pwait. */
132 static int last_pid = 0;
133 static int last_status = 0;
134 static int last_reaped = 0;
137 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
138 const char *program;
139 char * const *argv;
140 const char *this_pname;
141 const char *temp_base;
142 char **errmsg_fmt, **errmsg_arg;
143 int flags;
145 int rc;
147 last_pid++;
148 if (last_pid < 0)
149 last_pid = 1;
151 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
152 abort ();
154 #ifdef __GO32__
155 /* ??? What are the possible return values from spawnv? */
156 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
157 #else
158 char *scmd, *rf;
159 FILE *argfile;
160 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
162 if (temp_base == 0)
163 temp_base = choose_temp_base ();
164 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
165 rf = scmd + strlen(program) + 2 + el;
166 sprintf (scmd, "%s%s @%s.gp", program,
167 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
168 argfile = fopen (rf, "w");
169 if (argfile == 0)
171 int errno_save = errno;
172 free (scmd);
173 errno = errno_save;
174 *errmsg_fmt = "cannot open `%s.gp'";
175 *errmsg_arg = temp_base;
176 return -1;
179 for (i=1; argv[i]; i++)
181 char *cp;
182 for (cp = argv[i]; *cp; cp++)
184 if (*cp == '"' || *cp == '\'' || *cp == '\\' || ISSPACE (*cp))
185 fputc ('\\', argfile);
186 fputc (*cp, argfile);
188 fputc ('\n', argfile);
190 fclose (argfile);
192 rc = system (scmd);
195 int errno_save = errno;
196 remove (rf);
197 free (scmd);
198 errno = errno_save;
200 #endif
202 if (rc == -1)
204 *errmsg_fmt = install_error_msg;
205 *errmsg_arg = program;
206 return -1;
209 /* Tuck the status away for pwait, and return a "pid". */
210 last_status = rc << 8;
211 return last_pid;
215 pwait (pid, status, flags)
216 int pid;
217 int *status;
218 int flags;
220 /* On MSDOS each pexecute must be followed by it's associated pwait. */
221 if (pid != last_pid
222 /* Called twice for the same child? */
223 || pid == last_reaped)
225 /* ??? ECHILD would be a better choice. Can we use it here? */
226 errno = EINVAL;
227 return -1;
229 /* ??? Here's an opportunity to canonicalize the values in STATUS.
230 Needed? */
231 *status = last_status;
232 last_reaped = last_pid;
233 return last_pid;
236 #endif /* MSDOS */
238 #if defined (_WIN32) && ! defined (_UWIN)
240 #include <process.h>
242 #ifdef __CYGWIN__
244 #define fix_argv(argvec) (argvec)
246 extern int _spawnv ();
247 extern int _spawnvp ();
249 #else /* ! __CYGWIN__ */
251 /* This is a kludge to get around the Microsoft C spawn functions' propensity
252 to remove the outermost set of double quotes from all arguments. */
254 const char * const *
255 fix_argv (argvec)
256 char **argvec;
258 int i;
260 for (i = 1; argvec[i] != 0; i++)
262 int len, j;
263 char *temp, *newtemp;
265 temp = argvec[i];
266 len = strlen (temp);
267 for (j = 0; j < len; j++)
269 if (temp[j] == '"')
271 newtemp = xmalloc (len + 2);
272 strncpy (newtemp, temp, j);
273 newtemp [j] = '\\';
274 strncpy (&newtemp [j+1], &temp [j], len-j);
275 newtemp [len+1] = 0;
276 temp = newtemp;
277 len++;
278 j++;
282 argvec[i] = temp;
285 for (i = 0; argvec[i] != 0; i++)
287 if (strpbrk (argvec[i], " \t"))
289 int len, trailing_backslash;
290 char *temp;
292 len = strlen (argvec[i]);
293 trailing_backslash = 0;
295 /* There is an added complication when an arg with embedded white
296 space ends in a backslash (such as in the case of -iprefix arg
297 passed to cpp). The resulting quoted strings gets misinterpreted
298 by the command interpreter -- it thinks that the ending quote
299 is escaped by the trailing backslash and things get confused.
300 We handle this case by escaping the trailing backslash, provided
301 it was not escaped in the first place. */
302 if (len > 1
303 && argvec[i][len-1] == '\\'
304 && argvec[i][len-2] != '\\')
306 trailing_backslash = 1;
307 ++len; /* to escape the final backslash. */
310 len += 2; /* and for the enclosing quotes. */
312 temp = xmalloc (len + 1);
313 temp[0] = '"';
314 strcpy (temp + 1, argvec[i]);
315 if (trailing_backslash)
316 temp[len-2] = '\\';
317 temp[len-1] = '"';
318 temp[len] = '\0';
320 argvec[i] = temp;
324 return (const char * const *) argvec;
326 #endif /* __CYGWIN__ */
328 #include <io.h>
329 #include <fcntl.h>
330 #include <signal.h>
332 /* mingw32 headers may not define the following. */
334 #ifndef _P_WAIT
335 # define _P_WAIT 0
336 # define _P_NOWAIT 1
337 # define _P_OVERLAY 2
338 # define _P_NOWAITO 3
339 # define _P_DETACH 4
341 # define WAIT_CHILD 0
342 # define WAIT_GRANDCHILD 1
343 #endif
345 /* Win32 supports pipes */
347 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
348 const char *program;
349 char * const *argv;
350 const char *this_pname;
351 const char *temp_base;
352 char **errmsg_fmt, **errmsg_arg;
353 int flags;
355 int pid;
356 int pdes[2], org_stdin, org_stdout;
357 int input_desc, output_desc;
358 int retries, sleep_interval;
360 /* Pipe waiting from last process, to be used as input for the next one.
361 Value is STDIN_FILE_NO if no pipe is waiting
362 (i.e. the next command is the first of a group). */
363 static int last_pipe_input;
365 /* If this is the first process, initialize. */
366 if (flags & PEXECUTE_FIRST)
367 last_pipe_input = STDIN_FILE_NO;
369 input_desc = last_pipe_input;
371 /* If this isn't the last process, make a pipe for its output,
372 and record it as waiting to be the input to the next process. */
373 if (! (flags & PEXECUTE_LAST))
375 if (_pipe (pdes, 256, O_BINARY) < 0)
377 *errmsg_fmt = "pipe";
378 *errmsg_arg = NULL;
379 return -1;
381 output_desc = pdes[WRITE_PORT];
382 last_pipe_input = pdes[READ_PORT];
384 else
386 /* Last process. */
387 output_desc = STDOUT_FILE_NO;
388 last_pipe_input = STDIN_FILE_NO;
391 if (input_desc != STDIN_FILE_NO)
393 org_stdin = dup (STDIN_FILE_NO);
394 dup2 (input_desc, STDIN_FILE_NO);
395 close (input_desc);
398 if (output_desc != STDOUT_FILE_NO)
400 org_stdout = dup (STDOUT_FILE_NO);
401 dup2 (output_desc, STDOUT_FILE_NO);
402 close (output_desc);
405 pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv)
406 (_P_NOWAIT, program, fix_argv(argv));
408 if (input_desc != STDIN_FILE_NO)
410 dup2 (org_stdin, STDIN_FILE_NO);
411 close (org_stdin);
414 if (output_desc != STDOUT_FILE_NO)
416 dup2 (org_stdout, STDOUT_FILE_NO);
417 close (org_stdout);
420 if (pid == -1)
422 *errmsg_fmt = install_error_msg;
423 *errmsg_arg = program;
424 return -1;
427 return pid;
430 /* MS CRTDLL doesn't return enough information in status to decide if the
431 child exited due to a signal or not, rather it simply returns an
432 integer with the exit code of the child; eg., if the child exited with
433 an abort() call and didn't have a handler for SIGABRT, it simply returns
434 with status = 3. We fix the status code to conform to the usual WIF*
435 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
438 pwait (pid, status, flags)
439 int pid;
440 int *status;
441 int flags;
443 #ifdef __CYGWIN__
444 return wait (status);
445 #else
446 int termstat;
448 pid = _cwait (&termstat, pid, WAIT_CHILD);
450 /* ??? Here's an opportunity to canonicalize the values in STATUS.
451 Needed? */
453 /* cwait returns the child process exit code in termstat.
454 A value of 3 indicates that the child caught a signal, but not
455 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
456 report SIGABRT. */
457 if (termstat == 3)
458 *status = SIGABRT;
459 else
460 *status = (((termstat) & 0xff) << 8);
462 return pid;
463 #endif /* __CYGWIN__ */
466 #endif /* _WIN32 && ! _UWIN */
468 #ifdef OS2
470 /* ??? Does OS2 have process.h? */
471 extern int spawnv ();
472 extern int spawnvp ();
475 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
476 const char *program;
477 char * const *argv;
478 const char *this_pname;
479 const char *temp_base;
480 char **errmsg_fmt, **errmsg_arg;
481 int flags;
483 int pid;
485 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
486 abort ();
487 /* ??? Presumably 1 == _P_NOWAIT. */
488 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
489 if (pid == -1)
491 *errmsg_fmt = install_error_msg;
492 *errmsg_arg = program;
493 return -1;
495 return pid;
499 pwait (pid, status, flags)
500 int pid;
501 int *status;
502 int flags;
504 /* ??? Here's an opportunity to canonicalize the values in STATUS.
505 Needed? */
506 int pid = wait (status);
507 return pid;
510 #endif /* OS2 */
512 #ifdef MPW
514 /* MPW pexecute doesn't actually run anything; instead, it writes out
515 script commands that, when run, will do the actual executing.
517 For example, in GCC's case, GCC will write out several script commands:
519 cpp ...
520 cc1 ...
521 as ...
522 ld ...
524 and then exit. None of the above programs will have run yet. The task
525 that called GCC will then execute the script and cause cpp,etc. to run.
526 The caller must invoke pfinish before calling exit. This adds
527 the finishing touches to the generated script. */
529 static int first_time = 1;
532 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
533 const char *program;
534 char * const *argv;
535 const char *this_pname;
536 const char *temp_base;
537 char **errmsg_fmt, **errmsg_arg;
538 int flags;
540 char tmpprogram[255];
541 char *cp, *tmpname;
542 int i;
544 mpwify_filename (program, tmpprogram);
545 if (first_time)
547 printf ("Set Failed 0\n");
548 first_time = 0;
551 fputs ("If {Failed} == 0\n", stdout);
552 /* If being verbose, output a copy of the command. It should be
553 accurate enough and escaped enough to be "clickable". */
554 if (flags & PEXECUTE_VERBOSE)
556 fputs ("\tEcho ", stdout);
557 fputc ('\'', stdout);
558 fputs (tmpprogram, stdout);
559 fputc ('\'', stdout);
560 fputc (' ', stdout);
561 for (i=1; argv[i]; i++)
563 fputc ('\'', stdout);
564 /* See if we have an argument that needs fixing. */
565 if (strchr(argv[i], '/'))
567 tmpname = (char *) xmalloc (256);
568 mpwify_filename (argv[i], tmpname);
569 argv[i] = tmpname;
571 for (cp = argv[i]; *cp; cp++)
573 /* Write an Option-d escape char in front of special chars. */
574 if (strchr("'+", *cp))
575 fputc ('\266', stdout);
576 fputc (*cp, stdout);
578 fputc ('\'', stdout);
579 fputc (' ', stdout);
581 fputs ("\n", stdout);
583 fputs ("\t", stdout);
584 fputs (tmpprogram, stdout);
585 fputc (' ', stdout);
587 for (i=1; argv[i]; i++)
589 /* See if we have an argument that needs fixing. */
590 if (strchr(argv[i], '/'))
592 tmpname = (char *) xmalloc (256);
593 mpwify_filename (argv[i], tmpname);
594 argv[i] = tmpname;
596 if (strchr (argv[i], ' '))
597 fputc ('\'', stdout);
598 for (cp = argv[i]; *cp; cp++)
600 /* Write an Option-d escape char in front of special chars. */
601 if (strchr("'+", *cp))
602 fputc ('\266', stdout);
603 fputc (*cp, stdout);
605 if (strchr (argv[i], ' '))
606 fputc ('\'', stdout);
607 fputc (' ', stdout);
610 fputs ("\n", stdout);
612 /* Output commands that arrange to clean up and exit if a failure occurs.
613 We have to be careful to collect the status from the program that was
614 run, rather than some other script command. Also, we don't exit
615 immediately, since necessary cleanups are at the end of the script. */
616 fputs ("\tSet TmpStatus {Status}\n", stdout);
617 fputs ("\tIf {TmpStatus} != 0\n", stdout);
618 fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
619 fputs ("\tEnd\n", stdout);
620 fputs ("End\n", stdout);
622 /* We're just composing a script, can't fail here. */
623 return 0;
627 pwait (pid, status, flags)
628 int pid;
629 int *status;
630 int flags;
632 *status = 0;
633 return 0;
636 /* Write out commands that will exit with the correct error code
637 if something in the script failed. */
639 void
640 pfinish ()
642 printf ("\tExit \"{Failed}\"\n");
645 #endif /* MPW */
647 /* include for Unix-like environments but not for Dos-like environments */
648 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
649 && ! (defined (_WIN32) && ! defined (_UWIN))
651 extern int execv ();
652 extern int execvp ();
655 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
656 const char *program;
657 char * const *argv;
658 const char *this_pname;
659 const char *temp_base ATTRIBUTE_UNUSED;
660 char **errmsg_fmt, **errmsg_arg;
661 int flags;
663 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
664 int pid;
665 int pdes[2];
666 int input_desc, output_desc;
667 int retries, sleep_interval;
668 /* Pipe waiting from last process, to be used as input for the next one.
669 Value is STDIN_FILE_NO if no pipe is waiting
670 (i.e. the next command is the first of a group). */
671 static int last_pipe_input;
673 /* If this is the first process, initialize. */
674 if (flags & PEXECUTE_FIRST)
675 last_pipe_input = STDIN_FILE_NO;
677 input_desc = last_pipe_input;
679 /* If this isn't the last process, make a pipe for its output,
680 and record it as waiting to be the input to the next process. */
681 if (! (flags & PEXECUTE_LAST))
683 if (pipe (pdes) < 0)
685 *errmsg_fmt = "pipe";
686 *errmsg_arg = NULL;
687 return -1;
689 output_desc = pdes[WRITE_PORT];
690 last_pipe_input = pdes[READ_PORT];
692 else
694 /* Last process. */
695 output_desc = STDOUT_FILE_NO;
696 last_pipe_input = STDIN_FILE_NO;
699 /* Fork a subprocess; wait and retry if it fails. */
700 sleep_interval = 1;
701 for (retries = 0; retries < 4; retries++)
703 pid = vfork ();
704 if (pid >= 0)
705 break;
706 sleep (sleep_interval);
707 sleep_interval *= 2;
710 switch (pid)
712 case -1:
714 *errmsg_fmt = VFORK_STRING;
715 *errmsg_arg = NULL;
716 return -1;
719 case 0: /* child */
720 /* Move the input and output pipes into place, if necessary. */
721 if (input_desc != STDIN_FILE_NO)
723 close (STDIN_FILE_NO);
724 dup (input_desc);
725 close (input_desc);
727 if (output_desc != STDOUT_FILE_NO)
729 close (STDOUT_FILE_NO);
730 dup (output_desc);
731 close (output_desc);
734 /* Close the parent's descs that aren't wanted here. */
735 if (last_pipe_input != STDIN_FILE_NO)
736 close (last_pipe_input);
738 /* Exec the program. */
739 (*func) (program, argv);
741 /* Note: Calling fprintf and exit here doesn't seem right for vfork. */
742 fprintf (stderr, "%s: ", this_pname);
743 fprintf (stderr, install_error_msg, program);
744 fprintf (stderr, ": %s\n", xstrerror (errno));
745 exit (-1);
746 /* NOTREACHED */
747 return 0;
749 default:
750 /* In the parent, after forking.
751 Close the descriptors that we made for this child. */
752 if (input_desc != STDIN_FILE_NO)
753 close (input_desc);
754 if (output_desc != STDOUT_FILE_NO)
755 close (output_desc);
757 /* Return child's process number. */
758 return pid;
763 pwait (pid, status, flags)
764 int pid;
765 int *status;
766 int flags ATTRIBUTE_UNUSED;
768 /* ??? Here's an opportunity to canonicalize the values in STATUS.
769 Needed? */
770 #ifdef VMS
771 pid = waitpid (-1, status, 0);
772 #else
773 pid = wait (status);
774 #endif
775 return pid;
778 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! (_WIN32 && ! _UWIN) */