Initial revision
[official-gcc.git] / gcc / pexecute.c
blobdb43a2efde4b04ddc5d1622d566a405aa34fa585
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 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 #include <stdio.h>
27 #include <errno.h>
29 #ifdef IN_GCC
30 #include "config.h"
31 #include "gansidecl.h"
32 /* ??? Need to find a suitable header file. */
33 #define PEXECUTE_FIRST 1
34 #define PEXECUTE_LAST 2
35 #define PEXECUTE_ONE (PEXECUTE_FIRST + PEXECUTE_LAST)
36 #define PEXECUTE_SEARCH 4
37 #define PEXECUTE_VERBOSE 8
38 #else
39 #include "libiberty.h"
40 #endif
42 /* stdin file number. */
43 #define STDIN_FILE_NO 0
45 /* stdout file number. */
46 #define STDOUT_FILE_NO 1
48 /* value of `pipe': port index for reading. */
49 #define READ_PORT 0
51 /* value of `pipe': port index for writing. */
52 #define WRITE_PORT 1
54 static char *install_error_msg = "installation problem, cannot exec `%s'";
56 /* pexecute: execute a program.
58 PROGRAM and ARGV are the arguments to execv/execvp.
60 THIS_PNAME is name of the calling program (i.e. argv[0]).
62 TEMP_BASE is the path name, sans suffix, of a temporary file to use
63 if needed. This is currently only needed for MSDOS ports that don't use
64 GO32 (do any still exist?). Ports that don't need it can pass NULL.
66 (FLAGS & PEXECUTE_SEARCH) is non-zero if $PATH should be searched
67 (??? It's not clear that GCC passes this flag correctly).
68 (FLAGS & PEXECUTE_FIRST) is nonzero for the first process in chain.
69 (FLAGS & PEXECUTE_FIRST) is nonzero for the last process in chain.
70 FIRST_LAST could be simplified to only mark the last of a chain of processes
71 but that requires the caller to always mark the last one (and not give up
72 early if some error occurs). It's more robust to require the caller to
73 mark both ends of the chain.
75 The result is the pid on systems like Unix where we fork/exec and on systems
76 like WIN32 and OS2 where we use spawn. It is up to the caller to wait for
77 the child.
79 The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
80 for the child here.
82 Upon failure, ERRMSG_FMT and ERRMSG_ARG are set to the text of the error
83 message with an optional argument (if not needed, ERRMSG_ARG is set to
84 NULL), and -1 is returned. `errno' is available to the caller to use.
86 pwait: cover function for wait.
88 PID is the process id of the task to wait for.
89 STATUS is the `status' argument to wait.
90 FLAGS is currently unused (allows future enhancement without breaking
91 upward compatibility). Pass 0 for now.
93 The result is the pid of the child reaped,
94 or -1 for failure (errno says why).
96 On systems that don't support waiting for a particular child, PID is
97 ignored. On systems like MSDOS that don't really multitask pwait
98 is just a mechanism to provide a consistent interface for the caller.
100 pfinish: finish generation of script
102 pfinish is necessary for systems like MPW where a script is generated that
103 runs the requested programs.
106 #ifdef __MSDOS__
108 /* MSDOS doesn't multitask, but for the sake of a consistent interface
109 the code behaves like it does. pexecute runs the program, tucks the
110 exit code away, and returns a "pid". pwait must be called to fetch the
111 exit code. */
113 #include <process.h>
115 /* For communicating information from pexecute to pwait. */
116 static int last_pid = 0;
117 static int last_status = 0;
118 static int last_reaped = 0;
121 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
122 const char *program;
123 char * const *argv;
124 const char *this_pname;
125 const char *temp_base;
126 char **errmsg_fmt, **errmsg_arg;
127 int flags;
129 int rc;
131 last_pid++;
132 if (last_pid < 0)
133 last_pid = 1;
135 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
136 abort ();
138 #ifdef __GO32__
139 /* ??? What are the possible return values from spawnv? */
140 rc = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
141 #else
142 char *scmd, *rf;
143 FILE *argfile;
144 int i, el = flags & PEXECUTE_SEARCH ? 4 : 0;
146 scmd = (char *) xmalloc (strlen (program) + strlen (temp_base) + 6 + el);
147 rf = scmd + strlen(program) + 2 + el;
148 sprintf (scmd, "%s%s @%s.gp", program,
149 (flags & PEXECUTE_SEARCH ? ".exe" : ""), temp_base);
150 argfile = fopen (rf, "w");
151 if (argfile == 0)
153 int errno_save = errno;
154 free (scmd);
155 errno = errno_save;
156 *errmsg_fmt = "cannot open `%s.gp'";
157 *errmsg_arg = temp_base;
158 return -1;
161 for (i=1; argv[i]; i++)
163 char *cp;
164 for (cp = argv[i]; *cp; cp++)
166 if (*cp == '"' || *cp == '\'' || *cp == '\\' || isspace (*cp))
167 fputc ('\\', argfile);
168 fputc (*cp, argfile);
170 fputc ('\n', argfile);
172 fclose (argfile);
174 rc = system (scmd);
177 int errno_save = errno;
178 remove (rf);
179 free (scmd);
180 errno = errno_save;
182 #endif
184 if (rc == -1)
186 *errmsg_fmt = install_error_msg;
187 *errmsg_arg = program;
188 return -1;
191 /* Tuck the status away for pwait, and return a "pid". */
192 last_status = rc << 8;
193 return last_pid;
197 pwait (pid, status, flags)
198 int pid;
199 int *status;
200 int flags;
202 /* On MSDOS each pexecute must be followed by it's associated pwait. */
203 if (pid != last_pid
204 /* Called twice for the same child? */
205 || pid == last_reaped)
207 /* ??? ECHILD would be a better choice. Can we use it here? */
208 errno = EINVAL;
209 return -1;
211 /* ??? Here's an opportunity to canonicalize the values in STATUS.
212 Needed? */
213 *status = last_status;
214 last_reaped = last_pid;
215 return last_pid;
218 #endif /* MSDOS */
220 #if defined (_WIN32) && !defined (__CYGWIN32__)
222 #include <process.h>
223 extern int _spawnv ();
224 extern int _spawnvp ();
226 /* This is a kludge to get around the Microsoft C spawn functions' propensity
227 to remove the outermost set of double quotes from all arguments. */
229 const char * const *
230 fix_argv (argvec)
231 char **argvec;
233 int i;
235 for (i = 1; argvec[i] != 0; i++)
237 int len, j;
238 char *temp, *newtemp;
240 temp = argvec[i];
241 len = strlen (temp);
242 for (j = 0; j < len; j++)
244 if (temp[j] == '"')
246 newtemp = xmalloc (len + 2);
247 strncpy (newtemp, temp, j);
248 newtemp [j] = '\\';
249 strncpy (&newtemp [j+1], &temp [j], len-j);
250 newtemp [len+1] = 0;
251 temp = newtemp;
252 len++;
253 j++;
257 argvec[i] = temp;
260 return (const char * const *) argvec;
264 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
265 const char *program;
266 char * const *argv;
267 const char *this_pname;
268 const char *temp_base;
269 char **errmsg_fmt, **errmsg_arg;
270 int flags;
272 int pid;
274 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
275 abort ();
276 pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv)
277 (_P_NOWAIT, program, fix_argv(argv));
278 if (pid == -1)
280 *errmsg_fmt = install_error_msg;
281 *errmsg_arg = program;
282 return -1;
284 return pid;
288 pwait (pid, status, flags)
289 int pid;
290 int *status;
291 int flags;
293 /* ??? Here's an opportunity to canonicalize the values in STATUS.
294 Needed? */
295 return _cwait (status, pid, WAIT_CHILD);
298 #endif /* _WIN32 */
300 #ifdef OS2
302 /* ??? Does OS2 have process.h? */
303 extern int spawnv ();
304 extern int spawnvp ();
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;
317 if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
318 abort ();
319 /* ??? Presumably 1 == _P_NOWAIT. */
320 pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
321 if (pid == -1)
323 *errmsg_fmt = install_error_msg;
324 *errmsg_arg = program;
325 return -1;
327 return pid;
331 pwait (pid, status, flags)
332 int pid;
333 int *status;
334 int flags;
336 /* ??? Here's an opportunity to canonicalize the values in STATUS.
337 Needed? */
338 int pid = wait (status);
339 return pid;
342 #endif /* OS2 */
344 #ifdef MPW
346 /* MPW pexecute doesn't actually run anything; instead, it writes out
347 script commands that, when run, will do the actual executing.
349 For example, in GCC's case, GCC will write out several script commands:
351 cpp ...
352 cc1 ...
353 as ...
354 ld ...
356 and then exit. None of the above programs will have run yet. The task
357 that called GCC will then execute the script and cause cpp,etc. to run.
358 The caller must invoke pfinish before calling exit. This adds
359 the finishing touches to the generated script. */
361 static int first_time = 1;
364 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
365 const char *program;
366 char * const *argv;
367 const char *this_pname;
368 const char *temp_base;
369 char **errmsg_fmt, **errmsg_arg;
370 int flags;
372 char tmpprogram[255];
373 char *cp, *tmpname;
374 int i;
376 mpwify_filename (program, tmpprogram);
377 if (first_time)
379 printf ("Set Failed 0\n");
380 first_time = 0;
383 fputs ("If {Failed} == 0\n", stdout);
384 /* If being verbose, output a copy of the command. It should be
385 accurate enough and escaped enough to be "clickable". */
386 if (flags & PEXECUTE_VERBOSE)
388 fputs ("\tEcho ", stdout);
389 fputc ('\'', stdout);
390 fputs (tmpprogram, stdout);
391 fputc ('\'', stdout);
392 fputc (' ', stdout);
393 for (i=1; argv[i]; i++)
395 fputc ('\'', stdout);
396 /* See if we have an argument that needs fixing. */
397 if (strchr(argv[i], '/'))
399 tmpname = xmalloc (256);
400 mpwify_filename (argv[i], tmpname);
401 argv[i] = tmpname;
403 for (cp = argv[i]; *cp; cp++)
405 /* Write an Option-d escape char in front of special chars. */
406 if (strchr("'+", *cp))
407 fputc ('\266', stdout);
408 fputc (*cp, stdout);
410 fputc ('\'', stdout);
411 fputc (' ', stdout);
413 fputs ("\n", stdout);
415 fputs ("\t", stdout);
416 fputs (tmpprogram, stdout);
417 fputc (' ', stdout);
419 for (i=1; argv[i]; i++)
421 /* See if we have an argument that needs fixing. */
422 if (strchr(argv[i], '/'))
424 tmpname = xmalloc (256);
425 mpwify_filename (argv[i], tmpname);
426 argv[i] = tmpname;
428 if (strchr (argv[i], ' '))
429 fputc ('\'', stdout);
430 for (cp = argv[i]; *cp; cp++)
432 /* Write an Option-d escape char in front of special chars. */
433 if (strchr("'+", *cp))
434 fputc ('\266', stdout);
435 fputc (*cp, stdout);
437 if (strchr (argv[i], ' '))
438 fputc ('\'', stdout);
439 fputc (' ', stdout);
442 fputs ("\n", stdout);
444 /* Output commands that arrange to clean up and exit if a failure occurs.
445 We have to be careful to collect the status from the program that was
446 run, rather than some other script command. Also, we don't exit
447 immediately, since necessary cleanups are at the end of the script. */
448 fputs ("\tSet TmpStatus {Status}\n", stdout);
449 fputs ("\tIf {TmpStatus} != 0\n", stdout);
450 fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
451 fputs ("\tEnd\n", stdout);
452 fputs ("End\n", stdout);
454 /* We're just composing a script, can't fail here. */
455 return 0;
459 pwait (pid, status, flags)
460 int pid;
461 int *status;
462 int flags;
464 *status = 0;
465 return 0;
468 /* Write out commands that will exit with the correct error code
469 if something in the script failed. */
471 void
472 pfinish ()
474 printf ("\tExit \"{Failed}\"\n");
477 #endif /* MPW */
479 /* include for Unix-like environments but not for Dos-like environments */
480 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
481 && (defined (__CYGWIN32__) || ! defined (_WIN32))
483 #ifdef VMS
484 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
485 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
486 #else
487 #ifdef USG
488 #define vfork fork
489 #endif
490 #endif
492 extern int execv ();
493 extern int execvp ();
496 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
497 const char *program;
498 char * const *argv;
499 const char *this_pname;
500 const char *temp_base;
501 char **errmsg_fmt, **errmsg_arg;
502 int flags;
504 int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
505 int pid;
506 int pdes[2];
507 int input_desc, output_desc;
508 int retries, sleep_interval;
509 /* Pipe waiting from last process, to be used as input for the next one.
510 Value is STDIN_FILE_NO if no pipe is waiting
511 (i.e. the next command is the first of a group). */
512 static int last_pipe_input;
514 /* If this is the first process, initialize. */
515 if (flags & PEXECUTE_FIRST)
516 last_pipe_input = STDIN_FILE_NO;
518 input_desc = last_pipe_input;
520 /* If this isn't the last process, make a pipe for its output,
521 and record it as waiting to be the input to the next process. */
522 if (! (flags & PEXECUTE_LAST))
524 if (pipe (pdes) < 0)
526 *errmsg_fmt = "pipe";
527 *errmsg_arg = NULL;
528 return -1;
530 output_desc = pdes[WRITE_PORT];
531 last_pipe_input = pdes[READ_PORT];
533 else
535 /* Last process. */
536 output_desc = STDOUT_FILE_NO;
537 last_pipe_input = STDIN_FILE_NO;
540 /* Fork a subprocess; wait and retry if it fails. */
541 sleep_interval = 1;
542 for (retries = 0; retries < 4; retries++)
544 pid = vfork ();
545 if (pid >= 0)
546 break;
547 sleep (sleep_interval);
548 sleep_interval *= 2;
551 switch (pid)
553 case -1:
555 #ifdef vfork
556 *errmsg_fmt = "fork";
557 #else
558 *errmsg_fmt = "vfork";
559 #endif
560 *errmsg_arg = NULL;
561 return -1;
564 case 0: /* child */
565 /* Move the input and output pipes into place, if necessary. */
566 if (input_desc != STDIN_FILE_NO)
568 close (STDIN_FILE_NO);
569 dup (input_desc);
570 close (input_desc);
572 if (output_desc != STDOUT_FILE_NO)
574 close (STDOUT_FILE_NO);
575 dup (output_desc);
576 close (output_desc);
579 /* Close the parent's descs that aren't wanted here. */
580 if (last_pipe_input != STDIN_FILE_NO)
581 close (last_pipe_input);
583 /* Exec the program. */
584 (*func) (program, argv);
586 /* Note: Calling fprintf and exit here doesn't seem right for vfork. */
587 fprintf (stderr, "%s: ", this_pname);
588 fprintf (stderr, install_error_msg, program);
589 #ifdef IN_GCC
590 fprintf (stderr, ": %s\n", my_strerror (errno));
591 #else
592 fprintf (stderr, ": %s\n", xstrerror (errno));
593 #endif
594 exit (-1);
595 /* NOTREACHED */
596 return 0;
598 default:
599 /* In the parent, after forking.
600 Close the descriptors that we made for this child. */
601 if (input_desc != STDIN_FILE_NO)
602 close (input_desc);
603 if (output_desc != STDOUT_FILE_NO)
604 close (output_desc);
606 /* Return child's process number. */
607 return pid;
612 pwait (pid, status, flags)
613 int pid;
614 int *status;
615 int flags;
617 /* ??? Here's an opportunity to canonicalize the values in STATUS.
618 Needed? */
619 #ifdef VMS
620 pid = waitpid (-1, status, 0);
621 #else
622 pid = wait (status);
623 #endif
624 return pid;
627 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! _WIN32 */