kern_exit.c revision 1.296 1 /* $NetBSD: kern_exit.c,v 1.296 2023/10/04 20:42:38 ad Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 1999, 2006, 2007, 2008, 2020, 2023
5 * The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
10 * NASA Ames Research Center, and by Andrew Doran.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 /*
35 * Copyright (c) 1982, 1986, 1989, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 * (c) UNIX System Laboratories, Inc.
38 * All or some portions of this file are derived from material licensed
39 * to the University of California by American Telephone and Telegraph
40 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41 * the permission of UNIX System Laboratories, Inc.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 *
67 * @(#)kern_exit.c 8.10 (Berkeley) 2/23/95
68 */
69
70 #include <sys/cdefs.h>
71 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.296 2023/10/04 20:42:38 ad Exp $");
72
73 #include "opt_ktrace.h"
74 #include "opt_dtrace.h"
75 #include "opt_sysv.h"
76
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/ioctl.h>
80 #include <sys/tty.h>
81 #include <sys/time.h>
82 #include <sys/resource.h>
83 #include <sys/kernel.h>
84 #include <sys/proc.h>
85 #include <sys/buf.h>
86 #include <sys/wait.h>
87 #include <sys/file.h>
88 #include <sys/fstrans.h>
89 #include <sys/vnode.h>
90 #include <sys/syslog.h>
91 #include <sys/pool.h>
92 #include <sys/uidinfo.h>
93 #include <sys/ptrace.h>
94 #include <sys/acct.h>
95 #include <sys/filedesc.h>
96 #include <sys/ras.h>
97 #include <sys/signalvar.h>
98 #include <sys/sched.h>
99 #include <sys/mount.h>
100 #include <sys/syscallargs.h>
101 #include <sys/kauth.h>
102 #include <sys/sleepq.h>
103 #include <sys/lock.h>
104 #include <sys/lockdebug.h>
105 #include <sys/ktrace.h>
106 #include <sys/cpu.h>
107 #include <sys/lwpctl.h>
108 #include <sys/atomic.h>
109 #include <sys/sdt.h>
110 #include <sys/psref.h>
111
112 #include <uvm/uvm_extern.h>
113
114 #ifdef DEBUG_EXIT
115 int debug_exit = 0;
116 #define DPRINTF(x) if (debug_exit) printf x
117 #else
118 #define DPRINTF(x)
119 #endif
120
121 static int find_stopped_child(struct proc *, idtype_t, id_t, int,
122 struct proc **, struct wrusage *, siginfo_t *);
123 static void proc_free(struct proc *, struct wrusage *);
124
125 /*
126 * DTrace SDT provider definitions
127 */
128 SDT_PROVIDER_DECLARE(proc);
129 SDT_PROBE_DEFINE1(proc, kernel, , exit, "int");
130
131 /*
132 * Fill in the appropriate signal information, and signal the parent.
133 */
134 /* XXX noclone works around a gcc 4.5 bug on arm */
135 static void __noclone
136 exit_psignal(struct proc *p, struct proc *pp, ksiginfo_t *ksi)
137 {
138
139 KSI_INIT(ksi);
140 if ((ksi->ksi_signo = P_EXITSIG(p)) == SIGCHLD) {
141 if (p->p_xsig) {
142 if (p->p_sflag & PS_COREDUMP)
143 ksi->ksi_code = CLD_DUMPED;
144 else
145 ksi->ksi_code = CLD_KILLED;
146 ksi->ksi_status = p->p_xsig;
147 } else {
148 ksi->ksi_code = CLD_EXITED;
149 ksi->ksi_status = p->p_xexit;
150 }
151 } else {
152 ksi->ksi_code = SI_USER;
153 ksi->ksi_status = p->p_xsig;
154 }
155 /*
156 * We fill those in, even for non-SIGCHLD.
157 * It's safe to access p->p_cred unlocked here.
158 */
159 ksi->ksi_pid = p->p_pid;
160 ksi->ksi_uid = kauth_cred_geteuid(p->p_cred);
161 /* XXX: is this still valid? */
162 ksi->ksi_utime = p->p_stats->p_ru.ru_utime.tv_sec;
163 ksi->ksi_stime = p->p_stats->p_ru.ru_stime.tv_sec;
164 }
165
166 /*
167 * exit --
168 * Death of process.
169 */
170 int
171 sys_exit(struct lwp *l, const struct sys_exit_args *uap, register_t *retval)
172 {
173 /* {
174 syscallarg(int) rval;
175 } */
176 struct proc *p = l->l_proc;
177
178 /* Don't call exit1() multiple times in the same process. */
179 mutex_enter(p->p_lock);
180 if (p->p_sflag & PS_WEXIT) {
181 mutex_exit(p->p_lock);
182 lwp_exit(l);
183 }
184
185 /* exit1() will release the mutex. */
186 exit1(l, SCARG(uap, rval), 0);
187 /* NOTREACHED */
188 return (0);
189 }
190
191 /*
192 * Exit: deallocate address space and other resources, change proc state
193 * to zombie, and unlink proc from allproc and parent's lists. Save exit
194 * status and rusage for wait(). Check for child processes and orphan them.
195 *
196 * Must be called with p->p_lock held. Does not return.
197 */
198 void
199 exit1(struct lwp *l, int exitcode, int signo)
200 {
201 struct proc *p, *child, *next_child, *old_parent, *new_parent;
202 struct pgrp *pgrp;
203 ksiginfo_t ksi;
204 ksiginfoq_t kq;
205 int wakeinit;
206
207 p = l->l_proc;
208
209 /* Verify that we hold no locks other than p->p_lock. */
210 LOCKDEBUG_BARRIER(p->p_lock, 0);
211
212 /* XXX Temporary: something is leaking kernel_lock. */
213 KERNEL_UNLOCK_ALL(l, NULL);
214
215 KASSERT(mutex_owned(p->p_lock));
216 KASSERT(p->p_vmspace != NULL);
217
218 if (__predict_false(p == initproc)) {
219 panic("init died (signal %d, exit %d)", signo, exitcode);
220 }
221
222 p->p_sflag |= PS_WEXIT;
223
224 /*
225 * Force all other LWPs to exit before we do. Only then can we
226 * begin to tear down the rest of the process state.
227 */
228 if (p->p_nlwps > 1) {
229 exit_lwps(l);
230 }
231
232 ksiginfo_queue_init(&kq);
233
234 /*
235 * If we have been asked to stop on exit, do so now.
236 */
237 if (__predict_false(p->p_sflag & PS_STOPEXIT)) {
238 KASSERT(l->l_blcnt == 0);
239 sigclearall(p, &contsigmask, &kq);
240
241 if (!mutex_tryenter(&proc_lock)) {
242 mutex_exit(p->p_lock);
243 mutex_enter(&proc_lock);
244 mutex_enter(p->p_lock);
245 }
246 p->p_waited = 0;
247 p->p_pptr->p_nstopchild++;
248 p->p_stat = SSTOP;
249 mutex_exit(&proc_lock);
250 lwp_lock(l);
251 p->p_nrlwps--;
252 l->l_stat = LSSTOP;
253 lwp_unlock(l);
254 mutex_exit(p->p_lock);
255 lwp_lock(l);
256 spc_lock(l->l_cpu);
257 mi_switch(l);
258 mutex_enter(p->p_lock);
259 }
260
261 /*
262 * Bin any remaining signals and mark the process as dying so it will
263 * not be found for, e.g. signals.
264 */
265 sigfillset(&p->p_sigctx.ps_sigignore);
266 sigclearall(p, NULL, &kq);
267 p->p_stat = SDYING;
268
269 /*
270 * Perform any required thread cleanup. Do this early so
271 * anyone wanting to look us up by our global thread ID
272 * will fail to find us.
273 *
274 * N.B. this will unlock p->p_lock on our behalf.
275 */
276 lwp_thread_cleanup(l);
277
278 ksiginfo_queue_drain(&kq);
279
280 /* Destroy any lwpctl info. */
281 if (p->p_lwpctl != NULL)
282 lwp_ctl_exit();
283
284 /*
285 * Drain all remaining references that procfs, ptrace and others may
286 * have on the process.
287 */
288 rw_enter(&p->p_reflock, RW_WRITER);
289
290 DPRINTF(("%s: %d.%d exiting.\n", __func__, p->p_pid, l->l_lid));
291
292 ptimers_free(p, TIMERS_ALL);
293 #if defined(__HAVE_RAS)
294 ras_purgeall();
295 #endif
296
297 /*
298 * Close open files, release open-file table and free signal
299 * actions. This may block!
300 */
301 fd_free();
302 cwdfree(p->p_cwdi);
303 p->p_cwdi = NULL;
304 doexithooks(p);
305 sigactsfree(p->p_sigacts);
306
307 /*
308 * Write out accounting data.
309 */
310 (void)acct_process(l);
311
312 #ifdef KTRACE
313 /*
314 * Release trace file.
315 */
316 if (p->p_tracep != NULL) {
317 mutex_enter(&ktrace_lock);
318 ktrderef(p);
319 mutex_exit(&ktrace_lock);
320 }
321 #endif
322
323 p->p_xexit = exitcode;
324 p->p_xsig = signo;
325
326 /*
327 * If emulation has process exit hook, call it now.
328 * Set the exit status now so that the exit hook has
329 * an opportunity to tweak it (COMPAT_LINUX requires
330 * this for thread group emulation)
331 */
332 if (p->p_emul->e_proc_exit)
333 (*p->p_emul->e_proc_exit)(p);
334
335 /*
336 * Free the VM resources we're still holding on to.
337 * We must do this from a valid thread because doing
338 * so may block. This frees vmspace, which we don't
339 * need anymore. The only remaining lwp is the one
340 * we run at this moment, nothing runs in userland
341 * anymore.
342 */
343 ruspace(p); /* Update our vm resource use */
344 uvm_proc_exit(p);
345
346 /*
347 * Stop profiling.
348 */
349 if (__predict_false((p->p_stflag & PST_PROFIL) != 0)) {
350 mutex_spin_enter(&p->p_stmutex);
351 stopprofclock(p);
352 mutex_spin_exit(&p->p_stmutex);
353 }
354
355 /*
356 * If parent is waiting for us to exit or exec, PL_PPWAIT is set; we
357 * wake up the parent early to avoid deadlock. We can do this once
358 * the VM resources are released.
359 */
360 mutex_enter(&proc_lock);
361 if (p->p_lflag & PL_PPWAIT) {
362 lwp_t *lp;
363
364 l->l_lwpctl = NULL; /* was on loan from blocked parent */
365 p->p_lflag &= ~PL_PPWAIT;
366
367 lp = p->p_vforklwp;
368 p->p_vforklwp = NULL;
369 lp->l_vforkwaiting = false;
370 cv_broadcast(&lp->l_waitcv);
371 }
372
373 if (SESS_LEADER(p)) {
374 struct vnode *vprele = NULL, *vprevoke = NULL;
375 struct session *sp = p->p_session;
376 struct tty *tp;
377
378 if (sp->s_ttyvp) {
379 /*
380 * Controlling process.
381 * Signal foreground pgrp,
382 * drain controlling terminal
383 * and revoke access to controlling terminal.
384 */
385 tp = sp->s_ttyp;
386 mutex_spin_enter(&tty_lock);
387 if (tp->t_session == sp) {
388 /* we can't guarantee the revoke will do this */
389 pgrp = tp->t_pgrp;
390 tp->t_pgrp = NULL;
391 tp->t_session = NULL;
392 mutex_spin_exit(&tty_lock);
393 if (pgrp != NULL) {
394 pgsignal(pgrp, SIGHUP, 1);
395 }
396 mutex_exit(&proc_lock);
397 (void) ttywait(tp);
398 mutex_enter(&proc_lock);
399
400 /* The tty could have been revoked. */
401 vprevoke = sp->s_ttyvp;
402 } else
403 mutex_spin_exit(&tty_lock);
404 vprele = sp->s_ttyvp;
405 sp->s_ttyvp = NULL;
406 /*
407 * s_ttyp is not zero'd; we use this to indicate
408 * that the session once had a controlling terminal.
409 * (for logging and informational purposes)
410 */
411 }
412 sp->s_leader = NULL;
413
414 if (vprevoke != NULL || vprele != NULL) {
415 if (vprevoke != NULL) {
416 /* Releases proc_lock. */
417 proc_sessrele(sp);
418 VOP_REVOKE(vprevoke, REVOKEALL);
419 } else
420 mutex_exit(&proc_lock);
421 if (vprele != NULL)
422 vrele(vprele);
423 mutex_enter(&proc_lock);
424 }
425 }
426 fixjobc(p, p->p_pgrp, 0);
427
428 /* Release fstrans private data. */
429 fstrans_lwp_dtor(l);
430
431 /*
432 * Finalize the last LWP's specificdata, as well as the
433 * specificdata for the proc itself.
434 */
435 lwp_finispecific(l);
436 proc_finispecific(p);
437
438 /*
439 * Reset p_opptr pointer of all former children which got
440 * traced by another process and were reparented. We reset
441 * it to NULL here; the trace detach code then reparents
442 * the child to initproc. We only check allproc list, since
443 * eventual former children on zombproc list won't reference
444 * p_opptr anymore.
445 */
446 if (__predict_false(p->p_slflag & PSL_CHTRACED)) {
447 struct proc *q;
448 PROCLIST_FOREACH(q, &allproc) {
449 if (q->p_opptr == p)
450 q->p_opptr = NULL;
451 }
452 PROCLIST_FOREACH(q, &zombproc) {
453 if (q->p_opptr == p)
454 q->p_opptr = NULL;
455 }
456 }
457
458 /*
459 * Give orphaned children to init(8).
460 */
461 child = LIST_FIRST(&p->p_children);
462 wakeinit = (child != NULL);
463 for (; child != NULL; child = next_child) {
464 next_child = LIST_NEXT(child, p_sibling);
465
466 /*
467 * Traced processes are killed since their existence
468 * means someone is screwing up. Since we reset the
469 * trace flags, the logic in sys_wait4() would not be
470 * triggered to reparent the process to its
471 * original parent, so we must do this here.
472 */
473 if (__predict_false(child->p_slflag & PSL_TRACED)) {
474 mutex_enter(p->p_lock);
475 child->p_slflag &=
476 ~(PSL_TRACED|PSL_SYSCALL);
477 mutex_exit(p->p_lock);
478 if (child->p_opptr != child->p_pptr) {
479 struct proc *t = child->p_opptr;
480 proc_reparent(child, t ? t : initproc);
481 child->p_opptr = NULL;
482 } else
483 proc_reparent(child, initproc);
484 killproc(child, "orphaned traced process");
485 } else
486 proc_reparent(child, initproc);
487 }
488
489 /*
490 * Move proc from allproc to zombproc, it's now nearly ready to be
491 * collected by parent.
492 */
493 LIST_REMOVE(l, l_list);
494 LIST_REMOVE(p, p_list);
495 LIST_INSERT_HEAD(&zombproc, p, p_list);
496
497 /*
498 * Mark the process as dead. We must do this before we signal
499 * the parent.
500 */
501 p->p_stat = SDEAD;
502
503 /*
504 * Let anyone watching this DTrace probe know what we're
505 * on our way out.
506 */
507 SDT_PROBE(proc, kernel, , exit,
508 ((p->p_sflag & PS_COREDUMP) ? CLD_DUMPED :
509 (p->p_xsig ? CLD_KILLED : CLD_EXITED)),
510 0,0,0,0);
511
512 /* Put in front of parent's sibling list for parent to collect it */
513 old_parent = p->p_pptr;
514 old_parent->p_nstopchild++;
515 if (LIST_FIRST(&old_parent->p_children) != p) {
516 /* Put child where it can be found quickly */
517 LIST_REMOVE(p, p_sibling);
518 LIST_INSERT_HEAD(&old_parent->p_children, p, p_sibling);
519 }
520
521 /*
522 * Notify parent that we're gone. If parent has the P_NOCLDWAIT
523 * flag set, notify init instead (and hope it will handle
524 * this situation).
525 */
526 if (old_parent->p_flag & (PK_NOCLDWAIT|PK_CLDSIGIGN)) {
527 proc_reparent(p, initproc);
528 wakeinit = 1;
529
530 /*
531 * If this was the last child of our parent, notify
532 * parent, so in case he was wait(2)ing, he will
533 * continue.
534 */
535 if (LIST_FIRST(&old_parent->p_children) == NULL)
536 cv_broadcast(&old_parent->p_waitcv);
537 }
538
539 /* Reload parent pointer, since p may have been reparented above */
540 new_parent = p->p_pptr;
541
542 if (__predict_false(p->p_exitsig != 0)) {
543 exit_psignal(p, new_parent, &ksi);
544 kpsignal(new_parent, &ksi, NULL);
545 }
546
547 /* Calculate the final rusage info. */
548 calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime,
549 NULL, NULL);
550
551 if (wakeinit)
552 cv_broadcast(&initproc->p_waitcv);
553
554 callout_destroy(&l->l_timeout_ch);
555
556 /*
557 * Release any PCU resources before becoming a zombie.
558 */
559 pcu_discard_all(l);
560
561 mutex_enter(p->p_lock);
562 /*
563 * Notify other processes tracking us with a knote that
564 * we're exiting.
565 *
566 * N.B. we do this here because the process is now SDEAD,
567 * and thus cannot have any more knotes attached. Also,
568 * knote_proc_exit() expects that p->p_lock is already
569 * held (and will assert so).
570 */
571 if (!SLIST_EMPTY(&p->p_klist)) {
572 knote_proc_exit(p);
573 }
574
575 /* Free the LWP ID */
576 proc_free_lwpid(p, l->l_lid);
577 lwp_drainrefs(l);
578 lwp_lock(l);
579 l->l_prflag &= ~LPR_DETACHED;
580 l->l_stat = LSZOMB;
581 lwp_unlock(l);
582 KASSERT(curlwp == l);
583 KASSERT(p->p_nrlwps == 1);
584 KASSERT(p->p_nlwps == 1);
585 p->p_stat = SZOMB;
586 p->p_nrlwps--;
587 p->p_nzlwps++;
588 p->p_ndlwps = 0;
589 mutex_exit(p->p_lock);
590
591 /*
592 * Signal the parent to collect us, and drop the proclist lock.
593 * Drop debugger/procfs lock; no new references can be gained.
594 */
595 cv_broadcast(&p->p_pptr->p_waitcv);
596 rw_exit(&p->p_reflock);
597 mutex_exit(&proc_lock);
598
599 /*
600 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
601 */
602
603 /*
604 * Give machine-dependent code a chance to free any MD LWP
605 * resources. This must be done before uvm_lwp_exit(), in
606 * case these resources are in the PCB.
607 */
608 cpu_lwp_free(l, 1);
609
610 /* Switch away into oblivion. */
611 lwp_lock(l);
612 spc_lock(l->l_cpu);
613 mi_switch(l);
614 panic("exit1");
615 }
616
617 void
618 exit_lwps(struct lwp *l)
619 {
620 proc_t *p = l->l_proc;
621 lwp_t *l2;
622
623 retry:
624 KASSERT(mutex_owned(p->p_lock));
625
626 /*
627 * Interrupt LWPs in interruptable sleep, unsuspend suspended
628 * LWPs and then wait for everyone else to finish.
629 */
630 LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
631 if (l2 == l)
632 continue;
633 lwp_lock(l2);
634 l2->l_flag |= LW_WEXIT;
635 lwp_need_userret(l2);
636 if ((l2->l_stat == LSSLEEP && (l2->l_flag & LW_SINTR)) ||
637 l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
638 l2->l_flag &= ~LW_DBGSUSPEND;
639 /* setrunnable() will release the lock. */
640 setrunnable(l2);
641 continue;
642 }
643 lwp_unlock(l2);
644 }
645
646 /*
647 * Wait for every LWP to exit. Note: LWPs can get suspended/slept
648 * behind us or there may even be new LWPs created. Therefore, a
649 * full retry is required on error.
650 */
651 while (p->p_nlwps > 1) {
652 if (lwp_wait(l, 0, NULL, true)) {
653 goto retry;
654 }
655 }
656
657 KASSERT(p->p_nlwps == 1);
658 }
659
660 int
661 do_sys_waitid(idtype_t idtype, id_t id, int *pid, int *status, int options,
662 struct wrusage *wru, siginfo_t *si)
663 {
664 proc_t *child;
665 int error;
666
667
668 if (wru != NULL)
669 memset(wru, 0, sizeof(*wru));
670 if (si != NULL)
671 memset(si, 0, sizeof(*si));
672
673 mutex_enter(&proc_lock);
674 error = find_stopped_child(curproc, idtype, id, options, &child,
675 wru, si);
676 if (child == NULL) {
677 mutex_exit(&proc_lock);
678 *pid = 0;
679 *status = 0;
680 return error;
681 }
682 *pid = child->p_pid;
683
684 if (child->p_stat == SZOMB) {
685 /* Child is exiting */
686 *status = P_WAITSTATUS(child);
687 /* proc_free() will release the proc_lock. */
688 if (options & WNOWAIT) {
689 mutex_exit(&proc_lock);
690 } else {
691 proc_free(child, wru);
692 }
693 } else {
694 /* Don't mark SIGCONT if we are being stopped */
695 *status = (child->p_xsig == SIGCONT && child->p_stat != SSTOP) ?
696 W_CONTCODE() : W_STOPCODE(child->p_xsig);
697 mutex_exit(&proc_lock);
698 }
699 return 0;
700 }
701
702 int
703 do_sys_wait(int *pid, int *status, int options, struct rusage *ru)
704 {
705 idtype_t idtype;
706 id_t id;
707 int ret;
708 struct wrusage wru;
709
710 /*
711 * Translate the special pid values into the (idtype, pid)
712 * pair for wait6. The WAIT_MYPGRP case is handled by
713 * find_stopped_child() on its own.
714 */
715 if (*pid == WAIT_ANY) {
716 idtype = P_ALL;
717 id = 0;
718 } else if (*pid < 0) {
719 idtype = P_PGID;
720 id = (id_t)-*pid;
721 } else {
722 idtype = P_PID;
723 id = (id_t)*pid;
724 }
725 options |= WEXITED | WTRAPPED;
726 ret = do_sys_waitid(idtype, id, pid, status, options, ru ? &wru : NULL,
727 NULL);
728 if (ru)
729 *ru = wru.wru_self;
730 return ret;
731 }
732
733 int
734 sys___wait450(struct lwp *l, const struct sys___wait450_args *uap,
735 register_t *retval)
736 {
737 /* {
738 syscallarg(int) pid;
739 syscallarg(int *) status;
740 syscallarg(int) options;
741 syscallarg(struct rusage *) rusage;
742 } */
743 int error, status, pid = SCARG(uap, pid);
744 struct rusage ru;
745
746 error = do_sys_wait(&pid, &status, SCARG(uap, options),
747 SCARG(uap, rusage) != NULL ? &ru : NULL);
748
749 retval[0] = pid;
750 if (pid == 0) {
751 return error;
752 }
753 if (SCARG(uap, status)) {
754 error = copyout(&status, SCARG(uap, status), sizeof(status));
755 }
756 if (SCARG(uap, rusage) && error == 0) {
757 error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
758 }
759 return error;
760 }
761
762 int
763 sys_wait6(struct lwp *l, const struct sys_wait6_args *uap, register_t *retval)
764 {
765 /* {
766 syscallarg(idtype_t) idtype;
767 syscallarg(id_t) id;
768 syscallarg(int *) status;
769 syscallarg(int) options;
770 syscallarg(struct wrusage *) wru;
771 syscallarg(siginfo_t *) si;
772 } */
773 struct wrusage wru, *wrup;
774 siginfo_t si, *sip;
775 idtype_t idtype;
776 int pid;
777 id_t id;
778 int error, status;
779
780 idtype = SCARG(uap, idtype);
781 id = SCARG(uap, id);
782
783 if (SCARG(uap, wru) != NULL)
784 wrup = &wru;
785 else
786 wrup = NULL;
787
788 if (SCARG(uap, info) != NULL)
789 sip = &si;
790 else
791 sip = NULL;
792
793 /*
794 * We expect all callers of wait6() to know about WEXITED and
795 * WTRAPPED.
796 */
797 error = do_sys_waitid(idtype, id, &pid, &status, SCARG(uap, options),
798 wrup, sip);
799
800 retval[0] = pid; /* tell userland who it was */
801
802 #if 0
803 /*
804 * should we copyout if there was no process, hence no useful data?
805 * We don't for an old style wait4() (etc) but I believe
806 * FreeBSD does for wait6(), so a tossup... Go with FreeBSD for now.
807 */
808 if (pid == 0)
809 return error;
810 #endif
811
812 if (SCARG(uap, status) != NULL && error == 0)
813 error = copyout(&status, SCARG(uap, status), sizeof(status));
814 if (SCARG(uap, wru) != NULL && error == 0)
815 error = copyout(&wru, SCARG(uap, wru), sizeof(wru));
816 if (SCARG(uap, info) != NULL && error == 0)
817 error = copyout(&si, SCARG(uap, info), sizeof(si));
818 return error;
819 }
820
821
822 /*
823 * Find a process that matches the provided criteria, and fill siginfo
824 * and resources if found.
825 * Returns:
826 * -1: Not found, abort early
827 * 0: Not matched
828 * 1: Matched, there might be more matches
829 * 2: This is the only match
830 */
831 static int
832 match_process(const struct proc *pp, struct proc **q, idtype_t idtype, id_t id,
833 int options, struct wrusage *wrusage, siginfo_t *siginfo)
834 {
835 struct rusage *rup;
836 struct proc *p = *q;
837 int rv = 1;
838
839 mutex_enter(p->p_lock);
840 switch (idtype) {
841 case P_ALL:
842 break;
843 case P_PID:
844 if (p->p_pid != (pid_t)id) {
845 mutex_exit(p->p_lock);
846 p = *q = proc_find_raw((pid_t)id);
847 if (p == NULL || p->p_stat == SIDL || p->p_pptr != pp) {
848 *q = NULL;
849 return -1;
850 }
851 mutex_enter(p->p_lock);
852 }
853 rv++;
854 break;
855 case P_PGID:
856 if (p->p_pgid != (pid_t)id)
857 goto out;
858 break;
859 case P_SID:
860 if (p->p_session->s_sid != (pid_t)id)
861 goto out;
862 break;
863 case P_UID:
864 if (kauth_cred_geteuid(p->p_cred) != (uid_t)id)
865 goto out;
866 break;
867 case P_GID:
868 if (kauth_cred_getegid(p->p_cred) != (gid_t)id)
869 goto out;
870 break;
871 case P_CID:
872 case P_PSETID:
873 case P_CPUID:
874 /* XXX: Implement me */
875 default:
876 out:
877 mutex_exit(p->p_lock);
878 return 0;
879 }
880
881 if ((options & WEXITED) == 0 && p->p_stat == SZOMB)
882 goto out;
883
884 if (siginfo != NULL) {
885 siginfo->si_errno = 0;
886
887 /*
888 * SUSv4 requires that the si_signo value is always
889 * SIGCHLD. Obey it despite the rfork(2) interface
890 * allows to request other signal for child exit
891 * notification.
892 */
893 siginfo->si_signo = SIGCHLD;
894
895 /*
896 * This is still a rough estimate. We will fix the
897 * cases TRAPPED, STOPPED, and CONTINUED later.
898 */
899 if (p->p_sflag & PS_COREDUMP) {
900 siginfo->si_code = CLD_DUMPED;
901 siginfo->si_status = p->p_xsig;
902 } else if (p->p_xsig) {
903 siginfo->si_code = CLD_KILLED;
904 siginfo->si_status = p->p_xsig;
905 } else {
906 siginfo->si_code = CLD_EXITED;
907 siginfo->si_status = p->p_xexit;
908 }
909
910 siginfo->si_pid = p->p_pid;
911 siginfo->si_uid = kauth_cred_geteuid(p->p_cred);
912 siginfo->si_utime = p->p_stats->p_ru.ru_utime.tv_sec;
913 siginfo->si_stime = p->p_stats->p_ru.ru_stime.tv_sec;
914 }
915
916 /*
917 * There should be no reason to limit resources usage info to
918 * exited processes only. A snapshot about any resources used
919 * by a stopped process may be exactly what is needed.
920 */
921 if (wrusage != NULL) {
922 rup = &wrusage->wru_self;
923 *rup = p->p_stats->p_ru;
924 calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
925
926 rup = &wrusage->wru_children;
927 *rup = p->p_stats->p_cru;
928 calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
929 }
930
931 mutex_exit(p->p_lock);
932 return rv;
933 }
934
935 /*
936 * Determine if there are existing processes being debugged
937 * that used to be (and sometime later will be again) children
938 * of a specific parent (while matching wait criteria)
939 */
940 static bool
941 debugged_child_exists(idtype_t idtype, id_t id, int options, siginfo_t *si,
942 const struct proc *parent)
943 {
944 struct proc *pp;
945
946 /*
947 * If we are searching for a specific pid, we can optimise a little
948 */
949 if (idtype == P_PID) {
950 /*
951 * Check the specific process to see if its real parent is us
952 */
953 pp = proc_find_raw((pid_t)id);
954 if (pp != NULL && pp->p_stat != SIDL && pp->p_opptr == parent) {
955 /*
956 * using P_ALL here avoids match_process() doing the
957 * same work that we just did, but incorrectly for
958 * this scenario.
959 */
960 if (match_process(parent, &pp, P_ALL, id, options,
961 NULL, si))
962 return true;
963 }
964 return false;
965 }
966
967 /*
968 * For the hard cases, just look everywhere to see if some
969 * stolen (reparented) process is really our lost child.
970 * Then check if that process could satisfy the wait conditions.
971 */
972
973 /*
974 * XXX inefficient, but hopefully fairly rare.
975 * XXX should really use a list of reparented processes.
976 */
977 PROCLIST_FOREACH(pp, &allproc) {
978 if (pp->p_stat == SIDL) /* XXX impossible ?? */
979 continue;
980 if (pp->p_opptr == parent &&
981 match_process(parent, &pp, idtype, id, options, NULL, si))
982 return true;
983 }
984 PROCLIST_FOREACH(pp, &zombproc) {
985 if (pp->p_stat == SIDL) /* XXX impossible ?? */
986 continue;
987 if (pp->p_opptr == parent &&
988 match_process(parent, &pp, idtype, id, options, NULL, si))
989 return true;
990 }
991
992 return false;
993 }
994
995 /*
996 * Scan list of child processes for a child process that has stopped or
997 * exited. Used by sys_wait4 and 'compat' equivalents.
998 *
999 * Must be called with the proc_lock held, and may release while waiting.
1000 */
1001 static int
1002 find_stopped_child(struct proc *parent, idtype_t idtype, id_t id, int options,
1003 struct proc **child_p, struct wrusage *wru, siginfo_t *si)
1004 {
1005 struct proc *child, *dead;
1006 int error;
1007
1008 KASSERT(mutex_owned(&proc_lock));
1009
1010 if (options & ~WALLOPTS) {
1011 *child_p = NULL;
1012 return EINVAL;
1013 }
1014
1015 if ((options & WSELECTOPTS) == 0) {
1016 /*
1017 * We will be unable to find any matching processes,
1018 * because there are no known events to look for.
1019 * Prefer to return error instead of blocking
1020 * indefinitely.
1021 */
1022 *child_p = NULL;
1023 return EINVAL;
1024 }
1025
1026 if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1027 mutex_enter(parent->p_lock);
1028 id = (id_t)parent->p_pgid;
1029 mutex_exit(parent->p_lock);
1030 idtype = P_PGID;
1031 }
1032
1033 for (;;) {
1034 error = ECHILD;
1035 dead = NULL;
1036
1037 LIST_FOREACH(child, &parent->p_children, p_sibling) {
1038 int rv = match_process(parent, &child, idtype, id,
1039 options, wru, si);
1040 if (rv == -1)
1041 break;
1042 if (rv == 0)
1043 continue;
1044
1045 /*
1046 * Wait for processes with p_exitsig != SIGCHLD
1047 * processes only if WALTSIG is set; wait for
1048 * processes with p_exitsig == SIGCHLD only
1049 * if WALTSIG is clear.
1050 */
1051 if (((options & WALLSIG) == 0) &&
1052 (options & WALTSIG ? child->p_exitsig == SIGCHLD
1053 : P_EXITSIG(child) != SIGCHLD)){
1054 if (rv == 2) {
1055 child = NULL;
1056 break;
1057 }
1058 continue;
1059 }
1060
1061 error = 0;
1062 if ((options & WNOZOMBIE) == 0) {
1063 if (child->p_stat == SZOMB)
1064 break;
1065 if (child->p_stat == SDEAD) {
1066 /*
1067 * We may occasionally arrive here
1068 * after receiving a signal, but
1069 * immediately before the child
1070 * process is zombified. The wait
1071 * will be short, so avoid returning
1072 * to userspace.
1073 */
1074 dead = child;
1075 }
1076 }
1077
1078 if ((options & WCONTINUED) != 0 &&
1079 child->p_xsig == SIGCONT &&
1080 (child->p_sflag & PS_CONTINUED)) {
1081 if ((options & WNOWAIT) == 0) {
1082 child->p_sflag &= ~PS_CONTINUED;
1083 child->p_waited = 1;
1084 parent->p_nstopchild--;
1085 }
1086 if (si) {
1087 si->si_status = child->p_xsig;
1088 si->si_code = CLD_CONTINUED;
1089 }
1090 break;
1091 }
1092
1093 if ((options & (WTRAPPED|WSTOPPED)) != 0 &&
1094 child->p_stat == SSTOP &&
1095 child->p_waited == 0 &&
1096 ((child->p_slflag & PSL_TRACED) ||
1097 options & (WUNTRACED|WSTOPPED))) {
1098 if ((options & WNOWAIT) == 0) {
1099 child->p_waited = 1;
1100 parent->p_nstopchild--;
1101 }
1102 if (si) {
1103 si->si_status = child->p_xsig;
1104 si->si_code =
1105 (child->p_slflag & PSL_TRACED) ?
1106 CLD_TRAPPED : CLD_STOPPED;
1107 }
1108 break;
1109 }
1110 if (parent->p_nstopchild == 0 || rv == 2) {
1111 child = NULL;
1112 break;
1113 }
1114 }
1115
1116 /*
1117 * If we found nothing, but we are the bereaved parent
1118 * of a stolen child, look and see if that child (or
1119 * one of them) meets our search criteria. If so, then
1120 * we cannot succeed, but we can hang (wait...),
1121 * or if WNOHANG, return 0 instead of ECHILD
1122 */
1123 if (child == NULL && error == ECHILD &&
1124 (parent->p_slflag & PSL_CHTRACED) &&
1125 debugged_child_exists(idtype, id, options, si, parent))
1126 error = 0;
1127
1128 if (child != NULL || error != 0 ||
1129 ((options & WNOHANG) != 0 && dead == NULL)) {
1130 *child_p = child;
1131 return error;
1132 }
1133
1134 /*
1135 * Wait for another child process to stop.
1136 */
1137 error = cv_wait_sig(&parent->p_waitcv, &proc_lock);
1138
1139 if (error != 0) {
1140 *child_p = NULL;
1141 return error;
1142 }
1143 }
1144 }
1145
1146 /*
1147 * Free a process after parent has taken all the state info. Must be called
1148 * with the proclist lock held, and will release before returning.
1149 *
1150 * *ru is returned to the caller, and must be freed by the caller.
1151 */
1152 static void
1153 proc_free(struct proc *p, struct wrusage *wru)
1154 {
1155 struct proc *parent = p->p_pptr;
1156 struct lwp *l;
1157 ksiginfo_t ksi;
1158 kauth_cred_t cred1, cred2;
1159 uid_t uid;
1160
1161 KASSERT(mutex_owned(&proc_lock));
1162 KASSERT(p->p_nlwps == 1);
1163 KASSERT(p->p_nzlwps == 1);
1164 KASSERT(p->p_nrlwps == 0);
1165 KASSERT(p->p_stat == SZOMB);
1166
1167 /*
1168 * If we got the child via ptrace(2) or procfs, and
1169 * the parent is different (meaning the process was
1170 * attached, rather than run as a child), then we need
1171 * to give it back to the old parent, and send the
1172 * parent the exit signal. The rest of the cleanup
1173 * will be done when the old parent waits on the child.
1174 */
1175 if ((p->p_slflag & PSL_TRACED) != 0 && p->p_opptr != parent) {
1176 mutex_enter(p->p_lock);
1177 p->p_slflag &= ~(PSL_TRACED|PSL_SYSCALL);
1178 mutex_exit(p->p_lock);
1179 parent = (p->p_opptr == NULL) ? initproc : p->p_opptr;
1180 proc_reparent(p, parent);
1181 p->p_opptr = NULL;
1182 if (p->p_exitsig != 0) {
1183 exit_psignal(p, parent, &ksi);
1184 kpsignal(parent, &ksi, NULL);
1185 }
1186 cv_broadcast(&parent->p_waitcv);
1187 mutex_exit(&proc_lock);
1188 return;
1189 }
1190
1191 sched_proc_exit(parent, p);
1192
1193 /*
1194 * Add child times of exiting process onto its own times.
1195 * This cannot be done any earlier else it might get done twice.
1196 */
1197 l = LIST_FIRST(&p->p_lwps);
1198 ruadd(&p->p_stats->p_ru, &l->l_ru);
1199 ruadd(&p->p_stats->p_ru, &p->p_stats->p_cru);
1200 ruadd(&parent->p_stats->p_cru, &p->p_stats->p_ru);
1201 if (wru != NULL) {
1202 wru->wru_self = p->p_stats->p_ru;
1203 wru->wru_children = p->p_stats->p_cru;
1204 }
1205 p->p_xsig = 0;
1206 p->p_xexit = 0;
1207
1208 /*
1209 * At this point we are going to start freeing the final resources.
1210 * If anyone tries to access the proc structure after here they will
1211 * get a shock - bits are missing. Attempt to make it hard! We
1212 * don't bother with any further locking past this point.
1213 */
1214 p->p_stat = SIDL; /* not even a zombie any more */
1215 LIST_REMOVE(p, p_list); /* off zombproc */
1216 parent->p_nstopchild--;
1217 LIST_REMOVE(p, p_sibling);
1218
1219 /*
1220 * Let pid be reallocated.
1221 */
1222 proc_free_pid(p->p_pid);
1223 atomic_dec_uint(&nprocs);
1224
1225 /*
1226 * Unlink process from its process group.
1227 * Releases the proc_lock.
1228 */
1229 proc_leavepgrp(p);
1230
1231 /*
1232 * Delay release until after lwp_free.
1233 */
1234 cred2 = l->l_cred;
1235
1236 /*
1237 * Free the last LWP's resources.
1238 *
1239 * lwp_free ensures the LWP is no longer running on another CPU.
1240 */
1241 lwp_free(l, false, true);
1242
1243 /*
1244 * Now no one except us can reach the process p.
1245 */
1246
1247 /*
1248 * Decrement the count of procs running with this uid.
1249 */
1250 cred1 = p->p_cred;
1251 uid = kauth_cred_getuid(cred1);
1252 (void)chgproccnt(uid, -1);
1253
1254 /*
1255 * Release substructures.
1256 */
1257
1258 lim_free(p->p_limit);
1259 pstatsfree(p->p_stats);
1260 kauth_cred_free(cred1);
1261 kauth_cred_free(cred2);
1262
1263 /*
1264 * Release reference to text vnode
1265 */
1266 if (p->p_textvp)
1267 vrele(p->p_textvp);
1268 kmem_strfree(p->p_path);
1269
1270 mutex_destroy(&p->p_auxlock);
1271 mutex_obj_free(p->p_lock);
1272 mutex_destroy(&p->p_stmutex);
1273 cv_destroy(&p->p_waitcv);
1274 cv_destroy(&p->p_lwpcv);
1275 rw_destroy(&p->p_reflock);
1276
1277 proc_free_mem(p);
1278 }
1279
1280 /*
1281 * Change the parent of a process for tracing purposes.
1282 */
1283 void
1284 proc_changeparent(struct proc *t, struct proc *p)
1285 {
1286 SET(t->p_slflag, PSL_TRACED);
1287 t->p_opptr = t->p_pptr;
1288 if (t->p_pptr == p)
1289 return;
1290 struct proc *parent = t->p_pptr;
1291
1292 if (parent->p_lock < t->p_lock) {
1293 if (!mutex_tryenter(parent->p_lock)) {
1294 mutex_exit(t->p_lock);
1295 mutex_enter(parent->p_lock);
1296 mutex_enter(t->p_lock);
1297 }
1298 } else if (parent->p_lock > t->p_lock) {
1299 mutex_enter(parent->p_lock);
1300 }
1301 parent->p_slflag |= PSL_CHTRACED;
1302 proc_reparent(t, p);
1303 if (parent->p_lock != t->p_lock)
1304 mutex_exit(parent->p_lock);
1305 }
1306
1307 /*
1308 * make process 'parent' the new parent of process 'child'.
1309 *
1310 * Must be called with proc_lock held.
1311 */
1312 void
1313 proc_reparent(struct proc *child, struct proc *parent)
1314 {
1315
1316 KASSERT(mutex_owned(&proc_lock));
1317
1318 if (child->p_pptr == parent)
1319 return;
1320
1321 if (child->p_stat == SZOMB || child->p_stat == SDEAD ||
1322 (child->p_stat == SSTOP && !child->p_waited)) {
1323 child->p_pptr->p_nstopchild--;
1324 parent->p_nstopchild++;
1325 }
1326 if (parent == initproc) {
1327 child->p_exitsig = SIGCHLD;
1328 child->p_ppid = parent->p_pid;
1329 }
1330
1331 LIST_REMOVE(child, p_sibling);
1332 LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1333 child->p_pptr = parent;
1334 }
1335