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