bce2c3b4280f9bd12bd47ce2228e208fbd38b5e3
[external/binutils.git] / libiberty / pex-common.c
1 /* Common code for executing a program in a sub-process.
2    Copyright (C) 2005 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor <ian@airs.com>.
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., 51 Franklin Street - Fifth Floor,
19 Boston, MA 02110-1301, USA.  */
20
21 #include "config.h"
22 #include "libiberty.h"
23 #include "pex-common.h"
24
25 #include <stdio.h>
26 #include <errno.h>
27 #ifdef NEED_DECLARATION_ERRNO
28 extern int errno;
29 #endif
30 #ifdef HAVE_STDLIB_H
31 #include <stdlib.h>
32 #endif
33 #ifdef HAVE_STRING_H
34 #include <string.h>
35 #endif
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 extern int mkstemps (char *, int);
41
42 /* This file contains subroutines for the program execution routines
43    (pex_init, pex_run, etc.).  This file is compiled on all
44    systems.  */
45
46 static void pex_add_remove (struct pex_obj *, const char *, int);
47 static int pex_get_status_and_time (struct pex_obj *, int, const char **,
48                                     int *);
49
50 /* Initialize a pex_obj structure.  */
51
52 struct pex_obj *
53 pex_init_common (int flags, const char *pname, const char *tempbase,
54                  const struct pex_funcs *funcs)
55 {
56   struct pex_obj *obj;
57
58   obj = XNEW (struct pex_obj);
59   obj->flags = flags;
60   obj->pname = pname;
61   obj->tempbase = tempbase;
62   obj->next_input = STDIN_FILE_NO;
63   obj->next_input_name = NULL;
64   obj->next_input_name_allocated = 0;
65   obj->count = 0;
66   obj->children = NULL;
67   obj->status = NULL;
68   obj->time = NULL;
69   obj->number_waited = 0;
70   obj->input_file = NULL;
71   obj->read_output = NULL;
72   obj->remove_count = 0;
73   obj->remove = NULL;
74   obj->funcs = funcs;
75   obj->sysdep = NULL;
76   return obj;
77 }
78
79 /* Add a file to be removed when we are done.  */
80
81 static void
82 pex_add_remove (struct pex_obj *obj, const char *name, int allocated)
83 {
84   char *add;
85
86   ++obj->remove_count;
87   obj->remove = XRESIZEVEC (char *, obj->remove, obj->remove_count);
88   if (allocated)
89     add = (char *) name;
90   else
91     add = xstrdup (name);
92   obj->remove[obj->remove_count - 1] = add;
93 }
94
95 /* Generate a temporary file name based on OBJ, FLAGS, and NAME.
96    Return NULL if we were unable to reserve a temporary filename.
97
98    If non-NULL, the result is either allocated with malloc, or the
99    same pointer as NAME.  */
100 static char *
101 temp_file (struct pex_obj *obj, int flags, char *name)
102 {
103   if (name == NULL)
104     {
105       if (obj->tempbase == NULL)
106         {
107           name = make_temp_file (NULL);
108         }
109       else
110         {
111           int len = strlen (obj->tempbase);
112           int out;
113
114           if (len >= 6
115               && strcmp (obj->tempbase + len - 6, "XXXXXX") == 0)
116             name = xstrdup (obj->tempbase);
117           else
118             name = concat (obj->tempbase, "XXXXXX", NULL);
119
120           out = mkstemps (name, 0);
121           if (out < 0)
122             {
123               free (name);
124               return NULL;
125             }
126
127           /* This isn't obj->funcs->close because we got the
128              descriptor from mkstemps, not from a function in
129              obj->funcs.  Calling close here is just like what
130              make_temp_file does.  */
131           close (out);
132         }
133     }
134   else if ((flags & PEX_SUFFIX) != 0)
135     {
136       if (obj->tempbase == NULL)
137         name = make_temp_file (name);
138       else
139         name = concat (obj->tempbase, name, NULL);
140     }
141
142   return name;
143 }
144
145 /* Run a program.  */
146
147 const char *
148 pex_run (struct pex_obj *obj, int flags, const char *executable,
149          char * const * argv, const char *orig_outname, const char *errname,
150          int *err)
151 {
152   const char *errmsg;
153   int in, out, errdes;
154   char *outname;
155   int outname_allocated;
156   int p[2];
157   long pid;
158
159   in = -1;
160   out = -1;
161   errdes = -1;
162   p[READ_PORT] = -1;
163   p[WRITE_PORT] = -1;
164   outname = (char *) orig_outname;
165   outname_allocated = 0;
166
167   /* If the user called pex_input_file, close the file now.  */
168   if (obj->input_file)
169     {
170       if (fclose (obj->input_file) == EOF)
171         {
172           errmsg = "closing pipeline input file";
173           goto error_exit;
174         }
175       obj->input_file = NULL;
176     }
177
178   /* Set IN.  */
179
180   if (obj->next_input_name != NULL)
181     {
182       /* We have to make sure that the previous process has completed
183          before we try to read the file.  */
184       if (!pex_get_status_and_time (obj, 0, &errmsg, err))
185         goto error_exit;
186
187       in = obj->funcs->open_read (obj, obj->next_input_name,
188                                   (flags & PEX_BINARY_INPUT) != 0);
189       if (in < 0)
190         {
191           *err = errno;
192           errmsg = "open temporary file";
193           goto error_exit;
194         }
195       if (obj->next_input_name_allocated)
196         {
197           free (obj->next_input_name);
198           obj->next_input_name_allocated = 0;
199         }
200       obj->next_input_name = NULL;
201     }
202   else
203     {
204       in = obj->next_input;
205       if (in < 0)
206         {
207           *err = 0;
208           errmsg = "pipeline already complete";
209           goto error_exit;
210         }
211     }
212
213   /* Set OUT and OBJ->NEXT_INPUT/OBJ->NEXT_INPUT_NAME.  */
214
215   if ((flags & PEX_LAST) != 0)
216     {
217       if (outname == NULL)
218         out = STDOUT_FILE_NO;
219       else if ((flags & PEX_SUFFIX) != 0)
220         {
221           outname = concat (obj->tempbase, outname, NULL);
222           outname_allocated = 1;
223         }
224       obj->next_input = -1;
225     }
226   else if ((obj->flags & PEX_USE_PIPES) == 0)
227     {
228       outname = temp_file (obj, flags, outname);
229       if (! outname)
230         {
231           *err = 0;
232           errmsg = "could not create temporary file";
233           goto error_exit;
234         }
235
236       if (outname != orig_outname)
237         outname_allocated = 1;
238
239       if ((obj->flags & PEX_SAVE_TEMPS) == 0)
240         {
241           pex_add_remove (obj, outname, outname_allocated);
242           outname_allocated = 0;
243         }
244
245       /* Hand off ownership of outname to the next stage.  */
246       obj->next_input_name = outname;
247       obj->next_input_name_allocated = outname_allocated;
248       outname_allocated = 0;
249     }
250   else
251     {
252       if (obj->funcs->pipe (obj, p, (flags & PEX_BINARY_OUTPUT) != 0) < 0)
253         {
254           *err = errno;
255           errmsg = "pipe";
256           goto error_exit;
257         }
258
259       out = p[WRITE_PORT];
260       obj->next_input = p[READ_PORT];
261     }
262
263   if (out < 0)
264     {
265       out = obj->funcs->open_write (obj, outname,
266                                     (flags & PEX_BINARY_OUTPUT) != 0);
267       if (out < 0)
268         {
269           *err = errno;
270           errmsg = "open temporary output file";
271           goto error_exit;
272         }
273     }
274
275   if (outname_allocated)
276     {
277       free (outname);
278       outname_allocated = 0;
279     }
280
281   /* Set ERRDES.  */
282
283   if (errname == NULL)
284     errdes = STDERR_FILE_NO;
285   else
286     {
287       /* We assume that stderr is in text mode--it certainly shouldn't
288          be controlled by PEX_BINARY_OUTPUT.  If necessary, we can add
289          a PEX_BINARY_STDERR flag.  */
290       errdes = obj->funcs->open_write (obj, errname, 0);
291       if (errdes < 0)
292         {
293           *err = errno;
294           errmsg = "open error file";
295           goto error_exit;
296         }
297     }
298
299   /* Run the program.  */
300
301   pid = obj->funcs->exec_child (obj, flags, executable, argv, in, out, errdes,
302                                 &errmsg, err);
303   if (p[WRITE_PORT] != -1)
304     obj->funcs->close (obj, p[WRITE_PORT]);
305   if (pid < 0)
306     goto error_exit;
307
308   ++obj->count;
309   obj->children = XRESIZEVEC (long, obj->children, obj->count);
310   obj->children[obj->count - 1] = pid;
311
312   return NULL;
313
314  error_exit:
315   if (in >= 0 && in != STDIN_FILE_NO)
316     obj->funcs->close (obj, in);
317   if (out >= 0 && out != STDOUT_FILE_NO)
318     obj->funcs->close (obj, out);
319   if (errdes >= 0 && errdes != STDERR_FILE_NO)
320     obj->funcs->close (obj, errdes);
321   if (outname_allocated)
322     free (outname);
323   return errmsg;
324 }
325
326 /* Return a FILE pointer for the input of the first program
327    executed.  */
328
329 FILE *
330 pex_write_input (struct pex_obj *obj, int binary)
331 {
332   int p[2];
333   FILE *write_input;
334
335   /* You must call pex_write_input before the first pex_run or pex_one.  */
336   if (obj->count > 0)
337     goto usage_error;
338
339   /* You must be using pipes.  Implementations that don't support
340      pipes clear this flag before calling pex_init_common.  */
341   if (! (obj->flags & PEX_USE_PIPES))
342     goto usage_error;
343
344   /* If we have somehow already selected other input, that's a
345      mistake.  */
346   if ((obj->next_input >= 0 && obj->next_input != STDIN_FILE_NO)
347       || obj->next_input_name)
348     goto usage_error;
349
350   if (obj->funcs->pipe (obj, p, binary != 0) < 0)
351     return NULL;
352
353   write_input = obj->funcs->fdopenw (obj, p[WRITE_PORT], binary != 0);
354   if (! write_input)
355     {
356       int saved_errno = errno;
357       obj->funcs->close (obj, p[READ_PORT]);
358       obj->funcs->close (obj, p[WRITE_PORT]);
359       errno = saved_errno;
360       return NULL;
361     }
362
363   obj->next_input = p[READ_PORT];
364
365   return write_input;
366
367  usage_error:
368   errno = EINVAL;
369   return NULL;
370 }
371
372 /* Return a FILE pointer for a temporary file to fill with input for
373    the pipeline.  */
374 FILE *
375 pex_input_file (struct pex_obj *obj, int flags, const char *in_name)
376 {
377   char *name = (char *) in_name;
378   FILE *f;
379
380   /* This must be called before the first pipeline stage is run, and
381      there must not have been any other input selected.  */
382   if (obj->count != 0
383       || (obj->next_input >= 0 && obj->next_input != STDIN_FILE_NO)
384       || obj->next_input_name)
385     {
386       errno = EINVAL;
387       return NULL;
388     }
389
390   name = temp_file (obj, flags, name);
391   if (! name)
392     return NULL;
393
394   f = fopen (name, (flags & PEX_BINARY_OUTPUT) ? "wb" : "w");
395   if (! f)
396     {
397       free (name);
398       return NULL;
399     }
400
401   obj->input_file = f;
402   obj->next_input_name = name;
403   obj->next_input_name_allocated = (name != in_name);
404
405   return f;
406 }
407
408 /* Return a stream for a pipe connected to the standard input of the
409    first stage of the pipeline.  */
410 FILE *
411 pex_input_pipe (struct pex_obj *obj, int binary)
412 {
413   int p[2];
414   FILE *f;
415
416   /* You must call pex_input_pipe before the first pex_run or pex_one.  */
417   if (obj->count > 0)
418     goto usage_error;
419
420   /* You must be using pipes.  Implementations that don't support
421      pipes clear this flag before calling pex_init_common.  */
422   if (! (obj->flags & PEX_USE_PIPES))
423     goto usage_error;
424
425   /* If we have somehow already selected other input, that's a
426      mistake.  */
427   if ((obj->next_input >= 0 && obj->next_input != STDIN_FILE_NO)
428       || obj->next_input_name)
429     goto usage_error;
430
431   if (obj->funcs->pipe (obj, p, binary != 0) < 0)
432     return NULL;
433
434   f = obj->funcs->fdopenw (obj, p[WRITE_PORT], binary != 0);
435   if (! f)
436     {
437       int saved_errno = errno;
438       obj->funcs->close (obj, p[READ_PORT]);
439       obj->funcs->close (obj, p[WRITE_PORT]);
440       errno = saved_errno;
441       return NULL;
442     }
443
444   obj->next_input = p[READ_PORT];
445
446   return f;
447
448  usage_error:
449   errno = EINVAL;
450   return NULL;
451 }
452
453 /* Return a FILE pointer for the output of the last program
454    executed.  */
455
456 FILE *
457 pex_read_output (struct pex_obj *obj, int binary)
458 {
459   if (obj->next_input_name != NULL)
460     {
461       const char *errmsg;
462       int err;
463
464       /* We have to make sure that the process has completed before we
465          try to read the file.  */
466       if (!pex_get_status_and_time (obj, 0, &errmsg, &err))
467         {
468           errno = err;
469           return NULL;
470         }
471
472       obj->read_output = fopen (obj->next_input_name, binary ? "rb" : "r");
473
474       if (obj->next_input_name_allocated)
475         {
476           free (obj->next_input_name);
477           obj->next_input_name_allocated = 0;
478         }
479       obj->next_input_name = NULL;
480     }
481   else
482     {
483       int o;
484
485       o = obj->next_input;
486       if (o < 0 || o == STDIN_FILE_NO)
487         return NULL;
488       obj->read_output = obj->funcs->fdopenr (obj, o, binary);
489       obj->next_input = -1;
490     }
491
492   return obj->read_output;
493 }
494
495 /* Get the exit status and, if requested, the resource time for all
496    the child processes.  Return 0 on failure, 1 on success.  */
497
498 static int
499 pex_get_status_and_time (struct pex_obj *obj, int done, const char **errmsg,
500                          int *err)
501 {
502   int ret;
503   int i;
504
505   if (obj->number_waited == obj->count)
506     return 1;
507
508   obj->status = XRESIZEVEC (int, obj->status, obj->count);
509   if ((obj->flags & PEX_RECORD_TIMES) != 0)
510     obj->time = XRESIZEVEC (struct pex_time, obj->time, obj->count);
511
512   ret = 1;
513   for (i = obj->number_waited; i < obj->count; ++i)
514     {
515       if (obj->funcs->wait (obj, obj->children[i], &obj->status[i],
516                             obj->time == NULL ? NULL : &obj->time[i],
517                             done, errmsg, err) < 0)
518         ret = 0;
519     }
520   obj->number_waited = i;
521
522   return ret;
523 }
524
525 /* Get exit status of executed programs.  */
526
527 int
528 pex_get_status (struct pex_obj *obj, int count, int *vector)
529 {
530   if (obj->status == NULL)
531     {
532       const char *errmsg;
533       int err;
534
535       if (!pex_get_status_and_time (obj, 0, &errmsg, &err))
536         return 0;
537     }
538
539   if (count > obj->count)
540     {
541       memset (vector + obj->count, 0, (count - obj->count) * sizeof (int));
542       count = obj->count;
543     }
544
545   memcpy (vector, obj->status, count * sizeof (int));
546
547   return 1;
548 }
549
550 /* Get process times of executed programs.  */
551
552 int
553 pex_get_times (struct pex_obj *obj, int count, struct pex_time *vector)
554 {
555   if (obj->status == NULL)
556     {
557       const char *errmsg;
558       int err;
559
560       if (!pex_get_status_and_time (obj, 0, &errmsg, &err))
561         return 0;
562     }
563
564   if (obj->time == NULL)
565     return 0;
566
567   if (count > obj->count)
568     {
569       memset (vector + obj->count, 0,
570               (count - obj->count) * sizeof (struct pex_time));
571       count = obj->count;
572     }
573
574   memcpy (vector, obj->time, count * sizeof (struct pex_time));
575
576   return 1;
577 }
578
579 /* Free a pex_obj structure.  */
580
581 void
582 pex_free (struct pex_obj *obj)
583 {
584   if (obj->next_input >= 0 && obj->next_input != STDIN_FILE_NO)
585     obj->funcs->close (obj, obj->next_input);
586
587   /* If the caller forgot to wait for the children, we do it here, to
588      avoid zombies.  */
589   if (obj->status == NULL)
590     {
591       const char *errmsg;
592       int err;
593
594       obj->flags &= ~ PEX_RECORD_TIMES;
595       pex_get_status_and_time (obj, 1, &errmsg, &err);
596     }
597
598   if (obj->next_input_name_allocated)
599     free (obj->next_input_name);
600   if (obj->children != NULL)
601     free (obj->children);
602   if (obj->status != NULL)
603     free (obj->status);
604   if (obj->time != NULL)
605     free (obj->time);
606   if (obj->read_output != NULL)
607     fclose (obj->read_output);
608
609   if (obj->remove_count > 0)
610     {
611       int i;
612
613       for (i = 0; i < obj->remove_count; ++i)
614         {
615           remove (obj->remove[i]);
616           free (obj->remove[i]);
617         }
618       free (obj->remove);
619     }
620
621   if (obj->funcs->cleanup != NULL)
622     obj->funcs->cleanup (obj);
623
624   free (obj);
625 }