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