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