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