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