xref: /NextBSD/sys/kern/kern_exit.c (revision 4557fabb34e865d7f40be64b39c9e34fa41dbb60)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_compat.h"
41 #include "opt_ktrace.h"
42 #include "opt_thrworkq.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/capsicum.h>
48 #include <sys/eventhandler.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/lock.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/procdesc.h>
55 #include <sys/pioctl.h>
56 #include <sys/jail.h>
57 #include <sys/tty.h>
58 #include <sys/wait.h>
59 #include <sys/vmmeter.h>
60 #include <sys/vnode.h>
61 #include <sys/racct.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sbuf.h>
64 #include <sys/signalvar.h>
65 #include <sys/sched.h>
66 #include <sys/sx.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/syslog.h>
69 #include <sys/ptrace.h>
70 #include <sys/acct.h>		/* for acct_process() function prototype */
71 #include <sys/filedesc.h>
72 #include <sys/sdt.h>
73 #include <sys/shm.h>
74 #include <sys/sem.h>
75 #include <sys/umtx.h>
76 #ifdef THRWORKQ
77 #include <sys/thrworkq.h>
78 #endif
79 #ifdef KTRACE
80 #include <sys/ktrace.h>
81 #endif
82 
83 #include <security/audit/audit.h>
84 #include <security/mac/mac_framework.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_param.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_page.h>
92 #include <vm/uma.h>
93 #include <vm/vm_domain.h>
94 
95 #ifdef KDTRACE_HOOKS
96 #include <sys/dtrace_bsd.h>
97 dtrace_execexit_func_t	dtrace_fasttrap_exit;
98 #endif
99 
100 SDT_PROVIDER_DECLARE(proc);
101 SDT_PROBE_DEFINE1(proc, , , exit, "int");
102 
103 /* Hook for NFS teardown procedure. */
104 void (*nlminfo_release_p)(struct proc *p);
105 
106 struct proc *
proc_realparent(struct proc * child)107 proc_realparent(struct proc *child)
108 {
109 	struct proc *p, *parent;
110 
111 	sx_assert(&proctree_lock, SX_LOCKED);
112 	if ((child->p_treeflag & P_TREE_ORPHANED) == 0) {
113 		if (child->p_oppid == 0 ||
114 		    child->p_pptr->p_pid == child->p_oppid)
115 			parent = child->p_pptr;
116 		else
117 			parent = initproc;
118 		return (parent);
119 	}
120 	for (p = child; (p->p_treeflag & P_TREE_FIRST_ORPHAN) == 0;) {
121 		/* Cannot use LIST_PREV(), since the list head is not known. */
122 		p = __containerof(p->p_orphan.le_prev, struct proc,
123 		    p_orphan.le_next);
124 		KASSERT((p->p_treeflag & P_TREE_ORPHANED) != 0,
125 		    ("missing P_ORPHAN %p", p));
126 	}
127 	parent = __containerof(p->p_orphan.le_prev, struct proc,
128 	    p_orphans.lh_first);
129 	return (parent);
130 }
131 
132 void
reaper_abandon_children(struct proc * p,bool exiting)133 reaper_abandon_children(struct proc *p, bool exiting)
134 {
135 	struct proc *p1, *p2, *ptmp;
136 
137 	sx_assert(&proctree_lock, SX_LOCKED);
138 	KASSERT(p != initproc, ("reaper_abandon_children for initproc"));
139 	if ((p->p_treeflag & P_TREE_REAPER) == 0)
140 		return;
141 	p1 = p->p_reaper;
142 	LIST_FOREACH_SAFE(p2, &p->p_reaplist, p_reapsibling, ptmp) {
143 		LIST_REMOVE(p2, p_reapsibling);
144 		p2->p_reaper = p1;
145 		p2->p_reapsubtree = p->p_reapsubtree;
146 		LIST_INSERT_HEAD(&p1->p_reaplist, p2, p_reapsibling);
147 		if (exiting && p2->p_pptr == p) {
148 			PROC_LOCK(p2);
149 			proc_reparent(p2, p1);
150 			PROC_UNLOCK(p2);
151 		}
152 	}
153 	KASSERT(LIST_EMPTY(&p->p_reaplist), ("p_reaplist not empty"));
154 	p->p_treeflag &= ~P_TREE_REAPER;
155 }
156 
157 static void
clear_orphan(struct proc * p)158 clear_orphan(struct proc *p)
159 {
160 	struct proc *p1;
161 
162 	sx_assert(&proctree_lock, SA_XLOCKED);
163 	if ((p->p_treeflag & P_TREE_ORPHANED) == 0)
164 		return;
165 	if ((p->p_treeflag & P_TREE_FIRST_ORPHAN) != 0) {
166 		p1 = LIST_NEXT(p, p_orphan);
167 		if (p1 != NULL)
168 			p1->p_treeflag |= P_TREE_FIRST_ORPHAN;
169 		p->p_treeflag &= ~P_TREE_FIRST_ORPHAN;
170 	}
171 	LIST_REMOVE(p, p_orphan);
172 	p->p_treeflag &= ~P_TREE_ORPHANED;
173 }
174 
175 /*
176  * exit -- death of process.
177  */
178 void
sys_sys_exit(struct thread * td,struct sys_exit_args * uap)179 sys_sys_exit(struct thread *td, struct sys_exit_args *uap)
180 {
181 
182 	exit1(td, uap->rval, 0);
183 	/* NOTREACHED */
184 }
185 
186 /*
187  * Exit: deallocate address space and other resources, change proc state to
188  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
189  * and rusage for wait().  Check for child processes and orphan them.
190  */
191 void
exit1(struct thread * td,int rval,int signo)192 exit1(struct thread *td, int rval, int signo)
193 {
194 	struct proc *p, *nq, *q, *t;
195 	struct thread *tdt;
196 	struct vnode *ttyvp = NULL;
197 
198 	mtx_assert(&Giant, MA_NOTOWNED);
199 	KASSERT(rval == 0 || signo == 0, ("exit1 rv %d sig %d", rval, signo));
200 
201 	p = td->td_proc;
202 	/*
203 	 * XXX in case we're rebooting we just let init die in order to
204 	 * work around an unsolved stack overflow seen very late during
205 	 * shutdown on sparc64 when the gmirror worker process exists.
206 	 */
207 	if (p == initproc && rebooting == 0) {
208 		printf("init died (signal %d, exit %d)\n", signo, rval);
209 		panic("Going nowhere without my init!");
210 	}
211 
212 #ifdef THRWORKQ
213 	/*
214 	 * Check if this process has a thread workqueue.
215 	 */
216 	thrworkq_exit(p);
217 #endif
218 
219 	/*
220 	 * Deref SU mp, since the thread does not return to userspace.
221 	 */
222 	if (softdep_ast_cleanup != NULL)
223 		softdep_ast_cleanup();
224 
225 	/*
226 	 * MUST abort all other threads before proceeding past here.
227 	 */
228 	PROC_LOCK(p);
229 	/*
230 	 * First check if some other thread or external request got
231 	 * here before us.  If so, act appropriately: exit or suspend.
232 	 * We must ensure that stop requests are handled before we set
233 	 * P_WEXIT.
234 	 */
235 	thread_suspend_check(0);
236 	while (p->p_flag & P_HADTHREADS) {
237 		/*
238 		 * Kill off the other threads. This requires
239 		 * some co-operation from other parts of the kernel
240 		 * so it may not be instantaneous.  With this state set
241 		 * any thread entering the kernel from userspace will
242 		 * thread_exit() in trap().  Any thread attempting to
243 		 * sleep will return immediately with EINTR or EWOULDBLOCK
244 		 * which will hopefully force them to back out to userland
245 		 * freeing resources as they go.  Any thread attempting
246 		 * to return to userland will thread_exit() from userret().
247 		 * thread_exit() will unsuspend us when the last of the
248 		 * other threads exits.
249 		 * If there is already a thread singler after resumption,
250 		 * calling thread_single will fail; in that case, we just
251 		 * re-check all suspension request, the thread should
252 		 * either be suspended there or exit.
253 		 */
254 		if (!thread_single(p, SINGLE_EXIT))
255 			/*
256 			 * All other activity in this process is now
257 			 * stopped.  Threading support has been turned
258 			 * off.
259 			 */
260 			break;
261 		/*
262 		 * Recheck for new stop or suspend requests which
263 		 * might appear while process lock was dropped in
264 		 * thread_single().
265 		 */
266 		thread_suspend_check(0);
267 	}
268 	KASSERT(p->p_numthreads == 1,
269 	    ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
270 	racct_sub(p, RACCT_NTHR, 1);
271 
272 	/* Let event handler change exit status */
273 	p->p_xexit = rval;
274 	p->p_xsig = signo;
275 
276 	/*
277 	 * Wakeup anyone in procfs' PIOCWAIT.  They should have a hold
278 	 * on our vmspace, so we should block below until they have
279 	 * released their reference to us.  Note that if they have
280 	 * requested S_EXIT stops we will block here until they ack
281 	 * via PIOCCONT.
282 	 */
283 	_STOPEVENT(p, S_EXIT, 0);
284 
285 	/*
286 	 * Ignore any pending request to stop due to a stop signal.
287 	 * Once P_WEXIT is set, future requests will be ignored as
288 	 * well.
289 	 */
290 	p->p_flag &= ~P_STOPPED_SIG;
291 	KASSERT(!P_SHOULDSTOP(p), ("exiting process is stopped"));
292 
293 	/*
294 	 * Note that we are exiting and do another wakeup of anyone in
295 	 * PIOCWAIT in case they aren't listening for S_EXIT stops or
296 	 * decided to wait again after we told them we are exiting.
297 	 */
298 	p->p_flag |= P_WEXIT;
299 	wakeup(&p->p_stype);
300 
301 	/*
302 	 * Wait for any processes that have a hold on our vmspace to
303 	 * release their reference.
304 	 */
305 	while (p->p_lock > 0)
306 		msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
307 
308 	PROC_UNLOCK(p);
309 	/* Drain the limit callout while we don't have the proc locked */
310 	callout_drain(&p->p_limco);
311 
312 #ifdef AUDIT
313 	/*
314 	 * The Sun BSM exit token contains two components: an exit status as
315 	 * passed to exit(), and a return value to indicate what sort of exit
316 	 * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
317 	 * what the return value is.
318 	 */
319 	AUDIT_ARG_EXIT(rval, 0);
320 	AUDIT_SYSCALL_EXIT(0, td);
321 #endif
322 
323 	/* Are we a task leader with peers? */
324 	if (p->p_peers != NULL && p == p->p_leader) {
325 		mtx_lock(&ppeers_lock);
326 		q = p->p_peers;
327 		while (q != NULL) {
328 			PROC_LOCK(q);
329 			kern_psignal(q, SIGKILL);
330 			PROC_UNLOCK(q);
331 			q = q->p_peers;
332 		}
333 		while (p->p_peers != NULL)
334 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
335 		mtx_unlock(&ppeers_lock);
336 	}
337 
338 	/*
339 	 * Check if any loadable modules need anything done at process exit.
340 	 * E.g. SYSV IPC stuff.
341 	 * Event handler could change exit status.
342 	 * XXX what if one of these generates an error?
343 	 */
344 	EVENTHANDLER_INVOKE(process_exit, p);
345 
346 	/*
347 	 * If parent is waiting for us to exit or exec,
348 	 * P_PPWAIT is set; we will wakeup the parent below.
349 	 */
350 	PROC_LOCK(p);
351 	stopprofclock(p);
352 	p->p_flag &= ~(P_TRACED | P_PPWAIT | P_PPTRACE);
353 
354 	/*
355 	 * Stop the real interval timer.  If the handler is currently
356 	 * executing, prevent it from rearming itself and let it finish.
357 	 */
358 	if (timevalisset(&p->p_realtimer.it_value) &&
359 	    callout_stop(&p->p_itcallout) == 0) {
360 		timevalclear(&p->p_realtimer.it_interval);
361 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
362 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
363 		    ("realtime timer is still armed"));
364 	}
365 	PROC_UNLOCK(p);
366 
367 	/*
368 	 * Reset any sigio structures pointing to us as a result of
369 	 * F_SETOWN with our pid.
370 	 */
371 	funsetownlst(&p->p_sigiolst);
372 
373 	/*
374 	 * If this process has an nlminfo data area (for lockd), release it
375 	 */
376 	if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
377 		(*nlminfo_release_p)(p);
378 
379 	/*
380 	 * Close open files and release open-file table.
381 	 * This may block!
382 	 */
383 	fdescfree(td);
384 
385 	/*
386 	 * If this thread tickled GEOM, we need to wait for the giggling to
387 	 * stop before we return to userland
388 	 */
389 	if (td->td_pflags & TDP_GEOM)
390 		g_waitidle();
391 
392 	/*
393 	 * Remove ourself from our leader's peer list and wake our leader.
394 	 */
395 	if (p->p_leader->p_peers != NULL) {
396 		mtx_lock(&ppeers_lock);
397 		if (p->p_leader->p_peers != NULL) {
398 			q = p->p_leader;
399 			while (q->p_peers != p)
400 				q = q->p_peers;
401 			q->p_peers = p->p_peers;
402 			wakeup(p->p_leader);
403 		}
404 		mtx_unlock(&ppeers_lock);
405 	}
406 
407 	vmspace_exit(td);
408 
409 	sx_xlock(&proctree_lock);
410 	if (SESS_LEADER(p)) {
411 		struct session *sp = p->p_session;
412 		struct tty *tp;
413 
414 		/*
415 		 * s_ttyp is not zero'd; we use this to indicate that
416 		 * the session once had a controlling terminal. (for
417 		 * logging and informational purposes)
418 		 */
419 		SESS_LOCK(sp);
420 		ttyvp = sp->s_ttyvp;
421 		tp = sp->s_ttyp;
422 		sp->s_ttyvp = NULL;
423 		sp->s_ttydp = NULL;
424 		sp->s_leader = NULL;
425 		SESS_UNLOCK(sp);
426 
427 		/*
428 		 * Signal foreground pgrp and revoke access to
429 		 * controlling terminal if it has not been revoked
430 		 * already.
431 		 *
432 		 * Because the TTY may have been revoked in the mean
433 		 * time and could already have a new session associated
434 		 * with it, make sure we don't send a SIGHUP to a
435 		 * foreground process group that does not belong to this
436 		 * session.
437 		 */
438 
439 		if (tp != NULL) {
440 			tty_lock(tp);
441 			if (tp->t_session == sp)
442 				tty_signal_pgrp(tp, SIGHUP);
443 			tty_unlock(tp);
444 		}
445 
446 		if (ttyvp != NULL) {
447 			sx_xunlock(&proctree_lock);
448 			if (vn_lock(ttyvp, LK_EXCLUSIVE) == 0) {
449 				VOP_REVOKE(ttyvp, REVOKEALL);
450 				VOP_UNLOCK(ttyvp, 0);
451 			}
452 			sx_xlock(&proctree_lock);
453 		}
454 	}
455 	fixjobc(p, p->p_pgrp, 0);
456 	sx_xunlock(&proctree_lock);
457 	(void)acct_process(td);
458 
459 	/* Release the TTY now we've unlocked everything. */
460 	if (ttyvp != NULL)
461 		vrele(ttyvp);
462 #ifdef KTRACE
463 	ktrprocexit(td);
464 #endif
465 	/*
466 	 * Release reference to text vnode
467 	 */
468 	if (p->p_textvp != NULL) {
469 		vrele(p->p_textvp);
470 		p->p_textvp = NULL;
471 	}
472 
473 	/*
474 	 * Release our limits structure.
475 	 */
476 	lim_free(p->p_limit);
477 	p->p_limit = NULL;
478 
479 	tidhash_remove(td);
480 
481 	/*
482 	 * Remove proc from allproc queue and pidhash chain.
483 	 * Place onto zombproc.  Unlink from parent's child list.
484 	 */
485 	sx_xlock(&allproc_lock);
486 	LIST_REMOVE(p, p_list);
487 	LIST_INSERT_HEAD(&zombproc, p, p_list);
488 	LIST_REMOVE(p, p_hash);
489 	sx_xunlock(&allproc_lock);
490 
491 	/*
492 	 * Call machine-dependent code to release any
493 	 * machine-dependent resources other than the address space.
494 	 * The address space is released by "vmspace_exitfree(p)" in
495 	 * vm_waitproc().
496 	 */
497 	cpu_exit(td);
498 
499 	WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
500 
501 	/*
502 	 * Reparent all children processes:
503 	 * - traced ones to the original parent (or init if we are that parent)
504 	 * - the rest to init
505 	 */
506 	sx_xlock(&proctree_lock);
507 	q = LIST_FIRST(&p->p_children);
508 	if (q != NULL)		/* only need this if any child is S_ZOMB */
509 		wakeup(q->p_reaper);
510 	for (; q != NULL; q = nq) {
511 		nq = LIST_NEXT(q, p_sibling);
512 		PROC_LOCK(q);
513 		q->p_sigparent = SIGCHLD;
514 
515 		if (!(q->p_flag & P_TRACED)) {
516 			proc_reparent(q, q->p_reaper);
517 		} else {
518 			/*
519 			 * Traced processes are killed since their existence
520 			 * means someone is screwing up.
521 			 */
522 			t = proc_realparent(q);
523 			if (t == p) {
524 				proc_reparent(q, q->p_reaper);
525 			} else {
526 				PROC_LOCK(t);
527 				proc_reparent(q, t);
528 				PROC_UNLOCK(t);
529 			}
530 			/*
531 			 * Since q was found on our children list, the
532 			 * proc_reparent() call moved q to the orphan
533 			 * list due to present P_TRACED flag. Clear
534 			 * orphan link for q now while q is locked.
535 			 */
536 			clear_orphan(q);
537 			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
538 			FOREACH_THREAD_IN_PROC(q, tdt)
539 				tdt->td_dbgflags &= ~TDB_SUSPEND;
540 			kern_psignal(q, SIGKILL);
541 		}
542 		PROC_UNLOCK(q);
543 	}
544 
545 	/*
546 	 * Also get rid of our orphans.
547 	 */
548 	while ((q = LIST_FIRST(&p->p_orphans)) != NULL) {
549 		PROC_LOCK(q);
550 		CTR2(KTR_PTRACE, "exit: pid %d, clearing orphan %d", p->p_pid,
551 		    q->p_pid);
552 		clear_orphan(q);
553 		PROC_UNLOCK(q);
554 	}
555 
556 	/* Save exit status. */
557 	PROC_LOCK(p);
558 	p->p_xthread = td;
559 
560 	/* Tell the prison that we are gone. */
561 	prison_proc_free(p->p_ucred->cr_prison);
562 
563 #ifdef KDTRACE_HOOKS
564 	/*
565 	 * Tell the DTrace fasttrap provider about the exit if it
566 	 * has declared an interest.
567 	 */
568 	if (dtrace_fasttrap_exit)
569 		dtrace_fasttrap_exit(p);
570 #endif
571 
572 	/*
573 	 * Notify interested parties of our demise.
574 	 */
575 	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
576 
577 #ifdef KDTRACE_HOOKS
578 	int reason = CLD_EXITED;
579 	if (WCOREDUMP(signo))
580 		reason = CLD_DUMPED;
581 	else if (WIFSIGNALED(signo))
582 		reason = CLD_KILLED;
583 	SDT_PROBE1(proc, , , exit, reason);
584 #endif
585 
586 	/*
587 	 * Just delete all entries in the p_klist. At this point we won't
588 	 * report any more events, and there are nasty race conditions that
589 	 * can beat us if we don't.
590 	 */
591 	knlist_clear(&p->p_klist, 1);
592 
593 	/*
594 	 * If this is a process with a descriptor, we may not need to deliver
595 	 * a signal to the parent.  proctree_lock is held over
596 	 * procdesc_exit() to serialize concurrent calls to close() and
597 	 * exit().
598 	 */
599 	if (p->p_procdesc == NULL || procdesc_exit(p)) {
600 		/*
601 		 * Notify parent that we're gone.  If parent has the
602 		 * PS_NOCLDWAIT flag set, or if the handler is set to SIG_IGN,
603 		 * notify process 1 instead (and hope it will handle this
604 		 * situation).
605 		 */
606 		PROC_LOCK(p->p_pptr);
607 		mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
608 		if (p->p_pptr->p_sigacts->ps_flag &
609 		    (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
610 			struct proc *pp;
611 
612 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
613 			pp = p->p_pptr;
614 			PROC_UNLOCK(pp);
615 			proc_reparent(p, p->p_reaper);
616 			p->p_sigparent = SIGCHLD;
617 			PROC_LOCK(p->p_pptr);
618 
619 			/*
620 			 * Notify parent, so in case he was wait(2)ing or
621 			 * executing waitpid(2) with our pid, he will
622 			 * continue.
623 			 */
624 			wakeup(pp);
625 		} else
626 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
627 
628 		if (p->p_pptr == p->p_reaper || p->p_pptr == initproc)
629 			childproc_exited(p);
630 		else if (p->p_sigparent != 0) {
631 			if (p->p_sigparent == SIGCHLD)
632 				childproc_exited(p);
633 			else	/* LINUX thread */
634 				kern_psignal(p->p_pptr, p->p_sigparent);
635 		}
636 	} else
637 		PROC_LOCK(p->p_pptr);
638 	sx_xunlock(&proctree_lock);
639 
640 	/*
641 	 * The state PRS_ZOMBIE prevents other proesses from sending
642 	 * signal to the process, to avoid memory leak, we free memory
643 	 * for signal queue at the time when the state is set.
644 	 */
645 	sigqueue_flush(&p->p_sigqueue);
646 	sigqueue_flush(&td->td_sigqueue);
647 
648 	/*
649 	 * We have to wait until after acquiring all locks before
650 	 * changing p_state.  We need to avoid all possible context
651 	 * switches (including ones from blocking on a mutex) while
652 	 * marked as a zombie.  We also have to set the zombie state
653 	 * before we release the parent process' proc lock to avoid
654 	 * a lost wakeup.  So, we first call wakeup, then we grab the
655 	 * sched lock, update the state, and release the parent process'
656 	 * proc lock.
657 	 */
658 	wakeup(p->p_pptr);
659 	cv_broadcast(&p->p_pwait);
660 	sched_exit(p->p_pptr, td);
661 	umtx_thread_exit(td);
662 	PROC_SLOCK(p);
663 	p->p_state = PRS_ZOMBIE;
664 	PROC_UNLOCK(p->p_pptr);
665 
666 	/*
667 	 * Hopefully no one will try to deliver a signal to the process this
668 	 * late in the game.
669 	 */
670 	knlist_destroy(&p->p_klist);
671 
672 	/*
673 	 * Save our children's rusage information in our exit rusage.
674 	 */
675 	PROC_STATLOCK(p);
676 	ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
677 	PROC_STATUNLOCK(p);
678 
679 	/*
680 	 * Make sure the scheduler takes this thread out of its tables etc.
681 	 * This will also release this thread's reference to the ucred.
682 	 * Other thread parts to release include pcb bits and such.
683 	 */
684 	thread_exit();
685 }
686 
687 
688 #ifndef _SYS_SYSPROTO_H_
689 struct abort2_args {
690 	char *why;
691 	int nargs;
692 	void **args;
693 };
694 #endif
695 
696 int
sys_abort2(struct thread * td,struct abort2_args * uap)697 sys_abort2(struct thread *td, struct abort2_args *uap)
698 {
699 	struct proc *p = td->td_proc;
700 	struct sbuf *sb;
701 	void *uargs[16];
702 	int error, i, sig;
703 
704 	/*
705 	 * Do it right now so we can log either proper call of abort2(), or
706 	 * note, that invalid argument was passed. 512 is big enough to
707 	 * handle 16 arguments' descriptions with additional comments.
708 	 */
709 	sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
710 	sbuf_clear(sb);
711 	sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
712 	    p->p_comm, p->p_pid, td->td_ucred->cr_uid);
713 	/*
714 	 * Since we can't return from abort2(), send SIGKILL in cases, where
715 	 * abort2() was called improperly
716 	 */
717 	sig = SIGKILL;
718 	/* Prevent from DoSes from user-space. */
719 	if (uap->nargs < 0 || uap->nargs > 16)
720 		goto out;
721 	if (uap->nargs > 0) {
722 		if (uap->args == NULL)
723 			goto out;
724 		error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
725 		if (error != 0)
726 			goto out;
727 	}
728 	/*
729 	 * Limit size of 'reason' string to 128. Will fit even when
730 	 * maximal number of arguments was chosen to be logged.
731 	 */
732 	if (uap->why != NULL) {
733 		error = sbuf_copyin(sb, uap->why, 128);
734 		if (error < 0)
735 			goto out;
736 	} else {
737 		sbuf_printf(sb, "(null)");
738 	}
739 	if (uap->nargs > 0) {
740 		sbuf_printf(sb, "(");
741 		for (i = 0;i < uap->nargs; i++)
742 			sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
743 		sbuf_printf(sb, ")");
744 	}
745 	/*
746 	 * Final stage: arguments were proper, string has been
747 	 * successfully copied from userspace, and copying pointers
748 	 * from user-space succeed.
749 	 */
750 	sig = SIGABRT;
751 out:
752 	if (sig == SIGKILL) {
753 		sbuf_trim(sb);
754 		sbuf_printf(sb, " (Reason text inaccessible)");
755 	}
756 	sbuf_cat(sb, "\n");
757 	sbuf_finish(sb);
758 	log(LOG_INFO, "%s", sbuf_data(sb));
759 	sbuf_delete(sb);
760 	exit1(td, 0, sig);
761 	return (0);
762 }
763 
764 
765 #ifdef COMPAT_43
766 /*
767  * The dirty work is handled by kern_wait().
768  */
769 int
owait(struct thread * td,struct owait_args * uap __unused)770 owait(struct thread *td, struct owait_args *uap __unused)
771 {
772 	int error, status;
773 
774 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
775 	if (error == 0)
776 		td->td_retval[1] = status;
777 	return (error);
778 }
779 #endif /* COMPAT_43 */
780 
781 /*
782  * The dirty work is handled by kern_wait().
783  */
784 int
sys_wait4(struct thread * td,struct wait4_args * uap)785 sys_wait4(struct thread *td, struct wait4_args *uap)
786 {
787 	struct rusage ru, *rup;
788 	int error, status;
789 
790 	if (uap->rusage != NULL)
791 		rup = &ru;
792 	else
793 		rup = NULL;
794 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
795 	if (uap->status != NULL && error == 0)
796 		error = copyout(&status, uap->status, sizeof(status));
797 	if (uap->rusage != NULL && error == 0)
798 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
799 	return (error);
800 }
801 
802 int
sys_wait6(struct thread * td,struct wait6_args * uap)803 sys_wait6(struct thread *td, struct wait6_args *uap)
804 {
805 	struct __wrusage wru, *wrup;
806 	siginfo_t si, *sip;
807 	idtype_t idtype;
808 	id_t id;
809 	int error, status;
810 
811 	idtype = uap->idtype;
812 	id = uap->id;
813 
814 	if (uap->wrusage != NULL)
815 		wrup = &wru;
816 	else
817 		wrup = NULL;
818 
819 	if (uap->info != NULL) {
820 		sip = &si;
821 		bzero(sip, sizeof(*sip));
822 	} else
823 		sip = NULL;
824 
825 	/*
826 	 *  We expect all callers of wait6() to know about WEXITED and
827 	 *  WTRAPPED.
828 	 */
829 	error = kern_wait6(td, idtype, id, &status, uap->options, wrup, sip);
830 
831 	if (uap->status != NULL && error == 0)
832 		error = copyout(&status, uap->status, sizeof(status));
833 	if (uap->wrusage != NULL && error == 0)
834 		error = copyout(&wru, uap->wrusage, sizeof(wru));
835 	if (uap->info != NULL && error == 0)
836 		error = copyout(&si, uap->info, sizeof(si));
837 	return (error);
838 }
839 
840 /*
841  * Reap the remains of a zombie process and optionally return status and
842  * rusage.  Asserts and will release both the proctree_lock and the process
843  * lock as part of its work.
844  */
845 void
proc_reap(struct thread * td,struct proc * p,int * status,int options)846 proc_reap(struct thread *td, struct proc *p, int *status, int options)
847 {
848 	struct proc *q, *t;
849 
850 	sx_assert(&proctree_lock, SA_XLOCKED);
851 	PROC_LOCK_ASSERT(p, MA_OWNED);
852 	PROC_SLOCK_ASSERT(p, MA_OWNED);
853 	KASSERT(p->p_state == PRS_ZOMBIE, ("proc_reap: !PRS_ZOMBIE"));
854 
855 	q = td->td_proc;
856 
857 	PROC_SUNLOCK(p);
858 	if (status)
859 		*status = KW_EXITCODE(p->p_xexit, p->p_xsig);
860 	if (options & WNOWAIT) {
861 		/*
862 		 *  Only poll, returning the status.  Caller does not wish to
863 		 * release the proc struct just yet.
864 		 */
865 		PROC_UNLOCK(p);
866 		sx_xunlock(&proctree_lock);
867 		return;
868 	}
869 
870 	PROC_LOCK(q);
871 	sigqueue_take(p->p_ksi);
872 	PROC_UNLOCK(q);
873 
874 	/*
875 	 * If we got the child via a ptrace 'attach', we need to give it back
876 	 * to the old parent.
877 	 */
878 	if (p->p_oppid != 0 && p->p_oppid != p->p_pptr->p_pid) {
879 		PROC_UNLOCK(p);
880 		t = proc_realparent(p);
881 		PROC_LOCK(t);
882 		PROC_LOCK(p);
883 		CTR2(KTR_PTRACE,
884 		    "wait: traced child %d moved back to parent %d", p->p_pid,
885 		    t->p_pid);
886 		proc_reparent(p, t);
887 		p->p_oppid = 0;
888 		PROC_UNLOCK(p);
889 		pksignal(t, SIGCHLD, p->p_ksi);
890 		wakeup(t);
891 		cv_broadcast(&p->p_pwait);
892 		PROC_UNLOCK(t);
893 		sx_xunlock(&proctree_lock);
894 		return;
895 	}
896 	p->p_oppid = 0;
897 	PROC_UNLOCK(p);
898 
899 	/*
900 	 * Remove other references to this process to ensure we have an
901 	 * exclusive reference.
902 	 */
903 	sx_xlock(&allproc_lock);
904 	LIST_REMOVE(p, p_list);	/* off zombproc */
905 	sx_xunlock(&allproc_lock);
906 	LIST_REMOVE(p, p_sibling);
907 	reaper_abandon_children(p, true);
908 	LIST_REMOVE(p, p_reapsibling);
909 	PROC_LOCK(p);
910 	clear_orphan(p);
911 	PROC_UNLOCK(p);
912 	leavepgrp(p);
913 	if (p->p_procdesc != NULL)
914 		procdesc_reap(p);
915 	sx_xunlock(&proctree_lock);
916 
917 	/*
918 	 * Removal from allproc list and process group list paired with
919 	 * PROC_LOCK which was executed during that time should guarantee
920 	 * nothing can reach this process anymore. As such further locking
921 	 * is unnecessary.
922 	 */
923 	p->p_xexit = p->p_xsig = 0;		/* XXX: why? */
924 
925 	PROC_LOCK(q);
926 	ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru, &p->p_rux);
927 	PROC_UNLOCK(q);
928 
929 	/*
930 	 * Decrement the count of procs running with this uid.
931 	 */
932 	(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
933 
934 	/*
935 	 * Destroy resource accounting information associated with the process.
936 	 */
937 #ifdef RACCT
938 	if (racct_enable) {
939 		PROC_LOCK(p);
940 		racct_sub(p, RACCT_NPROC, 1);
941 		PROC_UNLOCK(p);
942 	}
943 #endif
944 	racct_proc_exit(p);
945 
946 	/*
947 	 * Free credentials, arguments, and sigacts.
948 	 */
949 	crfree(p->p_ucred);
950 	proc_set_cred(p, NULL);
951 	pargs_drop(p->p_args);
952 	p->p_args = NULL;
953 	sigacts_free(p->p_sigacts);
954 	p->p_sigacts = NULL;
955 
956 	/*
957 	 * Do any thread-system specific cleanups.
958 	 */
959 	thread_wait(p);
960 
961 	/*
962 	 * Give vm and machine-dependent layer a chance to free anything that
963 	 * cpu_exit couldn't release while still running in process context.
964 	 */
965 	vm_waitproc(p);
966 #ifdef MAC
967 	mac_proc_destroy(p);
968 #endif
969 	/*
970 	 * Free any domain policy that's still hiding around.
971 	 */
972 	vm_domain_policy_cleanup(&p->p_vm_dom_policy);
973 
974 	KASSERT(FIRST_THREAD_IN_PROC(p),
975 	    ("proc_reap: no residual thread!"));
976 	uma_zfree(proc_zone, p);
977 	atomic_add_int(&nprocs, -1);
978 }
979 
980 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,int check_only)981 proc_to_reap(struct thread *td, struct proc *p, idtype_t idtype, id_t id,
982     int *status, int options, struct __wrusage *wrusage, siginfo_t *siginfo,
983     int check_only)
984 {
985 	struct rusage *rup;
986 
987 	sx_assert(&proctree_lock, SA_XLOCKED);
988 
989 	PROC_LOCK(p);
990 
991 	switch (idtype) {
992 	case P_ALL:
993 		if (p->p_procdesc != NULL) {
994 			PROC_UNLOCK(p);
995 			return (0);
996 		}
997 		break;
998 	case P_PID:
999 		if (p->p_pid != (pid_t)id) {
1000 			PROC_UNLOCK(p);
1001 			return (0);
1002 		}
1003 		break;
1004 	case P_PGID:
1005 		if (p->p_pgid != (pid_t)id) {
1006 			PROC_UNLOCK(p);
1007 			return (0);
1008 		}
1009 		break;
1010 	case P_SID:
1011 		if (p->p_session->s_sid != (pid_t)id) {
1012 			PROC_UNLOCK(p);
1013 			return (0);
1014 		}
1015 		break;
1016 	case P_UID:
1017 		if (p->p_ucred->cr_uid != (uid_t)id) {
1018 			PROC_UNLOCK(p);
1019 			return (0);
1020 		}
1021 		break;
1022 	case P_GID:
1023 		if (p->p_ucred->cr_gid != (gid_t)id) {
1024 			PROC_UNLOCK(p);
1025 			return (0);
1026 		}
1027 		break;
1028 	case P_JAILID:
1029 		if (p->p_ucred->cr_prison->pr_id != (int)id) {
1030 			PROC_UNLOCK(p);
1031 			return (0);
1032 		}
1033 		break;
1034 	/*
1035 	 * It seems that the thread structures get zeroed out
1036 	 * at process exit.  This makes it impossible to
1037 	 * support P_SETID, P_CID or P_CPUID.
1038 	 */
1039 	default:
1040 		PROC_UNLOCK(p);
1041 		return (0);
1042 	}
1043 
1044 	if (p_canwait(td, p)) {
1045 		PROC_UNLOCK(p);
1046 		return (0);
1047 	}
1048 
1049 	if (((options & WEXITED) == 0) && (p->p_state == PRS_ZOMBIE)) {
1050 		PROC_UNLOCK(p);
1051 		return (0);
1052 	}
1053 
1054 	/*
1055 	 * This special case handles a kthread spawned by linux_clone
1056 	 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
1057 	 * functions need to be able to distinguish between waiting
1058 	 * on a process and waiting on a thread.  It is a thread if
1059 	 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
1060 	 * signifies we want to wait for threads and not processes.
1061 	 */
1062 	if ((p->p_sigparent != SIGCHLD) ^
1063 	    ((options & WLINUXCLONE) != 0)) {
1064 		PROC_UNLOCK(p);
1065 		return (0);
1066 	}
1067 
1068 	if (siginfo != NULL) {
1069 		bzero(siginfo, sizeof(*siginfo));
1070 		siginfo->si_errno = 0;
1071 
1072 		/*
1073 		 * SUSv4 requires that the si_signo value is always
1074 		 * SIGCHLD. Obey it despite the rfork(2) interface
1075 		 * allows to request other signal for child exit
1076 		 * notification.
1077 		 */
1078 		siginfo->si_signo = SIGCHLD;
1079 
1080 		/*
1081 		 *  This is still a rough estimate.  We will fix the
1082 		 *  cases TRAPPED, STOPPED, and CONTINUED later.
1083 		 */
1084 		if (WCOREDUMP(p->p_xsig)) {
1085 			siginfo->si_code = CLD_DUMPED;
1086 			siginfo->si_status = WTERMSIG(p->p_xsig);
1087 		} else if (WIFSIGNALED(p->p_xsig)) {
1088 			siginfo->si_code = CLD_KILLED;
1089 			siginfo->si_status = WTERMSIG(p->p_xsig);
1090 		} else {
1091 			siginfo->si_code = CLD_EXITED;
1092 			siginfo->si_status = p->p_xexit;
1093 		}
1094 
1095 		siginfo->si_pid = p->p_pid;
1096 		siginfo->si_uid = p->p_ucred->cr_uid;
1097 
1098 		/*
1099 		 * The si_addr field would be useful additional
1100 		 * detail, but apparently the PC value may be lost
1101 		 * when we reach this point.  bzero() above sets
1102 		 * siginfo->si_addr to NULL.
1103 		 */
1104 	}
1105 
1106 	/*
1107 	 * There should be no reason to limit resources usage info to
1108 	 * exited processes only.  A snapshot about any resources used
1109 	 * by a stopped process may be exactly what is needed.
1110 	 */
1111 	if (wrusage != NULL) {
1112 		rup = &wrusage->wru_self;
1113 		*rup = p->p_ru;
1114 		PROC_STATLOCK(p);
1115 		calcru(p, &rup->ru_utime, &rup->ru_stime);
1116 		PROC_STATUNLOCK(p);
1117 
1118 		rup = &wrusage->wru_children;
1119 		*rup = p->p_stats->p_cru;
1120 		calccru(p, &rup->ru_utime, &rup->ru_stime);
1121 	}
1122 
1123 	if (p->p_state == PRS_ZOMBIE && !check_only) {
1124 		PROC_SLOCK(p);
1125 		proc_reap(td, p, status, options);
1126 		return (-1);
1127 	}
1128 	PROC_UNLOCK(p);
1129 	return (1);
1130 }
1131 
1132 int
kern_wait(struct thread * td,pid_t pid,int * status,int options,struct rusage * rusage)1133 kern_wait(struct thread *td, pid_t pid, int *status, int options,
1134     struct rusage *rusage)
1135 {
1136 	struct __wrusage wru, *wrup;
1137 	idtype_t idtype;
1138 	id_t id;
1139 	int ret;
1140 
1141 	/*
1142 	 * Translate the special pid values into the (idtype, pid)
1143 	 * pair for kern_wait6.  The WAIT_MYPGRP case is handled by
1144 	 * kern_wait6() on its own.
1145 	 */
1146 	if (pid == WAIT_ANY) {
1147 		idtype = P_ALL;
1148 		id = 0;
1149 	} else if (pid < 0) {
1150 		idtype = P_PGID;
1151 		id = (id_t)-pid;
1152 	} else {
1153 		idtype = P_PID;
1154 		id = (id_t)pid;
1155 	}
1156 
1157 	if (rusage != NULL)
1158 		wrup = &wru;
1159 	else
1160 		wrup = NULL;
1161 
1162 	/*
1163 	 * For backward compatibility we implicitly add flags WEXITED
1164 	 * and WTRAPPED here.
1165 	 */
1166 	options |= WEXITED | WTRAPPED;
1167 	ret = kern_wait6(td, idtype, id, status, options, wrup, NULL);
1168 	if (rusage != NULL)
1169 		*rusage = wru.wru_self;
1170 	return (ret);
1171 }
1172 
1173 int
kern_wait6(struct thread * td,idtype_t idtype,id_t id,int * status,int options,struct __wrusage * wrusage,siginfo_t * siginfo)1174 kern_wait6(struct thread *td, idtype_t idtype, id_t id, int *status,
1175     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1176 {
1177 	struct proc *p, *q;
1178 	pid_t pid;
1179 	int error, nfound, ret;
1180 
1181 	AUDIT_ARG_VALUE((int)idtype);	/* XXX - This is likely wrong! */
1182 	AUDIT_ARG_PID((pid_t)id);	/* XXX - This may be wrong! */
1183 	AUDIT_ARG_VALUE(options);
1184 
1185 	q = td->td_proc;
1186 
1187 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1188 		PROC_LOCK(q);
1189 		id = (id_t)q->p_pgid;
1190 		PROC_UNLOCK(q);
1191 		idtype = P_PGID;
1192 	}
1193 
1194 	/* If we don't know the option, just return. */
1195 	if ((options & ~(WUNTRACED | WNOHANG | WCONTINUED | WNOWAIT |
1196 	    WEXITED | WTRAPPED | WLINUXCLONE)) != 0)
1197 		return (EINVAL);
1198 	if ((options & (WEXITED | WUNTRACED | WCONTINUED | WTRAPPED)) == 0) {
1199 		/*
1200 		 * We will be unable to find any matching processes,
1201 		 * because there are no known events to look for.
1202 		 * Prefer to return error instead of blocking
1203 		 * indefinitely.
1204 		 */
1205 		return (EINVAL);
1206 	}
1207 
1208 loop:
1209 	if (q->p_flag & P_STATCHILD) {
1210 		PROC_LOCK(q);
1211 		q->p_flag &= ~P_STATCHILD;
1212 		PROC_UNLOCK(q);
1213 	}
1214 	nfound = 0;
1215 	sx_xlock(&proctree_lock);
1216 	LIST_FOREACH(p, &q->p_children, p_sibling) {
1217 		pid = p->p_pid;
1218 		ret = proc_to_reap(td, p, idtype, id, status, options,
1219 		    wrusage, siginfo, 0);
1220 		if (ret == 0)
1221 			continue;
1222 		else if (ret == 1)
1223 			nfound++;
1224 		else {
1225 			td->td_retval[0] = pid;
1226 			return (0);
1227 		}
1228 
1229 		PROC_LOCK(p);
1230 		PROC_SLOCK(p);
1231 
1232 		if ((options & WTRAPPED) != 0 &&
1233 		    (p->p_flag & P_TRACED) != 0 &&
1234 		    (p->p_flag & (P_STOPPED_TRACE | P_STOPPED_SIG)) != 0 &&
1235 		    (p->p_suspcount == p->p_numthreads) &&
1236 		    ((p->p_flag & P_WAITED) == 0)) {
1237 			PROC_SUNLOCK(p);
1238 			if ((options & WNOWAIT) == 0)
1239 				p->p_flag |= P_WAITED;
1240 			sx_xunlock(&proctree_lock);
1241 
1242 			if (status != NULL)
1243 				*status = W_STOPCODE(p->p_xsig);
1244 			if (siginfo != NULL) {
1245 				siginfo->si_status = p->p_xsig;
1246 				siginfo->si_code = CLD_TRAPPED;
1247 			}
1248 			if ((options & WNOWAIT) == 0) {
1249 				PROC_LOCK(q);
1250 				sigqueue_take(p->p_ksi);
1251 				PROC_UNLOCK(q);
1252 			}
1253 
1254 			CTR4(KTR_PTRACE,
1255 	    "wait: returning trapped pid %d status %#x (xstat %d) xthread %d",
1256 			    p->p_pid, W_STOPCODE(p->p_xsig), p->p_xsig,
1257 			    p->p_xthread != NULL ? p->p_xthread->td_tid : -1);
1258 			PROC_UNLOCK(p);
1259 			td->td_retval[0] = pid;
1260 			return (0);
1261 		}
1262 		if ((options & WUNTRACED) != 0 &&
1263 		    (p->p_flag & P_STOPPED_SIG) != 0 &&
1264 		    (p->p_suspcount == p->p_numthreads) &&
1265 		    ((p->p_flag & P_WAITED) == 0)) {
1266 			PROC_SUNLOCK(p);
1267 			if ((options & WNOWAIT) == 0)
1268 				p->p_flag |= P_WAITED;
1269 			sx_xunlock(&proctree_lock);
1270 
1271 			if (status != NULL)
1272 				*status = W_STOPCODE(p->p_xsig);
1273 			if (siginfo != NULL) {
1274 				siginfo->si_status = p->p_xsig;
1275 				siginfo->si_code = CLD_STOPPED;
1276 			}
1277 			if ((options & WNOWAIT) == 0) {
1278 				PROC_LOCK(q);
1279 				sigqueue_take(p->p_ksi);
1280 				PROC_UNLOCK(q);
1281 			}
1282 
1283 			PROC_UNLOCK(p);
1284 			td->td_retval[0] = pid;
1285 			return (0);
1286 		}
1287 		PROC_SUNLOCK(p);
1288 		if ((options & WCONTINUED) != 0 &&
1289 		    (p->p_flag & P_CONTINUED) != 0) {
1290 			sx_xunlock(&proctree_lock);
1291 			if ((options & WNOWAIT) == 0) {
1292 				p->p_flag &= ~P_CONTINUED;
1293 				PROC_LOCK(q);
1294 				sigqueue_take(p->p_ksi);
1295 				PROC_UNLOCK(q);
1296 			}
1297 			PROC_UNLOCK(p);
1298 
1299 			if (status != NULL)
1300 				*status = SIGCONT;
1301 			if (siginfo != NULL) {
1302 				siginfo->si_status = SIGCONT;
1303 				siginfo->si_code = CLD_CONTINUED;
1304 			}
1305 			td->td_retval[0] = pid;
1306 			return (0);
1307 		}
1308 		PROC_UNLOCK(p);
1309 	}
1310 
1311 	/*
1312 	 * Look in the orphans list too, to allow the parent to
1313 	 * collect it's child exit status even if child is being
1314 	 * debugged.
1315 	 *
1316 	 * Debugger detaches from the parent upon successful
1317 	 * switch-over from parent to child.  At this point due to
1318 	 * re-parenting the parent loses the child to debugger and a
1319 	 * wait4(2) call would report that it has no children to wait
1320 	 * for.  By maintaining a list of orphans we allow the parent
1321 	 * to successfully wait until the child becomes a zombie.
1322 	 */
1323 	if (nfound == 0) {
1324 		LIST_FOREACH(p, &q->p_orphans, p_orphan) {
1325 			ret = proc_to_reap(td, p, idtype, id, NULL, options,
1326 			    NULL, NULL, 1);
1327 			if (ret != 0) {
1328 				KASSERT(ret != -1, ("reaped an orphan (pid %d)",
1329 				    (int)td->td_retval[0]));
1330 				nfound++;
1331 				break;
1332 			}
1333 		}
1334 	}
1335 	if (nfound == 0) {
1336 		sx_xunlock(&proctree_lock);
1337 		return (ECHILD);
1338 	}
1339 	if (options & WNOHANG) {
1340 		sx_xunlock(&proctree_lock);
1341 		td->td_retval[0] = 0;
1342 		return (0);
1343 	}
1344 	PROC_LOCK(q);
1345 	sx_xunlock(&proctree_lock);
1346 	if (q->p_flag & P_STATCHILD) {
1347 		q->p_flag &= ~P_STATCHILD;
1348 		error = 0;
1349 	} else
1350 		error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
1351 	PROC_UNLOCK(q);
1352 	if (error)
1353 		return (error);
1354 	goto loop;
1355 }
1356 
1357 /*
1358  * Make process 'parent' the new parent of process 'child'.
1359  * Must be called with an exclusive hold of proctree lock.
1360  */
1361 void
proc_reparent(struct proc * child,struct proc * parent)1362 proc_reparent(struct proc *child, struct proc *parent)
1363 {
1364 
1365 	sx_assert(&proctree_lock, SX_XLOCKED);
1366 	PROC_LOCK_ASSERT(child, MA_OWNED);
1367 	if (child->p_pptr == parent)
1368 		return;
1369 
1370 	PROC_LOCK(child->p_pptr);
1371 	sigqueue_take(child->p_ksi);
1372 	PROC_UNLOCK(child->p_pptr);
1373 	LIST_REMOVE(child, p_sibling);
1374 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1375 
1376 	clear_orphan(child);
1377 	if (child->p_flag & P_TRACED) {
1378 		if (LIST_EMPTY(&child->p_pptr->p_orphans)) {
1379 			child->p_treeflag |= P_TREE_FIRST_ORPHAN;
1380 			LIST_INSERT_HEAD(&child->p_pptr->p_orphans, child,
1381 			    p_orphan);
1382 		} else {
1383 			LIST_INSERT_AFTER(LIST_FIRST(&child->p_pptr->p_orphans),
1384 			    child, p_orphan);
1385 		}
1386 		child->p_treeflag |= P_TREE_ORPHANED;
1387 	}
1388 
1389 	child->p_pptr = parent;
1390 }
1391