xref: /freebsd/sys/kern/kern_exit.c (revision e8b9b6b9f31c463137b4104550bfb3286a43703a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include "opt_ddb.h"
38 #include "opt_ktrace.h"
39 
40 #define EXTERR_CATEGORY	EXTERR_CAT_PROCEXIT
41 #include <sys/systm.h>
42 #include <sys/acct.h>		/* for acct_process() function prototype */
43 #include <sys/capsicum.h>
44 #include <sys/eventhandler.h>
45 #include <sys/exterrvar.h>
46 #include <sys/filedesc.h>
47 #include <sys/jail.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/procdesc.h>
55 #include <sys/ptrace.h>
56 #include <sys/racct.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sbuf.h>
59 #include <sys/sched.h>
60 #include <sys/sdt.h>
61 #include <sys/sem.h>
62 #include <sys/shm.h>
63 #include <sys/signalvar.h>
64 #include <sys/sx.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/sysctl.h>
67 #include <sys/sysent.h>
68 #include <sys/syslog.h>
69 #include <sys/sysproto.h>
70 #include <sys/timers.h>
71 #include <sys/tty.h>
72 #include <sys/umtxvar.h>
73 #include <sys/vmmeter.h>
74 #include <sys/vnode.h>
75 #include <sys/wait.h>
76 #ifdef KTRACE
77 #include <sys/ktrace.h>
78 #endif
79 
80 #include <security/audit/audit.h>
81 #include <security/mac/mac_framework.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/uma.h>
90 
91 #ifdef KDTRACE_HOOKS
92 #include <sys/dtrace_bsd.h>
93 dtrace_execexit_func_t	dtrace_fasttrap_exit;
94 #endif
95 
96 SDT_PROVIDER_DECLARE(proc);
97 SDT_PROBE_DEFINE1(proc, , , exit, "int");
98 
99 static int kern_kill_on_dbg_exit = 1;
100 SYSCTL_INT(_kern, OID_AUTO, kill_on_debugger_exit, CTLFLAG_RWTUN,
101     &kern_kill_on_dbg_exit, 0,
102     "Kill ptraced processes when debugger exits");
103 
104 static bool kern_wait_dequeue_sigchld = 1;
105 SYSCTL_BOOL(_kern, OID_AUTO, wait_dequeue_sigchld, CTLFLAG_RWTUN,
106     &kern_wait_dequeue_sigchld, 0,
107     "Dequeue SIGCHLD on wait(2) for live process");
108 
109 struct proc *
proc_realparent(struct proc * child)110 proc_realparent(struct proc *child)
111 {
112 	struct proc *p, *parent;
113 
114 	sx_assert(&proctree_lock, SX_LOCKED);
115 	if ((child->p_treeflag & P_TREE_ORPHANED) == 0)
116 		return (child->p_pptr->p_pid == child->p_oppid ?
117 		    child->p_pptr : child->p_reaper);
118 	for (p = child; (p->p_treeflag & P_TREE_FIRST_ORPHAN) == 0;) {
119 		/* Cannot use LIST_PREV(), since the list head is not known. */
120 		p = __containerof(p->p_orphan.le_prev, struct proc,
121 		    p_orphan.le_next);
122 		KASSERT((p->p_treeflag & P_TREE_ORPHANED) != 0,
123 		    ("missing P_ORPHAN %p", p));
124 	}
125 	parent = __containerof(p->p_orphan.le_prev, struct proc,
126 	    p_orphans.lh_first);
127 	KASSERT(child->p_pptr != parent,
128 	    ("proc %d %p orphaned but parent %d %p is realparent",
129 	    child->p_pid, child, parent->p_pid, parent));
130 	return (parent);
131 }
132 
133 static void
reaper_clear(struct proc * p,struct proc * rp)134 reaper_clear(struct proc *p, struct proc *rp)
135 {
136 	struct proc *p1;
137 	bool clear;
138 
139 	sx_assert(&proctree_lock, SX_XLOCKED);
140 	LIST_REMOVE(p, p_reapsibling);
141 	if (p->p_reapsubtree == 1)
142 		return;
143 	clear = true;
144 	LIST_FOREACH(p1, &rp->p_reaplist, p_reapsibling) {
145 		if (p1->p_reapsubtree == p->p_reapsubtree) {
146 			clear = false;
147 			break;
148 		}
149 	}
150 	if (clear)
151 		proc_id_clear(PROC_ID_REAP, p->p_reapsubtree);
152 }
153 
154 void
reaper_abandon_children(struct proc * p,bool exiting)155 reaper_abandon_children(struct proc *p, bool exiting)
156 {
157 	struct proc *p1, *p2, *ptmp;
158 
159 	sx_assert(&proctree_lock, SX_XLOCKED);
160 	KASSERT(p != initproc, ("reaper_abandon_children for initproc"));
161 	if ((p->p_treeflag & P_TREE_REAPER) == 0)
162 		return;
163 	p1 = p->p_reaper;
164 	LIST_FOREACH_SAFE(p2, &p->p_reaplist, p_reapsibling, ptmp) {
165 		reaper_clear(p2, p);
166 		p2->p_reaper = p1;
167 		p2->p_reapsubtree = p->p_reapsubtree;
168 		LIST_INSERT_HEAD(&p1->p_reaplist, p2, p_reapsibling);
169 		if (exiting && p2->p_pptr == p) {
170 			PROC_LOCK(p2);
171 			proc_reparent(p2, p1, true);
172 			PROC_UNLOCK(p2);
173 		}
174 	}
175 	KASSERT(LIST_EMPTY(&p->p_reaplist), ("p_reaplist not empty"));
176 	p->p_treeflag &= ~P_TREE_REAPER;
177 }
178 
179 void
proc_clear_orphan(struct proc * p)180 proc_clear_orphan(struct proc *p)
181 {
182 	struct proc *p1;
183 
184 	sx_assert(&proctree_lock, SA_XLOCKED);
185 	if ((p->p_treeflag & P_TREE_ORPHANED) == 0)
186 		return;
187 	if ((p->p_treeflag & P_TREE_FIRST_ORPHAN) != 0) {
188 		p1 = LIST_NEXT(p, p_orphan);
189 		if (p1 != NULL)
190 			p1->p_treeflag |= P_TREE_FIRST_ORPHAN;
191 		p->p_treeflag &= ~P_TREE_FIRST_ORPHAN;
192 	}
193 	LIST_REMOVE(p, p_orphan);
194 	p->p_treeflag &= ~P_TREE_ORPHANED;
195 }
196 
197 void
exit_onexit(struct proc * p)198 exit_onexit(struct proc *p)
199 {
200 	MPASS(p->p_numthreads == 1);
201 	umtx_thread_exit(FIRST_THREAD_IN_PROC(p));
202 }
203 
204 /*
205  * exit -- death of process.
206  */
207 int
sys__exit(struct thread * td,struct _exit_args * uap)208 sys__exit(struct thread *td, struct _exit_args *uap)
209 {
210 	kern_exit(td, uap->rval, 0);
211 	return (0);
212 }
213 
214 void
proc_set_p2_wexit(struct proc * p)215 proc_set_p2_wexit(struct proc *p)
216 {
217 	PROC_LOCK_ASSERT(p, MA_OWNED);
218 	p->p_flag2 |= P2_WEXIT;
219 }
220 
221 static void
ast_async_exit(struct thread * td,int asts)222 ast_async_exit(struct thread *td, int asts)
223 {
224 	struct proc *p;
225 
226 	p = td->td_proc;
227 	if ((p->p_flag & P_ASYNC_EXIT) != 0)
228 		exit1(td, p->p_xexit, p->p_asig);
229 }
230 
231 /*
232  * The variation on exit1() intended to be used in the syscall
233  * handlers.  Unlike exit1(), it might delay the current process exit
234  * to ast.  This is needed e.g. when _exit(2) is executed due to the
235  * ptrace(PT_SC_REMOTERQ), which must do more work after the syscall
236  * handler call.
237  */
238 void
kern_exit(struct thread * td,int rval,int signo)239 kern_exit(struct thread *td, int rval, int signo)
240 {
241 	struct proc *p;
242 
243 	KASSERT(rval == 0 || signo == 0,
244 	    ("kern_exit rv %d sig %d", rval, signo));
245 
246 	p = td->td_proc;
247 	if ((td->td_dbgflags & TDB_SCREMOTEREQ) != 0) {
248 		PROC_LOCK(p);
249 		p->p_xexit = rval;
250 		p->p_asig = signo;
251 		p->p_flag |= P_ASYNC_EXIT;
252 		ast_sched(td, TDA_ASYNC_EXIT);
253 		PROC_UNLOCK(p);
254 		return;
255 	}
256 	if ((p->p_flag & P_ASYNC_EXIT) != 0) {
257 		rval = p->p_xexit;
258 		signo = p->p_asig;
259 	}
260 	exit1(td, rval, signo);
261 }
262 
263 /*
264  * Exit: deallocate address space and other resources, change proc state to
265  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
266  * and rusage for wait().  Check for child processes and orphan them.
267  */
268 void
exit1(struct thread * td,int rval,int signo)269 exit1(struct thread *td, int rval, int signo)
270 {
271 	struct proc *p, *nq, *q, *t;
272 	struct thread *tdt;
273 	ksiginfo_t *ksi, *ksi1;
274 	int signal_parent;
275 
276 	mtx_assert(&Giant, MA_NOTOWNED);
277 	KASSERT(rval == 0 || signo == 0, ("exit1 rv %d sig %d", rval, signo));
278 	MPASS((td->td_dbgflags & TDB_SCREMOTEREQ) == 0);
279 	TSPROCEXIT(td->td_proc->p_pid);
280 
281 	p = td->td_proc;
282 	/*
283 	 * In case we're rebooting we just let init die in order to
284 	 * work around an issues where pid 1 might get a fatal signal.
285 	 * For instance, if network interface serving NFS root is
286 	 * going down due to reboot, page-in requests for text are
287 	 * failing.
288 	 */
289 	if (p == initproc && rebooting == 0) {
290 		printf("init died (signal %d, exit %d)\n", signo, rval);
291 		panic("Going nowhere without my init!");
292 	}
293 
294 	/*
295 	 * Process deferred operations, designated with ASTF_KCLEAR.
296 	 * For instance, we need to deref SU mp, since the thread does
297 	 * not return to userspace, and wait for geom to stabilize.
298 	 */
299 	ast_kclear(td);
300 
301 	/*
302 	 * MUST abort all other threads before proceeding past here.
303 	 */
304 	PROC_LOCK(p);
305 	proc_set_p2_wexit(p);
306 
307 	/*
308 	 * First check if some other thread or external request got
309 	 * here before us.  If so, act appropriately: exit or suspend.
310 	 * We must ensure that stop requests are handled before we set
311 	 * P_WEXIT.
312 	 */
313 	thread_suspend_check(0);
314 	while (p->p_flag & P_HADTHREADS) {
315 		/*
316 		 * Kill off the other threads. This requires
317 		 * some co-operation from other parts of the kernel
318 		 * so it may not be instantaneous.  With this state set
319 		 * any thread attempting to interruptibly
320 		 * sleep will return immediately with EINTR or EWOULDBLOCK
321 		 * which will hopefully force them to back out to userland
322 		 * freeing resources as they go.  Any thread attempting
323 		 * to return to userland will thread_exit() from ast().
324 		 * thread_exit() will unsuspend us when the last of the
325 		 * other threads exits.
326 		 * If there is already a thread singler after resumption,
327 		 * calling thread_single() will fail; in that case, we just
328 		 * re-check all suspension request, the thread should
329 		 * either be suspended there or exit.
330 		 */
331 		if (!thread_single(p, SINGLE_EXIT))
332 			/*
333 			 * All other activity in this process is now
334 			 * stopped.  Threading support has been turned
335 			 * off.
336 			 */
337 			break;
338 		/*
339 		 * Recheck for new stop or suspend requests which
340 		 * might appear while process lock was dropped in
341 		 * thread_single().
342 		 */
343 		thread_suspend_check(0);
344 	}
345 	KASSERT(p->p_numthreads == 1,
346 	    ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
347 	racct_sub(p, RACCT_NTHR, 1);
348 
349 	/* Let event handler change exit status */
350 	p->p_xexit = rval;
351 	p->p_xsig = signo;
352 
353 	/*
354 	 * Ignore any pending request to stop due to a stop signal.
355 	 * Once P_WEXIT is set, future requests will be ignored as
356 	 * well.
357 	 */
358 	p->p_flag &= ~P_STOPPED_SIG;
359 	KASSERT(!P_SHOULDSTOP(p), ("exiting process is stopped"));
360 
361 	/* Note that we are exiting. */
362 	p->p_flag |= P_WEXIT;
363 
364 	/*
365 	 * Wait for any processes that have a hold on our vmspace to
366 	 * release their reference.
367 	 */
368 	while (p->p_lock > 0)
369 		msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
370 
371 	MPASS(p->p_execblock == 0);
372 	PROC_UNLOCK(p);
373 	/* Drain the limit callout while we don't have the proc locked */
374 	callout_drain(&p->p_limco);
375 
376 #ifdef AUDIT
377 	/*
378 	 * The Sun BSM exit token contains two components: an exit status as
379 	 * passed to exit(), and a return value to indicate what sort of exit
380 	 * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
381 	 * what the return value is.
382 	 */
383 	AUDIT_ARG_EXIT(rval, 0);
384 	AUDIT_SYSCALL_EXIT(0, td);
385 #endif
386 
387 	/* Are we a task leader with peers? */
388 	if (p->p_peers != NULL && p == p->p_leader) {
389 		mtx_lock(&ppeers_lock);
390 		q = p->p_peers;
391 		while (q != NULL) {
392 			PROC_LOCK(q);
393 			kern_psignal(q, SIGKILL);
394 			PROC_UNLOCK(q);
395 			q = q->p_peers;
396 		}
397 		while (p->p_peers != NULL)
398 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
399 		mtx_unlock(&ppeers_lock);
400 	}
401 
402 	itimers_exit(p);
403 
404 	/*
405 	 * Check if any loadable modules need anything done at process exit.
406 	 * E.g. SYSV IPC stuff.
407 	 * Event handler could change exit status.
408 	 * XXX what if one of these generates an error?
409 	 */
410 	EVENTHANDLER_DIRECT_INVOKE(process_exit, p);
411 
412 	/*
413 	 * If parent is waiting for us to exit or exec,
414 	 * P_PPWAIT is set; we will wakeup the parent below.
415 	 */
416 	PROC_LOCK(p);
417 	stopprofclock(p);
418 	p->p_ptevents = 0;
419 
420 	/*
421 	 * Stop the real interval timer.  If the handler is currently
422 	 * executing, prevent it from rearming itself and let it finish.
423 	 */
424 	p->p_flag2 &= ~P2_ITSTOPPED;
425 	if (timevalisset(&p->p_realtimer.it_value) &&
426 	    callout_stop(&p->p_itcallout) == 0) {
427 		timevalclear(&p->p_realtimer.it_interval);
428 		PROC_UNLOCK(p);
429 		callout_drain(&p->p_itcallout);
430 	} else {
431 		PROC_UNLOCK(p);
432 	}
433 
434 	if (p->p_sysent->sv_onexit != NULL)
435 		p->p_sysent->sv_onexit(p);
436 	seltdfini(td);
437 
438 	/*
439 	 * Reset any sigio structures pointing to us as a result of
440 	 * F_SETOWN with our pid.  The P_WEXIT flag interlocks with fsetown().
441 	 */
442 	funsetownlst(&p->p_sigiolst);
443 
444 	/*
445 	 * Close open files and release open-file table.
446 	 * This may block!
447 	 */
448 	pdescfree(td);
449 	fdescfree(td);
450 
451 	/*
452 	 * Remove ourself from our leader's peer list and wake our leader.
453 	 */
454 	if (p->p_leader->p_peers != NULL) {
455 		mtx_lock(&ppeers_lock);
456 		if (p->p_leader->p_peers != NULL) {
457 			q = p->p_leader;
458 			while (q->p_peers != p)
459 				q = q->p_peers;
460 			q->p_peers = p->p_peers;
461 			wakeup(p->p_leader);
462 		}
463 		mtx_unlock(&ppeers_lock);
464 	}
465 
466 	exec_free_abi_mappings(p);
467 	vmspace_exit(td);
468 	(void)acct_process(td);
469 
470 #ifdef KTRACE
471 	ktrprocexit(td);
472 #endif
473 	/*
474 	 * Release reference to text vnode etc
475 	 */
476 	if (p->p_textvp != NULL) {
477 		vrele(p->p_textvp);
478 		p->p_textvp = NULL;
479 	}
480 	if (p->p_textdvp != NULL) {
481 		vrele(p->p_textdvp);
482 		p->p_textdvp = NULL;
483 	}
484 	if (p->p_binname != NULL) {
485 		free(p->p_binname, M_PARGS);
486 		p->p_binname = NULL;
487 	}
488 
489 	/*
490 	 * Release our limits structure.
491 	 */
492 	lim_free(p->p_limit);
493 	p->p_limit = NULL;
494 
495 	tidhash_remove(td);
496 
497 	/*
498 	 * Call machine-dependent code to release any
499 	 * machine-dependent resources other than the address space.
500 	 * The address space is released by "vmspace_exitfree(p)" in
501 	 * vm_waitproc().
502 	 */
503 	cpu_exit(td);
504 
505 	WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
506 
507 	/*
508 	 * Remove from allproc. It still sits in the hash.
509 	 */
510 	sx_xlock(&allproc_lock);
511 	LIST_REMOVE(p, p_list);
512 
513 #ifdef DDB
514 	/*
515 	 * Used by ddb's 'ps' command to find this process via the
516 	 * pidhash.
517 	 */
518 	p->p_list.le_prev = NULL;
519 #endif
520 	prison_proc_unlink(p->p_ucred->cr_prison, p);
521 	sx_xunlock(&allproc_lock);
522 
523 	sx_xlock(&proctree_lock);
524 	if ((p->p_flag & (P_TRACED | P_PPWAIT | P_PPTRACE)) != 0) {
525 		PROC_LOCK(p);
526 		p->p_flag &= ~(P_TRACED | P_PPWAIT | P_PPTRACE);
527 		PROC_UNLOCK(p);
528 	}
529 
530 	/*
531 	 * killjobc() might drop and re-acquire proctree_lock to
532 	 * revoke control tty if exiting process was a session leader.
533 	 */
534 	killjobc();
535 
536 	/*
537 	 * Reparent all children processes:
538 	 * - traced ones to the original parent (or init if we are that parent)
539 	 * - the rest to init
540 	 */
541 	q = LIST_FIRST(&p->p_children);
542 	if (q != NULL)		/* only need this if any child is S_ZOMB */
543 		wakeup(q->p_reaper);
544 	for (; q != NULL; q = nq) {
545 		nq = LIST_NEXT(q, p_sibling);
546 		ksi = ksiginfo_alloc(M_WAITOK);
547 		PROC_LOCK(q);
548 		q->p_sigparent = SIGCHLD;
549 
550 		if ((q->p_flag & P_TRACED) == 0) {
551 			proc_reparent(q, q->p_reaper, true);
552 			if (q->p_state == PRS_ZOMBIE) {
553 				/*
554 				 * Inform reaper about the reparented
555 				 * zombie, since wait(2) has something
556 				 * new to report.  Guarantee queueing
557 				 * of the SIGCHLD signal, similar to
558 				 * the _exit() behaviour, by providing
559 				 * our ksiginfo.  Ksi is freed by the
560 				 * signal delivery.
561 				 */
562 				if (q->p_ksi == NULL) {
563 					ksi1 = NULL;
564 				} else {
565 					ksiginfo_copy(q->p_ksi, ksi);
566 					ksi->ksi_flags |= KSI_INS;
567 					ksi1 = ksi;
568 					ksi = NULL;
569 				}
570 				PROC_LOCK(q->p_reaper);
571 				pksignal(q->p_reaper, SIGCHLD, ksi1);
572 				PROC_UNLOCK(q->p_reaper);
573 			} else if (q->p_pdeathsig > 0) {
574 				/*
575 				 * The child asked to received a signal
576 				 * when we exit.
577 				 */
578 				kern_psignal(q, q->p_pdeathsig);
579 			}
580 		} else {
581 			/*
582 			 * Traced processes are killed by default
583 			 * since their existence means someone is
584 			 * screwing up.
585 			 */
586 			t = proc_realparent(q);
587 			if (t == p) {
588 				proc_reparent(q, q->p_reaper, true);
589 			} else {
590 				PROC_LOCK(t);
591 				proc_reparent(q, t, true);
592 				PROC_UNLOCK(t);
593 			}
594 			/*
595 			 * Since q was found on our children list, the
596 			 * proc_reparent() call moved q to the orphan
597 			 * list due to present P_TRACED flag. Clear
598 			 * orphan link for q now while q is locked.
599 			 */
600 			proc_clear_orphan(q);
601 			q->p_flag &= ~P_TRACED;
602 			q->p_flag2 &= ~P2_PTRACE_FSTP;
603 			q->p_ptevents = 0;
604 			p->p_xthread = NULL;
605 			FOREACH_THREAD_IN_PROC(q, tdt) {
606 				tdt->td_dbgflags &= ~(TDB_SUSPEND | TDB_XSIG |
607 				    TDB_FSTP);
608 				tdt->td_xsig = 0;
609 			}
610 			if (kern_kill_on_dbg_exit) {
611 				q->p_flag &= ~P_STOPPED_TRACE;
612 				kern_psignal(q, SIGKILL);
613 			} else if ((q->p_flag & (P_STOPPED_TRACE |
614 			    P_STOPPED_SIG)) != 0) {
615 				sigqueue_delete_proc(q, SIGTRAP);
616 				ptrace_unsuspend(q);
617 			}
618 		}
619 		PROC_UNLOCK(q);
620 		if (ksi != NULL)
621 			ksiginfo_free(ksi);
622 	}
623 
624 	/*
625 	 * Also get rid of our orphans.
626 	 */
627 	while ((q = LIST_FIRST(&p->p_orphans)) != NULL) {
628 		PROC_LOCK(q);
629 		KASSERT(q->p_oppid == p->p_pid,
630 		    ("orphan %p of %p has unexpected oppid %d", q, p,
631 		    q->p_oppid));
632 		q->p_oppid = q->p_reaper->p_pid;
633 
634 		/*
635 		 * If we are the real parent of this process
636 		 * but it has been reparented to a debugger, then
637 		 * check if it asked for a signal when we exit.
638 		 */
639 		if (q->p_pdeathsig > 0)
640 			kern_psignal(q, q->p_pdeathsig);
641 		CTR2(KTR_PTRACE, "exit: pid %d, clearing orphan %d", p->p_pid,
642 		    q->p_pid);
643 		proc_clear_orphan(q);
644 		PROC_UNLOCK(q);
645 	}
646 
647 #ifdef KDTRACE_HOOKS
648 	if (SDT_PROBES_ENABLED()) {
649 		int reason = CLD_EXITED;
650 		if (WCOREDUMP(signo))
651 			reason = CLD_DUMPED;
652 		else if (WIFSIGNALED(signo))
653 			reason = CLD_KILLED;
654 		SDT_PROBE1(proc, , , exit, reason);
655 	}
656 #endif
657 
658 	/* Save exit status. */
659 	PROC_LOCK(p);
660 	p->p_xthread = td;
661 
662 	if (p->p_sysent->sv_ontdexit != NULL)
663 		p->p_sysent->sv_ontdexit(td);
664 
665 #ifdef KDTRACE_HOOKS
666 	/*
667 	 * Tell the DTrace fasttrap provider about the exit if it
668 	 * has declared an interest.
669 	 */
670 	if (dtrace_fasttrap_exit)
671 		dtrace_fasttrap_exit(p);
672 #endif
673 
674 	/*
675 	 * Notify interested parties of our demise.
676 	 */
677 	KNOTE_LOCKED(p->p_klist, NOTE_EXIT);
678 
679 	/*
680 	 * If this is a process with a descriptor, we may not need to deliver
681 	 * a signal to the parent.  proctree_lock is held over
682 	 * procdesc_exit() to serialize concurrent calls to close() and
683 	 * exit().
684 	 */
685 	signal_parent = 0;
686 	if (p->p_procdesc == NULL || procdesc_exit(p)) {
687 		/*
688 		 * Notify parent that we're gone.  If parent has the
689 		 * PS_NOCLDWAIT flag set, or if the handler is set to SIG_IGN,
690 		 * notify process 1 instead (and hope it will handle this
691 		 * situation).
692 		 */
693 		PROC_LOCK(p->p_pptr);
694 		mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
695 		if (p->p_pptr->p_sigacts->ps_flag &
696 		    (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
697 			struct proc *pp;
698 
699 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
700 			pp = p->p_pptr;
701 			PROC_UNLOCK(pp);
702 			proc_reparent(p, p->p_reaper, true);
703 			p->p_sigparent = SIGCHLD;
704 			PROC_LOCK(p->p_pptr);
705 
706 			/*
707 			 * Notify parent, so in case he was wait(2)ing or
708 			 * executing waitpid(2) with our pid, he will
709 			 * continue.
710 			 */
711 			wakeup(pp);
712 		} else
713 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
714 
715 		if (p->p_pptr == p->p_reaper || p->p_pptr == initproc) {
716 			signal_parent = 1;
717 		} else if (p->p_sigparent != 0) {
718 			if (p->p_sigparent == SIGCHLD) {
719 				signal_parent = 1;
720 			} else { /* LINUX thread */
721 				signal_parent = 2;
722 			}
723 		}
724 	} else
725 		PROC_LOCK(p->p_pptr);
726 	sx_xunlock(&proctree_lock);
727 
728 	if (signal_parent == 1) {
729 		childproc_exited(p);
730 	} else if (signal_parent == 2) {
731 		kern_psignal(p->p_pptr, p->p_sigparent);
732 	}
733 
734 	/* Tell the prison that we are gone. */
735 	prison_proc_free(p->p_ucred->cr_prison);
736 
737 	/*
738 	 * The state PRS_ZOMBIE prevents other processes from sending
739 	 * signal to the process, to avoid memory leak, we free memory
740 	 * for signal queue at the time when the state is set.
741 	 */
742 	sigqueue_flush(&p->p_sigqueue);
743 	sigqueue_flush(&td->td_sigqueue);
744 
745 	/*
746 	 * We have to wait until after acquiring all locks before
747 	 * changing p_state.  We need to avoid all possible context
748 	 * switches (including ones from blocking on a mutex) while
749 	 * marked as a zombie.  We also have to set the zombie state
750 	 * before we release the parent process' proc lock to avoid
751 	 * a lost wakeup.  So, we first call wakeup, then we grab the
752 	 * sched lock, update the state, and release the parent process'
753 	 * proc lock.
754 	 */
755 	wakeup(p->p_pptr);
756 	cv_broadcast(&p->p_pwait);
757 	sched_exit(p->p_pptr, td);
758 	PROC_SLOCK(p);
759 	p->p_state = PRS_ZOMBIE;
760 	PROC_UNLOCK(p->p_pptr);
761 
762 	/*
763 	 * Save our children's rusage information in our exit rusage.
764 	 */
765 	PROC_STATLOCK(p);
766 	ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
767 	PROC_STATUNLOCK(p);
768 
769 	/*
770 	 * Make sure the scheduler takes this thread out of its tables etc.
771 	 * This will also release this thread's reference to the ucred.
772 	 * Other thread parts to release include pcb bits and such.
773 	 */
774 	thread_exit();
775 }
776 
777 #ifndef _SYS_SYSPROTO_H_
778 struct abort2_args {
779 	char *why;
780 	int nargs;
781 	void **args;
782 };
783 #endif
784 
785 int
sys_abort2(struct thread * td,struct abort2_args * uap)786 sys_abort2(struct thread *td, struct abort2_args *uap)
787 {
788 	void *uargs[16];
789 	void **uargsp;
790 	int error, nargs;
791 
792 	nargs = uap->nargs;
793 	if (nargs < 0 || nargs > nitems(uargs))
794 		nargs = -1;
795 	uargsp = NULL;
796 	if (nargs > 0) {
797 		if (uap->args != NULL) {
798 			error = copyin(uap->args, uargs,
799 			    nargs * sizeof(void *));
800 			if (error != 0)
801 				nargs = -1;
802 			else
803 				uargsp = uargs;
804 		} else
805 			nargs = -1;
806 	}
807 	return (kern_abort2(td, uap->why, nargs, uargsp));
808 }
809 
810 /*
811  * kern_abort2()
812  * Arguments:
813  *  why - user pointer to why
814  *  nargs - number of arguments copied or -1 if an error occurred in copying
815  *  args - pointer to an array of pointers in kernel format
816  */
817 int
kern_abort2(struct thread * td,const char * why,int nargs,void ** uargs)818 kern_abort2(struct thread *td, const char *why, int nargs, void **uargs)
819 {
820 	struct proc *p = td->td_proc;
821 	struct sbuf *sb;
822 	int error, i, sig;
823 
824 	/*
825 	 * Do it right now so we can log either proper call of abort2(), or
826 	 * note, that invalid argument was passed. 512 is big enough to
827 	 * handle 16 arguments' descriptions with additional comments.
828 	 */
829 	sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
830 	sbuf_clear(sb);
831 	sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
832 	    p->p_comm, p->p_pid, td->td_ucred->cr_uid);
833 	/*
834 	 * Since we can't return from abort2(), send SIGKILL in cases, where
835 	 * abort2() was called improperly
836 	 */
837 	sig = SIGKILL;
838 	/* Prevent from DoSes from user-space. */
839 	if (nargs == -1)
840 		goto out;
841 	KASSERT(nargs >= 0 && nargs <= 16, ("called with too many args (%d)",
842 	    nargs));
843 	/*
844 	 * Limit size of 'reason' string to 128. Will fit even when
845 	 * maximal number of arguments was chosen to be logged.
846 	 */
847 	if (why != NULL) {
848 		error = sbuf_copyin(sb, why, 128);
849 		if (error < 0)
850 			goto out;
851 	} else {
852 		sbuf_cat(sb, "(null)");
853 	}
854 	if (nargs > 0) {
855 		sbuf_putc(sb, '(');
856 		for (i = 0; i < nargs; i++)
857 			sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
858 		sbuf_putc(sb, ')');
859 	}
860 	/*
861 	 * Final stage: arguments were proper, string has been
862 	 * successfully copied from userspace, and copying pointers
863 	 * from user-space succeed.
864 	 */
865 	sig = SIGABRT;
866 out:
867 	if (sig == SIGKILL) {
868 		sbuf_trim(sb);
869 		sbuf_cat(sb, " (Reason text inaccessible)");
870 	}
871 	sbuf_cat(sb, "\n");
872 	sbuf_finish(sb);
873 	log(LOG_INFO, "%s", sbuf_data(sb));
874 	sbuf_delete(sb);
875 	PROC_LOCK(p);
876 	sigexit(td, sig);
877 	return (0);
878 }
879 
880 #ifdef COMPAT_43
881 /*
882  * The dirty work is handled by kern_wait().
883  */
884 int
owait(struct thread * td,struct owait_args * uap __unused)885 owait(struct thread *td, struct owait_args *uap __unused)
886 {
887 	int error, status;
888 
889 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
890 	if (error == 0)
891 		td->td_retval[1] = status;
892 	return (error);
893 }
894 #endif /* COMPAT_43 */
895 
896 /*
897  * The dirty work is handled by kern_wait().
898  */
899 int
sys_wait4(struct thread * td,struct wait4_args * uap)900 sys_wait4(struct thread *td, struct wait4_args *uap)
901 {
902 	struct rusage ru, *rup;
903 	int error, status;
904 
905 	if (uap->rusage != NULL)
906 		rup = &ru;
907 	else
908 		rup = NULL;
909 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
910 	if (uap->status != NULL && error == 0 && td->td_retval[0] != 0)
911 		error = copyout(&status, uap->status, sizeof(status));
912 	if (uap->rusage != NULL && error == 0 && td->td_retval[0] != 0)
913 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
914 	return (error);
915 }
916 
917 int
sys_wait6(struct thread * td,struct wait6_args * uap)918 sys_wait6(struct thread *td, struct wait6_args *uap)
919 {
920 	struct __wrusage wru, *wrup;
921 	siginfo_t si, *sip;
922 	idtype_t idtype;
923 	id_t id;
924 	int error, status;
925 
926 	idtype = uap->idtype;
927 	id = uap->id;
928 
929 	if (uap->wrusage != NULL)
930 		wrup = &wru;
931 	else
932 		wrup = NULL;
933 
934 	if (uap->info != NULL) {
935 		sip = &si;
936 		bzero(sip, sizeof(*sip));
937 	} else
938 		sip = NULL;
939 
940 	/*
941 	 *  We expect all callers of wait6() to know about WEXITED and
942 	 *  WTRAPPED.
943 	 */
944 	error = kern_wait6(td, idtype, id, &status, uap->options, wrup, sip);
945 
946 	if (uap->status != NULL && error == 0 && td->td_retval[0] != 0)
947 		error = copyout(&status, uap->status, sizeof(status));
948 	if (uap->wrusage != NULL && error == 0 && td->td_retval[0] != 0)
949 		error = copyout(&wru, uap->wrusage, sizeof(wru));
950 	if (uap->info != NULL && error == 0)
951 		error = copyout(&si, uap->info, sizeof(si));
952 	return (error);
953 }
954 
955 int
sys_pdwait(struct thread * td,struct pdwait_args * uap)956 sys_pdwait(struct thread *td, struct pdwait_args *uap)
957 {
958 	struct __wrusage wru, *wrup;
959 	siginfo_t si, *sip;
960 	int error, status;
961 
962 	wrup = uap->wrusage != NULL ? &wru : NULL;
963 
964 	if (uap->info != NULL) {
965 		sip = &si;
966 		bzero(sip, sizeof(*sip));
967 	} else {
968 		sip = NULL;
969 	}
970 
971 	error = kern_pdwait(td, uap->fd, &status, uap->options, wrup, sip);
972 
973 	if (uap->status != NULL && error == 0)
974 		error = copyout(&status, uap->status, sizeof(status));
975 	if (uap->wrusage != NULL && error == 0)
976 		error = copyout(&wru, uap->wrusage, sizeof(wru));
977 	if (uap->info != NULL && error == 0)
978 		error = copyout(&si, uap->info, sizeof(si));
979 	return (error);
980 }
981 
982 /*
983  * Reap the remains of a zombie process and optionally return status and
984  * rusage.  Asserts and will release both the proctree_lock and the process
985  * lock as part of its work.
986  */
987 void
proc_reap(struct thread * td,struct proc * p,int * status,int options,int zombieref)988 proc_reap(struct thread *td, struct proc *p, int *status, int options,
989     int zombieref)
990 {
991 	struct proc *q, *t;
992 
993 	sx_assert(&proctree_lock, SA_XLOCKED);
994 	PROC_LOCK_ASSERT(p, MA_OWNED);
995 	KASSERT(p->p_state == PRS_ZOMBIE, ("proc_reap: !PRS_ZOMBIE"));
996 
997 	mtx_spin_wait_unlocked(&p->p_slock);
998 
999 	q = td->td_proc;
1000 
1001 	if (status != NULL)
1002 		*status = KW_EXITCODE(p->p_xexit, p->p_xsig);
1003 	if ((options & WNOWAIT) != 0) {
1004 		/*
1005 		 *  Only poll, returning the status.  Caller does not wish to
1006 		 * release the proc struct just yet.
1007 		 */
1008 		PROC_UNLOCK(p);
1009 		sx_xunlock(&proctree_lock);
1010 		return;
1011 	}
1012 
1013 	p->p_zombieref &= ~zombieref;
1014 	if ((p->p_zombieref & PZOMBIEREF_REFMASK) != 0) {
1015 		sx_xunlock(&proctree_lock);
1016 		PROC_UNLOCK(p);
1017 		return;
1018 	}
1019 
1020 	PROC_LOCK(q);
1021 	sigqueue_take(p->p_ksi);
1022 	PROC_UNLOCK(q);
1023 
1024 	/*
1025 	 * If we got the child via a ptrace 'attach', we need to give it back
1026 	 * to the old parent.
1027 	 */
1028 	if (p->p_oppid != p->p_pptr->p_pid) {
1029 		PROC_UNLOCK(p);
1030 		t = proc_realparent(p);
1031 		PROC_LOCK(t);
1032 		PROC_LOCK(p);
1033 		CTR2(KTR_PTRACE,
1034 		    "wait: traced child %d moved back to parent %d", p->p_pid,
1035 		    t->p_pid);
1036 		proc_reparent(p, t, false);
1037 		PROC_UNLOCK(p);
1038 		pksignal(t, SIGCHLD, p->p_ksi);
1039 		wakeup(t);
1040 		cv_broadcast(&p->p_pwait);
1041 		PROC_UNLOCK(t);
1042 		sx_xunlock(&proctree_lock);
1043 		return;
1044 	}
1045 	PROC_UNLOCK(p);
1046 
1047 	/*
1048 	 * Remove other references to this process to ensure we have an
1049 	 * exclusive reference.
1050 	 */
1051 	sx_xlock(PIDHASHLOCK(p->p_pid));
1052 	LIST_REMOVE(p, p_hash);
1053 	sx_xunlock(PIDHASHLOCK(p->p_pid));
1054 	LIST_REMOVE(p, p_sibling);
1055 	reaper_abandon_children(p, true);
1056 	reaper_clear(p, p->p_reaper);
1057 	PROC_LOCK(p);
1058 	proc_clear_orphan(p);
1059 	PROC_UNLOCK(p);
1060 	leavepgrp(p);
1061 	if (p->p_procdesc != NULL)
1062 		procdesc_reap(p);
1063 	else
1064 		proc_id_clear(PROC_ID_PID, p->p_pid);
1065 	sx_xunlock(&proctree_lock);
1066 
1067 	PROC_LOCK(p);
1068 	KNOTE_LOCKED(p->p_klist, NOTE_REAP);
1069 	knlist_detach(p->p_klist);
1070 	p->p_klist = NULL;
1071 	PROC_UNLOCK(p);
1072 
1073 	/*
1074 	 * Removal from allproc list and process group list paired with
1075 	 * PROC_LOCK which was executed during that time should guarantee
1076 	 * nothing can reach this process anymore. As such further locking
1077 	 * is unnecessary.
1078 	 */
1079 	p->p_xexit = p->p_xsig = 0;		/* XXX: why? */
1080 
1081 	PROC_LOCK(q);
1082 	ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru, &p->p_rux);
1083 	PROC_UNLOCK(q);
1084 
1085 	/*
1086 	 * Destroy resource accounting information associated with the process.
1087 	 */
1088 #ifdef RACCT
1089 	if (racct_enable) {
1090 		PROC_LOCK(p);
1091 		racct_sub(p, RACCT_NPROC, 1);
1092 		PROC_UNLOCK(p);
1093 	}
1094 #endif
1095 	racct_proc_exit(p);
1096 
1097 	/*
1098 	 * Free credentials, arguments, and sigacts, and decrement the count of
1099 	 * processes running with this uid.
1100 	 */
1101 	proc_unset_cred(p, true);
1102 	pargs_drop(p->p_args);
1103 	p->p_args = NULL;
1104 	sigacts_free(p->p_sigacts);
1105 	p->p_sigacts = NULL;
1106 
1107 	/*
1108 	 * Do any thread-system specific cleanups.
1109 	 */
1110 	thread_wait(p);
1111 
1112 	/*
1113 	 * Give vm and machine-dependent layer a chance to free anything that
1114 	 * cpu_exit couldn't release while still running in process context.
1115 	 */
1116 	vm_waitproc(p);
1117 #ifdef MAC
1118 	mac_proc_destroy(p);
1119 #endif
1120 
1121 	KASSERT(FIRST_THREAD_IN_PROC(p),
1122 	    ("proc_reap: no residual thread!"));
1123 	PROC_TREE_UNREF(p);
1124 	atomic_add_int(&nprocs, -1);
1125 }
1126 
1127 void
wait_fill_siginfo(struct proc * p,siginfo_t * siginfo)1128 wait_fill_siginfo(struct proc *p, siginfo_t *siginfo)
1129 {
1130 	PROC_LOCK_ASSERT(p, MA_OWNED);
1131 
1132 	if (siginfo == NULL)
1133 		return;
1134 
1135 	bzero(siginfo, sizeof(*siginfo));
1136 	siginfo->si_errno = 0;
1137 
1138 	/*
1139 	 * SUSv4 requires that the si_signo value is always
1140 	 * SIGCHLD. Obey it despite the rfork(2) interface allows to
1141 	 * request other signal for child exit notification.
1142 	 */
1143 	siginfo->si_signo = SIGCHLD;
1144 
1145 	/*
1146 	 *  This is still a rough estimate.  We will fix the cases
1147 	 *  TRAPPED, STOPPED, and CONTINUED later.
1148 	 */
1149 	if (WCOREDUMP(p->p_xsig)) {
1150 		siginfo->si_code = CLD_DUMPED;
1151 		siginfo->si_status = WTERMSIG(p->p_xsig);
1152 	} else if (WIFSIGNALED(p->p_xsig)) {
1153 		siginfo->si_code = CLD_KILLED;
1154 		siginfo->si_status = WTERMSIG(p->p_xsig);
1155 	} else {
1156 		siginfo->si_code = CLD_EXITED;
1157 		siginfo->si_status = p->p_xexit;
1158 	}
1159 
1160 	siginfo->si_pid = p->p_pid;
1161 	siginfo->si_uid = p->p_ucred->cr_uid;
1162 
1163 	/*
1164 	 * The si_addr field would be useful additional detail, but
1165 	 * apparently the PC value may be lost when we reach this
1166 	 * point.  bzero() above sets siginfo->si_addr to NULL.
1167 	 */
1168 }
1169 
1170 void
wait_fill_wrusage(struct proc * p,struct __wrusage * wrusage)1171 wait_fill_wrusage(struct proc *p, struct __wrusage *wrusage)
1172 {
1173 	struct rusage *rup;
1174 
1175 	PROC_LOCK_ASSERT(p, MA_OWNED);
1176 
1177 	if (wrusage == NULL)
1178 		return;
1179 
1180 	rup = &wrusage->wru_self;
1181 	*rup = p->p_ru;
1182 	PROC_STATLOCK(p);
1183 	calcru(p, &rup->ru_utime, &rup->ru_stime);
1184 	PROC_STATUNLOCK(p);
1185 
1186 	rup = &wrusage->wru_children;
1187 	*rup = p->p_stats->p_cru;
1188 	calccru(p, &rup->ru_utime, &rup->ru_stime);
1189 }
1190 
1191 static int
proc_to_reap(struct thread * td,struct proc * p,idtype_t idtype,id_t id,int * status,int options,struct __wrusage * wrusage,siginfo_t * siginfo,bool check_only)1192 proc_to_reap(struct thread *td, struct proc *p, idtype_t idtype, id_t id,
1193     int *status, int options, struct __wrusage *wrusage, siginfo_t *siginfo,
1194     bool check_only)
1195 {
1196 	sx_assert(&proctree_lock, SA_XLOCKED);
1197 
1198 	PROC_LOCK(p);
1199 
1200 	switch (idtype) {
1201 	case P_ALL:
1202 		if ((p->p_zombieref & PZOMBIEREF_PARENT) != 0 ||
1203 		   (p->p_pptr == td->td_proc && (p->p_flag & P_TRACED) != 0)) {
1204 			break;
1205 		}
1206 
1207 		PROC_UNLOCK(p);
1208 		return (0);
1209 	case P_PID:
1210 		if (p->p_pid != (pid_t)id) {
1211 			PROC_UNLOCK(p);
1212 			return (0);
1213 		}
1214 		break;
1215 	case P_PGID:
1216 		if (p->p_pgid != (pid_t)id) {
1217 			PROC_UNLOCK(p);
1218 			return (0);
1219 		}
1220 		break;
1221 	case P_SID:
1222 		if (p->p_session->s_sid != (pid_t)id) {
1223 			PROC_UNLOCK(p);
1224 			return (0);
1225 		}
1226 		break;
1227 	case P_UID:
1228 		if (p->p_ucred->cr_uid != (uid_t)id) {
1229 			PROC_UNLOCK(p);
1230 			return (0);
1231 		}
1232 		break;
1233 	case P_GID:
1234 		if (p->p_ucred->cr_gid != (gid_t)id) {
1235 			PROC_UNLOCK(p);
1236 			return (0);
1237 		}
1238 		break;
1239 	case P_JAILID:
1240 		if (p->p_ucred->cr_prison->pr_id != (int)id) {
1241 			PROC_UNLOCK(p);
1242 			return (0);
1243 		}
1244 		break;
1245 	/*
1246 	 * It seems that the thread structures get zeroed out
1247 	 * at process exit.  This makes it impossible to
1248 	 * support P_SETID, P_CID or P_CPUID.
1249 	 */
1250 	default:
1251 		PROC_UNLOCK(p);
1252 		return (0);
1253 	}
1254 
1255 	if (p_canwait(td, p) != 0 ||
1256 	    ((options & WEXITED) == 0 && p->p_state == PRS_ZOMBIE) ||
1257 	    /* waitpid() is disabled and waiter is not the debugger */
1258 	    ((p->p_zombieref & PZOMBIEREF_PARENT) == 0 &&
1259 	    (p->p_pptr != td->td_proc || (p->p_flag & P_TRACED) == 0))) {
1260 		PROC_UNLOCK(p);
1261 		return (0);
1262 	}
1263 	if (check_only) {
1264 		PROC_UNLOCK(p);
1265 		return (1);
1266 	}
1267 
1268 	/*
1269 	 * This special case handles a kthread spawned by linux_clone
1270 	 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
1271 	 * functions need to be able to distinguish between waiting
1272 	 * on a process and waiting on a thread.  It is a thread if
1273 	 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
1274 	 * signifies we want to wait for threads and not processes.
1275 	 */
1276 	if ((p->p_sigparent != SIGCHLD) ^
1277 	    ((options & WLINUXCLONE) != 0)) {
1278 		PROC_UNLOCK(p);
1279 		return (0);
1280 	}
1281 
1282 	wait_fill_siginfo(p, siginfo);
1283 
1284 	/*
1285 	 * There should be no reason to limit resources usage info to
1286 	 * exited processes only.  A snapshot about any resources used
1287 	 * by a stopped process may be exactly what is needed.
1288 	 */
1289 	wait_fill_wrusage(p, wrusage);
1290 
1291 	if (p->p_state == PRS_ZOMBIE) {
1292 		proc_reap(td, p, status, options, PZOMBIEREF_PARENT);
1293 		return (-1);
1294 	}
1295 	return (1);
1296 }
1297 
1298 int
kern_wait(struct thread * td,pid_t pid,int * status,int options,struct rusage * rusage)1299 kern_wait(struct thread *td, pid_t pid, int *status, int options,
1300     struct rusage *rusage)
1301 {
1302 	struct __wrusage wru, *wrup;
1303 	idtype_t idtype;
1304 	id_t id;
1305 	int ret;
1306 
1307 	/*
1308 	 * Translate the special pid values into the (idtype, pid)
1309 	 * pair for kern_wait6.  The WAIT_MYPGRP case is handled by
1310 	 * kern_wait6() on its own.
1311 	 */
1312 	if (pid == WAIT_ANY) {
1313 		idtype = P_ALL;
1314 		id = 0;
1315 	} else if (pid < 0) {
1316 		idtype = P_PGID;
1317 		id = (id_t)-pid;
1318 	} else {
1319 		idtype = P_PID;
1320 		id = (id_t)pid;
1321 	}
1322 
1323 	if (rusage != NULL)
1324 		wrup = &wru;
1325 	else
1326 		wrup = NULL;
1327 
1328 	/*
1329 	 * For backward compatibility we implicitly add flags WEXITED
1330 	 * and WTRAPPED here.
1331 	 */
1332 	options |= WEXITED | WTRAPPED;
1333 	ret = kern_wait6(td, idtype, id, status, options, wrup, NULL);
1334 	if (rusage != NULL)
1335 		*rusage = wru.wru_self;
1336 	return (ret);
1337 }
1338 
1339 static void
report_alive_proc(struct thread * td,struct proc * p,siginfo_t * siginfo,int * status,int options,int si_code)1340 report_alive_proc(struct thread *td, struct proc *p, siginfo_t *siginfo,
1341     int *status, int options, int si_code)
1342 {
1343 	bool cont;
1344 
1345 	PROC_LOCK_ASSERT(p, MA_OWNED);
1346 	sx_assert(&proctree_lock, SA_XLOCKED);
1347 	MPASS(si_code == CLD_TRAPPED || si_code == CLD_STOPPED ||
1348 	    si_code == CLD_CONTINUED);
1349 
1350 	cont = si_code == CLD_CONTINUED;
1351 	if ((options & WNOWAIT) == 0) {
1352 		if (cont)
1353 			p->p_flag &= ~P_CONTINUED;
1354 		else
1355 			p->p_flag |= P_WAITED;
1356 		if (kern_wait_dequeue_sigchld &&
1357 		    (td->td_proc->p_sysent->sv_flags & SV_SIG_WAITNDQ) == 0) {
1358 			PROC_LOCK(td->td_proc);
1359 			sigqueue_take(p->p_ksi);
1360 			PROC_UNLOCK(td->td_proc);
1361 		}
1362 	}
1363 	sx_xunlock(&proctree_lock);
1364 	if (siginfo != NULL) {
1365 		siginfo->si_code = si_code;
1366 		siginfo->si_status = cont ? SIGCONT : p->p_xsig;
1367 	}
1368 	if (status != NULL)
1369 		*status = cont ? SIGCONT : W_STOPCODE(p->p_xsig);
1370 	PROC_UNLOCK(p);
1371 }
1372 
1373 static int
wait6_checkopt(int options)1374 wait6_checkopt(int options)
1375 {
1376 	/* If we don't know the option, just return. */
1377 	if ((options & ~(WUNTRACED | WNOHANG | WCONTINUED | WNOWAIT |
1378 	    WEXITED | WTRAPPED | WLINUXCLONE)) != 0)
1379 		return (EXTERROR(EINVAL, "Unknown options %#jx", options));
1380 	if ((options & (WEXITED | WUNTRACED | WCONTINUED | WTRAPPED)) == 0) {
1381 		/*
1382 		 * We will be unable to find any matching processes,
1383 		 * because there are no known events to look for.
1384 		 * Prefer to return error instead of blocking
1385 		 * indefinitely.
1386 		 */
1387 		return (EXTERROR(EINVAL,
1388 		    "Cannot match processes %#jx", options));
1389 	}
1390 	return (0);
1391 }
1392 
1393 /*
1394  * Checks and reports status for alive process, according to the
1395  * options.  Returns true if the process fits one of the requested
1396  * options and its status was updated in siginfo.
1397  *
1398  * If the process was reported (the function result is true), both the
1399  * process and proctree locks are unlocked.
1400  */
1401 static bool
wait6_check_alive(struct thread * td,int options,struct proc * p,int * status,siginfo_t * siginfo)1402 wait6_check_alive(struct thread *td, int options, struct proc *p, int *status,
1403     siginfo_t *siginfo)
1404 {
1405 	bool report;
1406 
1407 	PROC_LOCK_ASSERT(p, MA_OWNED);
1408 	sx_assert(&proctree_lock, SA_XLOCKED);
1409 
1410 	if ((options & WTRAPPED) != 0 && (p->p_flag & P_TRACED) != 0) {
1411 		PROC_SLOCK(p);
1412 		report = (p->p_flag & (P_STOPPED_TRACE | P_STOPPED_SIG)) &&
1413 		    p->p_suspcount == p->p_numthreads &&
1414 		    (p->p_flag & P_WAITED) == 0;
1415 		PROC_SUNLOCK(p);
1416 		if (report) {
1417 			CTR4(KTR_PTRACE,
1418 	    "wait: returning trapped pid %d status %#x (xstat %d) xthread %d",
1419 			    p->p_pid, W_STOPCODE(p->p_xsig), p->p_xsig,
1420 			    p->p_xthread != NULL ?
1421 			    p->p_xthread->td_tid : -1);
1422 			report_alive_proc(td, p, siginfo, status,
1423 			    options, CLD_TRAPPED);
1424 			return (true);
1425 		}
1426 	}
1427 
1428 	if ((options & WUNTRACED) != 0 && (p->p_flag & P_STOPPED_SIG) != 0) {
1429 		PROC_SLOCK(p);
1430 		report = p->p_suspcount == p->p_numthreads &&
1431 		    (p->p_flag & P_WAITED) == 0;
1432 		PROC_SUNLOCK(p);
1433 		if (report) {
1434 			report_alive_proc(td, p, siginfo, status, options,
1435 			    CLD_STOPPED);
1436 			return (true);
1437 		}
1438 	}
1439 
1440 	if ((options & WCONTINUED) != 0 && (p->p_flag & P_CONTINUED) != 0) {
1441 		report_alive_proc(td, p, siginfo, status, options,
1442 		    CLD_CONTINUED);
1443 		return (true);
1444 	}
1445 
1446 	return (false);
1447 }
1448 
1449 int
kern_wait6(struct thread * td,idtype_t idtype,id_t id,int * status,int options,struct __wrusage * wrusage,siginfo_t * siginfo)1450 kern_wait6(struct thread *td, idtype_t idtype, id_t id, int *status,
1451     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1452 {
1453 	struct proc *p, *q;
1454 	pid_t pid;
1455 	int error, nfound, ret;
1456 
1457 	AUDIT_ARG_VALUE((int)idtype);	/* XXX - This is likely wrong! */
1458 	AUDIT_ARG_PID((pid_t)id);	/* XXX - This may be wrong! */
1459 	AUDIT_ARG_VALUE(options);
1460 
1461 	q = td->td_proc;
1462 
1463 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1464 		PROC_LOCK(q);
1465 		id = (id_t)q->p_pgid;
1466 		PROC_UNLOCK(q);
1467 		idtype = P_PGID;
1468 	}
1469 
1470 	error = wait6_checkopt(options);
1471 	if (error != 0)
1472 		return (error);
1473 loop:
1474 	if (q->p_flag & P_STATCHILD) {
1475 		PROC_LOCK(q);
1476 		q->p_flag &= ~P_STATCHILD;
1477 		PROC_UNLOCK(q);
1478 	}
1479 	sx_xlock(&proctree_lock);
1480 loop_locked:
1481 	nfound = 0;
1482 	LIST_FOREACH(p, &q->p_children, p_sibling) {
1483 		pid = p->p_pid;
1484 		ret = proc_to_reap(td, p, idtype, id, status, options,
1485 		    wrusage, siginfo, false);
1486 		if (ret == 0)
1487 			continue;
1488 		else if (ret != 1) {
1489 			td->td_retval[0] = pid;
1490 			return (0);
1491 		}
1492 
1493 		nfound++;
1494 		PROC_LOCK_ASSERT(p, MA_OWNED);
1495 
1496 		if (wait6_check_alive(td, options, p, status, siginfo)) {
1497 			td->td_retval[0] = pid;
1498 			return (0);
1499 		}
1500 
1501 		PROC_UNLOCK(p);
1502 	}
1503 
1504 	/*
1505 	 * Look in the orphans list too, to allow the parent to
1506 	 * collect it's child exit status even if child is being
1507 	 * debugged.
1508 	 *
1509 	 * Debugger detaches from the parent upon successful
1510 	 * switch-over from parent to child.  At this point due to
1511 	 * re-parenting the parent loses the child to debugger and a
1512 	 * wait4(2) call would report that it has no children to wait
1513 	 * for.  By maintaining a list of orphans we allow the parent
1514 	 * to successfully wait until the child becomes a zombie.
1515 	 */
1516 	if (nfound == 0) {
1517 		LIST_FOREACH(p, &q->p_orphans, p_orphan) {
1518 			ret = proc_to_reap(td, p, idtype, id, NULL, options,
1519 			    NULL, NULL, true);
1520 			if (ret != 0) {
1521 				KASSERT(ret != -1, ("reaped an orphan (pid %d)",
1522 				    (int)td->td_retval[0]));
1523 				nfound++;
1524 				break;
1525 			}
1526 		}
1527 	}
1528 	if (nfound == 0) {
1529 		sx_xunlock(&proctree_lock);
1530 		return (ECHILD);
1531 	}
1532 	if ((options & WNOHANG) != 0) {
1533 		sx_xunlock(&proctree_lock);
1534 		td->td_retval[0] = 0;
1535 		return (0);
1536 	}
1537 	PROC_LOCK(q);
1538 	if ((q->p_flag & P_STATCHILD) != 0) {
1539 		q->p_flag &= ~P_STATCHILD;
1540 		PROC_UNLOCK(q);
1541 		goto loop_locked;
1542 	}
1543 	sx_xunlock(&proctree_lock);
1544 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH | PDROP, "wait", 0);
1545 	if (error != 0)
1546 		return (error);
1547 	goto loop;
1548 }
1549 
1550 int
kern_pdwait(struct thread * td,int fd,int * status,int options,struct __wrusage * wrusage,siginfo_t * siginfo)1551 kern_pdwait(struct thread *td, int fd, int *status,
1552     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1553 {
1554 	struct proc *p;
1555 	struct file *fp;
1556 	struct procdesc *pd;
1557 	int error;
1558 
1559 	AUDIT_ARG_FD(fd);
1560 	AUDIT_ARG_VALUE(options);
1561 
1562 	error = wait6_checkopt(options);
1563 	if (error != 0)
1564 		return (error);
1565 
1566 	error = fget_procdesc(td, fd, &cap_pdwait_rights, EINVAL, &fp,
1567 	    &pd, NULL);
1568 	if (error != 0)
1569 		goto exit_unlocked;
1570 
1571 	for (;;) {
1572 		sx_xlock(&proctree_lock);
1573 		/* We own a reference on the procdesc file. */
1574 		KASSERT(pd->pd_fpcount > 0,
1575 		    ("closed proc %p procdesc %p pd flags %#x",
1576 		    pd->pd_proc, pd, pd->pd_flags));
1577 
1578 		if ((pd->pd_flags & PDF_EXITED) != 0) {
1579 			if ((options & WEXITED) == 0) {
1580 				error = ESRCH;
1581 				goto exit_tree_locked;
1582 			}
1583 			procdesc_fill_winfo(pd, false);
1584 			*status = KW_EXITCODE(pd->pd_xexit, pd->pd_xsig);
1585 			if (wrusage != NULL) {
1586 				memcpy(wrusage, &pd->pd_wrusage,
1587 				    sizeof(*wrusage));
1588 			}
1589 			if (siginfo != NULL) {
1590 				memcpy(siginfo, &pd->pd_siginfo,
1591 				    sizeof(*siginfo));
1592 			}
1593 			goto exit_tree_locked;
1594 		}
1595 		p = pd->pd_proc;
1596 		if (p == NULL) {
1597 			error = ESRCH;
1598 			goto exit_tree_locked;
1599 		}
1600 		PROC_LOCK(p);
1601 		MPASS(p->p_state != PRS_ZOMBIE);
1602 
1603 		error = p_canwait(td, p);
1604 		if (error != 0)
1605 			break;
1606 
1607 		wait_fill_siginfo(p, siginfo);
1608 		wait_fill_wrusage(p, wrusage);
1609 
1610 		if (wait6_check_alive(td, options, p, status, siginfo))
1611 			goto exit_unlocked;
1612 
1613 		if ((options & WNOHANG) != 0) {
1614 			error = EWOULDBLOCK;
1615 			break;
1616 		}
1617 
1618 		PROC_UNLOCK(p);
1619 		error = sx_sleep(&p->p_procdesc, &proctree_lock,
1620 		    PWAIT | PCATCH | PDROP, "pdwait", 0);
1621 		if (error != 0)
1622 			goto exit_unlocked;
1623 	}
1624 
1625 	PROC_UNLOCK(p);
1626 exit_tree_locked:
1627 	sx_xunlock(&proctree_lock);
1628 exit_unlocked:
1629 	if (fp != NULL)
1630 		fdrop(fp, td);
1631 	return (error);
1632 }
1633 
1634 void
proc_add_orphan(struct proc * child,struct proc * parent)1635 proc_add_orphan(struct proc *child, struct proc *parent)
1636 {
1637 
1638 	sx_assert(&proctree_lock, SX_XLOCKED);
1639 	KASSERT((child->p_flag & P_TRACED) != 0,
1640 	    ("proc_add_orphan: not traced"));
1641 
1642 	if (LIST_EMPTY(&parent->p_orphans)) {
1643 		child->p_treeflag |= P_TREE_FIRST_ORPHAN;
1644 		LIST_INSERT_HEAD(&parent->p_orphans, child, p_orphan);
1645 	} else {
1646 		LIST_INSERT_AFTER(LIST_FIRST(&parent->p_orphans),
1647 		    child, p_orphan);
1648 	}
1649 	child->p_treeflag |= P_TREE_ORPHANED;
1650 }
1651 
1652 /*
1653  * Make process 'parent' the new parent of process 'child'.
1654  * Must be called with an exclusive hold of proctree lock.
1655  */
1656 void
proc_reparent(struct proc * child,struct proc * parent,bool set_oppid)1657 proc_reparent(struct proc *child, struct proc *parent, bool set_oppid)
1658 {
1659 
1660 	sx_assert(&proctree_lock, SX_XLOCKED);
1661 	PROC_LOCK_ASSERT(child, MA_OWNED);
1662 	if (child->p_pptr == parent)
1663 		return;
1664 
1665 	PROC_LOCK(child->p_pptr);
1666 	sigqueue_take(child->p_ksi);
1667 	PROC_UNLOCK(child->p_pptr);
1668 	LIST_REMOVE(child, p_sibling);
1669 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1670 
1671 	proc_clear_orphan(child);
1672 	if ((child->p_flag & P_TRACED) != 0 && child->p_oppid != parent->p_pid)
1673 		proc_add_orphan(child, child->p_pptr);
1674 
1675 	child->p_pptr = parent;
1676 	if (set_oppid)
1677 		child->p_oppid = parent->p_pid;
1678 
1679 	/*
1680 	 * When reparenting the child to the real parent which expects
1681 	 * to be able to call waitpid(), or reaper, re-enable
1682 	 * waitpid(2) for it, so that the zombie can be collected.
1683 	 */
1684 	if ((child->p_flag & P_TRACED) == 0 &&
1685 	    ((proc_realparent(child) == parent &&
1686 	    (child->p_zombieref & PZOMBIEREF_NEEDPARENT) != 0)
1687 	    || child->p_reaper == parent) &&
1688 	    (child->p_zombieref & PZOMBIEREF_PARENT) == 0)
1689 		child->p_zombieref |= PZOMBIEREF_PARENT;
1690 }
1691 
1692 static void
initexit(void * dummy __unused)1693 initexit(void *dummy __unused)
1694 {
1695 	ast_register(TDA_ASYNC_EXIT, ASTR_ASTF_REQUIRED, 0, ast_async_exit);
1696 }
1697 SYSINIT(exit, SI_SUB_EXEC, SI_ORDER_ANY, initexit, NULL);
1698