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