20000629-1.f: New test.
[official-gcc.git] / libiberty / pexecute.c
blobf1aea9db7f0eb625c64a38358ecfea3243dbf5f9
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 #ifdef HAVE_STDLIB_H
39 #include <stdlib.h>
40 #endif
41 #define ISSPACE (x) isspace(x)
42 #ifdef HAVE_SYS_WAIT_H
43 #include <sys/wait.h>
44 #endif
46 #ifdef vfork /* Autoconf may define this to fork for us. */
47 # define VFORK_STRING "fork"
48 #else
49 # define VFORK_STRING "vfork"
50 #endif
51 #ifdef HAVE_VFORK_H
52 #include <vfork.h>
53 #endif
54 #ifdef VMS
55 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
56 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
57 #endif /* VMS */
59 #include "libiberty.h"
61 /* stdin file number. */
62 #define STDIN_FILE_NO 0
64 /* stdout file number. */
65 #define STDOUT_FILE_NO 1
67 /* value of `pipe': port index for reading. */
68 #define READ_PORT 0
70 /* value of `pipe': port index for writing. */
71 #define WRITE_PORT 1
73 static char *install_error_msg = "installation problem, cannot exec `%s'";
75 /* pexecute: execute a program.
77 PROGRAM and ARGV are the arguments to execv/execvp.
79 THIS_PNAME is name of the calling program (i.e. argv[0]).
81 TEMP_BASE is the path name, sans suffix, of a temporary file to use
82 if needed. This is currently only needed for MSDOS ports that don't use
83 GO32 (do any still exist?). Ports that don't need it can pass NULL.
85 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
86 (??? It's not clear that GCC passes this flag correctly).
87 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
88 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
89 FIRST_LAST could be simplified to only mark the last of a chain of processes
90 but that requires the caller to always mark the last one (and not give up
91 early if some error occurs). It's more robust to require the caller to
92 mark both ends of the chain.
94 The result is the pid on systems like Unix where we fork/exec and on systems
95 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
96 the child.
98 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
99 for the child here.
101 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
102 message with an optional argument (if not needed, ERRMSG_ARG is set to
103 NULL), and -1 is returned. `errno' is available to the caller to use.
105 pwait: cover function for wait.
107 PID is the process id of the task to wait for.
108 STATUS is the `status' argument to wait.
109 FLAGS is currently unused (allows future enhancement without breaking
110 upward compatibility). Pass 0 for now.
112 The result is the pid of the child reaped,
113 or -1 for failure (errno says why).
115 On systems that don't support waiting for a particular child, PID is
116 ignored. On systems like MSDOS that don't really multitask pwait
117 is just a mechanism to provide a consistent interface for the caller.
119 pfinish: finish generation of script
121 pfinish is necessary for systems like MPW where a script is generated that
122 runs the requested programs.
125 #ifdef __MSDOS__
127 /* MSDOS doesn't multitask, but for the sake of a consistent interface
128 the code behaves like it does. pexecute runs the program, tucks the
129 exit code away, and returns a "pid". pwait must be called to fetch the
130 exit code. */
132 #include <process.h>
134 /* For communicating information from pexecute to pwait. */
135 static int last_pid = 0;
136 static int last_status = 0;
137 static int last_reaped = 0;
140 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
141 const char *program;
142 char * const *argv;
143 const char *this_pname;
144 const char *temp_base;
145 char **errmsg_fmt, **errmsg_arg;
146 int flags;
148 int rc;
150 last_pid++;
151 if (last_pid < 0)
152 last_pid = 1;
154 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
155 abort ();
157 #ifdef __GO32__
158 /* ??? What are the possible return values from spawnv? */
159 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
160 #else
161 char *scmd, *rf;
162 FILE *argfile;
163 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
165 if (temp_base == 0)
166 temp_base = choose_temp_base ();
167 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
168 rf = scmd + strlen(program) + 2 + el;
169 sprintf (scmd, "%s%s @%s.gp", program,
170 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
171 argfile = fopen (rf, "w");
172 if (argfile == 0)
174 int errno_save = errno;
175 free (scmd);
176 errno = errno_save;
177 *errmsg_fmt = "cannot open `%s.gp'";
178 *errmsg_arg = temp_base;
179 return -1;
182 for (i=1; argv[i]; i++)
184 char *cp;
185 for (cp = argv[i]; *cp; cp++)
187 if (*cp == '"' || *cp == '\'' || *cp == '\\' || ISSPACE (*cp))
188 fputc ('\\', argfile);
189 fputc (*cp, argfile);
191 fputc ('\n', argfile);
193 fclose (argfile);
195 rc = system (scmd);
198 int errno_save = errno;
199 remove (rf);
200 free (scmd);
201 errno = errno_save;
203 #endif
205 if (rc == -1)
207 *errmsg_fmt = install_error_msg;
208 *errmsg_arg = program;
209 return -1;
212 /* Tuck the status away for pwait, and return a "pid". */
213 last_status = rc << 8;
214 return last_pid;
218 pwait (pid, status, flags)
219 int pid;
220 int *status;
221 int flags;
223 /* On MSDOS each pexecute must be followed by it's associated pwait. */
224 if (pid != last_pid
225 /* Called twice for the same child? */
226 || pid == last_reaped)
228 /* ??? ECHILD would be a better choice. Can we use it here? */
229 errno = EINVAL;
230 return -1;
232 /* ??? Here's an opportunity to canonicalize the values in STATUS.
233 Needed? */
234 *status = last_status;
235 last_reaped = last_pid;
236 return last_pid;
239 #endif /* MSDOS */
241 #if defined (_WIN32) && ! defined (_UWIN)
243 #include <process.h>
245 #ifdef __CYGWIN__
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. */
257 const char * const *
258 fix_argv (argvec)
259 char **argvec;
261 int i;
263 for (i = 1; argvec[i] != 0; i++)
265 int len, j;
266 char *temp, *newtemp;
268 temp = argvec[i];
269 len = strlen (temp);
270 for (j = 0; j < len; j++)
272 if (temp[j] == '"')
274 newtemp = xmalloc (len + 2);
275 strncpy (newtemp, temp, j);
276 newtemp [j] = '\\';
277 strncpy (&newtemp [j+1], &temp [j], len-j);
278 newtemp [len+1] = 0;
279 temp = newtemp;
280 len++;
281 j++;
285 argvec[i] = temp;
288 for (i = 0; argvec[i] != 0; i++)
290 if (strpbrk (argvec[i], " \t"))
292 int len, trailing_backslash;
293 char *temp;
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. */
305 if (len > 1
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);
316 temp[0] = '"';
317 strcpy (temp + 1, argvec[i]);
318 if (trailing_backslash)
319 temp[len-2] = '\\';
320 temp[len-1] = '"';
321 temp[len] = '\0';
323 argvec[i] = temp;
327 return (const char * const *) argvec;
329 #endif /* __CYGWIN__ */
331 #include <io.h>
332 #include <fcntl.h>
333 #include <signal.h>
335 /* mingw32 headers may not define the following. */
337 #ifndef _P_WAIT
338 # define _P_WAIT 0
339 # define _P_NOWAIT 1
340 # define _P_OVERLAY 2
341 # define _P_NOWAITO 3
342 # define _P_DETACH 4
344 # define WAIT_CHILD 0
345 # define WAIT_GRANDCHILD 1
346 #endif
348 /* Win32 supports pipes */
350 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
351 const char *program;
352 char * const *argv;
353 const char *this_pname;
354 const char *temp_base;
355 char **errmsg_fmt, **errmsg_arg;
356 int flags;
358 int pid;
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";
381 *errmsg_arg = NULL;
382 return -1;
384 output_desc = pdes[WRITE_PORT];
385 last_pipe_input = pdes[READ_PORT];
387 else
389 /* Last process. */
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);
398 close (input_desc);
401 if (output_desc != STDOUT_FILE_NO)
403 org_stdout = dup (STDOUT_FILE_NO);
404 dup2 (output_desc, STDOUT_FILE_NO);
405 close (output_desc);
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);
414 close (org_stdin);
417 if (output_desc != STDOUT_FILE_NO)
419 dup2 (org_stdout, STDOUT_FILE_NO);
420 close (org_stdout);
423 if (pid == -1)
425 *errmsg_fmt = install_error_msg;
426 *errmsg_arg = program;
427 return -1;
430 return pid;
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)
442 int pid;
443 int *status;
444 int flags;
446 #ifdef __CYGWIN__
447 return wait (status);
448 #else
449 int termstat;
451 pid = _cwait (&termstat, pid, WAIT_CHILD);
453 /* ??? Here's an opportunity to canonicalize the values in STATUS.
454 Needed? */
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
459 report SIGABRT. */
460 if (termstat == 3)
461 *status = SIGABRT;
462 else
463 *status = (((termstat) & 0xff) << 8);
465 return pid;
466 #endif /* __CYGWIN__ */
469 #endif /* _WIN32 && ! _UWIN */
471 #ifdef OS2
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)
479 const char *program;
480 char * const *argv;
481 const char *this_pname;
482 const char *temp_base;
483 char **errmsg_fmt, **errmsg_arg;
484 int flags;
486 int pid;
488 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
489 abort ();
490 /* ??? Presumably 1 == _P_NOWAIT. */
491 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
492 if (pid == -1)
494 *errmsg_fmt = install_error_msg;
495 *errmsg_arg = program;
496 return -1;
498 return pid;
502 pwait (pid, status, flags)
503 int pid;
504 int *status;
505 int flags;
507 /* ??? Here's an opportunity to canonicalize the values in STATUS.
508 Needed? */
509 int pid = wait (status);
510 return pid;
513 #endif /* OS2 */
515 #ifdef MPW
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:
522 cpp ...
523 cc1 ...
524 as ...
525 ld ...
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)
536 const char *program;
537 char * const *argv;
538 const char *this_pname;
539 const char *temp_base;
540 char **errmsg_fmt, **errmsg_arg;
541 int flags;
543 char tmpprogram[255];
544 char *cp, *tmpname;
545 int i;
547 mpwify_filename (program, tmpprogram);
548 if (first_time)
550 printf ("Set Failed 0\n");
551 first_time = 0;
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);
563 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);
572 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);
579 fputc (*cp, stdout);
581 fputc ('\'', stdout);
582 fputc (' ', stdout);
584 fputs ("\n", stdout);
586 fputs ("\t", stdout);
587 fputs (tmpprogram, stdout);
588 fputc (' ', 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);
597 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);
606 fputc (*cp, stdout);
608 if (strchr (argv[i], ' '))
609 fputc ('\'', stdout);
610 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. */
626 return 0;
630 pwait (pid, status, flags)
631 int pid;
632 int *status;
633 int flags;
635 *status = 0;
636 return 0;
639 /* Write out commands that will exit with the correct error code
640 if something in the script failed. */
642 void
643 pfinish ()
645 printf ("\tExit \"{Failed}\"\n");
648 #endif /* MPW */
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))
654 extern int execv ();
655 extern int execvp ();
658 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
659 const char *program;
660 char * const *argv;
661 const char *this_pname;
662 const char *temp_base ATTRIBUTE_UNUSED;
663 char **errmsg_fmt, **errmsg_arg;
664 int flags;
666 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
667 int pid;
668 int pdes[2];
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))
686 if (pipe (pdes) < 0)
688 *errmsg_fmt = "pipe";
689 *errmsg_arg = NULL;
690 return -1;
692 output_desc = pdes[WRITE_PORT];
693 last_pipe_input = pdes[READ_PORT];
695 else
697 /* Last process. */
698 output_desc = STDOUT_FILE_NO;
699 last_pipe_input = STDIN_FILE_NO;
702 /* Fork a subprocess; wait and retry if it fails. */
703 sleep_interval = 1;
704 for (retries = 0; retries < 4; retries++)
706 pid = vfork ();
707 if (pid >= 0)
708 break;
709 sleep (sleep_interval);
710 sleep_interval *= 2;
713 switch (pid)
715 case -1:
717 *errmsg_fmt = VFORK_STRING;
718 *errmsg_arg = NULL;
719 return -1;
722 case 0: /* child */
723 /* Move the input and output pipes into place, if necessary. */
724 if (input_desc != STDIN_FILE_NO)
726 close (STDIN_FILE_NO);
727 dup (input_desc);
728 close (input_desc);
730 if (output_desc != STDOUT_FILE_NO)
732 close (STDOUT_FILE_NO);
733 dup (output_desc);
734 close (output_desc);
737 /* Close the parent's descs that aren't wanted here. */
738 if (last_pipe_input != STDIN_FILE_NO)
739 close (last_pipe_input);
741 /* Exec the program. */
742 (*func) (program, argv);
744 /* Note: Calling fprintf and exit here doesn't seem right for vfork. */
745 fprintf (stderr, "%s: ", this_pname);
746 fprintf (stderr, install_error_msg, program);
747 fprintf (stderr, ": %s\n", xstrerror (errno));
748 exit (-1);
749 /* NOTREACHED */
750 return 0;
752 default:
753 /* In the parent, after forking.
754 Close the descriptors that we made for this child. */
755 if (input_desc != STDIN_FILE_NO)
756 close (input_desc);
757 if (output_desc != STDOUT_FILE_NO)
758 close (output_desc);
760 /* Return child's process number. */
761 return pid;
766 pwait (pid, status, flags)
767 int pid;
768 int *status;
769 int flags ATTRIBUTE_UNUSED;
771 /* ??? Here's an opportunity to canonicalize the values in STATUS.
772 Needed? */
773 #ifdef VMS
774 pid = waitpid (-1, status, 0);
775 #else
776 pid = wait (status);
777 #endif
778 return pid;
781 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! (_WIN32 && ! _UWIN) */