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