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