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