OSDN Git Service

91th Cygnus<->FSF merge
[pf3gnuchains/gcc-fork.git] / gcc / pexecute.c
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.
4
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.
10
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.
15
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.  */
20
21 /* This file exports two functions: pexecute and pwait.  */
22
23 /* This file lives in at least two places: libiberty and gcc.
24    Don't change one without the other.  */
25
26 #include <stdio.h>
27 #include <errno.h>
28
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
41
42 /* stdin file number.  */
43 #define STDIN_FILE_NO 0
44
45 /* stdout file number.  */
46 #define STDOUT_FILE_NO 1
47
48 /* value of `pipe': port index for reading.  */
49 #define READ_PORT 0
50
51 /* value of `pipe': port index for writing.  */
52 #define WRITE_PORT 1
53
54 static char *install_error_msg = "installation problem, cannot exec `%s'";
55
56 /* pexecute: execute a program.
57
58    PROGRAM and ARGV are the arguments to execv/execvp.
59
60    THIS_PNAME is name of the calling program (i.e. argv[0]).
61
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.
65
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.
74
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.
78
79    The result is the WEXITSTATUS on systems like MSDOS where we spawn and wait
80    for the child here.
81
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.
85
86    pwait: cover function for wait.
87
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.
92
93    The result is the pid of the child reaped,
94    or -1 for failure (errno says why).
95
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.
99
100    pfinish: finish generation of script
101
102    pfinish is necessary for systems like MPW where a script is generated that
103    runs the requested programs.
104 */
105
106 #ifdef __MSDOS__
107
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.  */
112
113 #include <process.h>
114
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;
119
120 int
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;
128 {
129   int rc;
130
131   last_pid++;
132   if (last_pid < 0)
133     last_pid = 1;
134
135   if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
136     abort ();
137
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;
145
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)
152     {
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;
159     }
160
161   for (i=1; argv[i]; i++)
162     {
163       char *cp;
164       for (cp = argv[i]; *cp; cp++)
165         {
166           if (*cp == '"' || *cp == '\'' || *cp == '\\' || isspace (*cp))
167             fputc ('\\', argfile);
168           fputc (*cp, argfile);
169         }
170       fputc ('\n', argfile);
171     }
172   fclose (argfile);
173
174   rc = system (scmd);
175
176   {
177     int errno_save = errno;
178     remove (rf);
179     free (scmd);
180     errno = errno_save;
181   }
182 #endif
183
184   if (rc == -1)
185     {
186       *errmsg_fmt = install_error_msg;
187       *errmsg_arg = program;
188       return -1;
189     }
190
191   /* Tuck the status away for pwait, and return a "pid".  */
192   last_status = rc << 8;
193   return last_pid;
194 }
195
196 int
197 pwait (pid, status, flags)
198      int pid;
199      int *status;
200      int flags;
201 {
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)
206     {
207       /* ??? ECHILD would be a better choice.  Can we use it here?  */
208       errno = EINVAL;
209       return -1;
210     }
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;
216 }
217
218 #endif /* MSDOS */
219
220 #if defined (_WIN32)
221
222 #include <process.h>
223 extern int _spawnv ();
224 extern int _spawnvp ();
225
226 int
227 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
228      const char *program;
229      char * const *argv;
230      const char *this_pname;
231      const char *temp_base;
232      char **errmsg_fmt, **errmsg_arg;
233      int flags;
234 {
235   int pid;
236
237   if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
238     abort ();
239   pid = (flags & PEXECUTE_SEARCH ? _spawnvp : _spawnv) (_P_NOWAIT, program, argv);
240   if (pid == -1)
241     {
242       *errmsg_fmt = install_error_msg;
243       *errmsg_arg = program;
244       return -1;
245     }
246   return pid;
247 }
248
249 int
250 pwait (pid, status, flags)
251      int pid;
252      int *status;
253      int flags;
254 {
255   /* ??? Here's an opportunity to canonicalize the values in STATUS.
256      Needed?  */
257   return cwait (status, pid, WAIT_CHILD);
258 }
259
260 #endif /* _WIN32 */
261
262 #ifdef OS2
263
264 /* ??? Does OS2 have process.h?  */
265 extern int spawnv ();
266 extern int spawnvp ();
267
268 int
269 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
270      const char *program;
271      char * const *argv;
272      const char *this_pname;
273      const char *temp_base;
274      char **errmsg_fmt, **errmsg_arg;
275      int flags;
276 {
277   int pid;
278
279   if ((flags & PEXECUTE_ONE) != PEXECUTE_ONE)
280     abort ();
281   /* ??? Presumably 1 == _P_NOWAIT.  */
282   pid = (flags & PEXECUTE_SEARCH ? spawnvp : spawnv) (1, program, argv);
283   if (pid == -1)
284     {
285       *errmsg_fmt = install_error_msg;
286       *errmsg_arg = program;
287       return -1;
288     }
289   return pid;
290 }
291
292 int
293 pwait (pid, status, flags)
294      int pid;
295      int *status;
296      int flags;
297 {
298   /* ??? Here's an opportunity to canonicalize the values in STATUS.
299      Needed?  */
300   int pid = wait (status);
301   return pid;
302 }
303
304 #endif /* OS2 */
305
306 #ifdef MPW
307
308 /* MPW pexecute doesn't actually run anything; instead, it writes out
309    script commands that, when run, will do the actual executing.
310
311    For example, in GCC's case, GCC will write out several script commands:
312
313    cpp ...
314    cc1 ...
315    as ...
316    ld ...
317
318    and then exit.  None of the above programs will have run yet.  The task
319    that called GCC will then execute the script and cause cpp,etc. to run.
320    The caller must invoke pfinish before calling exit.  This adds
321    the finishing touches to the generated script.  */
322
323 static int first_time = 1;
324
325 int
326 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
327      const char *program;
328      char * const *argv;
329      const char *this_pname;
330      const char *temp_base;
331      char **errmsg_fmt, **errmsg_arg;
332      int flags;
333 {
334   char tmpprogram[255];
335   char *cp, *tmpname;
336   int i;
337
338   mpwify_filename (program, tmpprogram);
339   if (first_time)
340     {
341       printf ("Set Failed 0\n");
342       first_time = 0;
343     }
344
345   fputs ("If {Failed} == 0\n", stdout);
346   /* If being verbose, output a copy of the command.  It should be
347      accurate enough and escaped enough to be "clickable".  */
348   if (flags & PEXECUTE_VERBOSE)
349     {
350       fputs ("\tEcho ", stdout);
351       fputc ('\'', stdout);
352       fputs (tmpprogram, stdout);
353       fputc ('\'', stdout);
354       fputc (' ', stdout);
355       for (i=1; argv[i]; i++)
356         {
357           fputc ('\'', stdout);
358           /* See if we have an argument that needs fixing.  */
359           if (strchr(argv[i], '/'))
360             {
361               tmpname = xmalloc (256);
362               mpwify_filename (argv[i], tmpname);
363               argv[i] = tmpname;
364             }
365           for (cp = argv[i]; *cp; cp++)
366             {
367               /* Write an Option-d escape char in front of special chars.  */
368               if (strchr("'+", *cp))
369                 fputc ('\266', stdout);
370               fputc (*cp, stdout);
371             }
372           fputc ('\'', stdout);
373           fputc (' ', stdout);
374         }
375       fputs ("\n", stdout);
376     }
377   fputs ("\t", stdout);
378   fputs (tmpprogram, stdout);
379   fputc (' ', stdout);
380
381   for (i=1; argv[i]; i++)
382     {
383       /* See if we have an argument that needs fixing.  */
384       if (strchr(argv[i], '/'))
385         {
386           tmpname = xmalloc (256);
387           mpwify_filename (argv[i], tmpname);
388           argv[i] = tmpname;
389         }
390       if (strchr (argv[i], ' '))
391         fputc ('\'', stdout);
392       for (cp = argv[i]; *cp; cp++)
393         {
394           /* Write an Option-d escape char in front of special chars.  */
395           if (strchr("'+", *cp))
396             fputc ('\266', stdout);
397           fputc (*cp, stdout);
398         }
399       if (strchr (argv[i], ' '))
400         fputc ('\'', stdout);
401       fputc (' ', stdout);
402     }
403
404   fputs ("\n", stdout);
405
406   /* Output commands that arrange to clean up and exit if a failure occurs.
407      We have to be careful to collect the status from the program that was
408      run, rather than some other script command.  Also, we don't exit
409      immediately, since necessary cleanups are at the end of the script.  */
410   fputs ("\tSet TmpStatus {Status}\n", stdout);
411   fputs ("\tIf {TmpStatus} != 0\n", stdout);
412   fputs ("\t\tSet Failed {TmpStatus}\n", stdout);
413   fputs ("\tEnd\n", stdout);
414   fputs ("End\n", stdout);
415
416   /* We're just composing a script, can't fail here.  */
417   return 0;
418 }
419
420 int
421 pwait (pid, status, flags)
422      int pid;
423      int *status;
424      int flags;
425 {
426   *status = 0;
427   return 0;
428 }
429
430 /* Write out commands that will exit with the correct error code
431    if something in the script failed.  */
432
433 void
434 pfinish ()
435 {
436   printf ("\tExit \"{Failed}\"\n");
437 }
438
439 #endif /* MPW */
440
441 /* include for Unix-like environments but not for Dos-like environments */
442 #if ! defined (__MSDOS__) && ! defined (OS2) && ! defined (MPW) \
443     && ! defined (_WIN32)
444
445 #ifdef VMS
446 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
447                lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
448 #else
449 #ifdef USG
450 #define vfork fork
451 #endif
452 #endif
453
454 extern int execv ();
455 extern int execvp ();
456
457 int
458 pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
459      const char *program;
460      char * const *argv;
461      const char *this_pname;
462      const char *temp_base;
463      char **errmsg_fmt, **errmsg_arg;
464      int flags;
465 {
466   int (*func)() = (flags & PEXECUTE_SEARCH ? execvp : execv);
467   int pid;
468   int pdes[2];
469   int input_desc, output_desc;
470   int retries, sleep_interval;
471   /* Pipe waiting from last process, to be used as input for the next one.
472      Value is STDIN_FILE_NO if no pipe is waiting
473      (i.e. the next command is the first of a group).  */
474   static int last_pipe_input;
475
476   /* If this is the first process, initialize.  */
477   if (flags & PEXECUTE_FIRST)
478     last_pipe_input = STDIN_FILE_NO;
479
480   input_desc = last_pipe_input;
481
482   /* If this isn't the last process, make a pipe for its output,
483      and record it as waiting to be the input to the next process.  */
484   if (! (flags & PEXECUTE_LAST))
485     {
486       if (pipe (pdes) < 0)
487         {
488           *errmsg_fmt = "pipe";
489           *errmsg_arg = NULL;
490           return -1;
491         }
492       output_desc = pdes[WRITE_PORT];
493       last_pipe_input = pdes[READ_PORT];
494     }
495   else
496     {
497       /* Last process.  */
498       output_desc = STDOUT_FILE_NO;
499       last_pipe_input = STDIN_FILE_NO;
500     }
501
502   /* Fork a subprocess; wait and retry if it fails.  */
503   sleep_interval = 1;
504   for (retries = 0; retries < 4; retries++)
505     {
506       pid = vfork ();
507       if (pid >= 0)
508         break;
509       sleep (sleep_interval);
510       sleep_interval *= 2;
511     }
512
513   switch (pid)
514     {
515     case -1:
516       {
517 #ifdef vfork
518         *errmsg_fmt = "fork";
519 #else
520         *errmsg_fmt = "vfork";
521 #endif
522         *errmsg_arg = NULL;
523         return -1;
524       }
525
526     case 0: /* child */
527       /* Move the input and output pipes into place, if necessary.  */
528       if (input_desc != STDIN_FILE_NO)
529         {
530           close (STDIN_FILE_NO);
531           dup (input_desc);
532           close (input_desc);
533         }
534       if (output_desc != STDOUT_FILE_NO)
535         {
536           close (STDOUT_FILE_NO);
537           dup (output_desc);
538           close (output_desc);
539         }
540
541       /* Close the parent's descs that aren't wanted here.  */
542       if (last_pipe_input != STDIN_FILE_NO)
543         close (last_pipe_input);
544
545       /* Exec the program.  */
546       (*func) (program, argv);
547
548       /* Note: Calling fprintf and exit here doesn't seem right for vfork.  */
549       fprintf (stderr, "%s: ", this_pname);
550       fprintf (stderr, install_error_msg, program);
551 #ifdef IN_GCC
552       fprintf (stderr, ": %s\n", my_strerror (errno));
553 #else
554       fprintf (stderr, ": %s\n", xstrerror (errno));
555 #endif
556       exit (-1);
557       /* NOTREACHED */
558       return 0;
559
560     default:
561       /* In the parent, after forking.
562          Close the descriptors that we made for this child.  */
563       if (input_desc != STDIN_FILE_NO)
564         close (input_desc);
565       if (output_desc != STDOUT_FILE_NO)
566         close (output_desc);
567
568       /* Return child's process number.  */
569       return pid;
570     }
571 }
572
573 int
574 pwait (pid, status, flags)
575      int pid;
576      int *status;
577      int flags;
578 {
579   /* ??? Here's an opportunity to canonicalize the values in STATUS.
580      Needed?  */
581 #ifdef VMS
582   pid = waitpid (-1, status, 0);
583 #else
584   pid = wait (status);
585 #endif
586   return pid;
587 }
588
589 #endif /* ! __MSDOS__ && ! OS2 && ! MPW && ! _WIN32 */