xref: /openbsd-src/sys/kern/kern_exit.c (revision ddce81d18ead1cead306cecb446175faf94d13e9)
1 /*	$OpenBSD: kern_exit.c,v 1.171 2018/11/12 15:09:17 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 #ifdef SYSVSEM
196 		semexit(pr);
197 #endif
198 		killjobc(pr);
199 #ifdef ACCOUNTING
200 		acct_process(p);
201 #endif
202 
203 #ifdef KTRACE
204 		/* release trace file */
205 		if (pr->ps_tracevp)
206 			ktrcleartrace(pr);
207 #endif
208 
209 		unveil_destroy(pr);
210 
211 		/*
212 		 * If parent has the SAS_NOCLDWAIT flag set, we're not
213 		 * going to become a zombie.
214 		 */
215 		if (pr->ps_pptr->ps_sigacts->ps_flags & SAS_NOCLDWAIT)
216 			atomic_setbits_int(&pr->ps_flags, PS_NOZOMBIE);
217 	}
218 
219 	p->p_fd = NULL;		/* zap the thread's copy */
220 
221         /*
222 	 * Remove proc from pidhash chain and allproc so looking
223 	 * it up won't work.  We will put the proc on the
224 	 * deadproc list later (using the p_hash member), and
225 	 * wake up the reaper when we do.  If this is the last
226 	 * thread of a process that isn't PS_NOZOMBIE, we'll put
227 	 * the process on the zombprocess list below.
228 	 */
229 	/*
230 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
231 	 */
232 	p->p_stat = SDEAD;
233 
234 	LIST_REMOVE(p, p_hash);
235 	LIST_REMOVE(p, p_list);
236 
237 	if ((p->p_flag & P_THREAD) == 0) {
238 		LIST_REMOVE(pr, ps_hash);
239 		LIST_REMOVE(pr, ps_list);
240 
241 		if ((pr->ps_flags & PS_NOZOMBIE) == 0)
242 			LIST_INSERT_HEAD(&zombprocess, pr, ps_list);
243 		else {
244 			/*
245 			 * Not going to be a zombie, so it's now off all
246 			 * the lists scanned by ispidtaken(), so block
247 			 * fast reuse of the pid now.
248 			 */
249 			freepid(pr->ps_pid);
250 		}
251 
252 		/*
253 		 * Give orphaned children to init(8).
254 		 */
255 		qr = LIST_FIRST(&pr->ps_children);
256 		if (qr)		/* only need this if any child is S_ZOMB */
257 			wakeup(initprocess);
258 		for (; qr != 0; qr = nqr) {
259 			nqr = LIST_NEXT(qr, ps_sibling);
260 			proc_reparent(qr, initprocess);
261 			/*
262 			 * Traced processes are killed since their
263 			 * existence means someone is screwing up.
264 			 */
265 			if (qr->ps_flags & PS_TRACED &&
266 			    !(qr->ps_flags & PS_EXITING)) {
267 				atomic_clearbits_int(&qr->ps_flags, PS_TRACED);
268 				/*
269 				 * If single threading is active,
270 				 * direct the signal to the active
271 				 * thread to avoid deadlock.
272 				 */
273 				if (qr->ps_single)
274 					ptsignal(qr->ps_single, SIGKILL,
275 					    STHREAD);
276 				else
277 					prsignal(qr, SIGKILL);
278 			}
279 		}
280 	}
281 
282 	/* add thread's accumulated rusage into the process's total */
283 	ruadd(rup, &p->p_ru);
284 	tuagg(pr, p);
285 
286 	/*
287 	 * clear %cpu usage during swap
288 	 */
289 	p->p_pctcpu = 0;
290 
291 	if ((p->p_flag & P_THREAD) == 0) {
292 		/*
293 		 * Final thread has died, so add on our children's rusage
294 		 * and calculate the total times
295 		 */
296 		calcru(&pr->ps_tu, &rup->ru_utime, &rup->ru_stime, NULL);
297 		ruadd(rup, &pr->ps_cru);
298 
299 		/* notify interested parties of our demise and clean up */
300 		knote_processexit(p);
301 
302 		/*
303 		 * Notify parent that we're gone.  If we're not going to
304 		 * become a zombie, reparent to process 1 (init) so that
305 		 * we can wake our original parent to possibly unblock
306 		 * wait4() to return ECHILD.
307 		 */
308 		if (pr->ps_flags & PS_NOZOMBIE) {
309 			struct process *ppr = pr->ps_pptr;
310 			proc_reparent(pr, initprocess);
311 			wakeup(ppr);
312 		}
313 
314 		/*
315 		 * Release the process's signal state.
316 		 */
317 		sigactsfree(pr);
318 	}
319 
320 	/* just a thread? detach it from its process */
321 	if (p->p_flag & P_THREAD) {
322 		/* scheduler_wait_hook(pr->ps_mainproc, p); XXX */
323 		if (--pr->ps_refcnt == 1)
324 			wakeup(&pr->ps_threads);
325 		KASSERT(pr->ps_refcnt > 0);
326 	}
327 
328 	/*
329 	 * Other substructures are freed from reaper and wait().
330 	 */
331 
332 	/*
333 	 * Finally, call machine-dependent code to switch to a new
334 	 * context (possibly the idle context).  Once we are no longer
335 	 * using the dead process's vmspace and stack, exit2() will be
336 	 * called to schedule those resources to be released by the
337 	 * reaper thread.
338 	 *
339 	 * Note that cpu_exit() will end with a call equivalent to
340 	 * cpu_switch(), finishing our execution (pun intended).
341 	 */
342 	uvmexp.swtch++;
343 	cpu_exit(p);
344 	panic("cpu_exit returned");
345 }
346 
347 /*
348  * Locking of this proclist is special; it's accessed in a
349  * critical section of process exit, and thus locking it can't
350  * modify interrupt state.  We use a simple spin lock for this
351  * proclist.  We use the p_hash member to linkup to deadproc.
352  */
353 struct mutex deadproc_mutex =
354     MUTEX_INITIALIZER_FLAGS(IPL_NONE, NULL, MTX_NOWITNESS);
355 struct proclist deadproc = LIST_HEAD_INITIALIZER(deadproc);
356 
357 /*
358  * We are called from cpu_exit() once it is safe to schedule the
359  * dead process's resources to be freed.
360  *
361  * NOTE: One must be careful with locking in this routine.  It's
362  * called from a critical section in machine-dependent code, so
363  * we should refrain from changing any interrupt state.
364  *
365  * We lock the deadproc list, place the proc on that list (using
366  * the p_hash member), and wake up the reaper.
367  */
368 void
369 exit2(struct proc *p)
370 {
371 	mtx_enter(&deadproc_mutex);
372 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
373 	mtx_leave(&deadproc_mutex);
374 
375 	wakeup(&deadproc);
376 }
377 
378 void
379 proc_free(struct proc *p)
380 {
381 	crfree(p->p_ucred);
382 	pool_put(&proc_pool, p);
383 	nthreads--;
384 }
385 
386 /*
387  * Process reaper.  This is run by a kernel thread to free the resources
388  * of a dead process.  Once the resources are free, the process becomes
389  * a zombie, and the parent is allowed to read the undead's status.
390  */
391 void
392 reaper(void *arg)
393 {
394 	struct proc *p;
395 
396 	KERNEL_UNLOCK();
397 
398 	SCHED_ASSERT_UNLOCKED();
399 
400 	for (;;) {
401 		mtx_enter(&deadproc_mutex);
402 		while ((p = LIST_FIRST(&deadproc)) == NULL)
403 			msleep(&deadproc, &deadproc_mutex, PVM, "reaper", 0);
404 
405 		/* Remove us from the deadproc list. */
406 		LIST_REMOVE(p, p_hash);
407 		mtx_leave(&deadproc_mutex);
408 
409 		WITNESS_THREAD_EXIT(p);
410 
411 		KERNEL_LOCK();
412 
413 		/*
414 		 * Free the VM resources we're still holding on to.
415 		 * We must do this from a valid thread because doing
416 		 * so may block.
417 		 */
418 		uvm_uarea_free(p);
419 		p->p_vmspace = NULL;		/* zap the thread's copy */
420 
421 		if (p->p_flag & P_THREAD) {
422 			/* Just a thread */
423 			proc_free(p);
424 		} else {
425 			struct process *pr = p->p_p;
426 
427 			/* Release the rest of the process's vmspace */
428 			uvm_exit(pr);
429 
430 			if ((pr->ps_flags & PS_NOZOMBIE) == 0) {
431 				/* Process is now a true zombie. */
432 				atomic_setbits_int(&pr->ps_flags, PS_ZOMBIE);
433 				prsignal(pr->ps_pptr, SIGCHLD);
434 
435 				/* Wake up the parent so it can get exit status. */
436 				wakeup(pr->ps_pptr);
437 			} else {
438 				/* No one will wait for us. Just zap the process now */
439 				process_zap(pr);
440 			}
441 		}
442 
443 		KERNEL_UNLOCK();
444 	}
445 }
446 
447 int
448 sys_wait4(struct proc *q, void *v, register_t *retval)
449 {
450 	struct sys_wait4_args /* {
451 		syscallarg(pid_t) pid;
452 		syscallarg(int *) status;
453 		syscallarg(int) options;
454 		syscallarg(struct rusage *) rusage;
455 	} */ *uap = v;
456 	struct rusage ru;
457 	int status, error;
458 
459 	error = dowait4(q, SCARG(uap, pid),
460 	    SCARG(uap, status) ? &status : NULL,
461 	    SCARG(uap, options), SCARG(uap, rusage) ? &ru : NULL, retval);
462 	if (error == 0 && retval[0] > 0 && SCARG(uap, status)) {
463 		error = copyout(&status, SCARG(uap, status), sizeof(status));
464 	}
465 	if (error == 0 && retval[0] > 0 && SCARG(uap, rusage)) {
466 		error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
467 #ifdef KTRACE
468 		if (error == 0 && KTRPOINT(q, KTR_STRUCT))
469 			ktrrusage(q, &ru);
470 #endif
471 	}
472 	return (error);
473 }
474 
475 int
476 dowait4(struct proc *q, pid_t pid, int *statusp, int options,
477     struct rusage *rusage, register_t *retval)
478 {
479 	int nfound;
480 	struct process *pr;
481 	struct proc *p;
482 	int error;
483 
484 	if (pid == 0)
485 		pid = -q->p_p->ps_pgid;
486 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED))
487 		return (EINVAL);
488 
489 loop:
490 	nfound = 0;
491 	LIST_FOREACH(pr, &q->p_p->ps_children, ps_sibling) {
492 		if ((pr->ps_flags & PS_NOZOMBIE) ||
493 		    (pid != WAIT_ANY &&
494 		    pr->ps_pid != pid &&
495 		    pr->ps_pgid != -pid))
496 			continue;
497 
498 		p = pr->ps_mainproc;
499 
500 		nfound++;
501 		if (pr->ps_flags & PS_ZOMBIE) {
502 			retval[0] = pr->ps_pid;
503 
504 			if (statusp != NULL)
505 				*statusp = p->p_xstat;	/* convert to int */
506 			if (rusage != NULL)
507 				memcpy(rusage, pr->ps_ru, sizeof(*rusage));
508 			proc_finish_wait(q, p);
509 			return (0);
510 		}
511 		if (pr->ps_flags & PS_TRACED &&
512 		    (pr->ps_flags & PS_WAITED) == 0 && pr->ps_single &&
513 		    pr->ps_single->p_stat == SSTOP &&
514 		    (pr->ps_single->p_flag & P_SUSPSINGLE) == 0) {
515 			single_thread_wait(pr);
516 
517 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
518 			retval[0] = pr->ps_pid;
519 
520 			if (statusp != NULL)
521 				*statusp = W_STOPCODE(pr->ps_single->p_xstat);
522 			if (rusage != NULL)
523 				memset(rusage, 0, sizeof(*rusage));
524 			return (0);
525 		}
526 		if (p->p_stat == SSTOP &&
527 		    (pr->ps_flags & PS_WAITED) == 0 &&
528 		    (p->p_flag & P_SUSPSINGLE) == 0 &&
529 		    (pr->ps_flags & PS_TRACED ||
530 		    options & WUNTRACED)) {
531 			atomic_setbits_int(&pr->ps_flags, PS_WAITED);
532 			retval[0] = pr->ps_pid;
533 
534 			if (statusp != NULL)
535 				*statusp = W_STOPCODE(p->p_xstat);
536 			if (rusage != NULL)
537 				memset(rusage, 0, sizeof(*rusage));
538 			return (0);
539 		}
540 		if ((options & WCONTINUED) && (p->p_flag & P_CONTINUED)) {
541 			atomic_clearbits_int(&p->p_flag, P_CONTINUED);
542 			retval[0] = pr->ps_pid;
543 
544 			if (statusp != NULL)
545 				*statusp = _WCONTINUED;
546 			if (rusage != NULL)
547 				memset(rusage, 0, sizeof(*rusage));
548 			return (0);
549 		}
550 	}
551 	if (nfound == 0)
552 		return (ECHILD);
553 	if (options & WNOHANG) {
554 		retval[0] = 0;
555 		return (0);
556 	}
557 	if ((error = tsleep(q->p_p, PWAIT | PCATCH, "wait", 0)) != 0)
558 		return (error);
559 	goto loop;
560 }
561 
562 void
563 proc_finish_wait(struct proc *waiter, struct proc *p)
564 {
565 	struct process *pr, *tr;
566 	struct rusage *rup;
567 
568 	/*
569 	 * If we got the child via a ptrace 'attach',
570 	 * we need to give it back to the old parent.
571 	 */
572 	pr = p->p_p;
573 	if (pr->ps_oppid && (tr = prfind(pr->ps_oppid))) {
574 		atomic_clearbits_int(&pr->ps_flags, PS_TRACED);
575 		pr->ps_oppid = 0;
576 		proc_reparent(pr, tr);
577 		prsignal(tr, SIGCHLD);
578 		wakeup(tr);
579 	} else {
580 		scheduler_wait_hook(waiter, p);
581 		p->p_xstat = 0;
582 		rup = &waiter->p_p->ps_cru;
583 		ruadd(rup, pr->ps_ru);
584 		LIST_REMOVE(pr, ps_list);	/* off zombprocess */
585 		freepid(pr->ps_pid);
586 		process_zap(pr);
587 	}
588 }
589 
590 /*
591  * make process 'parent' the new parent of process 'child'.
592  */
593 void
594 proc_reparent(struct process *child, struct process *parent)
595 {
596 
597 	if (child->ps_pptr == parent)
598 		return;
599 
600 	LIST_REMOVE(child, ps_sibling);
601 	LIST_INSERT_HEAD(&parent->ps_children, child, ps_sibling);
602 	child->ps_pptr = parent;
603 }
604 
605 void
606 process_zap(struct process *pr)
607 {
608 	struct vnode *otvp;
609 	struct proc *p = pr->ps_mainproc;
610 
611 	/*
612 	 * Finally finished with old proc entry.
613 	 * Unlink it from its process group and free it.
614 	 */
615 	leavepgrp(pr);
616 	LIST_REMOVE(pr, ps_sibling);
617 
618 	/*
619 	 * Decrement the count of procs running with this uid.
620 	 */
621 	(void)chgproccnt(pr->ps_ucred->cr_ruid, -1);
622 
623 	/*
624 	 * Release reference to text vnode
625 	 */
626 	otvp = pr->ps_textvp;
627 	pr->ps_textvp = NULL;
628 	if (otvp)
629 		vrele(otvp);
630 
631 	KASSERT(pr->ps_refcnt == 1);
632 	if (pr->ps_ptstat != NULL)
633 		free(pr->ps_ptstat, M_SUBPROC, sizeof(*pr->ps_ptstat));
634 	pool_put(&rusage_pool, pr->ps_ru);
635 	KASSERT(TAILQ_EMPTY(&pr->ps_threads));
636 	limfree(pr->ps_limit);
637 	crfree(pr->ps_ucred);
638 	pool_put(&process_pool, pr);
639 	nprocesses--;
640 
641 	proc_free(p);
642 }
643