home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / gnu / djgpp / src / make-3.69 / job.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-27  |  40.6 KB  |  1,584 lines

  1. /* Job execution and handling for GNU Make.
  2. Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  3. This file is part of GNU Make.
  4.  
  5. GNU Make is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. GNU Make is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with GNU Make; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "make.h"
  20. #include "commands.h"
  21. #include "job.h"
  22. #include "file.h"
  23. #include "variable.h"
  24.  
  25. /* Default path to search for executables.  */
  26. static char default_path[] = ":/bin:/usr/bin";
  27.  
  28. /* Default shell to use.  */
  29. char default_shell[] = "/bin/sh";
  30.  
  31. #ifdef __MSDOS__
  32. #include <process.h>
  33. static int dos_pid = 123;
  34. static int dos_status = 0;
  35. static char *bname = 0;
  36. static char *bename = 0;
  37. static int is_batch_file = 0;
  38. #define PATH_SEPARATOR_CHAR ';'
  39. #else /* MSDOS */
  40. #define PATH_SEPARATOR_CHAR ':'
  41. #endif /* ?MSDOS */
  42.  
  43. /* If NGROUPS_MAX == 0 then try other methods for finding a real value.  */
  44. #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
  45. #undef NGROUPS_MAX
  46. #endif /* NGROUPS_MAX == 0 */
  47.  
  48. #ifndef    NGROUPS_MAX
  49. #ifdef    POSIX
  50. #define    GET_NGROUPS_MAX    sysconf (_SC_NGROUPS_MAX)
  51. #else    /* Not POSIX.  */
  52. #define    NGROUPS_MAX    NGROUPS
  53. #endif    /* POSIX.  */
  54. #endif
  55.  
  56. #ifdef    HAVE_SYS_WAIT_H
  57. #include <sys/wait.h>
  58. #endif
  59.  
  60. #ifdef    HAVE_WAITPID
  61. #define    WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
  62. #else    /* Don't have waitpid.  */
  63. #ifdef    HAVE_WAIT3
  64. #ifndef    wait3
  65. extern int wait3 ();
  66. #endif
  67. #define    WAIT_NOHANG(status)    wait3 ((status), WNOHANG, (struct rusage *) 0)
  68. #endif    /* Have wait3.  */
  69. #endif    /* Have waitpid.  */
  70.  
  71. #if    !defined (wait) && !defined (POSIX)
  72. extern int wait ();
  73. #endif
  74.  
  75. #ifndef    HAVE_UNION_WAIT
  76.  
  77. #define    WAIT_T int
  78.  
  79. #ifndef    WTERMSIG
  80. #define WTERMSIG(x) ((x) & 0x7f)
  81. #endif
  82. #ifndef    WCOREDUMP
  83. #define WCOREDUMP(x) ((x) & 0x80)
  84. #endif
  85. #ifndef    WEXITSTATUS
  86. #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
  87. #endif
  88. #ifndef    WIFSIGNALED
  89. #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
  90. #endif
  91. #ifndef    WIFEXITED
  92. #define WIFEXITED(x) (WTERMSIG (x) == 0)
  93. #endif
  94.  
  95. #else    /* Have `union wait'.  */
  96.  
  97. #define WAIT_T union wait
  98. #ifndef    WTERMSIG
  99. #define WTERMSIG(x)    ((x).w_termsig)
  100. #endif
  101. #ifndef    WCOREDUMP
  102. #define WCOREDUMP(x)    ((x).w_coredump)
  103. #endif
  104. #ifndef WEXITSTATUS
  105. #define WEXITSTATUS(x)    ((x).w_retcode)
  106. #endif
  107. #ifndef    WIFSIGNALED
  108. #define    WIFSIGNALED(x)    (WTERMSIG(x) != 0)
  109. #endif
  110. #ifndef    WIFEXITED
  111. #define    WIFEXITED(x)    (WTERMSIG(x) == 0)
  112. #endif
  113.  
  114. #endif    /* Don't have `union wait'.  */
  115.  
  116.  
  117. #ifndef    HAVE_UNISTD_H
  118. extern int dup2 ();
  119. extern int execve ();
  120. extern void _exit ();
  121. extern int geteuid (), getegid ();
  122. extern int setgid (), getgid ();
  123. #endif
  124.  
  125. #ifndef    getdtablesize
  126. #ifdef HAVE_GETDTABLESIZE
  127. extern int getdtablesize ();
  128. #else
  129. #include <sys/param.h>
  130. #define getdtablesize() NOFILE
  131. #if !defined (NOFILE) && defined (NOFILES_MAX)
  132. /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE.  */
  133. #define NOFILE    NOFILES_MAX
  134. #endif
  135. #endif
  136. #endif
  137.  
  138. extern int getloadavg ();
  139. extern int start_remote_job_p ();
  140. extern int start_remote_job (), remote_status ();
  141.  
  142. RETSIGTYPE child_handler ();
  143. static void free_child (), start_job_command ();
  144. static int load_too_high (), job_next_command ();
  145.  
  146. /* Chain of all live (or recently deceased) children.  */
  147.  
  148. struct child *children = 0;
  149.  
  150. /* Number of children currently running.  */
  151.  
  152. unsigned int job_slots_used = 0;
  153.  
  154. /* Nonzero if the `good' standard input is in use.  */
  155.  
  156. static int good_stdin_used = 0;
  157.  
  158. /* Chain of children waiting to run until the load average goes down.  */
  159.  
  160. static struct child *waiting_jobs = 0;
  161.  
  162. /* Write an error message describing the exit status given in
  163.    EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
  164.    Append "(ignored)" if IGNORED is nonzero.  */
  165.  
  166. static void
  167. child_error (target_name, exit_code, exit_sig, coredump, ignored)
  168.      char *target_name;
  169.      int exit_code, exit_sig, coredump;
  170.      int ignored;
  171. {
  172.   if (exit_sig == 0)
  173.     error (ignored ? "[%s] Error %d (ignored)" :
  174.        "*** [%s] Error %d",
  175.        target_name, exit_code);
  176.   else
  177.     {
  178.       char *coredump_string = coredump ? " (core dumped)" : "";
  179.       if (exit_sig > 0 && exit_sig < NSIG)
  180.     error ("*** [%s] %s%s",
  181.            target_name, sys_siglist[exit_sig], coredump_string);
  182.       else
  183.     error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
  184.     }
  185. }
  186.  
  187. static unsigned int dead_children = 0;
  188.  
  189. /* Notice that a child died.
  190.    reap_children should be called when convenient.  */
  191. RETSIGTYPE
  192. child_handler (sig)
  193.      int sig;
  194. {
  195.   ++dead_children;
  196.  
  197.   if (debug_flag)
  198.     printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
  199. }
  200.  
  201. extern int shell_function_pid, shell_function_completed;
  202.  
  203. /* Reap dead children, storing the returned status and the new command
  204.    state (`cs_finished') in the `file' member of the `struct child' for the
  205.    dead child, and removing the child from the chain.  If BLOCK nonzero,
  206.    reap at least one child, waiting for it to die if necessary.  If ERR is
  207.    nonzero, print an error message first.  */
  208.  
  209. void
  210. reap_children (block, err)
  211.      int block, err;
  212. {
  213.   WAIT_T status;
  214.  
  215.   while ((children != 0 || shell_function_pid != 0) &&
  216.      (block || dead_children > 0))
  217.     {
  218.       int remote = 0;
  219.       register int pid;
  220.       int exit_code, exit_sig, coredump;
  221.       register struct child *lastc, *c;
  222.       int child_failed;
  223.       int any_remote, any_local;
  224.  
  225.       if (err && dead_children == 0)
  226.     {
  227.       /* We might block for a while, so let the user know why.  */
  228.       fflush (stdout);
  229.       error ("*** Waiting for unfinished jobs....");
  230.     }
  231.  
  232.       /* We have one less dead child to reap.
  233.      The test and decrement are not atomic; if it is compiled into:
  234.          register = dead_children - 1;
  235.         dead_children = register;
  236.      a SIGCHLD could come between the two instructions.
  237.      child_handler increments dead_children.
  238.      The second instruction here would lose that increment.  But the
  239.      only effect of dead_children being wrong is that we might wait
  240.      longer than necessary to reap a child, and lose some parallelism;
  241.      and we might print the "Waiting for unfinished jobs" message above
  242.      when not necessary.  */
  243.  
  244.       if (dead_children != 0)
  245.     --dead_children;
  246.  
  247.       any_remote = 0;
  248.       any_local = shell_function_pid != -1;
  249.       for (c = children; c != 0; c = c->next)
  250.     {
  251.       any_remote |= c->remote;
  252.       any_local |= ! c->remote;
  253.       if (debug_flag)
  254.         printf ("Live child 0x%08lx PID %d%s\n",
  255.             (unsigned long int) c,
  256.             c->pid, c->remote ? " (remote)" : "");
  257.     }
  258.  
  259.       /* First, check for remote children.  */
  260.       if (any_remote)
  261.     pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
  262.       else
  263.     pid = 0;
  264.       if (pid < 0)
  265.     {
  266.     remote_status_lose:
  267. #ifdef    EINTR
  268.       if (errno == EINTR)
  269.         continue;
  270. #endif
  271.       pfatal_with_name ("remote_status");
  272.     }
  273.       else if (pid == 0)
  274.     {
  275. #ifndef __MSDOS__
  276.       /* No remote children.  Check for local children.  */
  277.  
  278.       if (any_local)
  279.         {
  280. #ifdef    WAIT_NOHANG
  281.           if (!block)
  282.         pid = WAIT_NOHANG (&status);
  283.           else
  284. #endif
  285.         pid = wait (&status);
  286.         }
  287.       else
  288.         pid = 0;
  289.  
  290.       if (pid < 0)
  291.         {
  292. #ifdef    EINTR
  293.           if (errno == EINTR)
  294.         continue;
  295. #endif
  296.           pfatal_with_name ("wait");
  297.         }
  298.       else if (pid == 0)
  299.         {
  300.           /* No local children.  */
  301.           if (block && any_remote)
  302.         {
  303.           /* Now try a blocking wait for a remote child.  */
  304.           pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
  305.           if (pid < 0)
  306.             goto remote_status_lose;
  307.           else if (pid == 0)
  308.             /* No remote children either.  Finally give up.  */
  309.             break;
  310.           else
  311.             /* We got a remote child.  */
  312.             remote = 1;
  313.         }
  314.           else
  315.         break;
  316.         }
  317.       else
  318.         {
  319.           /* Chop the status word up.  */
  320.           exit_code = WEXITSTATUS (status);
  321.           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
  322.           coredump = WCOREDUMP (status);
  323.         }
  324. #else /* MSDOS */
  325.       pid = dos_pid-1;
  326.       status = dos_status;
  327.       exit_code = dos_status;
  328.       exit_sig = 0;
  329.       coredump = 0;
  330. #endif /* ?MSDOS */
  331.     }
  332.       else
  333.     /* We got a remote child.  */
  334.     remote = 1;
  335.  
  336.       /* Check if this is the child of the `shell' function.  */
  337.       if (!remote && pid == shell_function_pid)
  338.     {
  339.       /* It is.  Leave an indicator for the `shell' function.  */
  340.       if (exit_sig == 0 && exit_code == 127)
  341.         shell_function_completed = -1;
  342.       else
  343.         shell_function_completed = 1;
  344.       break;
  345.     }
  346.  
  347.       child_failed = exit_sig != 0 || exit_code != 0;
  348.  
  349.       /* Search for a child matching the deceased one.  */
  350.       lastc = 0;
  351.       for (c = children; c != 0; lastc = c, c = c->next)
  352.     if (c->remote == remote && c->pid == pid)
  353.       break;
  354.  
  355.       if (c == 0)
  356.     {
  357.       /* An unknown child died.  */
  358.       char buf[100];
  359.       sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
  360.       if (child_failed)
  361.         child_error (buf, exit_code, exit_sig, coredump,
  362.              ignore_errors_flag);
  363.       else
  364.         error ("%s finished.", buf);
  365.     }
  366.       else
  367.     {
  368.       if (debug_flag)
  369.         printf ("Reaping %s child 0x%08lx PID %d%s\n",
  370.             child_failed ? "losing" : "winning",
  371.             (unsigned long int) c,
  372.             c->pid, c->remote ? " (remote)" : "");
  373.  
  374.       /* If this child had the good stdin, say it is now free.  */
  375.       if (c->good_stdin)
  376.         good_stdin_used = 0;
  377.  
  378.       if (child_failed && !c->noerror && !ignore_errors_flag)
  379.         {
  380.           /* The commands failed.  Write an error message,
  381.          delete non-precious targets, and abort.  */
  382.           child_error (c->file->name, exit_code, exit_sig, coredump, 0);
  383.           c->file->update_status = 1;
  384.           if (exit_sig != 0)
  385.         delete_child_targets (c);
  386.         }
  387.       else
  388.         {
  389.           if (child_failed)
  390.         {
  391.           /* The commands failed, but we don't care.  */
  392.           child_error (c->file->name,
  393.                    exit_code, exit_sig, coredump, 1);
  394.           child_failed = 0;
  395.         }
  396.  
  397.           /* If there are more commands to run, try to start them.  */
  398.           if (job_next_command (c))
  399.         {
  400.           if (handling_fatal_signal)
  401.             {
  402.               /* Never start new commands while we are dying.
  403.              Since there are more commands that wanted to be run,
  404.              the target was not completely remade.  So we treat
  405.              this as if a command had failed.  */
  406.               c->file->command_state = cs_finished;
  407.               c->file->update_status = 1;
  408.             }
  409.           else
  410.             {
  411.               /* Check again whether to start remotely.
  412.              Whether or not we want to changes over time.
  413.              Also, start_remote_job may need state set up
  414.              by start_remote_job_p.  */
  415.               c->remote = start_remote_job_p ();
  416.               start_job_command (c);
  417.             }
  418.         }
  419.  
  420.           switch (c->file->command_state)
  421.         {
  422.         case cs_running:
  423.           /* Successfully started.  Loop to reap more children.  */
  424.           continue;
  425.  
  426.         case cs_finished:
  427.           if (c->file->update_status != 0)
  428.             /* We failed to start the commands.  */
  429.             delete_child_targets (c);
  430.           break;
  431.  
  432.         default:
  433.           error ("internal error: `%s' has bogus command_state \
  434. %d in reap_children",
  435.              c->file->name, (int) c->file->command_state);
  436.           abort ();
  437.           break;
  438.         }
  439.         }
  440.  
  441.       if (! handling_fatal_signal)
  442.         /* Notice if the target of the commands has been changed.  */
  443.         notice_finished_file (c->file);
  444.  
  445.       if (debug_flag)
  446.         printf ("Removing child 0x%08lx PID %d%s from chain.\n",
  447.             (unsigned long int) c,
  448.             c->pid, c->remote ? " (remote)" : "");
  449.  
  450.       /* Remove the child from the chain and free it.  */
  451.       if (lastc == 0)
  452.         children = c->next;
  453.       else
  454.         lastc->next = c->next;
  455.       if (! handling_fatal_signal) /* Avoid nonreentrancy.  */
  456.         free_child (c);
  457.  
  458.       /* There is now another slot open.  */
  459.       --job_slots_used;
  460.  
  461.       /* If the job failed, and the -k flag was not given, die,
  462.          unless we are already in the process of dying.  */
  463.       if (!err && child_failed && !keep_going_flag)
  464.         die (1);
  465.     }
  466.  
  467.       /* Only block for one child.  */
  468.       block = 0;
  469.     }
  470. }
  471.  
  472. /* Free the storage allocated for CHILD.  */
  473.  
  474. static void
  475. free_child (child)
  476.      register struct child *child;
  477. {
  478.   if (child->command_lines != 0)
  479.     {
  480.       register unsigned int i;
  481.       for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
  482.     free (child->command_lines[i]);
  483.       free ((char *) child->command_lines);
  484.     }
  485.  
  486.   if (child->environment != 0)
  487.     {
  488.       register char **ep = child->environment;
  489.       while (*ep != 0)
  490.     free (*ep++);
  491.       free ((char *) child->environment);
  492.     }
  493.  
  494.   free ((char *) child);
  495. }
  496.  
  497. #ifdef __MSDOS__
  498. void unblock_sigs(){}
  499. #else /* MSDOS */
  500. #ifdef    POSIX
  501. extern sigset_t fatal_signal_set;
  502.  
  503. void
  504. unblock_sigs ()
  505. {
  506.   sigset_t empty;
  507.   sigemptyset (&empty);
  508.   sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
  509. }
  510. #endif
  511. #endif /* ?MSDOS */
  512.  
  513. /* Start a job to run the commands specified in CHILD.
  514.    CHILD is updated to reflect the commands and ID of the child process.  */
  515.  
  516. static void
  517. start_job_command (child)
  518.      register struct child *child;
  519. {
  520.   static int bad_stdin = -1;
  521.   register char *p;
  522.   int flags = child->file->cmds->lines_flags[child->command_line - 1];
  523.   char **argv;
  524.  
  525.   p = child->command_ptr;
  526.   child->noerror = flags & COMMANDS_NOERROR;
  527.   while (*p != '\0')
  528.     {
  529.       if (*p == '@')
  530.     flags |= COMMANDS_SILENT;
  531.       else if (*p == '+')
  532.     flags |= COMMANDS_RECURSE;
  533.       else if (*p == '-')
  534.     child->noerror = 1;
  535.       else if (!isblank (*p) && *p != '+')
  536.     break;
  537.       ++p;
  538.     }
  539.  
  540.   /* If -q was given, just say that updating `failed'.  */
  541.   if (question_flag && !(flags & COMMANDS_RECURSE))
  542.     goto error;
  543.  
  544.   /* There may be some preceding whitespace left if there
  545.      was nothing but a backslash on the first line.  */
  546.   p = next_token (p);
  547.   
  548.   /* Figure out an argument list from this command line.  */
  549.   
  550.   {
  551.     char *end;
  552.     argv = construct_command_argv (p, &end, child->file);
  553.     if (end == NULL)
  554.       child->command_ptr = NULL;
  555.     else
  556.       {
  557.     *end++ = '\0';
  558.     child->command_ptr = end;
  559.       }
  560.   }
  561.  
  562.   if (touch_flag && !(flags & COMMANDS_RECURSE))
  563.     {
  564.       /* Go on to the next command.  It might be the recursive one.
  565.      We construct ARGV only to find the end of the command line.  */
  566.       free (argv[0]);
  567.       free ((char *) argv);
  568.       argv = 0;
  569.     }
  570.  
  571.   if (argv == 0)
  572.     {
  573.       /* This line has no commands.  Go to the next.  */
  574.       if (job_next_command (child))
  575.     start_job_command (child);
  576.       return;
  577.     }
  578.  
  579.   /* Print out the command.  */
  580.  
  581.   if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
  582.     puts (p);
  583.  
  584.   /* Tell update_goal_chain that a command has been started on behalf of
  585.      this target.  It is important that this happens here and not in
  586.      reap_children (where we used to do it), because reap_children might be
  587.      reaping children from a different target.  We want this increment to
  588.      guaranteedly indicate that a command was started for the dependency
  589.      chain (i.e., update_file recursion chain) we are processing.  */
  590.  
  591.   ++commands_started;
  592.  
  593.   /* If -n was given, recurse to get the next line in the sequence.  */
  594.  
  595.   if (just_print_flag && !(flags & COMMANDS_RECURSE))
  596.     {
  597.       free (argv[0]);
  598.       free ((char *) argv);
  599.       if (job_next_command (child))
  600.     start_job_command (child);
  601.       return;
  602.     }
  603.  
  604.   /* Flush the output streams so they won't have things written twice.  */
  605.  
  606.   fflush (stdout);
  607.   fflush (stderr);
  608.   
  609.   /* Set up a bad standard input that reads from a broken pipe.  */
  610.  
  611.   if (bad_stdin == -1)
  612.     {
  613.       /* Make a file descriptor that is the read end of a broken pipe.
  614.      This will be used for some children's standard inputs.  */
  615.       int pd[2];
  616.       if (pipe (pd) == 0)
  617.     {
  618.       /* Close the write side.  */
  619.       (void) close (pd[1]);
  620.       /* Save the read side.  */
  621.       bad_stdin = pd[0];
  622.     }
  623.     }
  624.  
  625.   /* Decide whether to give this child the `good' standard input
  626.      (one that points to the terminal or whatever), or the `bad' one
  627.      that points to the read side of a broken pipe.  */
  628.  
  629.   child->good_stdin = !good_stdin_used;
  630.   if (child->good_stdin)
  631.     good_stdin_used = 1;
  632.  
  633.   child->deleted = 0;
  634.  
  635.   /* Set up the environment for the child.  */
  636.   if (child->environment == 0)
  637.     child->environment = target_environment (child->file);
  638.  
  639. #ifndef __MSDOS__
  640.  
  641.   /* start_waiting_job has set CHILD->remote if we can start a remote job.  */
  642.   if (child->remote)
  643.     {
  644.       int is_remote, id, used_stdin;
  645.       if (start_remote_job (argv, child->environment,
  646.                 child->good_stdin ? 0 : bad_stdin,
  647.                 &is_remote, &id, &used_stdin))
  648.     goto error;
  649.       else
  650.     {
  651.       if (child->good_stdin && !used_stdin)
  652.         {
  653.           child->good_stdin = 0;
  654.           good_stdin_used = 0;
  655.         }
  656.       child->remote = is_remote;
  657.       child->pid = id;
  658.     }
  659.     }
  660.   else
  661.     {
  662.       /* Fork the child process.  */
  663.  
  664. #ifdef     POSIX
  665.       (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
  666. #else
  667. #ifdef    HAVE_SIGSETMASK
  668.       (void) sigblock (fatal_signal_mask);
  669. #endif
  670. #endif
  671.  
  672.       child->remote = 0;
  673.       child->pid = vfork ();
  674.       if (child->pid == 0)
  675.     {
  676.       /* We are the child side.  */
  677.       unblock_sigs ();
  678.       child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
  679.                  argv, child->environment);
  680.     }
  681.       else if (child->pid < 0)
  682.     {
  683.       /* Fork failed!  */
  684.       unblock_sigs ();
  685.       perror_with_name ("vfork", "");
  686.       goto error;
  687.     }
  688.     }
  689. #else
  690.   dos_status = spawnvpe(P_WAIT, argv[0], argv, child->environment);
  691.   dead_children++;
  692.   child->pid = dos_pid++;
  693.   if (is_batch_file)
  694.   {
  695.     is_batch_file = 0;
  696.     remove(bname); /* ignore errors */
  697.     if (access(bename,0))
  698.       dos_status = 1;
  699.     else
  700.       dos_status = 0;
  701.     remove(bename);
  702.   }
  703. #endif
  704.   /* We are the parent side.  Set the state to
  705.      say the commands are running and return.  */
  706.  
  707.   child->file->command_state = cs_running;
  708.  
  709.   /* Free the storage used by the child's argument list.  */
  710.  
  711.   free (argv[0]);
  712.   free ((char *) argv);
  713.  
  714.   return;
  715.  
  716.  error:;
  717.   child->file->update_status = 1;
  718.   child->file->command_state = cs_finished;
  719. }
  720.  
  721. /* Try to start a child running.
  722.    Returns nonzero if the child was started (and maybe finished), or zero if
  723.    the load was too high and the child was put on the `waiting_jobs' chain.  */
  724.  
  725. static int
  726. start_waiting_job (c)
  727.      struct child *c;
  728. {
  729.   /* If we can start a job remotely, we always want to, and don't care about
  730.      the local load average.  We record that the job should be started
  731.      remotely in C->remote for start_job_command to test.  */
  732.  
  733.   c->remote = start_remote_job_p ();
  734.  
  735.   /* If this job is to be started locally, and we are already running
  736.      some jobs, make this one wait if the load average is too high.  */
  737.   if (!c->remote && job_slots_used > 0 && load_too_high ())
  738.     {
  739.       /* Put this child on the chain of children waiting
  740.      for the load average to go down.  */
  741.       c->file->command_state = cs_running;
  742.       c->next = waiting_jobs;
  743.       waiting_jobs = c;
  744.       return 0;
  745.     }
  746.  
  747.   /* Start the first command; reap_children will run later command lines.  */
  748.   start_job_command (c);
  749.  
  750.   switch (c->file->command_state)
  751.     {
  752.     case cs_running:
  753.       c->next = children;
  754.       if (debug_flag)
  755.     printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
  756.         (unsigned long int) c,
  757.         c->pid, c->remote ? " (remote)" : "");
  758.       children = c;
  759.       /* One more job slot is in use.  */
  760.       ++job_slots_used;
  761.       unblock_sigs ();
  762.       break;
  763.  
  764.     case cs_finished:
  765.       notice_finished_file (c->file);
  766.       free_child (c);
  767.       break;
  768.  
  769.     default:
  770.       error ("internal error: `%s' command_state == %d in new_job",
  771.          c->file->name, (int) c->file->command_state);
  772.       abort ();
  773.       break;
  774.     }
  775.  
  776.   return 1;
  777. }
  778.  
  779. /* Create a `struct child' for FILE and start its commands running.  */
  780.  
  781. void
  782. new_job (file)
  783.      register struct file *file;
  784. {
  785.   register struct commands *cmds = file->cmds;
  786.   register struct child *c;
  787.   char **lines;
  788.   register unsigned int i;
  789.  
  790.   /* Let any previously decided-upon jobs that are waiting
  791.      for the load to go down start before this new one.  */
  792.   start_waiting_jobs ();
  793.  
  794.   /* Reap any children that might have finished recently.  */
  795.   reap_children (0, 0);
  796.  
  797.   /* Chop the commands up into lines if they aren't already.  */
  798.   chop_commands (cmds);
  799.  
  800.   if (job_slots != 0)
  801.     /* Wait for a job slot to be freed up.  */
  802.     while (job_slots_used == job_slots)
  803.       reap_children (1, 0);
  804.  
  805.   /* Expand the command lines and store the results in LINES.  */
  806.   lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
  807.   for (i = 0; i < cmds->ncommand_lines; ++i)
  808.     {
  809.       /* Collapse backslash-newline combinations that are inside variable
  810.      or function references.  These are left alone by the parser so
  811.      that they will appear in the echoing of commands (where they look
  812.      nice); and collapsed by construct_command_argv when it tokenizes.
  813.      But letting them survive inside function invocations loses because
  814.      we don't want the functions to see them as part of the text.  */
  815.  
  816.       char *in, *out, *ref;
  817.  
  818.       /* IN points to where in the line we are scanning.
  819.      OUT points to where in the line we are writing.
  820.      When we collapse a backslash-newline combination,
  821.      IN gets ahead out OUT.  */
  822.  
  823.       in = out = cmds->command_lines[i];
  824.       while ((ref = index (in, '$')) != 0)
  825.     {
  826.       ++ref;        /* Move past the $.  */
  827.  
  828.       if (out != in)
  829.         /* Copy the text between the end of the last chunk
  830.            we processed (where IN points) and the new chunk
  831.            we are about to process (where REF points).  */
  832.         bcopy (in, out, ref - in);
  833.  
  834.       /* Move both pointers past the boring stuff.  */
  835.       out += ref - in;
  836.       in = ref;
  837.  
  838.       if (*ref == '(' || *ref == '{')
  839.         {
  840.           char openparen = *ref;
  841.           char closeparen = openparen == '(' ? ')' : '}';
  842.           int count;
  843.           char *p;
  844.  
  845.           *out++ = *in++;    /* Copy OPENPAREN.  */
  846.           /* IN now points past the opening paren or brace.
  847.          Count parens or braces until it is matched.  */
  848.           count = 0;
  849.           while (*in != '\0')
  850.         {
  851.           if (*in == closeparen && --count < 0)
  852.             break;
  853.           else if (*in == '\\' && in[1] == '\n')
  854.             {
  855.               /* We have found a backslash-newline inside a
  856.              variable or function reference.  Eat it and
  857.              any following whitespace.  */
  858.  
  859.               int quoted = 0;
  860.               for (p = in - 1; p > ref && *p == '\\'; --p)
  861.             quoted = !quoted;
  862.  
  863.               if (quoted)
  864.             /* There were two or more backslashes, so this is
  865.                not really a continuation line.  We don't collapse
  866.                the quoting backslashes here as is done in
  867.                collapse_continuations, because the line will
  868.                be collapsed again after expansion.  */
  869.             *out++ = *in++;
  870.               else
  871.             {
  872.               /* Skip the backslash, newline and
  873.                  any following whitespace.  */
  874.               in = next_token (in + 2);
  875.  
  876.               /* Discard any preceding whitespace that has
  877.                  already been written to the output.  */
  878.               while (out > ref && isblank (out[-1]))
  879.                 --out;
  880.  
  881.               /* Replace it all with a single space.  */
  882.               *out++ = ' ';
  883.             }
  884.             }
  885.           else
  886.             {
  887.               if (*in == openparen)
  888.             ++count;
  889.  
  890.               *out++ = *in++;
  891.             }
  892.         }
  893.         }
  894.     }
  895.  
  896.       /* There are no more references in this line to worry about.
  897.      Copy the remaining uninteresting text to the output.  */
  898.       if (out != in)
  899.     strcpy (out, in);
  900.  
  901.       /* Finally, expand the line.  */
  902.       lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
  903.                              file);
  904.     }
  905.  
  906.   /* Start the command sequence, record it in a new
  907.      `struct child', and add that to the chain.  */
  908.  
  909.   c = (struct child *) xmalloc (sizeof (struct child));
  910.   c->file = file;
  911.   c->command_lines = lines;
  912.   c->command_line = 0;
  913.   c->command_ptr = 0;
  914.   c->environment = 0;
  915.  
  916.   /* Fetch the first command line to be run.  */
  917.   if (! job_next_command (c))
  918.     /* There were no commands!  */
  919.     free_child (c);
  920.   else
  921.     {
  922.       /* The job is now primed.  Start it running.  */
  923.       start_waiting_job (c);
  924.  
  925.       if (job_slots == 1)
  926.     /* Since there is only one job slot, make things run linearly.
  927.        Wait for the child to die, setting the state to `cs_finished'.  */
  928.     while (file->command_state == cs_running)
  929.       reap_children (1, 0);
  930.     }
  931. }
  932.  
  933. /* Move CHILD's pointers to the next command for it to execute.
  934.    Returns nonzero if there is another command.  */
  935.  
  936. static int
  937. job_next_command (child)
  938.      struct child *child;
  939. {
  940.   if (child->command_ptr == 0 || *child->command_ptr == '\0')
  941.     {
  942.       /* There are no more lines in the expansion of this line.  */
  943.       if (child->command_line == child->file->cmds->ncommand_lines)
  944.     {
  945.       /* There are no more lines to be expanded.  */
  946.       child->command_ptr = 0;
  947.       child->file->command_state = cs_finished;
  948.       child->file->update_status = 0;
  949.       return 0;
  950.     }
  951.       else
  952.     /* Get the next line to run.  */
  953.     child->command_ptr = child->command_lines[child->command_line++];
  954.     }
  955.   return 1;
  956. }
  957.  
  958. static int
  959. load_too_high ()
  960. {
  961. #ifdef __MSDOS__
  962.   return 1;
  963. #else
  964.   extern int getloadavg ();
  965.   double load;
  966.  
  967.   if (max_load_average < 0)
  968.     return 0;
  969.  
  970.   make_access ();
  971.   if (getloadavg (&load, 1) != 1)
  972.     {
  973.       static int lossage = -1;
  974.       /* Complain only once for the same error.  */
  975.       if (lossage == -1 || errno != lossage)
  976.     {
  977.       if (errno == 0)
  978.         /* An errno value of zero means getloadavg is just unsupported.  */
  979.         error ("cannot enforce load limits on this operating system");
  980.       else
  981.         perror_with_name ("cannot enforce load limit: ", "getloadavg");
  982.     }
  983.       lossage = errno;
  984.       load = 0;
  985.     }
  986.   user_access ();
  987.  
  988.   return load >= max_load_average;
  989. #endif /* ?__MSDOS__ */
  990. }
  991.  
  992. /* Start jobs that are waiting for the load to be lower.  */
  993.  
  994. void
  995. start_waiting_jobs ()
  996. {
  997.   struct child *job;
  998.  
  999.   if (waiting_jobs == 0)
  1000.     return;
  1001.  
  1002.   do
  1003.     {
  1004.       /* Check for recently deceased descendants.  */
  1005.       reap_children (0, 0);
  1006.  
  1007.       /* Take a job off the waiting list.  */
  1008.       job = waiting_jobs;
  1009.       waiting_jobs = job->next;
  1010.  
  1011.       /* Try to start that job.  We break out of the loop as soon
  1012.      as start_waiting_job puts one back on the waiting list.  */
  1013.     } while (start_waiting_job (job) && waiting_jobs != 0);
  1014. }
  1015.  
  1016. /* Replace the current process with one executing the command in ARGV.
  1017.    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
  1018.    the environment of the new program.  This function does not return.  */
  1019.  
  1020. void
  1021. child_execute_job (stdin_fd, stdout_fd, argv, envp)
  1022.      int stdin_fd, stdout_fd;
  1023.      char **argv, **envp;
  1024. {
  1025.   if (stdin_fd != 0)
  1026.     (void) dup2 (stdin_fd, 0);
  1027.   if (stdout_fd != 1)
  1028.     (void) dup2 (stdout_fd, 1);
  1029.  
  1030.   /* Free up file descriptors.  */
  1031.   {
  1032.     register int d;
  1033.     int max = getdtablesize ();
  1034.     for (d = 3; d < max; ++d)
  1035.       (void) close (d);
  1036.   }
  1037.  
  1038.   /* Run the command.  */
  1039.   exec_command (argv, envp);
  1040. }
  1041.  
  1042. /* Search PATH for FILE.
  1043.    If successful, store the full pathname in PROGRAM and return 1.
  1044.    If not sucessful, return zero.  */
  1045.  
  1046. static int
  1047. search_path (file, path, program)
  1048.      char *file, *path, *program;
  1049. {
  1050.   if (path == 0 || path[0] == '\0')
  1051.     path = default_path;
  1052.  
  1053. #ifdef __MSDOS__
  1054.   if (strpbrk (file, "/\\:") != 0)
  1055. #else
  1056.   if (index (file, '/') != 0)
  1057. #endif
  1058.     {
  1059.       strcpy (program, file);
  1060.       return 1;
  1061.     }
  1062.   else
  1063.     {
  1064.       unsigned int len;
  1065.  
  1066. #ifdef    HAVE_GETGROUPS
  1067. #ifndef    HAVE_UNISTD_H
  1068.       extern int getgroups ();
  1069. #endif
  1070.       static int ngroups = -1;
  1071. #ifdef    NGROUPS_MAX
  1072.       static GETGROUPS_T groups[NGROUPS_MAX];
  1073. #define    ngroups_max    NGROUPS_MAX
  1074. #else
  1075.       static GETGROUPS_T *groups = 0;
  1076.       static int ngroups_max;
  1077.       if (groups == 0)
  1078.     {
  1079.       ngroups_max = GET_NGROUPS_MAX;
  1080.       groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
  1081.     }
  1082. #endif
  1083.       if (groups != 0 && ngroups == -1)
  1084.     ngroups = getgroups (ngroups_max, groups);
  1085. #endif    /* Have getgroups.  */
  1086.  
  1087.       len = strlen (file) + 1;
  1088.       do
  1089.     {
  1090.       struct stat st;
  1091.       int perm;
  1092.       char *p;
  1093.  
  1094.       p = index (path, PATH_SEPARATOR_CHAR);
  1095.       if (p == 0)
  1096.         p = path + strlen (path);
  1097.  
  1098.       if (p == path)
  1099.         bcopy (file, program, len);
  1100.       else
  1101.         {
  1102.           bcopy (path, program, p - path);
  1103.           program[p - path] = '/';
  1104.           bcopy (file, program + (p - path) + 1, len);
  1105.         }
  1106.  
  1107.       if (stat (program, &st) == 0
  1108.           && S_ISREG (st.st_mode))
  1109.         {
  1110.           if (st.st_uid == geteuid ())
  1111.         perm = (st.st_mode & 0100);
  1112.           else if (st.st_gid == getegid ())
  1113.         perm = (st.st_mode & 0010);
  1114.           else
  1115.         {
  1116. #ifdef    HAVE_GETGROUPS
  1117.           register int i;
  1118.           for (i = 0; i < ngroups; ++i)
  1119.             if (groups[i] == st.st_gid)
  1120.               break;
  1121.           if (i < ngroups)
  1122.             perm = (st.st_mode & 0010);
  1123.           else
  1124. #endif    /* Have getgroups.  */
  1125.             perm = (st.st_mode & 0001);
  1126.         }
  1127.  
  1128.           if (perm != 0)
  1129.         return 1;
  1130.         }
  1131.  
  1132.       path = p + 1;
  1133.     } while (*path != '\0');
  1134.     }
  1135.  
  1136.   return 0;
  1137. }
  1138.  
  1139. /* Replace the current process with one running the command in ARGV,
  1140.    with environment ENVP.  This function does not return.  */
  1141.  
  1142. void
  1143. exec_command (argv, envp)
  1144.      char **argv, **envp;
  1145. {
  1146.   char *shell, *path;
  1147.   PATH_VAR (program);
  1148.   register char **ep;
  1149.  
  1150.   shell = path = 0;
  1151.   for (ep = envp; *ep != 0; ++ep)
  1152.     {
  1153.       if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
  1154.     shell = &(*ep)[6];
  1155.       else if (path == 0 && !strncmp(*ep, "PATH=", 5))
  1156.     path = &(*ep)[5];
  1157.       else if (path != 0 && shell != 0)
  1158.     break;
  1159.     }
  1160.  
  1161.   /* Be the user, permanently.  */
  1162.   child_access ();
  1163.  
  1164.   if (!search_path (argv[0], path, program))
  1165.     error ("%s: Command not found", argv[0]);
  1166.   else
  1167.     {
  1168.       /* Run the program.  */
  1169.       execve (program, argv, envp);
  1170.  
  1171.       if (errno == ENOEXEC)
  1172.     {
  1173.       PATH_VAR (shell_program);
  1174.       char *shell_path;
  1175.       if (shell == 0)
  1176.         shell_path = default_shell;
  1177.       else
  1178.         {
  1179.           if (search_path (shell, path, shell_program))
  1180.         shell_path = shell_program;
  1181.           else
  1182.         {
  1183.           shell_path = 0;
  1184.           error ("%s: Shell program not found", shell);
  1185.         }
  1186.         }
  1187.  
  1188.       if (shell_path != 0)
  1189.         {
  1190.           char **new_argv;
  1191.           int argc;
  1192.  
  1193.           argc = 1;
  1194.           while (argv[argc] != 0)
  1195.         ++argc;
  1196.  
  1197.           new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
  1198.           new_argv[0] = shell_path;
  1199.           new_argv[1] = program;
  1200.           while (argc > 0)
  1201.         {
  1202.           new_argv[1 + argc] = argv[argc];
  1203.           --argc;
  1204.         }
  1205.  
  1206.           execve (shell_path, new_argv, envp);
  1207.           perror_with_name ("execve: ", shell_path);
  1208.         }
  1209.     }
  1210.       else
  1211.     perror_with_name ("execve: ", program);
  1212.     }
  1213.  
  1214.   _exit (127);
  1215. }
  1216.  
  1217. /* Figure out the argument list necessary to run LINE as a command.
  1218.    Try to avoid using a shell.  This routine handles only ' quoting.
  1219.    Starting quotes may be escaped with a backslash.  If any of the
  1220.    characters in sh_chars[] is seen, or any of the builtin commands
  1221.    listed in sh_cmds[] is the first word of a line, the shell is used.
  1222.  
  1223.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1224.    If *RESTP is NULL, newlines will be ignored.
  1225.  
  1226.    SHELL is the shell to use, or nil to use the default shell.
  1227.    IFS is the value of $IFS, or nil (meaning the default).  */
  1228.  
  1229. static char **
  1230. construct_command_argv_internal (line, restp, shell, ifs)
  1231.      char *line, **restp;
  1232.      char *shell, *ifs;
  1233. {
  1234. #ifdef __MSDOS__
  1235.   static char sh_chars[] = "\"|<>";
  1236.   static char *sh_cmds[] = {
  1237.     "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty",
  1238.     "date", "del", "dir", "echo", "erase", "exit", "for"
  1239.     "goto", "if", "if", "md", "mkdir", "path", "pause", "prompt",
  1240.     "rem", "ren", "rename", "set", "shift", "time", "type"
  1241.     "ver", "verify", "vol", ":", 0};
  1242. #else
  1243.   static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
  1244.   static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
  1245.                  "logout", "set", "umask", "wait", "while", "for",
  1246.                  "case", "if", ":", ".", "break", "continue",
  1247.                  "export", "read", "readonly", "shift", "times",
  1248.                  "trap", "switch", 0 };
  1249. #endif
  1250.   register int i;
  1251.   register char *p;
  1252.   register char *ap;
  1253.   char *end;
  1254.   int instring, word_has_equals, seen_nonequals;
  1255.   char **new_argv = 0;
  1256.  
  1257.   if (restp != NULL)
  1258.     *restp = NULL;
  1259.  
  1260.   /* Make sure not to bother processing an empty line.  */
  1261.   while (isblank (*line))
  1262.     ++line;
  1263.   if (*line == '\0')
  1264.     return 0;
  1265.  
  1266.   /* See if it is safe to parse commands internally.  */
  1267.   if (shell == 0)
  1268.     shell = default_shell;
  1269.   else if (strcmp (shell, default_shell))
  1270.     goto slow;
  1271.  
  1272.   if (ifs != 0)
  1273.     for (ap = ifs; *ap != '\0'; ++ap)
  1274.       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
  1275.     goto slow;
  1276.  
  1277.   i = strlen (line) + 1;
  1278.  
  1279.   /* More than 1 arg per character is impossible.  */
  1280.   new_argv = (char **) xmalloc (i * sizeof (char *));
  1281.  
  1282.   /* All the args can fit in a buffer as big as LINE is.   */
  1283.   ap = new_argv[0] = (char *) xmalloc (i);
  1284.   end = ap + i;
  1285.  
  1286.   /* I is how many complete arguments have been found.  */
  1287.   i = 0;
  1288.   instring = word_has_equals = seen_nonequals = 0;
  1289.   for (p = line; *p != '\0'; ++p)
  1290.     {
  1291.       if (ap > end)
  1292.     abort ();
  1293.  
  1294.       if (instring)
  1295.     {
  1296.       /* Inside a string, just copy any char except a closing quote.  */
  1297.       if (*p == '\'')
  1298.         instring = 0;
  1299.       else
  1300.         *ap++ = *p;
  1301.     }
  1302.       else if (index (sh_chars, *p) != 0)
  1303.     /* Not inside a string, but it's a special char.  */
  1304.     goto slow;
  1305.       else
  1306.     /* Not a special char.  */
  1307.     switch (*p)
  1308.       {
  1309.       case '=':
  1310.         /* Equals is a special character in leading words before the
  1311.            first word with no equals sign in it.  This is not the case
  1312.            with sh -k, but we never get here when using nonstandard
  1313.            shell flags.  */
  1314.         if (! seen_nonequals)
  1315.           goto slow;
  1316.         word_has_equals = 1;
  1317.         *ap++ = '=';
  1318.         break;
  1319.  
  1320.       case '\\':
  1321.         /* Backslash-newline combinations are eaten.  */
  1322.         if (p[1] == '\n')
  1323.           {
  1324.         /* Eat the backslash, the newline, and following whitespace,
  1325.            replacing it all with a single space.  */
  1326.         p += 2;
  1327.  
  1328.         /* If there is a tab after a backslash-newline,
  1329.            remove it from the source line which will be echoed,
  1330.            since it was most likely used to line
  1331.            up the continued line with the previous one.  */
  1332.         if (*p == '\t')
  1333.           strcpy (p, p + 1);
  1334.  
  1335.         if (ap != new_argv[i])
  1336.           /* Treat this as a space, ending the arg.
  1337.              But if it's at the beginning of the arg, it should
  1338.              just get eaten, rather than becoming an empty arg. */
  1339.           goto end_of_arg;
  1340.         else
  1341.           p = next_token (p) - 1;
  1342.           }
  1343.         else if (p[1] != '\0')
  1344.           /* Copy and skip the following char.  */
  1345.           *ap++ = *++p;
  1346.         break;
  1347.  
  1348.       case '\'':
  1349.         instring = 1;
  1350.         break;
  1351.  
  1352.       case '\n':
  1353.         if (restp != NULL)
  1354.           {
  1355.         /* End of the command line.  */
  1356.         *restp = p;
  1357.         goto end_of_line;
  1358.           }
  1359.         else
  1360.           /* Newlines are not special.  */
  1361.           *ap++ = '\n';
  1362.         break;
  1363.  
  1364.       case ' ':
  1365.       case '\t':
  1366.       end_of_arg:
  1367.         /* We have the end of an argument.
  1368.            Terminate the text of the argument.  */
  1369.         *ap++ = '\0';
  1370.         new_argv[++i] = ap;
  1371.  
  1372.         /* Update SEEN_NONEQUALS, which tells us if every word
  1373.            heretofore has contained an `='.  */
  1374.         seen_nonequals |= ! word_has_equals;
  1375.         if (word_has_equals && ! seen_nonequals)
  1376.           /* An `=' in a word before the first
  1377.          word without one is magical.  */
  1378.           goto slow;
  1379.         word_has_equals = 0; /* Prepare for the next word.  */
  1380.  
  1381.         /* If this argument is the command name,
  1382.            see if it is a built-in shell command.
  1383.            If so, have the shell handle it.  */
  1384.         if (i == 1)
  1385.           {
  1386.         register int j;
  1387.         for (j = 0; sh_cmds[j] != 0; ++j)
  1388.           if (streq (sh_cmds[j], new_argv[0]))
  1389.             goto slow;
  1390.           }
  1391.  
  1392.         /* Ignore multiple whitespace chars.  */
  1393.         p = next_token (p);
  1394.         /* Next iteration should examine the first nonwhite char.  */
  1395.         --p;
  1396.         break;
  1397.  
  1398.       default:
  1399.         *ap++ = *p;
  1400.         break;
  1401.       }
  1402.     }
  1403.  end_of_line:
  1404.  
  1405.   if (instring)
  1406.     /* Let the shell deal with an unterminated quote.  */
  1407.     goto slow;
  1408.  
  1409.   /* Terminate the last argument and the argument list.  */
  1410.  
  1411.   *ap = '\0';
  1412.   if (new_argv[i][0] != '\0')
  1413.     ++i;
  1414.   new_argv[i] = 0;
  1415.  
  1416.   if (i == 1)
  1417.     {
  1418.       register int j;
  1419.       for (j = 0; sh_cmds[j] != 0; ++j)
  1420.     if (streq (sh_cmds[j], new_argv[0]))
  1421.       goto slow;
  1422.     }
  1423.  
  1424.   if (new_argv[0] == 0)
  1425.     /* Line was empty.  */
  1426.     return 0;
  1427.   else
  1428.     return new_argv;
  1429.  
  1430.  slow:;
  1431.   /* We must use the shell.  */
  1432.  
  1433.   if (new_argv != 0)
  1434.     {
  1435.       /* Free the old argument list we were working on.  */
  1436.       free (new_argv[0]);
  1437.       free (new_argv);
  1438.     }
  1439. #ifdef __MSDOS__
  1440.   {
  1441.     FILE *batch;
  1442.     is_batch_file = 1;
  1443.     if (!bname)
  1444.     {
  1445.       bname = tempnam(".", "mk");
  1446.       for (i=0; bname[i]; i++)
  1447.         if (bname[i] == '/')
  1448.           bname[i] = '\\';
  1449.       bename = (char *)malloc(strlen(bname)+5);
  1450.       strcpy(bename, bname);
  1451.       strcat(bname, ".bat");
  1452.       strcat(bename, ".err");
  1453.     }
  1454.     fclose(fopen(bename, "w")); /* create a file */
  1455.     batch = fopen(bname, "w");
  1456.     fputs("@echo off\n", batch);
  1457.     fputs(line, batch);
  1458.     fprintf(batch, "\nif errorlevel 1 del %s\n", bename);
  1459.     fclose(batch);
  1460.     new_argv = (char **)xmalloc(2 * sizeof(char *));
  1461.     new_argv[0] = strdup(bname);
  1462.     new_argv[1] = 0;
  1463.   }
  1464. #else /* __MSDOS__ */
  1465.   {
  1466.     /* SHELL may be a multi-word command.  Construct a command line
  1467.        "SHELL -c LINE", with all special chars in LINE escaped.
  1468.        Then recurse, expanding this command line to get the final
  1469.        argument list.  */
  1470.     
  1471.     unsigned int shell_len = strlen (shell);
  1472.     static char minus_c[] = " -c ";
  1473.     unsigned int line_len = strlen (line);
  1474.     
  1475.     char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
  1476.                       + (line_len * 2) + 1);
  1477.     
  1478.     ap = new_line;
  1479.     bcopy (shell, ap, shell_len);
  1480.     ap += shell_len;
  1481.     bcopy (minus_c, ap, sizeof (minus_c) - 1);
  1482.     ap += sizeof (minus_c) - 1;
  1483.     for (p = line; *p != '\0'; ++p)
  1484.       {
  1485.     if (restp != NULL && *p == '\n')
  1486.       {
  1487.         *restp = p;
  1488.         break;
  1489.       }
  1490.     else if (*p == '\\' && p[1] == '\n')
  1491.       {
  1492.         /* Eat the backslash, the newline, and following whitespace,
  1493.            replacing it all with a single space (which is escaped
  1494.            from the shell).  */
  1495.         p += 2;
  1496.  
  1497.         /* If there is a tab after a backslash-newline,
  1498.            remove it from the source line which will be echoed,
  1499.            since it was most likely used to line
  1500.            up the continued line with the previous one.  */
  1501.         if (*p == '\t')
  1502.           strcpy (p, p + 1);
  1503.  
  1504.         p = next_token (p);
  1505.         --p;
  1506.         *ap++ = '\\';
  1507.         *ap++ = ' ';
  1508.         continue;
  1509.       }
  1510.  
  1511.     if (*p == '\\' || *p == '\''
  1512.         || isspace (*p)
  1513.         || index (sh_chars, *p) != 0)
  1514.       *ap++ = '\\';
  1515.     *ap++ = *p;
  1516.       }
  1517.     *ap = '\0';
  1518.     
  1519.     new_argv = construct_command_argv_internal (new_line, (char **) NULL,
  1520.                         (char *) 0, (char *) 0);
  1521.   }
  1522. #endif /* ?__MSDOS__ */
  1523.   return new_argv;
  1524. }
  1525.  
  1526. /* Figure out the argument list necessary to run LINE as a command.
  1527.    Try to avoid using a shell.  This routine handles only ' quoting.
  1528.    Starting quotes may be escaped with a backslash.  If any of the
  1529.    characters in sh_chars[] is seen, or any of the builtin commands
  1530.    listed in sh_cmds[] is the first word of a line, the shell is used.
  1531.  
  1532.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1533.    If *RESTP is NULL, newlines will be ignored.
  1534.  
  1535.    FILE is the target whose commands these are.  It is used for
  1536.    variable expansion for $(SHELL) and $(IFS).  */
  1537.  
  1538. char **
  1539. construct_command_argv (line, restp, file)
  1540.      char *line, **restp;
  1541.      struct file *file;
  1542. {
  1543.   char *shell, *ifs;
  1544.   char **argv;
  1545.  
  1546.   {
  1547.     /* Turn off --warn-undefined-variables while we expand SHELL and IFS.  */
  1548.     int save = warn_undefined_variables_flag;
  1549.     warn_undefined_variables_flag = 0;
  1550.  
  1551.     shell = allocated_variable_expand_for_file ("$(SHELL)", file);
  1552.     ifs = allocated_variable_expand_for_file ("$(IFS)", file);
  1553.  
  1554.     warn_undefined_variables_flag = save;
  1555.   }
  1556.  
  1557.   argv = construct_command_argv_internal (line, restp, shell, ifs);
  1558.  
  1559.   free (shell);
  1560.   free (ifs);
  1561.  
  1562.   return argv;
  1563. }
  1564.  
  1565. #ifndef    HAVE_DUP2
  1566. int
  1567. dup2 (old, new)
  1568.      int old, new;
  1569. {
  1570.   int fd;
  1571.  
  1572.   (void) close (new);
  1573.   fd = dup (old);
  1574.   if (fd != new)
  1575.     {
  1576.       (void) close (fd);
  1577.       errno = EMFILE;
  1578.       return -1;
  1579.     }
  1580.  
  1581.   return fd;
  1582. }
  1583. #endif
  1584.