xref: /freebsd/sys/kern/kern_sig.c (revision 2f513db7)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/ctype.h>
46 #include <sys/systm.h>
47 #include <sys/signalvar.h>
48 #include <sys/vnode.h>
49 #include <sys/acct.h>
50 #include <sys/bus.h>
51 #include <sys/capsicum.h>
52 #include <sys/compressor.h>
53 #include <sys/condvar.h>
54 #include <sys/event.h>
55 #include <sys/fcntl.h>
56 #include <sys/imgact.h>
57 #include <sys/kernel.h>
58 #include <sys/ktr.h>
59 #include <sys/ktrace.h>
60 #include <sys/limits.h>
61 #include <sys/lock.h>
62 #include <sys/malloc.h>
63 #include <sys/mutex.h>
64 #include <sys/refcount.h>
65 #include <sys/namei.h>
66 #include <sys/proc.h>
67 #include <sys/procdesc.h>
68 #include <sys/ptrace.h>
69 #include <sys/posix4.h>
70 #include <sys/pioctl.h>
71 #include <sys/racct.h>
72 #include <sys/resourcevar.h>
73 #include <sys/sdt.h>
74 #include <sys/sbuf.h>
75 #include <sys/sleepqueue.h>
76 #include <sys/smp.h>
77 #include <sys/stat.h>
78 #include <sys/sx.h>
79 #include <sys/syscallsubr.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysent.h>
82 #include <sys/syslog.h>
83 #include <sys/sysproto.h>
84 #include <sys/timers.h>
85 #include <sys/unistd.h>
86 #include <sys/wait.h>
87 #include <vm/vm.h>
88 #include <vm/vm_extern.h>
89 #include <vm/uma.h>
90 
91 #include <sys/jail.h>
92 
93 #include <machine/cpu.h>
94 
95 #include <security/audit/audit.h>
96 
97 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
98 
99 SDT_PROVIDER_DECLARE(proc);
100 SDT_PROBE_DEFINE3(proc, , , signal__send,
101     "struct thread *", "struct proc *", "int");
102 SDT_PROBE_DEFINE2(proc, , , signal__clear,
103     "int", "ksiginfo_t *");
104 SDT_PROBE_DEFINE3(proc, , , signal__discard,
105     "struct thread *", "struct proc *", "int");
106 
107 static int	coredump(struct thread *);
108 static int	killpg1(struct thread *td, int sig, int pgid, int all,
109 		    ksiginfo_t *ksi);
110 static int	issignal(struct thread *td);
111 static int	sigprop(int sig);
112 static void	tdsigwakeup(struct thread *, int, sig_t, int);
113 static int	sig_suspend_threads(struct thread *, struct proc *, int);
114 static int	filt_sigattach(struct knote *kn);
115 static void	filt_sigdetach(struct knote *kn);
116 static int	filt_signal(struct knote *kn, long hint);
117 static struct thread *sigtd(struct proc *p, int sig, bool fast_sigblock);
118 static void	sigqueue_start(void);
119 
120 static uma_zone_t	ksiginfo_zone = NULL;
121 struct filterops sig_filtops = {
122 	.f_isfd = 0,
123 	.f_attach = filt_sigattach,
124 	.f_detach = filt_sigdetach,
125 	.f_event = filt_signal,
126 };
127 
128 static int	kern_logsigexit = 1;
129 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
130     &kern_logsigexit, 0,
131     "Log processes quitting on abnormal signals to syslog(3)");
132 
133 static int	kern_forcesigexit = 1;
134 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
135     &kern_forcesigexit, 0, "Force trap signal to be handled");
136 
137 static SYSCTL_NODE(_kern, OID_AUTO, sigqueue, CTLFLAG_RW, 0,
138     "POSIX real time signal");
139 
140 static int	max_pending_per_proc = 128;
141 SYSCTL_INT(_kern_sigqueue, OID_AUTO, max_pending_per_proc, CTLFLAG_RW,
142     &max_pending_per_proc, 0, "Max pending signals per proc");
143 
144 static int	preallocate_siginfo = 1024;
145 SYSCTL_INT(_kern_sigqueue, OID_AUTO, preallocate, CTLFLAG_RDTUN,
146     &preallocate_siginfo, 0, "Preallocated signal memory size");
147 
148 static int	signal_overflow = 0;
149 SYSCTL_INT(_kern_sigqueue, OID_AUTO, overflow, CTLFLAG_RD,
150     &signal_overflow, 0, "Number of signals overflew");
151 
152 static int	signal_alloc_fail = 0;
153 SYSCTL_INT(_kern_sigqueue, OID_AUTO, alloc_fail, CTLFLAG_RD,
154     &signal_alloc_fail, 0, "signals failed to be allocated");
155 
156 static int	kern_lognosys = 0;
157 SYSCTL_INT(_kern, OID_AUTO, lognosys, CTLFLAG_RWTUN, &kern_lognosys, 0,
158     "Log invalid syscalls");
159 
160 SYSINIT(signal, SI_SUB_P1003_1B, SI_ORDER_FIRST+3, sigqueue_start, NULL);
161 
162 /*
163  * Policy -- Can ucred cr1 send SIGIO to process cr2?
164  * Should use cr_cansignal() once cr_cansignal() allows SIGIO and SIGURG
165  * in the right situations.
166  */
167 #define CANSIGIO(cr1, cr2) \
168 	((cr1)->cr_uid == 0 || \
169 	    (cr1)->cr_ruid == (cr2)->cr_ruid || \
170 	    (cr1)->cr_uid == (cr2)->cr_ruid || \
171 	    (cr1)->cr_ruid == (cr2)->cr_uid || \
172 	    (cr1)->cr_uid == (cr2)->cr_uid)
173 
174 static int	sugid_coredump;
175 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RWTUN,
176     &sugid_coredump, 0, "Allow setuid and setgid processes to dump core");
177 
178 static int	capmode_coredump;
179 SYSCTL_INT(_kern, OID_AUTO, capmode_coredump, CTLFLAG_RWTUN,
180     &capmode_coredump, 0, "Allow processes in capability mode to dump core");
181 
182 static int	do_coredump = 1;
183 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
184 	&do_coredump, 0, "Enable/Disable coredumps");
185 
186 static int	set_core_nodump_flag = 0;
187 SYSCTL_INT(_kern, OID_AUTO, nodump_coredump, CTLFLAG_RW, &set_core_nodump_flag,
188 	0, "Enable setting the NODUMP flag on coredump files");
189 
190 static int	coredump_devctl = 0;
191 SYSCTL_INT(_kern, OID_AUTO, coredump_devctl, CTLFLAG_RW, &coredump_devctl,
192 	0, "Generate a devctl notification when processes coredump");
193 
194 /*
195  * Signal properties and actions.
196  * The array below categorizes the signals and their default actions
197  * according to the following properties:
198  */
199 #define	SIGPROP_KILL		0x01	/* terminates process by default */
200 #define	SIGPROP_CORE		0x02	/* ditto and coredumps */
201 #define	SIGPROP_STOP		0x04	/* suspend process */
202 #define	SIGPROP_TTYSTOP		0x08	/* ditto, from tty */
203 #define	SIGPROP_IGNORE		0x10	/* ignore by default */
204 #define	SIGPROP_CONT		0x20	/* continue if suspended */
205 #define	SIGPROP_CANTMASK	0x40	/* non-maskable, catchable */
206 
207 static int sigproptbl[NSIG] = {
208 	[SIGHUP] =	SIGPROP_KILL,
209 	[SIGINT] =	SIGPROP_KILL,
210 	[SIGQUIT] =	SIGPROP_KILL | SIGPROP_CORE,
211 	[SIGILL] =	SIGPROP_KILL | SIGPROP_CORE,
212 	[SIGTRAP] =	SIGPROP_KILL | SIGPROP_CORE,
213 	[SIGABRT] =	SIGPROP_KILL | SIGPROP_CORE,
214 	[SIGEMT] =	SIGPROP_KILL | SIGPROP_CORE,
215 	[SIGFPE] =	SIGPROP_KILL | SIGPROP_CORE,
216 	[SIGKILL] =	SIGPROP_KILL,
217 	[SIGBUS] =	SIGPROP_KILL | SIGPROP_CORE,
218 	[SIGSEGV] =	SIGPROP_KILL | SIGPROP_CORE,
219 	[SIGSYS] =	SIGPROP_KILL | SIGPROP_CORE,
220 	[SIGPIPE] =	SIGPROP_KILL,
221 	[SIGALRM] =	SIGPROP_KILL,
222 	[SIGTERM] =	SIGPROP_KILL,
223 	[SIGURG] =	SIGPROP_IGNORE,
224 	[SIGSTOP] =	SIGPROP_STOP,
225 	[SIGTSTP] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
226 	[SIGCONT] =	SIGPROP_IGNORE | SIGPROP_CONT,
227 	[SIGCHLD] =	SIGPROP_IGNORE,
228 	[SIGTTIN] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
229 	[SIGTTOU] =	SIGPROP_STOP | SIGPROP_TTYSTOP,
230 	[SIGIO] =	SIGPROP_IGNORE,
231 	[SIGXCPU] =	SIGPROP_KILL,
232 	[SIGXFSZ] =	SIGPROP_KILL,
233 	[SIGVTALRM] =	SIGPROP_KILL,
234 	[SIGPROF] =	SIGPROP_KILL,
235 	[SIGWINCH] =	SIGPROP_IGNORE,
236 	[SIGINFO] =	SIGPROP_IGNORE,
237 	[SIGUSR1] =	SIGPROP_KILL,
238 	[SIGUSR2] =	SIGPROP_KILL,
239 };
240 
241 sigset_t fastblock_mask;
242 
243 static void
244 sigqueue_start(void)
245 {
246 	ksiginfo_zone = uma_zcreate("ksiginfo", sizeof(ksiginfo_t),
247 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
248 	uma_prealloc(ksiginfo_zone, preallocate_siginfo);
249 	p31b_setcfg(CTL_P1003_1B_REALTIME_SIGNALS, _POSIX_REALTIME_SIGNALS);
250 	p31b_setcfg(CTL_P1003_1B_RTSIG_MAX, SIGRTMAX - SIGRTMIN + 1);
251 	p31b_setcfg(CTL_P1003_1B_SIGQUEUE_MAX, max_pending_per_proc);
252 	SIGFILLSET(fastblock_mask);
253 	SIG_CANTMASK(fastblock_mask);
254 }
255 
256 ksiginfo_t *
257 ksiginfo_alloc(int wait)
258 {
259 	int flags;
260 
261 	flags = M_ZERO;
262 	if (! wait)
263 		flags |= M_NOWAIT;
264 	if (ksiginfo_zone != NULL)
265 		return ((ksiginfo_t *)uma_zalloc(ksiginfo_zone, flags));
266 	return (NULL);
267 }
268 
269 void
270 ksiginfo_free(ksiginfo_t *ksi)
271 {
272 	uma_zfree(ksiginfo_zone, ksi);
273 }
274 
275 static __inline int
276 ksiginfo_tryfree(ksiginfo_t *ksi)
277 {
278 	if (!(ksi->ksi_flags & KSI_EXT)) {
279 		uma_zfree(ksiginfo_zone, ksi);
280 		return (1);
281 	}
282 	return (0);
283 }
284 
285 void
286 sigqueue_init(sigqueue_t *list, struct proc *p)
287 {
288 	SIGEMPTYSET(list->sq_signals);
289 	SIGEMPTYSET(list->sq_kill);
290 	SIGEMPTYSET(list->sq_ptrace);
291 	TAILQ_INIT(&list->sq_list);
292 	list->sq_proc = p;
293 	list->sq_flags = SQ_INIT;
294 }
295 
296 /*
297  * Get a signal's ksiginfo.
298  * Return:
299  *	0	-	signal not found
300  *	others	-	signal number
301  */
302 static int
303 sigqueue_get(sigqueue_t *sq, int signo, ksiginfo_t *si)
304 {
305 	struct proc *p = sq->sq_proc;
306 	struct ksiginfo *ksi, *next;
307 	int count = 0;
308 
309 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
310 
311 	if (!SIGISMEMBER(sq->sq_signals, signo))
312 		return (0);
313 
314 	if (SIGISMEMBER(sq->sq_ptrace, signo)) {
315 		count++;
316 		SIGDELSET(sq->sq_ptrace, signo);
317 		si->ksi_flags |= KSI_PTRACE;
318 	}
319 	if (SIGISMEMBER(sq->sq_kill, signo)) {
320 		count++;
321 		if (count == 1)
322 			SIGDELSET(sq->sq_kill, signo);
323 	}
324 
325 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
326 		if (ksi->ksi_signo == signo) {
327 			if (count == 0) {
328 				TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
329 				ksi->ksi_sigq = NULL;
330 				ksiginfo_copy(ksi, si);
331 				if (ksiginfo_tryfree(ksi) && p != NULL)
332 					p->p_pendingcnt--;
333 			}
334 			if (++count > 1)
335 				break;
336 		}
337 	}
338 
339 	if (count <= 1)
340 		SIGDELSET(sq->sq_signals, signo);
341 	si->ksi_signo = signo;
342 	return (signo);
343 }
344 
345 void
346 sigqueue_take(ksiginfo_t *ksi)
347 {
348 	struct ksiginfo *kp;
349 	struct proc	*p;
350 	sigqueue_t	*sq;
351 
352 	if (ksi == NULL || (sq = ksi->ksi_sigq) == NULL)
353 		return;
354 
355 	p = sq->sq_proc;
356 	TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
357 	ksi->ksi_sigq = NULL;
358 	if (!(ksi->ksi_flags & KSI_EXT) && p != NULL)
359 		p->p_pendingcnt--;
360 
361 	for (kp = TAILQ_FIRST(&sq->sq_list); kp != NULL;
362 	     kp = TAILQ_NEXT(kp, ksi_link)) {
363 		if (kp->ksi_signo == ksi->ksi_signo)
364 			break;
365 	}
366 	if (kp == NULL && !SIGISMEMBER(sq->sq_kill, ksi->ksi_signo) &&
367 	    !SIGISMEMBER(sq->sq_ptrace, ksi->ksi_signo))
368 		SIGDELSET(sq->sq_signals, ksi->ksi_signo);
369 }
370 
371 static int
372 sigqueue_add(sigqueue_t *sq, int signo, ksiginfo_t *si)
373 {
374 	struct proc *p = sq->sq_proc;
375 	struct ksiginfo *ksi;
376 	int ret = 0;
377 
378 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
379 
380 	/*
381 	 * SIGKILL/SIGSTOP cannot be caught or masked, so take the fast path
382 	 * for these signals.
383 	 */
384 	if (signo == SIGKILL || signo == SIGSTOP || si == NULL) {
385 		SIGADDSET(sq->sq_kill, signo);
386 		goto out_set_bit;
387 	}
388 
389 	/* directly insert the ksi, don't copy it */
390 	if (si->ksi_flags & KSI_INS) {
391 		if (si->ksi_flags & KSI_HEAD)
392 			TAILQ_INSERT_HEAD(&sq->sq_list, si, ksi_link);
393 		else
394 			TAILQ_INSERT_TAIL(&sq->sq_list, si, ksi_link);
395 		si->ksi_sigq = sq;
396 		goto out_set_bit;
397 	}
398 
399 	if (__predict_false(ksiginfo_zone == NULL)) {
400 		SIGADDSET(sq->sq_kill, signo);
401 		goto out_set_bit;
402 	}
403 
404 	if (p != NULL && p->p_pendingcnt >= max_pending_per_proc) {
405 		signal_overflow++;
406 		ret = EAGAIN;
407 	} else if ((ksi = ksiginfo_alloc(0)) == NULL) {
408 		signal_alloc_fail++;
409 		ret = EAGAIN;
410 	} else {
411 		if (p != NULL)
412 			p->p_pendingcnt++;
413 		ksiginfo_copy(si, ksi);
414 		ksi->ksi_signo = signo;
415 		if (si->ksi_flags & KSI_HEAD)
416 			TAILQ_INSERT_HEAD(&sq->sq_list, ksi, ksi_link);
417 		else
418 			TAILQ_INSERT_TAIL(&sq->sq_list, ksi, ksi_link);
419 		ksi->ksi_sigq = sq;
420 	}
421 
422 	if (ret != 0) {
423 		if ((si->ksi_flags & KSI_PTRACE) != 0) {
424 			SIGADDSET(sq->sq_ptrace, signo);
425 			ret = 0;
426 			goto out_set_bit;
427 		} else if ((si->ksi_flags & KSI_TRAP) != 0 ||
428 		    (si->ksi_flags & KSI_SIGQ) == 0) {
429 			SIGADDSET(sq->sq_kill, signo);
430 			ret = 0;
431 			goto out_set_bit;
432 		}
433 		return (ret);
434 	}
435 
436 out_set_bit:
437 	SIGADDSET(sq->sq_signals, signo);
438 	return (ret);
439 }
440 
441 void
442 sigqueue_flush(sigqueue_t *sq)
443 {
444 	struct proc *p = sq->sq_proc;
445 	ksiginfo_t *ksi;
446 
447 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
448 
449 	if (p != NULL)
450 		PROC_LOCK_ASSERT(p, MA_OWNED);
451 
452 	while ((ksi = TAILQ_FIRST(&sq->sq_list)) != NULL) {
453 		TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
454 		ksi->ksi_sigq = NULL;
455 		if (ksiginfo_tryfree(ksi) && p != NULL)
456 			p->p_pendingcnt--;
457 	}
458 
459 	SIGEMPTYSET(sq->sq_signals);
460 	SIGEMPTYSET(sq->sq_kill);
461 	SIGEMPTYSET(sq->sq_ptrace);
462 }
463 
464 static void
465 sigqueue_move_set(sigqueue_t *src, sigqueue_t *dst, const sigset_t *set)
466 {
467 	sigset_t tmp;
468 	struct proc *p1, *p2;
469 	ksiginfo_t *ksi, *next;
470 
471 	KASSERT(src->sq_flags & SQ_INIT, ("src sigqueue not inited"));
472 	KASSERT(dst->sq_flags & SQ_INIT, ("dst sigqueue not inited"));
473 	p1 = src->sq_proc;
474 	p2 = dst->sq_proc;
475 	/* Move siginfo to target list */
476 	TAILQ_FOREACH_SAFE(ksi, &src->sq_list, ksi_link, next) {
477 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
478 			TAILQ_REMOVE(&src->sq_list, ksi, ksi_link);
479 			if (p1 != NULL)
480 				p1->p_pendingcnt--;
481 			TAILQ_INSERT_TAIL(&dst->sq_list, ksi, ksi_link);
482 			ksi->ksi_sigq = dst;
483 			if (p2 != NULL)
484 				p2->p_pendingcnt++;
485 		}
486 	}
487 
488 	/* Move pending bits to target list */
489 	tmp = src->sq_kill;
490 	SIGSETAND(tmp, *set);
491 	SIGSETOR(dst->sq_kill, tmp);
492 	SIGSETNAND(src->sq_kill, tmp);
493 
494 	tmp = src->sq_ptrace;
495 	SIGSETAND(tmp, *set);
496 	SIGSETOR(dst->sq_ptrace, tmp);
497 	SIGSETNAND(src->sq_ptrace, tmp);
498 
499 	tmp = src->sq_signals;
500 	SIGSETAND(tmp, *set);
501 	SIGSETOR(dst->sq_signals, tmp);
502 	SIGSETNAND(src->sq_signals, tmp);
503 }
504 
505 #if 0
506 static void
507 sigqueue_move(sigqueue_t *src, sigqueue_t *dst, int signo)
508 {
509 	sigset_t set;
510 
511 	SIGEMPTYSET(set);
512 	SIGADDSET(set, signo);
513 	sigqueue_move_set(src, dst, &set);
514 }
515 #endif
516 
517 static void
518 sigqueue_delete_set(sigqueue_t *sq, const sigset_t *set)
519 {
520 	struct proc *p = sq->sq_proc;
521 	ksiginfo_t *ksi, *next;
522 
523 	KASSERT(sq->sq_flags & SQ_INIT, ("src sigqueue not inited"));
524 
525 	/* Remove siginfo queue */
526 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
527 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
528 			TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
529 			ksi->ksi_sigq = NULL;
530 			if (ksiginfo_tryfree(ksi) && p != NULL)
531 				p->p_pendingcnt--;
532 		}
533 	}
534 	SIGSETNAND(sq->sq_kill, *set);
535 	SIGSETNAND(sq->sq_ptrace, *set);
536 	SIGSETNAND(sq->sq_signals, *set);
537 }
538 
539 void
540 sigqueue_delete(sigqueue_t *sq, int signo)
541 {
542 	sigset_t set;
543 
544 	SIGEMPTYSET(set);
545 	SIGADDSET(set, signo);
546 	sigqueue_delete_set(sq, &set);
547 }
548 
549 /* Remove a set of signals for a process */
550 static void
551 sigqueue_delete_set_proc(struct proc *p, const sigset_t *set)
552 {
553 	sigqueue_t worklist;
554 	struct thread *td0;
555 
556 	PROC_LOCK_ASSERT(p, MA_OWNED);
557 
558 	sigqueue_init(&worklist, NULL);
559 	sigqueue_move_set(&p->p_sigqueue, &worklist, set);
560 
561 	FOREACH_THREAD_IN_PROC(p, td0)
562 		sigqueue_move_set(&td0->td_sigqueue, &worklist, set);
563 
564 	sigqueue_flush(&worklist);
565 }
566 
567 void
568 sigqueue_delete_proc(struct proc *p, int signo)
569 {
570 	sigset_t set;
571 
572 	SIGEMPTYSET(set);
573 	SIGADDSET(set, signo);
574 	sigqueue_delete_set_proc(p, &set);
575 }
576 
577 static void
578 sigqueue_delete_stopmask_proc(struct proc *p)
579 {
580 	sigset_t set;
581 
582 	SIGEMPTYSET(set);
583 	SIGADDSET(set, SIGSTOP);
584 	SIGADDSET(set, SIGTSTP);
585 	SIGADDSET(set, SIGTTIN);
586 	SIGADDSET(set, SIGTTOU);
587 	sigqueue_delete_set_proc(p, &set);
588 }
589 
590 /*
591  * Determine signal that should be delivered to thread td, the current
592  * thread, 0 if none.  If there is a pending stop signal with default
593  * action, the process stops in issignal().
594  */
595 int
596 cursig(struct thread *td)
597 {
598 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
599 	mtx_assert(&td->td_proc->p_sigacts->ps_mtx, MA_OWNED);
600 	THREAD_LOCK_ASSERT(td, MA_NOTOWNED);
601 	return (SIGPENDING(td) ? issignal(td) : 0);
602 }
603 
604 /*
605  * Arrange for ast() to handle unmasked pending signals on return to user
606  * mode.  This must be called whenever a signal is added to td_sigqueue or
607  * unmasked in td_sigmask.
608  */
609 void
610 signotify(struct thread *td)
611 {
612 
613 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
614 
615 	if (SIGPENDING(td)) {
616 		thread_lock(td);
617 		td->td_flags |= TDF_NEEDSIGCHK | TDF_ASTPENDING;
618 		thread_unlock(td);
619 	}
620 }
621 
622 /*
623  * Returns 1 (true) if altstack is configured for the thread, and the
624  * passed stack bottom address falls into the altstack range.  Handles
625  * the 43 compat special case where the alt stack size is zero.
626  */
627 int
628 sigonstack(size_t sp)
629 {
630 	struct thread *td;
631 
632 	td = curthread;
633 	if ((td->td_pflags & TDP_ALTSTACK) == 0)
634 		return (0);
635 #if defined(COMPAT_43)
636 	if (SV_PROC_FLAG(td->td_proc, SV_AOUT) && td->td_sigstk.ss_size == 0)
637 		return ((td->td_sigstk.ss_flags & SS_ONSTACK) != 0);
638 #endif
639 	return (sp >= (size_t)td->td_sigstk.ss_sp &&
640 	    sp < td->td_sigstk.ss_size + (size_t)td->td_sigstk.ss_sp);
641 }
642 
643 static __inline int
644 sigprop(int sig)
645 {
646 
647 	if (sig > 0 && sig < nitems(sigproptbl))
648 		return (sigproptbl[sig]);
649 	return (0);
650 }
651 
652 int
653 sig_ffs(sigset_t *set)
654 {
655 	int i;
656 
657 	for (i = 0; i < _SIG_WORDS; i++)
658 		if (set->__bits[i])
659 			return (ffs(set->__bits[i]) + (i * 32));
660 	return (0);
661 }
662 
663 static bool
664 sigact_flag_test(const struct sigaction *act, int flag)
665 {
666 
667 	/*
668 	 * SA_SIGINFO is reset when signal disposition is set to
669 	 * ignore or default.  Other flags are kept according to user
670 	 * settings.
671 	 */
672 	return ((act->sa_flags & flag) != 0 && (flag != SA_SIGINFO ||
673 	    ((__sighandler_t *)act->sa_sigaction != SIG_IGN &&
674 	    (__sighandler_t *)act->sa_sigaction != SIG_DFL)));
675 }
676 
677 /*
678  * kern_sigaction
679  * sigaction
680  * freebsd4_sigaction
681  * osigaction
682  */
683 int
684 kern_sigaction(struct thread *td, int sig, const struct sigaction *act,
685     struct sigaction *oact, int flags)
686 {
687 	struct sigacts *ps;
688 	struct proc *p = td->td_proc;
689 
690 	if (!_SIG_VALID(sig))
691 		return (EINVAL);
692 	if (act != NULL && act->sa_handler != SIG_DFL &&
693 	    act->sa_handler != SIG_IGN && (act->sa_flags & ~(SA_ONSTACK |
694 	    SA_RESTART | SA_RESETHAND | SA_NOCLDSTOP | SA_NODEFER |
695 	    SA_NOCLDWAIT | SA_SIGINFO)) != 0)
696 		return (EINVAL);
697 
698 	PROC_LOCK(p);
699 	ps = p->p_sigacts;
700 	mtx_lock(&ps->ps_mtx);
701 	if (oact) {
702 		memset(oact, 0, sizeof(*oact));
703 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
704 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
705 			oact->sa_flags |= SA_ONSTACK;
706 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
707 			oact->sa_flags |= SA_RESTART;
708 		if (SIGISMEMBER(ps->ps_sigreset, sig))
709 			oact->sa_flags |= SA_RESETHAND;
710 		if (SIGISMEMBER(ps->ps_signodefer, sig))
711 			oact->sa_flags |= SA_NODEFER;
712 		if (SIGISMEMBER(ps->ps_siginfo, sig)) {
713 			oact->sa_flags |= SA_SIGINFO;
714 			oact->sa_sigaction =
715 			    (__siginfohandler_t *)ps->ps_sigact[_SIG_IDX(sig)];
716 		} else
717 			oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
718 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDSTOP)
719 			oact->sa_flags |= SA_NOCLDSTOP;
720 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDWAIT)
721 			oact->sa_flags |= SA_NOCLDWAIT;
722 	}
723 	if (act) {
724 		if ((sig == SIGKILL || sig == SIGSTOP) &&
725 		    act->sa_handler != SIG_DFL) {
726 			mtx_unlock(&ps->ps_mtx);
727 			PROC_UNLOCK(p);
728 			return (EINVAL);
729 		}
730 
731 		/*
732 		 * Change setting atomically.
733 		 */
734 
735 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
736 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
737 		if (sigact_flag_test(act, SA_SIGINFO)) {
738 			ps->ps_sigact[_SIG_IDX(sig)] =
739 			    (__sighandler_t *)act->sa_sigaction;
740 			SIGADDSET(ps->ps_siginfo, sig);
741 		} else {
742 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
743 			SIGDELSET(ps->ps_siginfo, sig);
744 		}
745 		if (!sigact_flag_test(act, SA_RESTART))
746 			SIGADDSET(ps->ps_sigintr, sig);
747 		else
748 			SIGDELSET(ps->ps_sigintr, sig);
749 		if (sigact_flag_test(act, SA_ONSTACK))
750 			SIGADDSET(ps->ps_sigonstack, sig);
751 		else
752 			SIGDELSET(ps->ps_sigonstack, sig);
753 		if (sigact_flag_test(act, SA_RESETHAND))
754 			SIGADDSET(ps->ps_sigreset, sig);
755 		else
756 			SIGDELSET(ps->ps_sigreset, sig);
757 		if (sigact_flag_test(act, SA_NODEFER))
758 			SIGADDSET(ps->ps_signodefer, sig);
759 		else
760 			SIGDELSET(ps->ps_signodefer, sig);
761 		if (sig == SIGCHLD) {
762 			if (act->sa_flags & SA_NOCLDSTOP)
763 				ps->ps_flag |= PS_NOCLDSTOP;
764 			else
765 				ps->ps_flag &= ~PS_NOCLDSTOP;
766 			if (act->sa_flags & SA_NOCLDWAIT) {
767 				/*
768 				 * Paranoia: since SA_NOCLDWAIT is implemented
769 				 * by reparenting the dying child to PID 1 (and
770 				 * trust it to reap the zombie), PID 1 itself
771 				 * is forbidden to set SA_NOCLDWAIT.
772 				 */
773 				if (p->p_pid == 1)
774 					ps->ps_flag &= ~PS_NOCLDWAIT;
775 				else
776 					ps->ps_flag |= PS_NOCLDWAIT;
777 			} else
778 				ps->ps_flag &= ~PS_NOCLDWAIT;
779 			if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
780 				ps->ps_flag |= PS_CLDSIGIGN;
781 			else
782 				ps->ps_flag &= ~PS_CLDSIGIGN;
783 		}
784 		/*
785 		 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
786 		 * and for signals set to SIG_DFL where the default is to
787 		 * ignore. However, don't put SIGCONT in ps_sigignore, as we
788 		 * have to restart the process.
789 		 */
790 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
791 		    (sigprop(sig) & SIGPROP_IGNORE &&
792 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
793 			/* never to be seen again */
794 			sigqueue_delete_proc(p, sig);
795 			if (sig != SIGCONT)
796 				/* easier in psignal */
797 				SIGADDSET(ps->ps_sigignore, sig);
798 			SIGDELSET(ps->ps_sigcatch, sig);
799 		} else {
800 			SIGDELSET(ps->ps_sigignore, sig);
801 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
802 				SIGDELSET(ps->ps_sigcatch, sig);
803 			else
804 				SIGADDSET(ps->ps_sigcatch, sig);
805 		}
806 #ifdef COMPAT_FREEBSD4
807 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
808 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
809 		    (flags & KSA_FREEBSD4) == 0)
810 			SIGDELSET(ps->ps_freebsd4, sig);
811 		else
812 			SIGADDSET(ps->ps_freebsd4, sig);
813 #endif
814 #ifdef COMPAT_43
815 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
816 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
817 		    (flags & KSA_OSIGSET) == 0)
818 			SIGDELSET(ps->ps_osigset, sig);
819 		else
820 			SIGADDSET(ps->ps_osigset, sig);
821 #endif
822 	}
823 	mtx_unlock(&ps->ps_mtx);
824 	PROC_UNLOCK(p);
825 	return (0);
826 }
827 
828 #ifndef _SYS_SYSPROTO_H_
829 struct sigaction_args {
830 	int	sig;
831 	struct	sigaction *act;
832 	struct	sigaction *oact;
833 };
834 #endif
835 int
836 sys_sigaction(struct thread *td, struct sigaction_args *uap)
837 {
838 	struct sigaction act, oact;
839 	struct sigaction *actp, *oactp;
840 	int error;
841 
842 	actp = (uap->act != NULL) ? &act : NULL;
843 	oactp = (uap->oact != NULL) ? &oact : NULL;
844 	if (actp) {
845 		error = copyin(uap->act, actp, sizeof(act));
846 		if (error)
847 			return (error);
848 	}
849 	error = kern_sigaction(td, uap->sig, actp, oactp, 0);
850 	if (oactp && !error)
851 		error = copyout(oactp, uap->oact, sizeof(oact));
852 	return (error);
853 }
854 
855 #ifdef COMPAT_FREEBSD4
856 #ifndef _SYS_SYSPROTO_H_
857 struct freebsd4_sigaction_args {
858 	int	sig;
859 	struct	sigaction *act;
860 	struct	sigaction *oact;
861 };
862 #endif
863 int
864 freebsd4_sigaction(struct thread *td, struct freebsd4_sigaction_args *uap)
865 {
866 	struct sigaction act, oact;
867 	struct sigaction *actp, *oactp;
868 	int error;
869 
870 	actp = (uap->act != NULL) ? &act : NULL;
871 	oactp = (uap->oact != NULL) ? &oact : NULL;
872 	if (actp) {
873 		error = copyin(uap->act, actp, sizeof(act));
874 		if (error)
875 			return (error);
876 	}
877 	error = kern_sigaction(td, uap->sig, actp, oactp, KSA_FREEBSD4);
878 	if (oactp && !error)
879 		error = copyout(oactp, uap->oact, sizeof(oact));
880 	return (error);
881 }
882 #endif	/* COMAPT_FREEBSD4 */
883 
884 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
885 #ifndef _SYS_SYSPROTO_H_
886 struct osigaction_args {
887 	int	signum;
888 	struct	osigaction *nsa;
889 	struct	osigaction *osa;
890 };
891 #endif
892 int
893 osigaction(struct thread *td, struct osigaction_args *uap)
894 {
895 	struct osigaction sa;
896 	struct sigaction nsa, osa;
897 	struct sigaction *nsap, *osap;
898 	int error;
899 
900 	if (uap->signum <= 0 || uap->signum >= ONSIG)
901 		return (EINVAL);
902 
903 	nsap = (uap->nsa != NULL) ? &nsa : NULL;
904 	osap = (uap->osa != NULL) ? &osa : NULL;
905 
906 	if (nsap) {
907 		error = copyin(uap->nsa, &sa, sizeof(sa));
908 		if (error)
909 			return (error);
910 		nsap->sa_handler = sa.sa_handler;
911 		nsap->sa_flags = sa.sa_flags;
912 		OSIG2SIG(sa.sa_mask, nsap->sa_mask);
913 	}
914 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
915 	if (osap && !error) {
916 		sa.sa_handler = osap->sa_handler;
917 		sa.sa_flags = osap->sa_flags;
918 		SIG2OSIG(osap->sa_mask, sa.sa_mask);
919 		error = copyout(&sa, uap->osa, sizeof(sa));
920 	}
921 	return (error);
922 }
923 
924 #if !defined(__i386__)
925 /* Avoid replicating the same stub everywhere */
926 int
927 osigreturn(struct thread *td, struct osigreturn_args *uap)
928 {
929 
930 	return (nosys(td, (struct nosys_args *)uap));
931 }
932 #endif
933 #endif /* COMPAT_43 */
934 
935 /*
936  * Initialize signal state for process 0;
937  * set to ignore signals that are ignored by default.
938  */
939 void
940 siginit(struct proc *p)
941 {
942 	int i;
943 	struct sigacts *ps;
944 
945 	PROC_LOCK(p);
946 	ps = p->p_sigacts;
947 	mtx_lock(&ps->ps_mtx);
948 	for (i = 1; i <= NSIG; i++) {
949 		if (sigprop(i) & SIGPROP_IGNORE && i != SIGCONT) {
950 			SIGADDSET(ps->ps_sigignore, i);
951 		}
952 	}
953 	mtx_unlock(&ps->ps_mtx);
954 	PROC_UNLOCK(p);
955 }
956 
957 /*
958  * Reset specified signal to the default disposition.
959  */
960 static void
961 sigdflt(struct sigacts *ps, int sig)
962 {
963 
964 	mtx_assert(&ps->ps_mtx, MA_OWNED);
965 	SIGDELSET(ps->ps_sigcatch, sig);
966 	if ((sigprop(sig) & SIGPROP_IGNORE) != 0 && sig != SIGCONT)
967 		SIGADDSET(ps->ps_sigignore, sig);
968 	ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
969 	SIGDELSET(ps->ps_siginfo, sig);
970 }
971 
972 /*
973  * Reset signals for an exec of the specified process.
974  */
975 void
976 execsigs(struct proc *p)
977 {
978 	sigset_t osigignore;
979 	struct sigacts *ps;
980 	int sig;
981 	struct thread *td;
982 
983 	/*
984 	 * Reset caught signals.  Held signals remain held
985 	 * through td_sigmask (unless they were caught,
986 	 * and are now ignored by default).
987 	 */
988 	PROC_LOCK_ASSERT(p, MA_OWNED);
989 	ps = p->p_sigacts;
990 	mtx_lock(&ps->ps_mtx);
991 	sig_drop_caught(p);
992 
993 	/*
994 	 * As CloudABI processes cannot modify signal handlers, fully
995 	 * reset all signals to their default behavior. Do ignore
996 	 * SIGPIPE, as it would otherwise be impossible to recover from
997 	 * writes to broken pipes and sockets.
998 	 */
999 	if (SV_PROC_ABI(p) == SV_ABI_CLOUDABI) {
1000 		osigignore = ps->ps_sigignore;
1001 		while (SIGNOTEMPTY(osigignore)) {
1002 			sig = sig_ffs(&osigignore);
1003 			SIGDELSET(osigignore, sig);
1004 			if (sig != SIGPIPE)
1005 				sigdflt(ps, sig);
1006 		}
1007 		SIGADDSET(ps->ps_sigignore, SIGPIPE);
1008 	}
1009 
1010 	/*
1011 	 * Reset stack state to the user stack.
1012 	 * Clear set of signals caught on the signal stack.
1013 	 */
1014 	td = curthread;
1015 	MPASS(td->td_proc == p);
1016 	td->td_sigstk.ss_flags = SS_DISABLE;
1017 	td->td_sigstk.ss_size = 0;
1018 	td->td_sigstk.ss_sp = 0;
1019 	td->td_pflags &= ~TDP_ALTSTACK;
1020 	/*
1021 	 * Reset no zombies if child dies flag as Solaris does.
1022 	 */
1023 	ps->ps_flag &= ~(PS_NOCLDWAIT | PS_CLDSIGIGN);
1024 	if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
1025 		ps->ps_sigact[_SIG_IDX(SIGCHLD)] = SIG_DFL;
1026 	mtx_unlock(&ps->ps_mtx);
1027 }
1028 
1029 /*
1030  * kern_sigprocmask()
1031  *
1032  *	Manipulate signal mask.
1033  */
1034 int
1035 kern_sigprocmask(struct thread *td, int how, sigset_t *set, sigset_t *oset,
1036     int flags)
1037 {
1038 	sigset_t new_block, oset1;
1039 	struct proc *p;
1040 	int error;
1041 
1042 	p = td->td_proc;
1043 	if ((flags & SIGPROCMASK_PROC_LOCKED) != 0)
1044 		PROC_LOCK_ASSERT(p, MA_OWNED);
1045 	else
1046 		PROC_LOCK(p);
1047 	mtx_assert(&p->p_sigacts->ps_mtx, (flags & SIGPROCMASK_PS_LOCKED) != 0
1048 	    ? MA_OWNED : MA_NOTOWNED);
1049 	if (oset != NULL)
1050 		*oset = td->td_sigmask;
1051 
1052 	error = 0;
1053 	if (set != NULL) {
1054 		switch (how) {
1055 		case SIG_BLOCK:
1056 			SIG_CANTMASK(*set);
1057 			oset1 = td->td_sigmask;
1058 			SIGSETOR(td->td_sigmask, *set);
1059 			new_block = td->td_sigmask;
1060 			SIGSETNAND(new_block, oset1);
1061 			break;
1062 		case SIG_UNBLOCK:
1063 			SIGSETNAND(td->td_sigmask, *set);
1064 			signotify(td);
1065 			goto out;
1066 		case SIG_SETMASK:
1067 			SIG_CANTMASK(*set);
1068 			oset1 = td->td_sigmask;
1069 			if (flags & SIGPROCMASK_OLD)
1070 				SIGSETLO(td->td_sigmask, *set);
1071 			else
1072 				td->td_sigmask = *set;
1073 			new_block = td->td_sigmask;
1074 			SIGSETNAND(new_block, oset1);
1075 			signotify(td);
1076 			break;
1077 		default:
1078 			error = EINVAL;
1079 			goto out;
1080 		}
1081 
1082 		/*
1083 		 * The new_block set contains signals that were not previously
1084 		 * blocked, but are blocked now.
1085 		 *
1086 		 * In case we block any signal that was not previously blocked
1087 		 * for td, and process has the signal pending, try to schedule
1088 		 * signal delivery to some thread that does not block the
1089 		 * signal, possibly waking it up.
1090 		 */
1091 		if (p->p_numthreads != 1)
1092 			reschedule_signals(p, new_block, flags);
1093 	}
1094 
1095 out:
1096 	if (!(flags & SIGPROCMASK_PROC_LOCKED))
1097 		PROC_UNLOCK(p);
1098 	return (error);
1099 }
1100 
1101 #ifndef _SYS_SYSPROTO_H_
1102 struct sigprocmask_args {
1103 	int	how;
1104 	const sigset_t *set;
1105 	sigset_t *oset;
1106 };
1107 #endif
1108 int
1109 sys_sigprocmask(struct thread *td, struct sigprocmask_args *uap)
1110 {
1111 	sigset_t set, oset;
1112 	sigset_t *setp, *osetp;
1113 	int error;
1114 
1115 	setp = (uap->set != NULL) ? &set : NULL;
1116 	osetp = (uap->oset != NULL) ? &oset : NULL;
1117 	if (setp) {
1118 		error = copyin(uap->set, setp, sizeof(set));
1119 		if (error)
1120 			return (error);
1121 	}
1122 	error = kern_sigprocmask(td, uap->how, setp, osetp, 0);
1123 	if (osetp && !error) {
1124 		error = copyout(osetp, uap->oset, sizeof(oset));
1125 	}
1126 	return (error);
1127 }
1128 
1129 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1130 #ifndef _SYS_SYSPROTO_H_
1131 struct osigprocmask_args {
1132 	int	how;
1133 	osigset_t mask;
1134 };
1135 #endif
1136 int
1137 osigprocmask(struct thread *td, struct osigprocmask_args *uap)
1138 {
1139 	sigset_t set, oset;
1140 	int error;
1141 
1142 	OSIG2SIG(uap->mask, set);
1143 	error = kern_sigprocmask(td, uap->how, &set, &oset, 1);
1144 	SIG2OSIG(oset, td->td_retval[0]);
1145 	return (error);
1146 }
1147 #endif /* COMPAT_43 */
1148 
1149 int
1150 sys_sigwait(struct thread *td, struct sigwait_args *uap)
1151 {
1152 	ksiginfo_t ksi;
1153 	sigset_t set;
1154 	int error;
1155 
1156 	error = copyin(uap->set, &set, sizeof(set));
1157 	if (error) {
1158 		td->td_retval[0] = error;
1159 		return (0);
1160 	}
1161 
1162 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1163 	if (error) {
1164 		if (error == EINTR && td->td_proc->p_osrel < P_OSREL_SIGWAIT)
1165 			error = ERESTART;
1166 		if (error == ERESTART)
1167 			return (error);
1168 		td->td_retval[0] = error;
1169 		return (0);
1170 	}
1171 
1172 	error = copyout(&ksi.ksi_signo, uap->sig, sizeof(ksi.ksi_signo));
1173 	td->td_retval[0] = error;
1174 	return (0);
1175 }
1176 
1177 int
1178 sys_sigtimedwait(struct thread *td, struct sigtimedwait_args *uap)
1179 {
1180 	struct timespec ts;
1181 	struct timespec *timeout;
1182 	sigset_t set;
1183 	ksiginfo_t ksi;
1184 	int error;
1185 
1186 	if (uap->timeout) {
1187 		error = copyin(uap->timeout, &ts, sizeof(ts));
1188 		if (error)
1189 			return (error);
1190 
1191 		timeout = &ts;
1192 	} else
1193 		timeout = NULL;
1194 
1195 	error = copyin(uap->set, &set, sizeof(set));
1196 	if (error)
1197 		return (error);
1198 
1199 	error = kern_sigtimedwait(td, set, &ksi, timeout);
1200 	if (error)
1201 		return (error);
1202 
1203 	if (uap->info)
1204 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1205 
1206 	if (error == 0)
1207 		td->td_retval[0] = ksi.ksi_signo;
1208 	return (error);
1209 }
1210 
1211 int
1212 sys_sigwaitinfo(struct thread *td, struct sigwaitinfo_args *uap)
1213 {
1214 	ksiginfo_t ksi;
1215 	sigset_t set;
1216 	int error;
1217 
1218 	error = copyin(uap->set, &set, sizeof(set));
1219 	if (error)
1220 		return (error);
1221 
1222 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1223 	if (error)
1224 		return (error);
1225 
1226 	if (uap->info)
1227 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1228 
1229 	if (error == 0)
1230 		td->td_retval[0] = ksi.ksi_signo;
1231 	return (error);
1232 }
1233 
1234 static void
1235 proc_td_siginfo_capture(struct thread *td, siginfo_t *si)
1236 {
1237 	struct thread *thr;
1238 
1239 	FOREACH_THREAD_IN_PROC(td->td_proc, thr) {
1240 		if (thr == td)
1241 			thr->td_si = *si;
1242 		else
1243 			thr->td_si.si_signo = 0;
1244 	}
1245 }
1246 
1247 int
1248 kern_sigtimedwait(struct thread *td, sigset_t waitset, ksiginfo_t *ksi,
1249 	struct timespec *timeout)
1250 {
1251 	struct sigacts *ps;
1252 	sigset_t saved_mask, new_block;
1253 	struct proc *p;
1254 	int error, sig, timo, timevalid = 0;
1255 	struct timespec rts, ets, ts;
1256 	struct timeval tv;
1257 	bool traced;
1258 
1259 	p = td->td_proc;
1260 	error = 0;
1261 	ets.tv_sec = 0;
1262 	ets.tv_nsec = 0;
1263 	traced = false;
1264 
1265 	if (timeout != NULL) {
1266 		if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) {
1267 			timevalid = 1;
1268 			getnanouptime(&rts);
1269 			timespecadd(&rts, timeout, &ets);
1270 		}
1271 	}
1272 	ksiginfo_init(ksi);
1273 	/* Some signals can not be waited for. */
1274 	SIG_CANTMASK(waitset);
1275 	ps = p->p_sigacts;
1276 	PROC_LOCK(p);
1277 	saved_mask = td->td_sigmask;
1278 	SIGSETNAND(td->td_sigmask, waitset);
1279 	for (;;) {
1280 		mtx_lock(&ps->ps_mtx);
1281 		sig = cursig(td);
1282 		mtx_unlock(&ps->ps_mtx);
1283 		KASSERT(sig >= 0, ("sig %d", sig));
1284 		if (sig != 0 && SIGISMEMBER(waitset, sig)) {
1285 			if (sigqueue_get(&td->td_sigqueue, sig, ksi) != 0 ||
1286 			    sigqueue_get(&p->p_sigqueue, sig, ksi) != 0) {
1287 				error = 0;
1288 				break;
1289 			}
1290 		}
1291 
1292 		if (error != 0)
1293 			break;
1294 
1295 		/*
1296 		 * POSIX says this must be checked after looking for pending
1297 		 * signals.
1298 		 */
1299 		if (timeout != NULL) {
1300 			if (!timevalid) {
1301 				error = EINVAL;
1302 				break;
1303 			}
1304 			getnanouptime(&rts);
1305 			if (timespeccmp(&rts, &ets, >=)) {
1306 				error = EAGAIN;
1307 				break;
1308 			}
1309 			timespecsub(&ets, &rts, &ts);
1310 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1311 			timo = tvtohz(&tv);
1312 		} else {
1313 			timo = 0;
1314 		}
1315 
1316 		if (traced) {
1317 			error = EINTR;
1318 			break;
1319 		}
1320 
1321 		error = msleep(ps, &p->p_mtx, PPAUSE|PCATCH, "sigwait", timo);
1322 
1323 		if (timeout != NULL) {
1324 			if (error == ERESTART) {
1325 				/* Timeout can not be restarted. */
1326 				error = EINTR;
1327 			} else if (error == EAGAIN) {
1328 				/* We will calculate timeout by ourself. */
1329 				error = 0;
1330 			}
1331 		}
1332 
1333 		/*
1334 		 * If PTRACE_SCE or PTRACE_SCX were set after
1335 		 * userspace entered the syscall, return spurious
1336 		 * EINTR after wait was done.  Only do this as last
1337 		 * resort after rechecking for possible queued signals
1338 		 * and expired timeouts.
1339 		 */
1340 		if (error == 0 && (p->p_ptevents & PTRACE_SYSCALL) != 0)
1341 			traced = true;
1342 	}
1343 
1344 	new_block = saved_mask;
1345 	SIGSETNAND(new_block, td->td_sigmask);
1346 	td->td_sigmask = saved_mask;
1347 	/*
1348 	 * Fewer signals can be delivered to us, reschedule signal
1349 	 * notification.
1350 	 */
1351 	if (p->p_numthreads != 1)
1352 		reschedule_signals(p, new_block, 0);
1353 
1354 	if (error == 0) {
1355 		SDT_PROBE2(proc, , , signal__clear, sig, ksi);
1356 
1357 		if (ksi->ksi_code == SI_TIMER)
1358 			itimer_accept(p, ksi->ksi_timerid, ksi);
1359 
1360 #ifdef KTRACE
1361 		if (KTRPOINT(td, KTR_PSIG)) {
1362 			sig_t action;
1363 
1364 			mtx_lock(&ps->ps_mtx);
1365 			action = ps->ps_sigact[_SIG_IDX(sig)];
1366 			mtx_unlock(&ps->ps_mtx);
1367 			ktrpsig(sig, action, &td->td_sigmask, ksi->ksi_code);
1368 		}
1369 #endif
1370 		if (sig == SIGKILL) {
1371 			proc_td_siginfo_capture(td, &ksi->ksi_info);
1372 			sigexit(td, sig);
1373 		}
1374 	}
1375 	PROC_UNLOCK(p);
1376 	return (error);
1377 }
1378 
1379 #ifndef _SYS_SYSPROTO_H_
1380 struct sigpending_args {
1381 	sigset_t	*set;
1382 };
1383 #endif
1384 int
1385 sys_sigpending(struct thread *td, struct sigpending_args *uap)
1386 {
1387 	struct proc *p = td->td_proc;
1388 	sigset_t pending;
1389 
1390 	PROC_LOCK(p);
1391 	pending = p->p_sigqueue.sq_signals;
1392 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1393 	PROC_UNLOCK(p);
1394 	return (copyout(&pending, uap->set, sizeof(sigset_t)));
1395 }
1396 
1397 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1398 #ifndef _SYS_SYSPROTO_H_
1399 struct osigpending_args {
1400 	int	dummy;
1401 };
1402 #endif
1403 int
1404 osigpending(struct thread *td, struct osigpending_args *uap)
1405 {
1406 	struct proc *p = td->td_proc;
1407 	sigset_t pending;
1408 
1409 	PROC_LOCK(p);
1410 	pending = p->p_sigqueue.sq_signals;
1411 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1412 	PROC_UNLOCK(p);
1413 	SIG2OSIG(pending, td->td_retval[0]);
1414 	return (0);
1415 }
1416 #endif /* COMPAT_43 */
1417 
1418 #if defined(COMPAT_43)
1419 /*
1420  * Generalized interface signal handler, 4.3-compatible.
1421  */
1422 #ifndef _SYS_SYSPROTO_H_
1423 struct osigvec_args {
1424 	int	signum;
1425 	struct	sigvec *nsv;
1426 	struct	sigvec *osv;
1427 };
1428 #endif
1429 /* ARGSUSED */
1430 int
1431 osigvec(struct thread *td, struct osigvec_args *uap)
1432 {
1433 	struct sigvec vec;
1434 	struct sigaction nsa, osa;
1435 	struct sigaction *nsap, *osap;
1436 	int error;
1437 
1438 	if (uap->signum <= 0 || uap->signum >= ONSIG)
1439 		return (EINVAL);
1440 	nsap = (uap->nsv != NULL) ? &nsa : NULL;
1441 	osap = (uap->osv != NULL) ? &osa : NULL;
1442 	if (nsap) {
1443 		error = copyin(uap->nsv, &vec, sizeof(vec));
1444 		if (error)
1445 			return (error);
1446 		nsap->sa_handler = vec.sv_handler;
1447 		OSIG2SIG(vec.sv_mask, nsap->sa_mask);
1448 		nsap->sa_flags = vec.sv_flags;
1449 		nsap->sa_flags ^= SA_RESTART;	/* opposite of SV_INTERRUPT */
1450 	}
1451 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
1452 	if (osap && !error) {
1453 		vec.sv_handler = osap->sa_handler;
1454 		SIG2OSIG(osap->sa_mask, vec.sv_mask);
1455 		vec.sv_flags = osap->sa_flags;
1456 		vec.sv_flags &= ~SA_NOCLDWAIT;
1457 		vec.sv_flags ^= SA_RESTART;
1458 		error = copyout(&vec, uap->osv, sizeof(vec));
1459 	}
1460 	return (error);
1461 }
1462 
1463 #ifndef _SYS_SYSPROTO_H_
1464 struct osigblock_args {
1465 	int	mask;
1466 };
1467 #endif
1468 int
1469 osigblock(struct thread *td, struct osigblock_args *uap)
1470 {
1471 	sigset_t set, oset;
1472 
1473 	OSIG2SIG(uap->mask, set);
1474 	kern_sigprocmask(td, SIG_BLOCK, &set, &oset, 0);
1475 	SIG2OSIG(oset, td->td_retval[0]);
1476 	return (0);
1477 }
1478 
1479 #ifndef _SYS_SYSPROTO_H_
1480 struct osigsetmask_args {
1481 	int	mask;
1482 };
1483 #endif
1484 int
1485 osigsetmask(struct thread *td, struct osigsetmask_args *uap)
1486 {
1487 	sigset_t set, oset;
1488 
1489 	OSIG2SIG(uap->mask, set);
1490 	kern_sigprocmask(td, SIG_SETMASK, &set, &oset, 0);
1491 	SIG2OSIG(oset, td->td_retval[0]);
1492 	return (0);
1493 }
1494 #endif /* COMPAT_43 */
1495 
1496 /*
1497  * Suspend calling thread until signal, providing mask to be set in the
1498  * meantime.
1499  */
1500 #ifndef _SYS_SYSPROTO_H_
1501 struct sigsuspend_args {
1502 	const sigset_t *sigmask;
1503 };
1504 #endif
1505 /* ARGSUSED */
1506 int
1507 sys_sigsuspend(struct thread *td, struct sigsuspend_args *uap)
1508 {
1509 	sigset_t mask;
1510 	int error;
1511 
1512 	error = copyin(uap->sigmask, &mask, sizeof(mask));
1513 	if (error)
1514 		return (error);
1515 	return (kern_sigsuspend(td, mask));
1516 }
1517 
1518 int
1519 kern_sigsuspend(struct thread *td, sigset_t mask)
1520 {
1521 	struct proc *p = td->td_proc;
1522 	int has_sig, sig;
1523 
1524 	/*
1525 	 * When returning from sigsuspend, we want
1526 	 * the old mask to be restored after the
1527 	 * signal handler has finished.  Thus, we
1528 	 * save it here and mark the sigacts structure
1529 	 * to indicate this.
1530 	 */
1531 	PROC_LOCK(p);
1532 	kern_sigprocmask(td, SIG_SETMASK, &mask, &td->td_oldsigmask,
1533 	    SIGPROCMASK_PROC_LOCKED);
1534 	td->td_pflags |= TDP_OLDMASK;
1535 
1536 	/*
1537 	 * Process signals now. Otherwise, we can get spurious wakeup
1538 	 * due to signal entered process queue, but delivered to other
1539 	 * thread. But sigsuspend should return only on signal
1540 	 * delivery.
1541 	 */
1542 	(p->p_sysent->sv_set_syscall_retval)(td, EINTR);
1543 	for (has_sig = 0; !has_sig;) {
1544 		while (msleep(&p->p_sigacts, &p->p_mtx, PPAUSE|PCATCH, "pause",
1545 			0) == 0)
1546 			/* void */;
1547 		thread_suspend_check(0);
1548 		mtx_lock(&p->p_sigacts->ps_mtx);
1549 		while ((sig = cursig(td)) != 0) {
1550 			KASSERT(sig >= 0, ("sig %d", sig));
1551 			has_sig += postsig(sig);
1552 		}
1553 		mtx_unlock(&p->p_sigacts->ps_mtx);
1554 
1555 		/*
1556 		 * If PTRACE_SCE or PTRACE_SCX were set after
1557 		 * userspace entered the syscall, return spurious
1558 		 * EINTR.
1559 		 */
1560 		if ((p->p_ptevents & PTRACE_SYSCALL) != 0)
1561 			has_sig += 1;
1562 	}
1563 	PROC_UNLOCK(p);
1564 	td->td_errno = EINTR;
1565 	td->td_pflags |= TDP_NERRNO;
1566 	return (EJUSTRETURN);
1567 }
1568 
1569 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1570 /*
1571  * Compatibility sigsuspend call for old binaries.  Note nonstandard calling
1572  * convention: libc stub passes mask, not pointer, to save a copyin.
1573  */
1574 #ifndef _SYS_SYSPROTO_H_
1575 struct osigsuspend_args {
1576 	osigset_t mask;
1577 };
1578 #endif
1579 /* ARGSUSED */
1580 int
1581 osigsuspend(struct thread *td, struct osigsuspend_args *uap)
1582 {
1583 	sigset_t mask;
1584 
1585 	OSIG2SIG(uap->mask, mask);
1586 	return (kern_sigsuspend(td, mask));
1587 }
1588 #endif /* COMPAT_43 */
1589 
1590 #if defined(COMPAT_43)
1591 #ifndef _SYS_SYSPROTO_H_
1592 struct osigstack_args {
1593 	struct	sigstack *nss;
1594 	struct	sigstack *oss;
1595 };
1596 #endif
1597 /* ARGSUSED */
1598 int
1599 osigstack(struct thread *td, struct osigstack_args *uap)
1600 {
1601 	struct sigstack nss, oss;
1602 	int error = 0;
1603 
1604 	if (uap->nss != NULL) {
1605 		error = copyin(uap->nss, &nss, sizeof(nss));
1606 		if (error)
1607 			return (error);
1608 	}
1609 	oss.ss_sp = td->td_sigstk.ss_sp;
1610 	oss.ss_onstack = sigonstack(cpu_getstack(td));
1611 	if (uap->nss != NULL) {
1612 		td->td_sigstk.ss_sp = nss.ss_sp;
1613 		td->td_sigstk.ss_size = 0;
1614 		td->td_sigstk.ss_flags |= nss.ss_onstack & SS_ONSTACK;
1615 		td->td_pflags |= TDP_ALTSTACK;
1616 	}
1617 	if (uap->oss != NULL)
1618 		error = copyout(&oss, uap->oss, sizeof(oss));
1619 
1620 	return (error);
1621 }
1622 #endif /* COMPAT_43 */
1623 
1624 #ifndef _SYS_SYSPROTO_H_
1625 struct sigaltstack_args {
1626 	stack_t	*ss;
1627 	stack_t	*oss;
1628 };
1629 #endif
1630 /* ARGSUSED */
1631 int
1632 sys_sigaltstack(struct thread *td, struct sigaltstack_args *uap)
1633 {
1634 	stack_t ss, oss;
1635 	int error;
1636 
1637 	if (uap->ss != NULL) {
1638 		error = copyin(uap->ss, &ss, sizeof(ss));
1639 		if (error)
1640 			return (error);
1641 	}
1642 	error = kern_sigaltstack(td, (uap->ss != NULL) ? &ss : NULL,
1643 	    (uap->oss != NULL) ? &oss : NULL);
1644 	if (error)
1645 		return (error);
1646 	if (uap->oss != NULL)
1647 		error = copyout(&oss, uap->oss, sizeof(stack_t));
1648 	return (error);
1649 }
1650 
1651 int
1652 kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
1653 {
1654 	struct proc *p = td->td_proc;
1655 	int oonstack;
1656 
1657 	oonstack = sigonstack(cpu_getstack(td));
1658 
1659 	if (oss != NULL) {
1660 		*oss = td->td_sigstk;
1661 		oss->ss_flags = (td->td_pflags & TDP_ALTSTACK)
1662 		    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1663 	}
1664 
1665 	if (ss != NULL) {
1666 		if (oonstack)
1667 			return (EPERM);
1668 		if ((ss->ss_flags & ~SS_DISABLE) != 0)
1669 			return (EINVAL);
1670 		if (!(ss->ss_flags & SS_DISABLE)) {
1671 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
1672 				return (ENOMEM);
1673 
1674 			td->td_sigstk = *ss;
1675 			td->td_pflags |= TDP_ALTSTACK;
1676 		} else {
1677 			td->td_pflags &= ~TDP_ALTSTACK;
1678 		}
1679 	}
1680 	return (0);
1681 }
1682 
1683 struct killpg1_ctx {
1684 	struct thread *td;
1685 	ksiginfo_t *ksi;
1686 	int sig;
1687 	bool sent;
1688 	bool found;
1689 	int ret;
1690 };
1691 
1692 static void
1693 killpg1_sendsig(struct proc *p, bool notself, struct killpg1_ctx *arg)
1694 {
1695 	int err;
1696 
1697 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) != 0 ||
1698 	    (notself && p == arg->td->td_proc) || p->p_state == PRS_NEW)
1699 		return;
1700 	PROC_LOCK(p);
1701 	err = p_cansignal(arg->td, p, arg->sig);
1702 	if (err == 0 && arg->sig != 0)
1703 		pksignal(p, arg->sig, arg->ksi);
1704 	PROC_UNLOCK(p);
1705 	if (err != ESRCH)
1706 		arg->found = true;
1707 	if (err == 0)
1708 		arg->sent = true;
1709 	else if (arg->ret == 0 && err != ESRCH && err != EPERM)
1710 		arg->ret = err;
1711 }
1712 
1713 /*
1714  * Common code for kill process group/broadcast kill.
1715  * cp is calling process.
1716  */
1717 static int
1718 killpg1(struct thread *td, int sig, int pgid, int all, ksiginfo_t *ksi)
1719 {
1720 	struct proc *p;
1721 	struct pgrp *pgrp;
1722 	struct killpg1_ctx arg;
1723 
1724 	arg.td = td;
1725 	arg.ksi = ksi;
1726 	arg.sig = sig;
1727 	arg.sent = false;
1728 	arg.found = false;
1729 	arg.ret = 0;
1730 	if (all) {
1731 		/*
1732 		 * broadcast
1733 		 */
1734 		sx_slock(&allproc_lock);
1735 		FOREACH_PROC_IN_SYSTEM(p) {
1736 			killpg1_sendsig(p, true, &arg);
1737 		}
1738 		sx_sunlock(&allproc_lock);
1739 	} else {
1740 		sx_slock(&proctree_lock);
1741 		if (pgid == 0) {
1742 			/*
1743 			 * zero pgid means send to my process group.
1744 			 */
1745 			pgrp = td->td_proc->p_pgrp;
1746 			PGRP_LOCK(pgrp);
1747 		} else {
1748 			pgrp = pgfind(pgid);
1749 			if (pgrp == NULL) {
1750 				sx_sunlock(&proctree_lock);
1751 				return (ESRCH);
1752 			}
1753 		}
1754 		sx_sunlock(&proctree_lock);
1755 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1756 			killpg1_sendsig(p, false, &arg);
1757 		}
1758 		PGRP_UNLOCK(pgrp);
1759 	}
1760 	MPASS(arg.ret != 0 || arg.found || !arg.sent);
1761 	if (arg.ret == 0 && !arg.sent)
1762 		arg.ret = arg.found ? EPERM : ESRCH;
1763 	return (arg.ret);
1764 }
1765 
1766 #ifndef _SYS_SYSPROTO_H_
1767 struct kill_args {
1768 	int	pid;
1769 	int	signum;
1770 };
1771 #endif
1772 /* ARGSUSED */
1773 int
1774 sys_kill(struct thread *td, struct kill_args *uap)
1775 {
1776 
1777 	return (kern_kill(td, uap->pid, uap->signum));
1778 }
1779 
1780 int
1781 kern_kill(struct thread *td, pid_t pid, int signum)
1782 {
1783 	ksiginfo_t ksi;
1784 	struct proc *p;
1785 	int error;
1786 
1787 	/*
1788 	 * A process in capability mode can send signals only to himself.
1789 	 * The main rationale behind this is that abort(3) is implemented as
1790 	 * kill(getpid(), SIGABRT).
1791 	 */
1792 	if (IN_CAPABILITY_MODE(td) && pid != td->td_proc->p_pid)
1793 		return (ECAPMODE);
1794 
1795 	AUDIT_ARG_SIGNUM(signum);
1796 	AUDIT_ARG_PID(pid);
1797 	if ((u_int)signum > _SIG_MAXSIG)
1798 		return (EINVAL);
1799 
1800 	ksiginfo_init(&ksi);
1801 	ksi.ksi_signo = signum;
1802 	ksi.ksi_code = SI_USER;
1803 	ksi.ksi_pid = td->td_proc->p_pid;
1804 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1805 
1806 	if (pid > 0) {
1807 		/* kill single process */
1808 		if ((p = pfind_any(pid)) == NULL)
1809 			return (ESRCH);
1810 		AUDIT_ARG_PROCESS(p);
1811 		error = p_cansignal(td, p, signum);
1812 		if (error == 0 && signum)
1813 			pksignal(p, signum, &ksi);
1814 		PROC_UNLOCK(p);
1815 		return (error);
1816 	}
1817 	switch (pid) {
1818 	case -1:		/* broadcast signal */
1819 		return (killpg1(td, signum, 0, 1, &ksi));
1820 	case 0:			/* signal own process group */
1821 		return (killpg1(td, signum, 0, 0, &ksi));
1822 	default:		/* negative explicit process group */
1823 		return (killpg1(td, signum, -pid, 0, &ksi));
1824 	}
1825 	/* NOTREACHED */
1826 }
1827 
1828 int
1829 sys_pdkill(struct thread *td, struct pdkill_args *uap)
1830 {
1831 	struct proc *p;
1832 	int error;
1833 
1834 	AUDIT_ARG_SIGNUM(uap->signum);
1835 	AUDIT_ARG_FD(uap->fd);
1836 	if ((u_int)uap->signum > _SIG_MAXSIG)
1837 		return (EINVAL);
1838 
1839 	error = procdesc_find(td, uap->fd, &cap_pdkill_rights, &p);
1840 	if (error)
1841 		return (error);
1842 	AUDIT_ARG_PROCESS(p);
1843 	error = p_cansignal(td, p, uap->signum);
1844 	if (error == 0 && uap->signum)
1845 		kern_psignal(p, uap->signum);
1846 	PROC_UNLOCK(p);
1847 	return (error);
1848 }
1849 
1850 #if defined(COMPAT_43)
1851 #ifndef _SYS_SYSPROTO_H_
1852 struct okillpg_args {
1853 	int	pgid;
1854 	int	signum;
1855 };
1856 #endif
1857 /* ARGSUSED */
1858 int
1859 okillpg(struct thread *td, struct okillpg_args *uap)
1860 {
1861 	ksiginfo_t ksi;
1862 
1863 	AUDIT_ARG_SIGNUM(uap->signum);
1864 	AUDIT_ARG_PID(uap->pgid);
1865 	if ((u_int)uap->signum > _SIG_MAXSIG)
1866 		return (EINVAL);
1867 
1868 	ksiginfo_init(&ksi);
1869 	ksi.ksi_signo = uap->signum;
1870 	ksi.ksi_code = SI_USER;
1871 	ksi.ksi_pid = td->td_proc->p_pid;
1872 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1873 	return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1874 }
1875 #endif /* COMPAT_43 */
1876 
1877 #ifndef _SYS_SYSPROTO_H_
1878 struct sigqueue_args {
1879 	pid_t pid;
1880 	int signum;
1881 	/* union sigval */ void *value;
1882 };
1883 #endif
1884 int
1885 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
1886 {
1887 	union sigval sv;
1888 
1889 	sv.sival_ptr = uap->value;
1890 
1891 	return (kern_sigqueue(td, uap->pid, uap->signum, &sv));
1892 }
1893 
1894 int
1895 kern_sigqueue(struct thread *td, pid_t pid, int signum, union sigval *value)
1896 {
1897 	ksiginfo_t ksi;
1898 	struct proc *p;
1899 	int error;
1900 
1901 	if ((u_int)signum > _SIG_MAXSIG)
1902 		return (EINVAL);
1903 
1904 	/*
1905 	 * Specification says sigqueue can only send signal to
1906 	 * single process.
1907 	 */
1908 	if (pid <= 0)
1909 		return (EINVAL);
1910 
1911 	if ((p = pfind_any(pid)) == NULL)
1912 		return (ESRCH);
1913 	error = p_cansignal(td, p, signum);
1914 	if (error == 0 && signum != 0) {
1915 		ksiginfo_init(&ksi);
1916 		ksi.ksi_flags = KSI_SIGQ;
1917 		ksi.ksi_signo = signum;
1918 		ksi.ksi_code = SI_QUEUE;
1919 		ksi.ksi_pid = td->td_proc->p_pid;
1920 		ksi.ksi_uid = td->td_ucred->cr_ruid;
1921 		ksi.ksi_value = *value;
1922 		error = pksignal(p, ksi.ksi_signo, &ksi);
1923 	}
1924 	PROC_UNLOCK(p);
1925 	return (error);
1926 }
1927 
1928 /*
1929  * Send a signal to a process group.
1930  */
1931 void
1932 gsignal(int pgid, int sig, ksiginfo_t *ksi)
1933 {
1934 	struct pgrp *pgrp;
1935 
1936 	if (pgid != 0) {
1937 		sx_slock(&proctree_lock);
1938 		pgrp = pgfind(pgid);
1939 		sx_sunlock(&proctree_lock);
1940 		if (pgrp != NULL) {
1941 			pgsignal(pgrp, sig, 0, ksi);
1942 			PGRP_UNLOCK(pgrp);
1943 		}
1944 	}
1945 }
1946 
1947 /*
1948  * Send a signal to a process group.  If checktty is 1,
1949  * limit to members which have a controlling terminal.
1950  */
1951 void
1952 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
1953 {
1954 	struct proc *p;
1955 
1956 	if (pgrp) {
1957 		PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
1958 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1959 			PROC_LOCK(p);
1960 			if (p->p_state == PRS_NORMAL &&
1961 			    (checkctty == 0 || p->p_flag & P_CONTROLT))
1962 				pksignal(p, sig, ksi);
1963 			PROC_UNLOCK(p);
1964 		}
1965 	}
1966 }
1967 
1968 /*
1969  * Recalculate the signal mask and reset the signal disposition after
1970  * usermode frame for delivery is formed.  Should be called after
1971  * mach-specific routine, because sysent->sv_sendsig() needs correct
1972  * ps_siginfo and signal mask.
1973  */
1974 static void
1975 postsig_done(int sig, struct thread *td, struct sigacts *ps)
1976 {
1977 	sigset_t mask;
1978 
1979 	mtx_assert(&ps->ps_mtx, MA_OWNED);
1980 	td->td_ru.ru_nsignals++;
1981 	mask = ps->ps_catchmask[_SIG_IDX(sig)];
1982 	if (!SIGISMEMBER(ps->ps_signodefer, sig))
1983 		SIGADDSET(mask, sig);
1984 	kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
1985 	    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
1986 	if (SIGISMEMBER(ps->ps_sigreset, sig))
1987 		sigdflt(ps, sig);
1988 }
1989 
1990 /*
1991  * Send a signal caused by a trap to the current thread.  If it will be
1992  * caught immediately, deliver it with correct code.  Otherwise, post it
1993  * normally.
1994  */
1995 void
1996 trapsignal(struct thread *td, ksiginfo_t *ksi)
1997 {
1998 	struct sigacts *ps;
1999 	struct proc *p;
2000 	sigset_t sigmask;
2001 	int code, sig;
2002 
2003 	p = td->td_proc;
2004 	sig = ksi->ksi_signo;
2005 	code = ksi->ksi_code;
2006 	KASSERT(_SIG_VALID(sig), ("invalid signal"));
2007 
2008 	PROC_LOCK(p);
2009 	ps = p->p_sigacts;
2010 	mtx_lock(&ps->ps_mtx);
2011 	sigmask = td->td_sigmask;
2012 	if (td->td_sigblock_val != 0)
2013 		SIGSETOR(sigmask, fastblock_mask);
2014 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
2015 	    !SIGISMEMBER(sigmask, sig)) {
2016 #ifdef KTRACE
2017 		if (KTRPOINT(curthread, KTR_PSIG))
2018 			ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
2019 			    &td->td_sigmask, code);
2020 #endif
2021 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
2022 				ksi, &td->td_sigmask);
2023 		postsig_done(sig, td, ps);
2024 		mtx_unlock(&ps->ps_mtx);
2025 	} else {
2026 		/*
2027 		 * Avoid a possible infinite loop if the thread
2028 		 * masking the signal or process is ignoring the
2029 		 * signal.
2030 		 */
2031 		if (kern_forcesigexit && (SIGISMEMBER(sigmask, sig) ||
2032 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
2033 			SIGDELSET(td->td_sigmask, sig);
2034 			SIGDELSET(ps->ps_sigcatch, sig);
2035 			SIGDELSET(ps->ps_sigignore, sig);
2036 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2037 			td->td_pflags &= ~TDP_SIGFASTBLOCK;
2038 			td->td_sigblock_val = 0;
2039 		}
2040 		mtx_unlock(&ps->ps_mtx);
2041 		p->p_sig = sig;		/* XXX to verify code */
2042 		tdsendsignal(p, td, sig, ksi);
2043 	}
2044 	PROC_UNLOCK(p);
2045 }
2046 
2047 static struct thread *
2048 sigtd(struct proc *p, int sig, bool fast_sigblock)
2049 {
2050 	struct thread *td, *signal_td;
2051 
2052 	PROC_LOCK_ASSERT(p, MA_OWNED);
2053 	MPASS(!fast_sigblock || p == curproc);
2054 
2055 	/*
2056 	 * Check if current thread can handle the signal without
2057 	 * switching context to another thread.
2058 	 */
2059 	if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig) &&
2060 	    (!fast_sigblock || curthread->td_sigblock_val == 0))
2061 		return (curthread);
2062 	signal_td = NULL;
2063 	FOREACH_THREAD_IN_PROC(p, td) {
2064 		if (!SIGISMEMBER(td->td_sigmask, sig) && (!fast_sigblock ||
2065 		    td != curthread || td->td_sigblock_val == 0)) {
2066 			signal_td = td;
2067 			break;
2068 		}
2069 	}
2070 	if (signal_td == NULL)
2071 		signal_td = FIRST_THREAD_IN_PROC(p);
2072 	return (signal_td);
2073 }
2074 
2075 /*
2076  * Send the signal to the process.  If the signal has an action, the action
2077  * is usually performed by the target process rather than the caller; we add
2078  * the signal to the set of pending signals for the process.
2079  *
2080  * Exceptions:
2081  *   o When a stop signal is sent to a sleeping process that takes the
2082  *     default action, the process is stopped without awakening it.
2083  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2084  *     regardless of the signal action (eg, blocked or ignored).
2085  *
2086  * Other ignored signals are discarded immediately.
2087  *
2088  * NB: This function may be entered from the debugger via the "kill" DDB
2089  * command.  There is little that can be done to mitigate the possibly messy
2090  * side effects of this unwise possibility.
2091  */
2092 void
2093 kern_psignal(struct proc *p, int sig)
2094 {
2095 	ksiginfo_t ksi;
2096 
2097 	ksiginfo_init(&ksi);
2098 	ksi.ksi_signo = sig;
2099 	ksi.ksi_code = SI_KERNEL;
2100 	(void) tdsendsignal(p, NULL, sig, &ksi);
2101 }
2102 
2103 int
2104 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
2105 {
2106 
2107 	return (tdsendsignal(p, NULL, sig, ksi));
2108 }
2109 
2110 /* Utility function for finding a thread to send signal event to. */
2111 int
2112 sigev_findtd(struct proc *p ,struct sigevent *sigev, struct thread **ttd)
2113 {
2114 	struct thread *td;
2115 
2116 	if (sigev->sigev_notify == SIGEV_THREAD_ID) {
2117 		td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
2118 		if (td == NULL)
2119 			return (ESRCH);
2120 		*ttd = td;
2121 	} else {
2122 		*ttd = NULL;
2123 		PROC_LOCK(p);
2124 	}
2125 	return (0);
2126 }
2127 
2128 void
2129 tdsignal(struct thread *td, int sig)
2130 {
2131 	ksiginfo_t ksi;
2132 
2133 	ksiginfo_init(&ksi);
2134 	ksi.ksi_signo = sig;
2135 	ksi.ksi_code = SI_KERNEL;
2136 	(void) tdsendsignal(td->td_proc, td, sig, &ksi);
2137 }
2138 
2139 void
2140 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2141 {
2142 
2143 	(void) tdsendsignal(td->td_proc, td, sig, ksi);
2144 }
2145 
2146 int
2147 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2148 {
2149 	sig_t action;
2150 	sigqueue_t *sigqueue;
2151 	int prop;
2152 	struct sigacts *ps;
2153 	int intrval;
2154 	int ret = 0;
2155 	int wakeup_swapper;
2156 
2157 	MPASS(td == NULL || p == td->td_proc);
2158 	PROC_LOCK_ASSERT(p, MA_OWNED);
2159 
2160 	if (!_SIG_VALID(sig))
2161 		panic("%s(): invalid signal %d", __func__, sig);
2162 
2163 	KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2164 
2165 	/*
2166 	 * IEEE Std 1003.1-2001: return success when killing a zombie.
2167 	 */
2168 	if (p->p_state == PRS_ZOMBIE) {
2169 		if (ksi && (ksi->ksi_flags & KSI_INS))
2170 			ksiginfo_tryfree(ksi);
2171 		return (ret);
2172 	}
2173 
2174 	ps = p->p_sigacts;
2175 	KNOTE_LOCKED(p->p_klist, NOTE_SIGNAL | sig);
2176 	prop = sigprop(sig);
2177 
2178 	if (td == NULL) {
2179 		td = sigtd(p, sig, false);
2180 		sigqueue = &p->p_sigqueue;
2181 	} else
2182 		sigqueue = &td->td_sigqueue;
2183 
2184 	SDT_PROBE3(proc, , , signal__send, td, p, sig);
2185 
2186 	/*
2187 	 * If the signal is being ignored,
2188 	 * then we forget about it immediately.
2189 	 * (Note: we don't set SIGCONT in ps_sigignore,
2190 	 * and if it is set to SIG_IGN,
2191 	 * action will be SIG_DFL here.)
2192 	 */
2193 	mtx_lock(&ps->ps_mtx);
2194 	if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2195 		SDT_PROBE3(proc, , , signal__discard, td, p, sig);
2196 
2197 		mtx_unlock(&ps->ps_mtx);
2198 		if (ksi && (ksi->ksi_flags & KSI_INS))
2199 			ksiginfo_tryfree(ksi);
2200 		return (ret);
2201 	}
2202 	if (SIGISMEMBER(td->td_sigmask, sig))
2203 		action = SIG_HOLD;
2204 	else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2205 		action = SIG_CATCH;
2206 	else
2207 		action = SIG_DFL;
2208 	if (SIGISMEMBER(ps->ps_sigintr, sig))
2209 		intrval = EINTR;
2210 	else
2211 		intrval = ERESTART;
2212 	mtx_unlock(&ps->ps_mtx);
2213 
2214 	if (prop & SIGPROP_CONT)
2215 		sigqueue_delete_stopmask_proc(p);
2216 	else if (prop & SIGPROP_STOP) {
2217 		/*
2218 		 * If sending a tty stop signal to a member of an orphaned
2219 		 * process group, discard the signal here if the action
2220 		 * is default; don't stop the process below if sleeping,
2221 		 * and don't clear any pending SIGCONT.
2222 		 */
2223 		if ((prop & SIGPROP_TTYSTOP) &&
2224 		    (p->p_pgrp->pg_jobc == 0) &&
2225 		    (action == SIG_DFL)) {
2226 			if (ksi && (ksi->ksi_flags & KSI_INS))
2227 				ksiginfo_tryfree(ksi);
2228 			return (ret);
2229 		}
2230 		sigqueue_delete_proc(p, SIGCONT);
2231 		if (p->p_flag & P_CONTINUED) {
2232 			p->p_flag &= ~P_CONTINUED;
2233 			PROC_LOCK(p->p_pptr);
2234 			sigqueue_take(p->p_ksi);
2235 			PROC_UNLOCK(p->p_pptr);
2236 		}
2237 	}
2238 
2239 	ret = sigqueue_add(sigqueue, sig, ksi);
2240 	if (ret != 0)
2241 		return (ret);
2242 	signotify(td);
2243 	/*
2244 	 * Defer further processing for signals which are held,
2245 	 * except that stopped processes must be continued by SIGCONT.
2246 	 */
2247 	if (action == SIG_HOLD &&
2248 	    !((prop & SIGPROP_CONT) && (p->p_flag & P_STOPPED_SIG)))
2249 		return (ret);
2250 
2251 	/* SIGKILL: Remove procfs STOPEVENTs. */
2252 	if (sig == SIGKILL) {
2253 		/* from procfs_ioctl.c: PIOCBIC */
2254 		p->p_stops = 0;
2255 		/* from procfs_ioctl.c: PIOCCONT */
2256 		p->p_step = 0;
2257 		wakeup(&p->p_step);
2258 	}
2259 	wakeup_swapper = 0;
2260 
2261 	/*
2262 	 * Some signals have a process-wide effect and a per-thread
2263 	 * component.  Most processing occurs when the process next
2264 	 * tries to cross the user boundary, however there are some
2265 	 * times when processing needs to be done immediately, such as
2266 	 * waking up threads so that they can cross the user boundary.
2267 	 * We try to do the per-process part here.
2268 	 */
2269 	if (P_SHOULDSTOP(p)) {
2270 		KASSERT(!(p->p_flag & P_WEXIT),
2271 		    ("signal to stopped but exiting process"));
2272 		if (sig == SIGKILL) {
2273 			/*
2274 			 * If traced process is already stopped,
2275 			 * then no further action is necessary.
2276 			 */
2277 			if (p->p_flag & P_TRACED)
2278 				goto out;
2279 			/*
2280 			 * SIGKILL sets process running.
2281 			 * It will die elsewhere.
2282 			 * All threads must be restarted.
2283 			 */
2284 			p->p_flag &= ~P_STOPPED_SIG;
2285 			goto runfast;
2286 		}
2287 
2288 		if (prop & SIGPROP_CONT) {
2289 			/*
2290 			 * If traced process is already stopped,
2291 			 * then no further action is necessary.
2292 			 */
2293 			if (p->p_flag & P_TRACED)
2294 				goto out;
2295 			/*
2296 			 * If SIGCONT is default (or ignored), we continue the
2297 			 * process but don't leave the signal in sigqueue as
2298 			 * it has no further action.  If SIGCONT is held, we
2299 			 * continue the process and leave the signal in
2300 			 * sigqueue.  If the process catches SIGCONT, let it
2301 			 * handle the signal itself.  If it isn't waiting on
2302 			 * an event, it goes back to run state.
2303 			 * Otherwise, process goes back to sleep state.
2304 			 */
2305 			p->p_flag &= ~P_STOPPED_SIG;
2306 			PROC_SLOCK(p);
2307 			if (p->p_numthreads == p->p_suspcount) {
2308 				PROC_SUNLOCK(p);
2309 				p->p_flag |= P_CONTINUED;
2310 				p->p_xsig = SIGCONT;
2311 				PROC_LOCK(p->p_pptr);
2312 				childproc_continued(p);
2313 				PROC_UNLOCK(p->p_pptr);
2314 				PROC_SLOCK(p);
2315 			}
2316 			if (action == SIG_DFL) {
2317 				thread_unsuspend(p);
2318 				PROC_SUNLOCK(p);
2319 				sigqueue_delete(sigqueue, sig);
2320 				goto out;
2321 			}
2322 			if (action == SIG_CATCH) {
2323 				/*
2324 				 * The process wants to catch it so it needs
2325 				 * to run at least one thread, but which one?
2326 				 */
2327 				PROC_SUNLOCK(p);
2328 				goto runfast;
2329 			}
2330 			/*
2331 			 * The signal is not ignored or caught.
2332 			 */
2333 			thread_unsuspend(p);
2334 			PROC_SUNLOCK(p);
2335 			goto out;
2336 		}
2337 
2338 		if (prop & SIGPROP_STOP) {
2339 			/*
2340 			 * If traced process is already stopped,
2341 			 * then no further action is necessary.
2342 			 */
2343 			if (p->p_flag & P_TRACED)
2344 				goto out;
2345 			/*
2346 			 * Already stopped, don't need to stop again
2347 			 * (If we did the shell could get confused).
2348 			 * Just make sure the signal STOP bit set.
2349 			 */
2350 			p->p_flag |= P_STOPPED_SIG;
2351 			sigqueue_delete(sigqueue, sig);
2352 			goto out;
2353 		}
2354 
2355 		/*
2356 		 * All other kinds of signals:
2357 		 * If a thread is sleeping interruptibly, simulate a
2358 		 * wakeup so that when it is continued it will be made
2359 		 * runnable and can look at the signal.  However, don't make
2360 		 * the PROCESS runnable, leave it stopped.
2361 		 * It may run a bit until it hits a thread_suspend_check().
2362 		 */
2363 		PROC_SLOCK(p);
2364 		thread_lock(td);
2365 		if (TD_CAN_ABORT(td))
2366 			wakeup_swapper = sleepq_abort(td, intrval);
2367 		else
2368 			thread_unlock(td);
2369 		PROC_SUNLOCK(p);
2370 		goto out;
2371 		/*
2372 		 * Mutexes are short lived. Threads waiting on them will
2373 		 * hit thread_suspend_check() soon.
2374 		 */
2375 	} else if (p->p_state == PRS_NORMAL) {
2376 		if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2377 			tdsigwakeup(td, sig, action, intrval);
2378 			goto out;
2379 		}
2380 
2381 		MPASS(action == SIG_DFL);
2382 
2383 		if (prop & SIGPROP_STOP) {
2384 			if (p->p_flag & (P_PPWAIT|P_WEXIT))
2385 				goto out;
2386 			p->p_flag |= P_STOPPED_SIG;
2387 			p->p_xsig = sig;
2388 			PROC_SLOCK(p);
2389 			wakeup_swapper = sig_suspend_threads(td, p, 1);
2390 			if (p->p_numthreads == p->p_suspcount) {
2391 				/*
2392 				 * only thread sending signal to another
2393 				 * process can reach here, if thread is sending
2394 				 * signal to its process, because thread does
2395 				 * not suspend itself here, p_numthreads
2396 				 * should never be equal to p_suspcount.
2397 				 */
2398 				thread_stopped(p);
2399 				PROC_SUNLOCK(p);
2400 				sigqueue_delete_proc(p, p->p_xsig);
2401 			} else
2402 				PROC_SUNLOCK(p);
2403 			goto out;
2404 		}
2405 	} else {
2406 		/* Not in "NORMAL" state. discard the signal. */
2407 		sigqueue_delete(sigqueue, sig);
2408 		goto out;
2409 	}
2410 
2411 	/*
2412 	 * The process is not stopped so we need to apply the signal to all the
2413 	 * running threads.
2414 	 */
2415 runfast:
2416 	tdsigwakeup(td, sig, action, intrval);
2417 	PROC_SLOCK(p);
2418 	thread_unsuspend(p);
2419 	PROC_SUNLOCK(p);
2420 out:
2421 	/* If we jump here, proc slock should not be owned. */
2422 	PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2423 	if (wakeup_swapper)
2424 		kick_proc0();
2425 
2426 	return (ret);
2427 }
2428 
2429 /*
2430  * The force of a signal has been directed against a single
2431  * thread.  We need to see what we can do about knocking it
2432  * out of any sleep it may be in etc.
2433  */
2434 static void
2435 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2436 {
2437 	struct proc *p = td->td_proc;
2438 	int prop, wakeup_swapper;
2439 
2440 	PROC_LOCK_ASSERT(p, MA_OWNED);
2441 	prop = sigprop(sig);
2442 
2443 	PROC_SLOCK(p);
2444 	thread_lock(td);
2445 	/*
2446 	 * Bring the priority of a thread up if we want it to get
2447 	 * killed in this lifetime.  Be careful to avoid bumping the
2448 	 * priority of the idle thread, since we still allow to signal
2449 	 * kernel processes.
2450 	 */
2451 	if (action == SIG_DFL && (prop & SIGPROP_KILL) != 0 &&
2452 	    td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2453 		sched_prio(td, PUSER);
2454 	if (TD_ON_SLEEPQ(td)) {
2455 		/*
2456 		 * If thread is sleeping uninterruptibly
2457 		 * we can't interrupt the sleep... the signal will
2458 		 * be noticed when the process returns through
2459 		 * trap() or syscall().
2460 		 */
2461 		if ((td->td_flags & TDF_SINTR) == 0)
2462 			goto out;
2463 		/*
2464 		 * If SIGCONT is default (or ignored) and process is
2465 		 * asleep, we are finished; the process should not
2466 		 * be awakened.
2467 		 */
2468 		if ((prop & SIGPROP_CONT) && action == SIG_DFL) {
2469 			thread_unlock(td);
2470 			PROC_SUNLOCK(p);
2471 			sigqueue_delete(&p->p_sigqueue, sig);
2472 			/*
2473 			 * It may be on either list in this state.
2474 			 * Remove from both for now.
2475 			 */
2476 			sigqueue_delete(&td->td_sigqueue, sig);
2477 			return;
2478 		}
2479 
2480 		/*
2481 		 * Don't awaken a sleeping thread for SIGSTOP if the
2482 		 * STOP signal is deferred.
2483 		 */
2484 		if ((prop & SIGPROP_STOP) != 0 && (td->td_flags & (TDF_SBDRY |
2485 		    TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2486 			goto out;
2487 
2488 		/*
2489 		 * Give low priority threads a better chance to run.
2490 		 */
2491 		if (td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2492 			sched_prio(td, PUSER);
2493 
2494 		wakeup_swapper = sleepq_abort(td, intrval);
2495 		PROC_SUNLOCK(p);
2496 		if (wakeup_swapper)
2497 			kick_proc0();
2498 		return;
2499 	}
2500 
2501 	/*
2502 	 * Other states do nothing with the signal immediately,
2503 	 * other than kicking ourselves if we are running.
2504 	 * It will either never be noticed, or noticed very soon.
2505 	 */
2506 #ifdef SMP
2507 	if (TD_IS_RUNNING(td) && td != curthread)
2508 		forward_signal(td);
2509 #endif
2510 
2511 out:
2512 	PROC_SUNLOCK(p);
2513 	thread_unlock(td);
2514 }
2515 
2516 static int
2517 sig_suspend_threads(struct thread *td, struct proc *p, int sending)
2518 {
2519 	struct thread *td2;
2520 	int wakeup_swapper;
2521 
2522 	PROC_LOCK_ASSERT(p, MA_OWNED);
2523 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2524 	MPASS(sending || td == curthread);
2525 
2526 	wakeup_swapper = 0;
2527 	FOREACH_THREAD_IN_PROC(p, td2) {
2528 		thread_lock(td2);
2529 		td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
2530 		if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2531 		    (td2->td_flags & TDF_SINTR)) {
2532 			if (td2->td_flags & TDF_SBDRY) {
2533 				/*
2534 				 * Once a thread is asleep with
2535 				 * TDF_SBDRY and without TDF_SERESTART
2536 				 * or TDF_SEINTR set, it should never
2537 				 * become suspended due to this check.
2538 				 */
2539 				KASSERT(!TD_IS_SUSPENDED(td2),
2540 				    ("thread with deferred stops suspended"));
2541 				if (TD_SBDRY_INTR(td2)) {
2542 					wakeup_swapper |= sleepq_abort(td2,
2543 					    TD_SBDRY_ERRNO(td2));
2544 					continue;
2545 				}
2546 			} else if (!TD_IS_SUSPENDED(td2))
2547 				thread_suspend_one(td2);
2548 		} else if (!TD_IS_SUSPENDED(td2)) {
2549 			if (sending || td != td2)
2550 				td2->td_flags |= TDF_ASTPENDING;
2551 #ifdef SMP
2552 			if (TD_IS_RUNNING(td2) && td2 != td)
2553 				forward_signal(td2);
2554 #endif
2555 		}
2556 		thread_unlock(td2);
2557 	}
2558 	return (wakeup_swapper);
2559 }
2560 
2561 /*
2562  * Stop the process for an event deemed interesting to the debugger. If si is
2563  * non-NULL, this is a signal exchange; the new signal requested by the
2564  * debugger will be returned for handling. If si is NULL, this is some other
2565  * type of interesting event. The debugger may request a signal be delivered in
2566  * that case as well, however it will be deferred until it can be handled.
2567  */
2568 int
2569 ptracestop(struct thread *td, int sig, ksiginfo_t *si)
2570 {
2571 	struct proc *p = td->td_proc;
2572 	struct thread *td2;
2573 	ksiginfo_t ksi;
2574 
2575 	PROC_LOCK_ASSERT(p, MA_OWNED);
2576 	KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2577 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2578 	    &p->p_mtx.lock_object, "Stopping for traced signal");
2579 
2580 	td->td_xsig = sig;
2581 
2582 	if (si == NULL || (si->ksi_flags & KSI_PTRACE) == 0) {
2583 		td->td_dbgflags |= TDB_XSIG;
2584 		CTR4(KTR_PTRACE, "ptracestop: tid %d (pid %d) flags %#x sig %d",
2585 		    td->td_tid, p->p_pid, td->td_dbgflags, sig);
2586 		PROC_SLOCK(p);
2587 		while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2588 			if (P_KILLED(p)) {
2589 				/*
2590 				 * Ensure that, if we've been PT_KILLed, the
2591 				 * exit status reflects that. Another thread
2592 				 * may also be in ptracestop(), having just
2593 				 * received the SIGKILL, but this thread was
2594 				 * unsuspended first.
2595 				 */
2596 				td->td_dbgflags &= ~TDB_XSIG;
2597 				td->td_xsig = SIGKILL;
2598 				p->p_ptevents = 0;
2599 				break;
2600 			}
2601 			if (p->p_flag & P_SINGLE_EXIT &&
2602 			    !(td->td_dbgflags & TDB_EXIT)) {
2603 				/*
2604 				 * Ignore ptrace stops except for thread exit
2605 				 * events when the process exits.
2606 				 */
2607 				td->td_dbgflags &= ~TDB_XSIG;
2608 				PROC_SUNLOCK(p);
2609 				return (0);
2610 			}
2611 
2612 			/*
2613 			 * Make wait(2) work.  Ensure that right after the
2614 			 * attach, the thread which was decided to become the
2615 			 * leader of attach gets reported to the waiter.
2616 			 * Otherwise, just avoid overwriting another thread's
2617 			 * assignment to p_xthread.  If another thread has
2618 			 * already set p_xthread, the current thread will get
2619 			 * a chance to report itself upon the next iteration.
2620 			 */
2621 			if ((td->td_dbgflags & TDB_FSTP) != 0 ||
2622 			    ((p->p_flag2 & P2_PTRACE_FSTP) == 0 &&
2623 			    p->p_xthread == NULL)) {
2624 				p->p_xsig = sig;
2625 				p->p_xthread = td;
2626 
2627 				/*
2628 				 * If we are on sleepqueue already,
2629 				 * let sleepqueue code decide if it
2630 				 * needs to go sleep after attach.
2631 				 */
2632 				if (td->td_wchan == NULL)
2633 					td->td_dbgflags &= ~TDB_FSTP;
2634 
2635 				p->p_flag2 &= ~P2_PTRACE_FSTP;
2636 				p->p_flag |= P_STOPPED_SIG | P_STOPPED_TRACE;
2637 				sig_suspend_threads(td, p, 0);
2638 			}
2639 			if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2640 				td->td_dbgflags &= ~TDB_STOPATFORK;
2641 			}
2642 stopme:
2643 			thread_suspend_switch(td, p);
2644 			if (p->p_xthread == td)
2645 				p->p_xthread = NULL;
2646 			if (!(p->p_flag & P_TRACED))
2647 				break;
2648 			if (td->td_dbgflags & TDB_SUSPEND) {
2649 				if (p->p_flag & P_SINGLE_EXIT)
2650 					break;
2651 				goto stopme;
2652 			}
2653 		}
2654 		PROC_SUNLOCK(p);
2655 	}
2656 
2657 	if (si != NULL && sig == td->td_xsig) {
2658 		/* Parent wants us to take the original signal unchanged. */
2659 		si->ksi_flags |= KSI_HEAD;
2660 		if (sigqueue_add(&td->td_sigqueue, sig, si) != 0)
2661 			si->ksi_signo = 0;
2662 	} else if (td->td_xsig != 0) {
2663 		/*
2664 		 * If parent wants us to take a new signal, then it will leave
2665 		 * it in td->td_xsig; otherwise we just look for signals again.
2666 		 */
2667 		ksiginfo_init(&ksi);
2668 		ksi.ksi_signo = td->td_xsig;
2669 		ksi.ksi_flags |= KSI_PTRACE;
2670 		td2 = sigtd(p, td->td_xsig, false);
2671 		tdsendsignal(p, td2, td->td_xsig, &ksi);
2672 		if (td != td2)
2673 			return (0);
2674 	}
2675 
2676 	return (td->td_xsig);
2677 }
2678 
2679 void
2680 reschedule_signals(struct proc *p, sigset_t block, int flags)
2681 {
2682 	struct sigacts *ps;
2683 	struct thread *td;
2684 	int sig;
2685 	bool fastblk, pslocked;
2686 
2687 	PROC_LOCK_ASSERT(p, MA_OWNED);
2688 	ps = p->p_sigacts;
2689 	pslocked = (flags & SIGPROCMASK_PS_LOCKED) != 0;
2690 	mtx_assert(&ps->ps_mtx, pslocked ? MA_OWNED : MA_NOTOWNED);
2691 	if (SIGISEMPTY(p->p_siglist))
2692 		return;
2693 	SIGSETAND(block, p->p_siglist);
2694 	fastblk = (flags & SIGPROCMASK_FASTBLK) != 0;
2695 	while ((sig = sig_ffs(&block)) != 0) {
2696 		SIGDELSET(block, sig);
2697 		td = sigtd(p, sig, fastblk);
2698 
2699 		/*
2700 		 * If sigtd() selected us despite sigfastblock is
2701 		 * blocking, do not activate AST or wake us, to avoid
2702 		 * loop in AST handler.
2703 		 */
2704 		if (fastblk && td == curthread)
2705 			continue;
2706 
2707 		signotify(td);
2708 		if (!pslocked)
2709 			mtx_lock(&ps->ps_mtx);
2710 		if (p->p_flag & P_TRACED ||
2711 		    (SIGISMEMBER(ps->ps_sigcatch, sig) &&
2712 		    !SIGISMEMBER(td->td_sigmask, sig))) {
2713 			tdsigwakeup(td, sig, SIG_CATCH,
2714 			    (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2715 			    ERESTART));
2716 		}
2717 		if (!pslocked)
2718 			mtx_unlock(&ps->ps_mtx);
2719 	}
2720 }
2721 
2722 void
2723 tdsigcleanup(struct thread *td)
2724 {
2725 	struct proc *p;
2726 	sigset_t unblocked;
2727 
2728 	p = td->td_proc;
2729 	PROC_LOCK_ASSERT(p, MA_OWNED);
2730 
2731 	sigqueue_flush(&td->td_sigqueue);
2732 	if (p->p_numthreads == 1)
2733 		return;
2734 
2735 	/*
2736 	 * Since we cannot handle signals, notify signal post code
2737 	 * about this by filling the sigmask.
2738 	 *
2739 	 * Also, if needed, wake up thread(s) that do not block the
2740 	 * same signals as the exiting thread, since the thread might
2741 	 * have been selected for delivery and woken up.
2742 	 */
2743 	SIGFILLSET(unblocked);
2744 	SIGSETNAND(unblocked, td->td_sigmask);
2745 	SIGFILLSET(td->td_sigmask);
2746 	reschedule_signals(p, unblocked, 0);
2747 
2748 }
2749 
2750 static int
2751 sigdeferstop_curr_flags(int cflags)
2752 {
2753 
2754 	MPASS((cflags & (TDF_SEINTR | TDF_SERESTART)) == 0 ||
2755 	    (cflags & TDF_SBDRY) != 0);
2756 	return (cflags & (TDF_SBDRY | TDF_SEINTR | TDF_SERESTART));
2757 }
2758 
2759 /*
2760  * Defer the delivery of SIGSTOP for the current thread, according to
2761  * the requested mode.  Returns previous flags, which must be restored
2762  * by sigallowstop().
2763  *
2764  * TDF_SBDRY, TDF_SEINTR, and TDF_SERESTART flags are only set and
2765  * cleared by the current thread, which allow the lock-less read-only
2766  * accesses below.
2767  */
2768 int
2769 sigdeferstop_impl(int mode)
2770 {
2771 	struct thread *td;
2772 	int cflags, nflags;
2773 
2774 	td = curthread;
2775 	cflags = sigdeferstop_curr_flags(td->td_flags);
2776 	switch (mode) {
2777 	case SIGDEFERSTOP_NOP:
2778 		nflags = cflags;
2779 		break;
2780 	case SIGDEFERSTOP_OFF:
2781 		nflags = 0;
2782 		break;
2783 	case SIGDEFERSTOP_SILENT:
2784 		nflags = (cflags | TDF_SBDRY) & ~(TDF_SEINTR | TDF_SERESTART);
2785 		break;
2786 	case SIGDEFERSTOP_EINTR:
2787 		nflags = (cflags | TDF_SBDRY | TDF_SEINTR) & ~TDF_SERESTART;
2788 		break;
2789 	case SIGDEFERSTOP_ERESTART:
2790 		nflags = (cflags | TDF_SBDRY | TDF_SERESTART) & ~TDF_SEINTR;
2791 		break;
2792 	default:
2793 		panic("sigdeferstop: invalid mode %x", mode);
2794 		break;
2795 	}
2796 	if (cflags == nflags)
2797 		return (SIGDEFERSTOP_VAL_NCHG);
2798 	thread_lock(td);
2799 	td->td_flags = (td->td_flags & ~cflags) | nflags;
2800 	thread_unlock(td);
2801 	return (cflags);
2802 }
2803 
2804 /*
2805  * Restores the STOP handling mode, typically permitting the delivery
2806  * of SIGSTOP for the current thread.  This does not immediately
2807  * suspend if a stop was posted.  Instead, the thread will suspend
2808  * either via ast() or a subsequent interruptible sleep.
2809  */
2810 void
2811 sigallowstop_impl(int prev)
2812 {
2813 	struct thread *td;
2814 	int cflags;
2815 
2816 	KASSERT(prev != SIGDEFERSTOP_VAL_NCHG, ("failed sigallowstop"));
2817 	KASSERT((prev & ~(TDF_SBDRY | TDF_SEINTR | TDF_SERESTART)) == 0,
2818 	    ("sigallowstop: incorrect previous mode %x", prev));
2819 	td = curthread;
2820 	cflags = sigdeferstop_curr_flags(td->td_flags);
2821 	if (cflags != prev) {
2822 		thread_lock(td);
2823 		td->td_flags = (td->td_flags & ~cflags) | prev;
2824 		thread_unlock(td);
2825 	}
2826 }
2827 
2828 /*
2829  * If the current process has received a signal (should be caught or cause
2830  * termination, should interrupt current syscall), return the signal number.
2831  * Stop signals with default action are processed immediately, then cleared;
2832  * they aren't returned.  This is checked after each entry to the system for
2833  * a syscall or trap (though this can usually be done without calling issignal
2834  * by checking the pending signal masks in cursig.) The normal call
2835  * sequence is
2836  *
2837  *	while (sig = cursig(curthread))
2838  *		postsig(sig);
2839  */
2840 static int
2841 issignal(struct thread *td)
2842 {
2843 	struct proc *p;
2844 	struct sigacts *ps;
2845 	struct sigqueue *queue;
2846 	sigset_t sigpending;
2847 	ksiginfo_t ksi;
2848 	int prop, sig, traced;
2849 
2850 	p = td->td_proc;
2851 	ps = p->p_sigacts;
2852 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2853 	PROC_LOCK_ASSERT(p, MA_OWNED);
2854 	for (;;) {
2855 		traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
2856 
2857 		sigpending = td->td_sigqueue.sq_signals;
2858 		SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
2859 		SIGSETNAND(sigpending, td->td_sigmask);
2860 
2861 		if ((p->p_flag & P_PPWAIT) != 0 || (td->td_flags &
2862 		    (TDF_SBDRY | TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2863 			SIG_STOPSIGMASK(sigpending);
2864 		if (SIGISEMPTY(sigpending))	/* no signal to send */
2865 			return (0);
2866 
2867 		/*
2868 		 * Do fast sigblock if requested by usermode.  Since
2869 		 * we do know that there was a signal pending at this
2870 		 * point, set the FAST_SIGBLOCK_PEND as indicator for
2871 		 * usermode to perform a dummy call to
2872 		 * FAST_SIGBLOCK_UNBLOCK, which causes immediate
2873 		 * delivery of postponed pending signal.
2874 		 */
2875 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
2876 			if (td->td_sigblock_val != 0)
2877 				SIGSETNAND(sigpending, fastblock_mask);
2878 			if (SIGISEMPTY(sigpending)) {
2879 				td->td_pflags |= TDP_SIGFASTPENDING;
2880 				return (0);
2881 			}
2882 		}
2883 
2884 		if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED &&
2885 		    (p->p_flag2 & P2_PTRACE_FSTP) != 0 &&
2886 		    SIGISMEMBER(sigpending, SIGSTOP)) {
2887 			/*
2888 			 * If debugger just attached, always consume
2889 			 * SIGSTOP from ptrace(PT_ATTACH) first, to
2890 			 * execute the debugger attach ritual in
2891 			 * order.
2892 			 */
2893 			sig = SIGSTOP;
2894 			td->td_dbgflags |= TDB_FSTP;
2895 		} else {
2896 			sig = sig_ffs(&sigpending);
2897 		}
2898 
2899 		if (p->p_stops & S_SIG) {
2900 			mtx_unlock(&ps->ps_mtx);
2901 			stopevent(p, S_SIG, sig);
2902 			mtx_lock(&ps->ps_mtx);
2903 		}
2904 
2905 		/*
2906 		 * We should see pending but ignored signals
2907 		 * only if P_TRACED was on when they were posted.
2908 		 */
2909 		if (SIGISMEMBER(ps->ps_sigignore, sig) && (traced == 0)) {
2910 			sigqueue_delete(&td->td_sigqueue, sig);
2911 			sigqueue_delete(&p->p_sigqueue, sig);
2912 			continue;
2913 		}
2914 		if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED) {
2915 			/*
2916 			 * If traced, always stop.
2917 			 * Remove old signal from queue before the stop.
2918 			 * XXX shrug off debugger, it causes siginfo to
2919 			 * be thrown away.
2920 			 */
2921 			queue = &td->td_sigqueue;
2922 			ksiginfo_init(&ksi);
2923 			if (sigqueue_get(queue, sig, &ksi) == 0) {
2924 				queue = &p->p_sigqueue;
2925 				sigqueue_get(queue, sig, &ksi);
2926 			}
2927 			td->td_si = ksi.ksi_info;
2928 
2929 			mtx_unlock(&ps->ps_mtx);
2930 			sig = ptracestop(td, sig, &ksi);
2931 			mtx_lock(&ps->ps_mtx);
2932 
2933 			td->td_si.si_signo = 0;
2934 
2935 			/*
2936 			 * Keep looking if the debugger discarded or
2937 			 * replaced the signal.
2938 			 */
2939 			if (sig == 0)
2940 				continue;
2941 
2942 			/*
2943 			 * If the signal became masked, re-queue it.
2944 			 */
2945 			if (SIGISMEMBER(td->td_sigmask, sig)) {
2946 				ksi.ksi_flags |= KSI_HEAD;
2947 				sigqueue_add(&p->p_sigqueue, sig, &ksi);
2948 				continue;
2949 			}
2950 
2951 			/*
2952 			 * If the traced bit got turned off, requeue
2953 			 * the signal and go back up to the top to
2954 			 * rescan signals.  This ensures that p_sig*
2955 			 * and p_sigact are consistent.
2956 			 */
2957 			if ((p->p_flag & P_TRACED) == 0) {
2958 				ksi.ksi_flags |= KSI_HEAD;
2959 				sigqueue_add(queue, sig, &ksi);
2960 				continue;
2961 			}
2962 		}
2963 
2964 		prop = sigprop(sig);
2965 
2966 		/*
2967 		 * Decide whether the signal should be returned.
2968 		 * Return the signal's number, or fall through
2969 		 * to clear it from the pending mask.
2970 		 */
2971 		switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
2972 
2973 		case (intptr_t)SIG_DFL:
2974 			/*
2975 			 * Don't take default actions on system processes.
2976 			 */
2977 			if (p->p_pid <= 1) {
2978 #ifdef DIAGNOSTIC
2979 				/*
2980 				 * Are you sure you want to ignore SIGSEGV
2981 				 * in init? XXX
2982 				 */
2983 				printf("Process (pid %lu) got signal %d\n",
2984 					(u_long)p->p_pid, sig);
2985 #endif
2986 				break;		/* == ignore */
2987 			}
2988 			/*
2989 			 * If there is a pending stop signal to process with
2990 			 * default action, stop here, then clear the signal.
2991 			 * Traced or exiting processes should ignore stops.
2992 			 * Additionally, a member of an orphaned process group
2993 			 * should ignore tty stops.
2994 			 */
2995 			if (prop & SIGPROP_STOP) {
2996 				if (p->p_flag &
2997 				    (P_TRACED | P_WEXIT | P_SINGLE_EXIT) ||
2998 				    (p->p_pgrp->pg_jobc == 0 &&
2999 				     prop & SIGPROP_TTYSTOP))
3000 					break;	/* == ignore */
3001 				if (TD_SBDRY_INTR(td)) {
3002 					KASSERT((td->td_flags & TDF_SBDRY) != 0,
3003 					    ("lost TDF_SBDRY"));
3004 					return (-1);
3005 				}
3006 				mtx_unlock(&ps->ps_mtx);
3007 				WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
3008 				    &p->p_mtx.lock_object, "Catching SIGSTOP");
3009 				sigqueue_delete(&td->td_sigqueue, sig);
3010 				sigqueue_delete(&p->p_sigqueue, sig);
3011 				p->p_flag |= P_STOPPED_SIG;
3012 				p->p_xsig = sig;
3013 				PROC_SLOCK(p);
3014 				sig_suspend_threads(td, p, 0);
3015 				thread_suspend_switch(td, p);
3016 				PROC_SUNLOCK(p);
3017 				mtx_lock(&ps->ps_mtx);
3018 				goto next;
3019 			} else if (prop & SIGPROP_IGNORE) {
3020 				/*
3021 				 * Except for SIGCONT, shouldn't get here.
3022 				 * Default action is to ignore; drop it.
3023 				 */
3024 				break;		/* == ignore */
3025 			} else
3026 				return (sig);
3027 			/*NOTREACHED*/
3028 
3029 		case (intptr_t)SIG_IGN:
3030 			/*
3031 			 * Masking above should prevent us ever trying
3032 			 * to take action on an ignored signal other
3033 			 * than SIGCONT, unless process is traced.
3034 			 */
3035 			if ((prop & SIGPROP_CONT) == 0 &&
3036 			    (p->p_flag & P_TRACED) == 0)
3037 				printf("issignal\n");
3038 			break;		/* == ignore */
3039 
3040 		default:
3041 			/*
3042 			 * This signal has an action, let
3043 			 * postsig() process it.
3044 			 */
3045 			return (sig);
3046 		}
3047 		sigqueue_delete(&td->td_sigqueue, sig);	/* take the signal! */
3048 		sigqueue_delete(&p->p_sigqueue, sig);
3049 next:;
3050 	}
3051 	/* NOTREACHED */
3052 }
3053 
3054 void
3055 thread_stopped(struct proc *p)
3056 {
3057 	int n;
3058 
3059 	PROC_LOCK_ASSERT(p, MA_OWNED);
3060 	PROC_SLOCK_ASSERT(p, MA_OWNED);
3061 	n = p->p_suspcount;
3062 	if (p == curproc)
3063 		n++;
3064 	if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
3065 		PROC_SUNLOCK(p);
3066 		p->p_flag &= ~P_WAITED;
3067 		PROC_LOCK(p->p_pptr);
3068 		childproc_stopped(p, (p->p_flag & P_TRACED) ?
3069 			CLD_TRAPPED : CLD_STOPPED);
3070 		PROC_UNLOCK(p->p_pptr);
3071 		PROC_SLOCK(p);
3072 	}
3073 }
3074 
3075 /*
3076  * Take the action for the specified signal
3077  * from the current set of pending signals.
3078  */
3079 int
3080 postsig(int sig)
3081 {
3082 	struct thread *td;
3083 	struct proc *p;
3084 	struct sigacts *ps;
3085 	sig_t action;
3086 	ksiginfo_t ksi;
3087 	sigset_t returnmask;
3088 
3089 	KASSERT(sig != 0, ("postsig"));
3090 
3091 	td = curthread;
3092 	p = td->td_proc;
3093 	PROC_LOCK_ASSERT(p, MA_OWNED);
3094 	ps = p->p_sigacts;
3095 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3096 	ksiginfo_init(&ksi);
3097 	if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
3098 	    sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
3099 		return (0);
3100 	ksi.ksi_signo = sig;
3101 	if (ksi.ksi_code == SI_TIMER)
3102 		itimer_accept(p, ksi.ksi_timerid, &ksi);
3103 	action = ps->ps_sigact[_SIG_IDX(sig)];
3104 #ifdef KTRACE
3105 	if (KTRPOINT(td, KTR_PSIG))
3106 		ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
3107 		    &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
3108 #endif
3109 	if ((p->p_stops & S_SIG) != 0) {
3110 		mtx_unlock(&ps->ps_mtx);
3111 		stopevent(p, S_SIG, sig);
3112 		mtx_lock(&ps->ps_mtx);
3113 	}
3114 
3115 	if (action == SIG_DFL) {
3116 		/*
3117 		 * Default action, where the default is to kill
3118 		 * the process.  (Other cases were ignored above.)
3119 		 */
3120 		mtx_unlock(&ps->ps_mtx);
3121 		proc_td_siginfo_capture(td, &ksi.ksi_info);
3122 		sigexit(td, sig);
3123 		/* NOTREACHED */
3124 	} else {
3125 		/*
3126 		 * If we get here, the signal must be caught.
3127 		 */
3128 		KASSERT(action != SIG_IGN, ("postsig action %p", action));
3129 		KASSERT(!SIGISMEMBER(td->td_sigmask, sig),
3130 		    ("postsig action: blocked sig %d", sig));
3131 
3132 		/*
3133 		 * Set the new mask value and also defer further
3134 		 * occurrences of this signal.
3135 		 *
3136 		 * Special case: user has done a sigsuspend.  Here the
3137 		 * current mask is not of interest, but rather the
3138 		 * mask from before the sigsuspend is what we want
3139 		 * restored after the signal processing is completed.
3140 		 */
3141 		if (td->td_pflags & TDP_OLDMASK) {
3142 			returnmask = td->td_oldsigmask;
3143 			td->td_pflags &= ~TDP_OLDMASK;
3144 		} else
3145 			returnmask = td->td_sigmask;
3146 
3147 		if (p->p_sig == sig) {
3148 			p->p_sig = 0;
3149 		}
3150 		(*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
3151 		postsig_done(sig, td, ps);
3152 	}
3153 	return (1);
3154 }
3155 
3156 void
3157 proc_wkilled(struct proc *p)
3158 {
3159 
3160 	PROC_LOCK_ASSERT(p, MA_OWNED);
3161 	if ((p->p_flag & P_WKILLED) == 0) {
3162 		p->p_flag |= P_WKILLED;
3163 		/*
3164 		 * Notify swapper that there is a process to swap in.
3165 		 * The notification is racy, at worst it would take 10
3166 		 * seconds for the swapper process to notice.
3167 		 */
3168 		if ((p->p_flag & (P_INMEM | P_SWAPPINGIN)) == 0)
3169 			wakeup(&proc0);
3170 	}
3171 }
3172 
3173 /*
3174  * Kill the current process for stated reason.
3175  */
3176 void
3177 killproc(struct proc *p, char *why)
3178 {
3179 
3180 	PROC_LOCK_ASSERT(p, MA_OWNED);
3181 	CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
3182 	    p->p_comm);
3183 	log(LOG_ERR, "pid %d (%s), jid %d, uid %d, was killed: %s\n",
3184 	    p->p_pid, p->p_comm, p->p_ucred->cr_prison->pr_id,
3185 	    p->p_ucred->cr_uid, why);
3186 	proc_wkilled(p);
3187 	kern_psignal(p, SIGKILL);
3188 }
3189 
3190 /*
3191  * Force the current process to exit with the specified signal, dumping core
3192  * if appropriate.  We bypass the normal tests for masked and caught signals,
3193  * allowing unrecoverable failures to terminate the process without changing
3194  * signal state.  Mark the accounting record with the signal termination.
3195  * If dumping core, save the signal number for the debugger.  Calls exit and
3196  * does not return.
3197  */
3198 void
3199 sigexit(struct thread *td, int sig)
3200 {
3201 	struct proc *p = td->td_proc;
3202 
3203 	PROC_LOCK_ASSERT(p, MA_OWNED);
3204 	p->p_acflag |= AXSIG;
3205 	/*
3206 	 * We must be single-threading to generate a core dump.  This
3207 	 * ensures that the registers in the core file are up-to-date.
3208 	 * Also, the ELF dump handler assumes that the thread list doesn't
3209 	 * change out from under it.
3210 	 *
3211 	 * XXX If another thread attempts to single-thread before us
3212 	 *     (e.g. via fork()), we won't get a dump at all.
3213 	 */
3214 	if ((sigprop(sig) & SIGPROP_CORE) &&
3215 	    thread_single(p, SINGLE_NO_EXIT) == 0) {
3216 		p->p_sig = sig;
3217 		/*
3218 		 * Log signals which would cause core dumps
3219 		 * (Log as LOG_INFO to appease those who don't want
3220 		 * these messages.)
3221 		 * XXX : Todo, as well as euid, write out ruid too
3222 		 * Note that coredump() drops proc lock.
3223 		 */
3224 		if (coredump(td) == 0)
3225 			sig |= WCOREFLAG;
3226 		if (kern_logsigexit)
3227 			log(LOG_INFO,
3228 			    "pid %d (%s), jid %d, uid %d: exited on "
3229 			    "signal %d%s\n", p->p_pid, p->p_comm,
3230 			    p->p_ucred->cr_prison->pr_id,
3231 			    td->td_ucred->cr_uid,
3232 			    sig &~ WCOREFLAG,
3233 			    sig & WCOREFLAG ? " (core dumped)" : "");
3234 	} else
3235 		PROC_UNLOCK(p);
3236 	exit1(td, 0, sig);
3237 	/* NOTREACHED */
3238 }
3239 
3240 /*
3241  * Send queued SIGCHLD to parent when child process's state
3242  * is changed.
3243  */
3244 static void
3245 sigparent(struct proc *p, int reason, int status)
3246 {
3247 	PROC_LOCK_ASSERT(p, MA_OWNED);
3248 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3249 
3250 	if (p->p_ksi != NULL) {
3251 		p->p_ksi->ksi_signo  = SIGCHLD;
3252 		p->p_ksi->ksi_code   = reason;
3253 		p->p_ksi->ksi_status = status;
3254 		p->p_ksi->ksi_pid    = p->p_pid;
3255 		p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
3256 		if (KSI_ONQ(p->p_ksi))
3257 			return;
3258 	}
3259 	pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
3260 }
3261 
3262 static void
3263 childproc_jobstate(struct proc *p, int reason, int sig)
3264 {
3265 	struct sigacts *ps;
3266 
3267 	PROC_LOCK_ASSERT(p, MA_OWNED);
3268 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3269 
3270 	/*
3271 	 * Wake up parent sleeping in kern_wait(), also send
3272 	 * SIGCHLD to parent, but SIGCHLD does not guarantee
3273 	 * that parent will awake, because parent may masked
3274 	 * the signal.
3275 	 */
3276 	p->p_pptr->p_flag |= P_STATCHILD;
3277 	wakeup(p->p_pptr);
3278 
3279 	ps = p->p_pptr->p_sigacts;
3280 	mtx_lock(&ps->ps_mtx);
3281 	if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
3282 		mtx_unlock(&ps->ps_mtx);
3283 		sigparent(p, reason, sig);
3284 	} else
3285 		mtx_unlock(&ps->ps_mtx);
3286 }
3287 
3288 void
3289 childproc_stopped(struct proc *p, int reason)
3290 {
3291 
3292 	childproc_jobstate(p, reason, p->p_xsig);
3293 }
3294 
3295 void
3296 childproc_continued(struct proc *p)
3297 {
3298 	childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
3299 }
3300 
3301 void
3302 childproc_exited(struct proc *p)
3303 {
3304 	int reason, status;
3305 
3306 	if (WCOREDUMP(p->p_xsig)) {
3307 		reason = CLD_DUMPED;
3308 		status = WTERMSIG(p->p_xsig);
3309 	} else if (WIFSIGNALED(p->p_xsig)) {
3310 		reason = CLD_KILLED;
3311 		status = WTERMSIG(p->p_xsig);
3312 	} else {
3313 		reason = CLD_EXITED;
3314 		status = p->p_xexit;
3315 	}
3316 	/*
3317 	 * XXX avoid calling wakeup(p->p_pptr), the work is
3318 	 * done in exit1().
3319 	 */
3320 	sigparent(p, reason, status);
3321 }
3322 
3323 #define	MAX_NUM_CORE_FILES 100000
3324 #ifndef NUM_CORE_FILES
3325 #define	NUM_CORE_FILES 5
3326 #endif
3327 CTASSERT(NUM_CORE_FILES >= 0 && NUM_CORE_FILES <= MAX_NUM_CORE_FILES);
3328 static int num_cores = NUM_CORE_FILES;
3329 
3330 static int
3331 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3332 {
3333 	int error;
3334 	int new_val;
3335 
3336 	new_val = num_cores;
3337 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3338 	if (error != 0 || req->newptr == NULL)
3339 		return (error);
3340 	if (new_val > MAX_NUM_CORE_FILES)
3341 		new_val = MAX_NUM_CORE_FILES;
3342 	if (new_val < 0)
3343 		new_val = 0;
3344 	num_cores = new_val;
3345 	return (0);
3346 }
3347 SYSCTL_PROC(_debug, OID_AUTO, ncores, CTLTYPE_INT|CTLFLAG_RW,
3348 	    0, sizeof(int), sysctl_debug_num_cores_check, "I",
3349 	    "Maximum number of generated process corefiles while using index format");
3350 
3351 #define	GZIP_SUFFIX	".gz"
3352 #define	ZSTD_SUFFIX	".zst"
3353 
3354 int compress_user_cores = 0;
3355 
3356 static int
3357 sysctl_compress_user_cores(SYSCTL_HANDLER_ARGS)
3358 {
3359 	int error, val;
3360 
3361 	val = compress_user_cores;
3362 	error = sysctl_handle_int(oidp, &val, 0, req);
3363 	if (error != 0 || req->newptr == NULL)
3364 		return (error);
3365 	if (val != 0 && !compressor_avail(val))
3366 		return (EINVAL);
3367 	compress_user_cores = val;
3368 	return (error);
3369 }
3370 SYSCTL_PROC(_kern, OID_AUTO, compress_user_cores, CTLTYPE_INT | CTLFLAG_RWTUN,
3371     0, sizeof(int), sysctl_compress_user_cores, "I",
3372     "Enable compression of user corefiles ("
3373     __XSTRING(COMPRESS_GZIP) " = gzip, "
3374     __XSTRING(COMPRESS_ZSTD) " = zstd)");
3375 
3376 int compress_user_cores_level = 6;
3377 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_level, CTLFLAG_RWTUN,
3378     &compress_user_cores_level, 0,
3379     "Corefile compression level");
3380 
3381 /*
3382  * Protect the access to corefilename[] by allproc_lock.
3383  */
3384 #define	corefilename_lock	allproc_lock
3385 
3386 static char corefilename[MAXPATHLEN] = {"%N.core"};
3387 TUNABLE_STR("kern.corefile", corefilename, sizeof(corefilename));
3388 
3389 static int
3390 sysctl_kern_corefile(SYSCTL_HANDLER_ARGS)
3391 {
3392 	int error;
3393 
3394 	sx_xlock(&corefilename_lock);
3395 	error = sysctl_handle_string(oidp, corefilename, sizeof(corefilename),
3396 	    req);
3397 	sx_xunlock(&corefilename_lock);
3398 
3399 	return (error);
3400 }
3401 SYSCTL_PROC(_kern, OID_AUTO, corefile, CTLTYPE_STRING | CTLFLAG_RW |
3402     CTLFLAG_MPSAFE, 0, 0, sysctl_kern_corefile, "A",
3403     "Process corefile name format string");
3404 
3405 static void
3406 vnode_close_locked(struct thread *td, struct vnode *vp)
3407 {
3408 
3409 	VOP_UNLOCK(vp);
3410 	vn_close(vp, FWRITE, td->td_ucred, td);
3411 }
3412 
3413 /*
3414  * If the core format has a %I in it, then we need to check
3415  * for existing corefiles before defining a name.
3416  * To do this we iterate over 0..ncores to find a
3417  * non-existing core file name to use. If all core files are
3418  * already used we choose the oldest one.
3419  */
3420 static int
3421 corefile_open_last(struct thread *td, char *name, int indexpos,
3422     int indexlen, int ncores, struct vnode **vpp)
3423 {
3424 	struct vnode *oldvp, *nextvp, *vp;
3425 	struct vattr vattr;
3426 	struct nameidata nd;
3427 	int error, i, flags, oflags, cmode;
3428 	char ch;
3429 	struct timespec lasttime;
3430 
3431 	nextvp = oldvp = NULL;
3432 	cmode = S_IRUSR | S_IWUSR;
3433 	oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3434 	    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3435 
3436 	for (i = 0; i < ncores; i++) {
3437 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
3438 
3439 		ch = name[indexpos + indexlen];
3440 		(void)snprintf(name + indexpos, indexlen + 1, "%.*u", indexlen,
3441 		    i);
3442 		name[indexpos + indexlen] = ch;
3443 
3444 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3445 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3446 		    NULL);
3447 		if (error != 0)
3448 			break;
3449 
3450 		vp = nd.ni_vp;
3451 		NDFREE(&nd, NDF_ONLY_PNBUF);
3452 		if ((flags & O_CREAT) == O_CREAT) {
3453 			nextvp = vp;
3454 			break;
3455 		}
3456 
3457 		error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3458 		if (error != 0) {
3459 			vnode_close_locked(td, vp);
3460 			break;
3461 		}
3462 
3463 		if (oldvp == NULL ||
3464 		    lasttime.tv_sec > vattr.va_mtime.tv_sec ||
3465 		    (lasttime.tv_sec == vattr.va_mtime.tv_sec &&
3466 		    lasttime.tv_nsec >= vattr.va_mtime.tv_nsec)) {
3467 			if (oldvp != NULL)
3468 				vnode_close_locked(td, oldvp);
3469 			oldvp = vp;
3470 			lasttime = vattr.va_mtime;
3471 		} else {
3472 			vnode_close_locked(td, vp);
3473 		}
3474 	}
3475 
3476 	if (oldvp != NULL) {
3477 		if (nextvp == NULL) {
3478 			if ((td->td_proc->p_flag & P_SUGID) != 0) {
3479 				error = EFAULT;
3480 				vnode_close_locked(td, oldvp);
3481 			} else {
3482 				nextvp = oldvp;
3483 			}
3484 		} else {
3485 			vnode_close_locked(td, oldvp);
3486 		}
3487 	}
3488 	if (error != 0) {
3489 		if (nextvp != NULL)
3490 			vnode_close_locked(td, oldvp);
3491 	} else {
3492 		*vpp = nextvp;
3493 	}
3494 
3495 	return (error);
3496 }
3497 
3498 /*
3499  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3500  * Expand the name described in corefilename, using name, uid, and pid
3501  * and open/create core file.
3502  * corefilename is a printf-like string, with three format specifiers:
3503  *	%N	name of process ("name")
3504  *	%P	process id (pid)
3505  *	%U	user id (uid)
3506  * For example, "%N.core" is the default; they can be disabled completely
3507  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3508  * This is controlled by the sysctl variable kern.corefile (see above).
3509  */
3510 static int
3511 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3512     int compress, int signum, struct vnode **vpp, char **namep)
3513 {
3514 	struct sbuf sb;
3515 	struct nameidata nd;
3516 	const char *format;
3517 	char *hostname, *name;
3518 	int cmode, error, flags, i, indexpos, indexlen, oflags, ncores;
3519 
3520 	hostname = NULL;
3521 	format = corefilename;
3522 	name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3523 	indexlen = 0;
3524 	indexpos = -1;
3525 	ncores = num_cores;
3526 	(void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3527 	sx_slock(&corefilename_lock);
3528 	for (i = 0; format[i] != '\0'; i++) {
3529 		switch (format[i]) {
3530 		case '%':	/* Format character */
3531 			i++;
3532 			switch (format[i]) {
3533 			case '%':
3534 				sbuf_putc(&sb, '%');
3535 				break;
3536 			case 'H':	/* hostname */
3537 				if (hostname == NULL) {
3538 					hostname = malloc(MAXHOSTNAMELEN,
3539 					    M_TEMP, M_WAITOK);
3540 				}
3541 				getcredhostname(td->td_ucred, hostname,
3542 				    MAXHOSTNAMELEN);
3543 				sbuf_printf(&sb, "%s", hostname);
3544 				break;
3545 			case 'I':	/* autoincrementing index */
3546 				if (indexpos != -1) {
3547 					sbuf_printf(&sb, "%%I");
3548 					break;
3549 				}
3550 
3551 				indexpos = sbuf_len(&sb);
3552 				sbuf_printf(&sb, "%u", ncores - 1);
3553 				indexlen = sbuf_len(&sb) - indexpos;
3554 				break;
3555 			case 'N':	/* process name */
3556 				sbuf_printf(&sb, "%s", comm);
3557 				break;
3558 			case 'P':	/* process id */
3559 				sbuf_printf(&sb, "%u", pid);
3560 				break;
3561 			case 'S':	/* signal number */
3562 				sbuf_printf(&sb, "%i", signum);
3563 				break;
3564 			case 'U':	/* user id */
3565 				sbuf_printf(&sb, "%u", uid);
3566 				break;
3567 			default:
3568 				log(LOG_ERR,
3569 				    "Unknown format character %c in "
3570 				    "corename `%s'\n", format[i], format);
3571 				break;
3572 			}
3573 			break;
3574 		default:
3575 			sbuf_putc(&sb, format[i]);
3576 			break;
3577 		}
3578 	}
3579 	sx_sunlock(&corefilename_lock);
3580 	free(hostname, M_TEMP);
3581 	if (compress == COMPRESS_GZIP)
3582 		sbuf_printf(&sb, GZIP_SUFFIX);
3583 	else if (compress == COMPRESS_ZSTD)
3584 		sbuf_printf(&sb, ZSTD_SUFFIX);
3585 	if (sbuf_error(&sb) != 0) {
3586 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
3587 		    "long\n", (long)pid, comm, (u_long)uid);
3588 		sbuf_delete(&sb);
3589 		free(name, M_TEMP);
3590 		return (ENOMEM);
3591 	}
3592 	sbuf_finish(&sb);
3593 	sbuf_delete(&sb);
3594 
3595 	if (indexpos != -1) {
3596 		error = corefile_open_last(td, name, indexpos, indexlen, ncores,
3597 		    vpp);
3598 		if (error != 0) {
3599 			log(LOG_ERR,
3600 			    "pid %d (%s), uid (%u):  Path `%s' failed "
3601 			    "on initial open test, error = %d\n",
3602 			    pid, comm, uid, name, error);
3603 		}
3604 	} else {
3605 		cmode = S_IRUSR | S_IWUSR;
3606 		oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3607 		    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3608 		flags = O_CREAT | FWRITE | O_NOFOLLOW;
3609 		if ((td->td_proc->p_flag & P_SUGID) != 0)
3610 			flags |= O_EXCL;
3611 
3612 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3613 		error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3614 		    NULL);
3615 		if (error == 0) {
3616 			*vpp = nd.ni_vp;
3617 			NDFREE(&nd, NDF_ONLY_PNBUF);
3618 		}
3619 	}
3620 
3621 	if (error != 0) {
3622 #ifdef AUDIT
3623 		audit_proc_coredump(td, name, error);
3624 #endif
3625 		free(name, M_TEMP);
3626 		return (error);
3627 	}
3628 	*namep = name;
3629 	return (0);
3630 }
3631 
3632 /*
3633  * Dump a process' core.  The main routine does some
3634  * policy checking, and creates the name of the coredump;
3635  * then it passes on a vnode and a size limit to the process-specific
3636  * coredump routine if there is one; if there _is not_ one, it returns
3637  * ENOSYS; otherwise it returns the error from the process-specific routine.
3638  */
3639 
3640 static int
3641 coredump(struct thread *td)
3642 {
3643 	struct proc *p = td->td_proc;
3644 	struct ucred *cred = td->td_ucred;
3645 	struct vnode *vp;
3646 	struct flock lf;
3647 	struct vattr vattr;
3648 	size_t fullpathsize;
3649 	int error, error1, locked;
3650 	char *name;			/* name of corefile */
3651 	void *rl_cookie;
3652 	off_t limit;
3653 	char *fullpath, *freepath = NULL;
3654 	struct sbuf *sb;
3655 
3656 	PROC_LOCK_ASSERT(p, MA_OWNED);
3657 	MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
3658 	_STOPEVENT(p, S_CORE, 0);
3659 
3660 	if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0) ||
3661 	    (p->p_flag2 & P2_NOTRACE) != 0) {
3662 		PROC_UNLOCK(p);
3663 		return (EFAULT);
3664 	}
3665 
3666 	/*
3667 	 * Note that the bulk of limit checking is done after
3668 	 * the corefile is created.  The exception is if the limit
3669 	 * for corefiles is 0, in which case we don't bother
3670 	 * creating the corefile at all.  This layout means that
3671 	 * a corefile is truncated instead of not being created,
3672 	 * if it is larger than the limit.
3673 	 */
3674 	limit = (off_t)lim_cur(td, RLIMIT_CORE);
3675 	if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
3676 		PROC_UNLOCK(p);
3677 		return (EFBIG);
3678 	}
3679 	PROC_UNLOCK(p);
3680 
3681 	error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td,
3682 	    compress_user_cores, p->p_sig, &vp, &name);
3683 	if (error != 0)
3684 		return (error);
3685 
3686 	/*
3687 	 * Don't dump to non-regular files or files with links.
3688 	 * Do not dump into system files. Effective user must own the corefile.
3689 	 */
3690 	if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
3691 	    vattr.va_nlink != 1 || (vp->v_vflag & VV_SYSTEM) != 0 ||
3692 	    vattr.va_uid != cred->cr_uid) {
3693 		VOP_UNLOCK(vp);
3694 		error = EFAULT;
3695 		goto out;
3696 	}
3697 
3698 	VOP_UNLOCK(vp);
3699 
3700 	/* Postpone other writers, including core dumps of other processes. */
3701 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3702 
3703 	lf.l_whence = SEEK_SET;
3704 	lf.l_start = 0;
3705 	lf.l_len = 0;
3706 	lf.l_type = F_WRLCK;
3707 	locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
3708 
3709 	VATTR_NULL(&vattr);
3710 	vattr.va_size = 0;
3711 	if (set_core_nodump_flag)
3712 		vattr.va_flags = UF_NODUMP;
3713 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3714 	VOP_SETATTR(vp, &vattr, cred);
3715 	VOP_UNLOCK(vp);
3716 	PROC_LOCK(p);
3717 	p->p_acflag |= ACORE;
3718 	PROC_UNLOCK(p);
3719 
3720 	if (p->p_sysent->sv_coredump != NULL) {
3721 		error = p->p_sysent->sv_coredump(td, vp, limit, 0);
3722 	} else {
3723 		error = ENOSYS;
3724 	}
3725 
3726 	if (locked) {
3727 		lf.l_type = F_UNLCK;
3728 		VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3729 	}
3730 	vn_rangelock_unlock(vp, rl_cookie);
3731 
3732 	/*
3733 	 * Notify the userland helper that a process triggered a core dump.
3734 	 * This allows the helper to run an automated debugging session.
3735 	 */
3736 	if (error != 0 || coredump_devctl == 0)
3737 		goto out;
3738 	sb = sbuf_new_auto();
3739 	if (vn_fullpath_global(td, p->p_textvp, &fullpath, &freepath) != 0)
3740 		goto out2;
3741 	sbuf_printf(sb, "comm=\"");
3742 	devctl_safe_quote_sb(sb, fullpath);
3743 	free(freepath, M_TEMP);
3744 	sbuf_printf(sb, "\" core=\"");
3745 
3746 	/*
3747 	 * We can't lookup core file vp directly. When we're replacing a core, and
3748 	 * other random times, we flush the name cache, so it will fail. Instead,
3749 	 * if the path of the core is relative, add the current dir in front if it.
3750 	 */
3751 	if (name[0] != '/') {
3752 		fullpathsize = MAXPATHLEN;
3753 		freepath = malloc(fullpathsize, M_TEMP, M_WAITOK);
3754 		if (vn_getcwd(td, freepath, &fullpath, &fullpathsize) != 0) {
3755 			free(freepath, M_TEMP);
3756 			goto out2;
3757 		}
3758 		devctl_safe_quote_sb(sb, fullpath);
3759 		free(freepath, M_TEMP);
3760 		sbuf_putc(sb, '/');
3761 	}
3762 	devctl_safe_quote_sb(sb, name);
3763 	sbuf_printf(sb, "\"");
3764 	if (sbuf_finish(sb) == 0)
3765 		devctl_notify("kernel", "signal", "coredump", sbuf_data(sb));
3766 out2:
3767 	sbuf_delete(sb);
3768 out:
3769 	error1 = vn_close(vp, FWRITE, cred, td);
3770 	if (error == 0)
3771 		error = error1;
3772 #ifdef AUDIT
3773 	audit_proc_coredump(td, name, error);
3774 #endif
3775 	free(name, M_TEMP);
3776 	return (error);
3777 }
3778 
3779 /*
3780  * Nonexistent system call-- signal process (may want to handle it).  Flag
3781  * error in case process won't see signal immediately (blocked or ignored).
3782  */
3783 #ifndef _SYS_SYSPROTO_H_
3784 struct nosys_args {
3785 	int	dummy;
3786 };
3787 #endif
3788 /* ARGSUSED */
3789 int
3790 nosys(struct thread *td, struct nosys_args *args)
3791 {
3792 	struct proc *p;
3793 
3794 	p = td->td_proc;
3795 
3796 	PROC_LOCK(p);
3797 	tdsignal(td, SIGSYS);
3798 	PROC_UNLOCK(p);
3799 	if (kern_lognosys == 1 || kern_lognosys == 3) {
3800 		uprintf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
3801 		    td->td_sa.code);
3802 	}
3803 	if (kern_lognosys == 2 || kern_lognosys == 3) {
3804 		printf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
3805 		    td->td_sa.code);
3806 	}
3807 	return (ENOSYS);
3808 }
3809 
3810 /*
3811  * Send a SIGIO or SIGURG signal to a process or process group using stored
3812  * credentials rather than those of the current process.
3813  */
3814 void
3815 pgsigio(struct sigio **sigiop, int sig, int checkctty)
3816 {
3817 	ksiginfo_t ksi;
3818 	struct sigio *sigio;
3819 
3820 	ksiginfo_init(&ksi);
3821 	ksi.ksi_signo = sig;
3822 	ksi.ksi_code = SI_KERNEL;
3823 
3824 	SIGIO_LOCK();
3825 	sigio = *sigiop;
3826 	if (sigio == NULL) {
3827 		SIGIO_UNLOCK();
3828 		return;
3829 	}
3830 	if (sigio->sio_pgid > 0) {
3831 		PROC_LOCK(sigio->sio_proc);
3832 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
3833 			kern_psignal(sigio->sio_proc, sig);
3834 		PROC_UNLOCK(sigio->sio_proc);
3835 	} else if (sigio->sio_pgid < 0) {
3836 		struct proc *p;
3837 
3838 		PGRP_LOCK(sigio->sio_pgrp);
3839 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
3840 			PROC_LOCK(p);
3841 			if (p->p_state == PRS_NORMAL &&
3842 			    CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
3843 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
3844 				kern_psignal(p, sig);
3845 			PROC_UNLOCK(p);
3846 		}
3847 		PGRP_UNLOCK(sigio->sio_pgrp);
3848 	}
3849 	SIGIO_UNLOCK();
3850 }
3851 
3852 static int
3853 filt_sigattach(struct knote *kn)
3854 {
3855 	struct proc *p = curproc;
3856 
3857 	kn->kn_ptr.p_proc = p;
3858 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
3859 
3860 	knlist_add(p->p_klist, kn, 0);
3861 
3862 	return (0);
3863 }
3864 
3865 static void
3866 filt_sigdetach(struct knote *kn)
3867 {
3868 	struct proc *p = kn->kn_ptr.p_proc;
3869 
3870 	knlist_remove(p->p_klist, kn, 0);
3871 }
3872 
3873 /*
3874  * signal knotes are shared with proc knotes, so we apply a mask to
3875  * the hint in order to differentiate them from process hints.  This
3876  * could be avoided by using a signal-specific knote list, but probably
3877  * isn't worth the trouble.
3878  */
3879 static int
3880 filt_signal(struct knote *kn, long hint)
3881 {
3882 
3883 	if (hint & NOTE_SIGNAL) {
3884 		hint &= ~NOTE_SIGNAL;
3885 
3886 		if (kn->kn_id == hint)
3887 			kn->kn_data++;
3888 	}
3889 	return (kn->kn_data != 0);
3890 }
3891 
3892 struct sigacts *
3893 sigacts_alloc(void)
3894 {
3895 	struct sigacts *ps;
3896 
3897 	ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
3898 	refcount_init(&ps->ps_refcnt, 1);
3899 	mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
3900 	return (ps);
3901 }
3902 
3903 void
3904 sigacts_free(struct sigacts *ps)
3905 {
3906 
3907 	if (refcount_release(&ps->ps_refcnt) == 0)
3908 		return;
3909 	mtx_destroy(&ps->ps_mtx);
3910 	free(ps, M_SUBPROC);
3911 }
3912 
3913 struct sigacts *
3914 sigacts_hold(struct sigacts *ps)
3915 {
3916 
3917 	refcount_acquire(&ps->ps_refcnt);
3918 	return (ps);
3919 }
3920 
3921 void
3922 sigacts_copy(struct sigacts *dest, struct sigacts *src)
3923 {
3924 
3925 	KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
3926 	mtx_lock(&src->ps_mtx);
3927 	bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
3928 	mtx_unlock(&src->ps_mtx);
3929 }
3930 
3931 int
3932 sigacts_shared(struct sigacts *ps)
3933 {
3934 
3935 	return (ps->ps_refcnt > 1);
3936 }
3937 
3938 void
3939 sig_drop_caught(struct proc *p)
3940 {
3941 	int sig;
3942 	struct sigacts *ps;
3943 
3944 	ps = p->p_sigacts;
3945 	PROC_LOCK_ASSERT(p, MA_OWNED);
3946 	mtx_assert(&ps->ps_mtx, MA_OWNED);
3947 	while (SIGNOTEMPTY(ps->ps_sigcatch)) {
3948 		sig = sig_ffs(&ps->ps_sigcatch);
3949 		sigdflt(ps, sig);
3950 		if ((sigprop(sig) & SIGPROP_IGNORE) != 0)
3951 			sigqueue_delete_proc(p, sig);
3952 	}
3953 }
3954 
3955 int
3956 sys_sigfastblock(struct thread *td, struct sigfastblock_args *uap)
3957 {
3958 	struct proc *p;
3959 	int error, res;
3960 	uint32_t oldval;
3961 
3962 	error = 0;
3963 	switch (uap->cmd) {
3964 	case SIGFASTBLOCK_SETPTR:
3965 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
3966 			error = EBUSY;
3967 			break;
3968 		}
3969 		if (((uintptr_t)(uap->ptr) & (sizeof(uint32_t) - 1)) != 0) {
3970 			error = EINVAL;
3971 			break;
3972 		}
3973 		td->td_pflags |= TDP_SIGFASTBLOCK;
3974 		td->td_sigblock_ptr = uap->ptr;
3975 		break;
3976 
3977 	case SIGFASTBLOCK_UNBLOCK:
3978 		if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
3979 			error = EINVAL;
3980 			break;
3981 		}
3982 again:
3983 		res = casueword32(td->td_sigblock_ptr, SIGFASTBLOCK_PEND,
3984 		    &oldval, 0);
3985 		if (res == -1) {
3986 			error = EFAULT;
3987 			break;
3988 		}
3989 		if (res == 1) {
3990 			if (oldval != SIGFASTBLOCK_PEND) {
3991 				error = EBUSY;
3992 				break;
3993 			}
3994 			error = thread_check_susp(td, false);
3995 			if (error != 0)
3996 				break;
3997 			goto again;
3998 		}
3999 		td->td_sigblock_val = 0;
4000 
4001 		/*
4002 		 * Rely on normal ast mechanism to deliver pending
4003 		 * signals to current thread.  But notify others about
4004 		 * fake unblock.
4005 		 */
4006 		p = td->td_proc;
4007 		if (error == 0 && p->p_numthreads != 1) {
4008 			PROC_LOCK(p);
4009 			reschedule_signals(p, td->td_sigmask, 0);
4010 			PROC_UNLOCK(p);
4011 		}
4012 		break;
4013 
4014 	case SIGFASTBLOCK_UNSETPTR:
4015 		if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4016 			error = EINVAL;
4017 			break;
4018 		}
4019 		res = fueword32(td->td_sigblock_ptr, &oldval);
4020 		if (res == -1) {
4021 			error = EFAULT;
4022 			break;
4023 		}
4024 		if (oldval != 0 && oldval != SIGFASTBLOCK_PEND) {
4025 			error = EBUSY;
4026 			break;
4027 		}
4028 		td->td_pflags &= ~TDP_SIGFASTBLOCK;
4029 		td->td_sigblock_val = 0;
4030 		break;
4031 
4032 	default:
4033 		error = EINVAL;
4034 		break;
4035 	}
4036 	return (error);
4037 }
4038 
4039 void
4040 fetch_sigfastblock(struct thread *td)
4041 {
4042 
4043 	if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4044 		return;
4045 	if (fueword32(td->td_sigblock_ptr, &td->td_sigblock_val) == -1) {
4046 		fetch_sigfastblock_failed(td, false);
4047 		return;
4048 	}
4049 	td->td_sigblock_val &= ~SIGFASTBLOCK_FLAGS;
4050 }
4051 
4052 void
4053 fetch_sigfastblock_failed(struct thread *td, bool write)
4054 {
4055 	ksiginfo_t ksi;
4056 
4057 	/*
4058 	 * Prevent further fetches and SIGSEGVs, allowing thread to
4059 	 * issue syscalls despite corruption.
4060 	 */
4061 	td->td_pflags &= ~TDP_SIGFASTBLOCK;
4062 
4063 	ksiginfo_init_trap(&ksi);
4064 	ksi.ksi_signo = SIGSEGV;
4065 	ksi.ksi_code = write ? SEGV_ACCERR : SEGV_MAPERR;
4066 	ksi.ksi_addr = td->td_sigblock_ptr;
4067 	trapsignal(td, &ksi);
4068 }
4069