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