• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$OpenBSD: jobs.c,v 1.43 2015/09/10 22:48:58 nicm Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
5  *		 2012, 2013, 2014, 2015, 2016, 2018, 2019
6  *	mirabilos <m@mirbsd.org>
7  *
8  * Provided that these terms and disclaimer and all copyright notices
9  * are retained or reproduced in an accompanying document, permission
10  * is granted to deal in this work without restriction, including un-
11  * limited rights to use, publicly perform, distribute, sell, modify,
12  * merge, give away, or sublicence.
13  *
14  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15  * the utmost extent permitted by applicable law, neither express nor
16  * implied; without malicious intent or gross negligence. In no event
17  * may a licensor, author or contributor be held liable for indirect,
18  * direct, other damage, loss, or other issues arising in any way out
19  * of dealing in the work, even if advised of the possibility of such
20  * damage or existence of a defect, except proven that it results out
21  * of said person's immediate fault when using the work as intended.
22  */
23 
24 #include "sh.h"
25 
26 __RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.128 2019/12/11 19:46:20 tg Exp $");
27 
28 #if HAVE_KILLPG
29 #define mksh_killpg		killpg
30 #else
31 /* cross fingers and hope kill is killpg-endowed */
32 #define mksh_killpg(p,s)	kill(-(p), (s))
33 #endif
34 
35 /* Order important! */
36 #define PRUNNING	0
37 #define PEXITED		1
38 #define PSIGNALLED	2
39 #define PSTOPPED	3
40 
41 typedef struct proc Proc;
42 /* to take alignment into consideration */
43 struct proc_dummy {
44 	Proc *next;
45 	pid_t pid;
46 	int state;
47 	int status;
48 	char command[128];
49 };
50 /* real structure */
51 struct proc {
52 	/* next process in pipeline (if any) */
53 	Proc *next;
54 	/* process id of this Unix process in the job */
55 	pid_t pid;
56 	/* one of the four P… above */
57 	int state;
58 	/* wait status */
59 	int status;
60 	/* process command string from vistree */
61 	char command[256 - (ALLOC_OVERHEAD +
62 	    offsetof(struct proc_dummy, command[0]))];
63 };
64 
65 /* Notify/print flag - j_print() argument */
66 #define JP_SHORT	1	/* print signals processes were killed by */
67 #define JP_MEDIUM	2	/* print [job-num] -/+ command */
68 #define JP_LONG		3	/* print [job-num] -/+ pid command */
69 #define JP_PGRP		4	/* print pgrp */
70 
71 /* put_job() flags */
72 #define PJ_ON_FRONT	0	/* at very front */
73 #define PJ_PAST_STOPPED	1	/* just past any stopped jobs */
74 
75 /* Job.flags values */
76 #define JF_STARTED	0x001	/* set when all processes in job are started */
77 #define JF_WAITING	0x002	/* set if j_waitj() is waiting on job */
78 #define JF_W_ASYNCNOTIFY 0x004	/* set if waiting and async notification ok */
79 #define JF_XXCOM	0x008	/* set for $(command) jobs */
80 #define JF_FG		0x010	/* running in foreground (also has tty pgrp) */
81 #define JF_SAVEDTTY	0x020	/* j->ttystat is valid */
82 #define JF_CHANGED	0x040	/* process has changed state */
83 #define JF_KNOWN	0x080	/* $! referenced */
84 #define JF_ZOMBIE	0x100	/* known, unwaited process */
85 #define JF_REMOVE	0x200	/* flagged for removal (j_jobs()/j_noityf()) */
86 #define JF_USETTYMODE	0x400	/* tty mode saved if process exits normally */
87 #define JF_SAVEDTTYPGRP	0x800	/* j->saved_ttypgrp is valid */
88 
89 typedef struct job Job;
90 struct job {
91 	ALLOC_ITEM alloc_INT;	/* internal, do not touch */
92 	Job *next;		/* next job in list */
93 	Proc *proc_list;	/* process list */
94 	Proc *last_proc;	/* last process in list */
95 	struct timeval systime;	/* system time used by job */
96 	struct timeval usrtime;	/* user time used by job */
97 	pid_t pgrp;		/* process group of job */
98 	pid_t ppid;		/* pid of process that forked job */
99 	int job;		/* job number: %n */
100 	int flags;		/* see JF_* */
101 	volatile int state;	/* job state */
102 	int status;		/* exit status of last process */
103 	int age;		/* number of jobs started */
104 	Coproc_id coproc_id;	/* 0 or id of coprocess output pipe */
105 #ifndef MKSH_UNEMPLOYED
106 	mksh_ttyst ttystat;	/* saved tty state for stopped jobs */
107 	pid_t saved_ttypgrp;	/* saved tty process group for stopped jobs */
108 #endif
109 };
110 
111 /* Flags for j_waitj() */
112 #define JW_NONE		0x00
113 #define JW_INTERRUPT	0x01	/* ^C will stop the wait */
114 #define JW_ASYNCNOTIFY	0x02	/* asynchronous notification during wait ok */
115 #define JW_STOPPEDWAIT	0x04	/* wait even if job stopped */
116 #define JW_PIPEST	0x08	/* want PIPESTATUS */
117 
118 /* Error codes for j_lookup() */
119 #define JL_NOSUCH	0	/* no such job */
120 #define JL_AMBIG	1	/* %foo or %?foo is ambiguous */
121 #define JL_INVALID	2	/* non-pid, non-% job id */
122 
123 static const char * const lookup_msgs[] = {
124 	"no such job",
125 	"ambiguous",
126 	"argument must be %job or process id"
127 };
128 
129 static Job *job_list;		/* job list */
130 static Job *last_job;
131 static Job *async_job;
132 static pid_t async_pid;
133 
134 static int nzombie;		/* # of zombies owned by this process */
135 static int njobs;		/* # of jobs started */
136 
137 #ifndef CHILD_MAX
138 #define CHILD_MAX	25
139 #endif
140 
141 #ifndef MKSH_NOPROSPECTOFWORK
142 /* held_sigchld is set if sigchld occurs before a job is completely started */
143 static volatile sig_atomic_t held_sigchld;
144 #endif
145 
146 #ifndef MKSH_UNEMPLOYED
147 static struct shf	*shl_j;
148 static bool		ttypgrp_ok;	/* set if can use tty pgrps */
149 static pid_t		restore_ttypgrp = -1;
150 static int const	tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
151 #endif
152 
153 static void		j_set_async(Job *);
154 static void		j_startjob(Job *);
155 static int		j_waitj(Job *, int, const char *);
156 static void		j_sigchld(int);
157 static void		j_print(Job *, int, struct shf *);
158 static Job		*j_lookup(const char *, int *);
159 static Job		*new_job(void);
160 static Proc		*new_proc(void);
161 static void		check_job(Job *);
162 static void		put_job(Job *, int);
163 static void		remove_job(Job *, const char *);
164 static int		kill_job(Job *, int);
165 
166 static void tty_init_talking(void);
167 static void tty_init_state(void);
168 
169 /* initialise job control */
170 void
j_init(void)171 j_init(void)
172 {
173 #ifndef MKSH_NOPROSPECTOFWORK
174 	(void)sigemptyset(&sm_default);
175 	sigprocmask(SIG_SETMASK, &sm_default, NULL);
176 
177 	(void)sigemptyset(&sm_sigchld);
178 	(void)sigaddset(&sm_sigchld, SIGCHLD);
179 
180 	setsig(&sigtraps[SIGCHLD], j_sigchld,
181 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
182 #else
183 	/* Make sure SIGCHLD isn't ignored - can do odd things under SYSV */
184 	setsig(&sigtraps[SIGCHLD], SIG_DFL, SS_RESTORE_ORIG|SS_FORCE);
185 #endif
186 
187 #ifndef MKSH_UNEMPLOYED
188 	if (Flag(FMONITOR) == 127)
189 		Flag(FMONITOR) = Flag(FTALKING);
190 
191 	/*
192 	 * shl_j is used to do asynchronous notification (used in
193 	 * an interrupt handler, so need a distinct shf)
194 	 */
195 	shl_j = shf_fdopen(2, SHF_WR, NULL);
196 
197 	if (Flag(FMONITOR) || Flag(FTALKING)) {
198 		int i;
199 
200 		/*
201 		 * the TF_SHELL_USES test is a kludge that lets us know if
202 		 * if the signals have been changed by the shell.
203 		 */
204 		for (i = NELEM(tt_sigs); --i >= 0; ) {
205 			sigtraps[tt_sigs[i]].flags |= TF_SHELL_USES;
206 			/* j_change() sets this to SS_RESTORE_DFL if FMONITOR */
207 			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
208 			    SS_RESTORE_IGN|SS_FORCE);
209 		}
210 	}
211 
212 	/* j_change() calls tty_init_talking() and tty_init_state() */
213 	if (Flag(FMONITOR))
214 		j_change();
215 	else
216 #endif
217 	  if (Flag(FTALKING)) {
218 		tty_init_talking();
219 		tty_init_state();
220 	}
221 }
222 
223 static int
proc_errorlevel(Proc * p)224 proc_errorlevel(Proc *p)
225 {
226 	switch (p->state) {
227 	case PEXITED:
228 		return ((WEXITSTATUS(p->status)) & 255);
229 	case PSIGNALLED:
230 		return (ksh_sigmask(WTERMSIG(p->status)));
231 	default:
232 		return (0);
233 	}
234 }
235 
236 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
237 /* suspend the shell */
238 void
j_suspend(void)239 j_suspend(void)
240 {
241 	struct sigaction sa, osa;
242 
243 	/* Restore tty and pgrp. */
244 	if (ttypgrp_ok) {
245 		if (tty_hasstate)
246 			mksh_tcset(tty_fd, &tty_state);
247 		if (restore_ttypgrp >= 0) {
248 			if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
249 				warningf(false, Tf_ssfaileds,
250 				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
251 			} else if (setpgid(0, restore_ttypgrp) < 0) {
252 				warningf(false, Tf_ssfaileds,
253 				    Tj_suspend, "setpgid", cstrerror(errno));
254 			}
255 		}
256 	}
257 
258 	/* Suspend the shell. */
259 	memset(&sa, 0, sizeof(sa));
260 	sigemptyset(&sa.sa_mask);
261 	sa.sa_handler = SIG_DFL;
262 	sigaction(SIGTSTP, &sa, &osa);
263 	kill(0, SIGTSTP);
264 
265 	/* Back from suspend, reset signals, pgrp and tty. */
266 	sigaction(SIGTSTP, &osa, NULL);
267 	if (ttypgrp_ok) {
268 		if (restore_ttypgrp >= 0) {
269 			if (setpgid(0, kshpid) < 0) {
270 				warningf(false, Tf_ssfaileds,
271 				    Tj_suspend, "setpgid", cstrerror(errno));
272 				ttypgrp_ok = false;
273 			} else if (tcsetpgrp(tty_fd, kshpid) < 0) {
274 				warningf(false, Tf_ssfaileds,
275 				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
276 				ttypgrp_ok = false;
277 			}
278 		}
279 		tty_init_state();
280 	}
281 }
282 #endif
283 
284 /* job cleanup before shell exit */
285 void
j_exit(void)286 j_exit(void)
287 {
288 	/* kill stopped, and possibly running, jobs */
289 	Job *j;
290 	bool killed = false;
291 
292 	for (j = job_list; j != NULL; j = j->next) {
293 		if (j->ppid == procpid &&
294 		    (j->state == PSTOPPED ||
295 		    (j->state == PRUNNING &&
296 		    ((j->flags & JF_FG) ||
297 		    (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
298 			killed = true;
299 			if (j->pgrp == 0)
300 				kill_job(j, SIGHUP);
301 			else
302 				mksh_killpg(j->pgrp, SIGHUP);
303 #ifndef MKSH_UNEMPLOYED
304 			if (j->state == PSTOPPED) {
305 				if (j->pgrp == 0)
306 					kill_job(j, SIGCONT);
307 				else
308 					mksh_killpg(j->pgrp, SIGCONT);
309 			}
310 #endif
311 		}
312 	}
313 	if (killed)
314 		sleep(1);
315 	j_notify();
316 
317 #ifndef MKSH_UNEMPLOYED
318 	if (kshpid == procpid && restore_ttypgrp >= 0) {
319 		/*
320 		 * Need to restore the tty pgrp to what it was when the
321 		 * shell started up, so that the process that started us
322 		 * will be able to access the tty when we are done.
323 		 * Also need to restore our process group in case we are
324 		 * about to do an exec so that both our parent and the
325 		 * process we are to become will be able to access the tty.
326 		 */
327 		tcsetpgrp(tty_fd, restore_ttypgrp);
328 		setpgid(0, restore_ttypgrp);
329 	}
330 	if (Flag(FMONITOR)) {
331 		Flag(FMONITOR) = 0;
332 		j_change();
333 	}
334 #endif
335 }
336 
337 #ifndef MKSH_UNEMPLOYED
338 /* turn job control on or off according to Flag(FMONITOR) */
339 void
j_change(void)340 j_change(void)
341 {
342 	int i;
343 
344 	if (Flag(FMONITOR)) {
345 		bool use_tty = Flag(FTALKING);
346 
347 		/* don't call mksh_tcget until we own the tty process group */
348 		if (use_tty)
349 			tty_init_talking();
350 
351 		/* no controlling tty, no SIGT* */
352 		if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
353 			setsig(&sigtraps[SIGTTIN], SIG_DFL,
354 			    SS_RESTORE_ORIG|SS_FORCE);
355 			/* wait to be given tty (POSIX.1, B.2, job control) */
356 			while (/* CONSTCOND */ 1) {
357 				pid_t ttypgrp;
358 
359 				if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
360 					warningf(false, Tf_ssfaileds,
361 					    "j_init", "tcgetpgrp",
362 					    cstrerror(errno));
363 					ttypgrp_ok = false;
364 					break;
365 				}
366 				if (ttypgrp == kshpgrp)
367 					break;
368 				kill(0, SIGTTIN);
369 			}
370 		}
371 		for (i = NELEM(tt_sigs); --i >= 0; )
372 			setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
373 			    SS_RESTORE_DFL|SS_FORCE);
374 		if (ttypgrp_ok && kshpgrp != kshpid) {
375 			if (setpgid(0, kshpid) < 0) {
376 				warningf(false, Tf_ssfaileds,
377 				    "j_init", "setpgid", cstrerror(errno));
378 				ttypgrp_ok = false;
379 			} else {
380 				if (tcsetpgrp(tty_fd, kshpid) < 0) {
381 					warningf(false, Tf_ssfaileds,
382 					    "j_init", "tcsetpgrp",
383 					    cstrerror(errno));
384 					ttypgrp_ok = false;
385 				} else
386 					restore_ttypgrp = kshpgrp;
387 				kshpgrp = kshpid;
388 			}
389 		}
390 #ifndef MKSH_DISABLE_TTY_WARNING
391 		if (use_tty && !ttypgrp_ok)
392 			warningf(false, Tf_sD_s, "warning",
393 			    "won't have full job control");
394 #endif
395 	} else {
396 		ttypgrp_ok = false;
397 		if (Flag(FTALKING))
398 			for (i = NELEM(tt_sigs); --i >= 0; )
399 				setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
400 				    SS_RESTORE_IGN|SS_FORCE);
401 		else
402 			for (i = NELEM(tt_sigs); --i >= 0; ) {
403 				if (sigtraps[tt_sigs[i]].flags &
404 				    (TF_ORIG_IGN | TF_ORIG_DFL))
405 					setsig(&sigtraps[tt_sigs[i]],
406 					    (sigtraps[tt_sigs[i]].flags & TF_ORIG_IGN) ?
407 					    SIG_IGN : SIG_DFL,
408 					    SS_RESTORE_ORIG|SS_FORCE);
409 			}
410 	}
411 	tty_init_state();
412 }
413 #endif
414 
415 #if HAVE_NICE
416 /* run nice(3) and ignore the result */
417 static void
ksh_nice(int ness)418 ksh_nice(int ness)
419 {
420 #if defined(__USE_FORTIFY_LEVEL) && (__USE_FORTIFY_LEVEL > 0)
421 	int eno;
422 
423 	errno = 0;
424 	/* this is gonna annoy users; complain to your distro, people! */
425 	if (nice(ness) == -1 && (eno = errno) != 0)
426 		warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
427 #else
428 	(void)nice(ness);
429 #endif
430 }
431 #endif
432 
433 /* execute tree in child subprocess */
434 int
exchild(struct op * t,int flags,volatile int * xerrok,int close_fd)435 exchild(struct op *t, int flags,
436     volatile int *xerrok,
437     /* used if XPCLOSE or XCCLOSE */
438     int close_fd)
439 {
440 	/* for pipelines */
441 	static Proc *last_proc;
442 
443 	int rv = 0, forksleep, jwflags = JW_NONE;
444 #ifndef MKSH_NOPROSPECTOFWORK
445 	sigset_t omask;
446 #endif
447 	Proc *p;
448 	Job *j;
449 	pid_t cldpid;
450 
451 	if (flags & XPIPEST) {
452 		flags &= ~XPIPEST;
453 		jwflags |= JW_PIPEST;
454 	}
455 
456 	if (flags & XEXEC)
457 		/*
458 		 * Clear XFORK|XPCLOSE|XCCLOSE|XCOPROC|XPIPEO|XPIPEI|XXCOM|XBGND
459 		 * (also done in another execute() below)
460 		 */
461 		return (execute(t, flags & (XEXEC | XERROK), xerrok));
462 
463 #ifndef MKSH_NOPROSPECTOFWORK
464 	/* no SIGCHLDs while messing with job and process lists */
465 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
466 #endif
467 
468 	p = new_proc();
469 	p->next = NULL;
470 	p->state = PRUNNING;
471 	p->status = 0;
472 	p->pid = 0;
473 
474 	/* link process into jobs list */
475 	if (flags & XPIPEI) {
476 		/* continuing with a pipe */
477 		if (!last_job)
478 			internal_errorf("exchild: XPIPEI and no last_job - pid %d",
479 			    (int)procpid);
480 		j = last_job;
481 		if (last_proc)
482 			last_proc->next = p;
483 		last_proc = p;
484 	} else {
485 		/* fills in j->job */
486 		j = new_job();
487 		/*
488 		 * we don't consider XXCOMs foreground since they don't get
489 		 * tty process group and we don't save or restore tty modes.
490 		 */
491 		j->flags = (flags & XXCOM) ? JF_XXCOM :
492 		    ((flags & XBGND) ? 0 : (JF_FG|JF_USETTYMODE));
493 		timerclear(&j->usrtime);
494 		timerclear(&j->systime);
495 		j->state = PRUNNING;
496 		j->pgrp = 0;
497 		j->ppid = procpid;
498 		j->age = ++njobs;
499 		j->proc_list = p;
500 		j->coproc_id = 0;
501 		last_job = j;
502 		last_proc = p;
503 		put_job(j, PJ_PAST_STOPPED);
504 	}
505 
506 	vistree(p->command, sizeof(p->command), t);
507 
508 	/* create child process */
509 	forksleep = 1;
510 	while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
511 		if (intrsig)
512 			/* allow user to ^C out... */
513 			break;
514 		sleep(forksleep);
515 		forksleep <<= 1;
516 	}
517 	/* ensure $RANDOM changes between parent and child */
518 	rndset((unsigned long)cldpid);
519 	/* fork failed? */
520 	if (cldpid < 0) {
521 		kill_job(j, SIGKILL);
522 		remove_job(j, "fork failed");
523 #ifndef MKSH_NOPROSPECTOFWORK
524 		sigprocmask(SIG_SETMASK, &omask, NULL);
525 #endif
526 		errorf("can't fork - try again");
527 	}
528 	p->pid = cldpid ? cldpid : (procpid = getpid());
529 
530 #ifndef MKSH_UNEMPLOYED
531 	/* job control set up */
532 	if (Flag(FMONITOR) && !(flags&XXCOM)) {
533 		bool dotty = false;
534 
535 		if (j->pgrp == 0) {
536 			/* First process */
537 			j->pgrp = p->pid;
538 			dotty = true;
539 		}
540 
541 		/*
542 		 * set pgrp in both parent and child to deal with race
543 		 * condition
544 		 */
545 		setpgid(p->pid, j->pgrp);
546 		if (ttypgrp_ok && dotty && !(flags & XBGND))
547 			tcsetpgrp(tty_fd, j->pgrp);
548 	}
549 #endif
550 
551 	/* used to close pipe input fd */
552 	if (close_fd >= 0 && (((flags & XPCLOSE) && cldpid) ||
553 	    ((flags & XCCLOSE) && !cldpid)))
554 		close(close_fd);
555 	if (!cldpid) {
556 		/* child */
557 
558 		/* Do this before restoring signal */
559 		if (flags & XCOPROC)
560 			coproc_cleanup(false);
561 		cleanup_parents_env();
562 #ifndef MKSH_UNEMPLOYED
563 		/*
564 		 * If FMONITOR or FTALKING is set, these signals are ignored,
565 		 * if neither FMONITOR nor FTALKING are set, the signals have
566 		 * their inherited values.
567 		 */
568 		if (Flag(FMONITOR) && !(flags & XXCOM)) {
569 			for (forksleep = NELEM(tt_sigs); --forksleep >= 0; )
570 				setsig(&sigtraps[tt_sigs[forksleep]], SIG_DFL,
571 				    SS_RESTORE_DFL|SS_FORCE);
572 		}
573 #endif
574 #if HAVE_NICE
575 		if (Flag(FBGNICE) && (flags & XBGND))
576 			ksh_nice(4);
577 #endif
578 		if ((flags & XBGND)
579 #ifndef MKSH_UNEMPLOYED
580 		    && !Flag(FMONITOR)
581 #endif
582 		    ) {
583 			setsig(&sigtraps[SIGINT], SIG_IGN,
584 			    SS_RESTORE_IGN|SS_FORCE);
585 			setsig(&sigtraps[SIGQUIT], SIG_IGN,
586 			    SS_RESTORE_IGN|SS_FORCE);
587 			if ((!(flags & (XPIPEI | XCOPROC))) &&
588 			    ((forksleep = open("/dev/null", 0)) > 0)) {
589 				(void)ksh_dup2(forksleep, 0, true);
590 				close(forksleep);
591 			}
592 		}
593 		/* in case of $(jobs) command */
594 		remove_job(j, "child");
595 #ifndef MKSH_NOPROSPECTOFWORK
596 		/* remove_job needs SIGCHLD blocked still */
597 		sigprocmask(SIG_SETMASK, &omask, NULL);
598 #endif
599 		nzombie = 0;
600 #ifndef MKSH_UNEMPLOYED
601 		ttypgrp_ok = false;
602 		Flag(FMONITOR) = 0;
603 #endif
604 		Flag(FTALKING) = 0;
605 		cleartraps();
606 		/* no return */
607 		execute(t, (flags & XERROK) | XEXEC, NULL);
608 #ifndef MKSH_SMALL
609 		if (t->type == TPIPE)
610 			unwind(LLEAVE);
611 		internal_warningf("%s: execute() returned", "exchild");
612 		fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
613 		    "exchild", t);
614 		shf_flush(shl_out);
615 #endif
616 		unwind(LLEAVE);
617 		/* NOTREACHED */
618 	}
619 
620 	/* shell (parent) stuff */
621 	if (!(flags & XPIPEO)) {
622 		/* last process in a job */
623 		j_startjob(j);
624 		if (flags & XCOPROC) {
625 			j->coproc_id = coproc.id;
626 			/* n jobs using co-process output */
627 			coproc.njobs++;
628 			/* j using co-process input */
629 			coproc.job = (void *)j;
630 		}
631 		if (flags & XBGND) {
632 			j_set_async(j);
633 			if (Flag(FTALKING)) {
634 				shf_fprintf(shl_out, "[%d]", j->job);
635 				for (p = j->proc_list; p; p = p->next)
636 					shf_fprintf(shl_out, Tf__d,
637 					    (int)p->pid);
638 				shf_putchar('\n', shl_out);
639 				shf_flush(shl_out);
640 			}
641 		} else
642 			rv = j_waitj(j, jwflags, "jw:last proc");
643 	}
644 
645 #ifndef MKSH_NOPROSPECTOFWORK
646 	sigprocmask(SIG_SETMASK, &omask, NULL);
647 #endif
648 
649 	return (rv);
650 }
651 
652 /* start the last job: only used for $(command) jobs */
653 void
startlast(void)654 startlast(void)
655 {
656 #ifndef MKSH_NOPROSPECTOFWORK
657 	sigset_t omask;
658 
659 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
660 #endif
661 
662 	/* no need to report error - waitlast() will do it */
663 	if (last_job) {
664 		/* ensure it isn't removed by check_job() */
665 		last_job->flags |= JF_WAITING;
666 		j_startjob(last_job);
667 	}
668 #ifndef MKSH_NOPROSPECTOFWORK
669 	sigprocmask(SIG_SETMASK, &omask, NULL);
670 #endif
671 }
672 
673 /* wait for last job: only used for $(command) jobs */
674 int
waitlast(void)675 waitlast(void)
676 {
677 	int rv;
678 	Job *j;
679 #ifndef MKSH_NOPROSPECTOFWORK
680 	sigset_t omask;
681 
682 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
683 #endif
684 
685 	j = last_job;
686 	if (!j || !(j->flags & JF_STARTED)) {
687 		if (!j)
688 			warningf(true, Tf_sD_s, "waitlast", "no last job");
689 		else
690 			internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
691 #ifndef MKSH_NOPROSPECTOFWORK
692 		sigprocmask(SIG_SETMASK, &omask, NULL);
693 #endif
694 		/* not so arbitrary, non-zero value */
695 		return (125);
696 	}
697 
698 	rv = j_waitj(j, JW_NONE, "waitlast");
699 
700 #ifndef MKSH_NOPROSPECTOFWORK
701 	sigprocmask(SIG_SETMASK, &omask, NULL);
702 #endif
703 
704 	return (rv);
705 }
706 
707 /* wait for child, interruptable. */
708 int
waitfor(const char * cp,int * sigp)709 waitfor(const char *cp, int *sigp)
710 {
711 	int rv, ecode, flags = JW_INTERRUPT|JW_ASYNCNOTIFY;
712 	Job *j;
713 #ifndef MKSH_NOPROSPECTOFWORK
714 	sigset_t omask;
715 
716 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
717 #endif
718 
719 	*sigp = 0;
720 
721 	if (cp == NULL) {
722 		/*
723 		 * wait for an unspecified job - always returns 0, so
724 		 * don't have to worry about exited/signaled jobs
725 		 */
726 		for (j = job_list; j; j = j->next)
727 			/* AT&T ksh will wait for stopped jobs - we don't */
728 			if (j->ppid == procpid && j->state == PRUNNING)
729 				break;
730 		if (!j) {
731 #ifndef MKSH_NOPROSPECTOFWORK
732 			sigprocmask(SIG_SETMASK, &omask, NULL);
733 #endif
734 			return (-1);
735 		}
736 	} else if ((j = j_lookup(cp, &ecode))) {
737 		/* don't report normal job completion */
738 		flags &= ~JW_ASYNCNOTIFY;
739 		if (j->ppid != procpid) {
740 #ifndef MKSH_NOPROSPECTOFWORK
741 			sigprocmask(SIG_SETMASK, &omask, NULL);
742 #endif
743 			return (-1);
744 		}
745 	} else {
746 #ifndef MKSH_NOPROSPECTOFWORK
747 		sigprocmask(SIG_SETMASK, &omask, NULL);
748 #endif
749 		if (ecode != JL_NOSUCH)
750 			bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
751 		return (-1);
752 	}
753 
754 	/* AT&T ksh will wait for stopped jobs - we don't */
755 	rv = j_waitj(j, flags, "jw:waitfor");
756 
757 #ifndef MKSH_NOPROSPECTOFWORK
758 	sigprocmask(SIG_SETMASK, &omask, NULL);
759 #endif
760 
761 	if (rv < 0)
762 		/* we were interrupted */
763 		*sigp = ksh_sigmask(-rv);
764 
765 	return (rv);
766 }
767 
768 /* kill (built-in) a job */
769 int
j_kill(const char * cp,int sig)770 j_kill(const char *cp, int sig)
771 {
772 	Job *j;
773 	int rv = 0, ecode;
774 #ifndef MKSH_NOPROSPECTOFWORK
775 	sigset_t omask;
776 
777 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
778 #endif
779 
780 	if ((j = j_lookup(cp, &ecode)) == NULL) {
781 #ifndef MKSH_NOPROSPECTOFWORK
782 		sigprocmask(SIG_SETMASK, &omask, NULL);
783 #endif
784 		bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
785 		return (1);
786 	}
787 
788 	if (j->pgrp == 0) {
789 		/* started when !Flag(FMONITOR) */
790 		if (kill_job(j, sig) < 0) {
791 			bi_errorf(Tf_sD_s, cp, cstrerror(errno));
792 			rv = 1;
793 		}
794 	} else {
795 #ifndef MKSH_UNEMPLOYED
796 		if (j->state == PSTOPPED && (sig == SIGTERM || sig == SIGHUP))
797 			mksh_killpg(j->pgrp, SIGCONT);
798 #endif
799 		if (mksh_killpg(j->pgrp, sig) < 0) {
800 			bi_errorf(Tf_sD_s, cp, cstrerror(errno));
801 			rv = 1;
802 		}
803 	}
804 
805 #ifndef MKSH_NOPROSPECTOFWORK
806 	sigprocmask(SIG_SETMASK, &omask, NULL);
807 #endif
808 
809 	return (rv);
810 }
811 
812 #ifndef MKSH_UNEMPLOYED
813 /* fg and bg built-ins: called only if Flag(FMONITOR) set */
814 int
j_resume(const char * cp,int bg)815 j_resume(const char *cp, int bg)
816 {
817 	Job *j;
818 	Proc *p;
819 	int ecode, rv = 0;
820 	bool running;
821 	sigset_t omask;
822 
823 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
824 
825 	if ((j = j_lookup(cp, &ecode)) == NULL) {
826 		sigprocmask(SIG_SETMASK, &omask, NULL);
827 		bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
828 		return (1);
829 	}
830 
831 	if (j->pgrp == 0) {
832 		sigprocmask(SIG_SETMASK, &omask, NULL);
833 		bi_errorf("job not job-controlled");
834 		return (1);
835 	}
836 
837 	if (bg)
838 		shprintf("[%d] ", j->job);
839 
840 	running = false;
841 	for (p = j->proc_list; p != NULL; p = p->next) {
842 		if (p->state == PSTOPPED) {
843 			p->state = PRUNNING;
844 			p->status = 0;
845 			running = true;
846 		}
847 		shf_puts(p->command, shl_stdout);
848 		if (p->next)
849 			shf_puts("| ", shl_stdout);
850 	}
851 	shf_putc('\n', shl_stdout);
852 	shf_flush(shl_stdout);
853 	if (running)
854 		j->state = PRUNNING;
855 
856 	put_job(j, PJ_PAST_STOPPED);
857 	if (bg)
858 		j_set_async(j);
859 	else {
860 		/* attach tty to job */
861 		if (j->state == PRUNNING) {
862 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
863 				mksh_tcset(tty_fd, &j->ttystat);
864 			/* See comment in j_waitj regarding saved_ttypgrp. */
865 			if (ttypgrp_ok &&
866 			    tcsetpgrp(tty_fd, (j->flags & JF_SAVEDTTYPGRP) ?
867 			    j->saved_ttypgrp : j->pgrp) < 0) {
868 				rv = errno;
869 				if (j->flags & JF_SAVEDTTY)
870 					mksh_tcset(tty_fd, &tty_state);
871 				sigprocmask(SIG_SETMASK, &omask, NULL);
872 				bi_errorf(Tf_ldfailed,
873 				    "fg: 1st", "tcsetpgrp", tty_fd,
874 				    (long)((j->flags & JF_SAVEDTTYPGRP) ?
875 				    j->saved_ttypgrp : j->pgrp),
876 				    cstrerror(rv));
877 				return (1);
878 			}
879 		}
880 		j->flags |= JF_FG;
881 		j->flags &= ~JF_KNOWN;
882 		if (j == async_job)
883 			async_job = NULL;
884 	}
885 
886 	if (j->state == PRUNNING && mksh_killpg(j->pgrp, SIGCONT) < 0) {
887 		int eno = errno;
888 
889 		if (!bg) {
890 			j->flags &= ~JF_FG;
891 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
892 				mksh_tcset(tty_fd, &tty_state);
893 			if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
894 				warningf(true, Tf_ldfailed,
895 				    "fg: 2nd", "tcsetpgrp", tty_fd,
896 				    (long)kshpgrp, cstrerror(errno));
897 		}
898 		sigprocmask(SIG_SETMASK, &omask, NULL);
899 		bi_errorf(Tf_s_sD_s, "can't continue job",
900 		    cp, cstrerror(eno));
901 		return (1);
902 	}
903 	if (!bg) {
904 		if (ttypgrp_ok) {
905 			j->flags &= ~(JF_SAVEDTTY | JF_SAVEDTTYPGRP);
906 		}
907 		rv = j_waitj(j, JW_NONE, "jw:resume");
908 	}
909 	sigprocmask(SIG_SETMASK, &omask, NULL);
910 	return (rv);
911 }
912 #endif
913 
914 /* are there any running or stopped jobs ? */
915 int
j_stopped_running(void)916 j_stopped_running(void)
917 {
918 	Job *j;
919 	int which = 0;
920 
921 	for (j = job_list; j != NULL; j = j->next) {
922 #ifndef MKSH_UNEMPLOYED
923 		if (j->ppid == procpid && j->state == PSTOPPED)
924 			which |= 1;
925 #endif
926 		if (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid &&
927 		    j->ppid == procpid && j->state == PRUNNING)
928 			which |= 2;
929 	}
930 	if (which) {
931 		shellf("You have %s%s%s jobs\n",
932 		    which & 1 ? "stopped" : "",
933 		    which == 3 ? " and " : "",
934 		    which & 2 ? "running" : "");
935 		return (1);
936 	}
937 
938 	return (0);
939 }
940 
941 
942 /* list jobs for jobs built-in */
943 int
j_jobs(const char * cp,int slp,int nflag)944 j_jobs(const char *cp, int slp,
945     /* 0: short, 1: long, 2: pgrp */
946     int nflag)
947 {
948 	Job *j, *tmp;
949 	int how, zflag = 0;
950 #ifndef MKSH_NOPROSPECTOFWORK
951 	sigset_t omask;
952 
953 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
954 #endif
955 
956 	if (nflag < 0) {
957 		/* kludge: print zombies */
958 		nflag = 0;
959 		zflag = 1;
960 	}
961 	if (cp) {
962 		int ecode;
963 
964 		if ((j = j_lookup(cp, &ecode)) == NULL) {
965 #ifndef MKSH_NOPROSPECTOFWORK
966 			sigprocmask(SIG_SETMASK, &omask, NULL);
967 #endif
968 			bi_errorf(Tf_sD_s, cp, lookup_msgs[ecode]);
969 			return (1);
970 		}
971 	} else
972 		j = job_list;
973 	how = slp == 0 ? JP_MEDIUM : (slp == 1 ? JP_LONG : JP_PGRP);
974 	for (; j; j = j->next) {
975 		if ((!(j->flags & JF_ZOMBIE) || zflag) &&
976 		    (!nflag || (j->flags & JF_CHANGED))) {
977 			j_print(j, how, shl_stdout);
978 			if (j->state == PEXITED || j->state == PSIGNALLED)
979 				j->flags |= JF_REMOVE;
980 		}
981 		if (cp)
982 			break;
983 	}
984 	/* Remove jobs after printing so there won't be multiple + or - jobs */
985 	for (j = job_list; j; j = tmp) {
986 		tmp = j->next;
987 		if (j->flags & JF_REMOVE)
988 			remove_job(j, Tjobs);
989 	}
990 #ifndef MKSH_NOPROSPECTOFWORK
991 	sigprocmask(SIG_SETMASK, &omask, NULL);
992 #endif
993 	return (0);
994 }
995 
996 /* list jobs for top-level notification */
997 void
j_notify(void)998 j_notify(void)
999 {
1000 	Job *j, *tmp;
1001 #ifndef MKSH_NOPROSPECTOFWORK
1002 	sigset_t omask;
1003 
1004 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1005 #endif
1006 	for (j = job_list; j; j = j->next) {
1007 #ifndef MKSH_UNEMPLOYED
1008 		if (Flag(FMONITOR) && (j->flags & JF_CHANGED))
1009 			j_print(j, JP_MEDIUM, shl_out);
1010 #endif
1011 		/*
1012 		 * Remove job after doing reports so there aren't
1013 		 * multiple +/- jobs.
1014 		 */
1015 		if (j->state == PEXITED || j->state == PSIGNALLED)
1016 			j->flags |= JF_REMOVE;
1017 	}
1018 	for (j = job_list; j; j = tmp) {
1019 		tmp = j->next;
1020 		if (j->flags & JF_REMOVE) {
1021 			if (j == async_job || (j->flags & JF_KNOWN)) {
1022 				j->flags = (j->flags & ~JF_REMOVE) | JF_ZOMBIE;
1023 				j->job = -1;
1024 				nzombie++;
1025 			} else
1026 				remove_job(j, "notify");
1027 		}
1028 	}
1029 	shf_flush(shl_out);
1030 #ifndef MKSH_NOPROSPECTOFWORK
1031 	sigprocmask(SIG_SETMASK, &omask, NULL);
1032 #endif
1033 }
1034 
1035 /* Return pid of last process in last asynchronous job */
1036 pid_t
j_async(void)1037 j_async(void)
1038 {
1039 #ifndef MKSH_NOPROSPECTOFWORK
1040 	sigset_t omask;
1041 
1042 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1043 #endif
1044 
1045 	if (async_job)
1046 		async_job->flags |= JF_KNOWN;
1047 
1048 #ifndef MKSH_NOPROSPECTOFWORK
1049 	sigprocmask(SIG_SETMASK, &omask, NULL);
1050 #endif
1051 
1052 	return (async_pid);
1053 }
1054 
1055 /*
1056  * Make j the last async process
1057  *
1058  * If jobs are compiled in then this routine expects sigchld to be blocked.
1059  */
1060 static void
j_set_async(Job * j)1061 j_set_async(Job *j)
1062 {
1063 	Job *jl, *oldest;
1064 
1065 	if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
1066 		remove_job(async_job, "async");
1067 	if (!(j->flags & JF_STARTED)) {
1068 		internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
1069 		return;
1070 	}
1071 	async_job = j;
1072 	async_pid = j->last_proc->pid;
1073 	while (nzombie > CHILD_MAX) {
1074 		oldest = NULL;
1075 		for (jl = job_list; jl; jl = jl->next)
1076 			if (jl != async_job && (jl->flags & JF_ZOMBIE) &&
1077 			    (!oldest || jl->age < oldest->age))
1078 				oldest = jl;
1079 		if (!oldest) {
1080 			/* XXX debugging */
1081 			if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
1082 				internal_warningf("%s: bad nzombie (%d)",
1083 				    "j_async", nzombie);
1084 				nzombie = 0;
1085 			}
1086 			break;
1087 		}
1088 		remove_job(oldest, "zombie");
1089 	}
1090 }
1091 
1092 /*
1093  * Start a job: set STARTED, check for held signals and set j->last_proc
1094  *
1095  * If jobs are compiled in then this routine expects sigchld to be blocked.
1096  */
1097 static void
j_startjob(Job * j)1098 j_startjob(Job *j)
1099 {
1100 	Proc *p;
1101 
1102 	j->flags |= JF_STARTED;
1103 	for (p = j->proc_list; p->next; p = p->next)
1104 		;
1105 	j->last_proc = p;
1106 
1107 #ifndef MKSH_NOPROSPECTOFWORK
1108 	if (held_sigchld) {
1109 		held_sigchld = 0;
1110 		/* Don't call j_sigchld() as it may remove job... */
1111 		kill(procpid, SIGCHLD);
1112 	}
1113 #endif
1114 }
1115 
1116 /*
1117  * wait for job to complete or change state
1118  *
1119  * If jobs are compiled in then this routine expects sigchld to be blocked.
1120  */
1121 static int
j_waitj(Job * j,int flags,const char * where)1122 j_waitj(Job *j,
1123     /* see JW_* */
1124     int flags,
1125     const char *where)
1126 {
1127 	Proc *p;
1128 	int rv;
1129 #ifdef MKSH_NO_SIGSUSPEND
1130 	sigset_t omask;
1131 #endif
1132 
1133 	/*
1134 	 * No auto-notify on the job we are waiting on.
1135 	 */
1136 	j->flags |= JF_WAITING;
1137 	if (flags & JW_ASYNCNOTIFY)
1138 		j->flags |= JF_W_ASYNCNOTIFY;
1139 
1140 #ifndef MKSH_UNEMPLOYED
1141 	if (!Flag(FMONITOR))
1142 #endif
1143 		flags |= JW_STOPPEDWAIT;
1144 
1145 	while (j->state == PRUNNING ||
1146 	    ((flags & JW_STOPPEDWAIT) && j->state == PSTOPPED)) {
1147 #ifndef MKSH_NOPROSPECTOFWORK
1148 #ifdef MKSH_NO_SIGSUSPEND
1149 		sigprocmask(SIG_SETMASK, &sm_default, &omask);
1150 		pause();
1151 		/* note that handlers may run here so they need to know */
1152 		sigprocmask(SIG_SETMASK, &omask, NULL);
1153 #else
1154 		sigsuspend(&sm_default);
1155 #endif
1156 #else
1157 		j_sigchld(SIGCHLD);
1158 #endif
1159 		if (fatal_trap) {
1160 			int oldf = j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY);
1161 			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1162 			runtraps(TF_FATAL);
1163 			/* not reached... */
1164 			j->flags |= oldf;
1165 		}
1166 		if ((flags & JW_INTERRUPT) && (rv = trap_pending())) {
1167 			j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1168 			return (-rv);
1169 		}
1170 	}
1171 	j->flags &= ~(JF_WAITING|JF_W_ASYNCNOTIFY);
1172 
1173 	if (j->flags & JF_FG) {
1174 		j->flags &= ~JF_FG;
1175 #ifndef MKSH_UNEMPLOYED
1176 		if (Flag(FMONITOR) && ttypgrp_ok && j->pgrp) {
1177 			/*
1178 			 * Save the tty's current pgrp so it can be restored
1179 			 * when the job is foregrounded. This is to
1180 			 * deal with things like the GNU su which does
1181 			 * a fork/exec instead of an exec (the fork means
1182 			 * the execed shell gets a different pid from its
1183 			 * pgrp, so naturally it sets its pgrp and gets hosed
1184 			 * when it gets foregrounded by the parent shell which
1185 			 * has restored the tty's pgrp to that of the su
1186 			 * process).
1187 			 */
1188 			if (j->state == PSTOPPED &&
1189 			    (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
1190 				j->flags |= JF_SAVEDTTYPGRP;
1191 			if (tcsetpgrp(tty_fd, kshpgrp) < 0)
1192 				warningf(true, Tf_ldfailed,
1193 				    "j_waitj:", "tcsetpgrp", tty_fd,
1194 				    (long)kshpgrp, cstrerror(errno));
1195 			if (j->state == PSTOPPED) {
1196 				j->flags |= JF_SAVEDTTY;
1197 				mksh_tcget(tty_fd, &j->ttystat);
1198 			}
1199 		}
1200 #endif
1201 		if (tty_hasstate) {
1202 			/*
1203 			 * Only restore tty settings if job was originally
1204 			 * started in the foreground. Problems can be
1205 			 * caused by things like 'more foobar &' which will
1206 			 * typically get and save the shell's vi/emacs tty
1207 			 * settings before setting up the tty for itself;
1208 			 * when more exits, it restores the 'original'
1209 			 * settings, and things go down hill from there...
1210 			 */
1211 			if (j->state == PEXITED && j->status == 0 &&
1212 			    (j->flags & JF_USETTYMODE)) {
1213 				mksh_tcget(tty_fd, &tty_state);
1214 			} else {
1215 				mksh_tcset(tty_fd, &tty_state);
1216 				/*-
1217 				 * Don't use tty mode if job is stopped and
1218 				 * later restarted and exits. Consider
1219 				 * the sequence:
1220 				 *	vi foo (stopped)
1221 				 *	...
1222 				 *	stty something
1223 				 *	...
1224 				 *	fg (vi; ZZ)
1225 				 * mode should be that of the stty, not what
1226 				 * was before the vi started.
1227 				 */
1228 				if (j->state == PSTOPPED)
1229 					j->flags &= ~JF_USETTYMODE;
1230 			}
1231 		}
1232 #ifndef MKSH_UNEMPLOYED
1233 		/*
1234 		 * If it looks like user hit ^C to kill a job, pretend we got
1235 		 * one too to break out of for loops, etc. (AT&T ksh does this
1236 		 * even when not monitoring, but this doesn't make sense since
1237 		 * a tty generated ^C goes to the whole process group)
1238 		 */
1239 		if (Flag(FMONITOR) && j->state == PSIGNALLED &&
1240 		    WIFSIGNALED(j->last_proc->status)) {
1241 			int termsig;
1242 
1243 			if ((termsig = WTERMSIG(j->last_proc->status)) > 0 &&
1244 			    termsig < ksh_NSIG &&
1245 			    (sigtraps[termsig].flags & TF_TTY_INTR))
1246 				trapsig(termsig);
1247 		}
1248 #endif
1249 	}
1250 
1251 	j_usrtime = j->usrtime;
1252 	j_systime = j->systime;
1253 	rv = j->status;
1254 
1255 	if (!(p = j->proc_list)) {
1256 		;	/* nothing */
1257 	} else if (flags & JW_PIPEST) {
1258 		uint32_t num = 0;
1259 		struct tbl *vp;
1260 
1261 		unset(vp_pipest, 1);
1262 		vp = vp_pipest;
1263 		vp->flag = DEFINED | ISSET | INTEGER | RDONLY | ARRAY | INT_U;
1264 		goto got_array;
1265 
1266 		while (p != NULL) {
1267 			{
1268 				struct tbl *vq;
1269 
1270 				/* strlen(vp_pipest->name) == 10 */
1271 				vq = alloc(offsetof(struct tbl, name[0]) + 11,
1272 				    vp_pipest->areap);
1273 				memset(vq, 0, offsetof(struct tbl, name[0]));
1274 				memcpy(vq->name, vp_pipest->name, 11);
1275 				vp->u.array = vq;
1276 				vp = vq;
1277 			}
1278 			vp->areap = vp_pipest->areap;
1279 			vp->ua.index = ++num;
1280 			vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
1281 			    ARRAY | INT_U | AINDEX;
1282  got_array:
1283 			vp->val.i = proc_errorlevel(p);
1284 			if (Flag(FPIPEFAIL) && vp->val.i)
1285 				rv = vp->val.i;
1286 			p = p->next;
1287 		}
1288 	} else if (Flag(FPIPEFAIL)) {
1289 		do {
1290 			const int i = proc_errorlevel(p);
1291 
1292 			if (i)
1293 				rv = i;
1294 		} while ((p = p->next));
1295 	}
1296 
1297 	if (!(flags & JW_ASYNCNOTIFY)
1298 #ifndef MKSH_UNEMPLOYED
1299 	    && (!Flag(FMONITOR) || j->state != PSTOPPED)
1300 #endif
1301 	    ) {
1302 		j_print(j, JP_SHORT, shl_out);
1303 		shf_flush(shl_out);
1304 	}
1305 	if (j->state != PSTOPPED
1306 #ifndef MKSH_UNEMPLOYED
1307 	    && (!Flag(FMONITOR) || !(flags & JW_ASYNCNOTIFY))
1308 #endif
1309 	    )
1310 		remove_job(j, where);
1311 
1312 	return (rv);
1313 }
1314 
1315 /*
1316  * SIGCHLD handler to reap children and update job states
1317  *
1318  * If jobs are compiled in then this routine expects sigchld to be blocked.
1319  */
1320 /* ARGSUSED */
1321 static void
j_sigchld(int sig MKSH_A_UNUSED)1322 j_sigchld(int sig MKSH_A_UNUSED)
1323 {
1324 	int saved_errno = errno;
1325 	Job *j;
1326 	Proc *p = NULL;
1327 	pid_t pid;
1328 	int status;
1329 	struct rusage ru0, ru1;
1330 #ifdef MKSH_NO_SIGSUSPEND
1331 	sigset_t omask;
1332 
1333 	/* this handler can run while SIGCHLD is not blocked, so block it now */
1334 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
1335 #endif
1336 
1337 #ifndef MKSH_NOPROSPECTOFWORK
1338 	/*
1339 	 * Don't wait for any processes if a job is partially started.
1340 	 * This is so we don't do away with the process group leader
1341 	 * before all the processes in a pipe line are started (so the
1342 	 * setpgid() won't fail)
1343 	 */
1344 	for (j = job_list; j; j = j->next)
1345 		if (j->ppid == procpid && !(j->flags & JF_STARTED)) {
1346 			held_sigchld = 1;
1347 			goto j_sigchld_out;
1348 		}
1349 #endif
1350 
1351 	getrusage(RUSAGE_CHILDREN, &ru0);
1352 	do {
1353 #ifndef MKSH_NOPROSPECTOFWORK
1354 		pid = waitpid(-1, &status, (WNOHANG |
1355 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1356 		    WCONTINUED |
1357 #endif
1358 		    WUNTRACED));
1359 #else
1360 		pid = wait(&status);
1361 #endif
1362 
1363 		/*
1364 		 * return if this would block (0) or no children
1365 		 * or interrupted (-1)
1366 		 */
1367 		if (pid <= 0)
1368 			goto j_sigchld_out;
1369 
1370 		getrusage(RUSAGE_CHILDREN, &ru1);
1371 
1372 		/* find job and process structures for this pid */
1373 		for (j = job_list; j != NULL; j = j->next)
1374 			for (p = j->proc_list; p != NULL; p = p->next)
1375 				if (p->pid == pid)
1376 					goto found;
1377  found:
1378 		if (j == NULL) {
1379 			/* Can occur if process has kids, then execs shell
1380 			warningf(true, "bad process waited for (pid = %d)",
1381 				pid);
1382 			 */
1383 			ru0 = ru1;
1384 			continue;
1385 		}
1386 
1387 		timeradd(&j->usrtime, &ru1.ru_utime, &j->usrtime);
1388 		timersub(&j->usrtime, &ru0.ru_utime, &j->usrtime);
1389 		timeradd(&j->systime, &ru1.ru_stime, &j->systime);
1390 		timersub(&j->systime, &ru0.ru_stime, &j->systime);
1391 		ru0 = ru1;
1392 		p->status = status;
1393 #ifndef MKSH_UNEMPLOYED
1394 		if (WIFSTOPPED(status))
1395 			p->state = PSTOPPED;
1396 		else
1397 #if defined(WCONTINUED) && defined(WIFCONTINUED)
1398 		  if (WIFCONTINUED(status)) {
1399 			p->state = j->state = PRUNNING;
1400 			/* skip check_job(), no-op in this case */
1401 			continue;
1402 		} else
1403 #endif
1404 #endif
1405 		  if (WIFSIGNALED(status))
1406 			p->state = PSIGNALLED;
1407 		else
1408 			p->state = PEXITED;
1409 
1410 		/* check to see if entire job is done */
1411 		check_job(j);
1412 	}
1413 #ifndef MKSH_NOPROSPECTOFWORK
1414 	    while (/* CONSTCOND */ 1);
1415 #else
1416 	    while (/* CONSTCOND */ 0);
1417 #endif
1418 
1419  j_sigchld_out:
1420 #ifdef MKSH_NO_SIGSUSPEND
1421 	sigprocmask(SIG_SETMASK, &omask, NULL);
1422 #endif
1423 	errno = saved_errno;
1424 }
1425 
1426 /*
1427  * Called only when a process in j has exited/stopped (ie, called only
1428  * from j_sigchld()). If no processes are running, the job status
1429  * and state are updated, asynchronous job notification is done and,
1430  * if unneeded, the job is removed.
1431  *
1432  * If jobs are compiled in then this routine expects sigchld to be blocked.
1433  */
1434 static void
check_job(Job * j)1435 check_job(Job *j)
1436 {
1437 	int jstate;
1438 	Proc *p;
1439 
1440 	/* XXX debugging (nasty - interrupt routine using shl_out) */
1441 	if (!(j->flags & JF_STARTED)) {
1442 		internal_warningf("check_job: job started (flags 0x%X)",
1443 		    (unsigned int)j->flags);
1444 		return;
1445 	}
1446 
1447 	jstate = PRUNNING;
1448 	for (p=j->proc_list; p != NULL; p = p->next) {
1449 		if (p->state == PRUNNING)
1450 			/* some processes still running */
1451 			return;
1452 		if (p->state > jstate)
1453 			jstate = p->state;
1454 	}
1455 	j->state = jstate;
1456 	j->status = proc_errorlevel(j->last_proc);
1457 
1458 	/*
1459 	 * Note when co-process dies: can't be done in j_wait() nor
1460 	 * remove_job() since neither may be called for non-interactive
1461 	 * shells.
1462 	 */
1463 	if (j->state == PEXITED || j->state == PSIGNALLED) {
1464 		/*
1465 		 * No need to keep co-process input any more
1466 		 * (at least, this is what ksh93d thinks)
1467 		 */
1468 		if (coproc.job == j) {
1469 			coproc.job = NULL;
1470 			/*
1471 			 * XXX would be nice to get the closes out of here
1472 			 * so they aren't done in the signal handler.
1473 			 * Would mean a check in coproc_getfd() to
1474 			 * do "if job == 0 && write >= 0, close write".
1475 			 */
1476 			coproc_write_close(coproc.write);
1477 		}
1478 		/* Do we need to keep the output? */
1479 		if (j->coproc_id && j->coproc_id == coproc.id &&
1480 		    --coproc.njobs == 0)
1481 			coproc_readw_close(coproc.read);
1482 	}
1483 
1484 	j->flags |= JF_CHANGED;
1485 #ifndef MKSH_UNEMPLOYED
1486 	if (Flag(FMONITOR) && !(j->flags & JF_XXCOM)) {
1487 		/*
1488 		 * Only put stopped jobs at the front to avoid confusing
1489 		 * the user (don't want finished jobs effecting %+ or %-)
1490 		 */
1491 		if (j->state == PSTOPPED)
1492 			put_job(j, PJ_ON_FRONT);
1493 		if (Flag(FNOTIFY) &&
1494 		    (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
1495 			/* Look for the real file descriptor 2 */
1496 			{
1497 				struct env *ep;
1498 				int fd = 2;
1499 
1500 				for (ep = e; ep; ep = ep->oenv)
1501 					if (ep->savefd && ep->savefd[2])
1502 						fd = ep->savefd[2];
1503 				shf_reopen(fd, SHF_WR, shl_j);
1504 			}
1505 			/*
1506 			 * Can't call j_notify() as it removes jobs. The job
1507 			 * must stay in the job list as j_waitj() may be
1508 			 * running with this job.
1509 			 */
1510 			j_print(j, JP_MEDIUM, shl_j);
1511 			shf_flush(shl_j);
1512 			if (!(j->flags & JF_WAITING) && j->state != PSTOPPED)
1513 				remove_job(j, "notify");
1514 		}
1515 	}
1516 #endif
1517 	if (
1518 #ifndef MKSH_UNEMPLOYED
1519 	    !Flag(FMONITOR) &&
1520 #endif
1521 	    !(j->flags & (JF_WAITING|JF_FG)) &&
1522 	    j->state != PSTOPPED) {
1523 		if (j == async_job || (j->flags & JF_KNOWN)) {
1524 			j->flags |= JF_ZOMBIE;
1525 			j->job = -1;
1526 			nzombie++;
1527 		} else
1528 			remove_job(j, "checkjob");
1529 	}
1530 }
1531 
1532 /*
1533  * Print job status in either short, medium or long format.
1534  *
1535  * If jobs are compiled in then this routine expects sigchld to be blocked.
1536  */
1537 static void
j_print(Job * j,int how,struct shf * shf)1538 j_print(Job *j, int how, struct shf *shf)
1539 {
1540 	Proc *p;
1541 	int state;
1542 	int status;
1543 #ifdef WCOREDUMP
1544 	bool coredumped;
1545 #endif
1546 	char jobchar = ' ';
1547 	char buf[64];
1548 	const char *filler;
1549 	int output = 0;
1550 
1551 	if (how == JP_PGRP) {
1552 		/*
1553 		 * POSIX doesn't say what to do it there is no process
1554 		 * group leader (ie, !FMONITOR). We arbitrarily return
1555 		 * last pid (which is what $! returns).
1556 		 */
1557 		shf_fprintf(shf, Tf_dN, (int)(j->pgrp ? j->pgrp :
1558 		    (j->last_proc ? j->last_proc->pid : 0)));
1559 		return;
1560 	}
1561 	j->flags &= ~JF_CHANGED;
1562 	filler = j->job > 10 ? "\n       " : "\n      ";
1563 	if (j == job_list)
1564 		jobchar = '+';
1565 	else if (j == job_list->next)
1566 		jobchar = '-';
1567 
1568 	for (p = j->proc_list; p != NULL;) {
1569 #ifdef WCOREDUMP
1570 		coredumped = false;
1571 #endif
1572 		switch (p->state) {
1573 		case PRUNNING:
1574 			memcpy(buf, "Running", 8);
1575 			break;
1576 		case PSTOPPED: {
1577 			int stopsig = WSTOPSIG(p->status);
1578 
1579 			strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
1580 			    sigtraps[stopsig].mess : "Stopped", sizeof(buf));
1581 			break;
1582 		}
1583 		case PEXITED: {
1584 			int exitstatus = (WEXITSTATUS(p->status)) & 255;
1585 
1586 			if (how == JP_SHORT)
1587 				buf[0] = '\0';
1588 			else if (exitstatus == 0)
1589 				memcpy(buf, "Done", 5);
1590 			else
1591 				shf_snprintf(buf, sizeof(buf), "Done (%d)",
1592 				    exitstatus);
1593 			break;
1594 		}
1595 		case PSIGNALLED: {
1596 			int termsig = WTERMSIG(p->status);
1597 #ifdef WCOREDUMP
1598 			if (WCOREDUMP(p->status))
1599 				coredumped = true;
1600 #endif
1601 			/*
1602 			 * kludge for not reporting 'normal termination
1603 			 * signals' (i.e. SIGINT, SIGPIPE)
1604 			 */
1605 			if (how == JP_SHORT &&
1606 #ifdef WCOREDUMP
1607 			    !coredumped &&
1608 #endif
1609 			    (termsig == SIGINT || termsig == SIGPIPE)) {
1610 				buf[0] = '\0';
1611 			} else
1612 				strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
1613 				    sigtraps[termsig].mess : "Signalled",
1614 				    sizeof(buf));
1615 			break;
1616 		}
1617 		default:
1618 			buf[0] = '\0';
1619 		}
1620 
1621 		if (how != JP_SHORT) {
1622 			if (p == j->proc_list)
1623 				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
1624 			else
1625 				shf_puts(filler, shf);
1626 		}
1627 
1628 		if (how == JP_LONG)
1629 			shf_fprintf(shf, "%5d ", (int)p->pid);
1630 
1631 		if (how == JP_SHORT) {
1632 			if (buf[0]) {
1633 				output = 1;
1634 #ifdef WCOREDUMP
1635 				shf_fprintf(shf, "%s%s ",
1636 				    buf, coredumped ? " (core dumped)" : null);
1637 #else
1638 				shf_puts(buf, shf);
1639 				shf_putchar(' ', shf);
1640 #endif
1641 			}
1642 		} else {
1643 			output = 1;
1644 			shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
1645 			    p->next ? "|" : null,
1646 #ifdef WCOREDUMP
1647 			    coredumped ? " (core dumped)" :
1648 #endif
1649 			     null);
1650 		}
1651 
1652 		state = p->state;
1653 		status = p->status;
1654 		p = p->next;
1655 		while (p && p->state == state && p->status == status) {
1656 			if (how == JP_LONG)
1657 				shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
1658 				    (int)p->pid, T1space, p->command,
1659 				    p->next ? "|" : null);
1660 			else if (how == JP_MEDIUM)
1661 				shf_fprintf(shf, Tf__ss, p->command,
1662 				    p->next ? "|" : null);
1663 			p = p->next;
1664 		}
1665 	}
1666 	if (output)
1667 		shf_putc('\n', shf);
1668 }
1669 
1670 /*
1671  * Convert % sequence to job
1672  *
1673  * If jobs are compiled in then this routine expects sigchld to be blocked.
1674  */
1675 static Job *
j_lookup(const char * cp,int * ecodep)1676 j_lookup(const char *cp, int *ecodep)
1677 {
1678 	Job *j, *last_match;
1679 	Proc *p;
1680 	size_t len;
1681 	int job = 0;
1682 
1683 	if (ctype(*cp, C_DIGIT) && getn(cp, &job)) {
1684 		/* Look for last_proc->pid (what $! returns) first... */
1685 		for (j = job_list; j != NULL; j = j->next)
1686 			if (j->last_proc && j->last_proc->pid == job)
1687 				return (j);
1688 		/*
1689 		 * ...then look for process group (this is non-POSIX,
1690 		 * but should not break anything
1691 		 */
1692 		for (j = job_list; j != NULL; j = j->next)
1693 			if (j->pgrp && j->pgrp == job)
1694 				return (j);
1695 		goto j_lookup_nosuch;
1696 	}
1697 	if (*cp != '%') {
1698  j_lookup_invalid:
1699 		if (ecodep)
1700 			*ecodep = JL_INVALID;
1701 		return (NULL);
1702 	}
1703 	switch (*++cp) {
1704 	case '\0': /* non-standard */
1705 	case '+':
1706 	case '%':
1707 		if (job_list != NULL)
1708 			return (job_list);
1709 		break;
1710 
1711 	case '-':
1712 		if (job_list != NULL && job_list->next)
1713 			return (job_list->next);
1714 		break;
1715 
1716 	case '0': case '1': case '2': case '3': case '4':
1717 	case '5': case '6': case '7': case '8': case '9':
1718 		if (!getn(cp, &job))
1719 			goto j_lookup_invalid;
1720 		for (j = job_list; j != NULL; j = j->next)
1721 			if (j->job == job)
1722 				return (j);
1723 		break;
1724 
1725 	/* %?string */
1726 	case '?':
1727 		last_match = NULL;
1728 		for (j = job_list; j != NULL; j = j->next)
1729 			for (p = j->proc_list; p != NULL; p = p->next)
1730 				if (strstr(p->command, cp+1) != NULL) {
1731 					if (last_match) {
1732 						if (ecodep)
1733 							*ecodep = JL_AMBIG;
1734 						return (NULL);
1735 					}
1736 					last_match = j;
1737 				}
1738 		if (last_match)
1739 			return (last_match);
1740 		break;
1741 
1742 	/* %string */
1743 	default:
1744 		len = strlen(cp);
1745 		last_match = NULL;
1746 		for (j = job_list; j != NULL; j = j->next)
1747 			if (strncmp(cp, j->proc_list->command, len) == 0) {
1748 				if (last_match) {
1749 					if (ecodep)
1750 						*ecodep = JL_AMBIG;
1751 					return (NULL);
1752 				}
1753 				last_match = j;
1754 			}
1755 		if (last_match)
1756 			return (last_match);
1757 		break;
1758 	}
1759  j_lookup_nosuch:
1760 	if (ecodep)
1761 		*ecodep = JL_NOSUCH;
1762 	return (NULL);
1763 }
1764 
1765 static Job	*free_jobs;
1766 static Proc	*free_procs;
1767 
1768 /*
1769  * allocate a new job and fill in the job number.
1770  *
1771  * If jobs are compiled in then this routine expects sigchld to be blocked.
1772  */
1773 static Job *
new_job(void)1774 new_job(void)
1775 {
1776 	int i;
1777 	Job *newj, *j;
1778 
1779 	if (free_jobs != NULL) {
1780 		newj = free_jobs;
1781 		free_jobs = free_jobs->next;
1782 	} else {
1783 		char *cp;
1784 
1785 		/*
1786 		 * struct job includes ALLOC_ITEM for alignment constraints
1787 		 * so first get the actually used memory, then assign it
1788 		 */
1789 		cp = alloc(sizeof(Job) - sizeof(ALLOC_ITEM), APERM);
1790 		/* undo what alloc() did to the malloc result address */
1791 		newj = (void *)(cp - sizeof(ALLOC_ITEM));
1792 	}
1793 
1794 	/* brute force method */
1795 	i = 0;
1796 	do {
1797 		++i;
1798 		j = job_list;
1799 		while (j && j->job != i)
1800 			j = j->next;
1801 	} while (j);
1802 	newj->job = i;
1803 
1804 	return (newj);
1805 }
1806 
1807 /*
1808  * Allocate new process struct
1809  *
1810  * If jobs are compiled in then this routine expects sigchld to be blocked.
1811  */
1812 static Proc *
new_proc(void)1813 new_proc(void)
1814 {
1815 	Proc *p;
1816 
1817 	if (free_procs != NULL) {
1818 		p = free_procs;
1819 		free_procs = free_procs->next;
1820 	} else
1821 		p = alloc(sizeof(Proc), APERM);
1822 
1823 	return (p);
1824 }
1825 
1826 /*
1827  * Take job out of job_list and put old structures into free list.
1828  * Keeps nzombies, last_job and async_job up to date.
1829  *
1830  * If jobs are compiled in then this routine expects sigchld to be blocked.
1831  */
1832 static void
remove_job(Job * j,const char * where)1833 remove_job(Job *j, const char *where)
1834 {
1835 	Proc *p, *tmp;
1836 	Job **prev, *curr;
1837 
1838 	prev = &job_list;
1839 	curr = job_list;
1840 	while (curr && curr != j) {
1841 		prev = &curr->next;
1842 		curr = *prev;
1843 	}
1844 	if (curr != j) {
1845 		internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
1846 		return;
1847 	}
1848 	*prev = curr->next;
1849 
1850 	/* free up proc structures */
1851 	for (p = j->proc_list; p != NULL; ) {
1852 		tmp = p;
1853 		p = p->next;
1854 		tmp->next = free_procs;
1855 		free_procs = tmp;
1856 	}
1857 
1858 	if ((j->flags & JF_ZOMBIE) && j->ppid == procpid)
1859 		--nzombie;
1860 	j->next = free_jobs;
1861 	free_jobs = j;
1862 
1863 	if (j == last_job)
1864 		last_job = NULL;
1865 	if (j == async_job)
1866 		async_job = NULL;
1867 }
1868 
1869 /*
1870  * put j in a particular location (taking it out job_list if it is there
1871  * already)
1872  *
1873  * If jobs are compiled in then this routine expects sigchld to be blocked.
1874  */
1875 static void
put_job(Job * j,int where)1876 put_job(Job *j, int where)
1877 {
1878 	Job **prev, *curr;
1879 
1880 	/* Remove job from list (if there) */
1881 	prev = &job_list;
1882 	curr = job_list;
1883 	while (curr && curr != j) {
1884 		prev = &curr->next;
1885 		curr = *prev;
1886 	}
1887 	if (curr == j)
1888 		*prev = curr->next;
1889 
1890 	switch (where) {
1891 	case PJ_ON_FRONT:
1892 		j->next = job_list;
1893 		job_list = j;
1894 		break;
1895 
1896 	case PJ_PAST_STOPPED:
1897 		prev = &job_list;
1898 		curr = job_list;
1899 		for (; curr && curr->state == PSTOPPED; prev = &curr->next,
1900 		    curr = *prev)
1901 			;
1902 		j->next = curr;
1903 		*prev = j;
1904 		break;
1905 	}
1906 }
1907 
1908 /*
1909  * nuke a job (called when unable to start full job).
1910  *
1911  * If jobs are compiled in then this routine expects sigchld to be blocked.
1912  */
1913 static int
kill_job(Job * j,int sig)1914 kill_job(Job *j, int sig)
1915 {
1916 	Proc *p;
1917 	int rval = 0;
1918 
1919 	for (p = j->proc_list; p != NULL; p = p->next)
1920 		if (p->pid != 0)
1921 			if (kill(p->pid, sig) < 0)
1922 				rval = -1;
1923 	return (rval);
1924 }
1925 
1926 static void
tty_init_talking(void)1927 tty_init_talking(void)
1928 {
1929 	switch (tty_init_fd()) {
1930 	case 0:
1931 		break;
1932 	case 1:
1933 #ifndef MKSH_DISABLE_TTY_WARNING
1934 		warningf(false, Tf_sD_s_sD_s,
1935 		    "No controlling tty", Topen, T_devtty, cstrerror(errno));
1936 #endif
1937 		break;
1938 	case 2:
1939 #ifndef MKSH_DISABLE_TTY_WARNING
1940 		warningf(false, Tf_s_sD_s, Tcant_find, Ttty_fd,
1941 		    cstrerror(errno));
1942 #endif
1943 		break;
1944 	case 3:
1945 		warningf(false, Tf_ssfaileds, "j_ttyinit",
1946 		    Ttty_fd_dupof, cstrerror(errno));
1947 		break;
1948 	case 4:
1949 		warningf(false, Tf_sD_sD_s, "j_ttyinit",
1950 		    "can't set close-on-exec flag", cstrerror(errno));
1951 		break;
1952 	}
1953 }
1954 
1955 static void
tty_init_state(void)1956 tty_init_state(void)
1957 {
1958 	if (tty_fd >= 0) {
1959 		mksh_tcget(tty_fd, &tty_state);
1960 		tty_hasstate = true;
1961 	}
1962 }
1963