aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

jobs.c (36677B)


      1 /* -
      2  * spdx-license-identifier: bsd-3-clause
      3  *
      4  * copyright (c) 1991, 1993
      5  * the regents of the university of california. all rights reserved
      6  *
      7  * this code is derived from software contributed to berkeley by
      8  * kenneth almquist
      9  *
     10  * redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. redistributions of source code must retain the above copyright
     14  * notice, this list of conditions and the following disclaimer
     15  * 2. redistributions in binary form must reproduce the above copyright
     16  * notice, this list of conditions and the following disclaimer in the
     17  * documentation and/or other materials provided with the distribution
     18  * 3. neither the name of the university nor the names of its contributors
     19  * may be used to endorse or promote products derived from this software
     20  * without specific prior written permission
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE
     25  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE
     33  */
     34 
     35 #if FEATURE_SH_EXT
     36 #ifndef _DEFAULT_SOURCE
     37 #define _DEFAULT_SOURCE
     38 #endif
     39 #ifndef _GNU_SOURCE
     40 #define _GNU_SOURCE
     41 #endif
     42 #endif
     43 #include <errno.h>
     44 #include <fcntl.h>
     45 #include <signal.h>
     46 #include <stddef.h>
     47 #include <stdlib.h>
     48 #include <sys/ioctl.h>
     49 #include <sys/param.h>
     50 #include <sys/resource.h>
     51 #include <sys/time.h>
     52 #include <sys/wait.h>
     53 #include <unistd.h>
     54 
     55 #include "../../../shared/paths.h"
     56 #include "shell.h"
     57 #if JOBS
     58 #include <termios.h>
     59 #undef CEOF /* syntax.h redefines this */
     60 #endif
     61 #include "builtins.h"
     62 #include "error.h"
     63 #include "eval.h"
     64 #include "exec.h"
     65 #include "input.h"
     66 #include "jobs.h"
     67 #include "main.h"
     68 #include "memalloc.h"
     69 #include "mystring.h"
     70 #include "nodes.h"
     71 #include "options.h"
     72 #include "output.h"
     73 #include "parser.h"
     74 #include "redir.h"
     75 #include "show.h"
     76 #include "syntax.h"
     77 #include "trap.h"
     78 #include "var.h"
     79 
     80 /*
     81  * a job structure contains information about a job. a job is either a
     82  * single process or a set of processes contained in a pipeline. in the
     83  * latter case, pidlist will be non-null, and will point to a -1 terminated
     84  * array of pids
     85  */
     86 
     87 struct procstat {
     88   pid_t pid;    /* process id */
     89   int   status; /* status flags (defined above) */
     90   char *cmd;    /* text of command being run */
     91 };
     92 
     93 /* states */
     94 #define JOBSTOPPED 1 /* all procs are stopped */
     95 #define JOBDONE    2 /* all procs are completed */
     96 
     97 struct job {
     98   struct procstat  ps0;        /* status of process */
     99   struct procstat *ps;         /* status or processes when more than one */
    100   short            nprocs;     /* number of processes */
    101   pid_t            pgrp;       /* process group of this job */
    102   char             state;      /* true if job is finished */
    103   char             used;       /* true if this entry is in use */
    104   char             changed;    /* true if status has changed */
    105   char             foreground; /* true if running in the foreground */
    106   char             remembered; /* true if $! referenced */
    107   char             pipefail;   /* pass any non-zero status */
    108 #if JOBS
    109   char        jobctl; /* job running under job control */
    110   struct job *next;   /* job used after this one */
    111 #endif
    112 };
    113 
    114 static struct job *jobtab;            /* array of jobs */
    115 static int         njobs;             /* size of array */
    116 static pid_t       backgndpid = -1;   /* pid of last background process */
    117 static struct job *bgjob      = NULL; /* last background process */
    118 #if JOBS
    119 static struct job *jobmru;      /* most recently used job list */
    120 static pid_t       initialpgrp; /* pgrp of shell on invocation */
    121 #endif
    122 static int ttyfd = -1;
    123 
    124 /* mode flags for dowait */
    125 #define DOWAIT_BLOCK    0x1 /* wait until a child exits */
    126 #define DOWAIT_SIG      0x2 /* if DOWAIT_BLOCK, abort on signal */
    127 #define DOWAIT_SIG_TRAP 0x4 /* if DOWAIT_SIG, abort on trapped signal only */
    128 
    129 #if JOBS
    130 static void restartjob(struct job *);
    131 #endif
    132 static void        freejob(struct job *);
    133 static int         waitcmdloop(struct job *);
    134 static struct job *getjob_nonotfound(const char *);
    135 static struct job *getjob(const char *);
    136 pid_t              killjob(const char *, int);
    137 static pid_t       dowait(int, struct job *);
    138 static void        checkzombies(void);
    139 static void        cmdtxt(union node *);
    140 static void        cmdputs(const char *);
    141 #if JOBS
    142 static void        setcurjob(struct job *);
    143 static void        deljob(struct job *);
    144 static struct job *getcurjob(struct job *);
    145 #endif
    146 static int  getjobstatus(const struct job *);
    147 static void printjobcmd(struct job *);
    148 static void showjob(struct job *, int);
    149 
    150 /*
    151  * turn job control on and off
    152  */
    153 
    154 static int jobctl;
    155 
    156 #if JOBS
    157 static void
    158 jobctl_notty(void)
    159 {
    160   if (ttyfd >= 0) {
    161     close(ttyfd);
    162     ttyfd = -1;
    163   }
    164   if (!iflag) {
    165     setsignal(SIGTSTP);
    166     setsignal(SIGTTOU);
    167     setsignal(SIGTTIN);
    168     jobctl = 1;
    169     return;
    170   }
    171   out2fmt_flush("sh: can't access tty; job control turned off\n");
    172   mflag = 0;
    173 }
    174 
    175 void
    176 setjobctl(int on)
    177 {
    178   int i;
    179 
    180   if (on == jobctl || rootshell == 0)
    181     return;
    182   if (on) {
    183     if (ttyfd != -1)
    184       close(ttyfd);
    185     if ((ttyfd = open(ARUU_PATH_DEVTTY, O_RDWR | O_CLOEXEC)) < 0) {
    186       i = 0;
    187       while (i <= 2 && !isatty(i))
    188         i++;
    189       if (i > 2 || (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0) {
    190         jobctl_notty();
    191         return;
    192       }
    193     }
    194     if (ttyfd < 10) {
    195       /*
    196        * keep our TTY file descriptor out of the way of
    197        * the user's redirections
    198        */
    199       if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
    200         jobctl_notty();
    201         return;
    202       }
    203       close(ttyfd);
    204       ttyfd = i;
    205     }
    206     do { /* while we are in the background */
    207       initialpgrp = tcgetpgrp(ttyfd);
    208       if (initialpgrp < 0) {
    209         jobctl_notty();
    210         return;
    211       }
    212       if (initialpgrp != getpgrp()) {
    213         if (!iflag) {
    214           initialpgrp = -1;
    215           jobctl_notty();
    216           return;
    217         }
    218         kill(0, SIGTTIN);
    219         continue;
    220       }
    221     } while (0);
    222     setsignal(SIGTSTP);
    223     setsignal(SIGTTOU);
    224     setsignal(SIGTTIN);
    225     setpgid(0, rootpid);
    226     tcsetpgrp(ttyfd, rootpid);
    227   } else { /* turning job control off */
    228     setpgid(0, initialpgrp);
    229     if (ttyfd >= 0) {
    230       tcsetpgrp(ttyfd, initialpgrp);
    231       close(ttyfd);
    232       ttyfd = -1;
    233     }
    234     setsignal(SIGTSTP);
    235     setsignal(SIGTTOU);
    236     setsignal(SIGTTIN);
    237   }
    238   jobctl = on;
    239 }
    240 #endif
    241 
    242 #if JOBS
    243 int
    244 fgcmd(int argc __unused, char **argv __unused)
    245 {
    246   struct job *jp;
    247   pid_t       pgrp;
    248   int         status;
    249 
    250   nextopt("");
    251   jp = getjob(*argptr);
    252   if (jp->jobctl == 0)
    253     error("job not created under job control");
    254   printjobcmd(jp);
    255   flushout(&output);
    256   pgrp = jp->ps[0].pid;
    257   if (ttyfd >= 0)
    258     tcsetpgrp(ttyfd, pgrp);
    259   restartjob(jp);
    260   jp->foreground = 1;
    261   INTOFF;
    262   status = waitforjob(jp, (int *)NULL);
    263   INTON;
    264   return status;
    265 }
    266 
    267 int
    268 bgcmd(int argc __unused, char **argv __unused)
    269 {
    270   struct job *jp;
    271 
    272   nextopt("");
    273   do {
    274     jp = getjob(*argptr);
    275     if (jp->jobctl == 0)
    276       error("job not created under job control");
    277     if (jp->state == JOBDONE)
    278       continue;
    279     restartjob(jp);
    280     jp->foreground = 0;
    281     out1fmt("[%td] ", jp - jobtab + 1);
    282     printjobcmd(jp);
    283   } while (*argptr != NULL && *++argptr != NULL);
    284   return 0;
    285 }
    286 
    287 static void
    288 restartjob(struct job *jp)
    289 {
    290   struct procstat *ps;
    291   int              i;
    292 
    293   if (jp->state == JOBDONE)
    294     return;
    295   setcurjob(jp);
    296   INTOFF;
    297   kill(-jp->ps[0].pid, SIGCONT);
    298   for (ps = jp->ps, i = jp->nprocs; --i >= 0; ps++) {
    299     if (WIFSTOPPED(ps->status)) {
    300       ps->status = -1;
    301       jp->state  = 0;
    302     }
    303   }
    304   INTON;
    305 }
    306 #endif
    307 
    308 int
    309 jobscmd(int argc __unused, char *argv[] __unused)
    310 {
    311   char *id;
    312   int   ch, mode;
    313 
    314   mode = SHOWJOBS_DEFAULT;
    315   while ((ch = nextopt("lps")) != '\0') {
    316     switch (ch) {
    317       case 'l':
    318         mode = SHOWJOBS_VERBOSE;
    319         break;
    320       case 'p':
    321         mode = SHOWJOBS_PGIDS;
    322         break;
    323       case 's':
    324         mode = SHOWJOBS_PIDS;
    325         break;
    326     }
    327   }
    328 
    329   if (*argptr == NULL)
    330     showjobs(0, mode);
    331   else
    332     while ((id = *argptr++) != NULL)
    333       showjob(getjob(id), mode);
    334 
    335   return (0);
    336 }
    337 
    338 static int
    339 getjobstatus(const struct job *jp)
    340 {
    341   int i, status;
    342 
    343   if (!jp->pipefail)
    344     return (jp->ps[jp->nprocs - 1].status);
    345   for (i = jp->nprocs - 1; i >= 0; i--) {
    346     status = jp->ps[i].status;
    347     if (status != 0)
    348       return (status);
    349   }
    350   return (0);
    351 }
    352 
    353 static void
    354 printjobcmd(struct job *jp)
    355 {
    356   struct procstat *ps;
    357   int              i;
    358 
    359   for (ps = jp->ps, i = jp->nprocs; --i >= 0; ps++) {
    360     out1str(ps->cmd);
    361     if (i > 0)
    362       out1str(" | ");
    363   }
    364   out1c('\n');
    365 }
    366 
    367 static void
    368 showjob(struct job *jp, int mode)
    369 {
    370   char             s[64];
    371   char             statebuf[16];
    372   const char      *statestr, *coredump;
    373   struct procstat *ps;
    374   struct job      *j;
    375   int              col, curr, i, jobno, prev, procno, status;
    376   char             c;
    377 
    378   procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
    379   jobno  = jp - jobtab + 1;
    380   curr = prev = 0;
    381 #if JOBS
    382   if ((j = getcurjob(NULL)) != NULL) {
    383     curr = j - jobtab + 1;
    384     if ((j = getcurjob(j)) != NULL)
    385       prev = j - jobtab + 1;
    386   }
    387 #endif
    388   coredump = "";
    389   status   = getjobstatus(jp);
    390   if (jp->state == 0) {
    391     statestr = "Running";
    392 #if JOBS
    393   } else if (jp->state == JOBSTOPPED) {
    394     ps = jp->ps + jp->nprocs - 1;
    395     while (!WIFSTOPPED(ps->status) && ps > jp->ps)
    396       ps--;
    397     if (WIFSTOPPED(ps->status))
    398       i = WSTOPSIG(ps->status);
    399     else
    400       i = -1;
    401     statestr = strsignal(i);
    402     if (statestr == NULL)
    403       statestr = "Suspended";
    404 #endif
    405   } else if (WIFEXITED(status)) {
    406     if (WEXITSTATUS(status) == 0)
    407       statestr = "Done";
    408     else {
    409       fmtstr(statebuf, sizeof(statebuf), "Done(%d)", WEXITSTATUS(status));
    410       statestr = statebuf;
    411     }
    412   } else {
    413     i        = WTERMSIG(status);
    414     statestr = strsignal(i);
    415     if (statestr == NULL)
    416       statestr = "Unknown signal";
    417     if (WCOREDUMP(status))
    418       coredump = " (core dumped)";
    419   }
    420 
    421   for (ps = jp->ps; procno > 0; ps++, procno--) { /* for each process */
    422     if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
    423       out1fmt("%d\n", (int)ps->pid);
    424       continue;
    425     }
    426     if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
    427       continue;
    428     if (jobno == curr && ps == jp->ps)
    429       c = '+';
    430     else if (jobno == prev && ps == jp->ps)
    431       c = '-';
    432     else
    433       c = ' ';
    434     if (ps == jp->ps)
    435       fmtstr(s, 64, "[%d] %c ", jobno, c);
    436     else
    437       fmtstr(s, 64, "    %c ", c);
    438     out1str(s);
    439     col = strlen(s);
    440     if (mode == SHOWJOBS_VERBOSE) {
    441       fmtstr(s, 64, "%d ", (int)ps->pid);
    442       out1str(s);
    443       col += strlen(s);
    444     }
    445     if (ps == jp->ps) {
    446       out1str(statestr);
    447       out1str(coredump);
    448       col += strlen(statestr) + strlen(coredump);
    449     }
    450     do {
    451       out1c(' ');
    452       col++;
    453     } while (col < 30);
    454     if (mode == SHOWJOBS_VERBOSE) {
    455       out1str(ps->cmd);
    456       out1c('\n');
    457     } else
    458       printjobcmd(jp);
    459   }
    460 }
    461 
    462 /*
    463  * print a list of jobs. if "change" is nonzero, only print jobs whose
    464  * statuses have changed since the last call to showjobs
    465  *
    466  * if the shell is interrupted in the process of creating a job, the
    467  * result may be a job structure containing zero processes. such structures
    468  * will be freed here
    469  */
    470 
    471 void
    472 showjobs(int change, int mode)
    473 {
    474   int         jobno;
    475   struct job *jp;
    476 
    477   TRACE(("showjobs(%d) called\n", change));
    478   checkzombies();
    479   for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
    480     if (!jp->used)
    481       continue;
    482     if (jp->nprocs == 0) {
    483       freejob(jp);
    484       continue;
    485     }
    486     if (change && !jp->changed)
    487       continue;
    488     showjob(jp, mode);
    489     if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
    490       jp->changed = 0;
    491       /* hack: discard jobs for which $! has not been
    492        * referenced in interactive mode when they terminate
    493        */
    494       if (jp->state == JOBDONE && !jp->remembered && (iflag || jp != bgjob)) {
    495         freejob(jp);
    496       }
    497     }
    498   }
    499 }
    500 
    501 /*
    502  * mark a job structure as unused
    503  */
    504 
    505 static void
    506 freejob(struct job *jp)
    507 {
    508   struct procstat *ps;
    509   int              i;
    510 
    511   INTOFF;
    512   if (bgjob == jp)
    513     bgjob = NULL;
    514   for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
    515     if (ps->cmd != nullstr)
    516       ckfree(ps->cmd);
    517   }
    518   if (jp->ps != &jp->ps0)
    519     ckfree(jp->ps);
    520   jp->used = 0;
    521 #if JOBS
    522   deljob(jp);
    523 #endif
    524   INTON;
    525 }
    526 
    527 int
    528 waitcmd(int argc __unused, char **argv __unused)
    529 {
    530   struct job *job;
    531   int         retval;
    532 
    533   nextopt("");
    534   if (*argptr == NULL)
    535     return (waitcmdloop(NULL));
    536 
    537   do {
    538     job = getjob_nonotfound(*argptr);
    539     if (job == NULL)
    540       retval = 127;
    541     else
    542       retval = waitcmdloop(job);
    543     argptr++;
    544   } while (*argptr != NULL);
    545 
    546   return (retval);
    547 }
    548 
    549 static int
    550 waitcmdloop(struct job *job)
    551 {
    552   int         status, retval, sig;
    553   struct job *jp;
    554 
    555   /*
    556    * loop until a process is terminated or stopped, or a SIGINT is
    557    * received
    558    */
    559 
    560   do {
    561     if (job != NULL) {
    562       if (job->state == JOBDONE) {
    563         status = getjobstatus(job);
    564         if (WIFEXITED(status))
    565           retval = WEXITSTATUS(status);
    566         else
    567           retval = WTERMSIG(status) + 128;
    568         if (!iflag || !job->changed)
    569           freejob(job);
    570         else {
    571           job->remembered = 0;
    572           deljob(job);
    573           if (job == bgjob)
    574             bgjob = NULL;
    575         }
    576         return retval;
    577       }
    578     } else {
    579       if (njobs == 0)
    580         return 0;
    581       for (jp = jobtab; jp < jobtab + njobs; jp++)
    582         if (jp->used && jp->state == JOBDONE) {
    583           if (!iflag || !jp->changed)
    584             freejob(jp);
    585           else {
    586             jp->remembered = 0;
    587             if (jp == bgjob)
    588               bgjob = NULL;
    589           }
    590         }
    591       for (jp = jobtab;; jp++) {
    592         if (jp >= jobtab + njobs) { /* no running procs */
    593           return 0;
    594         }
    595         if (jp->used && jp->state == 0)
    596           break;
    597       }
    598     }
    599   } while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, job) != -1);
    600 
    601   sig                = pendingsig_waitcmd;
    602   pendingsig_waitcmd = 0;
    603   return sig + 128;
    604 }
    605 
    606 int
    607 jobidcmd(int argc __unused, char **argv __unused)
    608 {
    609   struct job *jp;
    610   int         i;
    611 
    612   nextopt("");
    613   jp = getjob(*argptr);
    614   for (i = 0; i < jp->nprocs;) {
    615     out1fmt("%d", (int)jp->ps[i].pid);
    616     out1c(++i < jp->nprocs ? ' ' : '\n');
    617   }
    618   return 0;
    619 }
    620 
    621 /*
    622  * convert a job name to a job structure
    623  */
    624 
    625 static struct job *
    626 getjob_nonotfound(const char *name)
    627 {
    628   int         jobno;
    629   struct job *found, *jp;
    630   size_t      namelen;
    631   pid_t       pid;
    632   int         i;
    633 
    634   if (name == NULL) {
    635 #if JOBS
    636     name = "%+";
    637 #else
    638     error("No current job");
    639 #endif
    640   }
    641   if (name[0] == '%') {
    642     if (is_digit(name[1])) {
    643       jobno = number(name + 1);
    644       if (jobno > 0 && jobno <= njobs && jobtab[jobno - 1].used != 0)
    645         return &jobtab[jobno - 1];
    646 #if JOBS
    647     } else if ((name[1] == '%' || name[1] == '+') && name[2] == '\0') {
    648       if ((jp = getcurjob(NULL)) == NULL)
    649         error("No current job");
    650       return (jp);
    651     } else if (name[1] == '-' && name[2] == '\0') {
    652       if ((jp = getcurjob(NULL)) == NULL || (jp = getcurjob(jp)) == NULL)
    653         error("No previous job");
    654       return (jp);
    655 #endif
    656     } else if (name[1] == '?') {
    657       found = NULL;
    658       for (jp = jobtab, i = njobs; --i >= 0; jp++) {
    659         if (jp->used && jp->nprocs > 0 && strstr(jp->ps[0].cmd, name + 2) != NULL) {
    660           if (found)
    661             error("%s: ambiguous", name);
    662           found = jp;
    663         }
    664       }
    665       if (found != NULL)
    666         return (found);
    667     } else {
    668       namelen = strlen(name);
    669       found   = NULL;
    670       for (jp = jobtab, i = njobs; --i >= 0; jp++) {
    671         if (jp->used && jp->nprocs > 0 && strncmp(jp->ps[0].cmd, name + 1, namelen - 1) == 0) {
    672           if (found)
    673             error("%s: ambiguous", name);
    674           found = jp;
    675         }
    676       }
    677       if (found)
    678         return found;
    679     }
    680   } else if (is_number(name)) {
    681     pid = (pid_t)number(name);
    682     for (jp = jobtab, i = njobs; --i >= 0; jp++) {
    683       if (jp->used && jp->nprocs > 0 && jp->ps[jp->nprocs - 1].pid == pid)
    684         return jp;
    685     }
    686   }
    687   return NULL;
    688 }
    689 
    690 static struct job *
    691 getjob(const char *name)
    692 {
    693   struct job *jp;
    694 
    695   jp = getjob_nonotfound(name);
    696   if (jp == NULL)
    697     error("No such job: %s", name);
    698   return (jp);
    699 }
    700 
    701 int
    702 killjob(const char *name, int sig)
    703 {
    704   struct job *jp;
    705   int         i, ret;
    706 
    707   jp = getjob(name);
    708   if (jp->state == JOBDONE)
    709     return 0;
    710   if (jp->jobctl)
    711     return kill(-jp->ps[0].pid, sig);
    712   ret   = -1;
    713   errno = ESRCH;
    714   for (i = 0; i < jp->nprocs; i++)
    715     if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
    716       if (kill(jp->ps[i].pid, sig) == 0)
    717         ret = 0;
    718     } else
    719       ret = 0;
    720   return ret;
    721 }
    722 
    723 /*
    724  * return a new job structure,
    725  */
    726 
    727 struct job *
    728 makejob(union node *node __unused, int nprocs)
    729 {
    730   int         i;
    731   struct job *jp;
    732 
    733   for (i = njobs, jp = jobtab;; jp++) {
    734     if (--i < 0) {
    735       INTOFF;
    736       if (njobs == 0) {
    737         jobtab = ckmalloc(4 * sizeof jobtab[0]);
    738 #if JOBS
    739         jobmru = NULL;
    740 #endif
    741       } else {
    742         jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    743         memcpy(jp, jobtab, njobs * sizeof jp[0]);
    744 #if JOBS
    745         /* relocate `next' pointers and list head */
    746         if (jobmru != NULL)
    747           jobmru = &jp[jobmru - jobtab];
    748         for (i = 0; i < njobs; i++)
    749           if (jp[i].next != NULL)
    750             jp[i].next = &jp[jp[i].next - jobtab];
    751 #endif
    752         if (bgjob != NULL)
    753           bgjob = &jp[bgjob - jobtab];
    754         /* relocate `ps' pointers */
    755         for (i = 0; i < njobs; i++)
    756           if (jp[i].ps == &jobtab[i].ps0)
    757             jp[i].ps = &jp[i].ps0;
    758         ckfree(jobtab);
    759         jobtab = jp;
    760       }
    761       jp = jobtab + njobs;
    762       for (i = 4; --i >= 0; jobtab[njobs++].used = 0)
    763         ;
    764       INTON;
    765       break;
    766     }
    767     if (jp->used == 0)
    768       break;
    769   }
    770   INTOFF;
    771   jp->state      = 0;
    772   jp->used       = 1;
    773   jp->changed    = 0;
    774   jp->nprocs     = 0;
    775   jp->foreground = 0;
    776   jp->remembered = 0;
    777   jp->pipefail   = pipefailflag;
    778 #if JOBS
    779   jp->jobctl = jobctl;
    780   jp->next   = NULL;
    781 #endif
    782   if (nprocs > 1) {
    783     jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
    784   } else {
    785     jp->ps = &jp->ps0;
    786   }
    787   INTON;
    788   TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs, jp - jobtab + 1));
    789   return jp;
    790 }
    791 
    792 #if JOBS
    793 static void
    794 setcurjob(struct job *cj)
    795 {
    796   struct job *jp, *prev;
    797 
    798   for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
    799     if (jp == cj) {
    800       if (prev != NULL)
    801         prev->next = jp->next;
    802       else
    803         jobmru = jp->next;
    804       jp->next = jobmru;
    805       jobmru   = cj;
    806       return;
    807     }
    808   }
    809   cj->next = jobmru;
    810   jobmru   = cj;
    811 }
    812 
    813 static void
    814 deljob(struct job *j)
    815 {
    816   struct job *jp, *prev;
    817 
    818   for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
    819     if (jp == j) {
    820       if (prev != NULL)
    821         prev->next = jp->next;
    822       else
    823         jobmru = jp->next;
    824       return;
    825     }
    826   }
    827 }
    828 
    829 /*
    830  * return the most recently used job that isnt `nj', and preferably one
    831  * that is stopped
    832  */
    833 static struct job *
    834 getcurjob(struct job *nj)
    835 {
    836   struct job *jp;
    837 
    838   /* try to find a stopped one.. */
    839   for (jp = jobmru; jp != NULL; jp = jp->next)
    840     if (jp->used && jp != nj && jp->state == JOBSTOPPED)
    841       return (jp);
    842   /* otherwise the most recently used job that isnt `nj' */
    843   for (jp = jobmru; jp != NULL; jp = jp->next)
    844     if (jp->used && jp != nj)
    845       return (jp);
    846 
    847   return (NULL);
    848 }
    849 
    850 #endif
    851 
    852 /*
    853  * fork of a subshell. if we are doing job control, give the subshell its
    854  * own process group. jp is a job structure that the job is to be added to
    855  * n is the command that will be evaluated by the child. both jp and n may
    856  * be NULL. the mode parameter can be one of the following:
    857  * FORK_FG - fork off a foreground process
    858  * FORK_BG - fork off a background process
    859  * FORK_NOJOB - like FORK_FG, but dont give the process its own
    860  * process group even if job control is on
    861  *
    862  * when job control is turned off, background processes have their standard
    863  * input redirected to /dev/null (except for the second and later processes
    864  * in a pipeline)
    865  */
    866 
    867 pid_t
    868 forkshell(struct job *jp, union node *n, int mode)
    869 {
    870   pid_t pid;
    871   pid_t pgrp;
    872 
    873   TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n, mode));
    874   INTOFF;
    875   if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
    876     checkzombies();
    877   flushall();
    878   pid = fork();
    879   if (pid == -1) {
    880     TRACE(("Fork failed, errno=%d\n", errno));
    881     INTON;
    882     error("Cannot fork: %s", strerror(errno));
    883   }
    884   if (pid == 0) {
    885     struct job *p;
    886     int         wasroot;
    887     int         i;
    888 
    889     TRACE(("Child shell %d\n", (int)getpid()));
    890     wasroot   = rootshell;
    891     rootshell = 0;
    892     handler   = &main_handler;
    893     closescript();
    894     INTON;
    895     forcelocal = 0;
    896     clear_traps();
    897 #if JOBS
    898     jobctl = 0; /* do job control only in root shell */
    899     if (wasroot && mode != FORK_NOJOB && mflag) {
    900       if (jp == NULL || jp->nprocs == 0)
    901         pgrp = getpid();
    902       else
    903         pgrp = jp->ps[0].pid;
    904       if (setpgid(0, pgrp) == 0 && mode == FORK_FG && ttyfd >= 0) {
    905         /*
    906          * each process in a pipeline must have the tty
    907          * pgrp set before running its code
    908          * only for pipelines of three or more processes
    909          * could this be reduced to two calls
    910          */
    911         if (tcsetpgrp(ttyfd, pgrp) < 0)
    912           error("tcsetpgrp failed, errno=%d", errno);
    913       }
    914       setsignal(SIGTSTP);
    915       setsignal(SIGTTOU);
    916     } else if (mode == FORK_BG) {
    917       ignoresig(SIGINT);
    918       ignoresig(SIGQUIT);
    919       if ((jp == NULL || jp->nprocs == 0) && !fd0_redirected_p()) {
    920         close(0);
    921         if (open(ARUU_PATH_DEVNULL, O_RDONLY) != 0)
    922           error("cannot open %s: %s", ARUU_PATH_DEVNULL, strerror(errno));
    923       }
    924     }
    925 #else
    926     if (mode == FORK_BG) {
    927       ignoresig(SIGINT);
    928       ignoresig(SIGQUIT);
    929       if ((jp == NULL || jp->nprocs == 0) && !fd0_redirected_p()) {
    930         close(0);
    931         if (open(ARUU_PATH_DEVNULL, O_RDONLY) != 0)
    932           error("cannot open %s: %s", ARUU_PATH_DEVNULL, strerror(errno));
    933       }
    934     }
    935 #endif
    936     INTOFF;
    937     for (i = njobs, p = jobtab; --i >= 0; p++)
    938       if (p->used)
    939         freejob(p);
    940     INTON;
    941     if (wasroot && iflag) {
    942       setsignal(SIGINT);
    943       setsignal(SIGQUIT);
    944       setsignal(SIGTERM);
    945     }
    946     return pid;
    947   }
    948   if (rootshell && mode != FORK_NOJOB && mflag) {
    949     if (jp == NULL || jp->nprocs == 0)
    950       pgrp = pid;
    951     else
    952       pgrp = jp->ps[0].pid;
    953     setpgid(pid, pgrp);
    954   }
    955   if (mode == FORK_BG) {
    956     if (bgjob != NULL && bgjob->state == JOBDONE && !bgjob->remembered && !iflag)
    957       freejob(bgjob);
    958     backgndpid = pid; /* set $! */
    959     bgjob      = jp;
    960   }
    961   if (jp) {
    962     struct procstat *ps = &jp->ps[jp->nprocs++];
    963     ps->pid             = pid;
    964     ps->status          = -1;
    965     ps->cmd             = nullstr;
    966     if (iflag && rootshell && n)
    967       ps->cmd = commandtext(n);
    968     jp->foreground = mode == FORK_FG;
    969 #if JOBS
    970     setcurjob(jp);
    971 #endif
    972   }
    973   INTON;
    974   TRACE(("In parent shell:  child = %d\n", (int)pid));
    975   return pid;
    976 }
    977 
    978 pid_t
    979 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
    980 {
    981   pid_t          pid;
    982   struct jmploc  jmploc;
    983   struct jmploc *savehandler;
    984   int            inton;
    985 
    986   TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0], (void *)pip));
    987   inton = is_int_on();
    988   INTOFF;
    989   flushall();
    990   savehandler = handler;
    991   pid         = vfork();
    992   if (pid == -1) {
    993     TRACE(("Vfork failed, errno=%d\n", errno));
    994     INTON;
    995     error("Cannot fork: %s", strerror(errno));
    996   }
    997   if (pid == 0) {
    998     TRACE(("Child shell %d\n", (int)getpid()));
    999     if (setjmp(jmploc.loc))
   1000       _exit(exitstatus);
   1001     if (pip != NULL) {
   1002       close(pip[0]);
   1003       if (pip[1] != 1) {
   1004         dup2(pip[1], 1);
   1005         close(pip[1]);
   1006       }
   1007     }
   1008     handler = &jmploc;
   1009     shellexec(argv, envp, path, idx);
   1010   }
   1011   handler = savehandler;
   1012   if (jp) {
   1013     struct procstat *ps = &jp->ps[jp->nprocs++];
   1014     ps->pid             = pid;
   1015     ps->status          = -1;
   1016     ps->cmd             = nullstr;
   1017     jp->foreground      = 1;
   1018 #if JOBS
   1019     setcurjob(jp);
   1020 #endif
   1021   }
   1022   SETINTON(inton);
   1023   TRACE(("In parent shell:  child = %d\n", (int)pid));
   1024   return pid;
   1025 }
   1026 
   1027 /*
   1028  * wait for job to finish
   1029  *
   1030  * under job control we have the problem that while a child process is
   1031  * running interrupts generated by the user are sent to the child but not
   1032  * to the shell. this means that an infinite loop started by an inter-
   1033  * active user may be hard to kill. with job control turned off, an
   1034  * interactive user may place an interactive program inside a loop. if
   1035  * the interactive program catches interrupts, the user doesnt want
   1036  * these interrupts to also abort the loop. the approach we take here
   1037  * is to have the shell ignore interrupt signals while waiting for a
   1038  * foreground process to terminate, and then send itself an interrupt
   1039  * signal if the child process was terminated by an interrupt signal
   1040  * unfortunately, some programs want to do a bit of cleanup and then
   1041  * exit on interrupt; unless these processes terminate themselves by
   1042  * sending a signal to themselves (instead of calling exit) they will
   1043  * confuse this approach
   1044  */
   1045 
   1046 int
   1047 waitforjob(struct job *jp, int *signaled)
   1048 {
   1049 #if JOBS
   1050   int propagate_int = jp->jobctl && jp->foreground;
   1051 #endif
   1052   int jobindex;
   1053   int status;
   1054   int st;
   1055 
   1056   INTOFF;
   1057   TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
   1058   while (jp->state == 0)
   1059     if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG | DOWAIT_SIG_TRAP : 0), jp) == -1) {
   1060       jobindex = jp - jobtab;
   1061       dotrap();
   1062       jp = jobtab + jobindex;
   1063     }
   1064 #if JOBS
   1065   if (jp->jobctl) {
   1066     if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
   1067       error("tcsetpgrp failed, errno=%d\n", errno);
   1068   }
   1069   if (jp->state == JOBSTOPPED)
   1070     setcurjob(jp);
   1071 #endif
   1072   status = getjobstatus(jp);
   1073   if (signaled != NULL)
   1074     *signaled = WIFSIGNALED(status);
   1075   /* convert to 8 bits */
   1076   if (WIFEXITED(status))
   1077     st = WEXITSTATUS(status);
   1078 #if JOBS
   1079   else if (WIFSTOPPED(status))
   1080     st = WSTOPSIG(status) + 128;
   1081 #endif
   1082   else
   1083     st = WTERMSIG(status) + 128;
   1084   if (!JOBS || jp->state == JOBDONE)
   1085     freejob(jp);
   1086   if (int_pending()) {
   1087     if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
   1088       CLEAR_PENDING_INT;
   1089   }
   1090 #if JOBS
   1091   else if (rootshell && propagate_int && WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1092     kill(getpid(), SIGINT);
   1093 #endif
   1094   INTON;
   1095   return st;
   1096 }
   1097 
   1098 static void
   1099 dummy_handler(int sig __unused)
   1100 {
   1101 }
   1102 
   1103 /*
   1104  * wait for a process to terminate
   1105  */
   1106 
   1107 static pid_t
   1108 dowait(int mode, struct job *job)
   1109 {
   1110   struct sigaction sa, osa;
   1111   sigset_t         mask, omask;
   1112   pid_t            pid;
   1113   int              status;
   1114   struct procstat *sp;
   1115   struct job      *jp;
   1116   struct job      *thisjob;
   1117   const char      *sigstr;
   1118   int              done;
   1119   int              stopped;
   1120   int              sig;
   1121   int              coredump;
   1122   int              wflags;
   1123   int              restore_sigchld;
   1124 
   1125   TRACE(("dowait(%d, %p) called\n", mode, job));
   1126   restore_sigchld = 0;
   1127   if ((mode & DOWAIT_SIG) != 0) {
   1128     sigfillset(&mask);
   1129     sigprocmask(SIG_BLOCK, &mask, &omask);
   1130     INTOFF;
   1131     if (!issigchldtrapped()) {
   1132       restore_sigchld = 1;
   1133       sa.sa_handler   = dummy_handler;
   1134       sa.sa_flags     = 0;
   1135       sigemptyset(&sa.sa_mask);
   1136       sigaction(SIGCHLD, &sa, &osa);
   1137     }
   1138   }
   1139   do {
   1140 #if JOBS
   1141     if (iflag)
   1142       wflags = WUNTRACED | WCONTINUED;
   1143     else
   1144 #endif
   1145       wflags = 0;
   1146     if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
   1147       wflags |= WNOHANG;
   1148     pid = wait3(&status, wflags, (struct rusage *)NULL);
   1149     TRACE(("wait returns %d, status=%d\n", (int)pid, status));
   1150     if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
   1151       pid = -1;
   1152       if (((mode & DOWAIT_SIG_TRAP) != 0 ? pendingsig : pendingsig_waitcmd) != 0) {
   1153         errno = EINTR;
   1154         break;
   1155       }
   1156       sigsuspend(&omask);
   1157       if (int_pending())
   1158         break;
   1159     }
   1160   } while (pid == -1 && errno == EINTR);
   1161   if (pid == -1 && errno == ECHILD && job != NULL)
   1162     job->state = JOBDONE;
   1163   if ((mode & DOWAIT_SIG) != 0) {
   1164     if (restore_sigchld)
   1165       sigaction(SIGCHLD, &osa, NULL);
   1166     sigprocmask(SIG_SETMASK, &omask, NULL);
   1167     INTON;
   1168   }
   1169   if (pid <= 0)
   1170     return pid;
   1171   INTOFF;
   1172   thisjob = NULL;
   1173   for (jp = jobtab; jp < jobtab + njobs; jp++) {
   1174     if (jp->used && jp->nprocs > 0) {
   1175       done    = 1;
   1176       stopped = 1;
   1177       for (sp = jp->ps; sp < jp->ps + jp->nprocs; sp++) {
   1178         if (sp->pid == -1)
   1179           continue;
   1180         if (sp->pid == pid && (sp->status == -1 || WIFSTOPPED(sp->status))) {
   1181           TRACE(
   1182               ("Changing status of proc %d "
   1183                "from 0x%x to 0x%x\n",
   1184                (int)pid,
   1185                sp->status,
   1186                status)
   1187           );
   1188           if (WIFCONTINUED(status)) {
   1189             sp->status = -1;
   1190             jp->state  = 0;
   1191           } else
   1192             sp->status = status;
   1193           thisjob = jp;
   1194         }
   1195         if (sp->status == -1)
   1196           stopped = 0;
   1197         else if (WIFSTOPPED(sp->status))
   1198           done = 0;
   1199       }
   1200       if (stopped) { /* stopped or done */
   1201         int state = done ? JOBDONE : JOBSTOPPED;
   1202         if (jp->state != state) {
   1203           TRACE(
   1204               ("Job %td: changing state from "
   1205                "%d to %d\n",
   1206                jp - jobtab + 1,
   1207                jp->state,
   1208                state)
   1209           );
   1210           jp->state = state;
   1211           if (jp != job) {
   1212             if (done && !jp->remembered && !iflag && jp != bgjob)
   1213               freejob(jp);
   1214 #if JOBS
   1215             else if (done)
   1216               deljob(jp);
   1217 #endif
   1218           }
   1219         }
   1220       }
   1221     }
   1222   }
   1223   INTON;
   1224   if (!thisjob || thisjob->state == 0)
   1225     ;
   1226   else if (
   1227       (!rootshell || !iflag || thisjob == job) && thisjob->foreground
   1228       && thisjob->state != JOBSTOPPED
   1229   ) {
   1230     sig      = 0;
   1231     coredump = 0;
   1232     for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
   1233       if (WIFSIGNALED(sp->status)) {
   1234         sig      = WTERMSIG(sp->status);
   1235         coredump = WCOREDUMP(sp->status);
   1236       }
   1237     if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
   1238       sigstr = strsignal(sig);
   1239       if (sigstr != NULL)
   1240         out2str(sigstr);
   1241       else
   1242         out2str("Unknown signal");
   1243       if (coredump)
   1244         out2str(" (core dumped)");
   1245       out2c('\n');
   1246       flushout(out2);
   1247     }
   1248   } else {
   1249     TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
   1250     thisjob->changed = 1;
   1251   }
   1252   return pid;
   1253 }
   1254 
   1255 /*
   1256  * return 1 if there are stopped jobs, otherwise 0
   1257  */
   1258 int job_warning = 0;
   1259 int
   1260 stoppedjobs(void)
   1261 {
   1262   int         jobno;
   1263   struct job *jp;
   1264 
   1265   if (job_warning)
   1266     return (0);
   1267   for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1268     if (jp->used == 0)
   1269       continue;
   1270     if (jp->state == JOBSTOPPED) {
   1271       out2fmt_flush("You have stopped jobs.\n");
   1272       job_warning = 2;
   1273       return (1);
   1274     }
   1275   }
   1276 
   1277   return (0);
   1278 }
   1279 
   1280 static void
   1281 checkzombies(void)
   1282 {
   1283   while (njobs > 0 && dowait(0, NULL) > 0)
   1284     ;
   1285 }
   1286 
   1287 int
   1288 backgndpidset(void)
   1289 {
   1290   return backgndpid != -1;
   1291 }
   1292 
   1293 pid_t
   1294 backgndpidval(void)
   1295 {
   1296   if (bgjob != NULL && !forcelocal)
   1297     bgjob->remembered = 1;
   1298   return backgndpid;
   1299 }
   1300 
   1301 /*
   1302  * return a string identifying a command (to be printed by the
   1303  * jobs command
   1304  */
   1305 
   1306 static char *cmdnextc;
   1307 static int   cmdnleft;
   1308 #define MAXCMDTEXT 200
   1309 
   1310 char *
   1311 commandtext(union node *n)
   1312 {
   1313   char *name;
   1314 
   1315   cmdnextc = name = ckmalloc(MAXCMDTEXT);
   1316   cmdnleft        = MAXCMDTEXT - 4;
   1317   cmdtxt(n);
   1318   *cmdnextc = '\0';
   1319   return name;
   1320 }
   1321 
   1322 static void
   1323 cmdtxtdogroup(union node *n)
   1324 {
   1325   cmdputs("; do ");
   1326   cmdtxt(n);
   1327   cmdputs("; done");
   1328 }
   1329 
   1330 static void
   1331 cmdtxtredir(union node *n, const char *op, int deffd)
   1332 {
   1333   char s[2];
   1334 
   1335   if (n->nfile.fd != deffd) {
   1336     s[0] = n->nfile.fd + '0';
   1337     s[1] = '\0';
   1338     cmdputs(s);
   1339   }
   1340   cmdputs(op);
   1341   if (n->type == NTOFD || n->type == NFROMFD) {
   1342     if (n->ndup.dupfd >= 0)
   1343       s[0] = n->ndup.dupfd + '0';
   1344     else
   1345       s[0] = '-';
   1346     s[1] = '\0';
   1347     cmdputs(s);
   1348   } else {
   1349     cmdtxt(n->nfile.fname);
   1350   }
   1351 }
   1352 
   1353 static void
   1354 cmdtxt(union node *n)
   1355 {
   1356   union node      *np;
   1357   struct nodelist *lp;
   1358 
   1359   if (n == NULL)
   1360     return;
   1361   switch (n->type) {
   1362     case NSEMI:
   1363       cmdtxt(n->nbinary.ch1);
   1364       cmdputs("; ");
   1365       cmdtxt(n->nbinary.ch2);
   1366       break;
   1367     case NAND:
   1368       cmdtxt(n->nbinary.ch1);
   1369       cmdputs(" && ");
   1370       cmdtxt(n->nbinary.ch2);
   1371       break;
   1372     case NOR:
   1373       cmdtxt(n->nbinary.ch1);
   1374       cmdputs(" || ");
   1375       cmdtxt(n->nbinary.ch2);
   1376       break;
   1377     case NPIPE:
   1378       for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
   1379         cmdtxt(lp->n);
   1380         if (lp->next)
   1381           cmdputs(" | ");
   1382       }
   1383       break;
   1384     case NSUBSHELL:
   1385       cmdputs("(");
   1386       cmdtxt(n->nredir.n);
   1387       cmdputs(")");
   1388       break;
   1389     case NREDIR:
   1390     case NBACKGND:
   1391       cmdtxt(n->nredir.n);
   1392       break;
   1393     case NIF:
   1394       cmdputs("if ");
   1395       cmdtxt(n->nif.test);
   1396       cmdputs("; then ");
   1397       cmdtxt(n->nif.ifpart);
   1398       cmdputs("...");
   1399       break;
   1400     case NWHILE:
   1401       cmdputs("while ");
   1402       cmdtxt(n->nbinary.ch1);
   1403       cmdtxtdogroup(n->nbinary.ch2);
   1404       break;
   1405     case NUNTIL:
   1406       cmdputs("until ");
   1407       cmdtxt(n->nbinary.ch1);
   1408       cmdtxtdogroup(n->nbinary.ch2);
   1409       break;
   1410     case NFOR:
   1411       cmdputs("for ");
   1412       cmdputs(n->nfor.var);
   1413       cmdputs(" in ...");
   1414       break;
   1415     case NCASE:
   1416       cmdputs("case ");
   1417       cmdputs(n->ncase.expr->narg.text);
   1418       cmdputs(" in ...");
   1419       break;
   1420     case NDEFUN:
   1421       cmdputs(n->narg.text);
   1422       cmdputs("() ...");
   1423       break;
   1424     case NNOT:
   1425       cmdputs("! ");
   1426       cmdtxt(n->nnot.com);
   1427       break;
   1428     case NCMD:
   1429       for (np = n->ncmd.args; np; np = np->narg.next) {
   1430         cmdtxt(np);
   1431         if (np->narg.next)
   1432           cmdputs(" ");
   1433       }
   1434       for (np = n->ncmd.redirect; np; np = np->nfile.next) {
   1435         cmdputs(" ");
   1436         cmdtxt(np);
   1437       }
   1438       break;
   1439     case NARG:
   1440       cmdputs(n->narg.text);
   1441       break;
   1442     case NTO:
   1443       cmdtxtredir(n, ">", 1);
   1444       break;
   1445     case NAPPEND:
   1446       cmdtxtredir(n, ">>", 1);
   1447       break;
   1448     case NTOFD:
   1449       cmdtxtredir(n, ">&", 1);
   1450       break;
   1451     case NCLOBBER:
   1452       cmdtxtredir(n, ">|", 1);
   1453       break;
   1454     case NFROM:
   1455       cmdtxtredir(n, "<", 0);
   1456       break;
   1457     case NFROMTO:
   1458       cmdtxtredir(n, "<>", 0);
   1459       break;
   1460     case NFROMFD:
   1461       cmdtxtredir(n, "<&", 0);
   1462       break;
   1463     case NHERE:
   1464     case NXHERE:
   1465       cmdputs("<<...");
   1466       break;
   1467     default:
   1468       cmdputs("???");
   1469       break;
   1470   }
   1471 }
   1472 
   1473 static void
   1474 cmdputs(const char *s)
   1475 {
   1476   const char *p;
   1477   char       *q;
   1478   char        c;
   1479   int         subtype = 0;
   1480 
   1481   if (cmdnleft <= 0)
   1482     return;
   1483   p = s;
   1484   q = cmdnextc;
   1485   while ((c = *p++) != '\0') {
   1486     if (c == CTLESC)
   1487       *q++ = *p++;
   1488     else if (c == CTLVAR) {
   1489       *q++ = '$';
   1490       if (--cmdnleft > 0)
   1491         *q++ = '{';
   1492       subtype = *p++;
   1493       if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
   1494         *q++ = '#';
   1495     } else if (c == '=' && subtype != 0) {
   1496       *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
   1497       if (*q)
   1498         q++;
   1499       else
   1500         cmdnleft++;
   1501       if (((subtype & VSTYPE) == VSTRIMLEFTMAX || (subtype & VSTYPE) == VSTRIMRIGHTMAX)
   1502           && --cmdnleft > 0)
   1503         *q = q[-1], q++;
   1504       subtype = 0;
   1505     } else if (c == CTLENDVAR) {
   1506       *q++ = '}';
   1507     } else if (c == CTLBACKQ || c == CTLBACKQ + CTLQUOTE) {
   1508       cmdnleft -= 5;
   1509       if (cmdnleft > 0) {
   1510         *q++ = '$';
   1511         *q++ = '(';
   1512         *q++ = '.';
   1513         *q++ = '.';
   1514         *q++ = '.';
   1515         *q++ = ')';
   1516       }
   1517     } else if (c == CTLARI) {
   1518       cmdnleft -= 2;
   1519       if (cmdnleft > 0) {
   1520         *q++ = '$';
   1521         *q++ = '(';
   1522         *q++ = '(';
   1523       }
   1524       p++;
   1525     } else if (c == CTLENDARI) {
   1526       if (--cmdnleft > 0) {
   1527         *q++ = ')';
   1528         *q++ = ')';
   1529       }
   1530     } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
   1531       cmdnleft++; /* ignore */
   1532     else
   1533       *q++ = c;
   1534     if (--cmdnleft <= 0) {
   1535       *q++ = '.';
   1536       *q++ = '.';
   1537       *q++ = '.';
   1538       break;
   1539     }
   1540   }
   1541   cmdnextc = q;
   1542 }