source: trunk/third/gmake/job.c @ 15972

Revision 15972, 80.7 KB checked in by ghudson, 24 years ago (diff)
This commit was generated by cvs2svn to compensate for changes in r15971, which included commits to RCS files with non-trunk default branches.
Line 
1/* Job execution and handling for GNU Make.
2Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2, or (at your option)
8any later version.
9
10GNU Make is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with GNU Make; see the file COPYING.  If not, write to
17the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18Boston, MA 02111-1307, USA.  */
19
20#include "make.h"
21
22#include <assert.h>
23
24#include "job.h"
25#include "debug.h"
26#include "filedef.h"
27#include "commands.h"
28#include "variable.h"
29#include "debug.h"
30
31#include <string.h>
32
33/* Default shell to use.  */
34#ifdef WINDOWS32
35char *default_shell = "sh.exe";
36int no_default_sh_exe = 1;
37int batch_mode_shell = 1;
38#else  /* WINDOWS32 */
39# ifdef _AMIGA
40char default_shell[] = "";
41extern int MyExecute (char **);
42# else /* _AMIGA */
43#  ifdef __MSDOS__
44/* The default shell is a pointer so we can change it if Makefile
45   says so.  It is without an explicit path so we get a chance
46   to search the $PATH for it (since MSDOS doesn't have standard
47   directories we could trust).  */
48char *default_shell = "command.com";
49#  else  /* __MSDOS__ */
50#   ifdef VMS
51#    include <descrip.h>
52char default_shell[] = "";
53#   else
54char default_shell[] = "/bin/sh";
55#   endif /* VMS */
56#  endif /* __MSDOS__ */
57int batch_mode_shell = 0;
58# endif /* _AMIGA */
59#endif /* WINDOWS32 */
60
61#ifdef __MSDOS__
62# include <process.h>
63static int execute_by_shell;
64static int dos_pid = 123;
65int dos_status;
66int dos_command_running;
67#endif /* __MSDOS__ */
68
69#ifdef _AMIGA
70# include <proto/dos.h>
71static int amiga_pid = 123;
72static int amiga_status;
73static char amiga_bname[32];
74static int amiga_batch_file;
75#endif /* Amiga.  */
76
77#ifdef VMS
78# ifndef __GNUC__
79#   include <processes.h>
80# endif
81# include <starlet.h>
82# include <lib$routines.h>
83#endif
84
85#ifdef WINDOWS32
86# include <windows.h>
87# include <io.h>
88# include <process.h>
89# include "sub_proc.h"
90# include "w32err.h"
91# include "pathstuff.h"
92#endif /* WINDOWS32 */
93
94#ifdef HAVE_FCNTL_H
95# include <fcntl.h>
96#else
97# include <sys/file.h>
98#endif
99
100#if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
101# include <sys/wait.h>
102#endif
103
104#ifdef HAVE_WAITPID
105# define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
106#else   /* Don't have waitpid.  */
107# ifdef HAVE_WAIT3
108#  ifndef wait3
109extern int wait3 ();
110#  endif
111#  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
112# endif /* Have wait3.  */
113#endif /* Have waitpid.  */
114
115#if !defined (wait) && !defined (POSIX)
116extern int wait ();
117#endif
118
119#ifndef HAVE_UNION_WAIT
120
121# define WAIT_T int
122
123# ifndef WTERMSIG
124#  define WTERMSIG(x) ((x) & 0x7f)
125# endif
126# ifndef WCOREDUMP
127#  define WCOREDUMP(x) ((x) & 0x80)
128# endif
129# ifndef WEXITSTATUS
130#  define WEXITSTATUS(x) (((x) >> 8) & 0xff)
131# endif
132# ifndef WIFSIGNALED
133#  define WIFSIGNALED(x) (WTERMSIG (x) != 0)
134# endif
135# ifndef WIFEXITED
136#  define WIFEXITED(x) (WTERMSIG (x) == 0)
137# endif
138
139#else   /* Have `union wait'.  */
140
141# define WAIT_T union wait
142# ifndef WTERMSIG
143#  define WTERMSIG(x) ((x).w_termsig)
144# endif
145# ifndef WCOREDUMP
146#  define WCOREDUMP(x) ((x).w_coredump)
147# endif
148# ifndef WEXITSTATUS
149#  define WEXITSTATUS(x) ((x).w_retcode)
150# endif
151# ifndef WIFSIGNALED
152#  define WIFSIGNALED(x) (WTERMSIG(x) != 0)
153# endif
154# ifndef WIFEXITED
155#  define WIFEXITED(x) (WTERMSIG(x) == 0)
156# endif
157
158#endif  /* Don't have `union wait'.  */
159
160/* How to set close-on-exec for a file descriptor.  */
161
162#if !defined F_SETFD
163# define CLOSE_ON_EXEC(_d)
164#else
165# ifndef FD_CLOEXEC
166#  define FD_CLOEXEC 1
167# endif
168# define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
169#endif
170
171#ifdef VMS
172static int vms_jobsefnmask = 0;
173#endif /* !VMS */
174
175#ifndef HAVE_UNISTD_H
176extern int dup2 ();
177extern int execve ();
178extern void _exit ();
179# ifndef VMS
180extern int geteuid ();
181extern int getegid ();
182extern int setgid ();
183extern int getgid ();
184# endif
185#endif
186
187extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
188
189extern int getloadavg PARAMS ((double loadavg[], int nelem));
190extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
191                int *is_remote, int *id_ptr, int *used_stdin));
192extern int start_remote_job_p PARAMS ((int));
193extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
194                int *coredump_ptr, int block));
195
196RETSIGTYPE child_handler PARAMS ((int));
197static void free_child PARAMS ((struct child *));
198static void start_job_command PARAMS ((struct child *child));
199static int load_too_high PARAMS ((void));
200static int job_next_command PARAMS ((struct child *));
201static int start_waiting_job PARAMS ((struct child *));
202#ifdef VMS
203static void vmsWaitForChildren PARAMS ((int *));
204#endif
205
206/* Chain of all live (or recently deceased) children.  */
207
208struct child *children = 0;
209
210/* Number of children currently running.  */
211
212unsigned int job_slots_used = 0;
213
214/* Nonzero if the `good' standard input is in use.  */
215
216static int good_stdin_used = 0;
217
218/* Chain of children waiting to run until the load average goes down.  */
219
220static struct child *waiting_jobs = 0;
221
222/* Non-zero if we use a *real* shell (always so on Unix).  */
223
224int unixy_shell = 1;
225
226
227#ifdef WINDOWS32
228/*
229 * The macro which references this function is defined in make.h.
230 */
231int w32_kill(int pid, int sig)
232{
233  return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
234}
235#endif /* WINDOWS32 */
236
237/* Write an error message describing the exit status given in
238   EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
239   Append "(ignored)" if IGNORED is nonzero.  */
240
241static void
242child_error (target_name, exit_code, exit_sig, coredump, ignored)
243     char *target_name;
244     int exit_code, exit_sig, coredump;
245     int ignored;
246{
247  if (ignored && silent_flag)
248    return;
249
250#ifdef VMS
251  if (!(exit_code & 1))
252      error (NILF,
253             (ignored ? _("*** [%s] Error 0x%x (ignored)")
254              : _("*** [%s] Error 0x%x")),
255             target_name, exit_code);
256#else
257  if (exit_sig == 0)
258    error (NILF, ignored ? _("[%s] Error %d (ignored)") :
259           _("*** [%s] Error %d"),
260           target_name, exit_code);
261  else
262    error (NILF, "*** [%s] %s%s",
263           target_name, strsignal (exit_sig),
264           coredump ? _(" (core dumped)") : "");
265#endif /* VMS */
266}
267
268#ifdef VMS
269/* Wait for nchildren children to terminate */
270static void
271vmsWaitForChildren(int *status)
272{
273  while (1)
274    {
275      if (!vms_jobsefnmask)
276        {
277          *status = 0;
278          return;
279        }
280
281      *status = sys$wflor (32, vms_jobsefnmask);
282    }
283  return;
284}
285
286/* Set up IO redirection.  */
287
288char *
289vms_redirect (desc, fname, ibuf)
290    struct dsc$descriptor_s *desc;
291    char *fname;
292    char *ibuf;
293{
294  char *fptr;
295  extern char *vmsify ();
296
297  ibuf++;
298  while (isspace ((unsigned char)*ibuf))
299    ibuf++;
300  fptr = ibuf;
301  while (*ibuf && !isspace ((unsigned char)*ibuf))
302    ibuf++;
303  *ibuf = 0;
304  if (strcmp (fptr, "/dev/null") != 0)
305    {
306      strcpy (fname, vmsify (fptr, 0));
307      if (strchr (fname, '.') == 0)
308        strcat (fname, ".");
309    }
310  desc->dsc$w_length = strlen(fname);
311  desc->dsc$a_pointer = fname;
312  desc->dsc$b_dtype = DSC$K_DTYPE_T;
313  desc->dsc$b_class = DSC$K_CLASS_S;
314
315  if (*fname == 0)
316    printf (_("Warning: Empty redirection\n"));
317  return ibuf;
318}
319
320
321/*
322   found apostrophe at (p-1)
323
324   inc p until after closing apostrophe.  */
325
326static char *
327handle_apos (char *p)
328{
329  int alast;
330  int inside;
331
332#define SEPCHARS ",/()= "
333
334  inside = 0;
335
336  while (*p != 0)
337    {
338      if (*p == '"')
339        {
340          if (inside)
341            {
342              while ((alast > 0)
343                    && (*p == '"'))
344                {
345                  p++;
346                  alast--;
347                }
348              if (alast == 0)
349                inside = 0;
350              else
351                {
352                  fprintf (stderr, _("Syntax error, still inside '\"'\n"));
353                  exit (3);
354                }
355            }
356          else
357            {
358              p++;
359              if (strchr (SEPCHARS, *p))
360                break;
361              inside = 1;
362              alast = 1;
363              while (*p == '"')
364                {
365                  alast++;
366                  p++;
367                }
368            }
369        }
370      else
371        p++;
372    }
373
374  return p;
375}
376
377#endif
378
379
380/* Handle a dead child.  This handler may or may not ever be installed.
381
382   If we're using the jobserver feature, we need it.  First, installing it
383   ensures the read will interrupt on SIGCHLD.  Second, we close the dup'd
384   read FD to ensure we don't enter another blocking read without reaping all
385   the dead children.  In this case we don't need the dead_children count.
386
387   If we don't have either waitpid or wait3, then make is unreliable, but we
388   use the dead_children count to reap children as best we can.  */
389
390static unsigned int dead_children = 0;
391
392RETSIGTYPE
393child_handler (sig)
394     int sig;
395{
396  ++dead_children;
397
398  if (job_rfd >= 0)
399    {
400      close (job_rfd);
401      job_rfd = -1;
402    }
403
404  DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
405}
406
407
408extern int shell_function_pid, shell_function_completed;
409
410/* Reap all dead children, storing the returned status and the new command
411   state (`cs_finished') in the `file' member of the `struct child' for the
412   dead child, and removing the child from the chain.  In addition, if BLOCK
413   nonzero, we block in this function until we've reaped at least one
414   complete child, waiting for it to die if necessary.  If ERR is nonzero,
415   print an error message first.  */
416
417void
418reap_children (block, err)
419     int block, err;
420{
421  WAIT_T status;
422  /* Initially, assume we have some.  */
423  int reap_more = 1;
424
425#ifdef WAIT_NOHANG
426# define REAP_MORE reap_more
427#else
428# define REAP_MORE dead_children
429#endif
430
431  /* As long as:
432
433       We have at least one child outstanding OR a shell function in progress,
434         AND
435       We're blocking for a complete child OR there are more children to reap
436
437     we'll keep reaping children.  */
438
439  while ((children != 0 || shell_function_pid != 0) &&
440         (block || REAP_MORE))
441    {
442      int remote = 0;
443      register int pid;
444      int exit_code, exit_sig, coredump;
445      register struct child *lastc, *c;
446      int child_failed;
447      int any_remote, any_local;
448
449      if (err && block)
450        {
451          /* We might block for a while, so let the user know why.  */
452          fflush (stdout);
453          error (NILF, _("*** Waiting for unfinished jobs...."));
454        }
455
456      /* We have one less dead child to reap.  As noted in
457         child_handler() above, this count is completely unimportant for
458         all modern, POSIX-y systems that support wait3() or waitpid().
459         The rest of this comment below applies only to early, broken
460         pre-POSIX systems.  We keep the count only because... it's there...
461
462         The test and decrement are not atomic; if it is compiled into:
463                register = dead_children - 1;
464                dead_children = register;
465         a SIGCHLD could come between the two instructions.
466         child_handler increments dead_children.
467         The second instruction here would lose that increment.  But the
468         only effect of dead_children being wrong is that we might wait
469         longer than necessary to reap a child, and lose some parallelism;
470         and we might print the "Waiting for unfinished jobs" message above
471         when not necessary.  */
472
473      if (dead_children > 0)
474        --dead_children;
475
476      any_remote = 0;
477      any_local = shell_function_pid != 0;
478      for (c = children; c != 0; c = c->next)
479        {
480          any_remote |= c->remote;
481          any_local |= ! c->remote;
482          DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
483                        (unsigned long int) c, c->file->name,
484                        (long) c->pid, c->remote ? _(" (remote)") : ""));
485#ifdef VMS
486          break;
487#endif
488        }
489
490      /* First, check for remote children.  */
491      if (any_remote)
492        pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
493      else
494        pid = 0;
495
496      if (pid > 0)
497        /* We got a remote child.  */
498        remote = 1;
499      else if (pid < 0)
500        {
501          /* A remote status command failed miserably.  Punt.  */
502        remote_status_lose:
503          if (EINTR_SET)
504            continue;
505
506          pfatal_with_name ("remote_status");
507        }
508      else
509        {
510          /* No remote children.  Check for local children.  */
511#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
512          if (any_local)
513            {
514            local_wait:
515#ifdef VMS
516              vmsWaitForChildren (&status);
517              pid = c->pid;
518#else
519#ifdef WAIT_NOHANG
520              if (!block)
521                pid = WAIT_NOHANG (&status);
522              else
523#endif
524                pid = wait (&status);
525#endif /* !VMS */
526            }
527          else
528            pid = 0;
529
530          if (pid < 0)
531            {
532              /* EINTR?  Try again. */
533              if (EINTR_SET)
534                goto local_wait;
535
536              /* The wait*() failed miserably.  Punt.  */
537              pfatal_with_name ("wait");
538            }
539          else if (pid > 0)
540            {
541              /* We got a child exit; chop the status word up.  */
542              exit_code = WEXITSTATUS (status);
543              exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
544              coredump = WCOREDUMP (status);
545            }
546          else
547            {
548              /* No local children are dead.  */
549              reap_more = 0;
550
551              if (!block || !any_remote)
552                break;
553
554              /* Now try a blocking wait for a remote child.  */
555              pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
556              if (pid < 0)
557                goto remote_status_lose;
558              else if (pid == 0)
559                /* No remote children either.  Finally give up.  */
560                break;
561
562              /* We got a remote child.  */
563              remote = 1;
564            }
565#endif /* !__MSDOS__, !Amiga, !WINDOWS32.  */
566
567#ifdef __MSDOS__
568          /* Life is very different on MSDOS.  */
569          pid = dos_pid - 1;
570          status = dos_status;
571          exit_code = WEXITSTATUS (status);
572          if (exit_code == 0xff)
573            exit_code = -1;
574          exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
575          coredump = 0;
576#endif /* __MSDOS__ */
577#ifdef _AMIGA
578          /* Same on Amiga */
579          pid = amiga_pid - 1;
580          status = amiga_status;
581          exit_code = amiga_status;
582          exit_sig = 0;
583          coredump = 0;
584#endif /* _AMIGA */
585#ifdef WINDOWS32
586          {
587            HANDLE hPID;
588            int err;
589
590            /* wait for anything to finish */
591            if (hPID = process_wait_for_any()) {
592
593              /* was an error found on this process? */
594              err = process_last_err(hPID);
595
596              /* get exit data */
597              exit_code = process_exit_code(hPID);
598
599              if (err)
600                fprintf(stderr, "make (e=%d): %s",
601                  exit_code, map_windows32_error_to_string(exit_code));
602
603              /* signal */
604              exit_sig = process_signal(hPID);
605
606              /* cleanup process */
607              process_cleanup(hPID);
608
609              coredump = 0;
610            }
611            pid = (int) hPID;
612          }
613#endif /* WINDOWS32 */
614        }
615
616      /* Check if this is the child of the `shell' function.  */
617      if (!remote && pid == shell_function_pid)
618        {
619          /* It is.  Leave an indicator for the `shell' function.  */
620          if (exit_sig == 0 && exit_code == 127)
621            shell_function_completed = -1;
622          else
623            shell_function_completed = 1;
624          break;
625        }
626
627      child_failed = exit_sig != 0 || exit_code != 0;
628
629      /* Search for a child matching the deceased one.  */
630      lastc = 0;
631      for (c = children; c != 0; lastc = c, c = c->next)
632        if (c->remote == remote && c->pid == pid)
633          break;
634
635      if (c == 0)
636        /* An unknown child died.
637           Ignore it; it was inherited from our invoker.  */
638        continue;
639
640      DB (DB_JOBS, (child_failed
641                    ? _("Reaping losing child 0x%08lx PID %ld %s\n")
642                    : _("Reaping winning child 0x%08lx PID %ld %s\n"),
643                    (unsigned long int) c, (long) c->pid,
644                    c->remote ? _(" (remote)") : ""));
645
646      if (c->sh_batch_file) {
647        DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
648                      c->sh_batch_file));
649
650        /* just try and remove, don't care if this fails */
651        remove (c->sh_batch_file);
652
653        /* all done with memory */
654        free (c->sh_batch_file);
655        c->sh_batch_file = NULL;
656      }
657
658      /* If this child had the good stdin, say it is now free.  */
659      if (c->good_stdin)
660        good_stdin_used = 0;
661
662      if (child_failed && !c->noerror && !ignore_errors_flag)
663        {
664          /* The commands failed.  Write an error message,
665             delete non-precious targets, and abort.  */
666          static int delete_on_error = -1;
667          child_error (c->file->name, exit_code, exit_sig, coredump, 0);
668          c->file->update_status = 2;
669          if (delete_on_error == -1)
670            {
671              struct file *f = lookup_file (".DELETE_ON_ERROR");
672              delete_on_error = f != 0 && f->is_target;
673            }
674          if (exit_sig != 0 || delete_on_error)
675            delete_child_targets (c);
676        }
677      else
678        {
679          if (child_failed)
680            {
681              /* The commands failed, but we don't care.  */
682              child_error (c->file->name,
683                           exit_code, exit_sig, coredump, 1);
684              child_failed = 0;
685            }
686
687          /* If there are more commands to run, try to start them.  */
688          if (job_next_command (c))
689            {
690              if (handling_fatal_signal)
691                {
692                  /* Never start new commands while we are dying.
693                     Since there are more commands that wanted to be run,
694                     the target was not completely remade.  So we treat
695                     this as if a command had failed.  */
696                  c->file->update_status = 2;
697                }
698              else
699                {
700                  /* Check again whether to start remotely.
701                     Whether or not we want to changes over time.
702                     Also, start_remote_job may need state set up
703                     by start_remote_job_p.  */
704                  c->remote = start_remote_job_p (0);
705                  start_job_command (c);
706                  /* Fatal signals are left blocked in case we were
707                     about to put that child on the chain.  But it is
708                     already there, so it is safe for a fatal signal to
709                     arrive now; it will clean up this child's targets.  */
710                  unblock_sigs ();
711                  if (c->file->command_state == cs_running)
712                    /* We successfully started the new command.
713                       Loop to reap more children.  */
714                    continue;
715                }
716
717              if (c->file->update_status != 0)
718                /* We failed to start the commands.  */
719                delete_child_targets (c);
720            }
721          else
722            /* There are no more commands.  We got through them all
723               without an unignored error.  Now the target has been
724               successfully updated.  */
725            c->file->update_status = 0;
726        }
727
728      /* When we get here, all the commands for C->file are finished
729         (or aborted) and C->file->update_status contains 0 or 2.  But
730         C->file->command_state is still cs_running if all the commands
731         ran; notice_finish_file looks for cs_running to tell it that
732         it's interesting to check the file's modtime again now.  */
733
734      if (! handling_fatal_signal)
735        /* Notice if the target of the commands has been changed.
736           This also propagates its values for command_state and
737           update_status to its also_make files.  */
738        notice_finished_file (c->file);
739
740      DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
741                    (unsigned long int) c, (long) c->pid,
742                    c->remote ? _(" (remote)") : ""));
743
744      /* Block fatal signals while frobnicating the list, so that
745         children and job_slots_used are always consistent.  Otherwise
746         a fatal signal arriving after the child is off the chain and
747         before job_slots_used is decremented would believe a child was
748         live and call reap_children again.  */
749      block_sigs ();
750
751      /* There is now another slot open.  */
752      if (job_slots_used > 0)
753        --job_slots_used;
754
755      /* Remove the child from the chain and free it.  */
756      if (lastc == 0)
757        children = c->next;
758      else
759        lastc->next = c->next;
760
761      free_child (c);
762
763      unblock_sigs ();
764
765      /* If the job failed, and the -k flag was not given, die,
766         unless we are already in the process of dying.  */
767      if (!err && child_failed && !keep_going_flag &&
768          /* fatal_error_signal will die with the right signal.  */
769          !handling_fatal_signal)
770        die (2);
771
772      /* Only block for one child.  */
773      block = 0;
774    }
775
776  return;
777}
778
779/* Free the storage allocated for CHILD.  */
780
781static void
782free_child (child)
783     register struct child *child;
784{
785  /* If this child is the only one it was our "free" job, so don't put a
786     token back for it.  This child has already been removed from the list,
787     so if there any left this wasn't the last one.  */
788
789  if (job_fds[1] >= 0 && children)
790    {
791      char token = '+';
792
793      /* Write a job token back to the pipe.  */
794
795      while (write (job_fds[1], &token, 1) != 1)
796        if (!EINTR_SET)
797          pfatal_with_name (_("write jobserver"));
798
799      DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
800                    (unsigned long int) child, child->file->name));
801    }
802
803  if (handling_fatal_signal) /* Don't bother free'ing if about to die.  */
804    return;
805
806  if (child->command_lines != 0)
807    {
808      register unsigned int i;
809      for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
810        free (child->command_lines[i]);
811      free ((char *) child->command_lines);
812    }
813
814  if (child->environment != 0)
815    {
816      register char **ep = child->environment;
817      while (*ep != 0)
818        free (*ep++);
819      free ((char *) child->environment);
820    }
821
822  free ((char *) child);
823}
824
825#ifdef POSIX
826extern sigset_t fatal_signal_set;
827#endif
828
829void
830block_sigs ()
831{
832#ifdef POSIX
833  (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
834#else
835# ifdef HAVE_SIGSETMASK
836  (void) sigblock (fatal_signal_mask);
837# endif
838#endif
839}
840
841#ifdef  POSIX
842void
843unblock_sigs ()
844{
845  sigset_t empty;
846  sigemptyset (&empty);
847  sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
848}
849#endif
850
851/* Start a job to run the commands specified in CHILD.
852   CHILD is updated to reflect the commands and ID of the child process.
853
854   NOTE: On return fatal signals are blocked!  The caller is responsible
855   for calling `unblock_sigs', once the new child is safely on the chain so
856   it can be cleaned up in the event of a fatal signal.  */
857
858static void
859start_job_command (child)
860     register struct child *child;
861{
862#ifndef _AMIGA
863  static int bad_stdin = -1;
864#endif
865  register char *p;
866  int flags;
867#ifdef VMS
868  char *argv;
869#else
870  char **argv;
871#endif
872
873  /* If we have a completely empty commandset, stop now.  */
874  if (!child->command_ptr)
875    goto next_command;
876
877  /* Combine the flags parsed for the line itself with
878     the flags specified globally for this target.  */
879  flags = (child->file->command_flags
880           | child->file->cmds->lines_flags[child->command_line - 1]);
881
882  p = child->command_ptr;
883  child->noerror = flags & COMMANDS_NOERROR;
884
885  while (*p != '\0')
886    {
887      if (*p == '@')
888        flags |= COMMANDS_SILENT;
889      else if (*p == '+')
890        flags |= COMMANDS_RECURSE;
891      else if (*p == '-')
892        child->noerror = 1;
893      else if (!isblank ((unsigned char)*p))
894        break;
895      ++p;
896    }
897
898  /* Update the file's command flags with any new ones we found.  */
899  child->file->cmds->lines_flags[child->command_line - 1] |= flags;
900
901  /* Figure out an argument list from this command line.  */
902
903  {
904    char *end = 0;
905#ifdef VMS
906    argv = p;
907#else
908    argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
909#endif
910    if (end == NULL)
911      child->command_ptr = NULL;
912    else
913      {
914        *end++ = '\0';
915        child->command_ptr = end;
916      }
917  }
918
919  /* If -q was given, say that updating `failed' if there was any text on the
920     command line, or `succeeded' otherwise.  The exit status of 1 tells the
921     user that -q is saying `something to do'; the exit status for a random
922     error is 2.  */
923  if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
924    {
925#ifndef VMS
926      free (argv[0]);
927      free ((char *) argv);
928#endif
929      child->file->update_status = 1;
930      notice_finished_file (child->file);
931      return;
932    }
933
934  if (touch_flag && !(flags & COMMANDS_RECURSE))
935    {
936      /* Go on to the next command.  It might be the recursive one.
937         We construct ARGV only to find the end of the command line.  */
938#ifndef VMS
939      if (argv)
940        {
941          free (argv[0]);
942          free ((char *) argv);
943        }
944#endif
945      argv = 0;
946    }
947
948  if (argv == 0)
949    {
950    next_command:
951#ifdef __MSDOS__
952      execute_by_shell = 0;   /* in case construct_command_argv sets it */
953#endif
954      /* This line has no commands.  Go to the next.  */
955      if (job_next_command (child))
956        start_job_command (child);
957      else
958        {
959          /* No more commands.  Make sure we're "running"; we might not be if
960             (e.g.) all commands were skipped due to -n.  */
961          set_command_state (child->file, cs_running);
962          child->file->update_status = 0;
963          notice_finished_file (child->file);
964        }
965      return;
966    }
967
968  /* Print out the command.  If silent, we call `message' with null so it
969     can log the working directory before the command's own error messages
970     appear.  */
971
972  message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
973           ? "%s" : (char *) 0, p);
974
975  /* Tell update_goal_chain that a command has been started on behalf of
976     this target.  It is important that this happens here and not in
977     reap_children (where we used to do it), because reap_children might be
978     reaping children from a different target.  We want this increment to
979     guaranteedly indicate that a command was started for the dependency
980     chain (i.e., update_file recursion chain) we are processing.  */
981
982  ++commands_started;
983
984  /* Optimize an empty command.  People use this for timestamp rules,
985     so avoid forking a useless shell.  Do this after we increment
986     commands_started so make still treats this special case as if it
987     performed some action (makes a difference as to what messages are
988     printed, etc.  */
989
990#if !defined(VMS) && !defined(_AMIGA)
991  if (
992#ifdef __MSDOS__
993      unixy_shell       /* the test is complicated and we already did it */
994#else
995      (argv[0] && !strcmp (argv[0], "/bin/sh"))
996#endif
997      && (argv[1]
998          && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
999      && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1000      && argv[3] == NULL)
1001    {
1002      free (argv[0]);
1003      free ((char *) argv);
1004      goto next_command;
1005    }
1006#endif  /* !VMS && !_AMIGA */
1007
1008  /* If -n was given, recurse to get the next line in the sequence.  */
1009
1010  if (just_print_flag && !(flags & COMMANDS_RECURSE))
1011    {
1012#ifndef VMS
1013      free (argv[0]);
1014      free ((char *) argv);
1015#endif
1016      goto next_command;
1017    }
1018
1019  /* Flush the output streams so they won't have things written twice.  */
1020
1021  fflush (stdout);
1022  fflush (stderr);
1023
1024#ifndef VMS
1025#if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1026
1027  /* Set up a bad standard input that reads from a broken pipe.  */
1028
1029  if (bad_stdin == -1)
1030    {
1031      /* Make a file descriptor that is the read end of a broken pipe.
1032         This will be used for some children's standard inputs.  */
1033      int pd[2];
1034      if (pipe (pd) == 0)
1035        {
1036          /* Close the write side.  */
1037          (void) close (pd[1]);
1038          /* Save the read side.  */
1039          bad_stdin = pd[0];
1040
1041          /* Set the descriptor to close on exec, so it does not litter any
1042             child's descriptor table.  When it is dup2'd onto descriptor 0,
1043             that descriptor will not close on exec.  */
1044          CLOSE_ON_EXEC (bad_stdin);
1045        }
1046    }
1047
1048#endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1049
1050  /* Decide whether to give this child the `good' standard input
1051     (one that points to the terminal or whatever), or the `bad' one
1052     that points to the read side of a broken pipe.  */
1053
1054  child->good_stdin = !good_stdin_used;
1055  if (child->good_stdin)
1056    good_stdin_used = 1;
1057
1058#endif /* !VMS */
1059
1060  child->deleted = 0;
1061
1062#ifndef _AMIGA
1063  /* Set up the environment for the child.  */
1064  if (child->environment == 0)
1065    child->environment = target_environment (child->file);
1066#endif
1067
1068#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1069
1070#ifndef VMS
1071  /* start_waiting_job has set CHILD->remote if we can start a remote job.  */
1072  if (child->remote)
1073    {
1074      int is_remote, id, used_stdin;
1075      if (start_remote_job (argv, child->environment,
1076                            child->good_stdin ? 0 : bad_stdin,
1077                            &is_remote, &id, &used_stdin))
1078        /* Don't give up; remote execution may fail for various reasons.  If
1079           so, simply run the job locally.  */
1080        goto run_local;
1081      else
1082        {
1083          if (child->good_stdin && !used_stdin)
1084            {
1085              child->good_stdin = 0;
1086              good_stdin_used = 0;
1087            }
1088          child->remote = is_remote;
1089          child->pid = id;
1090        }
1091    }
1092  else
1093#endif /* !VMS */
1094    {
1095      /* Fork the child process.  */
1096
1097      char **parent_environ;
1098
1099    run_local:
1100      block_sigs ();
1101
1102      child->remote = 0;
1103
1104#ifdef VMS
1105
1106      if (!child_execute_job (argv, child)) {
1107        /* Fork failed!  */
1108        perror_with_name ("vfork", "");
1109        goto error;
1110      }
1111
1112#else
1113
1114      parent_environ = environ;
1115      child->pid = vfork ();
1116      environ = parent_environ; /* Restore value child may have clobbered.  */
1117      if (child->pid == 0)
1118        {
1119          /* We are the child side.  */
1120          unblock_sigs ();
1121
1122          /* If we aren't running a recursive command and we have a jobserver
1123             pipe, close it before exec'ing.  */
1124          if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1125            {
1126              close (job_fds[0]);
1127              close (job_fds[1]);
1128            }
1129          if (job_rfd >= 0)
1130            close (job_rfd);
1131
1132          child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1133                             argv, child->environment);
1134        }
1135      else if (child->pid < 0)
1136        {
1137          /* Fork failed!  */
1138          unblock_sigs ();
1139          perror_with_name ("vfork", "");
1140          goto error;
1141        }
1142#endif /* !VMS */
1143    }
1144
1145#else   /* __MSDOS__ or Amiga or WINDOWS32 */
1146#ifdef __MSDOS__
1147  {
1148    int proc_return;
1149
1150    block_sigs ();
1151    dos_status = 0;
1152
1153    /* We call `system' to do the job of the SHELL, since stock DOS
1154       shell is too dumb.  Our `system' knows how to handle long
1155       command lines even if pipes/redirection is needed; it will only
1156       call COMMAND.COM when its internal commands are used.  */
1157    if (execute_by_shell)
1158      {
1159        char *cmdline = argv[0];
1160        /* We don't have a way to pass environment to `system',
1161           so we need to save and restore ours, sigh...  */
1162        char **parent_environ = environ;
1163
1164        environ = child->environment;
1165
1166        /* If we have a *real* shell, tell `system' to call
1167           it to do everything for us.  */
1168        if (unixy_shell)
1169          {
1170            /* A *real* shell on MSDOS may not support long
1171               command lines the DJGPP way, so we must use `system'.  */
1172            cmdline = argv[2];  /* get past "shell -c" */
1173          }
1174
1175        dos_command_running = 1;
1176        proc_return = system (cmdline);
1177        environ = parent_environ;
1178        execute_by_shell = 0;   /* for the next time */
1179      }
1180    else
1181      {
1182        dos_command_running = 1;
1183        proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1184      }
1185
1186    /* Need to unblock signals before turning off
1187       dos_command_running, so that child's signals
1188       will be treated as such (see fatal_error_signal).  */
1189    unblock_sigs ();
1190    dos_command_running = 0;
1191
1192    /* If the child got a signal, dos_status has its
1193       high 8 bits set, so be careful not to alter them.  */
1194    if (proc_return == -1)
1195      dos_status |= 0xff;
1196    else
1197      dos_status |= (proc_return & 0xff);
1198    ++dead_children;
1199    child->pid = dos_pid++;
1200  }
1201#endif /* __MSDOS__ */
1202#ifdef _AMIGA
1203  amiga_status = MyExecute (argv);
1204
1205  ++dead_children;
1206  child->pid = amiga_pid++;
1207  if (amiga_batch_file)
1208  {
1209     amiga_batch_file = 0;
1210     DeleteFile (amiga_bname);        /* Ignore errors.  */
1211  }
1212#endif  /* Amiga */
1213#ifdef WINDOWS32
1214  {
1215      HANDLE hPID;
1216      char* arg0;
1217
1218      /* make UNC paths safe for CreateProcess -- backslash format */
1219      arg0 = argv[0];
1220      if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1221        for ( ; arg0 && *arg0; arg0++)
1222          if (*arg0 == '/')
1223            *arg0 = '\\';
1224
1225      /* make sure CreateProcess() has Path it needs */
1226      sync_Path_environment();
1227
1228      hPID = process_easy(argv, child->environment);
1229
1230      if (hPID != INVALID_HANDLE_VALUE)
1231        child->pid = (int) hPID;
1232      else {
1233        int i;
1234        unblock_sigs();
1235        fprintf(stderr,
1236          _("process_easy() failed failed to launch process (e=%d)\n"),
1237          process_last_err(hPID));
1238               for (i = 0; argv[i]; i++)
1239                 fprintf(stderr, "%s ", argv[i]);
1240               fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1241      }
1242  }
1243#endif /* WINDOWS32 */
1244#endif  /* __MSDOS__ or Amiga or WINDOWS32 */
1245
1246  /* We are the parent side.  Set the state to
1247     say the commands are running and return.  */
1248
1249  set_command_state (child->file, cs_running);
1250
1251  /* Free the storage used by the child's argument list.  */
1252#ifndef VMS
1253  free (argv[0]);
1254  free ((char *) argv);
1255#endif
1256
1257  return;
1258
1259 error:
1260  child->file->update_status = 2;
1261  notice_finished_file (child->file);
1262  return;
1263}
1264
1265/* Try to start a child running.
1266   Returns nonzero if the child was started (and maybe finished), or zero if
1267   the load was too high and the child was put on the `waiting_jobs' chain.  */
1268
1269static int
1270start_waiting_job (c)
1271     struct child *c;
1272{
1273  struct file *f = c->file;
1274
1275  /* If we can start a job remotely, we always want to, and don't care about
1276     the local load average.  We record that the job should be started
1277     remotely in C->remote for start_job_command to test.  */
1278
1279  c->remote = start_remote_job_p (1);
1280
1281  /* If we are running at least one job already and the load average
1282     is too high, make this one wait.  */
1283  if (!c->remote && job_slots_used > 0 && load_too_high ())
1284    {
1285      /* Put this child on the chain of children waiting for the load average
1286         to go down.  */
1287      set_command_state (f, cs_running);
1288      c->next = waiting_jobs;
1289      waiting_jobs = c;
1290      return 0;
1291    }
1292
1293  /* Start the first command; reap_children will run later command lines.  */
1294  start_job_command (c);
1295
1296  switch (f->command_state)
1297    {
1298    case cs_running:
1299      c->next = children;
1300      DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1301                    (unsigned long int) c, c->file->name,
1302                    (long) c->pid, c->remote ? _(" (remote)") : ""));
1303      children = c;
1304      /* One more job slot is in use.  */
1305      ++job_slots_used;
1306      unblock_sigs ();
1307      break;
1308
1309    case cs_not_started:
1310      /* All the command lines turned out to be empty.  */
1311      f->update_status = 0;
1312      /* FALLTHROUGH */
1313
1314    case cs_finished:
1315      notice_finished_file (f);
1316      free_child (c);
1317      break;
1318
1319    default:
1320      assert (f->command_state == cs_finished);
1321      break;
1322    }
1323
1324  return 1;
1325}
1326
1327/* Create a `struct child' for FILE and start its commands running.  */
1328
1329void
1330new_job (file)
1331     register struct file *file;
1332{
1333  register struct commands *cmds = file->cmds;
1334  register struct child *c;
1335  char **lines;
1336  register unsigned int i;
1337
1338  /* Let any previously decided-upon jobs that are waiting
1339     for the load to go down start before this new one.  */
1340  start_waiting_jobs ();
1341
1342  /* Reap any children that might have finished recently.  */
1343  reap_children (0, 0);
1344
1345  /* Chop the commands up into lines if they aren't already.  */
1346  chop_commands (cmds);
1347
1348  /* Expand the command lines and store the results in LINES.  */
1349  lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1350  for (i = 0; i < cmds->ncommand_lines; ++i)
1351    {
1352      /* Collapse backslash-newline combinations that are inside variable
1353         or function references.  These are left alone by the parser so
1354         that they will appear in the echoing of commands (where they look
1355         nice); and collapsed by construct_command_argv when it tokenizes.
1356         But letting them survive inside function invocations loses because
1357         we don't want the functions to see them as part of the text.  */
1358
1359      char *in, *out, *ref;
1360
1361      /* IN points to where in the line we are scanning.
1362         OUT points to where in the line we are writing.
1363         When we collapse a backslash-newline combination,
1364         IN gets ahead of OUT.  */
1365
1366      in = out = cmds->command_lines[i];
1367      while ((ref = strchr (in, '$')) != 0)
1368        {
1369          ++ref;                /* Move past the $.  */
1370
1371          if (out != in)
1372            /* Copy the text between the end of the last chunk
1373               we processed (where IN points) and the new chunk
1374               we are about to process (where REF points).  */
1375            bcopy (in, out, ref - in);
1376
1377          /* Move both pointers past the boring stuff.  */
1378          out += ref - in;
1379          in = ref;
1380
1381          if (*ref == '(' || *ref == '{')
1382            {
1383              char openparen = *ref;
1384              char closeparen = openparen == '(' ? ')' : '}';
1385              int count;
1386              char *p;
1387
1388              *out++ = *in++;   /* Copy OPENPAREN.  */
1389              /* IN now points past the opening paren or brace.
1390                 Count parens or braces until it is matched.  */
1391              count = 0;
1392              while (*in != '\0')
1393                {
1394                  if (*in == closeparen && --count < 0)
1395                    break;
1396                  else if (*in == '\\' && in[1] == '\n')
1397                    {
1398                      /* We have found a backslash-newline inside a
1399                         variable or function reference.  Eat it and
1400                         any following whitespace.  */
1401
1402                      int quoted = 0;
1403                      for (p = in - 1; p > ref && *p == '\\'; --p)
1404                        quoted = !quoted;
1405
1406                      if (quoted)
1407                        /* There were two or more backslashes, so this is
1408                           not really a continuation line.  We don't collapse
1409                           the quoting backslashes here as is done in
1410                           collapse_continuations, because the line will
1411                           be collapsed again after expansion.  */
1412                        *out++ = *in++;
1413                      else
1414                        {
1415                          /* Skip the backslash, newline and
1416                             any following whitespace.  */
1417                          in = next_token (in + 2);
1418
1419                          /* Discard any preceding whitespace that has
1420                             already been written to the output.  */
1421                          while (out > ref
1422                                 && isblank ((unsigned char)out[-1]))
1423                            --out;
1424
1425                          /* Replace it all with a single space.  */
1426                          *out++ = ' ';
1427                        }
1428                    }
1429                  else
1430                    {
1431                      if (*in == openparen)
1432                        ++count;
1433
1434                      *out++ = *in++;
1435                    }
1436                }
1437            }
1438        }
1439
1440      /* There are no more references in this line to worry about.
1441         Copy the remaining uninteresting text to the output.  */
1442      if (out != in)
1443        strcpy (out, in);
1444
1445      /* Finally, expand the line.  */
1446      lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1447                                                     file);
1448    }
1449
1450  /* Start the command sequence, record it in a new
1451     `struct child', and add that to the chain.  */
1452
1453  c = (struct child *) xmalloc (sizeof (struct child));
1454  bzero ((char *)c, sizeof (struct child));
1455  c->file = file;
1456  c->command_lines = lines;
1457  c->sh_batch_file = NULL;
1458
1459  /* Fetch the first command line to be run.  */
1460  job_next_command (c);
1461
1462  /* Wait for a job slot to be freed up.  If we allow an infinite number
1463     don't bother; also job_slots will == 0 if we're using the jobserver.  */
1464
1465  if (job_slots != 0)
1466    while (job_slots_used == job_slots)
1467      reap_children (1, 0);
1468
1469#ifdef MAKE_JOBSERVER
1470  /* If we are controlling multiple jobs make sure we have a token before
1471     starting the child. */
1472
1473  /* This can be inefficient.  There's a decent chance that this job won't
1474     actually have to run any subprocesses: the command script may be empty
1475     or otherwise optimized away.  It would be nice if we could defer
1476     obtaining a token until just before we need it, in start_job_command.
1477     To do that we'd need to keep track of whether we'd already obtained a
1478     token (since start_job_command is called for each line of the job, not
1479     just once).  Also more thought needs to go into the entire algorithm;
1480     this is where the old parallel job code waits, so...  */
1481
1482  else if (job_fds[0] >= 0)
1483    while (1)
1484      {
1485        char token;
1486
1487        /* If we don't already have a job started, use our "free" token.  */
1488        if (!children)
1489          break;
1490
1491        /* Read a token.  As long as there's no token available we'll block.
1492           If we get a SIGCHLD we'll return with EINTR.  If one happened
1493           before we got here we'll return immediately with EBADF because
1494           the signal handler closes the dup'd file descriptor.  */
1495
1496        if (read (job_rfd, &token, 1) == 1)
1497          {
1498            DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1499                          (unsigned long int) c, c->file->name));
1500            break;
1501          }
1502
1503        if (errno != EINTR && errno != EBADF)
1504          pfatal_with_name (_("read jobs pipe"));
1505
1506        /* Re-dup the read side of the pipe, so the signal handler can
1507           notify us if we miss a child.  */
1508        if (job_rfd < 0)
1509          job_rfd = dup (job_fds[0]);
1510
1511        /* Something's done.  We don't want to block for a whole child,
1512           just reap whatever's there.  */
1513        reap_children (0, 0);
1514      }
1515#endif
1516
1517  /* The job is now primed.  Start it running.
1518     (This will notice if there are in fact no commands.)  */
1519  (void) start_waiting_job (c);
1520
1521  if (job_slots == 1 || not_parallel)
1522    /* Since there is only one job slot, make things run linearly.
1523       Wait for the child to die, setting the state to `cs_finished'.  */
1524    while (file->command_state == cs_running)
1525      reap_children (1, 0);
1526
1527  return;
1528}
1529
1530/* Move CHILD's pointers to the next command for it to execute.
1531   Returns nonzero if there is another command.  */
1532
1533static int
1534job_next_command (child)
1535     struct child *child;
1536{
1537  while (child->command_ptr == 0 || *child->command_ptr == '\0')
1538    {
1539      /* There are no more lines in the expansion of this line.  */
1540      if (child->command_line == child->file->cmds->ncommand_lines)
1541        {
1542          /* There are no more lines to be expanded.  */
1543          child->command_ptr = 0;
1544          return 0;
1545        }
1546      else
1547        /* Get the next line to run.  */
1548        child->command_ptr = child->command_lines[child->command_line++];
1549    }
1550  return 1;
1551}
1552
1553static int
1554load_too_high ()
1555{
1556#if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1557  return 1;
1558#else
1559  double load;
1560
1561  if (max_load_average < 0)
1562    return 0;
1563
1564  make_access ();
1565  if (getloadavg (&load, 1) != 1)
1566    {
1567      static int lossage = -1;
1568      /* Complain only once for the same error.  */
1569      if (lossage == -1 || errno != lossage)
1570        {
1571          if (errno == 0)
1572            /* An errno value of zero means getloadavg is just unsupported.  */
1573            error (NILF,
1574                   _("cannot enforce load limits on this operating system"));
1575          else
1576            perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1577        }
1578      lossage = errno;
1579      load = 0;
1580    }
1581  user_access ();
1582
1583  return load >= max_load_average;
1584#endif
1585}
1586
1587/* Start jobs that are waiting for the load to be lower.  */
1588
1589void
1590start_waiting_jobs ()
1591{
1592  struct child *job;
1593
1594  if (waiting_jobs == 0)
1595    return;
1596
1597  do
1598    {
1599      /* Check for recently deceased descendants.  */
1600      reap_children (0, 0);
1601
1602      /* Take a job off the waiting list.  */
1603      job = waiting_jobs;
1604      waiting_jobs = job->next;
1605
1606      /* Try to start that job.  We break out of the loop as soon
1607         as start_waiting_job puts one back on the waiting list.  */
1608    }
1609  while (start_waiting_job (job) && waiting_jobs != 0);
1610
1611  return;
1612}
1613
1614#ifndef WINDOWS32
1615#ifdef VMS
1616#include <descrip.h>
1617#include <clidef.h>
1618
1619/* This is called as an AST when a child process dies (it won't get
1620   interrupted by anything except a higher level AST).
1621*/
1622int vmsHandleChildTerm(struct child *child)
1623{
1624    int status;
1625    register struct child *lastc, *c;
1626    int child_failed;
1627
1628    vms_jobsefnmask &= ~(1 << (child->efn - 32));
1629
1630    lib$free_ef(&child->efn);
1631
1632    (void) sigblock (fatal_signal_mask);
1633
1634    child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1635
1636    /* Search for a child matching the deceased one.  */
1637    lastc = 0;
1638#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1639    for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1640#else
1641    c = child;
1642#endif
1643
1644    if (child_failed && !c->noerror && !ignore_errors_flag)
1645      {
1646        /* The commands failed.  Write an error message,
1647           delete non-precious targets, and abort.  */
1648        child_error (c->file->name, c->cstatus, 0, 0, 0);
1649        c->file->update_status = 1;
1650        delete_child_targets (c);
1651      }
1652    else
1653      {
1654        if (child_failed)
1655          {
1656            /* The commands failed, but we don't care.  */
1657            child_error (c->file->name, c->cstatus, 0, 0, 1);
1658            child_failed = 0;
1659          }
1660
1661#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1662        /* If there are more commands to run, try to start them.  */
1663        start_job (c);
1664
1665        switch (c->file->command_state)
1666          {
1667          case cs_running:
1668            /* Successfully started.  */
1669            break;
1670
1671          case cs_finished:
1672            if (c->file->update_status != 0) {
1673                /* We failed to start the commands.  */
1674                delete_child_targets (c);
1675            }
1676            break;
1677
1678          default:
1679            error (NILF, _("internal error: `%s' command_state"),
1680                   c->file->name);
1681            abort ();
1682            break;
1683          }
1684#endif /* RECURSIVEJOBS */
1685      }
1686
1687    /* Set the state flag to say the commands have finished.  */
1688    c->file->command_state = cs_finished;
1689    notice_finished_file (c->file);
1690
1691#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1692    /* Remove the child from the chain and free it.  */
1693    if (lastc == 0)
1694      children = c->next;
1695    else
1696      lastc->next = c->next;
1697    free_child (c);
1698#endif /* RECURSIVEJOBS */
1699
1700    /* There is now another slot open.  */
1701    if (job_slots_used > 0)
1702      --job_slots_used;
1703
1704    /* If the job failed, and the -k flag was not given, die.  */
1705    if (child_failed && !keep_going_flag)
1706      die (EXIT_FAILURE);
1707
1708    (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1709
1710    return 1;
1711}
1712
1713/* VMS:
1714   Spawn a process executing the command in ARGV and return its pid. */
1715
1716#define MAXCMDLEN 200
1717
1718/* local helpers to make ctrl+c and ctrl+y working, see below */
1719#include <iodef.h>
1720#include <libclidef.h>
1721#include <ssdef.h>
1722
1723static int ctrlMask= LIB$M_CLI_CTRLY;
1724static int oldCtrlMask;
1725static int setupYAstTried= 0;
1726static int pidToAbort= 0;
1727static int chan= 0;
1728
1729static void reEnableAst(void) {
1730        lib$enable_ctrl (&oldCtrlMask,0);
1731}
1732
1733static astHandler (void) {
1734        if (pidToAbort) {
1735                sys$forcex (&pidToAbort, 0, SS$_ABORT);
1736                pidToAbort= 0;
1737        }
1738        kill (getpid(),SIGQUIT);
1739}
1740
1741static void tryToSetupYAst(void) {
1742        $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1743        int     status;
1744        struct {
1745                short int       status, count;
1746                int     dvi;
1747        } iosb;
1748
1749        setupYAstTried++;
1750
1751        if (!chan) {
1752                status= sys$assign(&inputDsc,&chan,0,0);
1753                if (!(status&SS$_NORMAL)) {
1754                        lib$signal(status);
1755                        return;
1756                }
1757        }
1758        status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1759                astHandler,0,0,0,0,0);
1760        if (status==SS$_ILLIOFUNC) {
1761                sys$dassgn(chan);
1762#ifdef  CTRLY_ENABLED_ANYWAY
1763                fprintf (stderr,
1764                         _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1765#else
1766                return;
1767#endif
1768        }
1769        if (status==SS$_NORMAL)
1770                status= iosb.status;
1771        if (!(status&SS$_NORMAL)) {
1772                lib$signal(status);
1773                return;
1774        }
1775
1776        /* called from AST handler ? */
1777        if (setupYAstTried>1)
1778                return;
1779        if (atexit(reEnableAst))
1780                fprintf (stderr,
1781                         _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1782        status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1783        if (!(status&SS$_NORMAL)) {
1784                lib$signal(status);
1785                return;
1786        }
1787}
1788int
1789child_execute_job (argv, child)
1790     char *argv;
1791     struct child *child;
1792{
1793  int i;
1794  static struct dsc$descriptor_s cmddsc;
1795  static struct dsc$descriptor_s pnamedsc;
1796  static struct dsc$descriptor_s ifiledsc;
1797  static struct dsc$descriptor_s ofiledsc;
1798  static struct dsc$descriptor_s efiledsc;
1799  int have_redirection = 0;
1800  int have_newline = 0;
1801
1802  int spflags = CLI$M_NOWAIT;
1803  int status;
1804  char *cmd = alloca (strlen (argv) + 512), *p, *q;
1805  char ifile[256], ofile[256], efile[256];
1806  char *comname = 0;
1807  char procname[100];
1808
1809  /* Parse IO redirection.  */
1810
1811  ifile[0] = 0;
1812  ofile[0] = 0;
1813  efile[0] = 0;
1814
1815  DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1816
1817  while (isspace ((unsigned char)*argv))
1818    argv++;
1819
1820  if (*argv == 0)
1821    return 0;
1822
1823  sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1824  pnamedsc.dsc$w_length = strlen(procname);
1825  pnamedsc.dsc$a_pointer = procname;
1826  pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1827  pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1828
1829  /* Handle comments and redirection. */
1830  for (p = argv, q = cmd; *p; p++, q++)
1831    {
1832      switch (*p)
1833        {
1834          case '#':
1835            *p-- = 0;
1836            *q-- = 0;
1837            break;
1838          case '\\':
1839            p++;
1840            if (*p == '\n')
1841              p++;
1842            if (isspace ((unsigned char)*p))
1843              {
1844                do { p++; } while (isspace ((unsigned char)*p));
1845                p--;
1846              }
1847            *q = *p;
1848            break;
1849          case '<':
1850            p = vms_redirect (&ifiledsc, ifile, p);
1851            *q = ' ';
1852            have_redirection = 1;
1853            break;
1854          case '>':
1855            have_redirection = 1;
1856            if (*(p-1) == '2')
1857              {
1858                q--;
1859                if (strncmp (p, ">&1", 3) == 0)
1860                  {
1861                    p += 3;
1862                    strcpy (efile, "sys$output");
1863                    efiledsc.dsc$w_length = strlen(efile);
1864                    efiledsc.dsc$a_pointer = efile;
1865                    efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
1866                    efiledsc.dsc$b_class = DSC$K_CLASS_S;
1867                  }
1868                else
1869                  {
1870                    p = vms_redirect (&efiledsc, efile, p);
1871                  }
1872              }
1873            else
1874              {
1875                p = vms_redirect (&ofiledsc, ofile, p);
1876              }
1877            *q = ' ';
1878            break;
1879          case '\n':
1880            have_newline = 1;
1881          default:
1882            *q = *p;
1883            break;
1884        }
1885    }
1886  *q = *p;
1887
1888  if (strncmp (cmd, "builtin_", 8) == 0)
1889    {
1890      child->pid = 270163;
1891      child->efn = 0;
1892      child->cstatus = 1;
1893
1894      DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
1895
1896      p = cmd + 8;
1897
1898      if ((*(p) == 'c')
1899          && (*(p+1) == 'd')
1900          && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1901        {
1902          p += 3;
1903          while ((*p == ' ') || (*p == '\t'))
1904            p++;
1905          DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
1906          if (chdir (p))
1907            return 0;
1908          else
1909            return 1;
1910        }
1911      else if ((*(p) == 'r')
1912          && (*(p+1) == 'm')
1913          && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1914        {
1915          int in_arg;
1916
1917          /* rm  */
1918          p += 3;
1919          while ((*p == ' ') || (*p == '\t'))
1920            p++;
1921          in_arg = 1;
1922
1923          DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
1924          while (*p)
1925            {
1926              switch (*p)
1927                {
1928                  case ' ':
1929                  case '\t':
1930                    if (in_arg)
1931                      {
1932                        *p++ = ';';
1933                        in_arg = 0;
1934                      }
1935                    break;
1936                  default:
1937                    break;
1938                }
1939              p++;
1940            }
1941        }
1942      else
1943        {
1944          printf(_("Unknown builtin command '%s'\n"), cmd);
1945          fflush(stdout);
1946          return 0;
1947        }
1948    }
1949
1950  /* Create a *.com file if either the command is too long for
1951     lib$spawn, or the command contains a newline, or if redirection
1952     is desired. Forcing commands with newlines into DCLs allows to
1953     store search lists on user mode logicals.  */
1954
1955  if (strlen (cmd) > MAXCMDLEN
1956      || (have_redirection != 0)
1957      || (have_newline != 0))
1958    {
1959      FILE *outfile;
1960      char c;
1961      char *sep;
1962      int alevel = 0;   /* apostrophe level */
1963
1964      if (strlen (cmd) == 0)
1965        {
1966          printf (_("Error, empty command\n"));
1967          fflush (stdout);
1968          return 0;
1969        }
1970
1971      outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
1972      if (outfile == 0)
1973        pfatal_with_name (_("fopen (temporary file)"));
1974
1975      if (ifile[0])
1976        {
1977          fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
1978          DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
1979          ifiledsc.dsc$w_length = 0;
1980        }
1981
1982      if (efile[0])
1983        {
1984          fprintf (outfile, "$ define sys$error %s\n", efile);
1985          DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
1986          efiledsc.dsc$w_length = 0;
1987        }
1988
1989      if (ofile[0])
1990        {
1991          fprintf (outfile, "$ define sys$output %s\n", ofile);
1992          DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
1993          ofiledsc.dsc$w_length = 0;
1994        }
1995
1996      p = sep = q = cmd;
1997      for (c = '\n'; c; c = *q++)
1998        {
1999          switch (c)
2000            {
2001            case '\n':
2002              /* At a newline, skip any whitespace around a leading $
2003                 from the command and issue exactly one $ into the DCL. */
2004              while (isspace ((unsigned char)*p))
2005                p++;
2006              if (*p == '$')
2007                p++;
2008              while (isspace ((unsigned char)*p))
2009                p++;
2010              fwrite (p, 1, q - p, outfile);
2011              fputc ('$', outfile);
2012              fputc (' ', outfile);
2013              /* Reset variables. */
2014              p = sep = q;
2015              break;
2016
2017              /* Nice places for line breaks are after strings, after
2018                 comma or space and before slash. */
2019            case '"':
2020              q = handle_apos (q + 1);
2021              sep = q;
2022              break;
2023            case ',':
2024            case ' ':
2025              sep = q;
2026              break;
2027            case '/':
2028            case '\0':
2029              sep = q - 1;
2030              break;
2031            default:
2032              break;
2033            }
2034          if (sep - p > 78)
2035            {
2036              /* Enough stuff for a line. */
2037              fwrite (p, 1, sep - p, outfile);
2038              p = sep;
2039              if (*sep)
2040                {
2041                  /* The command continues.  */
2042                  fputc ('-', outfile);
2043                }
2044              fputc ('\n', outfile);
2045            }
2046        }
2047
2048      fwrite (p, 1, q - p, outfile);
2049      fputc ('\n', outfile);
2050
2051      fclose (outfile);
2052
2053      sprintf (cmd, "$ @%s", comname);
2054
2055      DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2056    }
2057
2058  cmddsc.dsc$w_length = strlen(cmd);
2059  cmddsc.dsc$a_pointer = cmd;
2060  cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2061  cmddsc.dsc$b_class = DSC$K_CLASS_S;
2062
2063  child->efn = 0;
2064  while (child->efn < 32 || child->efn > 63)
2065    {
2066      status = lib$get_ef ((unsigned long *)&child->efn);
2067      if (!(status & 1))
2068        return 0;
2069    }
2070
2071  sys$clref (child->efn);
2072
2073  vms_jobsefnmask |= (1 << (child->efn - 32));
2074
2075/*
2076             LIB$SPAWN  [command-string]
2077                        [,input-file]
2078                        [,output-file]
2079                        [,flags]
2080                        [,process-name]
2081                        [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2082                        [,AST-address] [,varying-AST-argument]
2083                        [,prompt-string] [,cli] [,table]
2084*/
2085
2086#ifndef DONTWAITFORCHILD
2087/*
2088 *      Code to make ctrl+c and ctrl+y working.
2089 *      The problem starts with the synchronous case where after lib$spawn is
2090 *      called any input will go to the child. But with input re-directed,
2091 *      both control characters won't make it to any of the programs, neither
2092 *      the spawning nor to the spawned one. Hence the caller needs to spawn
2093 *      with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2094 *      has to follow to simulate the wanted synchronous behaviour.
2095 *      The next problem is ctrl+y which isn't caught by the crtl and
2096 *      therefore isn't converted to SIGQUIT (for a signal handler which is
2097 *      already established). The only way to catch ctrl+y, is an AST
2098 *      assigned to the input channel. But ctrl+y handling of DCL needs to be
2099 *      disabled, otherwise it will handle it. Not to mention the previous
2100 *      ctrl+y handling of DCL needs to be re-established before make exits.
2101 *      One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2102 *      make it to the signal handler after the child "normally" terminates.
2103 *      This isn't enough. It seems reasonable for simple command lines like
2104 *      a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2105 *      spawning make. Therefore we need to abort the process in the AST.
2106 *
2107 *      Prior to the spawn it is checked if an AST is already set up for
2108 *      ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2109 *      this will work except if make is run in a batch environment, but there
2110 *      nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2111 *      is disabled and an exit handler is established to re-enable it.
2112 *      If the user interrupts with ctrl+y, the assigned AST will fire, force
2113 *      an abort to the subprocess and signal SIGQUIT, which will be caught by
2114 *      the already established handler and will bring us back to common code.
2115 *      After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2116 *      enables the ctrl+y be delivered to this code. And the ctrl+c too,
2117 *      which the crtl converts to SIGINT and which is caught by the common
2118 *      signal handler. Because signals were blocked before entering this code
2119 *      sys$waitfr will always complete and the SIGQUIT will be processed after
2120 *      it (after termination of the current block, somewhere in common code).
2121 *      And SIGINT too will be delayed. That is ctrl+c can only abort when the
2122 *      current command completes. Anyway it's better than nothing :-)
2123 */
2124
2125  if (!setupYAstTried)
2126    tryToSetupYAst();
2127  status = lib$spawn (&cmddsc,                                  /* cmd-string  */
2128                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file  */
2129                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2130                      &spflags,                                 /* flags  */
2131                      &pnamedsc,                                /* proc name  */
2132                      &child->pid, &child->cstatus, &child->efn,
2133                      0, 0,
2134                      0, 0, 0);
2135  pidToAbort= child->pid;
2136  status= sys$waitfr (child->efn);
2137  pidToAbort= 0;
2138  vmsHandleChildTerm(child);
2139#else
2140  status = lib$spawn (&cmddsc,
2141                      (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2142                      (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2143                      &spflags,
2144                      &pnamedsc,
2145                      &child->pid, &child->cstatus, &child->efn,
2146                      vmsHandleChildTerm, child,
2147                      0, 0, 0);
2148#endif
2149
2150  if (!(status & 1))
2151    {
2152      printf (_("Error spawning, %d\n") ,status);
2153      fflush (stdout);
2154    }
2155
2156  if (comname && !ISDB (DB_JOBS))
2157    unlink (comname);
2158
2159  return (status & 1);
2160}
2161
2162#else /* !VMS */
2163
2164#if !defined (_AMIGA) && !defined (__MSDOS__)
2165/* UNIX:
2166   Replace the current process with one executing the command in ARGV.
2167   STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2168   the environment of the new program.  This function does not return.  */
2169
2170void
2171child_execute_job (stdin_fd, stdout_fd, argv, envp)
2172     int stdin_fd, stdout_fd;
2173     char **argv, **envp;
2174{
2175  if (stdin_fd != 0)
2176    (void) dup2 (stdin_fd, 0);
2177  if (stdout_fd != 1)
2178    (void) dup2 (stdout_fd, 1);
2179  if (stdin_fd != 0)
2180    (void) close (stdin_fd);
2181  if (stdout_fd != 1)
2182    (void) close (stdout_fd);
2183
2184  /* Run the command.  */
2185  exec_command (argv, envp);
2186}
2187#endif /* !AMIGA && !__MSDOS__ */
2188#endif /* !VMS */
2189#endif /* !WINDOWS32 */
2190
2191#ifndef _AMIGA
2192/* Replace the current process with one running the command in ARGV,
2193   with environment ENVP.  This function does not return.  */
2194
2195void
2196exec_command (argv, envp)
2197     char **argv, **envp;
2198{
2199#ifdef VMS
2200  /* to work around a problem with signals and execve: ignore them */
2201#ifdef SIGCHLD
2202  signal (SIGCHLD,SIG_IGN);
2203#endif
2204  /* Run the program.  */
2205  execve (argv[0], argv, envp);
2206  perror_with_name ("execve: ", argv[0]);
2207  _exit (EXIT_FAILURE);
2208#else
2209#ifdef WINDOWS32
2210  HANDLE hPID;
2211  HANDLE hWaitPID;
2212  int err = 0;
2213  int exit_code = EXIT_FAILURE;
2214
2215  /* make sure CreateProcess() has Path it needs */
2216  sync_Path_environment();
2217
2218  /* launch command */
2219  hPID = process_easy(argv, envp);
2220
2221  /* make sure launch ok */
2222  if (hPID == INVALID_HANDLE_VALUE)
2223    {
2224      int i;
2225      fprintf(stderr,
2226              _("process_easy() failed failed to launch process (e=%d)\n"),
2227              process_last_err(hPID));
2228      for (i = 0; argv[i]; i++)
2229          fprintf(stderr, "%s ", argv[i]);
2230      fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2231      exit(EXIT_FAILURE);
2232    }
2233
2234  /* wait and reap last child */
2235  while (hWaitPID = process_wait_for_any())
2236    {
2237      /* was an error found on this process? */
2238      err = process_last_err(hWaitPID);
2239
2240      /* get exit data */
2241      exit_code = process_exit_code(hWaitPID);
2242
2243      if (err)
2244          fprintf(stderr, "make (e=%d, rc=%d): %s",
2245                  err, exit_code, map_windows32_error_to_string(err));
2246
2247      /* cleanup process */
2248      process_cleanup(hWaitPID);
2249
2250      /* expect to find only last pid, warn about other pids reaped */
2251      if (hWaitPID == hPID)
2252          break;
2253      else
2254          fprintf(stderr,
2255                  _("make reaped child pid %d, still waiting for pid %d\n"),
2256                  hWaitPID, hPID);
2257    }
2258
2259  /* return child's exit code as our exit code */
2260  exit(exit_code);
2261
2262#else  /* !WINDOWS32 */
2263
2264  /* Be the user, permanently.  */
2265  child_access ();
2266
2267  /* Run the program.  */
2268  environ = envp;
2269  execvp (argv[0], argv);
2270
2271  switch (errno)
2272    {
2273    case ENOENT:
2274      error (NILF, _("%s: Command not found"), argv[0]);
2275      break;
2276    case ENOEXEC:
2277      {
2278        /* The file is not executable.  Try it as a shell script.  */
2279        extern char *getenv ();
2280        char *shell;
2281        char **new_argv;
2282        int argc;
2283
2284        shell = getenv ("SHELL");
2285        if (shell == 0)
2286          shell = default_shell;
2287
2288        argc = 1;
2289        while (argv[argc] != 0)
2290          ++argc;
2291
2292        new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2293        new_argv[0] = shell;
2294        new_argv[1] = argv[0];
2295        while (argc > 0)
2296          {
2297            new_argv[1 + argc] = argv[argc];
2298            --argc;
2299          }
2300
2301        execvp (shell, new_argv);
2302        if (errno == ENOENT)
2303          error (NILF, _("%s: Shell program not found"), shell);
2304        else
2305          perror_with_name ("execvp: ", shell);
2306        break;
2307      }
2308
2309    default:
2310      perror_with_name ("execvp: ", argv[0]);
2311      break;
2312    }
2313
2314  _exit (127);
2315#endif /* !WINDOWS32 */
2316#endif /* !VMS */
2317}
2318#else /* On Amiga */
2319void exec_command (argv)
2320     char **argv;
2321{
2322  MyExecute (argv);
2323}
2324
2325void clean_tmp (void)
2326{
2327  DeleteFile (amiga_bname);
2328}
2329
2330#endif /* On Amiga */
2331
2332#ifndef VMS
2333/* Figure out the argument list necessary to run LINE as a command.  Try to
2334   avoid using a shell.  This routine handles only ' quoting, and " quoting
2335   when no backslash, $ or ` characters are seen in the quotes.  Starting
2336   quotes may be escaped with a backslash.  If any of the characters in
2337   sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2338   is the first word of a line, the shell is used.
2339
2340   If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2341   If *RESTP is NULL, newlines will be ignored.
2342
2343   SHELL is the shell to use, or nil to use the default shell.
2344   IFS is the value of $IFS, or nil (meaning the default).  */
2345
2346static char **
2347construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
2348     char *line, **restp;
2349     char *shell, *ifs;
2350     char **batch_filename_ptr;
2351{
2352#ifdef __MSDOS__
2353  /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2354     We call `system' for anything that requires ``slow'' processing,
2355     because DOS shells are too dumb.  When $SHELL points to a real
2356     (unix-style) shell, `system' just calls it to do everything.  When
2357     $SHELL points to a DOS shell, `system' does most of the work
2358     internally, calling the shell only for its internal commands.
2359     However, it looks on the $PATH first, so you can e.g. have an
2360     external command named `mkdir'.
2361
2362     Since we call `system', certain characters and commands below are
2363     actually not specific to COMMAND.COM, but to the DJGPP implementation
2364     of `system'.  In particular:
2365
2366       The shell wildcard characters are in DOS_CHARS because they will
2367       not be expanded if we call the child via `spawnXX'.
2368
2369       The `;' is in DOS_CHARS, because our `system' knows how to run
2370       multiple commands on a single line.
2371
2372       DOS_CHARS also include characters special to 4DOS/NDOS, so we
2373       won't have to tell one from another and have one more set of
2374       commands and special characters.  */
2375  static char sh_chars_dos[] = "*?[];|<>%^&()";
2376  static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2377                                 "copy", "ctty", "date", "del", "dir", "echo",
2378                                 "erase", "exit", "for", "goto", "if", "md",
2379                                 "mkdir", "path", "pause", "prompt", "rd",
2380                                 "rmdir", "rem", "ren", "rename", "set",
2381                                 "shift", "time", "type", "ver", "verify",
2382                                 "vol", ":", 0 };
2383
2384  static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^";
2385  static char *sh_cmds_sh[]  = { "cd", "echo", "eval", "exec", "exit", "login",
2386                                 "logout", "set", "umask", "wait", "while",
2387                                 "for", "case", "if", ":", ".", "break",
2388                                 "continue", "export", "read", "readonly",
2389                                 "shift", "times", "trap", "switch", "unset",
2390                                 0 };
2391
2392  char *sh_chars;
2393  char **sh_cmds;
2394#else
2395#ifdef _AMIGA
2396  static char sh_chars[] = "#;\"|<>()?*$`";
2397  static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2398                             "rename", "set", "setenv", "date", "makedir",
2399                             "skip", "else", "endif", "path", "prompt",
2400                             "unset", "unsetenv", "version",
2401                             0 };
2402#else
2403#ifdef WINDOWS32
2404  static char sh_chars_dos[] = "\"|&<>";
2405  static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2406                             "copy", "ctty", "date", "del", "dir", "echo",
2407                             "erase", "exit", "for", "goto", "if", "if", "md",
2408                             "mkdir", "path", "pause", "prompt", "rd", "rem",
2409                             "ren", "rename", "rmdir", "set", "shift", "time",
2410                             "type", "ver", "verify", "vol", ":", 0 };
2411  static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2412  static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2413                             "logout", "set", "umask", "wait", "while", "for",
2414                             "case", "if", ":", ".", "break", "continue",
2415                             "export", "read", "readonly", "shift", "times",
2416                             "trap", "switch", "test",
2417#ifdef BATCH_MODE_ONLY_SHELL
2418                 "echo",
2419#endif
2420                 0 };
2421  char*  sh_chars;
2422  char** sh_cmds;
2423#else  /* WINDOWS32 */
2424  static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
2425  static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2426                             "logout", "set", "umask", "wait", "while", "for",
2427                             "case", "if", ":", ".", "break", "continue",
2428                             "export", "read", "readonly", "shift", "times",
2429                             "trap", "switch", 0 };
2430#endif /* WINDOWS32 */
2431#endif /* Amiga */
2432#endif /* __MSDOS__ */
2433  register int i;
2434  register char *p;
2435  register char *ap;
2436  char *end;
2437  int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2438  char **new_argv = 0;
2439#ifdef WINDOWS32
2440  int slow_flag = 0;
2441
2442  if (no_default_sh_exe) {
2443    sh_cmds = sh_cmds_dos;
2444    sh_chars = sh_chars_dos;
2445  } else {
2446    sh_cmds = sh_cmds_sh;
2447    sh_chars = sh_chars_sh;
2448  }
2449#endif /* WINDOWS32 */
2450
2451  if (restp != NULL)
2452    *restp = NULL;
2453
2454  /* Make sure not to bother processing an empty line.  */
2455  while (isblank ((unsigned char)*line))
2456    ++line;
2457  if (*line == '\0')
2458    return 0;
2459
2460  /* See if it is safe to parse commands internally.  */
2461  if (shell == 0)
2462    shell = default_shell;
2463#ifdef WINDOWS32
2464  else if (strcmp (shell, default_shell))
2465  {
2466    char *s1 = _fullpath(NULL, shell, 0);
2467    char *s2 = _fullpath(NULL, default_shell, 0);
2468
2469    slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2470
2471    if (s1)
2472      free (s1);
2473    if (s2)
2474      free (s2);
2475  }
2476  if (slow_flag)
2477    goto slow;
2478#else  /* not WINDOWS32 */
2479#ifdef __MSDOS__
2480  else if (stricmp (shell, default_shell))
2481    {
2482      extern int _is_unixy_shell (const char *_path);
2483
2484      message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2485      unixy_shell = _is_unixy_shell (shell);
2486      default_shell = shell;
2487    }
2488  if (unixy_shell)
2489    {
2490      sh_chars = sh_chars_sh;
2491      sh_cmds  = sh_cmds_sh;
2492    }
2493  else
2494    {
2495      sh_chars = sh_chars_dos;
2496      sh_cmds  = sh_cmds_dos;
2497    }
2498#else  /* not __MSDOS__ */
2499  else if (strcmp (shell, default_shell))
2500    goto slow;
2501#endif /* not __MSDOS__ */
2502#endif /* not WINDOWS32 */
2503
2504  if (ifs != 0)
2505    for (ap = ifs; *ap != '\0'; ++ap)
2506      if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2507        goto slow;
2508
2509  i = strlen (line) + 1;
2510
2511  /* More than 1 arg per character is impossible.  */
2512  new_argv = (char **) xmalloc (i * sizeof (char *));
2513
2514  /* All the args can fit in a buffer as big as LINE is.   */
2515  ap = new_argv[0] = (char *) xmalloc (i);
2516  end = ap + i;
2517
2518  /* I is how many complete arguments have been found.  */
2519  i = 0;
2520  instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2521  for (p = line; *p != '\0'; ++p)
2522    {
2523      if (ap > end)
2524        abort ();
2525
2526      if (instring)
2527        {
2528        string_char:
2529          /* Inside a string, just copy any char except a closing quote
2530             or a backslash-newline combination.  */
2531          if (*p == instring)
2532            {
2533              instring = 0;
2534              if (ap == new_argv[0] || *(ap-1) == '\0')
2535                last_argument_was_empty = 1;
2536            }
2537          else if (*p == '\\' && p[1] == '\n')
2538            goto swallow_escaped_newline;
2539          else if (*p == '\n' && restp != NULL)
2540            {
2541              /* End of the command line.  */
2542              *restp = p;
2543              goto end_of_line;
2544            }
2545          /* Backslash, $, and ` are special inside double quotes.
2546             If we see any of those, punt.
2547             But on MSDOS, if we use COMMAND.COM, double and single
2548             quotes have the same effect.  */
2549          else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2550            goto slow;
2551          else
2552            *ap++ = *p;
2553        }
2554      else if (strchr (sh_chars, *p) != 0)
2555        /* Not inside a string, but it's a special char.  */
2556        goto slow;
2557#ifdef  __MSDOS__
2558      else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2559        /* `...' is a wildcard in DJGPP.  */
2560        goto slow;
2561#endif
2562      else
2563        /* Not a special char.  */
2564        switch (*p)
2565          {
2566          case '=':
2567            /* Equals is a special character in leading words before the
2568               first word with no equals sign in it.  This is not the case
2569               with sh -k, but we never get here when using nonstandard
2570               shell flags.  */
2571            if (! seen_nonequals && unixy_shell)
2572              goto slow;
2573            word_has_equals = 1;
2574            *ap++ = '=';
2575            break;
2576
2577          case '\\':
2578            /* Backslash-newline combinations are eaten.  */
2579            if (p[1] == '\n')
2580              {
2581              swallow_escaped_newline:
2582
2583                /* Eat the backslash, the newline, and following whitespace,
2584                   replacing it all with a single space.  */
2585                p += 2;
2586
2587                /* If there is a tab after a backslash-newline,
2588                   remove it from the source line which will be echoed,
2589                   since it was most likely used to line
2590                   up the continued line with the previous one.  */
2591                if (*p == '\t')
2592                  /* Note these overlap and strcpy() is undefined for
2593                     overlapping objects in ANSI C.  The strlen() _IS_ right,
2594                     since we need to copy the nul byte too.  */
2595                  bcopy (p + 1, p, strlen (p));
2596
2597                if (instring)
2598                  goto string_char;
2599                else
2600                  {
2601                    if (ap != new_argv[i])
2602                      /* Treat this as a space, ending the arg.
2603                         But if it's at the beginning of the arg, it should
2604                         just get eaten, rather than becoming an empty arg. */
2605                      goto end_of_arg;
2606                    else
2607                      p = next_token (p) - 1;
2608                  }
2609              }
2610            else if (p[1] != '\0')
2611              {
2612#if defined(__MSDOS__) || defined(WINDOWS32)
2613                /* Only remove backslashes before characters special
2614                   to Unixy shells.  All other backslashes are copied
2615                   verbatim, since they are probably DOS-style
2616                   directory separators.  This still leaves a small
2617                   window for problems, but at least it should work
2618                   for the vast majority of naive users.  */
2619
2620#ifdef __MSDOS__
2621                /* A dot is only special as part of the "..."
2622                   wildcard.  */
2623                if (strneq (p + 1, ".\\.\\.", 5))
2624                  {
2625                    *ap++ = '.';
2626                    *ap++ = '.';
2627                    p += 4;
2628                  }
2629                else
2630#endif
2631                  if (p[1] != '\\' && p[1] != '\''
2632                      && !isspace ((unsigned char)p[1])
2633                      && (strchr (sh_chars_sh, p[1]) == 0))
2634                    /* back up one notch, to copy the backslash */
2635                    --p;
2636
2637#endif  /* __MSDOS__ || WINDOWS32 */
2638                /* Copy and skip the following char.  */
2639                *ap++ = *++p;
2640              }
2641            break;
2642
2643          case '\'':
2644          case '"':
2645            instring = *p;
2646            break;
2647
2648          case '\n':
2649            if (restp != NULL)
2650              {
2651                /* End of the command line.  */
2652                *restp = p;
2653                goto end_of_line;
2654              }
2655            else
2656              /* Newlines are not special.  */
2657              *ap++ = '\n';
2658            break;
2659
2660          case ' ':
2661          case '\t':
2662          end_of_arg:
2663            /* We have the end of an argument.
2664               Terminate the text of the argument.  */
2665            *ap++ = '\0';
2666            new_argv[++i] = ap;
2667            last_argument_was_empty = 0;
2668
2669            /* Update SEEN_NONEQUALS, which tells us if every word
2670               heretofore has contained an `='.  */
2671            seen_nonequals |= ! word_has_equals;
2672            if (word_has_equals && ! seen_nonequals)
2673              /* An `=' in a word before the first
2674                 word without one is magical.  */
2675              goto slow;
2676            word_has_equals = 0; /* Prepare for the next word.  */
2677
2678            /* If this argument is the command name,
2679               see if it is a built-in shell command.
2680               If so, have the shell handle it.  */
2681            if (i == 1)
2682              {
2683                register int j;
2684                for (j = 0; sh_cmds[j] != 0; ++j)
2685                  if (streq (sh_cmds[j], new_argv[0]))
2686                    goto slow;
2687              }
2688
2689            /* Ignore multiple whitespace chars.  */
2690            p = next_token (p);
2691            /* Next iteration should examine the first nonwhite char.  */
2692            --p;
2693            break;
2694
2695          default:
2696            *ap++ = *p;
2697            break;
2698          }
2699    }
2700 end_of_line:
2701
2702  if (instring)
2703    /* Let the shell deal with an unterminated quote.  */
2704    goto slow;
2705
2706  /* Terminate the last argument and the argument list.  */
2707
2708  *ap = '\0';
2709  if (new_argv[i][0] != '\0' || last_argument_was_empty)
2710    ++i;
2711  new_argv[i] = 0;
2712
2713  if (i == 1)
2714    {
2715      register int j;
2716      for (j = 0; sh_cmds[j] != 0; ++j)
2717        if (streq (sh_cmds[j], new_argv[0]))
2718          goto slow;
2719    }
2720
2721  if (new_argv[0] == 0)
2722    /* Line was empty.  */
2723    return 0;
2724  else
2725    return new_argv;
2726
2727 slow:;
2728  /* We must use the shell.  */
2729
2730  if (new_argv != 0)
2731    {
2732      /* Free the old argument list we were working on.  */
2733      free (new_argv[0]);
2734      free ((void *)new_argv);
2735    }
2736
2737#ifdef __MSDOS__
2738  execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2739#endif
2740
2741#ifdef _AMIGA
2742  {
2743    char *ptr;
2744    char *buffer;
2745    char *dptr;
2746
2747    buffer = (char *)xmalloc (strlen (line)+1);
2748
2749    ptr = line;
2750    for (dptr=buffer; *ptr; )
2751    {
2752      if (*ptr == '\\' && ptr[1] == '\n')
2753        ptr += 2;
2754      else if (*ptr == '@') /* Kludge: multiline commands */
2755      {
2756        ptr += 2;
2757        *dptr++ = '\n';
2758      }
2759      else
2760        *dptr++ = *ptr++;
2761    }
2762    *dptr = 0;
2763
2764    new_argv = (char **) xmalloc (2 * sizeof (char *));
2765    new_argv[0] = buffer;
2766    new_argv[1] = 0;
2767  }
2768#else   /* Not Amiga  */
2769#ifdef WINDOWS32
2770  /*
2771   * Not eating this whitespace caused things like
2772   *
2773   *    sh -c "\n"
2774   *
2775   * which gave the shell fits. I think we have to eat
2776   * whitespace here, but this code should be considered
2777   * suspicious if things start failing....
2778   */
2779
2780  /* Make sure not to bother processing an empty line.  */
2781  while (isspace ((unsigned char)*line))
2782    ++line;
2783  if (*line == '\0')
2784    return 0;
2785#endif /* WINDOWS32 */
2786  {
2787    /* SHELL may be a multi-word command.  Construct a command line
2788       "SHELL -c LINE", with all special chars in LINE escaped.
2789       Then recurse, expanding this command line to get the final
2790       argument list.  */
2791
2792    unsigned int shell_len = strlen (shell);
2793#ifndef VMS
2794    static char minus_c[] = " -c ";
2795#else
2796    static char minus_c[] = "";
2797#endif
2798    unsigned int line_len = strlen (line);
2799
2800    char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2801                                      + (line_len * 2) + 1);
2802    char *command_ptr = NULL; /* used for batch_mode_shell mode */
2803
2804    ap = new_line;
2805    bcopy (shell, ap, shell_len);
2806    ap += shell_len;
2807    bcopy (minus_c, ap, sizeof (minus_c) - 1);
2808    ap += sizeof (minus_c) - 1;
2809    command_ptr = ap;
2810    for (p = line; *p != '\0'; ++p)
2811      {
2812        if (restp != NULL && *p == '\n')
2813          {
2814            *restp = p;
2815            break;
2816          }
2817        else if (*p == '\\' && p[1] == '\n')
2818          {
2819            /* Eat the backslash, the newline, and following whitespace,
2820               replacing it all with a single space (which is escaped
2821               from the shell).  */
2822            p += 2;
2823
2824            /* If there is a tab after a backslash-newline,
2825               remove it from the source line which will be echoed,
2826               since it was most likely used to line
2827               up the continued line with the previous one.  */
2828            if (*p == '\t')
2829              bcopy (p + 1, p, strlen (p));
2830
2831            p = next_token (p);
2832            --p;
2833            if (unixy_shell && !batch_mode_shell)
2834              *ap++ = '\\';
2835            *ap++ = ' ';
2836            continue;
2837          }
2838
2839        /* DOS shells don't know about backslash-escaping.  */
2840        if (unixy_shell && !batch_mode_shell &&
2841            (*p == '\\' || *p == '\'' || *p == '"'
2842             || isspace ((unsigned char)*p)
2843             || strchr (sh_chars, *p) != 0))
2844          *ap++ = '\\';
2845#ifdef __MSDOS__
2846        else if (unixy_shell && strneq (p, "...", 3))
2847          {
2848            /* The case of `...' wildcard again.  */
2849            strcpy (ap, "\\.\\.\\");
2850            ap += 5;
2851            p  += 2;
2852          }
2853#endif
2854        *ap++ = *p;
2855      }
2856    if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2857      /* Line was empty.  */
2858      return 0;
2859    *ap = '\0';
2860
2861#ifdef WINDOWS32
2862    /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2863       command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems).  In these
2864       cases, run commands via a script file.  */
2865    if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2866      FILE* batch = NULL;
2867      int id = GetCurrentProcessId();
2868      PATH_VAR(fbuf);
2869      char* fname = NULL;
2870
2871      /* create a file name */
2872      sprintf(fbuf, "make%d", id);
2873      fname = tempnam(".", fbuf);
2874
2875          /* create batch file name */
2876      *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2877      strcpy(*batch_filename_ptr, fname);
2878
2879      /* make sure path name is in DOS backslash format */
2880      if (!unixy_shell) {
2881        fname = *batch_filename_ptr;
2882        for (i = 0; fname[i] != '\0'; ++i)
2883          if (fname[i] == '/')
2884            fname[i] = '\\';
2885        strcat(*batch_filename_ptr, ".bat");
2886      } else {
2887        strcat(*batch_filename_ptr, ".sh");
2888      }
2889
2890      DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2891                    *batch_filename_ptr));
2892
2893      /* create batch file to execute command */
2894      batch = fopen (*batch_filename_ptr, "w");
2895      if (!unixy_shell)
2896        fputs ("@echo off\n", batch);
2897      fputs (command_ptr, batch);
2898      fputc ('\n', batch);
2899      fclose (batch);
2900
2901      /* create argv */
2902      new_argv = (char **) xmalloc(3 * sizeof (char *));
2903      if (unixy_shell) {
2904        new_argv[0] = xstrdup (shell);
2905        new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2906      } else {
2907        new_argv[0] = xstrdup (*batch_filename_ptr);
2908        new_argv[1] = NULL;
2909      }
2910      new_argv[2] = NULL;
2911    } else
2912#endif /* WINDOWS32 */
2913    if (unixy_shell)
2914      new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2915                                                  (char *) 0, (char *) 0,
2916                                                  (char **) 0);
2917#ifdef  __MSDOS__
2918    else
2919      {
2920      /* With MSDOS shells, we must construct the command line here
2921         instead of recursively calling ourselves, because we
2922         cannot backslash-escape the special characters (see above).  */
2923      new_argv = (char **) xmalloc (sizeof (char *));
2924      line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2925      new_argv[0] = xmalloc (line_len + 1);
2926      strncpy (new_argv[0],
2927               new_line + shell_len + sizeof (minus_c) - 1, line_len);
2928      new_argv[0][line_len] = '\0';
2929      }
2930#else
2931    else
2932      fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2933            __FILE__, __LINE__);
2934#endif
2935  }
2936#endif  /* ! AMIGA */
2937
2938  return new_argv;
2939}
2940#endif /* !VMS */
2941
2942/* Figure out the argument list necessary to run LINE as a command.  Try to
2943   avoid using a shell.  This routine handles only ' quoting, and " quoting
2944   when no backslash, $ or ` characters are seen in the quotes.  Starting
2945   quotes may be escaped with a backslash.  If any of the characters in
2946   sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2947   is the first word of a line, the shell is used.
2948
2949   If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2950   If *RESTP is NULL, newlines will be ignored.
2951
2952   FILE is the target whose commands these are.  It is used for
2953   variable expansion for $(SHELL) and $(IFS).  */
2954
2955char **
2956construct_command_argv (line, restp, file, batch_filename_ptr)
2957     char *line, **restp;
2958     struct file *file;
2959     char** batch_filename_ptr;
2960{
2961  char *shell, *ifs;
2962  char **argv;
2963
2964#ifdef VMS
2965  char *cptr;
2966  int argc;
2967
2968  argc = 0;
2969  cptr = line;
2970  for (;;)
2971    {
2972      while ((*cptr != 0)
2973             && (isspace ((unsigned char)*cptr)))
2974        cptr++;
2975      if (*cptr == 0)
2976        break;
2977      while ((*cptr != 0)
2978             && (!isspace((unsigned char)*cptr)))
2979        cptr++;
2980      argc++;
2981    }
2982
2983  argv = (char **)malloc (argc * sizeof (char *));
2984  if (argv == 0)
2985    abort ();
2986
2987  cptr = line;
2988  argc = 0;
2989  for (;;)
2990    {
2991      while ((*cptr != 0)
2992             && (isspace ((unsigned char)*cptr)))
2993        cptr++;
2994      if (*cptr == 0)
2995        break;
2996      DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
2997      argv[argc++] = cptr;
2998      while ((*cptr != 0)
2999             && (!isspace((unsigned char)*cptr)))
3000        cptr++;
3001      if (*cptr != 0)
3002        *cptr++ = 0;
3003    }
3004#else
3005  {
3006    /* Turn off --warn-undefined-variables while we expand SHELL and IFS.  */
3007    int save = warn_undefined_variables_flag;
3008    warn_undefined_variables_flag = 0;
3009
3010    shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3011#ifdef WINDOWS32
3012    /*
3013     * Convert to forward slashes so that construct_command_argv_internal()
3014     * is not confused.
3015     */
3016    if (shell) {
3017      char *p = w32ify(shell, 0);
3018      strcpy(shell, p);
3019    }
3020#endif
3021    ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3022
3023    warn_undefined_variables_flag = save;
3024  }
3025
3026  argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3027
3028  free (shell);
3029  free (ifs);
3030#endif /* !VMS */
3031  return argv;
3032}
3033
3034#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3035int
3036dup2 (old, new)
3037     int old, new;
3038{
3039  int fd;
3040
3041  (void) close (new);
3042  fd = dup (old);
3043  if (fd != new)
3044    {
3045      (void) close (fd);
3046      errno = EMFILE;
3047      return -1;
3048    }
3049
3050  return fd;
3051}
3052#endif /* !HAPE_DUP2 && !_AMIGA */
Note: See TracBrowser for help on using the repository browser.