xref: /openbsd-src/sys/kern/kern_exit.c (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
1 /*	$OpenBSD: kern_exit.c,v 1.172 2019/01/06 12:59:45 visa Exp $	*/
2 /*	$NetBSD: kern_exit.c,v 1.39 1996/04/22 01:38:25 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/ioctl.h>
43 #include <sys/proc.h>
44 #include <sys/tty.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/wait.h>
50 #include <sys/vnode.h>
51 #include <sys/syslog.h>
52 #include <sys/malloc.h>
53 #include <sys/resourcevar.h>
54 #include <sys/ptrace.h>
55 #include <sys/acct.h>
56 #include <sys/filedesc.h>
57 #include <sys/signalvar.h>
58 #include <sys/sched.h>
59 #include <sys/ktrace.h>
60 #include <sys/pool.h>
61 #include <sys/mutex.h>
62 #include <sys/pledge.h>
63 #ifdef SYSVSEM
64 #include <sys/sem.h>
65 #endif
66 #include <sys/witness.h>
67 
68 #include <sys/mount.h>
69 #include <sys/syscallargs.h>
70 
71 #include <uvm/uvm_extern.h>
72 
73 #include "kcov.h"
74 #if NKCOV > 0
75 #include <sys/kcov.h>
76 #endif
77 
78 void	proc_finish_wait(struct proc *, struct proc *);
79 void	process_zap(struct process *);
80 void	proc_free(struct proc *);
81 void	unveil_destroy(struct process *ps);
82 
83 /*
84  * exit --
85  *	Death of process.
86  */
87 int
88 sys_exit(struct proc *p, void *v, register_t *retval)
89 {
90 	struct sys_exit_args /* {
91 		syscallarg(int) rval;
92 	} */ *uap = v;
93 
94 	exit1(p, W_EXITCODE(SCARG(uap, rval), 0), EXIT_NORMAL);
95 	/* NOTREACHED */
96 	return (0);
97 }
98 
99 int
100 sys___threxit(struct proc *p, void *v, register_t *retval)
101 {
102 	struct sys___threxit_args /* {
103 		syscallarg(pid_t *) notdead;
104 	} */ *uap = v;
105 
106 	if (SCARG(uap, notdead) != NULL) {
107 		pid_t zero = 0;
108 		if (copyout(&zero, SCARG(uap, notdead), sizeof(zero)))
109 			psignal(p, SIGSEGV);
110 	}
111 	exit1(p, 0, EXIT_THREAD);
112 
113 	return (0);
114 }
115 
116 /*
117  * Exit: deallocate address space and other resources, change proc state
118  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
119  * status and rusage for wait().  Check for child processes and orphan them.
120  */
121 void
122 exit1(struct proc *p, int rv, int flags)
123 {
124 	struct process *pr, *qr, *nqr;
125 	struct rusage *rup;
126 
127 	atomic_setbits_int(&p->p_flag, P_WEXIT);
128 
129 	pr = p->p_p;
130 
131 	/* single-threaded? */
132 	if (!P_HASSIBLING(p)) {
133 		flags = EXIT_NORMAL;
134 	} else {
135 		/* nope, multi-threaded */
136 		if (flags == EXIT_NORMAL)
137 			single_thread_set(p, SINGLE_EXIT, 0);
138 		else if (flags == EXIT_THREAD)
139 			single_thread_check(p, 0);
140 	}
141 
142 	if (flags == EXIT_NORMAL) {
143 		if (pr->ps_pid == 1)
144 			panic("init died (signal %d, exit %d)",
145 			    WTERMSIG(rv), WEXITSTATUS(rv));
146 
147 		atomic_setbits_int(&pr->ps_flags, PS_EXITING);
148 		pr->ps_mainproc->p_xstat = rv;
149 
150 		/*
151 		 * If parent is waiting for us to exit or exec, PS_PPWAIT
152 		 * is set; we wake up the parent early to avoid deadlock.
153 		 */
154 		if (pr->ps_flags & PS_PPWAIT) {
155 			atomic_clearbits_int(&pr->ps_flags, PS_PPWAIT);
156 			atomic_clearbits_int(&pr->ps_pptr->ps_flags,
157 			    PS_ISPWAIT);
158 			wakeup(pr->ps_pptr);
159 		}
160 	}
161 
162 	/* unlink ourselves from the active threads */
163 	TAILQ_REMOVE(&pr->ps_threads, p, p_thr_link);
164 	if ((p->p_flag & P_THREAD) == 0) {
165 		/* main thread gotta wait because it has the pid, et al */
166 		while (pr->ps_refcnt > 1)
167 			tsleep(&pr->ps_threads, PUSER, "thrdeath", 0);
168 		if (pr->ps_flags & PS_PROFIL)
169 			stopprofclock(pr);
170 	}
171 
172 	rup = pr->ps_ru;
173 	if (rup == NULL) {
174 		rup = pool_get(&rusage_pool, PR_WAITOK | PR_ZERO);
175 		if (pr->ps_ru == NULL) {
176 			pr->ps_ru = rup;
177 		} else {
178 			pool_put(&rusage_pool, rup);
179 			rup = pr->ps_ru;
180 		}
181 	}
182 	p->p_siglist = 0;
183 
184 #if NKCOV > 0
185 	kcov_exit(p);
186 #endif
187 
188 	if ((p->p_flag & P_THREAD) == 0) {
189 		sigio_freelist(&pr->ps_sigiolst);
190 
191 		/* close open files and release open-file table */
192 		fdfree(p);
193 
194 		timeout_del(&pr->ps_realit_to);
195 		timeout_del(&pr->ps_rucheck_to);
196 #ifdef SYSVSEM
197 		semexit(pr);
198 #endif
199 		killjobc(pr);
200 #ifdef ACCOUNTING
201 		acct_process(p);
202 #endif
203 
204 #ifdef KTRACE
205 		/* release trace file */
206 		if (pr->ps_tracevp)
207 			ktrcleartrace(pr);
208 #endif
209 
210 		unveil_destroy(pr);
211 
212 		/*
213 		 * If parent has the SAS_NOCLDWAIT flag set, we're not
214 		 * going to become a zombie.
215 		 */
216 		if (pr->ps_pptr->ps_sigacts->ps_flags & SAS_NOCLDWAIT)
217 			atomic_setbits_int(&pr->ps_flags, PS_NOZOMBIE);
218 	}
219 
220 	p->p_fd = NULL;		/* zap the thread's copy */
221 
222         /*
223 	 * Remove proc from pidhash chain and allproc so looking
224 	 * it up won't work.  We will put the proc on the
225 	 * deadproc list later (using the p_hash member), and
226 	 * wake up the reaper when we do.  If this is the last
227 	 * thread of a process that isn't PS_NOZOMBIE, we'll put
228 	 * the process on the zombprocess list below.
229 	 */
230 	/*
231 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
232 	 */
233 	p->p_stat = SDEAD;
234 
235 	LIST_REMOVE(p, p_hash);
236 	LIST_REMOVE(p, p_list);
237 
238 	if ((p->p_flag & P_THREAD) == 0) {
239 		LIST_REMOVE(pr, ps_hash);
240 		LIST_REMOVE(pr, ps_list);
241 
242 		if ((pr->ps_flags & PS_NOZOMBIE) == 0)
243 			LIST_INSERT_HEAD(&zombprocess, pr, ps_list);
244 		else {
245 			/*
246 			 * Not going to be a zombie, so it's now off all
247 			 * the lists scanned by ispidtaken(), so block
248 			 * fast reuse of the pid now.
249 			 */
250 			freepid(pr->ps_pid);
251 		}
252 
253 		/*
254 		 * Give orphaned children to init(8).
255 		 */
256 		qr = LIST_FIRST(&pr->ps_children);
257 		if (qr)		/* only need this if any child is S_ZOMB */
258 			wakeup(initprocess);
259 		for (; qr != 0; qr = nqr) {
260 			nqr = LIST_NEXT(qr, ps_sibling);
261 			proc_reparent(qr, initprocess);
262 			/*
263 			 * Traced processes are killed since their
264 			 * existence means someone is screwing up.
265 			 */
266 			if (qr->ps_flags & PS_TRACED &&
267 			    !(qr->ps_flags & PS_EXITING)) {
268 				atomic_clearbits_int(&qr->ps_flags, PS_TRACED);
269 				/*
270 				 * If single threading is active,
271 				 * direct the signal to the active
272 				 * thread to avoid deadlock.
273 				 */
274 				if (qr->ps_single)
275 					ptsignal(qr->ps_single, SIGKILL,
276 					    STHREAD);
277 				else
278 					prsignal(qr, SIGKILL);
279 			}
280 		}
281 	}
282 
283 	/* add thread's accumulated rusage into the process's total */
284 	ruadd(rup, &p->p_ru);
285 	tuagg(pr, p);
286 
287 	/*
288 	 * clear %cpu usage during swap
289 	 */
290 	p->p_pctcpu = 0;
291 
292 	if ((p->p_flag & P_THREAD) == 0) {
293 		/*
294 		 * Final thread has died, so add on our children's rusage
295 		 * and calculate the total times
296 		 */
297 		calcru(&pr->ps_tu, &rup->ru_utime, &rup->ru_stime, NULL);
298 		ruadd(rup, &pr->ps_cru);
299 
300 		/* notify interested parties of our demise and clean up */
301 		knote_processexit(p);
302 
303 		/*
304 		 * Notify parent that we're gone.  If we're not going to
305 		 * become a zombie, reparent to process 1 (init) so that
306 		 * we can wake our original parent to possibly unblock
307 		 * wait4() to return ECHILD.
308 		 */
309 		if (pr->ps_flags & PS_NOZOMBIE) {
310 			struct process *ppr = pr->ps_pptr;
311 			proc_reparent(pr, initprocess);
312 			wakeup(ppr);
313 		}
314 
315 		/*
316 		 * Release the process's signal state.
317 		 */
318 		sigactsfree(pr);
319 	}
320 
321 	/* just a thread? detach it from its process */
322 	if (p->p_flag & P_THREAD) {
323 		/* scheduler_wait_hook(pr->ps_mainproc, p); XXX */
324 		if (--pr->ps_refcnt == 1)
325 			wakeup(&pr->ps_threads);
326 		KASSERT(pr->ps_refcnt > 0);
327 	}
328 
329 	/*
330 	 * Other substructures are freed from reaper and wait().
331 	 */
332 
333 	/*
334 	 * Finally, call machine-dependent code to switch to a new
335 	 * context (possibly the idle context).  Once we are no longer
336 	 * using the dead process's vmspace and stack, exit2() will be
337 	 * called to schedule those resources to be released by the
338 	 * reaper thread.
339 	 *
340 	 * Note that cpu_exit() will end with a call equivalent to
341 	 * cpu_switch(), finishing our execution (pun intended).
342 	 */
343 	uvmexp.swtch++;
344 	cpu_exit(p);
345 	panic("cpu_exit returned");
346 }
347 
348 /*
349  * Locking of this proclist is special; it's accessed in a
350  * critical section of process exit, and thus locking it can't
351  * modify interrupt state.  We use a simple spin lock for this
352  * proclist.  We use the p_hash member to linkup to deadproc.
353  */
354 struct mutex deadproc_mutex =
355     MUTEX_INITIALIZER_FLAGS(IPL_NONE, NULL, MTX_NOWITNESS);
356 struct proclist deadproc = LIST_HEAD_INITIALIZER(deadproc);
357 
358 /*
359  * We are called from cpu_exit() once it is safe to schedule the
360  * dead process's resources to be freed.
361  *
362  * NOTE: One must be careful with locking in this routine.  It's
363  * called from a critical section in machine-dependent code, so
364  * we should refrain from changing any interrupt state.
365  *
366  * We lock the deadproc list, place the proc on that list (using
367  * the p_hash member), and wake up the reaper.
368  */
369 void
370 exit2(struct proc *p)
371 {
372 	mtx_enter(&deadproc_mutex);
373 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
374 	mtx_leave(&deadproc_mutex);
375 
376 	wakeup(&deadproc);
377 }
378 
379 void
380 proc_free(struct proc *p)
381 {
382 	crfree(p->p_ucred);
383 	pool_put(&proc_pool, p);
384 	nthreads--;
385 }
386 
387 /*
388  * Process reaper.  This is run by a kernel thread to free the resources
389  * of a dead process.  Once the resources are free, the process becomes
390  * a zombie, and the parent is allowed to read the undead's status.
391  */
392 void
393 reaper(void *arg)
394 {
395 	struct proc *p;
396 
397 	KERNEL_UNLOCK();
398 
399 	SCHED_ASSERT_UNLOCKED();
400 
401 	for (;;) {
402 		mtx_enter(&deadproc_mutex);
403 		while ((p = LIST_FIRST(&deadproc)) == NULL)
404 			msleep(&deadproc, &deadproc_mutex, PVM, "reaper", 0);
405 
406 		/* Remove us from the deadproc list. */
407 		LIST_REMOVE(p, p_hash);
408 		mtx_leave(&deadproc_mutex);
409 
410 		WITNESS_THREAD_EXIT(p);
411 
412 		KERNEL_LOCK();
413 
414 		/*
415 		 * Free the VM resources we're still holding on to.
416 		 * We must do this from a valid thread because doing
417 		 * so may block.
418 		 */
419 		uvm_uarea_free(p);
420 		p->p_vmspace = NULL;		/* zap the thread's copy */
421 
422 		if (p->p_flag & P_THREAD) {
423 			/* Just a thread */
424 			proc_free(p);
425 		} else {
426 			struct process *pr = p->p_p;
427 
428 			/* Release the rest of the process's vmspace */
429 			uvm_exit(pr);
430 
431 			if ((pr->ps_flags & PS_NOZOMBIE) == 0) {
432 				/* Process is now a true zombie. */
433 				atomic_setbits_int(&pr->ps_flags, PS_ZOMBIE);
434 				prsignal(pr->ps_pptr, SIGCHLD);
435 
436 				/* Wake up the parent so it can get exit status. */
437 				wakeup(pr->ps_pptr);
438 			} else {
439 				/* No one will wait for us. Just zap the process now */
440 				process_zap(pr);
441 			}
442 		}
443 
444 		KERNEL_UNLOCK();
445 	}
446 }
447 
448 int
449 sys_wait4(struct proc *q, void *v, register_t *retval)
450 {
451 	struct sys_wait4_args /* {
452 		syscallarg(pid_t) pid;
453 		syscallarg(int *) status;
454 		syscallarg(int) options;
455 		syscallarg(struct rusage *) rusage;
456 	} */ *uap = v;
457 	struct rusage ru;
458 	int status, error;
459 
460 	error = dowait4(q, SCARG(uap, pid),
461 	    SCARG(uap, status) ? &status : NULL,
462 	    SCARG(uap, options), SCARG(uap, rusage) ? &ru : NULL, retval);
463 	if (error == 0 && retval[0] > 0 && SCARG(uap, status)) {
464 		error = copyout(&status, SCARG(uap, status), sizeof(status));
465 	}
466 	if (error == 0 && retval[0] > 0 && SCARG(uap, rusage)) {
467 		error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
468 #ifdef KTRACE
469 		if (error == 0 && KTRPOINT(q, KTR_STRUCT))
470 			ktrrusage(q, &ru);
471 #endif
472 	}
473 	return (error);
474 }
475 
476 int
477 dowait4(struct proc *q, pid_t pid, int *statusp, int options,
478     struct rusage *rusage, register_t *retval)
479 {
480 	int nfound;
481 	struct process *pr;
482 	struct proc *p;
483 	int error;
484 
485 	if (pid == 0)
486 		pid = -q->p_p->ps_pgid;
487 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED))
488 		return (EINVAL);
489 
490 loop:
491 	nfound = 0;
492 	LIST_FOREACH(pr, &q->p_p->ps_children, ps_sibling) {
493 		if ((pr->ps_flags & PS_NOZOMBIE) ||
494 		    (pid != WAIT_ANY &&
495 		    pr->ps_pid != pid &&
496 		    pr->ps_pgid != -pid))
497 			continue;
498 
499 		p = pr->ps_mainproc;
500 
501 		nfound++;
502 		if (pr->ps_flags & PS_ZOMBIE) {
503 			retval[0] = pr->ps_pid;
504 
505 			if (statusp != NULL)
506 				*statusp = p->p_xstat;	/* convert to int */
507 			if (rusage != NULL)
508 				memcpy(rusage, pr->ps_ru, sizeof(*rusage));
509 			proc_finish_wait(q, p);
510 			return (0);
511 		}
512 		if (pr->ps_flags & PS_TRACED &&
513 		    (pr->ps_flags & PS_WAITED) == 0 && pr->ps_single &&
514 		    pr->ps_single->p_stat == SSTOP &&
515 		    (pr->ps_single->p_flag & P_SUSPSINGLE) == 0) {
516 			single_thread_wait(pr);
517 
518 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
519 			retval[0] = pr->ps_pid;
520 
521 			if (statusp != NULL)
522 				*statusp = W_STOPCODE(pr->ps_single->p_xstat);
523 			if (rusage != NULL)
524 				memset(rusage, 0, sizeof(*rusage));
525 			return (0);
526 		}
527 		if (p->p_stat == SSTOP &&
528 		    (pr->ps_flags & PS_WAITED) == 0 &&
529 		    (p->p_flag & P_SUSPSINGLE) == 0 &&
530 		    (pr->ps_flags & PS_TRACED ||
531 		    options & WUNTRACED)) {
532 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
533 			retval[0] = pr->ps_pid;
534 
535 			if (statusp != NULL)
536 				*statusp = W_STOPCODE(p->p_xstat);
537 			if (rusage != NULL)
538 				memset(rusage, 0, sizeof(*rusage));
539 			return (0);
540 		}
541 		if ((options & WCONTINUED) && (p->p_flag & P_CONTINUED)) {
542 			atomic_clearbits_int(&p->p_flag, P_CONTINUED);
543 			retval[0] = pr->ps_pid;
544 
545 			if (statusp != NULL)
546 				*statusp = _WCONTINUED;
547 			if (rusage != NULL)
548 				memset(rusage, 0, sizeof(*rusage));
549 			return (0);
550 		}
551 	}
552 	if (nfound == 0)
553 		return (ECHILD);
554 	if (options & WNOHANG) {
555 		retval[0] = 0;
556 		return (0);
557 	}
558 	if ((error = tsleep(q->p_p, PWAIT | PCATCH, "wait", 0)) != 0)
559 		return (error);
560 	goto loop;
561 }
562 
563 void
564 proc_finish_wait(struct proc *waiter, struct proc *p)
565 {
566 	struct process *pr, *tr;
567 	struct rusage *rup;
568 
569 	/*
570 	 * If we got the child via a ptrace 'attach',
571 	 * we need to give it back to the old parent.
572 	 */
573 	pr = p->p_p;
574 	if (pr->ps_oppid && (tr = prfind(pr->ps_oppid))) {
575 		atomic_clearbits_int(&pr->ps_flags, PS_TRACED);
576 		pr->ps_oppid = 0;
577 		proc_reparent(pr, tr);
578 		prsignal(tr, SIGCHLD);
579 		wakeup(tr);
580 	} else {
581 		scheduler_wait_hook(waiter, p);
582 		p->p_xstat = 0;
583 		rup = &waiter->p_p->ps_cru;
584 		ruadd(rup, pr->ps_ru);
585 		LIST_REMOVE(pr, ps_list);	/* off zombprocess */
586 		freepid(pr->ps_pid);
587 		process_zap(pr);
588 	}
589 }
590 
591 /*
592  * make process 'parent' the new parent of process 'child'.
593  */
594 void
595 proc_reparent(struct process *child, struct process *parent)
596 {
597 
598 	if (child->ps_pptr == parent)
599 		return;
600 
601 	LIST_REMOVE(child, ps_sibling);
602 	LIST_INSERT_HEAD(&parent->ps_children, child, ps_sibling);
603 	child->ps_pptr = parent;
604 }
605 
606 void
607 process_zap(struct process *pr)
608 {
609 	struct vnode *otvp;
610 	struct proc *p = pr->ps_mainproc;
611 
612 	/*
613 	 * Finally finished with old proc entry.
614 	 * Unlink it from its process group and free it.
615 	 */
616 	leavepgrp(pr);
617 	LIST_REMOVE(pr, ps_sibling);
618 
619 	/*
620 	 * Decrement the count of procs running with this uid.
621 	 */
622 	(void)chgproccnt(pr->ps_ucred->cr_ruid, -1);
623 
624 	/*
625 	 * Release reference to text vnode
626 	 */
627 	otvp = pr->ps_textvp;
628 	pr->ps_textvp = NULL;
629 	if (otvp)
630 		vrele(otvp);
631 
632 	KASSERT(pr->ps_refcnt == 1);
633 	if (pr->ps_ptstat != NULL)
634 		free(pr->ps_ptstat, M_SUBPROC, sizeof(*pr->ps_ptstat));
635 	pool_put(&rusage_pool, pr->ps_ru);
636 	KASSERT(TAILQ_EMPTY(&pr->ps_threads));
637 	limfree(pr->ps_limit);
638 	crfree(pr->ps_ucred);
639 	pool_put(&process_pool, pr);
640 	nprocesses--;
641 
642 	proc_free(p);
643 }
644