Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.70
      1 /*	$NetBSD: jobs.c,v 1.70 2012/02/23 18:23:33 joerg Exp $	*/
      2 
      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 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: jobs.c,v 1.70 2012/02/23 18:23:33 joerg Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <fcntl.h>
     45 #include <signal.h>
     46 #include <errno.h>
     47 #include <unistd.h>
     48 #include <stdlib.h>
     49 #include <paths.h>
     50 #include <sys/types.h>
     51 #include <sys/param.h>
     52 #ifdef BSD
     53 #include <sys/wait.h>
     54 #include <sys/time.h>
     55 #include <sys/resource.h>
     56 #endif
     57 #include <sys/ioctl.h>
     58 
     59 #include "shell.h"
     60 #if JOBS
     61 #if OLD_TTY_DRIVER
     62 #include "sgtty.h"
     63 #else
     64 #include <termios.h>
     65 #endif
     66 #undef CEOF			/* syntax.h redefines this */
     67 #endif
     68 #include "redir.h"
     69 #include "show.h"
     70 #include "main.h"
     71 #include "parser.h"
     72 #include "nodes.h"
     73 #include "jobs.h"
     74 #include "options.h"
     75 #include "builtins.h"
     76 #include "trap.h"
     77 #include "syntax.h"
     78 #include "input.h"
     79 #include "output.h"
     80 #include "memalloc.h"
     81 #include "error.h"
     82 #include "mystring.h"
     83 
     84 
     85 static struct job *jobtab;		/* array of jobs */
     86 static int njobs;			/* size of array */
     87 static int jobs_invalid;		/* set in child */
     88 MKINIT pid_t backgndpid = -1;	/* pid of last background process */
     89 #if JOBS
     90 int initialpgrp;		/* pgrp of shell on invocation */
     91 static int curjob = -1;		/* current job */
     92 #endif
     93 static int ttyfd = -1;
     94 
     95 STATIC void restartjob(struct job *);
     96 STATIC void freejob(struct job *);
     97 STATIC struct job *getjob(const char *, int);
     98 STATIC int dowait(int, struct job *);
     99 #define WBLOCK	1
    100 #define WNOFREE 2
    101 STATIC int waitproc(int, struct job *, int *);
    102 STATIC void cmdtxt(union node *);
    103 STATIC void cmdlist(union node *, int);
    104 STATIC void cmdputs(const char *);
    105 
    106 #ifdef SYSV
    107 STATIC int onsigchild(void);
    108 #endif
    109 
    110 #ifdef OLD_TTY_DRIVER
    111 static pid_t tcgetpgrp(int fd);
    112 static int tcsetpgrp(int fd, pid_t pgrp);
    113 
    114 static pid_t
    115 tcgetpgrp(int fd)
    116 {
    117 	pid_t pgrp;
    118 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
    119 		return -1;
    120 	else
    121 		return pgrp;
    122 }
    123 
    124 static int
    125 tcsetpgrp(int fd, pid_tpgrp)
    126 {
    127 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
    128 }
    129 #endif
    130 
    131 /*
    132  * Turn job control on and off.
    133  *
    134  * Note:  This code assumes that the third arg to ioctl is a character
    135  * pointer, which is true on Berkeley systems but not System V.  Since
    136  * System V doesn't have job control yet, this isn't a problem now.
    137  */
    138 
    139 MKINIT int jobctl;
    140 
    141 void
    142 setjobctl(int on)
    143 {
    144 #ifdef OLD_TTY_DRIVER
    145 	int ldisc;
    146 #endif
    147 
    148 	if (on == jobctl || rootshell == 0)
    149 		return;
    150 	if (on) {
    151 #if defined(FIOCLEX) || defined(FD_CLOEXEC)
    152 		int err;
    153 		int i;
    154 		if (ttyfd != -1)
    155 			close(ttyfd);
    156 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
    157 			for (i = 0; i < 3; i++) {
    158 				if (isatty(i) && (ttyfd = dup(i)) != -1)
    159 					break;
    160 			}
    161 			if (i == 3)
    162 				goto out;
    163 		}
    164 		/* Move to a high fd */
    165 		for (i = 10; i > 2; i--) {
    166 			if ((err = fcntl(ttyfd, F_DUPFD, (1 << i) - 1)) != -1)
    167 				break;
    168 		}
    169 		if (err != -1) {
    170 			close(ttyfd);
    171 			ttyfd = err;
    172 		}
    173 #ifdef FIOCLEX
    174 		err = ioctl(ttyfd, FIOCLEX, 0);
    175 #elif FD_CLOEXEC
    176 		err = fcntl(ttyfd, F_SETFD,
    177 		    fcntl(ttyfd, F_GETFD, 0) | FD_CLOEXEC);
    178 #endif
    179 		if (err == -1) {
    180 			close(ttyfd);
    181 			ttyfd = -1;
    182 			goto out;
    183 		}
    184 #else
    185 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
    186 		goto out;
    187 #endif
    188 		do { /* while we are in the background */
    189 			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
    190 out:
    191 				out2str("sh: can't access tty; job control turned off\n");
    192 				mflag = 0;
    193 				return;
    194 			}
    195 			if (initialpgrp == -1)
    196 				initialpgrp = getpgrp();
    197 			else if (initialpgrp != getpgrp()) {
    198 				killpg(0, SIGTTIN);
    199 				continue;
    200 			}
    201 		} while (0);
    202 
    203 #ifdef OLD_TTY_DRIVER
    204 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
    205 		    || ldisc != NTTYDISC) {
    206 			out2str("sh: need new tty driver to run job control; job control turned off\n");
    207 			mflag = 0;
    208 			return;
    209 		}
    210 #endif
    211 		setsignal(SIGTSTP, 0);
    212 		setsignal(SIGTTOU, 0);
    213 		setsignal(SIGTTIN, 0);
    214 		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
    215 			error("Cannot set process group (%s) at %d",
    216 			    strerror(errno), __LINE__);
    217 		if (tcsetpgrp(ttyfd, rootpid) == -1)
    218 			error("Cannot set tty process group (%s) at %d",
    219 			    strerror(errno), __LINE__);
    220 	} else { /* turning job control off */
    221 		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
    222 			error("Cannot set process group (%s) at %d",
    223 			    strerror(errno), __LINE__);
    224 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
    225 			error("Cannot set tty process group (%s) at %d",
    226 			    strerror(errno), __LINE__);
    227 		close(ttyfd);
    228 		ttyfd = -1;
    229 		setsignal(SIGTSTP, 0);
    230 		setsignal(SIGTTOU, 0);
    231 		setsignal(SIGTTIN, 0);
    232 	}
    233 	jobctl = on;
    234 }
    235 
    236 
    237 #ifdef mkinit
    238 INCLUDE <stdlib.h>
    239 
    240 SHELLPROC {
    241 	backgndpid = -1;
    242 #if JOBS
    243 	jobctl = 0;
    244 #endif
    245 }
    246 
    247 #endif
    248 
    249 
    250 
    251 #if JOBS
    252 int
    253 fgcmd(int argc, char **argv)
    254 {
    255 	struct job *jp;
    256 	int i;
    257 	int status;
    258 
    259 	nextopt("");
    260 	jp = getjob(*argptr, 0);
    261 	if (jp->jobctl == 0)
    262 		error("job not created under job control");
    263 	out1fmt("%s", jp->ps[0].cmd);
    264 	for (i = 1; i < jp->nprocs; i++)
    265 		out1fmt(" | %s", jp->ps[i].cmd );
    266 	out1c('\n');
    267 	flushall();
    268 
    269 	for (i = 0; i < jp->nprocs; i++)
    270 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
    271 		    break;
    272 
    273 	if (i >= jp->nprocs) {
    274 		error("Cannot set tty process group (%s) at %d",
    275 		    strerror(errno), __LINE__);
    276 	}
    277 	restartjob(jp);
    278 	INTOFF;
    279 	status = waitforjob(jp);
    280 	INTON;
    281 	return status;
    282 }
    283 
    284 static void
    285 set_curjob(struct job *jp, int mode)
    286 {
    287 	struct job *jp1, *jp2;
    288 	int i, ji;
    289 
    290 	ji = jp - jobtab;
    291 
    292 	/* first remove from list */
    293 	if (ji == curjob)
    294 		curjob = jp->prev_job;
    295 	else {
    296 		for (i = 0; i < njobs; i++) {
    297 			if (jobtab[i].prev_job != ji)
    298 				continue;
    299 			jobtab[i].prev_job = jp->prev_job;
    300 			break;
    301 		}
    302 	}
    303 
    304 	/* Then re-insert in correct position */
    305 	switch (mode) {
    306 	case 0:	/* job being deleted */
    307 		jp->prev_job = -1;
    308 		break;
    309 	case 1:	/* newly created job or backgrounded job,
    310 		   put after all stopped jobs. */
    311 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
    312 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
    313 				if (jp1->prev_job == -1)
    314 					break;
    315 				jp2 = jobtab + jp1->prev_job;
    316 				if (jp2->state != JOBSTOPPED)
    317 					break;
    318 			}
    319 			jp->prev_job = jp1->prev_job;
    320 			jp1->prev_job = ji;
    321 			break;
    322 		}
    323 		/* FALLTHROUGH */
    324 	case 2:	/* newly stopped job - becomes curjob */
    325 		jp->prev_job = curjob;
    326 		curjob = ji;
    327 		break;
    328 	}
    329 }
    330 
    331 int
    332 bgcmd(int argc, char **argv)
    333 {
    334 	struct job *jp;
    335 	int i;
    336 
    337 	nextopt("");
    338 	do {
    339 		jp = getjob(*argptr, 0);
    340 		if (jp->jobctl == 0)
    341 			error("job not created under job control");
    342 		set_curjob(jp, 1);
    343 		out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
    344 		for (i = 1; i < jp->nprocs; i++)
    345 			out1fmt(" | %s", jp->ps[i].cmd );
    346 		out1c('\n');
    347 		flushall();
    348 		restartjob(jp);
    349 	} while (*argptr && *++argptr);
    350 	return 0;
    351 }
    352 
    353 
    354 STATIC void
    355 restartjob(struct job *jp)
    356 {
    357 	struct procstat *ps;
    358 	int i;
    359 
    360 	if (jp->state == JOBDONE)
    361 		return;
    362 	INTOFF;
    363 	for (i = 0; i < jp->nprocs; i++)
    364 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
    365 			break;
    366 	if (i >= jp->nprocs)
    367 		error("Cannot continue job (%s)", strerror(errno));
    368 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
    369 		if (WIFSTOPPED(ps->status)) {
    370 			ps->status = -1;
    371 			jp->state = JOBRUNNING;
    372 		}
    373 	}
    374 	INTON;
    375 }
    376 #endif
    377 
    378 static void
    379 showjob(struct output *out, struct job *jp, int mode)
    380 {
    381 	int procno;
    382 	int st;
    383 	struct procstat *ps;
    384 	int col;
    385 	char s[64];
    386 
    387 #if JOBS
    388 	if (mode & SHOW_PGID) {
    389 		/* just output process (group) id of pipeline */
    390 		outfmt(out, "%ld\n", (long)jp->ps->pid);
    391 		return;
    392 	}
    393 #endif
    394 
    395 	procno = jp->nprocs;
    396 	if (!procno)
    397 		return;
    398 
    399 	if (mode & SHOW_PID)
    400 		mode |= SHOW_MULTILINE;
    401 
    402 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
    403 	    || (mode & SHOW_SIGNALLED)) {
    404 		/* See if we have more than one status to report */
    405 		ps = jp->ps;
    406 		st = ps->status;
    407 		do {
    408 			int st1 = ps->status;
    409 			if (st1 != st)
    410 				/* yes - need multi-line output */
    411 				mode |= SHOW_MULTILINE;
    412 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
    413 				continue;
    414 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
    415 			    && st1 != SIGINT && st1 != SIGPIPE))
    416 				mode |= SHOW_ISSIG;
    417 
    418 		} while (ps++, --procno);
    419 		procno = jp->nprocs;
    420 	}
    421 
    422 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
    423 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
    424 			TRACE(("showjob: freeing job %d\n", jp - jobtab + 1));
    425 			freejob(jp);
    426 		}
    427 		return;
    428 	}
    429 
    430 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
    431 		if (ps == jp->ps)
    432 			fmtstr(s, 16, "[%ld] %c ",
    433 				(long)(jp - jobtab + 1),
    434 #if JOBS
    435 				jp == jobtab + curjob ? '+' :
    436 				curjob != -1 && jp == jobtab +
    437 					    jobtab[curjob].prev_job ? '-' :
    438 #endif
    439 				' ');
    440 		else
    441 			fmtstr(s, 16, "      " );
    442 		col = strlen(s);
    443 		if (mode & SHOW_PID) {
    444 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
    445 			     col += strlen(s + col);
    446 		}
    447 		if (ps->status == -1) {
    448 			scopy("Running", s + col);
    449 		} else if (WIFEXITED(ps->status)) {
    450 			st = WEXITSTATUS(ps->status);
    451 			if (st)
    452 				fmtstr(s + col, 16, "Done(%d)", st);
    453 			else
    454 				fmtstr(s + col, 16, "Done");
    455 		} else {
    456 #if JOBS
    457 			if (WIFSTOPPED(ps->status))
    458 				st = WSTOPSIG(ps->status);
    459 			else /* WIFSIGNALED(ps->status) */
    460 #endif
    461 				st = WTERMSIG(ps->status);
    462 			st &= 0x7f;
    463 			if (st < NSIG && sys_siglist[st])
    464 				scopyn(sys_siglist[st], s + col, 32);
    465 			else
    466 				fmtstr(s + col, 16, "Signal %d", st);
    467 			if (WCOREDUMP(ps->status)) {
    468 				col += strlen(s + col);
    469 				scopyn(" (core dumped)", s + col,  64 - col);
    470 			}
    471 		}
    472 		col += strlen(s + col);
    473 		outstr(s, out);
    474 		do {
    475 			outc(' ', out);
    476 			col++;
    477 		} while (col < 30);
    478 		outstr(ps->cmd, out);
    479 		if (mode & SHOW_MULTILINE) {
    480 			if (procno > 0) {
    481 				outc(' ', out);
    482 				outc('|', out);
    483 			}
    484 		} else {
    485 			while (--procno >= 0)
    486 				outfmt(out, " | %s", (++ps)->cmd );
    487 		}
    488 		outc('\n', out);
    489 	}
    490 	flushout(out);
    491 	jp->changed = 0;
    492 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
    493 		freejob(jp);
    494 }
    495 
    496 
    497 int
    498 jobscmd(int argc, char **argv)
    499 {
    500 	int mode, m;
    501 	int sv = jobs_invalid;
    502 
    503 	jobs_invalid = 0;
    504 	mode = 0;
    505 	while ((m = nextopt("lp")))
    506 		if (m == 'l')
    507 			mode = SHOW_PID;
    508 		else
    509 			mode = SHOW_PGID;
    510 	if (*argptr)
    511 		do
    512 			showjob(out1, getjob(*argptr,0), mode);
    513 		while (*++argptr);
    514 	else
    515 		showjobs(out1, mode);
    516 	jobs_invalid = sv;
    517 	return 0;
    518 }
    519 
    520 
    521 /*
    522  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
    523  * statuses have changed since the last call to showjobs.
    524  *
    525  * If the shell is interrupted in the process of creating a job, the
    526  * result may be a job structure containing zero processes.  Such structures
    527  * will be freed here.
    528  */
    529 
    530 void
    531 showjobs(struct output *out, int mode)
    532 {
    533 	int jobno;
    534 	struct job *jp;
    535 	int silent = 0, gotpid;
    536 
    537 	TRACE(("showjobs(%x) called\n", mode));
    538 
    539 	/* If not even one one job changed, there is nothing to do */
    540 	gotpid = dowait(0, NULL);
    541 	while (dowait(0, NULL) > 0)
    542 		continue;
    543 #ifdef JOBS
    544 	/*
    545 	 * Check if we are not in our foreground group, and if not
    546 	 * put us in it.
    547 	 */
    548 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
    549 		if (tcsetpgrp(ttyfd, getpid()) == -1)
    550 			error("Cannot set tty process group (%s) at %d",
    551 			    strerror(errno), __LINE__);
    552 		TRACE(("repaired tty process group\n"));
    553 		silent = 1;
    554 	}
    555 #endif
    556 	if (jobs_invalid)
    557 		return;
    558 
    559 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
    560 		if (!jp->used)
    561 			continue;
    562 		if (jp->nprocs == 0) {
    563 			freejob(jp);
    564 			continue;
    565 		}
    566 		if ((mode & SHOW_CHANGED) && !jp->changed)
    567 			continue;
    568 		if (silent && jp->changed) {
    569 			jp->changed = 0;
    570 			continue;
    571 		}
    572 		showjob(out, jp, mode);
    573 	}
    574 }
    575 
    576 /*
    577  * Mark a job structure as unused.
    578  */
    579 
    580 STATIC void
    581 freejob(struct job *jp)
    582 {
    583 	INTOFF;
    584 	if (jp->ps != &jp->ps0) {
    585 		ckfree(jp->ps);
    586 		jp->ps = &jp->ps0;
    587 	}
    588 	jp->nprocs = 0;
    589 	jp->used = 0;
    590 #if JOBS
    591 	set_curjob(jp, 0);
    592 #endif
    593 	INTON;
    594 }
    595 
    596 
    597 
    598 int
    599 waitcmd(int argc, char **argv)
    600 {
    601 	struct job *job;
    602 	int status, retval;
    603 	struct job *jp;
    604 
    605 	nextopt("");
    606 
    607 	if (!*argptr) {
    608 		/* wait for all jobs */
    609 		jp = jobtab;
    610 		if (jobs_invalid)
    611 			return 0;
    612 		for (;;) {
    613 			if (jp >= jobtab + njobs) {
    614 				/* no running procs */
    615 				return 0;
    616 			}
    617 			if (!jp->used || jp->state != JOBRUNNING) {
    618 				jp++;
    619 				continue;
    620 			}
    621 			if (dowait(WBLOCK, NULL) == -1)
    622 			       return 128 + SIGINT;
    623 			jp = jobtab;
    624 		}
    625 	}
    626 
    627 	retval = 127;		/* XXXGCC: -Wuninitialized */
    628 	for (; *argptr; argptr++) {
    629 		job = getjob(*argptr, 1);
    630 		if (!job) {
    631 			retval = 127;
    632 			continue;
    633 		}
    634 		/* loop until process terminated or stopped */
    635 		while (job->state == JOBRUNNING) {
    636 			if (dowait(WBLOCK|WNOFREE, job) == -1)
    637 			       return 128 + SIGINT;
    638 		}
    639 		status = job->ps[job->nprocs - 1].status;
    640 		if (WIFEXITED(status))
    641 			retval = WEXITSTATUS(status);
    642 #if JOBS
    643 		else if (WIFSTOPPED(status))
    644 			retval = WSTOPSIG(status) + 128;
    645 #endif
    646 		else {
    647 			/* XXX: limits number of signals */
    648 			retval = WTERMSIG(status) + 128;
    649 		}
    650 		if (!iflag)
    651 			freejob(job);
    652 	}
    653 	return retval;
    654 }
    655 
    656 
    657 
    658 int
    659 jobidcmd(int argc, char **argv)
    660 {
    661 	struct job *jp;
    662 	int i;
    663 
    664 	nextopt("");
    665 	jp = getjob(*argptr, 0);
    666 	for (i = 0 ; i < jp->nprocs ; ) {
    667 		out1fmt("%ld", (long)jp->ps[i].pid);
    668 		out1c(++i < jp->nprocs ? ' ' : '\n');
    669 	}
    670 	return 0;
    671 }
    672 
    673 int
    674 getjobpgrp(const char *name)
    675 {
    676 	struct job *jp;
    677 
    678 	jp = getjob(name, 1);
    679 	if (jp == 0)
    680 		return 0;
    681 	return -jp->ps[0].pid;
    682 }
    683 
    684 /*
    685  * Convert a job name to a job structure.
    686  */
    687 
    688 STATIC struct job *
    689 getjob(const char *name, int noerror)
    690 {
    691 	int jobno = -1;
    692 	struct job *jp;
    693 	int pid;
    694 	int i;
    695 	const char *err_msg = "No such job: %s";
    696 
    697 	if (name == NULL) {
    698 #if JOBS
    699 		jobno = curjob;
    700 #endif
    701 		err_msg = "No current job";
    702 	} else if (name[0] == '%') {
    703 		if (is_number(name + 1)) {
    704 			jobno = number(name + 1) - 1;
    705 		} else if (!name[2]) {
    706 			switch (name[1]) {
    707 #if JOBS
    708 			case 0:
    709 			case '+':
    710 			case '%':
    711 				jobno = curjob;
    712 				err_msg = "No current job";
    713 				break;
    714 			case '-':
    715 				jobno = curjob;
    716 				if (jobno != -1)
    717 					jobno = jobtab[jobno].prev_job;
    718 				err_msg = "No previous job";
    719 				break;
    720 #endif
    721 			default:
    722 				goto check_pattern;
    723 			}
    724 		} else {
    725 			struct job *found;
    726     check_pattern:
    727 			found = NULL;
    728 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    729 				if (!jp->used || jp->nprocs <= 0)
    730 					continue;
    731 				if ((name[1] == '?'
    732 					&& strstr(jp->ps[0].cmd, name + 2))
    733 				    || prefix(name + 1, jp->ps[0].cmd)) {
    734 					if (found) {
    735 						err_msg = "%s: ambiguous";
    736 						found = 0;
    737 						break;
    738 					}
    739 					found = jp;
    740 				}
    741 			}
    742 			if (found)
    743 				return found;
    744 		}
    745 
    746 	} else if (is_number(name)) {
    747 		pid = number(name);
    748 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    749 			if (jp->used && jp->nprocs > 0
    750 			 && jp->ps[jp->nprocs - 1].pid == pid)
    751 				return jp;
    752 		}
    753 	}
    754 
    755 	if (!jobs_invalid && jobno >= 0 && jobno < njobs) {
    756 		jp = jobtab + jobno;
    757 		if (jp->used)
    758 			return jp;
    759 	}
    760 	if (!noerror)
    761 		error(err_msg, name);
    762 	return 0;
    763 }
    764 
    765 
    766 
    767 /*
    768  * Return a new job structure,
    769  */
    770 
    771 struct job *
    772 makejob(union node *node, int nprocs)
    773 {
    774 	int i;
    775 	struct job *jp;
    776 
    777 	if (jobs_invalid) {
    778 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
    779 			if (jp->used)
    780 				freejob(jp);
    781 		}
    782 		jobs_invalid = 0;
    783 	}
    784 
    785 	for (i = njobs, jp = jobtab ; ; jp++) {
    786 		if (--i < 0) {
    787 			INTOFF;
    788 			if (njobs == 0) {
    789 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
    790 			} else {
    791 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
    792 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
    793 				/* Relocate `ps' pointers */
    794 				for (i = 0; i < njobs; i++)
    795 					if (jp[i].ps == &jobtab[i].ps0)
    796 						jp[i].ps = &jp[i].ps0;
    797 				ckfree(jobtab);
    798 				jobtab = jp;
    799 			}
    800 			jp = jobtab + njobs;
    801 			for (i = 4 ; --i >= 0 ; )
    802 				jobtab[njobs++].used = 0;
    803 			INTON;
    804 			break;
    805 		}
    806 		if (jp->used == 0)
    807 			break;
    808 	}
    809 	INTOFF;
    810 	jp->state = JOBRUNNING;
    811 	jp->used = 1;
    812 	jp->changed = 0;
    813 	jp->nprocs = 0;
    814 #if JOBS
    815 	jp->jobctl = jobctl;
    816 	set_curjob(jp, 1);
    817 #endif
    818 	if (nprocs > 1) {
    819 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
    820 	} else {
    821 		jp->ps = &jp->ps0;
    822 	}
    823 	INTON;
    824 	TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
    825 	    jp - jobtab + 1));
    826 	return jp;
    827 }
    828 
    829 
    830 /*
    831  * Fork off a subshell.  If we are doing job control, give the subshell its
    832  * own process group.  Jp is a job structure that the job is to be added to.
    833  * N is the command that will be evaluated by the child.  Both jp and n may
    834  * be NULL.  The mode parameter can be one of the following:
    835  *	FORK_FG - Fork off a foreground process.
    836  *	FORK_BG - Fork off a background process.
    837  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
    838  *		     process group even if job control is on.
    839  *
    840  * When job control is turned off, background processes have their standard
    841  * input redirected to /dev/null (except for the second and later processes
    842  * in a pipeline).
    843  */
    844 
    845 int
    846 forkshell(struct job *jp, union node *n, int mode)
    847 {
    848 	int pid;
    849 
    850 	TRACE(("forkshell(%%%d, %p, %d) called\n", jp - jobtab, n, mode));
    851 	switch ((pid = fork())) {
    852 	case -1:
    853 		TRACE(("Fork failed, errno=%d\n", errno));
    854 		INTON;
    855 		error("Cannot fork");
    856 		break;
    857 	case 0:
    858 		forkchild(jp, n, mode, 0);
    859 		return 0;
    860 	default:
    861 		return forkparent(jp, n, mode, pid);
    862 	}
    863 }
    864 
    865 int
    866 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
    867 {
    868 	int pgrp;
    869 
    870 	if (rootshell && mode != FORK_NOJOB && mflag) {
    871 		if (jp == NULL || jp->nprocs == 0)
    872 			pgrp = pid;
    873 		else
    874 			pgrp = jp->ps[0].pid;
    875 		/* This can fail because we are doing it in the child also */
    876 		(void)setpgid(pid, pgrp);
    877 	}
    878 	if (mode == FORK_BG)
    879 		backgndpid = pid;		/* set $! */
    880 	if (jp) {
    881 		struct procstat *ps = &jp->ps[jp->nprocs++];
    882 		ps->pid = pid;
    883 		ps->status = -1;
    884 		ps->cmd[0] = 0;
    885 		if (/* iflag && rootshell && */ n)
    886 			commandtext(ps, n);
    887 	}
    888 	TRACE(("In parent shell:  child = %d\n", pid));
    889 	return pid;
    890 }
    891 
    892 void
    893 forkchild(struct job *jp, union node *n, int mode, int vforked)
    894 {
    895 	int wasroot;
    896 	int pgrp;
    897 	const char *devnull = _PATH_DEVNULL;
    898 	const char *nullerr = "Can't open %s";
    899 
    900 	wasroot = rootshell;
    901 	TRACE(("Child shell %d\n", getpid()));
    902 	if (!vforked)
    903 		rootshell = 0;
    904 
    905 	closescript(vforked);
    906 	clear_traps(vforked);
    907 #if JOBS
    908 	if (!vforked)
    909 		jobctl = 0;		/* do job control only in root shell */
    910 	if (wasroot && mode != FORK_NOJOB && mflag) {
    911 		if (jp == NULL || jp->nprocs == 0)
    912 			pgrp = getpid();
    913 		else
    914 			pgrp = jp->ps[0].pid;
    915 		/* This can fail because we are doing it in the parent also */
    916 		(void)setpgid(0, pgrp);
    917 		if (mode == FORK_FG) {
    918 			if (tcsetpgrp(ttyfd, pgrp) == -1)
    919 				error("Cannot set tty process group (%s) at %d",
    920 				    strerror(errno), __LINE__);
    921 		}
    922 		setsignal(SIGTSTP, vforked);
    923 		setsignal(SIGTTOU, vforked);
    924 	} else if (mode == FORK_BG) {
    925 		ignoresig(SIGINT, vforked);
    926 		ignoresig(SIGQUIT, vforked);
    927 		if ((jp == NULL || jp->nprocs == 0) &&
    928 		    ! fd0_redirected_p ()) {
    929 			close(0);
    930 			if (open(devnull, O_RDONLY) != 0)
    931 				error(nullerr, devnull);
    932 		}
    933 	}
    934 #else
    935 	if (mode == FORK_BG) {
    936 		ignoresig(SIGINT, vforked);
    937 		ignoresig(SIGQUIT, vforked);
    938 		if ((jp == NULL || jp->nprocs == 0) &&
    939 		    ! fd0_redirected_p ()) {
    940 			close(0);
    941 			if (open(devnull, O_RDONLY) != 0)
    942 				error(nullerr, devnull);
    943 		}
    944 	}
    945 #endif
    946 	if (wasroot && iflag) {
    947 		setsignal(SIGINT, vforked);
    948 		setsignal(SIGQUIT, vforked);
    949 		setsignal(SIGTERM, vforked);
    950 	}
    951 
    952 	if (!vforked)
    953 		jobs_invalid = 1;
    954 }
    955 
    956 /*
    957  * Wait for job to finish.
    958  *
    959  * Under job control we have the problem that while a child process is
    960  * running interrupts generated by the user are sent to the child but not
    961  * to the shell.  This means that an infinite loop started by an inter-
    962  * active user may be hard to kill.  With job control turned off, an
    963  * interactive user may place an interactive program inside a loop.  If
    964  * the interactive program catches interrupts, the user doesn't want
    965  * these interrupts to also abort the loop.  The approach we take here
    966  * is to have the shell ignore interrupt signals while waiting for a
    967  * forground process to terminate, and then send itself an interrupt
    968  * signal if the child process was terminated by an interrupt signal.
    969  * Unfortunately, some programs want to do a bit of cleanup and then
    970  * exit on interrupt; unless these processes terminate themselves by
    971  * sending a signal to themselves (instead of calling exit) they will
    972  * confuse this approach.
    973  */
    974 
    975 int
    976 waitforjob(struct job *jp)
    977 {
    978 #if JOBS
    979 	int mypgrp = getpgrp();
    980 #endif
    981 	int status;
    982 	int st;
    983 
    984 	INTOFF;
    985 	TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
    986 	while (jp->state == JOBRUNNING) {
    987 		dowait(WBLOCK, jp);
    988 	}
    989 #if JOBS
    990 	if (jp->jobctl) {
    991 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
    992 			error("Cannot set tty process group (%s) at %d",
    993 			    strerror(errno), __LINE__);
    994 	}
    995 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
    996 		set_curjob(jp, 2);
    997 #endif
    998 	status = jp->ps[jp->nprocs - 1].status;
    999 	/* convert to 8 bits */
   1000 	if (WIFEXITED(status))
   1001 		st = WEXITSTATUS(status);
   1002 #if JOBS
   1003 	else if (WIFSTOPPED(status))
   1004 		st = WSTOPSIG(status) + 128;
   1005 #endif
   1006 	else
   1007 		st = WTERMSIG(status) + 128;
   1008 	TRACE(("waitforjob: job %d, nproc %d, status %x, st %x\n",
   1009 		jp - jobtab + 1, jp->nprocs, status, st ));
   1010 #if JOBS
   1011 	if (jp->jobctl) {
   1012 		/*
   1013 		 * This is truly gross.
   1014 		 * If we're doing job control, then we did a TIOCSPGRP which
   1015 		 * caused us (the shell) to no longer be in the controlling
   1016 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1017 		 * intuit from the subprocess exit status whether a SIGINT
   1018 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1019 		 */
   1020 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1021 			raise(SIGINT);
   1022 	}
   1023 #endif
   1024 	if (! JOBS || jp->state == JOBDONE)
   1025 		freejob(jp);
   1026 	INTON;
   1027 	return st;
   1028 }
   1029 
   1030 
   1031 
   1032 /*
   1033  * Wait for a process to terminate.
   1034  */
   1035 
   1036 STATIC int
   1037 dowait(int flags, struct job *job)
   1038 {
   1039 	int pid;
   1040 	int status;
   1041 	struct procstat *sp;
   1042 	struct job *jp;
   1043 	struct job *thisjob;
   1044 	int done;
   1045 	int stopped;
   1046 	extern volatile char gotsig[];
   1047 
   1048 	TRACE(("dowait(%x) called\n", flags));
   1049 	do {
   1050 		pid = waitproc(flags & WBLOCK, job, &status);
   1051 		TRACE(("wait returns pid %d, status %d\n", pid, status));
   1052 	} while (pid == -1 && errno == EINTR && gotsig[SIGINT - 1] == 0);
   1053 	if (pid <= 0)
   1054 		return pid;
   1055 	INTOFF;
   1056 	thisjob = NULL;
   1057 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1058 		if (jp->used) {
   1059 			done = 1;
   1060 			stopped = 1;
   1061 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1062 				if (sp->pid == -1)
   1063 					continue;
   1064 				if (sp->pid == pid) {
   1065 					TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jp - jobtab + 1, pid, sp->status, status));
   1066 					sp->status = status;
   1067 					thisjob = jp;
   1068 				}
   1069 				if (sp->status == -1)
   1070 					stopped = 0;
   1071 				else if (WIFSTOPPED(sp->status))
   1072 					done = 0;
   1073 			}
   1074 			if (stopped) {		/* stopped or done */
   1075 				int state = done ? JOBDONE : JOBSTOPPED;
   1076 				if (jp->state != state) {
   1077 					TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
   1078 					jp->state = state;
   1079 #if JOBS
   1080 					if (done)
   1081 						set_curjob(jp, 0);
   1082 #endif
   1083 				}
   1084 			}
   1085 		}
   1086 	}
   1087 
   1088 	if (thisjob && thisjob->state != JOBRUNNING) {
   1089 		int mode = 0;
   1090 		if (!rootshell || !iflag)
   1091 			mode = SHOW_SIGNALLED;
   1092 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1093 		    (job != thisjob && (flags & WNOFREE) != 0))
   1094 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1095 		if (mode)
   1096 			showjob(out2, thisjob, mode);
   1097 		else {
   1098 			TRACE(("Not printing status, rootshell=%d, job=%p\n",
   1099 				rootshell, job));
   1100 			thisjob->changed = 1;
   1101 		}
   1102 	}
   1103 
   1104 	INTON;
   1105 	return pid;
   1106 }
   1107 
   1108 
   1109 
   1110 /*
   1111  * Do a wait system call.  If job control is compiled in, we accept
   1112  * stopped processes.  If block is zero, we return a value of zero
   1113  * rather than blocking.
   1114  *
   1115  * System V doesn't have a non-blocking wait system call.  It does
   1116  * have a SIGCLD signal that is sent to a process when one of its
   1117  * children dies.  The obvious way to use SIGCLD would be to install
   1118  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1119  * was received, and have waitproc bump another counter when it got
   1120  * the status of a process.  Waitproc would then know that a wait
   1121  * system call would not block if the two counters were different.
   1122  * This approach doesn't work because if a process has children that
   1123  * have not been waited for, System V will send it a SIGCLD when it
   1124  * installs a signal handler for SIGCLD.  What this means is that when
   1125  * a child exits, the shell will be sent SIGCLD signals continuously
   1126  * until is runs out of stack space, unless it does a wait call before
   1127  * restoring the signal handler.  The code below takes advantage of
   1128  * this (mis)feature by installing a signal handler for SIGCLD and
   1129  * then checking to see whether it was called.  If there are any
   1130  * children to be waited for, it will be.
   1131  *
   1132  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1133  * waits at all.  In this case, the user will not be informed when
   1134  * a background process until the next time she runs a real program
   1135  * (as opposed to running a builtin command or just typing return),
   1136  * and the jobs command may give out of date information.
   1137  */
   1138 
   1139 #ifdef SYSV
   1140 STATIC int gotsigchild;
   1141 
   1142 STATIC int onsigchild() {
   1143 	gotsigchild = 1;
   1144 }
   1145 #endif
   1146 
   1147 
   1148 STATIC int
   1149 waitproc(int block, struct job *jp, int *status)
   1150 {
   1151 #ifdef BSD
   1152 	int flags = 0;
   1153 
   1154 #if JOBS
   1155 	if (jp != NULL && jp->jobctl)
   1156 		flags |= WUNTRACED;
   1157 #endif
   1158 	if (block == 0)
   1159 		flags |= WNOHANG;
   1160 	return waitpid(-1, status, flags);
   1161 #else
   1162 #ifdef SYSV
   1163 	int (*save)();
   1164 
   1165 	if (block == 0) {
   1166 		gotsigchild = 0;
   1167 		save = signal(SIGCLD, onsigchild);
   1168 		signal(SIGCLD, save);
   1169 		if (gotsigchild == 0)
   1170 			return 0;
   1171 	}
   1172 	return wait(status);
   1173 #else
   1174 	if (block == 0)
   1175 		return 0;
   1176 	return wait(status);
   1177 #endif
   1178 #endif
   1179 }
   1180 
   1181 /*
   1182  * return 1 if there are stopped jobs, otherwise 0
   1183  */
   1184 int job_warning = 0;
   1185 int
   1186 stoppedjobs(void)
   1187 {
   1188 	int jobno;
   1189 	struct job *jp;
   1190 
   1191 	if (job_warning || jobs_invalid)
   1192 		return (0);
   1193 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1194 		if (jp->used == 0)
   1195 			continue;
   1196 		if (jp->state == JOBSTOPPED) {
   1197 			out2str("You have stopped jobs.\n");
   1198 			job_warning = 2;
   1199 			return (1);
   1200 		}
   1201 	}
   1202 
   1203 	return (0);
   1204 }
   1205 
   1206 /*
   1207  * Return a string identifying a command (to be printed by the
   1208  * jobs command).
   1209  */
   1210 
   1211 STATIC char *cmdnextc;
   1212 STATIC int cmdnleft;
   1213 
   1214 void
   1215 commandtext(struct procstat *ps, union node *n)
   1216 {
   1217 	int len;
   1218 
   1219 	cmdnextc = ps->cmd;
   1220 	if (iflag || mflag || sizeof ps->cmd < 100)
   1221 		len = sizeof(ps->cmd);
   1222 	else
   1223 		len = sizeof(ps->cmd) / 10;
   1224 	cmdnleft = len;
   1225 	cmdtxt(n);
   1226 	if (cmdnleft <= 0) {
   1227 		char *p = ps->cmd + len - 4;
   1228 		p[0] = '.';
   1229 		p[1] = '.';
   1230 		p[2] = '.';
   1231 		p[3] = 0;
   1232 	} else
   1233 		*cmdnextc = '\0';
   1234 	TRACE(("commandtext: ps->cmd %x, end %x, left %d\n\t\"%s\"\n",
   1235 		ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1236 }
   1237 
   1238 
   1239 STATIC void
   1240 cmdtxt(union node *n)
   1241 {
   1242 	union node *np;
   1243 	struct nodelist *lp;
   1244 	const char *p;
   1245 	int i;
   1246 	char s[2];
   1247 
   1248 	if (n == NULL || cmdnleft <= 0)
   1249 		return;
   1250 	switch (n->type) {
   1251 	case NSEMI:
   1252 		cmdtxt(n->nbinary.ch1);
   1253 		cmdputs("; ");
   1254 		cmdtxt(n->nbinary.ch2);
   1255 		break;
   1256 	case NAND:
   1257 		cmdtxt(n->nbinary.ch1);
   1258 		cmdputs(" && ");
   1259 		cmdtxt(n->nbinary.ch2);
   1260 		break;
   1261 	case NOR:
   1262 		cmdtxt(n->nbinary.ch1);
   1263 		cmdputs(" || ");
   1264 		cmdtxt(n->nbinary.ch2);
   1265 		break;
   1266 	case NPIPE:
   1267 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1268 			cmdtxt(lp->n);
   1269 			if (lp->next)
   1270 				cmdputs(" | ");
   1271 		}
   1272 		break;
   1273 	case NSUBSHELL:
   1274 		cmdputs("(");
   1275 		cmdtxt(n->nredir.n);
   1276 		cmdputs(")");
   1277 		break;
   1278 	case NREDIR:
   1279 	case NBACKGND:
   1280 		cmdtxt(n->nredir.n);
   1281 		break;
   1282 	case NIF:
   1283 		cmdputs("if ");
   1284 		cmdtxt(n->nif.test);
   1285 		cmdputs("; then ");
   1286 		cmdtxt(n->nif.ifpart);
   1287 		if (n->nif.elsepart) {
   1288 			cmdputs("; else ");
   1289 			cmdtxt(n->nif.elsepart);
   1290 		}
   1291 		cmdputs("; fi");
   1292 		break;
   1293 	case NWHILE:
   1294 		cmdputs("while ");
   1295 		goto until;
   1296 	case NUNTIL:
   1297 		cmdputs("until ");
   1298 until:
   1299 		cmdtxt(n->nbinary.ch1);
   1300 		cmdputs("; do ");
   1301 		cmdtxt(n->nbinary.ch2);
   1302 		cmdputs("; done");
   1303 		break;
   1304 	case NFOR:
   1305 		cmdputs("for ");
   1306 		cmdputs(n->nfor.var);
   1307 		cmdputs(" in ");
   1308 		cmdlist(n->nfor.args, 1);
   1309 		cmdputs("; do ");
   1310 		cmdtxt(n->nfor.body);
   1311 		cmdputs("; done");
   1312 		break;
   1313 	case NCASE:
   1314 		cmdputs("case ");
   1315 		cmdputs(n->ncase.expr->narg.text);
   1316 		cmdputs(" in ");
   1317 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1318 			cmdtxt(np->nclist.pattern);
   1319 			cmdputs(") ");
   1320 			cmdtxt(np->nclist.body);
   1321 			cmdputs(";; ");
   1322 		}
   1323 		cmdputs("esac");
   1324 		break;
   1325 	case NDEFUN:
   1326 		cmdputs(n->narg.text);
   1327 		cmdputs("() { ... }");
   1328 		break;
   1329 	case NCMD:
   1330 		cmdlist(n->ncmd.args, 1);
   1331 		cmdlist(n->ncmd.redirect, 0);
   1332 		break;
   1333 	case NARG:
   1334 		cmdputs(n->narg.text);
   1335 		break;
   1336 	case NTO:
   1337 		p = ">";  i = 1;  goto redir;
   1338 	case NCLOBBER:
   1339 		p = ">|";  i = 1;  goto redir;
   1340 	case NAPPEND:
   1341 		p = ">>";  i = 1;  goto redir;
   1342 	case NTOFD:
   1343 		p = ">&";  i = 1;  goto redir;
   1344 	case NFROM:
   1345 		p = "<";  i = 0;  goto redir;
   1346 	case NFROMFD:
   1347 		p = "<&";  i = 0;  goto redir;
   1348 	case NFROMTO:
   1349 		p = "<>";  i = 0;  goto redir;
   1350 redir:
   1351 		if (n->nfile.fd != i) {
   1352 			s[0] = n->nfile.fd + '0';
   1353 			s[1] = '\0';
   1354 			cmdputs(s);
   1355 		}
   1356 		cmdputs(p);
   1357 		if (n->type == NTOFD || n->type == NFROMFD) {
   1358 			s[0] = n->ndup.dupfd + '0';
   1359 			s[1] = '\0';
   1360 			cmdputs(s);
   1361 		} else {
   1362 			cmdtxt(n->nfile.fname);
   1363 		}
   1364 		break;
   1365 	case NHERE:
   1366 	case NXHERE:
   1367 		cmdputs("<<...");
   1368 		break;
   1369 	default:
   1370 		cmdputs("???");
   1371 		break;
   1372 	}
   1373 }
   1374 
   1375 STATIC void
   1376 cmdlist(union node *np, int sep)
   1377 {
   1378 	for (; np; np = np->narg.next) {
   1379 		if (!sep)
   1380 			cmdputs(" ");
   1381 		cmdtxt(np);
   1382 		if (sep && np->narg.next)
   1383 			cmdputs(" ");
   1384 	}
   1385 }
   1386 
   1387 
   1388 STATIC void
   1389 cmdputs(const char *s)
   1390 {
   1391 	const char *p, *str = 0;
   1392 	char c, cc[2] = " ";
   1393 	char *nextc;
   1394 	int nleft;
   1395 	int subtype = 0;
   1396 	int quoted = 0;
   1397 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1398 					"#", "##", "%", "%%" };
   1399 
   1400 	p = s;
   1401 	nextc = cmdnextc;
   1402 	nleft = cmdnleft;
   1403 	while (nleft > 0 && (c = *p++) != 0) {
   1404 		switch (c) {
   1405 		case CTLESC:
   1406 			c = *p++;
   1407 			break;
   1408 		case CTLVAR:
   1409 			subtype = *p++;
   1410 			if ((subtype & VSTYPE) == VSLENGTH)
   1411 				str = "${#";
   1412 			else
   1413 				str = "${";
   1414 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1415 				quoted ^= 1;
   1416 				c = '"';
   1417 			} else
   1418 				c = *str++;
   1419 			break;
   1420 		case CTLENDVAR:
   1421 			if (quoted & 1) {
   1422 				c = '"';
   1423 				str = "}";
   1424 			} else
   1425 				c = '}';
   1426 			quoted >>= 1;
   1427 			subtype = 0;
   1428 			break;
   1429 		case CTLBACKQ:
   1430 			c = '$';
   1431 			str = "(...)";
   1432 			break;
   1433 		case CTLBACKQ+CTLQUOTE:
   1434 			c = '"';
   1435 			str = "$(...)\"";
   1436 			break;
   1437 		case CTLARI:
   1438 			c = '$';
   1439 			str = "((";
   1440 			break;
   1441 		case CTLENDARI:
   1442 			c = ')';
   1443 			str = ")";
   1444 			break;
   1445 		case CTLQUOTEMARK:
   1446 			quoted ^= 1;
   1447 			c = '"';
   1448 			break;
   1449 		case '=':
   1450 			if (subtype == 0)
   1451 				break;
   1452 			str = vstype[subtype & VSTYPE];
   1453 			if (subtype & VSNUL)
   1454 				c = ':';
   1455 			else
   1456 				c = *str++;
   1457 			if (c != '}')
   1458 				quoted <<= 1;
   1459 			break;
   1460 		case '\'':
   1461 		case '\\':
   1462 		case '"':
   1463 		case '$':
   1464 			/* These can only happen inside quotes */
   1465 			cc[0] = c;
   1466 			str = cc;
   1467 			c = '\\';
   1468 			break;
   1469 		default:
   1470 			break;
   1471 		}
   1472 		do {
   1473 			*nextc++ = c;
   1474 		} while (--nleft > 0 && str && (c = *str++));
   1475 		str = 0;
   1476 	}
   1477 	if ((quoted & 1) && nleft) {
   1478 		*nextc++ = '"';
   1479 		nleft--;
   1480 	}
   1481 	cmdnleft = nleft;
   1482 	cmdnextc = nextc;
   1483 }
   1484