Define ENTRY in PE emulation files. Also:
[binutils.git] / libiberty / pexecute.c
blobc644c98e0feb42060d9c8610b7a20deadbde5e1c
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, 1997, 1998 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_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #define ISSPACE (x) isspace(x)
36 #ifdef HAVE_SYS_WAIT_H
37 #include <sys/wait.h>
38 #endif
40 #ifdef vfork /* Autoconf may define this to fork for us. */
41 # define VFORK_STRING "fork"
42 #else
43 # define VFORK_STRING "vfork"
44 #endif
45 #ifdef HAVE_VFORK_H
46 #include <vfork.h>
47 #endif
48 #ifdef VMS
49 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
50 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
51 #endif /* VMS */
53 #include "libiberty.h"
55 #if !defined (__CYGWIN__) && defined (__CYGWIN32__)
56 #define __CYGWIN__ 1
57 #endif
59 /* stdin file number. */
60 #define STDIN_FILE_NO 0
62 /* stdout file number. */
63 #define STDOUT_FILE_NO 1
65 /* value of `pipe': port index for reading. */
66 #define READ_PORT 0
68 /* value of `pipe': port index for writing. */
69 #define WRITE_PORT 1
71 static char *install_error_msg = "installation problem, cannot exec `%s'";
73 /* pexecute: execute a program.
75 PROGRAM and ARGV are the arguments to execv/execvp.
77 THIS_PNAME is name of the calling program (i.e. argv[0]).
79 TEMP_BASE is the path name, sans suffix, of a temporary file to use
80 if needed. This is currently only needed for MSDOS ports that don't use
81 GO32 (do any still exist?). Ports that don't need it can pass NULL.
83 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
84 (??? It's not clear that GCC passes this flag correctly).
85 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
86 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
87 FIRST_LAST could be simplified to only mark the last of a chain of processes
88 but that requires the caller to always mark the last one (and not give up
89 early if some error occurs). It's more robust to require the caller to
90 mark both ends of the chain.
92 The result is the pid on systems like Unix where we fork/exec and on systems
93 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
94 the child.
96 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
97 for the child here.
99 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
100 message with an optional argument (if not needed, ERRMSG_ARG is set to
101 NULL), and -1 is returned. `errno' is available to the caller to use.
103 pwait: cover function for wait.
105 PID is the process id of the task to wait for.
106 STATUS is the `status' argument to wait.
107 FLAGS is currently unused (allows future enhancement without breaking
108 upward compatibility). Pass 0 for now.
110 The result is the pid of the child reaped,
111 or -1 for failure (errno says why).
113 On systems that don't support waiting for a particular child, PID is
114 ignored. On systems like MSDOS that don't really multitask pwait
115 is just a mechanism to provide a consistent interface for the caller.
117 pfinish: finish generation of script
119 pfinish is necessary for systems like MPW where a script is generated that
120 runs the requested programs.
123 #ifdef __MSDOS__
125 /* MSDOS doesn't multitask, but for the sake of a consistent interface
126 the code behaves like it does. pexecute runs the program, tucks the
127 exit code away, and returns a "pid". pwait must be called to fetch the
128 exit code. */
130 #include <process.h>
132 /* For communicating information from pexecute to pwait. */
133 static int last_pid = 0;
134 static int last_status = 0;
135 static int last_reaped = 0;
138 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
139 const char *program;
140 char * const *argv;
141 const char *this_pname;
142 const char *temp_base;
143 char **errmsg_fmt, **errmsg_arg;
144 int flags;
146 int rc;
148 last_pid++;
149 if (last_pid < 0)
150 last_pid = 1;
152 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
153 abort ();
155 #ifdef __GO32__
156 /* ??? What are the possible return values from spawnv? */
157 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
158 #else
159 char *scmd, *rf;
160 FILE *argfile;
161 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
163 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
164 rf = scmd + strlen(program) + 2 + el;
165 sprintf (scmd, "%s%s @%s.gp", program,
166 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
167 argfile = fopen (rf, "w");
168 if (argfile == 0)
170 int errno_save = errno;
171 free (scmd);
172 errno = errno_save;
173 *errmsg_fmt = "cannot open `%s.gp'";
174 *errmsg_arg = temp_base;
175 return -1;
178 for (i=1; argv[i]; i++)
180 char *cp;
181 for (cp = argv[i]; *cp; cp++)
183 if (*cp == '"' || *cp == '\'' || *cp == '\\' || ISSPACE (*cp))
184 fputc ('\\', argfile);
185 fputc (*cp, argfile);
187 fputc ('\n', argfile);
189 fclose (argfile);
191 rc = system (scmd);
194 int errno_save = errno;
195 remove (rf);
196 free (scmd);
197 errno = errno_save;
199 #endif
201 if (rc == -1)
203 *errmsg_fmt = install_error_msg;
204 *errmsg_arg = program;
205 return -1;
208 /* Tuck the status away for pwait, and return a "pid". */
209 last_status = rc << 8;
210 return last_pid;
214 pwait (pid, status, flags)
215 int pid;
216 int *status;
217 int flags;
219 /* On MSDOS each pexecute must be followed by it's associated pwait. */
220 if (pid != last_pid
221 /* Called twice for the same child? */
222 || pid == last_reaped)
224 /* ??? ECHILD would be a better choice. Can we use it here? */
225 errno = EINVAL;
226 return -1;
228 /* ??? Here's an opportunity to canonicalize the values in STATUS.
229 Needed? */
230 *status = last_status;
231 last_reaped = last_pid;
232 return last_pid;
235 #endif /* MSDOS */
237 #if defined (_WIN32) && ! defined (__UWIN__)
239 #include <process.h>
241 #ifdef __CYGWIN__
243 #define fix_argv(argvec) (argvec)
245 extern int _spawnv ();
246 extern int _spawnvp ();
248 #else /* ! __CYGWIN__ */
250 /* This is a kludge to get around the Microsoft C spawn functions' propensity
251 to remove the outermost set of double quotes from all arguments. */
253 const char * const *
254 fix_argv (argvec)
255 char **argvec;
257 int i;
259 for (i = 1; argvec[i] != 0; i++)
261 int len, j;
262 char *temp, *newtemp;
264 temp = argvec[i];
265 len = strlen (temp);
266 for (j = 0; j < len; j++)
268 if (temp[j] == '"')
270 newtemp = xmalloc (len + 2);
271 strncpy (newtemp, temp, j);
272 newtemp [j] = '\\';
273 strncpy (&newtemp [j+1], &temp [j], len-j);
274 newtemp [len+1] = 0;
275 temp = newtemp;
276 len++;
277 j++;
281 argvec[i] = temp;
284 return (const char * const *) argvec;
286 #endif /* __CYGWIN__ */
288 #include <io.h>
289 #include <fcntl.h>
290 #include <signal.h>
292 /* mingw32 headers may not define the following. */
294 #ifndef _P_WAIT
295 # define _P_WAIT 0
296 # define _P_NOWAIT 1
297 # define _P_OVERLAY 2
298 # define _P_NOWAITO 3
299 # define _P_DETACH 4
301 # define WAIT_CHILD 0
302 # define WAIT_GRANDCHILD 1
303 #endif
305 /* Win32 supports pipes */
307 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
308 const char *program;
309 char * const *argv;
310 const char *this_pname;
311 const char *temp_base;
312 char **errmsg_fmt, **errmsg_arg;
313 int flags;
315 int pid;
316 int pdes[2], org_stdin, org_stdout;
317 int input_desc, output_desc;
318 int retries, sleep_interval;
320 /* Pipe waiting from last process, to be used as input for the next one.
321 Value is STDIN_FILE_NO if no pipe is waiting
322 (i.e. the next command is the first of a group). */
323 static int last_pipe_input;
325 /* If this is the first process, initialize. */
326 if (flags & PEXECUTE_FIRST)
327 last_pipe_input = STDIN_FILE_NO;
329 input_desc = last_pipe_input;
331 /* If this isn't the last process, make a pipe for its output,
332 and record it as waiting to be the input to the next process. */
333 if (! (flags & PEXECUTE_LAST))
335 if (_pipe (pdes, 256, O_BINARY) < 0)
337 *errmsg_fmt = "pipe";
338 *errmsg_arg = NULL;
339 return -1;
341 output_desc = pdes[WRITE_PORT];
342 last_pipe_input = pdes[READ_PORT];
344 else
346 /* Last process. */
347 output_desc = STDOUT_FILE_NO;
348 last_pipe_input = STDIN_FILE_NO;
351 if (input_desc != STDIN_FILE_NO)
353 org_stdin = dup (STDIN_FILE_NO);
354 dup2 (input_desc, STDIN_FILE_NO);
355 close (input_desc);
358 if (output_desc != STDOUT_FILE_NO)
360 org_stdout = dup (STDOUT_FILE_NO);
361 dup2 (output_desc, STDOUT_FILE_NO);
362 close (output_desc);
365 pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv)
366 (_P_NOWAIT, program, fix_argv(argv));
368 if (input_desc != STDIN_FILE_NO)
370 dup2 (org_stdin, STDIN_FILE_NO);
371 close (org_stdin);
374 if (output_desc != STDOUT_FILE_NO)
376 dup2 (org_stdout, STDOUT_FILE_NO);
377 close (org_stdout);
380 if (pid == -1)
382 *errmsg_fmt = install_error_msg;
383 *errmsg_arg = program;
384 return -1;
387 return pid;
390 /* MS CRTDLL doesn't return enough information in status to decide if the
391 child exited due to a signal or not, rather it simply returns an
392 integer with the exit code of the child; eg., if the child exited with
393 an abort() call and didn't have a handler for SIGABRT, it simply returns
394 with status = 3. We fix the status code to conform to the usual WIF*
395 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
398 pwait (pid, status, flags)
399 int pid;
400 int *status;
401 int flags;
403 #ifdef __CYGWIN__
404 return wait (status);
405 #else
406 int termstat;
408 pid = _cwait (&termstat, pid, WAIT_CHILD);
410 /* ??? Here's an opportunity to canonicalize the values in STATUS.
411 Needed? */
413 /* cwait returns the child process exit code in termstat.
414 A value of 3 indicates that the child caught a signal, but not
415 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
416 report SIGABRT. */
417 if (termstat == 3)
418 *status = SIGABRT;
419 else
420 *status = (((termstat) & 0xff) << 8);
422 return pid;
423 #endif /* __CYGWIN__ */
426 #endif /* _WIN32 && ! __UWIN__ */
428 #ifdef OS2
430 /* ??? Does OS2 have process.h? */
431 extern int spawnv ();
432 extern int spawnvp ();
435 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
436 const char *program;
437 char * const *argv;
438 const char *this_pname;
439 const char *temp_base;
440 char **errmsg_fmt, **errmsg_arg;
441 int flags;
443 int pid;
445 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
446 abort ();
447 /* ??? Presumably 1 == _P_NOWAIT. */
448 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
449 if (pid == -1)
451 *errmsg_fmt = install_error_msg;
452 *errmsg_arg = program;
453 return -1;
455 return pid;
459 pwait (pid, status, flags)
460 int pid;
461 int *status;
462 int flags;
464 /* ??? Here's an opportunity to canonicalize the values in STATUS.
465 Needed? */
466 int pid = wait (status);
467 return pid;
470 #endif /* OS2 */
472 #ifdef MPW
474 /* MPW pexecute doesn't actually run anything; instead, it writes out
475 script commands that, when run, will do the actual executing.
477 For example, in GCC's case, GCC will write out several script commands:
479 cpp ...
480 cc1 ...
481 as ...
482 ld ...
484 and then exit. None of the above programs will have run yet. The task
485 that called GCC will then execute the script and cause cpp,etc. to run.
486 The caller must invoke pfinish before calling exit. This adds
487 the finishing touches to the generated script. */
489 static int first_time = 1;
492 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
493 const char *program;
494 char * const *argv;
495 const char *this_pname;
496 const char *temp_base;
497 char **errmsg_fmt, **errmsg_arg;
498 int flags;
500 char tmpprogram[255];
501 char *cp, *tmpname;
502 int i;
504 mpwify_filename (program, tmpprogram);
505 if (first_time)
507 printf ("Set Failed 0\n");
508 first_time = 0;
511 fputs ("If {Failed} == 0\n", stdout);
512 /* If being verbose, output a copy of the command. It should be
513 accurate enough and escaped enough to be "clickable". */
514 if (flags & PEXECUTE_VERBOSE)
516 fputs ("\tEcho ", stdout);
517 fputc ('\'', stdout);
518 fputs (tmpprogram, stdout);
519 fputc ('\'', stdout);
520 fputc (' ', stdout);
521 for (i=1; argv[i]; i++)
523 fputc ('\'', stdout);
524 /* See if we have an argument that needs fixing. */
525 if (strchr(argv[i], '/'))
527 tmpname = (char *) xmalloc (256);
528 mpwify_filename (argv[i], tmpname);
529 argv[i] = tmpname;
531 for (cp = argv[i]; *cp; cp++)
533 /* Write an Option-d escape char in front of special chars. */
534 if (strchr("'+", *cp))
535 fputc ('\266', stdout);
536 fputc (*cp, stdout);
538 fputc ('\'', stdout);
539 fputc (' ', stdout);
541 fputs ("\n", stdout);
543 fputs ("\t", stdout);
544 fputs (tmpprogram, stdout);
545 fputc (' ', stdout);
547 for (i=1; argv[i]; i++)
549 /* See if we have an argument that needs fixing. */
550 if (strchr(argv[i], '/'))
552 tmpname = (char *) xmalloc (256);
553 mpwify_filename (argv[i], tmpname);
554 argv[i] = tmpname;
556 if (strchr (argv[i], ' '))
557 fputc ('\'', stdout);
558 for (cp = argv[i]; *cp; cp++)
560 /* Write an Option-d escape char in front of special chars. */
561 if (strchr("'+", *cp))
562 fputc ('\266', stdout);
563 fputc (*cp, stdout);
565 if (strchr (argv[i], ' '))
566 fputc ('\'', stdout);
567 fputc (' ', stdout);
570 fputs ("\n", stdout);
572 /* Output commands that arrange to clean up and exit if a failure occurs.
573 We have to be careful to collect the status from the program that was
574 run, rather than some other script command. Also, we don't exit
575 immediately, since necessary cleanups are at the end of the script. */
576 fputs ("\tSet TmpStatus {Status}\n", stdout);
577 fputs ("\tIf {TmpStatus} != 0\n", stdout);
578 fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
579 fputs ("\tEnd\n", stdout);
580 fputs ("End\n", stdout);
582 /* We're just composing a script, can't fail here. */
583 return 0;
587 pwait (pid, status, flags)
588 int pid;
589 int *status;
590 int flags;
592 *status = 0;
593 return 0;
596 /* Write out commands that will exit with the correct error code
597 if something in the script failed. */
599 void
600 pfinish ()
602 printf ("\tExit \"{Failed}\"\n");
605 #endif /* MPW */
607 /* include for Unix-like environments but not for Dos-like environments */
608 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
609 && ! (defined (_WIN32) && ! defined (__UWIN__))
611 extern int execv ();
612 extern int execvp ();
615 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
616 const char *program;
617 char * const *argv;
618 const char *this_pname;
619 const char *temp_base ATTRIBUTE_UNUSED;
620 char **errmsg_fmt, **errmsg_arg;
621 int flags;
623 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
624 int pid;
625 int pdes[2];
626 int input_desc, output_desc;
627 int retries, sleep_interval;
628 /* Pipe waiting from last process, to be used as input for the next one.
629 Value is STDIN_FILE_NO if no pipe is waiting
630 (i.e. the next command is the first of a group). */
631 static int last_pipe_input;
633 /* If this is the first process, initialize. */
634 if (flags & PEXECUTE_FIRST)
635 last_pipe_input = STDIN_FILE_NO;
637 input_desc = last_pipe_input;
639 /* If this isn't the last process, make a pipe for its output,
640 and record it as waiting to be the input to the next process. */
641 if (! (flags & PEXECUTE_LAST))
643 if (pipe (pdes) < 0)
645 *errmsg_fmt = "pipe";
646 *errmsg_arg = NULL;
647 return -1;
649 output_desc = pdes[WRITE_PORT];
650 last_pipe_input = pdes[READ_PORT];
652 else
654 /* Last process. */
655 output_desc = STDOUT_FILE_NO;
656 last_pipe_input = STDIN_FILE_NO;
659 /* Fork a subprocess; wait and retry if it fails. */
660 sleep_interval = 1;
661 for (retries = 0; retries < 4; retries++)
663 pid = vfork ();
664 if (pid >= 0)
665 break;
666 sleep (sleep_interval);
667 sleep_interval *= 2;
670 switch (pid)
672 case -1:
674 *errmsg_fmt = VFORK_STRING;
675 *errmsg_arg = NULL;
676 return -1;
679 case 0: /* child */
680 /* Move the input and output pipes into place, if necessary. */
681 if (input_desc != STDIN_FILE_NO)
683 close (STDIN_FILE_NO);
684 dup (input_desc);
685 close (input_desc);
687 if (output_desc != STDOUT_FILE_NO)
689 close (STDOUT_FILE_NO);
690 dup (output_desc);
691 close (output_desc);
694 /* Close the parent's descs that aren't wanted here. */
695 if (last_pipe_input != STDIN_FILE_NO)
696 close (last_pipe_input);
698 /* Exec the program. */
699 (*func) (program, argv);
701 /* Note: Calling fprintf and exit here doesn't seem right for vfork. */
702 fprintf (stderr, "%s: ", this_pname);
703 fprintf (stderr, install_error_msg, program);
704 fprintf (stderr, ": %s\n", xstrerror (errno));
705 exit (-1);
706 /* NOTREACHED */
707 return 0;
709 default:
710 /* In the parent, after forking.
711 Close the descriptors that we made for this child. */
712 if (input_desc != STDIN_FILE_NO)
713 close (input_desc);
714 if (output_desc != STDOUT_FILE_NO)
715 close (output_desc);
717 /* Return child's process number. */
718 return pid;
723 pwait (pid, status, flags)
724 int pid;
725 int *status;
726 int flags ATTRIBUTE_UNUSED;
728 /* ??? Here's an opportunity to canonicalize the values in STATUS.
729 Needed? */
730 #ifdef VMS
731 pid = waitpid (-1, status, 0);
732 #else
733 pid = wait (status);
734 #endif
735 return pid;
738 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! (_WIN32 && ! __UWIN__) */