xref: /openbsd-src/sys/kern/kern_sig.c (revision 0c9ac8635e8d83339c39049dbcd3e482fb06a631)
1 /*	$OpenBSD: kern_sig.c,v 1.353 2024/12/17 14:45:00 claudio Exp $	*/
2 /*	$NetBSD: kern_sig.c,v 1.54 1996/04/22 01:38:32 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1997 Theo de Raadt. All rights reserved.
6  * Copyright (c) 1982, 1986, 1989, 1991, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
39  */
40 
41 #include <sys/param.h>
42 #include <sys/signalvar.h>
43 #include <sys/queue.h>
44 #include <sys/namei.h>
45 #include <sys/vnode.h>
46 #include <sys/event.h>
47 #include <sys/proc.h>
48 #include <sys/systm.h>
49 #include <sys/acct.h>
50 #include <sys/fcntl.h>
51 #include <sys/filedesc.h>
52 #include <sys/wait.h>
53 #include <sys/ktrace.h>
54 #include <sys/stat.h>
55 #include <sys/malloc.h>
56 #include <sys/pool.h>
57 #include <sys/sched.h>
58 #include <sys/user.h>
59 #include <sys/syslog.h>
60 #include <sys/ttycom.h>
61 #include <sys/pledge.h>
62 #include <sys/witness.h>
63 #include <sys/exec_elf.h>
64 
65 #include <sys/mount.h>
66 #include <sys/syscallargs.h>
67 
68 #include <uvm/uvm_extern.h>
69 #include <machine/tcb.h>
70 
71 int nosuidcoredump = 1;
72 
73 /*
74  * The array below categorizes the signals and their default actions.
75  */
76 const int sigprop[NSIG] = {
77 	0,			/* unused */
78 	SA_KILL,		/* SIGHUP */
79 	SA_KILL,		/* SIGINT */
80 	SA_KILL|SA_CORE,	/* SIGQUIT */
81 	SA_KILL|SA_CORE,	/* SIGILL */
82 	SA_KILL|SA_CORE,	/* SIGTRAP */
83 	SA_KILL|SA_CORE,	/* SIGABRT */
84 	SA_KILL|SA_CORE,	/* SIGEMT */
85 	SA_KILL|SA_CORE,	/* SIGFPE */
86 	SA_KILL,		/* SIGKILL */
87 	SA_KILL|SA_CORE,	/* SIGBUS */
88 	SA_KILL|SA_CORE,	/* SIGSEGV */
89 	SA_KILL|SA_CORE,	/* SIGSYS */
90 	SA_KILL,		/* SIGPIPE */
91 	SA_KILL,		/* SIGALRM */
92 	SA_KILL,		/* SIGTERM */
93 	SA_IGNORE,		/* SIGURG */
94 	SA_STOP,		/* SIGSTOP */
95 	SA_STOP|SA_TTYSTOP,	/* SIGTSTP */
96 	SA_IGNORE|SA_CONT,	/* SIGCONT */
97 	SA_IGNORE,		/* SIGCHLD */
98 	SA_STOP|SA_TTYSTOP,	/* SIGTTIN */
99 	SA_STOP|SA_TTYSTOP,	/* SIGTTOU */
100 	SA_IGNORE,		/* SIGIO */
101 	SA_KILL,		/* SIGXCPU */
102 	SA_KILL,		/* SIGXFSZ */
103 	SA_KILL,		/* SIGVTALRM */
104 	SA_KILL,		/* SIGPROF */
105 	SA_IGNORE,		/* SIGWINCH  */
106 	SA_IGNORE,		/* SIGINFO */
107 	SA_KILL,		/* SIGUSR1 */
108 	SA_KILL,		/* SIGUSR2 */
109 	SA_IGNORE,		/* SIGTHR */
110 };
111 
112 #define	CONTSIGMASK	(sigmask(SIGCONT))
113 #define	STOPSIGMASK	(sigmask(SIGSTOP) | sigmask(SIGTSTP) | \
114 			    sigmask(SIGTTIN) | sigmask(SIGTTOU))
115 
116 void setsigvec(struct proc *, int, struct sigaction *);
117 
118 int proc_trap(struct proc *, int);
119 void proc_stop(struct proc *p, int);
120 void proc_stop_sweep(void *);
121 void *proc_stop_si;
122 
123 void setsigctx(struct proc *, int, struct sigctx *);
124 void postsig_done(struct proc *, int, sigset_t, int);
125 void postsig(struct proc *, int, struct sigctx *);
126 int cansignal(struct proc *, struct process *, int);
127 
128 void ptsignal_locked(struct proc *, int, enum signal_type);
129 
130 struct pool sigacts_pool;	/* memory pool for sigacts structures */
131 
132 void sigio_del(struct sigiolst *);
133 void sigio_unlink(struct sigio_ref *, struct sigiolst *);
134 struct mutex sigio_lock = MUTEX_INITIALIZER(IPL_HIGH);
135 
136 /*
137  * Can thread p, send the signal signum to process qr?
138  */
139 int
140 cansignal(struct proc *p, struct process *qr, int signum)
141 {
142 	struct process *pr = p->p_p;
143 	struct ucred *uc = p->p_ucred;
144 	struct ucred *quc = qr->ps_ucred;
145 
146 	if (uc->cr_uid == 0)
147 		return (1);		/* root can always signal */
148 
149 	if (pr == qr)
150 		return (1);		/* process can always signal itself */
151 
152 	/* optimization: if the same creds then the tests below will pass */
153 	if (uc == quc)
154 		return (1);
155 
156 	if (signum == SIGCONT && qr->ps_session == pr->ps_session)
157 		return (1);		/* SIGCONT in session */
158 
159 	/*
160 	 * Using kill(), only certain signals can be sent to setugid
161 	 * child processes
162 	 */
163 	if (qr->ps_flags & PS_SUGID) {
164 		switch (signum) {
165 		case 0:
166 		case SIGKILL:
167 		case SIGINT:
168 		case SIGTERM:
169 		case SIGALRM:
170 		case SIGSTOP:
171 		case SIGTTIN:
172 		case SIGTTOU:
173 		case SIGTSTP:
174 		case SIGHUP:
175 		case SIGUSR1:
176 		case SIGUSR2:
177 			if (uc->cr_ruid == quc->cr_ruid ||
178 			    uc->cr_uid == quc->cr_ruid)
179 				return (1);
180 		}
181 		return (0);
182 	}
183 
184 	if (uc->cr_ruid == quc->cr_ruid ||
185 	    uc->cr_ruid == quc->cr_svuid ||
186 	    uc->cr_uid == quc->cr_ruid ||
187 	    uc->cr_uid == quc->cr_svuid)
188 		return (1);
189 	return (0);
190 }
191 
192 /*
193  * Initialize signal-related data structures.
194  */
195 void
196 signal_init(void)
197 {
198 	proc_stop_si = softintr_establish(IPL_SOFTCLOCK, proc_stop_sweep,
199 	    NULL);
200 	if (proc_stop_si == NULL)
201 		panic("signal_init failed to register softintr");
202 
203 	pool_init(&sigacts_pool, sizeof(struct sigacts), 0, IPL_NONE,
204 	    PR_WAITOK, "sigapl", NULL);
205 }
206 
207 /*
208  * Initialize a new sigaltstack structure.
209  */
210 void
211 sigstkinit(struct sigaltstack *ss)
212 {
213 	ss->ss_flags = SS_DISABLE;
214 	ss->ss_size = 0;
215 	ss->ss_sp = NULL;
216 }
217 
218 /*
219  * Create an initial sigacts structure, using the same signal state
220  * as pr.
221  */
222 struct sigacts *
223 sigactsinit(struct process *pr)
224 {
225 	struct sigacts *ps;
226 
227 	ps = pool_get(&sigacts_pool, PR_WAITOK);
228 	memcpy(ps, pr->ps_sigacts, sizeof(struct sigacts));
229 	return (ps);
230 }
231 
232 /*
233  * Release a sigacts structure.
234  */
235 void
236 sigactsfree(struct sigacts *ps)
237 {
238 	pool_put(&sigacts_pool, ps);
239 }
240 
241 int
242 sys_sigaction(struct proc *p, void *v, register_t *retval)
243 {
244 	struct sys_sigaction_args /* {
245 		syscallarg(int) signum;
246 		syscallarg(const struct sigaction *) nsa;
247 		syscallarg(struct sigaction *) osa;
248 	} */ *uap = v;
249 	struct sigaction vec;
250 #ifdef KTRACE
251 	struct sigaction ovec;
252 #endif
253 	struct sigaction *sa;
254 	const struct sigaction *nsa;
255 	struct sigaction *osa;
256 	struct sigacts *ps = p->p_p->ps_sigacts;
257 	int signum;
258 	int bit, error;
259 
260 	signum = SCARG(uap, signum);
261 	nsa = SCARG(uap, nsa);
262 	osa = SCARG(uap, osa);
263 
264 	if (signum <= 0 || signum >= NSIG ||
265 	    (nsa && (signum == SIGKILL || signum == SIGSTOP)))
266 		return (EINVAL);
267 	sa = &vec;
268 	if (osa) {
269 		mtx_enter(&p->p_p->ps_mtx);
270 		sa->sa_handler = ps->ps_sigact[signum];
271 		sa->sa_mask = ps->ps_catchmask[signum];
272 		bit = sigmask(signum);
273 		sa->sa_flags = 0;
274 		if ((ps->ps_sigonstack & bit) != 0)
275 			sa->sa_flags |= SA_ONSTACK;
276 		if ((ps->ps_sigintr & bit) == 0)
277 			sa->sa_flags |= SA_RESTART;
278 		if ((ps->ps_sigreset & bit) != 0)
279 			sa->sa_flags |= SA_RESETHAND;
280 		if ((ps->ps_siginfo & bit) != 0)
281 			sa->sa_flags |= SA_SIGINFO;
282 		if (signum == SIGCHLD) {
283 			if ((ps->ps_sigflags & SAS_NOCLDSTOP) != 0)
284 				sa->sa_flags |= SA_NOCLDSTOP;
285 			if ((ps->ps_sigflags & SAS_NOCLDWAIT) != 0)
286 				sa->sa_flags |= SA_NOCLDWAIT;
287 		}
288 		mtx_leave(&p->p_p->ps_mtx);
289 		if ((sa->sa_mask & bit) == 0)
290 			sa->sa_flags |= SA_NODEFER;
291 		sa->sa_mask &= ~bit;
292 		error = copyout(sa, osa, sizeof (vec));
293 		if (error)
294 			return (error);
295 #ifdef KTRACE
296 		if (KTRPOINT(p, KTR_STRUCT))
297 			ovec = vec;
298 #endif
299 	}
300 	if (nsa) {
301 		error = copyin(nsa, sa, sizeof (vec));
302 		if (error)
303 			return (error);
304 #ifdef KTRACE
305 		if (KTRPOINT(p, KTR_STRUCT))
306 			ktrsigaction(p, sa);
307 #endif
308 		setsigvec(p, signum, sa);
309 	}
310 #ifdef KTRACE
311 	if (osa && KTRPOINT(p, KTR_STRUCT))
312 		ktrsigaction(p, &ovec);
313 #endif
314 	return (0);
315 }
316 
317 void
318 setsigvec(struct proc *p, int signum, struct sigaction *sa)
319 {
320 	struct sigacts *ps = p->p_p->ps_sigacts;
321 	int bit;
322 
323 	bit = sigmask(signum);
324 
325 	mtx_enter(&p->p_p->ps_mtx);
326 	ps->ps_sigact[signum] = sa->sa_handler;
327 	if ((sa->sa_flags & SA_NODEFER) == 0)
328 		sa->sa_mask |= sigmask(signum);
329 	ps->ps_catchmask[signum] = sa->sa_mask &~ sigcantmask;
330 	if (signum == SIGCHLD) {
331 		if (sa->sa_flags & SA_NOCLDSTOP)
332 			atomic_setbits_int(&ps->ps_sigflags, SAS_NOCLDSTOP);
333 		else
334 			atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDSTOP);
335 		/*
336 		 * If the SA_NOCLDWAIT flag is set or the handler
337 		 * is SIG_IGN we reparent the dying child to PID 1
338 		 * (init) which will reap the zombie.  Because we use
339 		 * init to do our dirty work we never set SAS_NOCLDWAIT
340 		 * for PID 1.
341 		 * XXX exit1 rework means this is unnecessary?
342 		 */
343 		if (initprocess->ps_sigacts != ps &&
344 		    ((sa->sa_flags & SA_NOCLDWAIT) ||
345 		    sa->sa_handler == SIG_IGN))
346 			atomic_setbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
347 		else
348 			atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
349 	}
350 	if ((sa->sa_flags & SA_RESETHAND) != 0)
351 		ps->ps_sigreset |= bit;
352 	else
353 		ps->ps_sigreset &= ~bit;
354 	if ((sa->sa_flags & SA_SIGINFO) != 0)
355 		ps->ps_siginfo |= bit;
356 	else
357 		ps->ps_siginfo &= ~bit;
358 	if ((sa->sa_flags & SA_RESTART) == 0)
359 		ps->ps_sigintr |= bit;
360 	else
361 		ps->ps_sigintr &= ~bit;
362 	if ((sa->sa_flags & SA_ONSTACK) != 0)
363 		ps->ps_sigonstack |= bit;
364 	else
365 		ps->ps_sigonstack &= ~bit;
366 	/*
367 	 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
368 	 * and for signals set to SIG_DFL where the default is to ignore.
369 	 * However, don't put SIGCONT in ps_sigignore,
370 	 * as we have to restart the process.
371 	 */
372 	if (sa->sa_handler == SIG_IGN ||
373 	    (sigprop[signum] & SA_IGNORE && sa->sa_handler == SIG_DFL)) {
374 		atomic_clearbits_int(&p->p_siglist, bit);
375 		atomic_clearbits_int(&p->p_p->ps_siglist, bit);
376 		if (signum != SIGCONT)
377 			ps->ps_sigignore |= bit;	/* easier in psignal */
378 		ps->ps_sigcatch &= ~bit;
379 	} else {
380 		ps->ps_sigignore &= ~bit;
381 		if (sa->sa_handler == SIG_DFL)
382 			ps->ps_sigcatch &= ~bit;
383 		else
384 			ps->ps_sigcatch |= bit;
385 	}
386 	mtx_leave(&p->p_p->ps_mtx);
387 }
388 
389 /*
390  * Initialize signal state for process 0;
391  * set to ignore signals that are ignored by default.
392  */
393 void
394 siginit(struct sigacts *ps)
395 {
396 	int i;
397 
398 	for (i = 0; i < NSIG; i++)
399 		if (sigprop[i] & SA_IGNORE && i != SIGCONT)
400 			ps->ps_sigignore |= sigmask(i);
401 	ps->ps_sigflags = SAS_NOCLDWAIT | SAS_NOCLDSTOP;
402 }
403 
404 /*
405  * Reset signals for an exec by the specified thread.
406  */
407 void
408 execsigs(struct proc *p)
409 {
410 	struct sigacts *ps;
411 	int nc, mask;
412 
413 	ps = p->p_p->ps_sigacts;
414 	mtx_enter(&p->p_p->ps_mtx);
415 
416 	/*
417 	 * Reset caught signals.  Held signals remain held
418 	 * through p_sigmask (unless they were caught,
419 	 * and are now ignored by default).
420 	 */
421 	while (ps->ps_sigcatch) {
422 		nc = ffs((long)ps->ps_sigcatch);
423 		mask = sigmask(nc);
424 		ps->ps_sigcatch &= ~mask;
425 		if (sigprop[nc] & SA_IGNORE) {
426 			if (nc != SIGCONT)
427 				ps->ps_sigignore |= mask;
428 			atomic_clearbits_int(&p->p_siglist, mask);
429 			atomic_clearbits_int(&p->p_p->ps_siglist, mask);
430 		}
431 		ps->ps_sigact[nc] = SIG_DFL;
432 	}
433 	/*
434 	 * Reset stack state to the user stack.
435 	 * Clear set of signals caught on the signal stack.
436 	 */
437 	sigstkinit(&p->p_sigstk);
438 	atomic_clearbits_int(&ps->ps_sigflags, SAS_NOCLDWAIT);
439 	if (ps->ps_sigact[SIGCHLD] == SIG_IGN)
440 		ps->ps_sigact[SIGCHLD] = SIG_DFL;
441 	mtx_leave(&p->p_p->ps_mtx);
442 }
443 
444 /*
445  * Manipulate signal mask.
446  * Note that we receive new mask, not pointer,
447  * and return old mask as return value;
448  * the library stub does the rest.
449  */
450 int
451 sys_sigprocmask(struct proc *p, void *v, register_t *retval)
452 {
453 	struct sys_sigprocmask_args /* {
454 		syscallarg(int) how;
455 		syscallarg(sigset_t) mask;
456 	} */ *uap = v;
457 	int error = 0;
458 	sigset_t mask;
459 
460 	KASSERT(p == curproc);
461 
462 	*retval = p->p_sigmask;
463 	mask = SCARG(uap, mask) &~ sigcantmask;
464 
465 	switch (SCARG(uap, how)) {
466 	case SIG_BLOCK:
467 		SET(p->p_sigmask, mask);
468 		break;
469 	case SIG_UNBLOCK:
470 		CLR(p->p_sigmask, mask);
471 		break;
472 	case SIG_SETMASK:
473 		p->p_sigmask = mask;
474 		break;
475 	default:
476 		error = EINVAL;
477 		break;
478 	}
479 	return (error);
480 }
481 
482 int
483 sys_sigpending(struct proc *p, void *v, register_t *retval)
484 {
485 	*retval = p->p_siglist | p->p_p->ps_siglist;
486 	return (0);
487 }
488 
489 /*
490  * Temporarily replace calling proc's signal mask for the duration of a
491  * system call.  Original signal mask will be restored by userret().
492  */
493 void
494 dosigsuspend(struct proc *p, sigset_t newmask)
495 {
496 	KASSERT(p == curproc);
497 
498 	p->p_oldmask = p->p_sigmask;
499 	p->p_sigmask = newmask;
500 	atomic_setbits_int(&p->p_flag, P_SIGSUSPEND);
501 }
502 
503 /*
504  * Suspend thread until signal, providing mask to be set
505  * in the meantime.  Note nonstandard calling convention:
506  * libc stub passes mask, not pointer, to save a copyin.
507  */
508 int
509 sys_sigsuspend(struct proc *p, void *v, register_t *retval)
510 {
511 	struct sys_sigsuspend_args /* {
512 		syscallarg(int) mask;
513 	} */ *uap = v;
514 
515 	dosigsuspend(p, SCARG(uap, mask) &~ sigcantmask);
516 	while (tsleep_nsec(&nowake, PPAUSE|PCATCH, "sigsusp", INFSLP) == 0)
517 		continue;
518 	/* always return EINTR rather than ERESTART... */
519 	return (EINTR);
520 }
521 
522 int
523 sigonstack(size_t stack)
524 {
525 	const struct sigaltstack *ss = &curproc->p_sigstk;
526 
527 	return (ss->ss_flags & SS_DISABLE ? 0 :
528 	    (stack - (size_t)ss->ss_sp < ss->ss_size));
529 }
530 
531 int
532 sys_sigaltstack(struct proc *p, void *v, register_t *retval)
533 {
534 	struct sys_sigaltstack_args /* {
535 		syscallarg(const struct sigaltstack *) nss;
536 		syscallarg(struct sigaltstack *) oss;
537 	} */ *uap = v;
538 	struct sigaltstack ss;
539 	const struct sigaltstack *nss;
540 	struct sigaltstack *oss;
541 	int onstack = sigonstack(PROC_STACK(p));
542 	int error;
543 
544 	nss = SCARG(uap, nss);
545 	oss = SCARG(uap, oss);
546 
547 	if (oss != NULL) {
548 		ss = p->p_sigstk;
549 		if (onstack)
550 			ss.ss_flags |= SS_ONSTACK;
551 		if ((error = copyout(&ss, oss, sizeof(ss))))
552 			return (error);
553 	}
554 	if (nss == NULL)
555 		return (0);
556 	error = copyin(nss, &ss, sizeof(ss));
557 	if (error)
558 		return (error);
559 	if (onstack)
560 		return (EPERM);
561 	if (ss.ss_flags & ~SS_DISABLE)
562 		return (EINVAL);
563 	if (ss.ss_flags & SS_DISABLE) {
564 		p->p_sigstk.ss_flags = ss.ss_flags;
565 		return (0);
566 	}
567 	if (ss.ss_size < MINSIGSTKSZ)
568 		return (ENOMEM);
569 
570 	error = uvm_map_remap_as_stack(p, (vaddr_t)ss.ss_sp, ss.ss_size);
571 	if (error)
572 		return (error);
573 
574 	p->p_sigstk = ss;
575 	return (0);
576 }
577 
578 int
579 sys_kill(struct proc *cp, void *v, register_t *retval)
580 {
581 	struct sys_kill_args /* {
582 		syscallarg(int) pid;
583 		syscallarg(int) signum;
584 	} */ *uap = v;
585 	struct process *pr;
586 	int pid = SCARG(uap, pid);
587 	int signum = SCARG(uap, signum);
588 	int error;
589 	int zombie = 0;
590 
591 	if ((error = pledge_kill(cp, pid)) != 0)
592 		return (error);
593 	if (((u_int)signum) >= NSIG)
594 		return (EINVAL);
595 	if (pid > 0) {
596 		if ((pr = prfind(pid)) == NULL) {
597 			if ((pr = zombiefind(pid)) == NULL)
598 				return (ESRCH);
599 			else
600 				zombie = 1;
601 		}
602 		if (!cansignal(cp, pr, signum))
603 			return (EPERM);
604 
605 		/* kill single process */
606 		if (signum && !zombie)
607 			prsignal(pr, signum);
608 		return (0);
609 	}
610 	switch (pid) {
611 	case -1:		/* broadcast signal */
612 		return (killpg1(cp, signum, 0, 1));
613 	case 0:			/* signal own process group */
614 		return (killpg1(cp, signum, 0, 0));
615 	default:		/* negative explicit process group */
616 		return (killpg1(cp, signum, -pid, 0));
617 	}
618 }
619 
620 int
621 sys_thrkill(struct proc *cp, void *v, register_t *retval)
622 {
623 	struct sys_thrkill_args /* {
624 		syscallarg(pid_t) tid;
625 		syscallarg(int) signum;
626 		syscallarg(void *) tcb;
627 	} */ *uap = v;
628 	struct proc *p;
629 	int tid = SCARG(uap, tid);
630 	int signum = SCARG(uap, signum);
631 	void *tcb;
632 
633 	if (((u_int)signum) >= NSIG)
634 		return (EINVAL);
635 
636 	p = tid ? tfind_user(tid, cp->p_p) : cp;
637 	if (p == NULL)
638 		return (ESRCH);
639 
640 	/* optionally require the target thread to have the given tcb addr */
641 	tcb = SCARG(uap, tcb);
642 	if (tcb != NULL && tcb != TCB_GET(p))
643 		return (ESRCH);
644 
645 	if (signum)
646 		ptsignal(p, signum, STHREAD);
647 	return (0);
648 }
649 
650 /*
651  * Common code for kill process group/broadcast kill.
652  * cp is calling process.
653  */
654 int
655 killpg1(struct proc *cp, int signum, int pgid, int all)
656 {
657 	struct process *pr;
658 	struct pgrp *pgrp;
659 	int nfound = 0;
660 
661 	if (all) {
662 		/*
663 		 * broadcast
664 		 */
665 		LIST_FOREACH(pr, &allprocess, ps_list) {
666 			if (pr->ps_pid <= 1 ||
667 			    pr->ps_flags & (PS_SYSTEM | PS_NOBROADCASTKILL) ||
668 			    pr == cp->p_p || !cansignal(cp, pr, signum))
669 				continue;
670 			nfound++;
671 			if (signum)
672 				prsignal(pr, signum);
673 		}
674 	} else {
675 		if (pgid == 0)
676 			/*
677 			 * zero pgid means send to my process group.
678 			 */
679 			pgrp = cp->p_p->ps_pgrp;
680 		else {
681 			pgrp = pgfind(pgid);
682 			if (pgrp == NULL)
683 				return (ESRCH);
684 		}
685 		LIST_FOREACH(pr, &pgrp->pg_members, ps_pglist) {
686 			if (pr->ps_pid <= 1 || pr->ps_flags & PS_SYSTEM ||
687 			    !cansignal(cp, pr, signum))
688 				continue;
689 			nfound++;
690 			if (signum)
691 				prsignal(pr, signum);
692 		}
693 	}
694 	return (nfound ? 0 : ESRCH);
695 }
696 
697 #define CANDELIVER(uid, euid, pr) \
698 	(euid == 0 || \
699 	(uid) == (pr)->ps_ucred->cr_ruid || \
700 	(uid) == (pr)->ps_ucred->cr_svuid || \
701 	(uid) == (pr)->ps_ucred->cr_uid || \
702 	(euid) == (pr)->ps_ucred->cr_ruid || \
703 	(euid) == (pr)->ps_ucred->cr_svuid || \
704 	(euid) == (pr)->ps_ucred->cr_uid)
705 
706 #define CANSIGIO(cr, pr) \
707 	CANDELIVER((cr)->cr_ruid, (cr)->cr_uid, (pr))
708 
709 /*
710  * Send a signal to a process group.  If checktty is 1,
711  * limit to members which have a controlling terminal.
712  */
713 void
714 pgsignal(struct pgrp *pgrp, int signum, int checkctty)
715 {
716 	struct process *pr;
717 
718 	if (pgrp)
719 		LIST_FOREACH(pr, &pgrp->pg_members, ps_pglist)
720 			if (checkctty == 0 || pr->ps_flags & PS_CONTROLT)
721 				prsignal(pr, signum);
722 }
723 
724 /*
725  * Send a SIGIO or SIGURG signal to a process or process group using stored
726  * credentials rather than those of the current process.
727  */
728 void
729 pgsigio(struct sigio_ref *sir, int sig, int checkctty)
730 {
731 	struct process *pr;
732 	struct sigio *sigio;
733 
734 	if (sir->sir_sigio == NULL)
735 		return;
736 
737 	KERNEL_LOCK();
738 	mtx_enter(&sigio_lock);
739 	sigio = sir->sir_sigio;
740 	if (sigio == NULL)
741 		goto out;
742 	if (sigio->sio_pgid > 0) {
743 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc))
744 			prsignal(sigio->sio_proc, sig);
745 	} else if (sigio->sio_pgid < 0) {
746 		LIST_FOREACH(pr, &sigio->sio_pgrp->pg_members, ps_pglist) {
747 			if (CANSIGIO(sigio->sio_ucred, pr) &&
748 			    (checkctty == 0 || (pr->ps_flags & PS_CONTROLT)))
749 				prsignal(pr, sig);
750 		}
751 	}
752 out:
753 	mtx_leave(&sigio_lock);
754 	KERNEL_UNLOCK();
755 }
756 
757 /*
758  * Recalculate the signal mask and reset the signal disposition after
759  * usermode frame for delivery is formed.
760  */
761 void
762 postsig_done(struct proc *p, int signum, sigset_t catchmask, int reset)
763 {
764 	p->p_ru.ru_nsignals++;
765 	SET(p->p_sigmask, catchmask);
766 	if (reset != 0) {
767 		sigset_t mask = sigmask(signum);
768 		struct sigacts *ps = p->p_p->ps_sigacts;
769 
770 		mtx_enter(&p->p_p->ps_mtx);
771 		ps->ps_sigcatch &= ~mask;
772 		if (signum != SIGCONT && sigprop[signum] & SA_IGNORE)
773 			ps->ps_sigignore |= mask;
774 		ps->ps_sigact[signum] = SIG_DFL;
775 		mtx_leave(&p->p_p->ps_mtx);
776 	}
777 }
778 
779 /*
780  * Send a signal caused by a trap to the current thread
781  * If it will be caught immediately, deliver it with correct code.
782  * Otherwise, post it normally.
783  */
784 void
785 trapsignal(struct proc *p, int signum, u_long trapno, int code,
786     union sigval sigval)
787 {
788 	struct process *pr = p->p_p;
789 	struct sigctx ctx;
790 	int mask;
791 
792 	switch (signum) {
793 	case SIGILL:
794 		if (code == ILL_BTCFI) {
795 			pr->ps_acflag |= ABTCFI;
796 			break;
797 		}
798 		/* FALLTHROUGH */
799 	case SIGBUS:
800 	case SIGSEGV:
801 		pr->ps_acflag |= ATRAP;
802 		break;
803 	}
804 
805 	mask = sigmask(signum);
806 	setsigctx(p, signum, &ctx);
807 	if ((pr->ps_flags & PS_TRACED) == 0 && ctx.sig_catch != 0 &&
808 	    (p->p_sigmask & mask) == 0) {
809 		siginfo_t si;
810 
811 		initsiginfo(&si, signum, trapno, code, sigval);
812 #ifdef KTRACE
813 		if (KTRPOINT(p, KTR_PSIG)) {
814 			ktrpsig(p, signum, ctx.sig_action,
815 			    p->p_sigmask, code, &si);
816 		}
817 #endif
818 		if (sendsig(ctx.sig_action, signum, p->p_sigmask, &si,
819 		    ctx.sig_info, ctx.sig_onstack)) {
820 			KERNEL_LOCK();
821 			sigexit(p, SIGILL);
822 			/* NOTREACHED */
823 		}
824 		postsig_done(p, signum, ctx.sig_catchmask, ctx.sig_reset);
825 	} else {
826 		p->p_sisig = signum;
827 		p->p_sitrapno = trapno;	/* XXX for core dump/debugger */
828 		p->p_sicode = code;
829 		p->p_sigval = sigval;
830 
831 		/*
832 		 * If traced, stop if signal is masked, and stay stopped
833 		 * until released by the debugger.  If our parent process
834 		 * is waiting for us, don't hang as we could deadlock.
835 		 */
836 		if (((pr->ps_flags & (PS_TRACED | PS_PPWAIT)) == PS_TRACED) &&
837 		    signum != SIGKILL && (p->p_sigmask & mask) != 0) {
838 			signum = proc_trap(p, signum);
839 
840 			mask = sigmask(signum);
841 			setsigctx(p, signum, &ctx);
842 
843 			/*
844 			 * If we are no longer being traced, or the parent
845 			 * didn't give us a signal, skip sending the signal.
846 			 */
847 			if ((pr->ps_flags & PS_TRACED) == 0 || signum == 0)
848 				return;
849 
850 			/* update signal info */
851 			p->p_sisig = signum;
852 		}
853 
854 		/*
855 		 * Signals like SIGBUS and SIGSEGV should not, when
856 		 * generated by the kernel, be ignorable or blockable.
857 		 * If it is and we're not being traced, then just kill
858 		 * the process.
859 		 * After vfs_shutdown(9), init(8) cannot receive signals
860 		 * because new code pages of the signal handler cannot be
861 		 * mapped from halted storage.  init(8) may not die or the
862 		 * kernel panics.  Better loop between signal handler and
863 		 * page fault trap until the machine is halted.
864 		 */
865 		if ((pr->ps_flags & PS_TRACED) == 0 &&
866 		    (sigprop[signum] & SA_KILL) &&
867 		    ((p->p_sigmask & mask) || ctx.sig_ignore) &&
868 		    pr->ps_pid != 1) {
869 			KERNEL_LOCK();
870 			sigexit(p, signum);
871 			/* NOTREACHED */
872 		}
873 		ptsignal(p, signum, STHREAD);
874 	}
875 }
876 
877 /*
878  * Send the signal to the process.  If the signal has an action, the action
879  * is usually performed by the target process rather than the caller; we add
880  * the signal to the set of pending signals for the process.
881  *
882  * Exceptions:
883  *   o When a stop signal is sent to a sleeping process that takes the
884  *     default action, the process is stopped without awakening it.
885  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
886  *     regardless of the signal action (eg, blocked or ignored).
887  *
888  * Other ignored signals are discarded immediately.
889  */
890 void
891 psignal(struct proc *p, int signum)
892 {
893 	ptsignal(p, signum, SPROCESS);
894 }
895 
896 void
897 prsignal(struct process *pr, int signum)
898 {
899 	mtx_enter(&pr->ps_mtx);
900 	/* Ignore signal if the target process is exiting */
901 	if (pr->ps_flags & PS_EXITING) {
902 		mtx_leave(&pr->ps_mtx);
903 		return;
904 	}
905 	ptsignal_locked(TAILQ_FIRST(&pr->ps_threads), signum, SPROCESS);
906 	mtx_leave(&pr->ps_mtx);
907 }
908 
909 /*
910  * type = SPROCESS	process signal, can be diverted (sigwait())
911  * type = STHREAD	thread signal, but should be propagated if unhandled
912  * type = SPROPAGATED	propagated to this thread, so don't propagate again
913  */
914 void
915 ptsignal(struct proc *p, int signum, enum signal_type type)
916 {
917 	struct process *pr = p->p_p;
918 
919 	mtx_enter(&pr->ps_mtx);
920 	ptsignal_locked(p, signum, type);
921 	mtx_leave(&pr->ps_mtx);
922 }
923 
924 void
925 ptsignal_locked(struct proc *p, int signum, enum signal_type type)
926 {
927 	int prop;
928 	sig_t action, altaction = SIG_DFL;
929 	sigset_t mask, sigmask;
930 	int *siglist;
931 	struct process *pr = p->p_p;
932 	struct proc *q;
933 	int wakeparent = 0;
934 
935 	MUTEX_ASSERT_LOCKED(&pr->ps_mtx);
936 
937 #ifdef DIAGNOSTIC
938 	if ((u_int)signum >= NSIG || signum == 0)
939 		panic("psignal signal number");
940 #endif
941 
942 	/* Ignore signal if the target process is exiting */
943 	if (pr->ps_flags & PS_EXITING)
944 		return;
945 
946 	mask = sigmask(signum);
947 	sigmask = READ_ONCE(p->p_sigmask);
948 
949 	if (type == SPROCESS) {
950 		sigset_t tmpmask;
951 
952 		/* Accept SIGKILL to coredumping processes */
953 		if (pr->ps_flags & PS_COREDUMP && signum == SIGKILL) {
954 			atomic_setbits_int(&pr->ps_siglist, mask);
955 			return;
956 		}
957 
958 		/*
959 		 * If the current thread can process the signal
960 		 * immediately (it's unblocked) then have it take it.
961 		 */
962 		q = curproc;
963 		tmpmask = READ_ONCE(q->p_sigmask);
964 		if (q->p_p == pr && (q->p_flag & P_WEXIT) == 0 &&
965 		    (tmpmask & mask) == 0) {
966 			p = q;
967 			sigmask = tmpmask;
968 		} else {
969 			/*
970 			 * A process-wide signal can be diverted to a
971 			 * different thread that's in sigwait() for this
972 			 * signal.  If there isn't such a thread, then
973 			 * pick a thread that doesn't have it blocked so
974 			 * that the stop/kill consideration isn't
975 			 * delayed.  Otherwise, mark it pending on the
976 			 * main thread.
977 			 */
978 			TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
979 
980 				/* ignore exiting threads */
981 				if (q->p_flag & P_WEXIT)
982 					continue;
983 
984 				/* skip threads that have the signal blocked */
985 				tmpmask = READ_ONCE(q->p_sigmask);
986 				if ((tmpmask & mask) != 0)
987 					continue;
988 
989 				/* okay, could send to this thread */
990 				p = q;
991 				sigmask = tmpmask;
992 
993 				/*
994 				 * sigsuspend, sigwait, ppoll/pselect, etc?
995 				 * Definitely go to this thread, as it's
996 				 * already blocked in the kernel.
997 				 */
998 				if (q->p_flag & P_SIGSUSPEND)
999 					break;
1000 			}
1001 		}
1002 	}
1003 
1004 	if (type != SPROPAGATED)
1005 		knote_locked(&pr->ps_klist, NOTE_SIGNAL | signum);
1006 
1007 	prop = sigprop[signum];
1008 
1009 	/*
1010 	 * If proc is traced, always give parent a chance.
1011 	 */
1012 	if (pr->ps_flags & PS_TRACED) {
1013 		action = SIG_DFL;
1014 	} else {
1015 		sigset_t sigcatch, sigignore;
1016 
1017 		/*
1018 		 * If the signal is being ignored,
1019 		 * then we forget about it immediately.
1020 		 * (Note: we don't set SIGCONT in ps_sigignore,
1021 		 * and if it is set to SIG_IGN,
1022 		 * action will be SIG_DFL here.)
1023 		 */
1024 		sigignore = pr->ps_sigacts->ps_sigignore;
1025 		sigcatch = pr->ps_sigacts->ps_sigcatch;
1026 
1027 		if (sigignore & mask)
1028 			return;
1029 		if (sigmask & mask) {
1030 			action = SIG_HOLD;
1031 			if (sigcatch & mask)
1032 				altaction = SIG_CATCH;
1033 		} else if (sigcatch & mask) {
1034 			action = SIG_CATCH;
1035 		} else {
1036 			action = SIG_DFL;
1037 
1038 			if (prop & SA_KILL && pr->ps_nice > NZERO)
1039 				 pr->ps_nice = NZERO;
1040 
1041 			/*
1042 			 * If sending a tty stop signal to a member of an
1043 			 * orphaned process group, discard the signal here if
1044 			 * the action is default; don't stop the process below
1045 			 * if sleeping, and don't clear any pending SIGCONT.
1046 			 */
1047 			if (prop & SA_TTYSTOP && pr->ps_pgrp->pg_jobc == 0)
1048 				return;
1049 		}
1050 	}
1051 	/*
1052 	 * If delivered to process, mark as pending there.  Continue and stop
1053 	 * signals will be propagated to all threads.  So they are always
1054 	 * marked at thread level.
1055 	 */
1056 	siglist = (type == SPROCESS) ? &pr->ps_siglist : &p->p_siglist;
1057 	if (prop & (SA_CONT | SA_STOP))
1058 		siglist = &p->p_siglist;
1059 
1060 	/*
1061 	 * XXX delay processing of SA_STOP signals unless action == SIG_DFL?
1062 	 */
1063 	if (prop & (SA_CONT | SA_STOP) && type != SPROPAGATED)
1064 		TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link)
1065 			if (q != p)
1066 				ptsignal_locked(q, signum, SPROPAGATED);
1067 
1068 	SCHED_LOCK();
1069 
1070 	switch (p->p_stat) {
1071 
1072 	case SSTOP:
1073 		/*
1074 		 * If traced process is already stopped,
1075 		 * then no further action is necessary.
1076 		 */
1077 		if (pr->ps_flags & PS_TRACED)
1078 			goto out;
1079 
1080 		/*
1081 		 * Kill signal always sets processes running.
1082 		 */
1083 		if (signum == SIGKILL) {
1084 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1085 			/* Raise priority to at least PUSER. */
1086 			if (p->p_usrpri > PUSER)
1087 				p->p_usrpri = PUSER;
1088 			unsleep(p);
1089 			setrunnable(p);
1090 			goto out;
1091 		}
1092 
1093 		if (prop & SA_CONT) {
1094 			/*
1095 			 * If SIGCONT is default (or ignored), we continue the
1096 			 * process but don't leave the signal in p_siglist, as
1097 			 * it has no further action.  If SIGCONT is held, we
1098 			 * continue the process and leave the signal in
1099 			 * p_siglist.  If the process catches SIGCONT, let it
1100 			 * handle the signal itself.  If it isn't waiting on
1101 			 * an event, then it goes back to run state.
1102 			 * Otherwise, process goes back to sleep state.
1103 			 */
1104 			atomic_setbits_int(&pr->ps_flags, PS_CONTINUED);
1105 			atomic_clearbits_int(&pr->ps_flags,
1106 			    PS_WAITED | PS_STOPPED | PS_TRAPPED);
1107 			atomic_clearbits_int(&p->p_flag, P_SUSPSIG);
1108 			wakeparent = 1;
1109 			if (action == SIG_DFL)
1110 				mask = 0;
1111 			if (action == SIG_CATCH) {
1112 				/* Raise priority to at least PUSER. */
1113 				if (p->p_usrpri > PUSER)
1114 					p->p_usrpri = PUSER;
1115 				unsleep(p);
1116 				setrunnable(p);
1117 				goto out;
1118 			}
1119 			if (p->p_wchan == NULL) {
1120 				setrunnable(p);
1121 				goto out;
1122 			}
1123 			p->p_stat = SSLEEP;
1124 			goto out;
1125 		}
1126 
1127 		/*
1128 		 * Defer further processing for signals which are held,
1129 		 * except that stopped processes must be continued by SIGCONT.
1130 		 */
1131 		if (action == SIG_HOLD)
1132 			goto out;
1133 
1134 		if (prop & SA_STOP) {
1135 			/*
1136 			 * Already stopped, don't need to stop again.
1137 			 * (If we did the shell could get confused.)
1138 			 */
1139 			mask = 0;
1140 			goto out;
1141 		}
1142 
1143 		/*
1144 		 * If process is sleeping interruptibly, then simulate a
1145 		 * wakeup so that when it is continued, it will be made
1146 		 * runnable and can look at the signal.  But don't make
1147 		 * the process runnable, leave it stopped.
1148 		 */
1149 		if (p->p_flag & P_SINTR)
1150 			unsleep(p);
1151 		goto out;
1152 
1153 	case SSLEEP:
1154 		/*
1155 		 * If process is sleeping uninterruptibly
1156 		 * we can't interrupt the sleep... the signal will
1157 		 * be noticed when the process returns through
1158 		 * trap() or syscall().
1159 		 */
1160 		if ((p->p_flag & P_SINTR) == 0)
1161 			goto out;
1162 		/*
1163 		 * Process is sleeping and traced... make it runnable
1164 		 * so it can discover the signal in cursig() and stop
1165 		 * for the parent.
1166 		 */
1167 		if (pr->ps_flags & PS_TRACED) {
1168 			unsleep(p);
1169 			setrunnable(p);
1170 			goto out;
1171 		}
1172 
1173 		/*
1174 		 * Recheck sigmask before waking up the process,
1175 		 * there is a chance that while sending the signal
1176 		 * the process changed sigmask and went to sleep.
1177 		 */
1178 		sigmask = READ_ONCE(p->p_sigmask);
1179 		if (sigmask & mask)
1180 			goto out;
1181 		else if (action == SIG_HOLD) {
1182 			/* signal got unmasked, get proper action */
1183 			action = altaction;
1184 
1185 			if (action == SIG_DFL) {
1186 				if (prop & SA_KILL && pr->ps_nice > NZERO)
1187 					 pr->ps_nice = NZERO;
1188 
1189 				/*
1190 				 * Discard tty stop signals sent to an
1191 				 * orphaned process group, see above.
1192 				 */
1193 				if (prop & SA_TTYSTOP &&
1194 				    pr->ps_pgrp->pg_jobc == 0) {
1195 					mask = 0;
1196 					prop = 0;
1197 					goto out;
1198 				}
1199 			}
1200 		}
1201 
1202 		/*
1203 		 * If SIGCONT is default (or ignored) and process is
1204 		 * asleep, we are finished; the process should not
1205 		 * be awakened.
1206 		 */
1207 		if ((prop & SA_CONT) && action == SIG_DFL) {
1208 			mask = 0;
1209 			goto out;
1210 		}
1211 		/*
1212 		 * When a sleeping process receives a stop
1213 		 * signal, process immediately if possible.
1214 		 */
1215 		if ((prop & SA_STOP) && action == SIG_DFL) {
1216 			/*
1217 			 * If a child holding parent blocked,
1218 			 * stopping could cause deadlock.
1219 			 */
1220 			if (pr->ps_flags & PS_PPWAIT)
1221 				goto out;
1222 			mask = 0;
1223 			pr->ps_xsig = signum;
1224 			proc_stop(p, 0);
1225 			goto out;
1226 		}
1227 		/*
1228 		 * All other (caught or default) signals
1229 		 * cause the process to run.
1230 		 * Raise priority to at least PUSER.
1231 		 */
1232 		if (p->p_usrpri > PUSER)
1233 			p->p_usrpri = PUSER;
1234 		unsleep(p);
1235 		setrunnable(p);
1236 		goto out;
1237 		/* NOTREACHED */
1238 
1239 	case SONPROC:
1240 		if (action == SIG_HOLD)
1241 			goto out;
1242 
1243 		/* set siglist before issuing the ast */
1244 		atomic_setbits_int(siglist, mask);
1245 		mask = 0;
1246 		signotify(p);
1247 		/* FALLTHROUGH */
1248 	default:
1249 		/*
1250 		 * SRUN, SIDL, SDEAD do nothing with the signal,
1251 		 * other than kicking ourselves if we are running.
1252 		 * It will either never be noticed, or noticed very soon.
1253 		 */
1254 		goto out;
1255 	}
1256 	/* NOTREACHED */
1257 
1258 out:
1259 	/* finally adjust siglist */
1260 	if (mask)
1261 		atomic_setbits_int(siglist, mask);
1262 	if (prop & SA_CONT) {
1263 		atomic_clearbits_int(siglist, STOPSIGMASK);
1264 	}
1265 	if (prop & SA_STOP) {
1266 		atomic_clearbits_int(siglist, CONTSIGMASK);
1267 		atomic_clearbits_int(&pr->ps_flags, PS_CONTINUED);
1268 	}
1269 
1270 	SCHED_UNLOCK();
1271 	if (wakeparent)
1272 		wakeup(pr->ps_pptr);
1273 }
1274 
1275 /* fill the signal context which should be used by postsig() and issignal() */
1276 void
1277 setsigctx(struct proc *p, int signum, struct sigctx *sctx)
1278 {
1279 	struct process *pr = p->p_p;
1280 	struct sigacts *ps = pr->ps_sigacts;
1281 	sigset_t mask;
1282 
1283 	mtx_enter(&pr->ps_mtx);
1284 	mask = sigmask(signum);
1285 	sctx->sig_action = ps->ps_sigact[signum];
1286 	sctx->sig_catchmask = ps->ps_catchmask[signum];
1287 	sctx->sig_reset = (ps->ps_sigreset & mask) != 0;
1288 	sctx->sig_info = (ps->ps_siginfo & mask) != 0;
1289 	sctx->sig_intr = (ps->ps_sigintr & mask) != 0;
1290 	sctx->sig_onstack = (ps->ps_sigonstack & mask) != 0;
1291 	sctx->sig_ignore = (ps->ps_sigignore & mask) != 0;
1292 	sctx->sig_catch = (ps->ps_sigcatch & mask) != 0;
1293 	sctx->sig_stop = sigprop[signum] & SA_STOP &&
1294 	    (long)sctx->sig_action == (long)SIG_DFL;
1295 	if (sctx->sig_stop) {
1296 		/*
1297 		 * If the process is a member of an orphaned
1298 		 * process group, ignore tty stop signals.
1299 		 */
1300 		if (pr->ps_flags & PS_TRACED ||
1301 		    (pr->ps_pgrp->pg_jobc == 0 &&
1302 		    sigprop[signum] & SA_TTYSTOP)) {
1303 			sctx->sig_stop = 0;
1304 			sctx->sig_ignore = 1;
1305 		}
1306 	}
1307 	mtx_leave(&pr->ps_mtx);
1308 }
1309 
1310 /*
1311  * Determine signal that should be delivered to process p, the current
1312  * process, 0 if none.
1313  *
1314  * If the current process has received a signal (should be caught or cause
1315  * termination, should interrupt current syscall), return the signal number.
1316  * Stop signals with default action are processed immediately, then cleared;
1317  * they aren't returned.  This is checked after each entry to the system for
1318  * a syscall or trap. The normal call sequence is
1319  *
1320  *	while (signum = cursig(curproc, &ctx, 0))
1321  *		postsig(signum, &ctx);
1322  *
1323  * Assumes that if the P_SINTR flag is set, we're holding both the
1324  * kernel and scheduler locks.
1325  */
1326 int
1327 cursig(struct proc *p, struct sigctx *sctx, int deep)
1328 {
1329 	struct process *pr = p->p_p;
1330 	int signum, mask, keep = 0, prop;
1331 	sigset_t ps_siglist;
1332 
1333 	KASSERT(p == curproc);
1334 
1335 	for (;;) {
1336 		ps_siglist = READ_ONCE(pr->ps_siglist);
1337 		membar_consumer();
1338 		mask = SIGPENDING(p);
1339 		if (pr->ps_flags & PS_PPWAIT)
1340 			mask &= ~STOPSIGMASK;
1341 		signum = ffs(mask);
1342 		if (signum == 0)	 	/* no signal to send */
1343 			goto keep;
1344 		mask = sigmask(signum);
1345 
1346 		/* take the signal! */
1347 		if (atomic_cas_uint(&pr->ps_siglist, ps_siglist,
1348 		    ps_siglist & ~mask) != ps_siglist) {
1349 			/* lost race taking the process signal, restart */
1350 			continue;
1351 		}
1352 		atomic_clearbits_int(&p->p_siglist, mask);
1353 		setsigctx(p, signum, sctx);
1354 
1355 		/*
1356 		 * We should see pending but ignored signals
1357 		 * only if PS_TRACED was on when they were posted.
1358 		 */
1359 		if (sctx->sig_ignore && (pr->ps_flags & PS_TRACED) == 0)
1360 			continue;
1361 
1362 		/*
1363 		 * If cursig is called while going to sleep, abort now
1364 		 * and stop the sleep. When the call unwinded to userret
1365 		 * cursig is called again and there the signal can be
1366 		 * handled cleanly.
1367 		 */
1368 		if (deep) {
1369 			/*
1370 			 * Do not stop the thread here if multiple
1371 			 * signals are pending and at least one of
1372 			 * them would force an unwind.
1373 			 *
1374 			 * ffs() favors low numbered signals and
1375 			 * so stop signals may be picked up before
1376 			 * other pending signals.
1377 			 */
1378 			if (sctx->sig_stop && SIGPENDING(p)) {
1379 				keep |= mask;
1380 				continue;
1381 			}
1382 			goto keep;
1383 		}
1384 
1385 		/*
1386 		 * If traced, always stop, and stay stopped until released
1387 		 * by the debugger.  If our parent process is waiting for
1388 		 * us, don't hang as we could deadlock.
1389 		 */
1390 		if (((pr->ps_flags & (PS_TRACED | PS_PPWAIT)) == PS_TRACED) &&
1391 		    signum != SIGKILL) {
1392 			signum = proc_trap(p, signum);
1393 
1394 			mask = sigmask(signum);
1395 			setsigctx(p, signum, sctx);
1396 
1397 			/*
1398 			 * If we are no longer being traced, or the parent
1399 			 * didn't give us a signal, or the signal is ignored,
1400 			 * look for more signals.
1401 			 */
1402 			if ((pr->ps_flags & PS_TRACED) == 0 || signum == 0 ||
1403 			    sctx->sig_ignore)
1404 				continue;
1405 
1406 			/*
1407 			 * If the new signal is being masked, look for other
1408 			 * signals but leave it for later.
1409 			 */
1410 			if ((p->p_sigmask & mask) != 0) {
1411 				atomic_setbits_int(&p->p_siglist, mask);
1412 				continue;
1413 			}
1414 
1415 		}
1416 
1417 		prop = sigprop[signum];
1418 
1419 		/*
1420 		 * Decide whether the signal should be returned.
1421 		 * Return the signal's number, or fall through
1422 		 * to clear it from the pending mask.
1423 		 */
1424 		switch ((long)sctx->sig_action) {
1425 		case (long)SIG_DFL:
1426 			/*
1427 			 * Don't take default actions on system processes.
1428 			 */
1429 			if (pr->ps_pid <= 1) {
1430 #ifdef DIAGNOSTIC
1431 				/*
1432 				 * Are you sure you want to ignore SIGSEGV
1433 				 * in init? XXX
1434 				 */
1435 				printf("Process (pid %d) got signal"
1436 				    " %d\n", pr->ps_pid, signum);
1437 #endif
1438 				break;		/* == ignore */
1439 			}
1440 			/*
1441 			 * If there is a pending stop signal to process
1442 			 * with default action, stop here,
1443 			 * then clear the signal.
1444 			 */
1445 			if (sctx->sig_stop) {
1446 				pr->ps_xsig = signum;
1447 				SCHED_LOCK();
1448 				proc_stop(p, 1);
1449 				SCHED_UNLOCK();
1450 				break;
1451 			} else if (prop & SA_IGNORE) {
1452 				/*
1453 				 * Except for SIGCONT, shouldn't get here.
1454 				 * Default action is to ignore; drop it.
1455 				 */
1456 				break;		/* == ignore */
1457 			} else
1458 				goto keep;
1459 			/* NOTREACHED */
1460 		case (long)SIG_IGN:
1461 			/*
1462 			 * Masking above should prevent us ever trying
1463 			 * to take action on an ignored signal other
1464 			 * than SIGCONT, unless process is traced.
1465 			 */
1466 			if ((prop & SA_CONT) == 0 &&
1467 			    (pr->ps_flags & PS_TRACED) == 0)
1468 				printf("%s\n", __func__);
1469 			break;		/* == ignore */
1470 		default:
1471 			/*
1472 			 * This signal has an action, let
1473 			 * postsig() process it.
1474 			 */
1475 			goto keep;
1476 		}
1477 	}
1478 	/* NOTREACHED */
1479 
1480 keep:
1481 	/*
1482 	 * if we stashed a stop signal but no other signal is pending
1483 	 * anymore pick the stop signal up again.
1484 	 */
1485 	if (keep != 0 && signum == 0) {
1486 		signum = ffs(keep);
1487 		setsigctx(p, signum, sctx);
1488 	}
1489 	/* move the signal to p_siglist for later */
1490 	atomic_setbits_int(&p->p_siglist, mask | keep);
1491 	return (signum);
1492 }
1493 
1494 int
1495 proc_trap(struct proc *p, int signum)
1496 {
1497 	struct process *pr = p->p_p;
1498 
1499 	single_thread_set(p, SINGLE_SUSPEND | SINGLE_NOWAIT);
1500 	pr->ps_xsig = signum;
1501 
1502 	SCHED_LOCK();
1503 	atomic_setbits_int(&pr->ps_flags, PS_TRAPPED);
1504 	proc_stop(p, 1);
1505 	atomic_clearbits_int(&pr->ps_flags,
1506 	    PS_WAITED | PS_STOPPED | PS_TRAPPED);
1507 	SCHED_UNLOCK();
1508 
1509 	signum = pr->ps_xsig;
1510 	pr->ps_xsig = 0;
1511 	if ((p->p_flag & P_TRACESINGLE) == 0)
1512 		single_thread_clear(p, 0);
1513 	atomic_clearbits_int(&p->p_flag, P_TRACESINGLE);
1514 
1515 	return signum;
1516 }
1517 
1518 /*
1519  * Put the argument process into the stopped state and notify the parent
1520  * via wakeup.  Signals are handled elsewhere.  The process must not be
1521  * on the run queue.
1522  */
1523 void
1524 proc_stop(struct proc *p, int sw)
1525 {
1526 	struct process *pr = p->p_p;
1527 
1528 #ifdef MULTIPROCESSOR
1529 	SCHED_ASSERT_LOCKED();
1530 #endif
1531 	/* do not stop exiting procs */
1532 	if (ISSET(p->p_flag, P_WEXIT))
1533 		return;
1534 
1535 	p->p_stat = SSTOP;
1536 	atomic_clearbits_int(&pr->ps_flags, PS_WAITED);
1537 	atomic_setbits_int(&pr->ps_flags, PS_STOPPING);
1538 	atomic_setbits_int(&p->p_flag, P_SUSPSIG);
1539 	/*
1540 	 * We need this soft interrupt to be handled fast.
1541 	 * Extra calls to softclock don't hurt.
1542 	 */
1543 	softintr_schedule(proc_stop_si);
1544 	if (sw)
1545 		mi_switch();
1546 }
1547 
1548 /*
1549  * Called from a soft interrupt to send signals to the parents of stopped
1550  * processes.
1551  * We can't do this in proc_stop because it's called with nasty locks held
1552  * and we would need recursive scheduler lock to deal with that.
1553  */
1554 void
1555 proc_stop_sweep(void *v)
1556 {
1557 	struct process *pr;
1558 
1559 	LIST_FOREACH(pr, &allprocess, ps_list) {
1560 		if ((pr->ps_flags & PS_STOPPING) == 0)
1561 			continue;
1562 		atomic_setbits_int(&pr->ps_flags, PS_STOPPED);
1563 		atomic_clearbits_int(&pr->ps_flags, PS_STOPPING);
1564 
1565 		if ((pr->ps_pptr->ps_sigacts->ps_sigflags & SAS_NOCLDSTOP) == 0)
1566 			prsignal(pr->ps_pptr, SIGCHLD);
1567 		wakeup(pr->ps_pptr);
1568 	}
1569 }
1570 
1571 /*
1572  * Take the action for the specified signal
1573  * from the current set of pending signals.
1574  */
1575 void
1576 postsig(struct proc *p, int signum, struct sigctx *sctx)
1577 {
1578 	u_long trapno;
1579 	int mask, returnmask;
1580 	siginfo_t si;
1581 	union sigval sigval;
1582 	int code;
1583 
1584 	KASSERT(signum != 0);
1585 
1586 	mask = sigmask(signum);
1587 	atomic_clearbits_int(&p->p_siglist, mask);
1588 	sigval.sival_ptr = NULL;
1589 
1590 	if (p->p_sisig != signum) {
1591 		trapno = 0;
1592 		code = SI_USER;
1593 		sigval.sival_ptr = NULL;
1594 	} else {
1595 		trapno = p->p_sitrapno;
1596 		code = p->p_sicode;
1597 		sigval = p->p_sigval;
1598 	}
1599 	initsiginfo(&si, signum, trapno, code, sigval);
1600 
1601 #ifdef KTRACE
1602 	if (KTRPOINT(p, KTR_PSIG)) {
1603 		ktrpsig(p, signum, sctx->sig_action, p->p_flag & P_SIGSUSPEND ?
1604 		    p->p_oldmask : p->p_sigmask, code, &si);
1605 	}
1606 #endif
1607 	if (sctx->sig_action == SIG_DFL) {
1608 		/*
1609 		 * Default action, where the default is to kill
1610 		 * the process.  (Other cases were ignored above.)
1611 		 */
1612 		KERNEL_LOCK();
1613 		sigexit(p, signum);
1614 		/* NOTREACHED */
1615 	} else {
1616 		/*
1617 		 * If we get here, the signal must be caught.
1618 		 */
1619 #ifdef DIAGNOSTIC
1620 		if (sctx->sig_action == SIG_IGN || (p->p_sigmask & mask))
1621 			panic("postsig action");
1622 #endif
1623 		/*
1624 		 * Set the new mask value and also defer further
1625 		 * occurrences of this signal.
1626 		 *
1627 		 * Special case: user has done a sigpause.  Here the
1628 		 * current mask is not of interest, but rather the
1629 		 * mask from before the sigpause is what we want
1630 		 * restored after the signal processing is completed.
1631 		 */
1632 		if (p->p_flag & P_SIGSUSPEND) {
1633 			atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
1634 			returnmask = p->p_oldmask;
1635 		} else {
1636 			returnmask = p->p_sigmask;
1637 		}
1638 		if (p->p_sisig == signum) {
1639 			p->p_sisig = 0;
1640 			p->p_sitrapno = 0;
1641 			p->p_sicode = SI_USER;
1642 			p->p_sigval.sival_ptr = NULL;
1643 		}
1644 
1645 		if (sendsig(sctx->sig_action, signum, returnmask, &si,
1646 		    sctx->sig_info, sctx->sig_onstack)) {
1647 			KERNEL_LOCK();
1648 			sigexit(p, SIGILL);
1649 			/* NOTREACHED */
1650 		}
1651 		postsig_done(p, signum, sctx->sig_catchmask, sctx->sig_reset);
1652 	}
1653 }
1654 
1655 /*
1656  * Force the current process to exit with the specified signal, dumping core
1657  * if appropriate.  We bypass the normal tests for masked and caught signals,
1658  * allowing unrecoverable failures to terminate the process without changing
1659  * signal state.  Mark the accounting record with the signal termination.
1660  * If dumping core, save the signal number for the debugger.  Calls exit and
1661  * does not return.
1662  */
1663 void
1664 sigexit(struct proc *p, int signum)
1665 {
1666 	/* Mark process as going away */
1667 	atomic_setbits_int(&p->p_flag, P_WEXIT);
1668 
1669 	p->p_p->ps_acflag |= AXSIG;
1670 	if (sigprop[signum] & SA_CORE) {
1671 		p->p_sisig = signum;
1672 
1673 		/* if there are other threads, pause them */
1674 		if (P_HASSIBLING(p))
1675 			single_thread_set(p, SINGLE_UNWIND);
1676 
1677 		if (coredump(p) == 0)
1678 			signum |= WCOREFLAG;
1679 	}
1680 	exit1(p, 0, signum, EXIT_NORMAL);
1681 	/* NOTREACHED */
1682 }
1683 
1684 /*
1685  * Send uncatchable SIGABRT for coredump.
1686  */
1687 void
1688 sigabort(struct proc *p)
1689 {
1690 	struct sigaction sa;
1691 
1692 	KASSERT(p == curproc || panicstr || db_active);
1693 
1694 	memset(&sa, 0, sizeof sa);
1695 	sa.sa_handler = SIG_DFL;
1696 	setsigvec(p, SIGABRT, &sa);
1697 	CLR(p->p_sigmask, sigmask(SIGABRT));
1698 	psignal(p, SIGABRT);
1699 }
1700 
1701 /*
1702  * Return 1 if `sig', a given signal, is ignored or masked for `p', a given
1703  * thread, and 0 otherwise.
1704  */
1705 int
1706 sigismasked(struct proc *p, int sig)
1707 {
1708 	struct process *pr = p->p_p;
1709 	int rv;
1710 
1711 	KASSERT(p == curproc);
1712 
1713 	mtx_enter(&pr->ps_mtx);
1714 	rv = (pr->ps_sigacts->ps_sigignore & sigmask(sig)) ||
1715 	    (p->p_sigmask & sigmask(sig));
1716 	mtx_leave(&pr->ps_mtx);
1717 
1718 	return !!rv;
1719 }
1720 
1721 struct coredump_iostate {
1722 	struct proc *io_proc;
1723 	struct vnode *io_vp;
1724 	struct ucred *io_cred;
1725 	off_t io_offset;
1726 };
1727 
1728 /*
1729  * Dump core, into a file named "progname.core", unless the process was
1730  * setuid/setgid.
1731  */
1732 int
1733 coredump(struct proc *p)
1734 {
1735 #ifdef SMALL_KERNEL
1736 	return EPERM;
1737 #else
1738 	struct process *pr = p->p_p;
1739 	struct vnode *vp;
1740 	struct ucred *cred = p->p_ucred;
1741 	struct vmspace *vm = p->p_vmspace;
1742 	struct nameidata nd;
1743 	struct vattr vattr;
1744 	struct coredump_iostate	io;
1745 	int error, len, incrash = 0;
1746 	char *name;
1747 	const char *dir = "/var/crash";
1748 
1749 	atomic_setbits_int(&pr->ps_flags, PS_COREDUMP);
1750 
1751 #ifdef PMAP_CHECK_COPYIN
1752 	/* disable copyin checks, so we can write out text sections if needed */
1753 	p->p_vmspace->vm_map.check_copyin_count = 0;
1754 #endif
1755 
1756 	/* Don't dump if will exceed file size limit. */
1757 	if (USPACE + ptoa(vm->vm_dsize + vm->vm_ssize) >= lim_cur(RLIMIT_CORE))
1758 		return (EFBIG);
1759 
1760 	name = pool_get(&namei_pool, PR_WAITOK);
1761 
1762 	/*
1763 	 * If the process has inconsistent uids, nosuidcoredump
1764 	 * determines coredump placement policy.
1765 	 */
1766 	if (((pr->ps_flags & PS_SUGID) && (error = suser(p))) ||
1767 	   ((pr->ps_flags & PS_SUGID) && nosuidcoredump)) {
1768 		if (nosuidcoredump == 3) {
1769 			/*
1770 			 * If the program directory does not exist, dumps of
1771 			 * that core will silently fail.
1772 			 */
1773 			len = snprintf(name, MAXPATHLEN, "%s/%s/%u.core",
1774 			    dir, pr->ps_comm, pr->ps_pid);
1775 			incrash = KERNELPATH;
1776 		} else if (nosuidcoredump == 2) {
1777 			len = snprintf(name, MAXPATHLEN, "%s/%s.core",
1778 			    dir, pr->ps_comm);
1779 			incrash = KERNELPATH;
1780 		} else {
1781 			pool_put(&namei_pool, name);
1782 			return (EPERM);
1783 		}
1784 	} else
1785 		len = snprintf(name, MAXPATHLEN, "%s.core", pr->ps_comm);
1786 
1787 	if (len >= MAXPATHLEN) {
1788 		pool_put(&namei_pool, name);
1789 		return (EACCES);
1790 	}
1791 
1792 	/*
1793 	 * Control the UID used to write out.  The normal case uses
1794 	 * the real UID.  If the sugid case is going to write into the
1795 	 * controlled directory, we do so as root.
1796 	 */
1797 	if (incrash == 0) {
1798 		cred = crdup(cred);
1799 		cred->cr_uid = cred->cr_ruid;
1800 		cred->cr_gid = cred->cr_rgid;
1801 	} else {
1802 		if (p->p_fd->fd_rdir) {
1803 			vrele(p->p_fd->fd_rdir);
1804 			p->p_fd->fd_rdir = NULL;
1805 		}
1806 		p->p_ucred = crdup(p->p_ucred);
1807 		crfree(cred);
1808 		cred = p->p_ucred;
1809 		crhold(cred);
1810 		cred->cr_uid = 0;
1811 		cred->cr_gid = 0;
1812 	}
1813 
1814 	/* incrash should be 0 or KERNELPATH only */
1815 	NDINIT(&nd, 0, BYPASSUNVEIL | incrash, UIO_SYSSPACE, name, p);
1816 
1817 	error = vn_open(&nd, O_CREAT | FWRITE | O_NOFOLLOW | O_NONBLOCK,
1818 	    S_IRUSR | S_IWUSR);
1819 
1820 	if (error)
1821 		goto out;
1822 
1823 	/*
1824 	 * Don't dump to non-regular files, files with links, or files
1825 	 * owned by someone else.
1826 	 */
1827 	vp = nd.ni_vp;
1828 	if ((error = VOP_GETATTR(vp, &vattr, cred, p)) != 0) {
1829 		VOP_UNLOCK(vp);
1830 		vn_close(vp, FWRITE, cred, p);
1831 		goto out;
1832 	}
1833 	if (vp->v_type != VREG || vattr.va_nlink != 1 ||
1834 	    vattr.va_mode & ((VREAD | VWRITE) >> 3 | (VREAD | VWRITE) >> 6) ||
1835 	    vattr.va_uid != cred->cr_uid) {
1836 		error = EACCES;
1837 		VOP_UNLOCK(vp);
1838 		vn_close(vp, FWRITE, cred, p);
1839 		goto out;
1840 	}
1841 	vattr_null(&vattr);
1842 	vattr.va_size = 0;
1843 	VOP_SETATTR(vp, &vattr, cred, p);
1844 	pr->ps_acflag |= ACORE;
1845 
1846 	io.io_proc = p;
1847 	io.io_vp = vp;
1848 	io.io_cred = cred;
1849 	io.io_offset = 0;
1850 	VOP_UNLOCK(vp);
1851 	vref(vp);
1852 	error = vn_close(vp, FWRITE, cred, p);
1853 	if (error == 0)
1854 		error = coredump_elf(p, &io);
1855 	vrele(vp);
1856 out:
1857 	crfree(cred);
1858 	pool_put(&namei_pool, name);
1859 	return (error);
1860 #endif
1861 }
1862 
1863 #ifndef SMALL_KERNEL
1864 int
1865 coredump_write(void *cookie, enum uio_seg segflg, const void *data, size_t len,
1866     int isvnode)
1867 {
1868 	struct coredump_iostate *io = cookie;
1869 	off_t coffset = 0;
1870 	size_t csize;
1871 	int chunk, error;
1872 
1873 	csize = len;
1874 	do {
1875 		if (sigmask(SIGKILL) &
1876 		    (io->io_proc->p_siglist | io->io_proc->p_p->ps_siglist))
1877 			return (EINTR);
1878 
1879 		/* Rest of the loop sleeps with lock held, so... */
1880 		yield();
1881 
1882 		chunk = MIN(csize, MAXPHYS);
1883 		error = vn_rdwr(UIO_WRITE, io->io_vp,
1884 		    (caddr_t)data + coffset, chunk,
1885 		    io->io_offset + coffset, segflg,
1886 		    IO_UNIT, io->io_cred, NULL, io->io_proc);
1887 		if (error && (error != EFAULT || !isvnode)) {
1888 			struct process *pr = io->io_proc->p_p;
1889 
1890 			if (error == ENOSPC)
1891 				log(LOG_ERR,
1892 				    "coredump of %s(%d) failed, filesystem full\n",
1893 				    pr->ps_comm, pr->ps_pid);
1894 			else
1895 				log(LOG_ERR,
1896 				    "coredump of %s(%d), write failed: errno %d\n",
1897 				    pr->ps_comm, pr->ps_pid, error);
1898 			return (error);
1899 		}
1900 
1901 		coffset += chunk;
1902 		csize -= chunk;
1903 	} while (csize > 0);
1904 
1905 	io->io_offset += len;
1906 	return (0);
1907 }
1908 
1909 void
1910 coredump_unmap(void *cookie, vaddr_t start, vaddr_t end)
1911 {
1912 	struct coredump_iostate *io = cookie;
1913 
1914 	uvm_unmap(&io->io_proc->p_vmspace->vm_map, start, end);
1915 }
1916 
1917 #endif	/* !SMALL_KERNEL */
1918 
1919 /*
1920  * Nonexistent system call-- signal process (may want to handle it).
1921  * Flag error in case process won't see signal immediately (blocked or ignored).
1922  */
1923 int
1924 sys_nosys(struct proc *p, void *v, register_t *retval)
1925 {
1926 	ptsignal(p, SIGSYS, STHREAD);
1927 	return (ENOSYS);
1928 }
1929 
1930 int
1931 sys___thrsigdivert(struct proc *p, void *v, register_t *retval)
1932 {
1933 	struct sys___thrsigdivert_args /* {
1934 		syscallarg(sigset_t) sigmask;
1935 		syscallarg(siginfo_t *) info;
1936 		syscallarg(const struct timespec *) timeout;
1937 	} */ *uap = v;
1938 	struct sigctx ctx;
1939 	sigset_t mask = SCARG(uap, sigmask) &~ sigcantmask;
1940 	siginfo_t si;
1941 	uint64_t nsecs = INFSLP;
1942 	int timeinvalid = 0;
1943 	int error = 0;
1944 
1945 	memset(&si, 0, sizeof(si));
1946 
1947 	if (SCARG(uap, timeout) != NULL) {
1948 		struct timespec ts;
1949 		if ((error = copyin(SCARG(uap, timeout), &ts, sizeof(ts))) != 0)
1950 			return (error);
1951 #ifdef KTRACE
1952 		if (KTRPOINT(p, KTR_STRUCT))
1953 			ktrreltimespec(p, &ts);
1954 #endif
1955 		if (!timespecisvalid(&ts))
1956 			timeinvalid = 1;
1957 		else
1958 			nsecs = TIMESPEC_TO_NSEC(&ts);
1959 	}
1960 
1961 	dosigsuspend(p, p->p_sigmask &~ mask);
1962 	for (;;) {
1963 		si.si_signo = cursig(p, &ctx, 0);
1964 		if (si.si_signo != 0) {
1965 			sigset_t smask = sigmask(si.si_signo);
1966 			if (smask & mask) {
1967 				atomic_clearbits_int(&p->p_siglist, smask);
1968 				error = 0;
1969 				break;
1970 			}
1971 		}
1972 
1973 		/* per-POSIX, delay this error until after the above */
1974 		if (timeinvalid)
1975 			error = EINVAL;
1976 		/* per-POSIX, return immediately if timeout is zero-valued */
1977 		if (nsecs == 0)
1978 			error = EAGAIN;
1979 
1980 		if (error != 0)
1981 			break;
1982 
1983 		error = tsleep_nsec(&nowake, PPAUSE|PCATCH, "sigwait", nsecs);
1984 	}
1985 
1986 	if (error == 0) {
1987 		*retval = si.si_signo;
1988 		if (SCARG(uap, info) != NULL) {
1989 			error = copyout(&si, SCARG(uap, info), sizeof(si));
1990 #ifdef KTRACE
1991 			if (error == 0 && KTRPOINT(p, KTR_STRUCT))
1992 				ktrsiginfo(p, &si);
1993 #endif
1994 		}
1995 	} else if (error == ERESTART && SCARG(uap, timeout) != NULL) {
1996 		/*
1997 		 * Restarting is wrong if there's a timeout, as it'll be
1998 		 * for the same interval again
1999 		 */
2000 		error = EINTR;
2001 	}
2002 
2003 	return (error);
2004 }
2005 
2006 void
2007 initsiginfo(siginfo_t *si, int sig, u_long trapno, int code, union sigval val)
2008 {
2009 	memset(si, 0, sizeof(*si));
2010 
2011 	si->si_signo = sig;
2012 	si->si_code = code;
2013 	if (code == SI_USER) {
2014 		si->si_value = val;
2015 	} else {
2016 		switch (sig) {
2017 		case SIGSEGV:
2018 		case SIGILL:
2019 		case SIGBUS:
2020 		case SIGFPE:
2021 			si->si_addr = val.sival_ptr;
2022 			si->si_trapno = trapno;
2023 			break;
2024 		case SIGXFSZ:
2025 			break;
2026 		}
2027 	}
2028 }
2029 
2030 void
2031 userret(struct proc *p)
2032 {
2033 	struct sigctx ctx;
2034 	int signum;
2035 
2036 	if (p->p_flag & P_SUSPSINGLE)
2037 		single_thread_check(p, 0);
2038 
2039 	/* send SIGPROF or SIGVTALRM if their timers interrupted this thread */
2040 	if (p->p_flag & P_PROFPEND) {
2041 		atomic_clearbits_int(&p->p_flag, P_PROFPEND);
2042 		psignal(p, SIGPROF);
2043 	}
2044 	if (p->p_flag & P_ALRMPEND) {
2045 		atomic_clearbits_int(&p->p_flag, P_ALRMPEND);
2046 		psignal(p, SIGVTALRM);
2047 	}
2048 
2049 	if (SIGPENDING(p) != 0) {
2050 		while ((signum = cursig(p, &ctx, 0)) != 0)
2051 			postsig(p, signum, &ctx);
2052 	}
2053 
2054 	/*
2055 	 * If P_SIGSUSPEND is still set here, then we still need to restore
2056 	 * the original sigmask before returning to userspace.  Also, this
2057 	 * might unmask some pending signals, so we need to check a second
2058 	 * time for signals to post.
2059 	 */
2060 	if (p->p_flag & P_SIGSUSPEND) {
2061 		p->p_sigmask = p->p_oldmask;
2062 		atomic_clearbits_int(&p->p_flag, P_SIGSUSPEND);
2063 
2064 		while ((signum = cursig(p, &ctx, 0)) != 0)
2065 			postsig(p, signum, &ctx);
2066 	}
2067 
2068 	WITNESS_WARN(WARN_PANIC, NULL, "userret: returning");
2069 
2070 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
2071 }
2072 
2073 int
2074 single_thread_check_locked(struct proc *p, int deep)
2075 {
2076 	struct process *pr = p->p_p;
2077 
2078 	MUTEX_ASSERT_LOCKED(&pr->ps_mtx);
2079 
2080 	if (pr->ps_single == NULL || pr->ps_single == p)
2081 		return (0);
2082 
2083 	do {
2084 		/* if we're in deep, we need to unwind to the edge */
2085 		if (deep) {
2086 			if (pr->ps_flags & PS_SINGLEUNWIND)
2087 				return (ERESTART);
2088 			if (pr->ps_flags & PS_SINGLEEXIT)
2089 				return (EINTR);
2090 		}
2091 
2092 		if (pr->ps_flags & PS_SINGLEEXIT) {
2093 			mtx_leave(&pr->ps_mtx);
2094 			KERNEL_LOCK();
2095 			exit1(p, 0, 0, EXIT_THREAD_NOCHECK);
2096 			/* NOTREACHED */
2097 		}
2098 
2099 		if (--pr->ps_singlecnt == 0)
2100 			wakeup(&pr->ps_singlecnt);
2101 
2102 		/* not exiting and don't need to unwind, so suspend */
2103 		mtx_leave(&pr->ps_mtx);
2104 
2105 		SCHED_LOCK();
2106 		p->p_stat = SSTOP;
2107 		mi_switch();
2108 		SCHED_UNLOCK();
2109 		mtx_enter(&pr->ps_mtx);
2110 	} while (pr->ps_single != NULL);
2111 
2112 	return (0);
2113 }
2114 
2115 int
2116 single_thread_check(struct proc *p, int deep)
2117 {
2118 	int error;
2119 
2120 	mtx_enter(&p->p_p->ps_mtx);
2121 	error = single_thread_check_locked(p, deep);
2122 	mtx_leave(&p->p_p->ps_mtx);
2123 
2124 	return error;
2125 }
2126 
2127 /*
2128  * Stop other threads in the process.  The mode controls how and
2129  * where the other threads should stop:
2130  *  - SINGLE_SUSPEND: stop wherever they are, will later be released (via
2131  *    single_thread_clear())
2132  *  - SINGLE_UNWIND: just unwind to kernel boundary, will be told to exit
2133  *    (by setting to SINGLE_EXIT) or released as with SINGLE_SUSPEND
2134  *  - SINGLE_EXIT: unwind to kernel boundary and exit
2135  */
2136 int
2137 single_thread_set(struct proc *p, int flags)
2138 {
2139 	struct process *pr = p->p_p;
2140 	struct proc *q;
2141 	int error, mode = flags & SINGLE_MASK;
2142 
2143 	KASSERT(curproc == p);
2144 
2145 	mtx_enter(&pr->ps_mtx);
2146 	error = single_thread_check_locked(p, flags & SINGLE_DEEP);
2147 	if (error) {
2148 		mtx_leave(&pr->ps_mtx);
2149 		return error;
2150 	}
2151 
2152 	switch (mode) {
2153 	case SINGLE_SUSPEND:
2154 		break;
2155 	case SINGLE_UNWIND:
2156 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2157 		break;
2158 	case SINGLE_EXIT:
2159 		atomic_setbits_int(&pr->ps_flags, PS_SINGLEEXIT);
2160 		atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND);
2161 		break;
2162 #ifdef DIAGNOSTIC
2163 	default:
2164 		panic("single_thread_mode = %d", mode);
2165 #endif
2166 	}
2167 	KASSERT((p->p_flag & P_SUSPSINGLE) == 0);
2168 	pr->ps_single = p;
2169 	pr->ps_singlecnt = pr->ps_threadcnt;
2170 
2171 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2172 		if (q == p)
2173 			continue;
2174 		SCHED_LOCK();
2175 		atomic_setbits_int(&q->p_flag, P_SUSPSINGLE);
2176 		switch (q->p_stat) {
2177 		case SSTOP:
2178 			if (mode == SINGLE_EXIT) {
2179 				unsleep(q);
2180 				setrunnable(q);
2181 			} else
2182 				--pr->ps_singlecnt;
2183 			break;
2184 		case SSLEEP:
2185 			/* if it's not interruptible, then just have to wait */
2186 			if (q->p_flag & P_SINTR) {
2187 				/* merely need to suspend?  just stop it */
2188 				if (mode == SINGLE_SUSPEND) {
2189 					q->p_stat = SSTOP;
2190 					--pr->ps_singlecnt;
2191 					break;
2192 				}
2193 				/* need to unwind or exit, so wake it */
2194 				unsleep(q);
2195 				setrunnable(q);
2196 			}
2197 			break;
2198 		case SONPROC:
2199 			signotify(q);
2200 			break;
2201 		case SRUN:
2202 		case SIDL:
2203 		case SDEAD:
2204 			break;
2205 		}
2206 		SCHED_UNLOCK();
2207 	}
2208 
2209 	/* count ourself out */
2210 	--pr->ps_singlecnt;
2211 	mtx_leave(&pr->ps_mtx);
2212 
2213 	if ((flags & SINGLE_NOWAIT) == 0)
2214 		single_thread_wait(pr, 1);
2215 
2216 	return 0;
2217 }
2218 
2219 /*
2220  * Wait for other threads to stop. If recheck is false then the function
2221  * returns non-zero if the caller needs to restart the check else 0 is
2222  * returned. If recheck is true the return value is always 0.
2223  */
2224 int
2225 single_thread_wait(struct process *pr, int recheck)
2226 {
2227 	int wait;
2228 
2229 	/* wait until they're all suspended */
2230 	mtx_enter(&pr->ps_mtx);
2231 	while ((wait = pr->ps_singlecnt > 0)) {
2232 		msleep_nsec(&pr->ps_singlecnt, &pr->ps_mtx, PWAIT, "suspend",
2233 		    INFSLP);
2234 		if (!recheck)
2235 			break;
2236 	}
2237 	KASSERT((pr->ps_single->p_flag & P_SUSPSINGLE) == 0);
2238 	mtx_leave(&pr->ps_mtx);
2239 
2240 	return wait;
2241 }
2242 
2243 void
2244 single_thread_clear(struct proc *p, int flag)
2245 {
2246 	struct process *pr = p->p_p;
2247 	struct proc *q;
2248 
2249 	KASSERT(pr->ps_single == p);
2250 	KASSERT(curproc == p);
2251 
2252 	mtx_enter(&pr->ps_mtx);
2253 	pr->ps_single = NULL;
2254 	atomic_clearbits_int(&pr->ps_flags, PS_SINGLEUNWIND | PS_SINGLEEXIT);
2255 
2256 	TAILQ_FOREACH(q, &pr->ps_threads, p_thr_link) {
2257 		if (q == p || (q->p_flag & P_SUSPSINGLE) == 0)
2258 			continue;
2259 		atomic_clearbits_int(&q->p_flag, P_SUSPSINGLE);
2260 
2261 		/*
2262 		 * if the thread was only stopped for single threading
2263 		 * then clearing that either makes it runnable or puts
2264 		 * it back into some sleep queue
2265 		 */
2266 		SCHED_LOCK();
2267 		if (q->p_stat == SSTOP && (q->p_flag & flag) == 0) {
2268 			if (q->p_wchan == NULL)
2269 				setrunnable(q);
2270 			else {
2271 				atomic_clearbits_int(&q->p_flag, P_WSLEEP);
2272 				q->p_stat = SSLEEP;
2273 			}
2274 		}
2275 		SCHED_UNLOCK();
2276 	}
2277 	mtx_leave(&pr->ps_mtx);
2278 }
2279 
2280 void
2281 sigio_del(struct sigiolst *rmlist)
2282 {
2283 	struct sigio *sigio;
2284 
2285 	while ((sigio = LIST_FIRST(rmlist)) != NULL) {
2286 		LIST_REMOVE(sigio, sio_pgsigio);
2287 		crfree(sigio->sio_ucred);
2288 		free(sigio, M_SIGIO, sizeof(*sigio));
2289 	}
2290 }
2291 
2292 void
2293 sigio_unlink(struct sigio_ref *sir, struct sigiolst *rmlist)
2294 {
2295 	struct sigio *sigio;
2296 
2297 	MUTEX_ASSERT_LOCKED(&sigio_lock);
2298 
2299 	sigio = sir->sir_sigio;
2300 	if (sigio != NULL) {
2301 		KASSERT(sigio->sio_myref == sir);
2302 		sir->sir_sigio = NULL;
2303 
2304 		if (sigio->sio_pgid > 0)
2305 			sigio->sio_proc = NULL;
2306 		else
2307 			sigio->sio_pgrp = NULL;
2308 		LIST_REMOVE(sigio, sio_pgsigio);
2309 
2310 		LIST_INSERT_HEAD(rmlist, sigio, sio_pgsigio);
2311 	}
2312 }
2313 
2314 void
2315 sigio_free(struct sigio_ref *sir)
2316 {
2317 	struct sigiolst rmlist;
2318 
2319 	if (sir->sir_sigio == NULL)
2320 		return;
2321 
2322 	LIST_INIT(&rmlist);
2323 
2324 	mtx_enter(&sigio_lock);
2325 	sigio_unlink(sir, &rmlist);
2326 	mtx_leave(&sigio_lock);
2327 
2328 	sigio_del(&rmlist);
2329 }
2330 
2331 void
2332 sigio_freelist(struct sigiolst *sigiolst)
2333 {
2334 	struct sigiolst rmlist;
2335 	struct sigio *sigio;
2336 
2337 	if (LIST_EMPTY(sigiolst))
2338 		return;
2339 
2340 	LIST_INIT(&rmlist);
2341 
2342 	mtx_enter(&sigio_lock);
2343 	while ((sigio = LIST_FIRST(sigiolst)) != NULL)
2344 		sigio_unlink(sigio->sio_myref, &rmlist);
2345 	mtx_leave(&sigio_lock);
2346 
2347 	sigio_del(&rmlist);
2348 }
2349 
2350 int
2351 sigio_setown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2352 {
2353 	struct sigiolst rmlist;
2354 	struct proc *p = curproc;
2355 	struct pgrp *pgrp = NULL;
2356 	struct process *pr = NULL;
2357 	struct sigio *sigio;
2358 	int error;
2359 	pid_t pgid = *(int *)data;
2360 
2361 	if (pgid == 0) {
2362 		sigio_free(sir);
2363 		return (0);
2364 	}
2365 
2366 	if (cmd == TIOCSPGRP) {
2367 		if (pgid < 0)
2368 			return (EINVAL);
2369 		pgid = -pgid;
2370 	}
2371 
2372 	sigio = malloc(sizeof(*sigio), M_SIGIO, M_WAITOK);
2373 	sigio->sio_pgid = pgid;
2374 	sigio->sio_ucred = crhold(p->p_ucred);
2375 	sigio->sio_myref = sir;
2376 
2377 	LIST_INIT(&rmlist);
2378 
2379 	/*
2380 	 * The kernel lock, and not sleeping between prfind()/pgfind() and
2381 	 * linking of the sigio ensure that the process or process group does
2382 	 * not disappear unexpectedly.
2383 	 */
2384 	KERNEL_LOCK();
2385 	mtx_enter(&sigio_lock);
2386 
2387 	if (pgid > 0) {
2388 		pr = prfind(pgid);
2389 		if (pr == NULL) {
2390 			error = ESRCH;
2391 			goto fail;
2392 		}
2393 
2394 		/*
2395 		 * Policy - Don't allow a process to FSETOWN a process
2396 		 * in another session.
2397 		 *
2398 		 * Remove this test to allow maximum flexibility or
2399 		 * restrict FSETOWN to the current process or process
2400 		 * group for maximum safety.
2401 		 */
2402 		if (pr->ps_session != p->p_p->ps_session) {
2403 			error = EPERM;
2404 			goto fail;
2405 		}
2406 
2407 		if ((pr->ps_flags & PS_EXITING) != 0) {
2408 			error = ESRCH;
2409 			goto fail;
2410 		}
2411 	} else /* if (pgid < 0) */ {
2412 		pgrp = pgfind(-pgid);
2413 		if (pgrp == NULL) {
2414 			error = ESRCH;
2415 			goto fail;
2416 		}
2417 
2418 		/*
2419 		 * Policy - Don't allow a process to FSETOWN a process
2420 		 * in another session.
2421 		 *
2422 		 * Remove this test to allow maximum flexibility or
2423 		 * restrict FSETOWN to the current process or process
2424 		 * group for maximum safety.
2425 		 */
2426 		if (pgrp->pg_session != p->p_p->ps_session) {
2427 			error = EPERM;
2428 			goto fail;
2429 		}
2430 	}
2431 
2432 	if (pgid > 0) {
2433 		sigio->sio_proc = pr;
2434 		LIST_INSERT_HEAD(&pr->ps_sigiolst, sigio, sio_pgsigio);
2435 	} else {
2436 		sigio->sio_pgrp = pgrp;
2437 		LIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
2438 	}
2439 
2440 	sigio_unlink(sir, &rmlist);
2441 	sir->sir_sigio = sigio;
2442 
2443 	mtx_leave(&sigio_lock);
2444 	KERNEL_UNLOCK();
2445 
2446 	sigio_del(&rmlist);
2447 
2448 	return (0);
2449 
2450 fail:
2451 	mtx_leave(&sigio_lock);
2452 	KERNEL_UNLOCK();
2453 
2454 	crfree(sigio->sio_ucred);
2455 	free(sigio, M_SIGIO, sizeof(*sigio));
2456 
2457 	return (error);
2458 }
2459 
2460 void
2461 sigio_getown(struct sigio_ref *sir, u_long cmd, caddr_t data)
2462 {
2463 	struct sigio *sigio;
2464 	pid_t pgid = 0;
2465 
2466 	mtx_enter(&sigio_lock);
2467 	sigio = sir->sir_sigio;
2468 	if (sigio != NULL)
2469 		pgid = sigio->sio_pgid;
2470 	mtx_leave(&sigio_lock);
2471 
2472 	if (cmd == TIOCGPGRP)
2473 		pgid = -pgid;
2474 
2475 	*(int *)data = pgid;
2476 }
2477 
2478 void
2479 sigio_copy(struct sigio_ref *dst, struct sigio_ref *src)
2480 {
2481 	struct sigiolst rmlist;
2482 	struct sigio *newsigio, *sigio;
2483 
2484 	sigio_free(dst);
2485 
2486 	if (src->sir_sigio == NULL)
2487 		return;
2488 
2489 	newsigio = malloc(sizeof(*newsigio), M_SIGIO, M_WAITOK);
2490 	LIST_INIT(&rmlist);
2491 
2492 	mtx_enter(&sigio_lock);
2493 
2494 	sigio = src->sir_sigio;
2495 	if (sigio == NULL) {
2496 		mtx_leave(&sigio_lock);
2497 		free(newsigio, M_SIGIO, sizeof(*newsigio));
2498 		return;
2499 	}
2500 
2501 	newsigio->sio_pgid = sigio->sio_pgid;
2502 	newsigio->sio_ucred = crhold(sigio->sio_ucred);
2503 	newsigio->sio_myref = dst;
2504 	if (newsigio->sio_pgid > 0) {
2505 		newsigio->sio_proc = sigio->sio_proc;
2506 		LIST_INSERT_HEAD(&newsigio->sio_proc->ps_sigiolst, newsigio,
2507 		    sio_pgsigio);
2508 	} else {
2509 		newsigio->sio_pgrp = sigio->sio_pgrp;
2510 		LIST_INSERT_HEAD(&newsigio->sio_pgrp->pg_sigiolst, newsigio,
2511 		    sio_pgsigio);
2512 	}
2513 
2514 	sigio_unlink(dst, &rmlist);
2515 	dst->sir_sigio = newsigio;
2516 
2517 	mtx_leave(&sigio_lock);
2518 
2519 	sigio_del(&rmlist);
2520 }
2521