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