xref: /freebsd/sys/kern/kern_sig.c (revision 28f42739a547ffe0b5dfaaf9f49fb4c4813aa232)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_compat.h"
41 #include "opt_ktrace.h"
42 #include "opt_core.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/signalvar.h>
47 #include <sys/vnode.h>
48 #include <sys/acct.h>
49 #include <sys/capsicum.h>
50 #include <sys/condvar.h>
51 #include <sys/event.h>
52 #include <sys/fcntl.h>
53 #include <sys/imgact.h>
54 #include <sys/kernel.h>
55 #include <sys/ktr.h>
56 #include <sys/ktrace.h>
57 #include <sys/lock.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/refcount.h>
61 #include <sys/namei.h>
62 #include <sys/proc.h>
63 #include <sys/procdesc.h>
64 #include <sys/posix4.h>
65 #include <sys/pioctl.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
68 #include <sys/sdt.h>
69 #include <sys/sbuf.h>
70 #include <sys/sleepqueue.h>
71 #include <sys/smp.h>
72 #include <sys/stat.h>
73 #include <sys/sx.h>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 #include <sys/sysent.h>
77 #include <sys/syslog.h>
78 #include <sys/sysproto.h>
79 #include <sys/timers.h>
80 #include <sys/unistd.h>
81 #include <sys/wait.h>
82 #include <vm/vm.h>
83 #include <vm/vm_extern.h>
84 #include <vm/uma.h>
85 
86 #include <sys/jail.h>
87 
88 #include <machine/cpu.h>
89 
90 #include <security/audit/audit.h>
91 
92 #define	ONSIG	32		/* NSIG for osig* syscalls.  XXX. */
93 
94 SDT_PROVIDER_DECLARE(proc);
95 SDT_PROBE_DEFINE3(proc, kernel, , signal__send, "struct thread *",
96     "struct proc *", "int");
97 SDT_PROBE_DEFINE2(proc, kernel, , signal__clear, "int",
98     "ksiginfo_t *");
99 SDT_PROBE_DEFINE3(proc, kernel, , signal__discard,
100     "struct thread *", "struct proc *", "int");
101 
102 static int	coredump(struct thread *);
103 static int	killpg1(struct thread *td, int sig, int pgid, int all,
104 		    ksiginfo_t *ksi);
105 static int	issignal(struct thread *td);
106 static int	sigprop(int sig);
107 static void	tdsigwakeup(struct thread *, int, sig_t, int);
108 static void	sig_suspend_threads(struct thread *, struct proc *, int);
109 static int	filt_sigattach(struct knote *kn);
110 static void	filt_sigdetach(struct knote *kn);
111 static int	filt_signal(struct knote *kn, long hint);
112 static struct thread *sigtd(struct proc *p, int sig, int prop);
113 static void	sigqueue_start(void);
114 
115 static uma_zone_t	ksiginfo_zone = NULL;
116 struct filterops sig_filtops = {
117 	.f_isfd = 0,
118 	.f_attach = filt_sigattach,
119 	.f_detach = filt_sigdetach,
120 	.f_event = filt_signal,
121 };
122 
123 static int	kern_logsigexit = 1;
124 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
125     &kern_logsigexit, 0,
126     "Log processes quitting on abnormal signals to syslog(3)");
127 
128 static int	kern_forcesigexit = 1;
129 SYSCTL_INT(_kern, OID_AUTO, forcesigexit, CTLFLAG_RW,
130     &kern_forcesigexit, 0, "Force trap signal to be handled");
131 
132 static SYSCTL_NODE(_kern, OID_AUTO, sigqueue, CTLFLAG_RW, 0,
133     "POSIX real time signal");
134 
135 static int	max_pending_per_proc = 128;
136 SYSCTL_INT(_kern_sigqueue, OID_AUTO, max_pending_per_proc, CTLFLAG_RW,
137     &max_pending_per_proc, 0, "Max pending signals per proc");
138 
139 static int	preallocate_siginfo = 1024;
140 SYSCTL_INT(_kern_sigqueue, OID_AUTO, preallocate, CTLFLAG_RDTUN,
141     &preallocate_siginfo, 0, "Preallocated signal memory size");
142 
143 static int	signal_overflow = 0;
144 SYSCTL_INT(_kern_sigqueue, OID_AUTO, overflow, CTLFLAG_RD,
145     &signal_overflow, 0, "Number of signals overflew");
146 
147 static int	signal_alloc_fail = 0;
148 SYSCTL_INT(_kern_sigqueue, OID_AUTO, alloc_fail, CTLFLAG_RD,
149     &signal_alloc_fail, 0, "signals failed to be allocated");
150 
151 SYSINIT(signal, SI_SUB_P1003_1B, SI_ORDER_FIRST+3, sigqueue_start, NULL);
152 
153 /*
154  * Policy -- Can ucred cr1 send SIGIO to process cr2?
155  * Should use cr_cansignal() once cr_cansignal() allows SIGIO and SIGURG
156  * in the right situations.
157  */
158 #define CANSIGIO(cr1, cr2) \
159 	((cr1)->cr_uid == 0 || \
160 	    (cr1)->cr_ruid == (cr2)->cr_ruid || \
161 	    (cr1)->cr_uid == (cr2)->cr_ruid || \
162 	    (cr1)->cr_ruid == (cr2)->cr_uid || \
163 	    (cr1)->cr_uid == (cr2)->cr_uid)
164 
165 static int	sugid_coredump;
166 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RWTUN,
167     &sugid_coredump, 0, "Allow setuid and setgid processes to dump core");
168 
169 static int	capmode_coredump;
170 SYSCTL_INT(_kern, OID_AUTO, capmode_coredump, CTLFLAG_RWTUN,
171     &capmode_coredump, 0, "Allow processes in capability mode to dump core");
172 
173 static int	do_coredump = 1;
174 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
175 	&do_coredump, 0, "Enable/Disable coredumps");
176 
177 static int	set_core_nodump_flag = 0;
178 SYSCTL_INT(_kern, OID_AUTO, nodump_coredump, CTLFLAG_RW, &set_core_nodump_flag,
179 	0, "Enable setting the NODUMP flag on coredump files");
180 
181 /*
182  * Signal properties and actions.
183  * The array below categorizes the signals and their default actions
184  * according to the following properties:
185  */
186 #define	SA_KILL		0x01		/* terminates process by default */
187 #define	SA_CORE		0x02		/* ditto and coredumps */
188 #define	SA_STOP		0x04		/* suspend process */
189 #define	SA_TTYSTOP	0x08		/* ditto, from tty */
190 #define	SA_IGNORE	0x10		/* ignore by default */
191 #define	SA_CONT		0x20		/* continue if suspended */
192 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
193 
194 static int sigproptbl[NSIG] = {
195 	SA_KILL,			/* SIGHUP */
196 	SA_KILL,			/* SIGINT */
197 	SA_KILL|SA_CORE,		/* SIGQUIT */
198 	SA_KILL|SA_CORE,		/* SIGILL */
199 	SA_KILL|SA_CORE,		/* SIGTRAP */
200 	SA_KILL|SA_CORE,		/* SIGABRT */
201 	SA_KILL|SA_CORE,		/* SIGEMT */
202 	SA_KILL|SA_CORE,		/* SIGFPE */
203 	SA_KILL,			/* SIGKILL */
204 	SA_KILL|SA_CORE,		/* SIGBUS */
205 	SA_KILL|SA_CORE,		/* SIGSEGV */
206 	SA_KILL|SA_CORE,		/* SIGSYS */
207 	SA_KILL,			/* SIGPIPE */
208 	SA_KILL,			/* SIGALRM */
209 	SA_KILL,			/* SIGTERM */
210 	SA_IGNORE,			/* SIGURG */
211 	SA_STOP,			/* SIGSTOP */
212 	SA_STOP|SA_TTYSTOP,		/* SIGTSTP */
213 	SA_IGNORE|SA_CONT,		/* SIGCONT */
214 	SA_IGNORE,			/* SIGCHLD */
215 	SA_STOP|SA_TTYSTOP,		/* SIGTTIN */
216 	SA_STOP|SA_TTYSTOP,		/* SIGTTOU */
217 	SA_IGNORE,			/* SIGIO */
218 	SA_KILL,			/* SIGXCPU */
219 	SA_KILL,			/* SIGXFSZ */
220 	SA_KILL,			/* SIGVTALRM */
221 	SA_KILL,			/* SIGPROF */
222 	SA_IGNORE,			/* SIGWINCH  */
223 	SA_IGNORE,			/* SIGINFO */
224 	SA_KILL,			/* SIGUSR1 */
225 	SA_KILL,			/* SIGUSR2 */
226 };
227 
228 static void reschedule_signals(struct proc *p, sigset_t block, int flags);
229 
230 static void
231 sigqueue_start(void)
232 {
233 	ksiginfo_zone = uma_zcreate("ksiginfo", sizeof(ksiginfo_t),
234 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
235 	uma_prealloc(ksiginfo_zone, preallocate_siginfo);
236 	p31b_setcfg(CTL_P1003_1B_REALTIME_SIGNALS, _POSIX_REALTIME_SIGNALS);
237 	p31b_setcfg(CTL_P1003_1B_RTSIG_MAX, SIGRTMAX - SIGRTMIN + 1);
238 	p31b_setcfg(CTL_P1003_1B_SIGQUEUE_MAX, max_pending_per_proc);
239 }
240 
241 ksiginfo_t *
242 ksiginfo_alloc(int wait)
243 {
244 	int flags;
245 
246 	flags = M_ZERO;
247 	if (! wait)
248 		flags |= M_NOWAIT;
249 	if (ksiginfo_zone != NULL)
250 		return ((ksiginfo_t *)uma_zalloc(ksiginfo_zone, flags));
251 	return (NULL);
252 }
253 
254 void
255 ksiginfo_free(ksiginfo_t *ksi)
256 {
257 	uma_zfree(ksiginfo_zone, ksi);
258 }
259 
260 static __inline int
261 ksiginfo_tryfree(ksiginfo_t *ksi)
262 {
263 	if (!(ksi->ksi_flags & KSI_EXT)) {
264 		uma_zfree(ksiginfo_zone, ksi);
265 		return (1);
266 	}
267 	return (0);
268 }
269 
270 void
271 sigqueue_init(sigqueue_t *list, struct proc *p)
272 {
273 	SIGEMPTYSET(list->sq_signals);
274 	SIGEMPTYSET(list->sq_kill);
275 	TAILQ_INIT(&list->sq_list);
276 	list->sq_proc = p;
277 	list->sq_flags = SQ_INIT;
278 }
279 
280 /*
281  * Get a signal's ksiginfo.
282  * Return:
283  *	0	-	signal not found
284  *	others	-	signal number
285  */
286 static int
287 sigqueue_get(sigqueue_t *sq, int signo, ksiginfo_t *si)
288 {
289 	struct proc *p = sq->sq_proc;
290 	struct ksiginfo *ksi, *next;
291 	int count = 0;
292 
293 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
294 
295 	if (!SIGISMEMBER(sq->sq_signals, signo))
296 		return (0);
297 
298 	if (SIGISMEMBER(sq->sq_kill, signo)) {
299 		count++;
300 		SIGDELSET(sq->sq_kill, signo);
301 	}
302 
303 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
304 		if (ksi->ksi_signo == signo) {
305 			if (count == 0) {
306 				TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
307 				ksi->ksi_sigq = NULL;
308 				ksiginfo_copy(ksi, si);
309 				if (ksiginfo_tryfree(ksi) && p != NULL)
310 					p->p_pendingcnt--;
311 			}
312 			if (++count > 1)
313 				break;
314 		}
315 	}
316 
317 	if (count <= 1)
318 		SIGDELSET(sq->sq_signals, signo);
319 	si->ksi_signo = signo;
320 	return (signo);
321 }
322 
323 void
324 sigqueue_take(ksiginfo_t *ksi)
325 {
326 	struct ksiginfo *kp;
327 	struct proc	*p;
328 	sigqueue_t	*sq;
329 
330 	if (ksi == NULL || (sq = ksi->ksi_sigq) == NULL)
331 		return;
332 
333 	p = sq->sq_proc;
334 	TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
335 	ksi->ksi_sigq = NULL;
336 	if (!(ksi->ksi_flags & KSI_EXT) && p != NULL)
337 		p->p_pendingcnt--;
338 
339 	for (kp = TAILQ_FIRST(&sq->sq_list); kp != NULL;
340 	     kp = TAILQ_NEXT(kp, ksi_link)) {
341 		if (kp->ksi_signo == ksi->ksi_signo)
342 			break;
343 	}
344 	if (kp == NULL && !SIGISMEMBER(sq->sq_kill, ksi->ksi_signo))
345 		SIGDELSET(sq->sq_signals, ksi->ksi_signo);
346 }
347 
348 static int
349 sigqueue_add(sigqueue_t *sq, int signo, ksiginfo_t *si)
350 {
351 	struct proc *p = sq->sq_proc;
352 	struct ksiginfo *ksi;
353 	int ret = 0;
354 
355 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
356 
357 	if (signo == SIGKILL || signo == SIGSTOP || si == NULL) {
358 		SIGADDSET(sq->sq_kill, signo);
359 		goto out_set_bit;
360 	}
361 
362 	/* directly insert the ksi, don't copy it */
363 	if (si->ksi_flags & KSI_INS) {
364 		if (si->ksi_flags & KSI_HEAD)
365 			TAILQ_INSERT_HEAD(&sq->sq_list, si, ksi_link);
366 		else
367 			TAILQ_INSERT_TAIL(&sq->sq_list, si, ksi_link);
368 		si->ksi_sigq = sq;
369 		goto out_set_bit;
370 	}
371 
372 	if (__predict_false(ksiginfo_zone == NULL)) {
373 		SIGADDSET(sq->sq_kill, signo);
374 		goto out_set_bit;
375 	}
376 
377 	if (p != NULL && p->p_pendingcnt >= max_pending_per_proc) {
378 		signal_overflow++;
379 		ret = EAGAIN;
380 	} else if ((ksi = ksiginfo_alloc(0)) == NULL) {
381 		signal_alloc_fail++;
382 		ret = EAGAIN;
383 	} else {
384 		if (p != NULL)
385 			p->p_pendingcnt++;
386 		ksiginfo_copy(si, ksi);
387 		ksi->ksi_signo = signo;
388 		if (si->ksi_flags & KSI_HEAD)
389 			TAILQ_INSERT_HEAD(&sq->sq_list, ksi, ksi_link);
390 		else
391 			TAILQ_INSERT_TAIL(&sq->sq_list, ksi, ksi_link);
392 		ksi->ksi_sigq = sq;
393 	}
394 
395 	if ((si->ksi_flags & KSI_TRAP) != 0 ||
396 	    (si->ksi_flags & KSI_SIGQ) == 0) {
397 		if (ret != 0)
398 			SIGADDSET(sq->sq_kill, signo);
399 		ret = 0;
400 		goto out_set_bit;
401 	}
402 
403 	if (ret != 0)
404 		return (ret);
405 
406 out_set_bit:
407 	SIGADDSET(sq->sq_signals, signo);
408 	return (ret);
409 }
410 
411 void
412 sigqueue_flush(sigqueue_t *sq)
413 {
414 	struct proc *p = sq->sq_proc;
415 	ksiginfo_t *ksi;
416 
417 	KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
418 
419 	if (p != NULL)
420 		PROC_LOCK_ASSERT(p, MA_OWNED);
421 
422 	while ((ksi = TAILQ_FIRST(&sq->sq_list)) != NULL) {
423 		TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
424 		ksi->ksi_sigq = NULL;
425 		if (ksiginfo_tryfree(ksi) && p != NULL)
426 			p->p_pendingcnt--;
427 	}
428 
429 	SIGEMPTYSET(sq->sq_signals);
430 	SIGEMPTYSET(sq->sq_kill);
431 }
432 
433 static void
434 sigqueue_move_set(sigqueue_t *src, sigqueue_t *dst, const sigset_t *set)
435 {
436 	sigset_t tmp;
437 	struct proc *p1, *p2;
438 	ksiginfo_t *ksi, *next;
439 
440 	KASSERT(src->sq_flags & SQ_INIT, ("src sigqueue not inited"));
441 	KASSERT(dst->sq_flags & SQ_INIT, ("dst sigqueue not inited"));
442 	p1 = src->sq_proc;
443 	p2 = dst->sq_proc;
444 	/* Move siginfo to target list */
445 	TAILQ_FOREACH_SAFE(ksi, &src->sq_list, ksi_link, next) {
446 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
447 			TAILQ_REMOVE(&src->sq_list, ksi, ksi_link);
448 			if (p1 != NULL)
449 				p1->p_pendingcnt--;
450 			TAILQ_INSERT_TAIL(&dst->sq_list, ksi, ksi_link);
451 			ksi->ksi_sigq = dst;
452 			if (p2 != NULL)
453 				p2->p_pendingcnt++;
454 		}
455 	}
456 
457 	/* Move pending bits to target list */
458 	tmp = src->sq_kill;
459 	SIGSETAND(tmp, *set);
460 	SIGSETOR(dst->sq_kill, tmp);
461 	SIGSETNAND(src->sq_kill, tmp);
462 
463 	tmp = src->sq_signals;
464 	SIGSETAND(tmp, *set);
465 	SIGSETOR(dst->sq_signals, tmp);
466 	SIGSETNAND(src->sq_signals, tmp);
467 }
468 
469 #if 0
470 static void
471 sigqueue_move(sigqueue_t *src, sigqueue_t *dst, int signo)
472 {
473 	sigset_t set;
474 
475 	SIGEMPTYSET(set);
476 	SIGADDSET(set, signo);
477 	sigqueue_move_set(src, dst, &set);
478 }
479 #endif
480 
481 static void
482 sigqueue_delete_set(sigqueue_t *sq, const sigset_t *set)
483 {
484 	struct proc *p = sq->sq_proc;
485 	ksiginfo_t *ksi, *next;
486 
487 	KASSERT(sq->sq_flags & SQ_INIT, ("src sigqueue not inited"));
488 
489 	/* Remove siginfo queue */
490 	TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
491 		if (SIGISMEMBER(*set, ksi->ksi_signo)) {
492 			TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
493 			ksi->ksi_sigq = NULL;
494 			if (ksiginfo_tryfree(ksi) && p != NULL)
495 				p->p_pendingcnt--;
496 		}
497 	}
498 	SIGSETNAND(sq->sq_kill, *set);
499 	SIGSETNAND(sq->sq_signals, *set);
500 }
501 
502 void
503 sigqueue_delete(sigqueue_t *sq, int signo)
504 {
505 	sigset_t set;
506 
507 	SIGEMPTYSET(set);
508 	SIGADDSET(set, signo);
509 	sigqueue_delete_set(sq, &set);
510 }
511 
512 /* Remove a set of signals for a process */
513 static void
514 sigqueue_delete_set_proc(struct proc *p, const sigset_t *set)
515 {
516 	sigqueue_t worklist;
517 	struct thread *td0;
518 
519 	PROC_LOCK_ASSERT(p, MA_OWNED);
520 
521 	sigqueue_init(&worklist, NULL);
522 	sigqueue_move_set(&p->p_sigqueue, &worklist, set);
523 
524 	FOREACH_THREAD_IN_PROC(p, td0)
525 		sigqueue_move_set(&td0->td_sigqueue, &worklist, set);
526 
527 	sigqueue_flush(&worklist);
528 }
529 
530 void
531 sigqueue_delete_proc(struct proc *p, int signo)
532 {
533 	sigset_t set;
534 
535 	SIGEMPTYSET(set);
536 	SIGADDSET(set, signo);
537 	sigqueue_delete_set_proc(p, &set);
538 }
539 
540 static void
541 sigqueue_delete_stopmask_proc(struct proc *p)
542 {
543 	sigset_t set;
544 
545 	SIGEMPTYSET(set);
546 	SIGADDSET(set, SIGSTOP);
547 	SIGADDSET(set, SIGTSTP);
548 	SIGADDSET(set, SIGTTIN);
549 	SIGADDSET(set, SIGTTOU);
550 	sigqueue_delete_set_proc(p, &set);
551 }
552 
553 /*
554  * Determine signal that should be delivered to thread td, the current
555  * thread, 0 if none.  If there is a pending stop signal with default
556  * action, the process stops in issignal().
557  */
558 int
559 cursig(struct thread *td)
560 {
561 	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
562 	mtx_assert(&td->td_proc->p_sigacts->ps_mtx, MA_OWNED);
563 	THREAD_LOCK_ASSERT(td, MA_NOTOWNED);
564 	return (SIGPENDING(td) ? issignal(td) : 0);
565 }
566 
567 /*
568  * Arrange for ast() to handle unmasked pending signals on return to user
569  * mode.  This must be called whenever a signal is added to td_sigqueue or
570  * unmasked in td_sigmask.
571  */
572 void
573 signotify(struct thread *td)
574 {
575 	struct proc *p;
576 
577 	p = td->td_proc;
578 
579 	PROC_LOCK_ASSERT(p, MA_OWNED);
580 
581 	if (SIGPENDING(td)) {
582 		thread_lock(td);
583 		td->td_flags |= TDF_NEEDSIGCHK | TDF_ASTPENDING;
584 		thread_unlock(td);
585 	}
586 }
587 
588 int
589 sigonstack(size_t sp)
590 {
591 	struct thread *td = curthread;
592 
593 	return ((td->td_pflags & TDP_ALTSTACK) ?
594 #if defined(COMPAT_43)
595 	    ((td->td_sigstk.ss_size == 0) ?
596 		(td->td_sigstk.ss_flags & SS_ONSTACK) :
597 		((sp - (size_t)td->td_sigstk.ss_sp) < td->td_sigstk.ss_size))
598 #else
599 	    ((sp - (size_t)td->td_sigstk.ss_sp) < td->td_sigstk.ss_size)
600 #endif
601 	    : 0);
602 }
603 
604 static __inline int
605 sigprop(int sig)
606 {
607 
608 	if (sig > 0 && sig < NSIG)
609 		return (sigproptbl[_SIG_IDX(sig)]);
610 	return (0);
611 }
612 
613 int
614 sig_ffs(sigset_t *set)
615 {
616 	int i;
617 
618 	for (i = 0; i < _SIG_WORDS; i++)
619 		if (set->__bits[i])
620 			return (ffs(set->__bits[i]) + (i * 32));
621 	return (0);
622 }
623 
624 static bool
625 sigact_flag_test(struct sigaction *act, int flag)
626 {
627 
628 	/*
629 	 * SA_SIGINFO is reset when signal disposition is set to
630 	 * ignore or default.  Other flags are kept according to user
631 	 * settings.
632 	 */
633 	return ((act->sa_flags & flag) != 0 && (flag != SA_SIGINFO ||
634 	    ((__sighandler_t *)act->sa_sigaction != SIG_IGN &&
635 	    (__sighandler_t *)act->sa_sigaction != SIG_DFL)));
636 }
637 
638 /*
639  * kern_sigaction
640  * sigaction
641  * freebsd4_sigaction
642  * osigaction
643  */
644 int
645 kern_sigaction(td, sig, act, oact, flags)
646 	struct thread *td;
647 	register int sig;
648 	struct sigaction *act, *oact;
649 	int flags;
650 {
651 	struct sigacts *ps;
652 	struct proc *p = td->td_proc;
653 
654 	if (!_SIG_VALID(sig))
655 		return (EINVAL);
656 	if (act != NULL && (act->sa_flags & ~(SA_ONSTACK | SA_RESTART |
657 	    SA_RESETHAND | SA_NOCLDSTOP | SA_NODEFER | SA_NOCLDWAIT |
658 	    SA_SIGINFO)) != 0)
659 		return (EINVAL);
660 
661 	PROC_LOCK(p);
662 	ps = p->p_sigacts;
663 	mtx_lock(&ps->ps_mtx);
664 	if (oact) {
665 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
666 		oact->sa_flags = 0;
667 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
668 			oact->sa_flags |= SA_ONSTACK;
669 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
670 			oact->sa_flags |= SA_RESTART;
671 		if (SIGISMEMBER(ps->ps_sigreset, sig))
672 			oact->sa_flags |= SA_RESETHAND;
673 		if (SIGISMEMBER(ps->ps_signodefer, sig))
674 			oact->sa_flags |= SA_NODEFER;
675 		if (SIGISMEMBER(ps->ps_siginfo, sig)) {
676 			oact->sa_flags |= SA_SIGINFO;
677 			oact->sa_sigaction =
678 			    (__siginfohandler_t *)ps->ps_sigact[_SIG_IDX(sig)];
679 		} else
680 			oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
681 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDSTOP)
682 			oact->sa_flags |= SA_NOCLDSTOP;
683 		if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDWAIT)
684 			oact->sa_flags |= SA_NOCLDWAIT;
685 	}
686 	if (act) {
687 		if ((sig == SIGKILL || sig == SIGSTOP) &&
688 		    act->sa_handler != SIG_DFL) {
689 			mtx_unlock(&ps->ps_mtx);
690 			PROC_UNLOCK(p);
691 			return (EINVAL);
692 		}
693 
694 		/*
695 		 * Change setting atomically.
696 		 */
697 
698 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
699 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
700 		if (sigact_flag_test(act, SA_SIGINFO)) {
701 			ps->ps_sigact[_SIG_IDX(sig)] =
702 			    (__sighandler_t *)act->sa_sigaction;
703 			SIGADDSET(ps->ps_siginfo, sig);
704 		} else {
705 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
706 			SIGDELSET(ps->ps_siginfo, sig);
707 		}
708 		if (!sigact_flag_test(act, SA_RESTART))
709 			SIGADDSET(ps->ps_sigintr, sig);
710 		else
711 			SIGDELSET(ps->ps_sigintr, sig);
712 		if (sigact_flag_test(act, SA_ONSTACK))
713 			SIGADDSET(ps->ps_sigonstack, sig);
714 		else
715 			SIGDELSET(ps->ps_sigonstack, sig);
716 		if (sigact_flag_test(act, SA_RESETHAND))
717 			SIGADDSET(ps->ps_sigreset, sig);
718 		else
719 			SIGDELSET(ps->ps_sigreset, sig);
720 		if (sigact_flag_test(act, SA_NODEFER))
721 			SIGADDSET(ps->ps_signodefer, sig);
722 		else
723 			SIGDELSET(ps->ps_signodefer, sig);
724 		if (sig == SIGCHLD) {
725 			if (act->sa_flags & SA_NOCLDSTOP)
726 				ps->ps_flag |= PS_NOCLDSTOP;
727 			else
728 				ps->ps_flag &= ~PS_NOCLDSTOP;
729 			if (act->sa_flags & SA_NOCLDWAIT) {
730 				/*
731 				 * Paranoia: since SA_NOCLDWAIT is implemented
732 				 * by reparenting the dying child to PID 1 (and
733 				 * trust it to reap the zombie), PID 1 itself
734 				 * is forbidden to set SA_NOCLDWAIT.
735 				 */
736 				if (p->p_pid == 1)
737 					ps->ps_flag &= ~PS_NOCLDWAIT;
738 				else
739 					ps->ps_flag |= PS_NOCLDWAIT;
740 			} else
741 				ps->ps_flag &= ~PS_NOCLDWAIT;
742 			if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
743 				ps->ps_flag |= PS_CLDSIGIGN;
744 			else
745 				ps->ps_flag &= ~PS_CLDSIGIGN;
746 		}
747 		/*
748 		 * Set bit in ps_sigignore for signals that are set to SIG_IGN,
749 		 * and for signals set to SIG_DFL where the default is to
750 		 * ignore. However, don't put SIGCONT in ps_sigignore, as we
751 		 * have to restart the process.
752 		 */
753 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
754 		    (sigprop(sig) & SA_IGNORE &&
755 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
756 			/* never to be seen again */
757 			sigqueue_delete_proc(p, sig);
758 			if (sig != SIGCONT)
759 				/* easier in psignal */
760 				SIGADDSET(ps->ps_sigignore, sig);
761 			SIGDELSET(ps->ps_sigcatch, sig);
762 		} else {
763 			SIGDELSET(ps->ps_sigignore, sig);
764 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
765 				SIGDELSET(ps->ps_sigcatch, sig);
766 			else
767 				SIGADDSET(ps->ps_sigcatch, sig);
768 		}
769 #ifdef COMPAT_FREEBSD4
770 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
771 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
772 		    (flags & KSA_FREEBSD4) == 0)
773 			SIGDELSET(ps->ps_freebsd4, sig);
774 		else
775 			SIGADDSET(ps->ps_freebsd4, sig);
776 #endif
777 #ifdef COMPAT_43
778 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
779 		    ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
780 		    (flags & KSA_OSIGSET) == 0)
781 			SIGDELSET(ps->ps_osigset, sig);
782 		else
783 			SIGADDSET(ps->ps_osigset, sig);
784 #endif
785 	}
786 	mtx_unlock(&ps->ps_mtx);
787 	PROC_UNLOCK(p);
788 	return (0);
789 }
790 
791 #ifndef _SYS_SYSPROTO_H_
792 struct sigaction_args {
793 	int	sig;
794 	struct	sigaction *act;
795 	struct	sigaction *oact;
796 };
797 #endif
798 int
799 sys_sigaction(td, uap)
800 	struct thread *td;
801 	register struct sigaction_args *uap;
802 {
803 	struct sigaction act, oact;
804 	register struct sigaction *actp, *oactp;
805 	int error;
806 
807 	actp = (uap->act != NULL) ? &act : NULL;
808 	oactp = (uap->oact != NULL) ? &oact : NULL;
809 	if (actp) {
810 		error = copyin(uap->act, actp, sizeof(act));
811 		if (error)
812 			return (error);
813 	}
814 	error = kern_sigaction(td, uap->sig, actp, oactp, 0);
815 	if (oactp && !error)
816 		error = copyout(oactp, uap->oact, sizeof(oact));
817 	return (error);
818 }
819 
820 #ifdef COMPAT_FREEBSD4
821 #ifndef _SYS_SYSPROTO_H_
822 struct freebsd4_sigaction_args {
823 	int	sig;
824 	struct	sigaction *act;
825 	struct	sigaction *oact;
826 };
827 #endif
828 int
829 freebsd4_sigaction(td, uap)
830 	struct thread *td;
831 	register struct freebsd4_sigaction_args *uap;
832 {
833 	struct sigaction act, oact;
834 	register struct sigaction *actp, *oactp;
835 	int error;
836 
837 
838 	actp = (uap->act != NULL) ? &act : NULL;
839 	oactp = (uap->oact != NULL) ? &oact : NULL;
840 	if (actp) {
841 		error = copyin(uap->act, actp, sizeof(act));
842 		if (error)
843 			return (error);
844 	}
845 	error = kern_sigaction(td, uap->sig, actp, oactp, KSA_FREEBSD4);
846 	if (oactp && !error)
847 		error = copyout(oactp, uap->oact, sizeof(oact));
848 	return (error);
849 }
850 #endif	/* COMAPT_FREEBSD4 */
851 
852 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
853 #ifndef _SYS_SYSPROTO_H_
854 struct osigaction_args {
855 	int	signum;
856 	struct	osigaction *nsa;
857 	struct	osigaction *osa;
858 };
859 #endif
860 int
861 osigaction(td, uap)
862 	struct thread *td;
863 	register struct osigaction_args *uap;
864 {
865 	struct osigaction sa;
866 	struct sigaction nsa, osa;
867 	register struct sigaction *nsap, *osap;
868 	int error;
869 
870 	if (uap->signum <= 0 || uap->signum >= ONSIG)
871 		return (EINVAL);
872 
873 	nsap = (uap->nsa != NULL) ? &nsa : NULL;
874 	osap = (uap->osa != NULL) ? &osa : NULL;
875 
876 	if (nsap) {
877 		error = copyin(uap->nsa, &sa, sizeof(sa));
878 		if (error)
879 			return (error);
880 		nsap->sa_handler = sa.sa_handler;
881 		nsap->sa_flags = sa.sa_flags;
882 		OSIG2SIG(sa.sa_mask, nsap->sa_mask);
883 	}
884 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
885 	if (osap && !error) {
886 		sa.sa_handler = osap->sa_handler;
887 		sa.sa_flags = osap->sa_flags;
888 		SIG2OSIG(osap->sa_mask, sa.sa_mask);
889 		error = copyout(&sa, uap->osa, sizeof(sa));
890 	}
891 	return (error);
892 }
893 
894 #if !defined(__i386__)
895 /* Avoid replicating the same stub everywhere */
896 int
897 osigreturn(td, uap)
898 	struct thread *td;
899 	struct osigreturn_args *uap;
900 {
901 
902 	return (nosys(td, (struct nosys_args *)uap));
903 }
904 #endif
905 #endif /* COMPAT_43 */
906 
907 /*
908  * Initialize signal state for process 0;
909  * set to ignore signals that are ignored by default.
910  */
911 void
912 siginit(p)
913 	struct proc *p;
914 {
915 	register int i;
916 	struct sigacts *ps;
917 
918 	PROC_LOCK(p);
919 	ps = p->p_sigacts;
920 	mtx_lock(&ps->ps_mtx);
921 	for (i = 1; i <= NSIG; i++) {
922 		if (sigprop(i) & SA_IGNORE && i != SIGCONT) {
923 			SIGADDSET(ps->ps_sigignore, i);
924 		}
925 	}
926 	mtx_unlock(&ps->ps_mtx);
927 	PROC_UNLOCK(p);
928 }
929 
930 /*
931  * Reset specified signal to the default disposition.
932  */
933 static void
934 sigdflt(struct sigacts *ps, int sig)
935 {
936 
937 	mtx_assert(&ps->ps_mtx, MA_OWNED);
938 	SIGDELSET(ps->ps_sigcatch, sig);
939 	if ((sigprop(sig) & SA_IGNORE) != 0 && sig != SIGCONT)
940 		SIGADDSET(ps->ps_sigignore, sig);
941 	ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
942 	SIGDELSET(ps->ps_siginfo, sig);
943 }
944 
945 /*
946  * Reset signals for an exec of the specified process.
947  */
948 void
949 execsigs(struct proc *p)
950 {
951 	struct sigacts *ps;
952 	int sig;
953 	struct thread *td;
954 
955 	/*
956 	 * Reset caught signals.  Held signals remain held
957 	 * through td_sigmask (unless they were caught,
958 	 * and are now ignored by default).
959 	 */
960 	PROC_LOCK_ASSERT(p, MA_OWNED);
961 	td = FIRST_THREAD_IN_PROC(p);
962 	ps = p->p_sigacts;
963 	mtx_lock(&ps->ps_mtx);
964 	while (SIGNOTEMPTY(ps->ps_sigcatch)) {
965 		sig = sig_ffs(&ps->ps_sigcatch);
966 		sigdflt(ps, sig);
967 		if ((sigprop(sig) & SA_IGNORE) != 0)
968 			sigqueue_delete_proc(p, sig);
969 	}
970 	/*
971 	 * Reset stack state to the user stack.
972 	 * Clear set of signals caught on the signal stack.
973 	 */
974 	td->td_sigstk.ss_flags = SS_DISABLE;
975 	td->td_sigstk.ss_size = 0;
976 	td->td_sigstk.ss_sp = 0;
977 	td->td_pflags &= ~TDP_ALTSTACK;
978 	/*
979 	 * Reset no zombies if child dies flag as Solaris does.
980 	 */
981 	ps->ps_flag &= ~(PS_NOCLDWAIT | PS_CLDSIGIGN);
982 	if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
983 		ps->ps_sigact[_SIG_IDX(SIGCHLD)] = SIG_DFL;
984 	mtx_unlock(&ps->ps_mtx);
985 }
986 
987 /*
988  * kern_sigprocmask()
989  *
990  *	Manipulate signal mask.
991  */
992 int
993 kern_sigprocmask(struct thread *td, int how, sigset_t *set, sigset_t *oset,
994     int flags)
995 {
996 	sigset_t new_block, oset1;
997 	struct proc *p;
998 	int error;
999 
1000 	p = td->td_proc;
1001 	if ((flags & SIGPROCMASK_PROC_LOCKED) != 0)
1002 		PROC_LOCK_ASSERT(p, MA_OWNED);
1003 	else
1004 		PROC_LOCK(p);
1005 	mtx_assert(&p->p_sigacts->ps_mtx, (flags & SIGPROCMASK_PS_LOCKED) != 0
1006 	    ? MA_OWNED : MA_NOTOWNED);
1007 	if (oset != NULL)
1008 		*oset = td->td_sigmask;
1009 
1010 	error = 0;
1011 	if (set != NULL) {
1012 		switch (how) {
1013 		case SIG_BLOCK:
1014 			SIG_CANTMASK(*set);
1015 			oset1 = td->td_sigmask;
1016 			SIGSETOR(td->td_sigmask, *set);
1017 			new_block = td->td_sigmask;
1018 			SIGSETNAND(new_block, oset1);
1019 			break;
1020 		case SIG_UNBLOCK:
1021 			SIGSETNAND(td->td_sigmask, *set);
1022 			signotify(td);
1023 			goto out;
1024 		case SIG_SETMASK:
1025 			SIG_CANTMASK(*set);
1026 			oset1 = td->td_sigmask;
1027 			if (flags & SIGPROCMASK_OLD)
1028 				SIGSETLO(td->td_sigmask, *set);
1029 			else
1030 				td->td_sigmask = *set;
1031 			new_block = td->td_sigmask;
1032 			SIGSETNAND(new_block, oset1);
1033 			signotify(td);
1034 			break;
1035 		default:
1036 			error = EINVAL;
1037 			goto out;
1038 		}
1039 
1040 		/*
1041 		 * The new_block set contains signals that were not previously
1042 		 * blocked, but are blocked now.
1043 		 *
1044 		 * In case we block any signal that was not previously blocked
1045 		 * for td, and process has the signal pending, try to schedule
1046 		 * signal delivery to some thread that does not block the
1047 		 * signal, possibly waking it up.
1048 		 */
1049 		if (p->p_numthreads != 1)
1050 			reschedule_signals(p, new_block, flags);
1051 	}
1052 
1053 out:
1054 	if (!(flags & SIGPROCMASK_PROC_LOCKED))
1055 		PROC_UNLOCK(p);
1056 	return (error);
1057 }
1058 
1059 #ifndef _SYS_SYSPROTO_H_
1060 struct sigprocmask_args {
1061 	int	how;
1062 	const sigset_t *set;
1063 	sigset_t *oset;
1064 };
1065 #endif
1066 int
1067 sys_sigprocmask(td, uap)
1068 	register struct thread *td;
1069 	struct sigprocmask_args *uap;
1070 {
1071 	sigset_t set, oset;
1072 	sigset_t *setp, *osetp;
1073 	int error;
1074 
1075 	setp = (uap->set != NULL) ? &set : NULL;
1076 	osetp = (uap->oset != NULL) ? &oset : NULL;
1077 	if (setp) {
1078 		error = copyin(uap->set, setp, sizeof(set));
1079 		if (error)
1080 			return (error);
1081 	}
1082 	error = kern_sigprocmask(td, uap->how, setp, osetp, 0);
1083 	if (osetp && !error) {
1084 		error = copyout(osetp, uap->oset, sizeof(oset));
1085 	}
1086 	return (error);
1087 }
1088 
1089 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1090 #ifndef _SYS_SYSPROTO_H_
1091 struct osigprocmask_args {
1092 	int	how;
1093 	osigset_t mask;
1094 };
1095 #endif
1096 int
1097 osigprocmask(td, uap)
1098 	register struct thread *td;
1099 	struct osigprocmask_args *uap;
1100 {
1101 	sigset_t set, oset;
1102 	int error;
1103 
1104 	OSIG2SIG(uap->mask, set);
1105 	error = kern_sigprocmask(td, uap->how, &set, &oset, 1);
1106 	SIG2OSIG(oset, td->td_retval[0]);
1107 	return (error);
1108 }
1109 #endif /* COMPAT_43 */
1110 
1111 int
1112 sys_sigwait(struct thread *td, struct sigwait_args *uap)
1113 {
1114 	ksiginfo_t ksi;
1115 	sigset_t set;
1116 	int error;
1117 
1118 	error = copyin(uap->set, &set, sizeof(set));
1119 	if (error) {
1120 		td->td_retval[0] = error;
1121 		return (0);
1122 	}
1123 
1124 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1125 	if (error) {
1126 		if (error == EINTR && td->td_proc->p_osrel < P_OSREL_SIGWAIT)
1127 			error = ERESTART;
1128 		if (error == ERESTART)
1129 			return (error);
1130 		td->td_retval[0] = error;
1131 		return (0);
1132 	}
1133 
1134 	error = copyout(&ksi.ksi_signo, uap->sig, sizeof(ksi.ksi_signo));
1135 	td->td_retval[0] = error;
1136 	return (0);
1137 }
1138 
1139 int
1140 sys_sigtimedwait(struct thread *td, struct sigtimedwait_args *uap)
1141 {
1142 	struct timespec ts;
1143 	struct timespec *timeout;
1144 	sigset_t set;
1145 	ksiginfo_t ksi;
1146 	int error;
1147 
1148 	if (uap->timeout) {
1149 		error = copyin(uap->timeout, &ts, sizeof(ts));
1150 		if (error)
1151 			return (error);
1152 
1153 		timeout = &ts;
1154 	} else
1155 		timeout = NULL;
1156 
1157 	error = copyin(uap->set, &set, sizeof(set));
1158 	if (error)
1159 		return (error);
1160 
1161 	error = kern_sigtimedwait(td, set, &ksi, timeout);
1162 	if (error)
1163 		return (error);
1164 
1165 	if (uap->info)
1166 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1167 
1168 	if (error == 0)
1169 		td->td_retval[0] = ksi.ksi_signo;
1170 	return (error);
1171 }
1172 
1173 int
1174 sys_sigwaitinfo(struct thread *td, struct sigwaitinfo_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 		return (error);
1183 
1184 	error = kern_sigtimedwait(td, set, &ksi, NULL);
1185 	if (error)
1186 		return (error);
1187 
1188 	if (uap->info)
1189 		error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1190 
1191 	if (error == 0)
1192 		td->td_retval[0] = ksi.ksi_signo;
1193 	return (error);
1194 }
1195 
1196 int
1197 kern_sigtimedwait(struct thread *td, sigset_t waitset, ksiginfo_t *ksi,
1198 	struct timespec *timeout)
1199 {
1200 	struct sigacts *ps;
1201 	sigset_t saved_mask, new_block;
1202 	struct proc *p;
1203 	int error, sig, timo, timevalid = 0;
1204 	struct timespec rts, ets, ts;
1205 	struct timeval tv;
1206 
1207 	p = td->td_proc;
1208 	error = 0;
1209 	ets.tv_sec = 0;
1210 	ets.tv_nsec = 0;
1211 
1212 	if (timeout != NULL) {
1213 		if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) {
1214 			timevalid = 1;
1215 			getnanouptime(&rts);
1216 			ets = rts;
1217 			timespecadd(&ets, timeout);
1218 		}
1219 	}
1220 	ksiginfo_init(ksi);
1221 	/* Some signals can not be waited for. */
1222 	SIG_CANTMASK(waitset);
1223 	ps = p->p_sigacts;
1224 	PROC_LOCK(p);
1225 	saved_mask = td->td_sigmask;
1226 	SIGSETNAND(td->td_sigmask, waitset);
1227 	for (;;) {
1228 		mtx_lock(&ps->ps_mtx);
1229 		sig = cursig(td);
1230 		mtx_unlock(&ps->ps_mtx);
1231 		if (sig != 0 && SIGISMEMBER(waitset, sig)) {
1232 			if (sigqueue_get(&td->td_sigqueue, sig, ksi) != 0 ||
1233 			    sigqueue_get(&p->p_sigqueue, sig, ksi) != 0) {
1234 				error = 0;
1235 				break;
1236 			}
1237 		}
1238 
1239 		if (error != 0)
1240 			break;
1241 
1242 		/*
1243 		 * POSIX says this must be checked after looking for pending
1244 		 * signals.
1245 		 */
1246 		if (timeout != NULL) {
1247 			if (!timevalid) {
1248 				error = EINVAL;
1249 				break;
1250 			}
1251 			getnanouptime(&rts);
1252 			if (timespeccmp(&rts, &ets, >=)) {
1253 				error = EAGAIN;
1254 				break;
1255 			}
1256 			ts = ets;
1257 			timespecsub(&ts, &rts);
1258 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1259 			timo = tvtohz(&tv);
1260 		} else {
1261 			timo = 0;
1262 		}
1263 
1264 		error = msleep(ps, &p->p_mtx, PPAUSE|PCATCH, "sigwait", timo);
1265 
1266 		if (timeout != NULL) {
1267 			if (error == ERESTART) {
1268 				/* Timeout can not be restarted. */
1269 				error = EINTR;
1270 			} else if (error == EAGAIN) {
1271 				/* We will calculate timeout by ourself. */
1272 				error = 0;
1273 			}
1274 		}
1275 	}
1276 
1277 	new_block = saved_mask;
1278 	SIGSETNAND(new_block, td->td_sigmask);
1279 	td->td_sigmask = saved_mask;
1280 	/*
1281 	 * Fewer signals can be delivered to us, reschedule signal
1282 	 * notification.
1283 	 */
1284 	if (p->p_numthreads != 1)
1285 		reschedule_signals(p, new_block, 0);
1286 
1287 	if (error == 0) {
1288 		SDT_PROBE(proc, kernel, , signal__clear, sig, ksi, 0, 0, 0);
1289 
1290 		if (ksi->ksi_code == SI_TIMER)
1291 			itimer_accept(p, ksi->ksi_timerid, ksi);
1292 
1293 #ifdef KTRACE
1294 		if (KTRPOINT(td, KTR_PSIG)) {
1295 			sig_t action;
1296 
1297 			mtx_lock(&ps->ps_mtx);
1298 			action = ps->ps_sigact[_SIG_IDX(sig)];
1299 			mtx_unlock(&ps->ps_mtx);
1300 			ktrpsig(sig, action, &td->td_sigmask, ksi->ksi_code);
1301 		}
1302 #endif
1303 		if (sig == SIGKILL)
1304 			sigexit(td, sig);
1305 	}
1306 	PROC_UNLOCK(p);
1307 	return (error);
1308 }
1309 
1310 #ifndef _SYS_SYSPROTO_H_
1311 struct sigpending_args {
1312 	sigset_t	*set;
1313 };
1314 #endif
1315 int
1316 sys_sigpending(td, uap)
1317 	struct thread *td;
1318 	struct sigpending_args *uap;
1319 {
1320 	struct proc *p = td->td_proc;
1321 	sigset_t pending;
1322 
1323 	PROC_LOCK(p);
1324 	pending = p->p_sigqueue.sq_signals;
1325 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1326 	PROC_UNLOCK(p);
1327 	return (copyout(&pending, uap->set, sizeof(sigset_t)));
1328 }
1329 
1330 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1331 #ifndef _SYS_SYSPROTO_H_
1332 struct osigpending_args {
1333 	int	dummy;
1334 };
1335 #endif
1336 int
1337 osigpending(td, uap)
1338 	struct thread *td;
1339 	struct osigpending_args *uap;
1340 {
1341 	struct proc *p = td->td_proc;
1342 	sigset_t pending;
1343 
1344 	PROC_LOCK(p);
1345 	pending = p->p_sigqueue.sq_signals;
1346 	SIGSETOR(pending, td->td_sigqueue.sq_signals);
1347 	PROC_UNLOCK(p);
1348 	SIG2OSIG(pending, td->td_retval[0]);
1349 	return (0);
1350 }
1351 #endif /* COMPAT_43 */
1352 
1353 #if defined(COMPAT_43)
1354 /*
1355  * Generalized interface signal handler, 4.3-compatible.
1356  */
1357 #ifndef _SYS_SYSPROTO_H_
1358 struct osigvec_args {
1359 	int	signum;
1360 	struct	sigvec *nsv;
1361 	struct	sigvec *osv;
1362 };
1363 #endif
1364 /* ARGSUSED */
1365 int
1366 osigvec(td, uap)
1367 	struct thread *td;
1368 	register struct osigvec_args *uap;
1369 {
1370 	struct sigvec vec;
1371 	struct sigaction nsa, osa;
1372 	register struct sigaction *nsap, *osap;
1373 	int error;
1374 
1375 	if (uap->signum <= 0 || uap->signum >= ONSIG)
1376 		return (EINVAL);
1377 	nsap = (uap->nsv != NULL) ? &nsa : NULL;
1378 	osap = (uap->osv != NULL) ? &osa : NULL;
1379 	if (nsap) {
1380 		error = copyin(uap->nsv, &vec, sizeof(vec));
1381 		if (error)
1382 			return (error);
1383 		nsap->sa_handler = vec.sv_handler;
1384 		OSIG2SIG(vec.sv_mask, nsap->sa_mask);
1385 		nsap->sa_flags = vec.sv_flags;
1386 		nsap->sa_flags ^= SA_RESTART;	/* opposite of SV_INTERRUPT */
1387 	}
1388 	error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
1389 	if (osap && !error) {
1390 		vec.sv_handler = osap->sa_handler;
1391 		SIG2OSIG(osap->sa_mask, vec.sv_mask);
1392 		vec.sv_flags = osap->sa_flags;
1393 		vec.sv_flags &= ~SA_NOCLDWAIT;
1394 		vec.sv_flags ^= SA_RESTART;
1395 		error = copyout(&vec, uap->osv, sizeof(vec));
1396 	}
1397 	return (error);
1398 }
1399 
1400 #ifndef _SYS_SYSPROTO_H_
1401 struct osigblock_args {
1402 	int	mask;
1403 };
1404 #endif
1405 int
1406 osigblock(td, uap)
1407 	register struct thread *td;
1408 	struct osigblock_args *uap;
1409 {
1410 	sigset_t set, oset;
1411 
1412 	OSIG2SIG(uap->mask, set);
1413 	kern_sigprocmask(td, SIG_BLOCK, &set, &oset, 0);
1414 	SIG2OSIG(oset, td->td_retval[0]);
1415 	return (0);
1416 }
1417 
1418 #ifndef _SYS_SYSPROTO_H_
1419 struct osigsetmask_args {
1420 	int	mask;
1421 };
1422 #endif
1423 int
1424 osigsetmask(td, uap)
1425 	struct thread *td;
1426 	struct osigsetmask_args *uap;
1427 {
1428 	sigset_t set, oset;
1429 
1430 	OSIG2SIG(uap->mask, set);
1431 	kern_sigprocmask(td, SIG_SETMASK, &set, &oset, 0);
1432 	SIG2OSIG(oset, td->td_retval[0]);
1433 	return (0);
1434 }
1435 #endif /* COMPAT_43 */
1436 
1437 /*
1438  * Suspend calling thread until signal, providing mask to be set in the
1439  * meantime.
1440  */
1441 #ifndef _SYS_SYSPROTO_H_
1442 struct sigsuspend_args {
1443 	const sigset_t *sigmask;
1444 };
1445 #endif
1446 /* ARGSUSED */
1447 int
1448 sys_sigsuspend(td, uap)
1449 	struct thread *td;
1450 	struct sigsuspend_args *uap;
1451 {
1452 	sigset_t mask;
1453 	int error;
1454 
1455 	error = copyin(uap->sigmask, &mask, sizeof(mask));
1456 	if (error)
1457 		return (error);
1458 	return (kern_sigsuspend(td, mask));
1459 }
1460 
1461 int
1462 kern_sigsuspend(struct thread *td, sigset_t mask)
1463 {
1464 	struct proc *p = td->td_proc;
1465 	int has_sig, sig;
1466 
1467 	/*
1468 	 * When returning from sigsuspend, we want
1469 	 * the old mask to be restored after the
1470 	 * signal handler has finished.  Thus, we
1471 	 * save it here and mark the sigacts structure
1472 	 * to indicate this.
1473 	 */
1474 	PROC_LOCK(p);
1475 	kern_sigprocmask(td, SIG_SETMASK, &mask, &td->td_oldsigmask,
1476 	    SIGPROCMASK_PROC_LOCKED);
1477 	td->td_pflags |= TDP_OLDMASK;
1478 
1479 	/*
1480 	 * Process signals now. Otherwise, we can get spurious wakeup
1481 	 * due to signal entered process queue, but delivered to other
1482 	 * thread. But sigsuspend should return only on signal
1483 	 * delivery.
1484 	 */
1485 	(p->p_sysent->sv_set_syscall_retval)(td, EINTR);
1486 	for (has_sig = 0; !has_sig;) {
1487 		while (msleep(&p->p_sigacts, &p->p_mtx, PPAUSE|PCATCH, "pause",
1488 			0) == 0)
1489 			/* void */;
1490 		thread_suspend_check(0);
1491 		mtx_lock(&p->p_sigacts->ps_mtx);
1492 		while ((sig = cursig(td)) != 0)
1493 			has_sig += postsig(sig);
1494 		mtx_unlock(&p->p_sigacts->ps_mtx);
1495 	}
1496 	PROC_UNLOCK(p);
1497 	td->td_errno = EINTR;
1498 	td->td_pflags |= TDP_NERRNO;
1499 	return (EJUSTRETURN);
1500 }
1501 
1502 #ifdef COMPAT_43	/* XXX - COMPAT_FBSD3 */
1503 /*
1504  * Compatibility sigsuspend call for old binaries.  Note nonstandard calling
1505  * convention: libc stub passes mask, not pointer, to save a copyin.
1506  */
1507 #ifndef _SYS_SYSPROTO_H_
1508 struct osigsuspend_args {
1509 	osigset_t mask;
1510 };
1511 #endif
1512 /* ARGSUSED */
1513 int
1514 osigsuspend(td, uap)
1515 	struct thread *td;
1516 	struct osigsuspend_args *uap;
1517 {
1518 	sigset_t mask;
1519 
1520 	OSIG2SIG(uap->mask, mask);
1521 	return (kern_sigsuspend(td, mask));
1522 }
1523 #endif /* COMPAT_43 */
1524 
1525 #if defined(COMPAT_43)
1526 #ifndef _SYS_SYSPROTO_H_
1527 struct osigstack_args {
1528 	struct	sigstack *nss;
1529 	struct	sigstack *oss;
1530 };
1531 #endif
1532 /* ARGSUSED */
1533 int
1534 osigstack(td, uap)
1535 	struct thread *td;
1536 	register struct osigstack_args *uap;
1537 {
1538 	struct sigstack nss, oss;
1539 	int error = 0;
1540 
1541 	if (uap->nss != NULL) {
1542 		error = copyin(uap->nss, &nss, sizeof(nss));
1543 		if (error)
1544 			return (error);
1545 	}
1546 	oss.ss_sp = td->td_sigstk.ss_sp;
1547 	oss.ss_onstack = sigonstack(cpu_getstack(td));
1548 	if (uap->nss != NULL) {
1549 		td->td_sigstk.ss_sp = nss.ss_sp;
1550 		td->td_sigstk.ss_size = 0;
1551 		td->td_sigstk.ss_flags |= nss.ss_onstack & SS_ONSTACK;
1552 		td->td_pflags |= TDP_ALTSTACK;
1553 	}
1554 	if (uap->oss != NULL)
1555 		error = copyout(&oss, uap->oss, sizeof(oss));
1556 
1557 	return (error);
1558 }
1559 #endif /* COMPAT_43 */
1560 
1561 #ifndef _SYS_SYSPROTO_H_
1562 struct sigaltstack_args {
1563 	stack_t	*ss;
1564 	stack_t	*oss;
1565 };
1566 #endif
1567 /* ARGSUSED */
1568 int
1569 sys_sigaltstack(td, uap)
1570 	struct thread *td;
1571 	register struct sigaltstack_args *uap;
1572 {
1573 	stack_t ss, oss;
1574 	int error;
1575 
1576 	if (uap->ss != NULL) {
1577 		error = copyin(uap->ss, &ss, sizeof(ss));
1578 		if (error)
1579 			return (error);
1580 	}
1581 	error = kern_sigaltstack(td, (uap->ss != NULL) ? &ss : NULL,
1582 	    (uap->oss != NULL) ? &oss : NULL);
1583 	if (error)
1584 		return (error);
1585 	if (uap->oss != NULL)
1586 		error = copyout(&oss, uap->oss, sizeof(stack_t));
1587 	return (error);
1588 }
1589 
1590 int
1591 kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
1592 {
1593 	struct proc *p = td->td_proc;
1594 	int oonstack;
1595 
1596 	oonstack = sigonstack(cpu_getstack(td));
1597 
1598 	if (oss != NULL) {
1599 		*oss = td->td_sigstk;
1600 		oss->ss_flags = (td->td_pflags & TDP_ALTSTACK)
1601 		    ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1602 	}
1603 
1604 	if (ss != NULL) {
1605 		if (oonstack)
1606 			return (EPERM);
1607 		if ((ss->ss_flags & ~SS_DISABLE) != 0)
1608 			return (EINVAL);
1609 		if (!(ss->ss_flags & SS_DISABLE)) {
1610 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
1611 				return (ENOMEM);
1612 
1613 			td->td_sigstk = *ss;
1614 			td->td_pflags |= TDP_ALTSTACK;
1615 		} else {
1616 			td->td_pflags &= ~TDP_ALTSTACK;
1617 		}
1618 	}
1619 	return (0);
1620 }
1621 
1622 /*
1623  * Common code for kill process group/broadcast kill.
1624  * cp is calling process.
1625  */
1626 static int
1627 killpg1(struct thread *td, int sig, int pgid, int all, ksiginfo_t *ksi)
1628 {
1629 	struct proc *p;
1630 	struct pgrp *pgrp;
1631 	int err;
1632 	int ret;
1633 
1634 	ret = ESRCH;
1635 	if (all) {
1636 		/*
1637 		 * broadcast
1638 		 */
1639 		sx_slock(&allproc_lock);
1640 		FOREACH_PROC_IN_SYSTEM(p) {
1641 			PROC_LOCK(p);
1642 			if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1643 			    p == td->td_proc || p->p_state == PRS_NEW) {
1644 				PROC_UNLOCK(p);
1645 				continue;
1646 			}
1647 			err = p_cansignal(td, p, sig);
1648 			if (err == 0) {
1649 				if (sig)
1650 					pksignal(p, sig, ksi);
1651 				ret = err;
1652 			}
1653 			else if (ret == ESRCH)
1654 				ret = err;
1655 			PROC_UNLOCK(p);
1656 		}
1657 		sx_sunlock(&allproc_lock);
1658 	} else {
1659 		sx_slock(&proctree_lock);
1660 		if (pgid == 0) {
1661 			/*
1662 			 * zero pgid means send to my process group.
1663 			 */
1664 			pgrp = td->td_proc->p_pgrp;
1665 			PGRP_LOCK(pgrp);
1666 		} else {
1667 			pgrp = pgfind(pgid);
1668 			if (pgrp == NULL) {
1669 				sx_sunlock(&proctree_lock);
1670 				return (ESRCH);
1671 			}
1672 		}
1673 		sx_sunlock(&proctree_lock);
1674 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1675 			PROC_LOCK(p);
1676 			if (p->p_pid <= 1 || p->p_flag & P_SYSTEM ||
1677 			    p->p_state == PRS_NEW) {
1678 				PROC_UNLOCK(p);
1679 				continue;
1680 			}
1681 			err = p_cansignal(td, p, sig);
1682 			if (err == 0) {
1683 				if (sig)
1684 					pksignal(p, sig, ksi);
1685 				ret = err;
1686 			}
1687 			else if (ret == ESRCH)
1688 				ret = err;
1689 			PROC_UNLOCK(p);
1690 		}
1691 		PGRP_UNLOCK(pgrp);
1692 	}
1693 	return (ret);
1694 }
1695 
1696 #ifndef _SYS_SYSPROTO_H_
1697 struct kill_args {
1698 	int	pid;
1699 	int	signum;
1700 };
1701 #endif
1702 /* ARGSUSED */
1703 int
1704 sys_kill(struct thread *td, struct kill_args *uap)
1705 {
1706 	ksiginfo_t ksi;
1707 	struct proc *p;
1708 	int error;
1709 
1710 	/*
1711 	 * A process in capability mode can send signals only to himself.
1712 	 * The main rationale behind this is that abort(3) is implemented as
1713 	 * kill(getpid(), SIGABRT).
1714 	 */
1715 	if (IN_CAPABILITY_MODE(td) && uap->pid != td->td_proc->p_pid)
1716 		return (ECAPMODE);
1717 
1718 	AUDIT_ARG_SIGNUM(uap->signum);
1719 	AUDIT_ARG_PID(uap->pid);
1720 	if ((u_int)uap->signum > _SIG_MAXSIG)
1721 		return (EINVAL);
1722 
1723 	ksiginfo_init(&ksi);
1724 	ksi.ksi_signo = uap->signum;
1725 	ksi.ksi_code = SI_USER;
1726 	ksi.ksi_pid = td->td_proc->p_pid;
1727 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1728 
1729 	if (uap->pid > 0) {
1730 		/* kill single process */
1731 		if ((p = pfind(uap->pid)) == NULL) {
1732 			if ((p = zpfind(uap->pid)) == NULL)
1733 				return (ESRCH);
1734 		}
1735 		AUDIT_ARG_PROCESS(p);
1736 		error = p_cansignal(td, p, uap->signum);
1737 		if (error == 0 && uap->signum)
1738 			pksignal(p, uap->signum, &ksi);
1739 		PROC_UNLOCK(p);
1740 		return (error);
1741 	}
1742 	switch (uap->pid) {
1743 	case -1:		/* broadcast signal */
1744 		return (killpg1(td, uap->signum, 0, 1, &ksi));
1745 	case 0:			/* signal own process group */
1746 		return (killpg1(td, uap->signum, 0, 0, &ksi));
1747 	default:		/* negative explicit process group */
1748 		return (killpg1(td, uap->signum, -uap->pid, 0, &ksi));
1749 	}
1750 	/* NOTREACHED */
1751 }
1752 
1753 int
1754 sys_pdkill(td, uap)
1755 	struct thread *td;
1756 	struct pdkill_args *uap;
1757 {
1758 	struct proc *p;
1759 	cap_rights_t rights;
1760 	int error;
1761 
1762 	AUDIT_ARG_SIGNUM(uap->signum);
1763 	AUDIT_ARG_FD(uap->fd);
1764 	if ((u_int)uap->signum > _SIG_MAXSIG)
1765 		return (EINVAL);
1766 
1767 	error = procdesc_find(td, uap->fd,
1768 	    cap_rights_init(&rights, CAP_PDKILL), &p);
1769 	if (error)
1770 		return (error);
1771 	AUDIT_ARG_PROCESS(p);
1772 	error = p_cansignal(td, p, uap->signum);
1773 	if (error == 0 && uap->signum)
1774 		kern_psignal(p, uap->signum);
1775 	PROC_UNLOCK(p);
1776 	return (error);
1777 }
1778 
1779 #if defined(COMPAT_43)
1780 #ifndef _SYS_SYSPROTO_H_
1781 struct okillpg_args {
1782 	int	pgid;
1783 	int	signum;
1784 };
1785 #endif
1786 /* ARGSUSED */
1787 int
1788 okillpg(struct thread *td, struct okillpg_args *uap)
1789 {
1790 	ksiginfo_t ksi;
1791 
1792 	AUDIT_ARG_SIGNUM(uap->signum);
1793 	AUDIT_ARG_PID(uap->pgid);
1794 	if ((u_int)uap->signum > _SIG_MAXSIG)
1795 		return (EINVAL);
1796 
1797 	ksiginfo_init(&ksi);
1798 	ksi.ksi_signo = uap->signum;
1799 	ksi.ksi_code = SI_USER;
1800 	ksi.ksi_pid = td->td_proc->p_pid;
1801 	ksi.ksi_uid = td->td_ucred->cr_ruid;
1802 	return (killpg1(td, uap->signum, uap->pgid, 0, &ksi));
1803 }
1804 #endif /* COMPAT_43 */
1805 
1806 #ifndef _SYS_SYSPROTO_H_
1807 struct sigqueue_args {
1808 	pid_t pid;
1809 	int signum;
1810 	/* union sigval */ void *value;
1811 };
1812 #endif
1813 int
1814 sys_sigqueue(struct thread *td, struct sigqueue_args *uap)
1815 {
1816 	ksiginfo_t ksi;
1817 	struct proc *p;
1818 	int error;
1819 
1820 	if ((u_int)uap->signum > _SIG_MAXSIG)
1821 		return (EINVAL);
1822 
1823 	/*
1824 	 * Specification says sigqueue can only send signal to
1825 	 * single process.
1826 	 */
1827 	if (uap->pid <= 0)
1828 		return (EINVAL);
1829 
1830 	if ((p = pfind(uap->pid)) == NULL) {
1831 		if ((p = zpfind(uap->pid)) == NULL)
1832 			return (ESRCH);
1833 	}
1834 	error = p_cansignal(td, p, uap->signum);
1835 	if (error == 0 && uap->signum != 0) {
1836 		ksiginfo_init(&ksi);
1837 		ksi.ksi_flags = KSI_SIGQ;
1838 		ksi.ksi_signo = uap->signum;
1839 		ksi.ksi_code = SI_QUEUE;
1840 		ksi.ksi_pid = td->td_proc->p_pid;
1841 		ksi.ksi_uid = td->td_ucred->cr_ruid;
1842 		ksi.ksi_value.sival_ptr = uap->value;
1843 		error = pksignal(p, ksi.ksi_signo, &ksi);
1844 	}
1845 	PROC_UNLOCK(p);
1846 	return (error);
1847 }
1848 
1849 /*
1850  * Send a signal to a process group.
1851  */
1852 void
1853 gsignal(int pgid, int sig, ksiginfo_t *ksi)
1854 {
1855 	struct pgrp *pgrp;
1856 
1857 	if (pgid != 0) {
1858 		sx_slock(&proctree_lock);
1859 		pgrp = pgfind(pgid);
1860 		sx_sunlock(&proctree_lock);
1861 		if (pgrp != NULL) {
1862 			pgsignal(pgrp, sig, 0, ksi);
1863 			PGRP_UNLOCK(pgrp);
1864 		}
1865 	}
1866 }
1867 
1868 /*
1869  * Send a signal to a process group.  If checktty is 1,
1870  * limit to members which have a controlling terminal.
1871  */
1872 void
1873 pgsignal(struct pgrp *pgrp, int sig, int checkctty, ksiginfo_t *ksi)
1874 {
1875 	struct proc *p;
1876 
1877 	if (pgrp) {
1878 		PGRP_LOCK_ASSERT(pgrp, MA_OWNED);
1879 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
1880 			PROC_LOCK(p);
1881 			if (p->p_state == PRS_NORMAL &&
1882 			    (checkctty == 0 || p->p_flag & P_CONTROLT))
1883 				pksignal(p, sig, ksi);
1884 			PROC_UNLOCK(p);
1885 		}
1886 	}
1887 }
1888 
1889 
1890 /*
1891  * Recalculate the signal mask and reset the signal disposition after
1892  * usermode frame for delivery is formed.  Should be called after
1893  * mach-specific routine, because sysent->sv_sendsig() needs correct
1894  * ps_siginfo and signal mask.
1895  */
1896 static void
1897 postsig_done(int sig, struct thread *td, struct sigacts *ps)
1898 {
1899 	sigset_t mask;
1900 
1901 	mtx_assert(&ps->ps_mtx, MA_OWNED);
1902 	td->td_ru.ru_nsignals++;
1903 	mask = ps->ps_catchmask[_SIG_IDX(sig)];
1904 	if (!SIGISMEMBER(ps->ps_signodefer, sig))
1905 		SIGADDSET(mask, sig);
1906 	kern_sigprocmask(td, SIG_BLOCK, &mask, NULL,
1907 	    SIGPROCMASK_PROC_LOCKED | SIGPROCMASK_PS_LOCKED);
1908 	if (SIGISMEMBER(ps->ps_sigreset, sig))
1909 		sigdflt(ps, sig);
1910 }
1911 
1912 
1913 /*
1914  * Send a signal caused by a trap to the current thread.  If it will be
1915  * caught immediately, deliver it with correct code.  Otherwise, post it
1916  * normally.
1917  */
1918 void
1919 trapsignal(struct thread *td, ksiginfo_t *ksi)
1920 {
1921 	struct sigacts *ps;
1922 	struct proc *p;
1923 	int sig;
1924 	int code;
1925 
1926 	p = td->td_proc;
1927 	sig = ksi->ksi_signo;
1928 	code = ksi->ksi_code;
1929 	KASSERT(_SIG_VALID(sig), ("invalid signal"));
1930 
1931 	PROC_LOCK(p);
1932 	ps = p->p_sigacts;
1933 	mtx_lock(&ps->ps_mtx);
1934 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
1935 	    !SIGISMEMBER(td->td_sigmask, sig)) {
1936 #ifdef KTRACE
1937 		if (KTRPOINT(curthread, KTR_PSIG))
1938 			ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
1939 			    &td->td_sigmask, code);
1940 #endif
1941 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
1942 				ksi, &td->td_sigmask);
1943 		postsig_done(sig, td, ps);
1944 		mtx_unlock(&ps->ps_mtx);
1945 	} else {
1946 		/*
1947 		 * Avoid a possible infinite loop if the thread
1948 		 * masking the signal or process is ignoring the
1949 		 * signal.
1950 		 */
1951 		if (kern_forcesigexit &&
1952 		    (SIGISMEMBER(td->td_sigmask, sig) ||
1953 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
1954 			SIGDELSET(td->td_sigmask, sig);
1955 			SIGDELSET(ps->ps_sigcatch, sig);
1956 			SIGDELSET(ps->ps_sigignore, sig);
1957 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1958 		}
1959 		mtx_unlock(&ps->ps_mtx);
1960 		p->p_code = code;	/* XXX for core dump/debugger */
1961 		p->p_sig = sig;		/* XXX to verify code */
1962 		tdsendsignal(p, td, sig, ksi);
1963 	}
1964 	PROC_UNLOCK(p);
1965 }
1966 
1967 static struct thread *
1968 sigtd(struct proc *p, int sig, int prop)
1969 {
1970 	struct thread *td, *signal_td;
1971 
1972 	PROC_LOCK_ASSERT(p, MA_OWNED);
1973 
1974 	/*
1975 	 * Check if current thread can handle the signal without
1976 	 * switching context to another thread.
1977 	 */
1978 	if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig))
1979 		return (curthread);
1980 	signal_td = NULL;
1981 	FOREACH_THREAD_IN_PROC(p, td) {
1982 		if (!SIGISMEMBER(td->td_sigmask, sig)) {
1983 			signal_td = td;
1984 			break;
1985 		}
1986 	}
1987 	if (signal_td == NULL)
1988 		signal_td = FIRST_THREAD_IN_PROC(p);
1989 	return (signal_td);
1990 }
1991 
1992 /*
1993  * Send the signal to the process.  If the signal has an action, the action
1994  * is usually performed by the target process rather than the caller; we add
1995  * the signal to the set of pending signals for the process.
1996  *
1997  * Exceptions:
1998  *   o When a stop signal is sent to a sleeping process that takes the
1999  *     default action, the process is stopped without awakening it.
2000  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2001  *     regardless of the signal action (eg, blocked or ignored).
2002  *
2003  * Other ignored signals are discarded immediately.
2004  *
2005  * NB: This function may be entered from the debugger via the "kill" DDB
2006  * command.  There is little that can be done to mitigate the possibly messy
2007  * side effects of this unwise possibility.
2008  */
2009 void
2010 kern_psignal(struct proc *p, int sig)
2011 {
2012 	ksiginfo_t ksi;
2013 
2014 	ksiginfo_init(&ksi);
2015 	ksi.ksi_signo = sig;
2016 	ksi.ksi_code = SI_KERNEL;
2017 	(void) tdsendsignal(p, NULL, sig, &ksi);
2018 }
2019 
2020 int
2021 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
2022 {
2023 
2024 	return (tdsendsignal(p, NULL, sig, ksi));
2025 }
2026 
2027 /* Utility function for finding a thread to send signal event to. */
2028 int
2029 sigev_findtd(struct proc *p ,struct sigevent *sigev, struct thread **ttd)
2030 {
2031 	struct thread *td;
2032 
2033 	if (sigev->sigev_notify == SIGEV_THREAD_ID) {
2034 		td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
2035 		if (td == NULL)
2036 			return (ESRCH);
2037 		*ttd = td;
2038 	} else {
2039 		*ttd = NULL;
2040 		PROC_LOCK(p);
2041 	}
2042 	return (0);
2043 }
2044 
2045 void
2046 tdsignal(struct thread *td, int sig)
2047 {
2048 	ksiginfo_t ksi;
2049 
2050 	ksiginfo_init(&ksi);
2051 	ksi.ksi_signo = sig;
2052 	ksi.ksi_code = SI_KERNEL;
2053 	(void) tdsendsignal(td->td_proc, td, sig, &ksi);
2054 }
2055 
2056 void
2057 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2058 {
2059 
2060 	(void) tdsendsignal(td->td_proc, td, sig, ksi);
2061 }
2062 
2063 int
2064 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2065 {
2066 	sig_t action;
2067 	sigqueue_t *sigqueue;
2068 	int prop;
2069 	struct sigacts *ps;
2070 	int intrval;
2071 	int ret = 0;
2072 	int wakeup_swapper;
2073 
2074 	MPASS(td == NULL || p == td->td_proc);
2075 	PROC_LOCK_ASSERT(p, MA_OWNED);
2076 
2077 	if (!_SIG_VALID(sig))
2078 		panic("%s(): invalid signal %d", __func__, sig);
2079 
2080 	KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2081 
2082 	/*
2083 	 * IEEE Std 1003.1-2001: return success when killing a zombie.
2084 	 */
2085 	if (p->p_state == PRS_ZOMBIE) {
2086 		if (ksi && (ksi->ksi_flags & KSI_INS))
2087 			ksiginfo_tryfree(ksi);
2088 		return (ret);
2089 	}
2090 
2091 	ps = p->p_sigacts;
2092 	KNOTE_LOCKED(&p->p_klist, NOTE_SIGNAL | sig);
2093 	prop = sigprop(sig);
2094 
2095 	if (td == NULL) {
2096 		td = sigtd(p, sig, prop);
2097 		sigqueue = &p->p_sigqueue;
2098 	} else
2099 		sigqueue = &td->td_sigqueue;
2100 
2101 	SDT_PROBE(proc, kernel, , signal__send, td, p, sig, 0, 0 );
2102 
2103 	/*
2104 	 * If the signal is being ignored,
2105 	 * then we forget about it immediately.
2106 	 * (Note: we don't set SIGCONT in ps_sigignore,
2107 	 * and if it is set to SIG_IGN,
2108 	 * action will be SIG_DFL here.)
2109 	 */
2110 	mtx_lock(&ps->ps_mtx);
2111 	if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2112 		SDT_PROBE(proc, kernel, , signal__discard, td, p, sig, 0, 0 );
2113 
2114 		mtx_unlock(&ps->ps_mtx);
2115 		if (ksi && (ksi->ksi_flags & KSI_INS))
2116 			ksiginfo_tryfree(ksi);
2117 		return (ret);
2118 	}
2119 	if (SIGISMEMBER(td->td_sigmask, sig))
2120 		action = SIG_HOLD;
2121 	else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2122 		action = SIG_CATCH;
2123 	else
2124 		action = SIG_DFL;
2125 	if (SIGISMEMBER(ps->ps_sigintr, sig))
2126 		intrval = EINTR;
2127 	else
2128 		intrval = ERESTART;
2129 	mtx_unlock(&ps->ps_mtx);
2130 
2131 	if (prop & SA_CONT)
2132 		sigqueue_delete_stopmask_proc(p);
2133 	else if (prop & SA_STOP) {
2134 		/*
2135 		 * If sending a tty stop signal to a member of an orphaned
2136 		 * process group, discard the signal here if the action
2137 		 * is default; don't stop the process below if sleeping,
2138 		 * and don't clear any pending SIGCONT.
2139 		 */
2140 		if ((prop & SA_TTYSTOP) &&
2141 		    (p->p_pgrp->pg_jobc == 0) &&
2142 		    (action == SIG_DFL)) {
2143 			if (ksi && (ksi->ksi_flags & KSI_INS))
2144 				ksiginfo_tryfree(ksi);
2145 			return (ret);
2146 		}
2147 		sigqueue_delete_proc(p, SIGCONT);
2148 		if (p->p_flag & P_CONTINUED) {
2149 			p->p_flag &= ~P_CONTINUED;
2150 			PROC_LOCK(p->p_pptr);
2151 			sigqueue_take(p->p_ksi);
2152 			PROC_UNLOCK(p->p_pptr);
2153 		}
2154 	}
2155 
2156 	ret = sigqueue_add(sigqueue, sig, ksi);
2157 	if (ret != 0)
2158 		return (ret);
2159 	signotify(td);
2160 	/*
2161 	 * Defer further processing for signals which are held,
2162 	 * except that stopped processes must be continued by SIGCONT.
2163 	 */
2164 	if (action == SIG_HOLD &&
2165 	    !((prop & SA_CONT) && (p->p_flag & P_STOPPED_SIG)))
2166 		return (ret);
2167 	/*
2168 	 * SIGKILL: Remove procfs STOPEVENTs.
2169 	 */
2170 	if (sig == SIGKILL) {
2171 		/* from procfs_ioctl.c: PIOCBIC */
2172 		p->p_stops = 0;
2173 		/* from procfs_ioctl.c: PIOCCONT */
2174 		p->p_step = 0;
2175 		wakeup(&p->p_step);
2176 	}
2177 	/*
2178 	 * Some signals have a process-wide effect and a per-thread
2179 	 * component.  Most processing occurs when the process next
2180 	 * tries to cross the user boundary, however there are some
2181 	 * times when processing needs to be done immediately, such as
2182 	 * waking up threads so that they can cross the user boundary.
2183 	 * We try to do the per-process part here.
2184 	 */
2185 	if (P_SHOULDSTOP(p)) {
2186 		KASSERT(!(p->p_flag & P_WEXIT),
2187 		    ("signal to stopped but exiting process"));
2188 		if (sig == SIGKILL) {
2189 			/*
2190 			 * If traced process is already stopped,
2191 			 * then no further action is necessary.
2192 			 */
2193 			if (p->p_flag & P_TRACED)
2194 				goto out;
2195 			/*
2196 			 * SIGKILL sets process running.
2197 			 * It will die elsewhere.
2198 			 * All threads must be restarted.
2199 			 */
2200 			p->p_flag &= ~P_STOPPED_SIG;
2201 			goto runfast;
2202 		}
2203 
2204 		if (prop & SA_CONT) {
2205 			/*
2206 			 * If traced process is already stopped,
2207 			 * then no further action is necessary.
2208 			 */
2209 			if (p->p_flag & P_TRACED)
2210 				goto out;
2211 			/*
2212 			 * If SIGCONT is default (or ignored), we continue the
2213 			 * process but don't leave the signal in sigqueue as
2214 			 * it has no further action.  If SIGCONT is held, we
2215 			 * continue the process and leave the signal in
2216 			 * sigqueue.  If the process catches SIGCONT, let it
2217 			 * handle the signal itself.  If it isn't waiting on
2218 			 * an event, it goes back to run state.
2219 			 * Otherwise, process goes back to sleep state.
2220 			 */
2221 			p->p_flag &= ~P_STOPPED_SIG;
2222 			PROC_SLOCK(p);
2223 			if (p->p_numthreads == p->p_suspcount) {
2224 				PROC_SUNLOCK(p);
2225 				p->p_flag |= P_CONTINUED;
2226 				p->p_xstat = SIGCONT;
2227 				PROC_LOCK(p->p_pptr);
2228 				childproc_continued(p);
2229 				PROC_UNLOCK(p->p_pptr);
2230 				PROC_SLOCK(p);
2231 			}
2232 			if (action == SIG_DFL) {
2233 				thread_unsuspend(p);
2234 				PROC_SUNLOCK(p);
2235 				sigqueue_delete(sigqueue, sig);
2236 				goto out;
2237 			}
2238 			if (action == SIG_CATCH) {
2239 				/*
2240 				 * The process wants to catch it so it needs
2241 				 * to run at least one thread, but which one?
2242 				 */
2243 				PROC_SUNLOCK(p);
2244 				goto runfast;
2245 			}
2246 			/*
2247 			 * The signal is not ignored or caught.
2248 			 */
2249 			thread_unsuspend(p);
2250 			PROC_SUNLOCK(p);
2251 			goto out;
2252 		}
2253 
2254 		if (prop & SA_STOP) {
2255 			/*
2256 			 * If traced process is already stopped,
2257 			 * then no further action is necessary.
2258 			 */
2259 			if (p->p_flag & P_TRACED)
2260 				goto out;
2261 			/*
2262 			 * Already stopped, don't need to stop again
2263 			 * (If we did the shell could get confused).
2264 			 * Just make sure the signal STOP bit set.
2265 			 */
2266 			p->p_flag |= P_STOPPED_SIG;
2267 			sigqueue_delete(sigqueue, sig);
2268 			goto out;
2269 		}
2270 
2271 		/*
2272 		 * All other kinds of signals:
2273 		 * If a thread is sleeping interruptibly, simulate a
2274 		 * wakeup so that when it is continued it will be made
2275 		 * runnable and can look at the signal.  However, don't make
2276 		 * the PROCESS runnable, leave it stopped.
2277 		 * It may run a bit until it hits a thread_suspend_check().
2278 		 */
2279 		wakeup_swapper = 0;
2280 		PROC_SLOCK(p);
2281 		thread_lock(td);
2282 		if (TD_ON_SLEEPQ(td) && (td->td_flags & TDF_SINTR))
2283 			wakeup_swapper = sleepq_abort(td, intrval);
2284 		thread_unlock(td);
2285 		PROC_SUNLOCK(p);
2286 		if (wakeup_swapper)
2287 			kick_proc0();
2288 		goto out;
2289 		/*
2290 		 * Mutexes are short lived. Threads waiting on them will
2291 		 * hit thread_suspend_check() soon.
2292 		 */
2293 	} else if (p->p_state == PRS_NORMAL) {
2294 		if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2295 			tdsigwakeup(td, sig, action, intrval);
2296 			goto out;
2297 		}
2298 
2299 		MPASS(action == SIG_DFL);
2300 
2301 		if (prop & SA_STOP) {
2302 			if (p->p_flag & (P_PPWAIT|P_WEXIT))
2303 				goto out;
2304 			p->p_flag |= P_STOPPED_SIG;
2305 			p->p_xstat = sig;
2306 			PROC_SLOCK(p);
2307 			sig_suspend_threads(td, p, 1);
2308 			if (p->p_numthreads == p->p_suspcount) {
2309 				/*
2310 				 * only thread sending signal to another
2311 				 * process can reach here, if thread is sending
2312 				 * signal to its process, because thread does
2313 				 * not suspend itself here, p_numthreads
2314 				 * should never be equal to p_suspcount.
2315 				 */
2316 				thread_stopped(p);
2317 				PROC_SUNLOCK(p);
2318 				sigqueue_delete_proc(p, p->p_xstat);
2319 			} else
2320 				PROC_SUNLOCK(p);
2321 			goto out;
2322 		}
2323 	} else {
2324 		/* Not in "NORMAL" state. discard the signal. */
2325 		sigqueue_delete(sigqueue, sig);
2326 		goto out;
2327 	}
2328 
2329 	/*
2330 	 * The process is not stopped so we need to apply the signal to all the
2331 	 * running threads.
2332 	 */
2333 runfast:
2334 	tdsigwakeup(td, sig, action, intrval);
2335 	PROC_SLOCK(p);
2336 	thread_unsuspend(p);
2337 	PROC_SUNLOCK(p);
2338 out:
2339 	/* If we jump here, proc slock should not be owned. */
2340 	PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2341 	return (ret);
2342 }
2343 
2344 /*
2345  * The force of a signal has been directed against a single
2346  * thread.  We need to see what we can do about knocking it
2347  * out of any sleep it may be in etc.
2348  */
2349 static void
2350 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2351 {
2352 	struct proc *p = td->td_proc;
2353 	register int prop;
2354 	int wakeup_swapper;
2355 
2356 	wakeup_swapper = 0;
2357 	PROC_LOCK_ASSERT(p, MA_OWNED);
2358 	prop = sigprop(sig);
2359 
2360 	PROC_SLOCK(p);
2361 	thread_lock(td);
2362 	/*
2363 	 * Bring the priority of a thread up if we want it to get
2364 	 * killed in this lifetime.
2365 	 */
2366 	if (action == SIG_DFL && (prop & SA_KILL) && td->td_priority > PUSER)
2367 		sched_prio(td, PUSER);
2368 	if (TD_ON_SLEEPQ(td)) {
2369 		/*
2370 		 * If thread is sleeping uninterruptibly
2371 		 * we can't interrupt the sleep... the signal will
2372 		 * be noticed when the process returns through
2373 		 * trap() or syscall().
2374 		 */
2375 		if ((td->td_flags & TDF_SINTR) == 0)
2376 			goto out;
2377 		/*
2378 		 * If SIGCONT is default (or ignored) and process is
2379 		 * asleep, we are finished; the process should not
2380 		 * be awakened.
2381 		 */
2382 		if ((prop & SA_CONT) && action == SIG_DFL) {
2383 			thread_unlock(td);
2384 			PROC_SUNLOCK(p);
2385 			sigqueue_delete(&p->p_sigqueue, sig);
2386 			/*
2387 			 * It may be on either list in this state.
2388 			 * Remove from both for now.
2389 			 */
2390 			sigqueue_delete(&td->td_sigqueue, sig);
2391 			return;
2392 		}
2393 
2394 		/*
2395 		 * Don't awaken a sleeping thread for SIGSTOP if the
2396 		 * STOP signal is deferred.
2397 		 */
2398 		if ((prop & SA_STOP) && (td->td_flags & TDF_SBDRY))
2399 			goto out;
2400 
2401 		/*
2402 		 * Give low priority threads a better chance to run.
2403 		 */
2404 		if (td->td_priority > PUSER)
2405 			sched_prio(td, PUSER);
2406 
2407 		wakeup_swapper = sleepq_abort(td, intrval);
2408 	} else {
2409 		/*
2410 		 * Other states do nothing with the signal immediately,
2411 		 * other than kicking ourselves if we are running.
2412 		 * It will either never be noticed, or noticed very soon.
2413 		 */
2414 #ifdef SMP
2415 		if (TD_IS_RUNNING(td) && td != curthread)
2416 			forward_signal(td);
2417 #endif
2418 	}
2419 out:
2420 	PROC_SUNLOCK(p);
2421 	thread_unlock(td);
2422 	if (wakeup_swapper)
2423 		kick_proc0();
2424 }
2425 
2426 static void
2427 sig_suspend_threads(struct thread *td, struct proc *p, int sending)
2428 {
2429 	struct thread *td2;
2430 
2431 	PROC_LOCK_ASSERT(p, MA_OWNED);
2432 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2433 
2434 	FOREACH_THREAD_IN_PROC(p, td2) {
2435 		thread_lock(td2);
2436 		td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
2437 		if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2438 		    (td2->td_flags & TDF_SINTR)) {
2439 			if (td2->td_flags & TDF_SBDRY) {
2440 				/*
2441 				 * Once a thread is asleep with
2442 				 * TDF_SBDRY set, it should never
2443 				 * become suspended due to this check.
2444 				 */
2445 				KASSERT(!TD_IS_SUSPENDED(td2),
2446 				    ("thread with deferred stops suspended"));
2447 			} else if (!TD_IS_SUSPENDED(td2)) {
2448 				thread_suspend_one(td2);
2449 			}
2450 		} else if (!TD_IS_SUSPENDED(td2)) {
2451 			if (sending || td != td2)
2452 				td2->td_flags |= TDF_ASTPENDING;
2453 #ifdef SMP
2454 			if (TD_IS_RUNNING(td2) && td2 != td)
2455 				forward_signal(td2);
2456 #endif
2457 		}
2458 		thread_unlock(td2);
2459 	}
2460 }
2461 
2462 int
2463 ptracestop(struct thread *td, int sig)
2464 {
2465 	struct proc *p = td->td_proc;
2466 
2467 	PROC_LOCK_ASSERT(p, MA_OWNED);
2468 	KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2469 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2470 	    &p->p_mtx.lock_object, "Stopping for traced signal");
2471 
2472 	td->td_dbgflags |= TDB_XSIG;
2473 	td->td_xsig = sig;
2474 	PROC_SLOCK(p);
2475 	while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2476 		if (p->p_flag & P_SINGLE_EXIT) {
2477 			td->td_dbgflags &= ~TDB_XSIG;
2478 			PROC_SUNLOCK(p);
2479 			return (sig);
2480 		}
2481 		/*
2482 		 * Just make wait() to work, the last stopped thread
2483 		 * will win.
2484 		 */
2485 		p->p_xstat = sig;
2486 		p->p_xthread = td;
2487 		p->p_flag |= (P_STOPPED_SIG|P_STOPPED_TRACE);
2488 		sig_suspend_threads(td, p, 0);
2489 		if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2490 			td->td_dbgflags &= ~TDB_STOPATFORK;
2491 			cv_broadcast(&p->p_dbgwait);
2492 		}
2493 stopme:
2494 		thread_suspend_switch(td, p);
2495 		if (p->p_xthread == td)
2496 			p->p_xthread = NULL;
2497 		if (!(p->p_flag & P_TRACED))
2498 			break;
2499 		if (td->td_dbgflags & TDB_SUSPEND) {
2500 			if (p->p_flag & P_SINGLE_EXIT)
2501 				break;
2502 			goto stopme;
2503 		}
2504 	}
2505 	PROC_SUNLOCK(p);
2506 	return (td->td_xsig);
2507 }
2508 
2509 static void
2510 reschedule_signals(struct proc *p, sigset_t block, int flags)
2511 {
2512 	struct sigacts *ps;
2513 	struct thread *td;
2514 	int sig;
2515 
2516 	PROC_LOCK_ASSERT(p, MA_OWNED);
2517 	ps = p->p_sigacts;
2518 	mtx_assert(&ps->ps_mtx, (flags & SIGPROCMASK_PS_LOCKED) != 0 ?
2519 	    MA_OWNED : MA_NOTOWNED);
2520 	if (SIGISEMPTY(p->p_siglist))
2521 		return;
2522 	SIGSETAND(block, p->p_siglist);
2523 	while ((sig = sig_ffs(&block)) != 0) {
2524 		SIGDELSET(block, sig);
2525 		td = sigtd(p, sig, 0);
2526 		signotify(td);
2527 		if (!(flags & SIGPROCMASK_PS_LOCKED))
2528 			mtx_lock(&ps->ps_mtx);
2529 		if (p->p_flag & P_TRACED || SIGISMEMBER(ps->ps_sigcatch, sig))
2530 			tdsigwakeup(td, sig, SIG_CATCH,
2531 			    (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2532 			     ERESTART));
2533 		if (!(flags & SIGPROCMASK_PS_LOCKED))
2534 			mtx_unlock(&ps->ps_mtx);
2535 	}
2536 }
2537 
2538 void
2539 tdsigcleanup(struct thread *td)
2540 {
2541 	struct proc *p;
2542 	sigset_t unblocked;
2543 
2544 	p = td->td_proc;
2545 	PROC_LOCK_ASSERT(p, MA_OWNED);
2546 
2547 	sigqueue_flush(&td->td_sigqueue);
2548 	if (p->p_numthreads == 1)
2549 		return;
2550 
2551 	/*
2552 	 * Since we cannot handle signals, notify signal post code
2553 	 * about this by filling the sigmask.
2554 	 *
2555 	 * Also, if needed, wake up thread(s) that do not block the
2556 	 * same signals as the exiting thread, since the thread might
2557 	 * have been selected for delivery and woken up.
2558 	 */
2559 	SIGFILLSET(unblocked);
2560 	SIGSETNAND(unblocked, td->td_sigmask);
2561 	SIGFILLSET(td->td_sigmask);
2562 	reschedule_signals(p, unblocked, 0);
2563 
2564 }
2565 
2566 /*
2567  * Defer the delivery of SIGSTOP for the current thread.  Returns true
2568  * if stops were deferred and false if they were already deferred.
2569  */
2570 int
2571 sigdeferstop(void)
2572 {
2573 	struct thread *td;
2574 
2575 	td = curthread;
2576 	if (td->td_flags & TDF_SBDRY)
2577 		return (0);
2578 	thread_lock(td);
2579 	td->td_flags |= TDF_SBDRY;
2580 	thread_unlock(td);
2581 	return (1);
2582 }
2583 
2584 /*
2585  * Permit the delivery of SIGSTOP for the current thread.  This does
2586  * not immediately suspend if a stop was posted.  Instead, the thread
2587  * will suspend either via ast() or a subsequent interruptible sleep.
2588  */
2589 void
2590 sigallowstop()
2591 {
2592 	struct thread *td;
2593 
2594 	td = curthread;
2595 	thread_lock(td);
2596 	td->td_flags &= ~TDF_SBDRY;
2597 	thread_unlock(td);
2598 }
2599 
2600 /*
2601  * If the current process has received a signal (should be caught or cause
2602  * termination, should interrupt current syscall), return the signal number.
2603  * Stop signals with default action are processed immediately, then cleared;
2604  * they aren't returned.  This is checked after each entry to the system for
2605  * a syscall or trap (though this can usually be done without calling issignal
2606  * by checking the pending signal masks in cursig.) The normal call
2607  * sequence is
2608  *
2609  *	while (sig = cursig(curthread))
2610  *		postsig(sig);
2611  */
2612 static int
2613 issignal(struct thread *td)
2614 {
2615 	struct proc *p;
2616 	struct sigacts *ps;
2617 	struct sigqueue *queue;
2618 	sigset_t sigpending;
2619 	int sig, prop, newsig;
2620 
2621 	p = td->td_proc;
2622 	ps = p->p_sigacts;
2623 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2624 	PROC_LOCK_ASSERT(p, MA_OWNED);
2625 	for (;;) {
2626 		int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
2627 
2628 		sigpending = td->td_sigqueue.sq_signals;
2629 		SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
2630 		SIGSETNAND(sigpending, td->td_sigmask);
2631 
2632 		if (p->p_flag & P_PPWAIT || td->td_flags & TDF_SBDRY)
2633 			SIG_STOPSIGMASK(sigpending);
2634 		if (SIGISEMPTY(sigpending))	/* no signal to send */
2635 			return (0);
2636 		sig = sig_ffs(&sigpending);
2637 
2638 		if (p->p_stops & S_SIG) {
2639 			mtx_unlock(&ps->ps_mtx);
2640 			stopevent(p, S_SIG, sig);
2641 			mtx_lock(&ps->ps_mtx);
2642 		}
2643 
2644 		/*
2645 		 * We should see pending but ignored signals
2646 		 * only if P_TRACED was on when they were posted.
2647 		 */
2648 		if (SIGISMEMBER(ps->ps_sigignore, sig) && (traced == 0)) {
2649 			sigqueue_delete(&td->td_sigqueue, sig);
2650 			sigqueue_delete(&p->p_sigqueue, sig);
2651 			continue;
2652 		}
2653 		if (p->p_flag & P_TRACED && (p->p_flag & P_PPTRACE) == 0) {
2654 			/*
2655 			 * If traced, always stop.
2656 			 * Remove old signal from queue before the stop.
2657 			 * XXX shrug off debugger, it causes siginfo to
2658 			 * be thrown away.
2659 			 */
2660 			queue = &td->td_sigqueue;
2661 			td->td_dbgksi.ksi_signo = 0;
2662 			if (sigqueue_get(queue, sig, &td->td_dbgksi) == 0) {
2663 				queue = &p->p_sigqueue;
2664 				sigqueue_get(queue, sig, &td->td_dbgksi);
2665 			}
2666 
2667 			mtx_unlock(&ps->ps_mtx);
2668 			newsig = ptracestop(td, sig);
2669 			mtx_lock(&ps->ps_mtx);
2670 
2671 			if (sig != newsig) {
2672 
2673 				/*
2674 				 * If parent wants us to take the signal,
2675 				 * then it will leave it in p->p_xstat;
2676 				 * otherwise we just look for signals again.
2677 				*/
2678 				if (newsig == 0)
2679 					continue;
2680 				sig = newsig;
2681 
2682 				/*
2683 				 * Put the new signal into td_sigqueue. If the
2684 				 * signal is being masked, look for other
2685 				 * signals.
2686 				 */
2687 				sigqueue_add(queue, sig, NULL);
2688 				if (SIGISMEMBER(td->td_sigmask, sig))
2689 					continue;
2690 				signotify(td);
2691 			} else {
2692 				if (td->td_dbgksi.ksi_signo != 0) {
2693 					td->td_dbgksi.ksi_flags |= KSI_HEAD;
2694 					if (sigqueue_add(&td->td_sigqueue, sig,
2695 					    &td->td_dbgksi) != 0)
2696 						td->td_dbgksi.ksi_signo = 0;
2697 				}
2698 				if (td->td_dbgksi.ksi_signo == 0)
2699 					sigqueue_add(&td->td_sigqueue, sig,
2700 					    NULL);
2701 			}
2702 
2703 			/*
2704 			 * If the traced bit got turned off, go back up
2705 			 * to the top to rescan signals.  This ensures
2706 			 * that p_sig* and p_sigact are consistent.
2707 			 */
2708 			if ((p->p_flag & P_TRACED) == 0)
2709 				continue;
2710 		}
2711 
2712 		prop = sigprop(sig);
2713 
2714 		/*
2715 		 * Decide whether the signal should be returned.
2716 		 * Return the signal's number, or fall through
2717 		 * to clear it from the pending mask.
2718 		 */
2719 		switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
2720 
2721 		case (intptr_t)SIG_DFL:
2722 			/*
2723 			 * Don't take default actions on system processes.
2724 			 */
2725 			if (p->p_pid <= 1) {
2726 #ifdef DIAGNOSTIC
2727 				/*
2728 				 * Are you sure you want to ignore SIGSEGV
2729 				 * in init? XXX
2730 				 */
2731 				printf("Process (pid %lu) got signal %d\n",
2732 					(u_long)p->p_pid, sig);
2733 #endif
2734 				break;		/* == ignore */
2735 			}
2736 			/*
2737 			 * If there is a pending stop signal to process
2738 			 * with default action, stop here,
2739 			 * then clear the signal.  However,
2740 			 * if process is member of an orphaned
2741 			 * process group, ignore tty stop signals.
2742 			 */
2743 			if (prop & SA_STOP) {
2744 				if (p->p_flag & (P_TRACED|P_WEXIT) ||
2745 				    (p->p_pgrp->pg_jobc == 0 &&
2746 				     prop & SA_TTYSTOP))
2747 					break;	/* == ignore */
2748 				mtx_unlock(&ps->ps_mtx);
2749 				WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2750 				    &p->p_mtx.lock_object, "Catching SIGSTOP");
2751 				p->p_flag |= P_STOPPED_SIG;
2752 				p->p_xstat = sig;
2753 				PROC_SLOCK(p);
2754 				sig_suspend_threads(td, p, 0);
2755 				thread_suspend_switch(td, p);
2756 				PROC_SUNLOCK(p);
2757 				mtx_lock(&ps->ps_mtx);
2758 				break;
2759 			} else if (prop & SA_IGNORE) {
2760 				/*
2761 				 * Except for SIGCONT, shouldn't get here.
2762 				 * Default action is to ignore; drop it.
2763 				 */
2764 				break;		/* == ignore */
2765 			} else
2766 				return (sig);
2767 			/*NOTREACHED*/
2768 
2769 		case (intptr_t)SIG_IGN:
2770 			/*
2771 			 * Masking above should prevent us ever trying
2772 			 * to take action on an ignored signal other
2773 			 * than SIGCONT, unless process is traced.
2774 			 */
2775 			if ((prop & SA_CONT) == 0 &&
2776 			    (p->p_flag & P_TRACED) == 0)
2777 				printf("issignal\n");
2778 			break;		/* == ignore */
2779 
2780 		default:
2781 			/*
2782 			 * This signal has an action, let
2783 			 * postsig() process it.
2784 			 */
2785 			return (sig);
2786 		}
2787 		sigqueue_delete(&td->td_sigqueue, sig);	/* take the signal! */
2788 		sigqueue_delete(&p->p_sigqueue, sig);
2789 	}
2790 	/* NOTREACHED */
2791 }
2792 
2793 void
2794 thread_stopped(struct proc *p)
2795 {
2796 	int n;
2797 
2798 	PROC_LOCK_ASSERT(p, MA_OWNED);
2799 	PROC_SLOCK_ASSERT(p, MA_OWNED);
2800 	n = p->p_suspcount;
2801 	if (p == curproc)
2802 		n++;
2803 	if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
2804 		PROC_SUNLOCK(p);
2805 		p->p_flag &= ~P_WAITED;
2806 		PROC_LOCK(p->p_pptr);
2807 		childproc_stopped(p, (p->p_flag & P_TRACED) ?
2808 			CLD_TRAPPED : CLD_STOPPED);
2809 		PROC_UNLOCK(p->p_pptr);
2810 		PROC_SLOCK(p);
2811 	}
2812 }
2813 
2814 /*
2815  * Take the action for the specified signal
2816  * from the current set of pending signals.
2817  */
2818 int
2819 postsig(sig)
2820 	register int sig;
2821 {
2822 	struct thread *td = curthread;
2823 	register struct proc *p = td->td_proc;
2824 	struct sigacts *ps;
2825 	sig_t action;
2826 	ksiginfo_t ksi;
2827 	sigset_t returnmask;
2828 
2829 	KASSERT(sig != 0, ("postsig"));
2830 
2831 	PROC_LOCK_ASSERT(p, MA_OWNED);
2832 	ps = p->p_sigacts;
2833 	mtx_assert(&ps->ps_mtx, MA_OWNED);
2834 	ksiginfo_init(&ksi);
2835 	if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
2836 	    sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
2837 		return (0);
2838 	ksi.ksi_signo = sig;
2839 	if (ksi.ksi_code == SI_TIMER)
2840 		itimer_accept(p, ksi.ksi_timerid, &ksi);
2841 	action = ps->ps_sigact[_SIG_IDX(sig)];
2842 #ifdef KTRACE
2843 	if (KTRPOINT(td, KTR_PSIG))
2844 		ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
2845 		    &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
2846 #endif
2847 	if (p->p_stops & S_SIG) {
2848 		mtx_unlock(&ps->ps_mtx);
2849 		stopevent(p, S_SIG, sig);
2850 		mtx_lock(&ps->ps_mtx);
2851 	}
2852 
2853 	if (action == SIG_DFL) {
2854 		/*
2855 		 * Default action, where the default is to kill
2856 		 * the process.  (Other cases were ignored above.)
2857 		 */
2858 		mtx_unlock(&ps->ps_mtx);
2859 		sigexit(td, sig);
2860 		/* NOTREACHED */
2861 	} else {
2862 		/*
2863 		 * If we get here, the signal must be caught.
2864 		 */
2865 		KASSERT(action != SIG_IGN && !SIGISMEMBER(td->td_sigmask, sig),
2866 		    ("postsig action"));
2867 		/*
2868 		 * Set the new mask value and also defer further
2869 		 * occurrences of this signal.
2870 		 *
2871 		 * Special case: user has done a sigsuspend.  Here the
2872 		 * current mask is not of interest, but rather the
2873 		 * mask from before the sigsuspend is what we want
2874 		 * restored after the signal processing is completed.
2875 		 */
2876 		if (td->td_pflags & TDP_OLDMASK) {
2877 			returnmask = td->td_oldsigmask;
2878 			td->td_pflags &= ~TDP_OLDMASK;
2879 		} else
2880 			returnmask = td->td_sigmask;
2881 
2882 		if (p->p_sig == sig) {
2883 			p->p_code = 0;
2884 			p->p_sig = 0;
2885 		}
2886 		(*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
2887 		postsig_done(sig, td, ps);
2888 	}
2889 	return (1);
2890 }
2891 
2892 /*
2893  * Kill the current process for stated reason.
2894  */
2895 void
2896 killproc(p, why)
2897 	struct proc *p;
2898 	char *why;
2899 {
2900 
2901 	PROC_LOCK_ASSERT(p, MA_OWNED);
2902 	CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
2903 	    p->p_comm);
2904 	log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n", p->p_pid,
2905 	    p->p_comm, p->p_ucred ? p->p_ucred->cr_uid : -1, why);
2906 	p->p_flag |= P_WKILLED;
2907 	kern_psignal(p, SIGKILL);
2908 }
2909 
2910 /*
2911  * Force the current process to exit with the specified signal, dumping core
2912  * if appropriate.  We bypass the normal tests for masked and caught signals,
2913  * allowing unrecoverable failures to terminate the process without changing
2914  * signal state.  Mark the accounting record with the signal termination.
2915  * If dumping core, save the signal number for the debugger.  Calls exit and
2916  * does not return.
2917  */
2918 void
2919 sigexit(td, sig)
2920 	struct thread *td;
2921 	int sig;
2922 {
2923 	struct proc *p = td->td_proc;
2924 
2925 	PROC_LOCK_ASSERT(p, MA_OWNED);
2926 	p->p_acflag |= AXSIG;
2927 	/*
2928 	 * We must be single-threading to generate a core dump.  This
2929 	 * ensures that the registers in the core file are up-to-date.
2930 	 * Also, the ELF dump handler assumes that the thread list doesn't
2931 	 * change out from under it.
2932 	 *
2933 	 * XXX If another thread attempts to single-thread before us
2934 	 *     (e.g. via fork()), we won't get a dump at all.
2935 	 */
2936 	if ((sigprop(sig) & SA_CORE) && thread_single(p, SINGLE_NO_EXIT) == 0) {
2937 		p->p_sig = sig;
2938 		/*
2939 		 * Log signals which would cause core dumps
2940 		 * (Log as LOG_INFO to appease those who don't want
2941 		 * these messages.)
2942 		 * XXX : Todo, as well as euid, write out ruid too
2943 		 * Note that coredump() drops proc lock.
2944 		 */
2945 		if (coredump(td) == 0)
2946 			sig |= WCOREFLAG;
2947 		if (kern_logsigexit)
2948 			log(LOG_INFO,
2949 			    "pid %d (%s), uid %d: exited on signal %d%s\n",
2950 			    p->p_pid, p->p_comm,
2951 			    td->td_ucred ? td->td_ucred->cr_uid : -1,
2952 			    sig &~ WCOREFLAG,
2953 			    sig & WCOREFLAG ? " (core dumped)" : "");
2954 	} else
2955 		PROC_UNLOCK(p);
2956 	exit1(td, W_EXITCODE(0, sig));
2957 	/* NOTREACHED */
2958 }
2959 
2960 /*
2961  * Send queued SIGCHLD to parent when child process's state
2962  * is changed.
2963  */
2964 static void
2965 sigparent(struct proc *p, int reason, int status)
2966 {
2967 	PROC_LOCK_ASSERT(p, MA_OWNED);
2968 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2969 
2970 	if (p->p_ksi != NULL) {
2971 		p->p_ksi->ksi_signo  = SIGCHLD;
2972 		p->p_ksi->ksi_code   = reason;
2973 		p->p_ksi->ksi_status = status;
2974 		p->p_ksi->ksi_pid    = p->p_pid;
2975 		p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
2976 		if (KSI_ONQ(p->p_ksi))
2977 			return;
2978 	}
2979 	pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
2980 }
2981 
2982 static void
2983 childproc_jobstate(struct proc *p, int reason, int sig)
2984 {
2985 	struct sigacts *ps;
2986 
2987 	PROC_LOCK_ASSERT(p, MA_OWNED);
2988 	PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
2989 
2990 	/*
2991 	 * Wake up parent sleeping in kern_wait(), also send
2992 	 * SIGCHLD to parent, but SIGCHLD does not guarantee
2993 	 * that parent will awake, because parent may masked
2994 	 * the signal.
2995 	 */
2996 	p->p_pptr->p_flag |= P_STATCHILD;
2997 	wakeup(p->p_pptr);
2998 
2999 	ps = p->p_pptr->p_sigacts;
3000 	mtx_lock(&ps->ps_mtx);
3001 	if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
3002 		mtx_unlock(&ps->ps_mtx);
3003 		sigparent(p, reason, sig);
3004 	} else
3005 		mtx_unlock(&ps->ps_mtx);
3006 }
3007 
3008 void
3009 childproc_stopped(struct proc *p, int reason)
3010 {
3011 	/* p_xstat is a plain signal number, not a full wait() status here. */
3012 	childproc_jobstate(p, reason, p->p_xstat);
3013 }
3014 
3015 void
3016 childproc_continued(struct proc *p)
3017 {
3018 	childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
3019 }
3020 
3021 void
3022 childproc_exited(struct proc *p)
3023 {
3024 	int reason;
3025 	int xstat = p->p_xstat; /* convert to int */
3026 	int status;
3027 
3028 	if (WCOREDUMP(xstat))
3029 		reason = CLD_DUMPED, status = WTERMSIG(xstat);
3030 	else if (WIFSIGNALED(xstat))
3031 		reason = CLD_KILLED, status = WTERMSIG(xstat);
3032 	else
3033 		reason = CLD_EXITED, status = WEXITSTATUS(xstat);
3034 	/*
3035 	 * XXX avoid calling wakeup(p->p_pptr), the work is
3036 	 * done in exit1().
3037 	 */
3038 	sigparent(p, reason, status);
3039 }
3040 
3041 /*
3042  * We only have 1 character for the core count in the format
3043  * string, so the range will be 0-9
3044  */
3045 #define MAX_NUM_CORES 10
3046 static int num_cores = 5;
3047 
3048 static int
3049 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3050 {
3051 	int error;
3052 	int new_val;
3053 
3054 	new_val = num_cores;
3055 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3056 	if (error != 0 || req->newptr == NULL)
3057 		return (error);
3058 	if (new_val > MAX_NUM_CORES)
3059 		new_val = MAX_NUM_CORES;
3060 	if (new_val < 0)
3061 		new_val = 0;
3062 	num_cores = new_val;
3063 	return (0);
3064 }
3065 SYSCTL_PROC(_debug, OID_AUTO, ncores, CTLTYPE_INT|CTLFLAG_RW,
3066 	    0, sizeof(int), sysctl_debug_num_cores_check, "I", "");
3067 
3068 #if defined(COMPRESS_USER_CORES)
3069 int compress_user_cores = 1;
3070 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores, CTLFLAG_RW,
3071     &compress_user_cores, 0, "Compression of user corefiles");
3072 
3073 int compress_user_cores_gzlevel = -1; /* default level */
3074 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_gzlevel, CTLFLAG_RW,
3075     &compress_user_cores_gzlevel, -1, "Corefile gzip compression level");
3076 
3077 #define GZ_SUFFIX	".gz"
3078 #define GZ_SUFFIX_LEN	3
3079 #endif
3080 
3081 static char corefilename[MAXPATHLEN] = {"%N.core"};
3082 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RWTUN, corefilename,
3083     sizeof(corefilename), "Process corefile name format string");
3084 
3085 /*
3086  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3087  * Expand the name described in corefilename, using name, uid, and pid
3088  * and open/create core file.
3089  * corefilename is a printf-like string, with three format specifiers:
3090  *	%N	name of process ("name")
3091  *	%P	process id (pid)
3092  *	%U	user id (uid)
3093  * For example, "%N.core" is the default; they can be disabled completely
3094  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3095  * This is controlled by the sysctl variable kern.corefile (see above).
3096  */
3097 static int
3098 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3099     int compress, struct vnode **vpp, char **namep)
3100 {
3101 	struct nameidata nd;
3102 	struct sbuf sb;
3103 	const char *format;
3104 	char *hostname, *name;
3105 	int indexpos, i, error, cmode, flags, oflags;
3106 
3107 	hostname = NULL;
3108 	format = corefilename;
3109 	name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3110 	indexpos = -1;
3111 	(void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3112 	for (i = 0; format[i] != '\0'; i++) {
3113 		switch (format[i]) {
3114 		case '%':	/* Format character */
3115 			i++;
3116 			switch (format[i]) {
3117 			case '%':
3118 				sbuf_putc(&sb, '%');
3119 				break;
3120 			case 'H':	/* hostname */
3121 				if (hostname == NULL) {
3122 					hostname = malloc(MAXHOSTNAMELEN,
3123 					    M_TEMP, M_WAITOK);
3124 				}
3125 				getcredhostname(td->td_ucred, hostname,
3126 				    MAXHOSTNAMELEN);
3127 				sbuf_printf(&sb, "%s", hostname);
3128 				break;
3129 			case 'I':	/* autoincrementing index */
3130 				sbuf_printf(&sb, "0");
3131 				indexpos = sbuf_len(&sb) - 1;
3132 				break;
3133 			case 'N':	/* process name */
3134 				sbuf_printf(&sb, "%s", comm);
3135 				break;
3136 			case 'P':	/* process id */
3137 				sbuf_printf(&sb, "%u", pid);
3138 				break;
3139 			case 'U':	/* user id */
3140 				sbuf_printf(&sb, "%u", uid);
3141 				break;
3142 			default:
3143 				log(LOG_ERR,
3144 				    "Unknown format character %c in "
3145 				    "corename `%s'\n", format[i], format);
3146 				break;
3147 			}
3148 			break;
3149 		default:
3150 			sbuf_putc(&sb, format[i]);
3151 			break;
3152 		}
3153 	}
3154 	free(hostname, M_TEMP);
3155 #ifdef COMPRESS_USER_CORES
3156 	if (compress)
3157 		sbuf_printf(&sb, GZ_SUFFIX);
3158 #endif
3159 	if (sbuf_error(&sb) != 0) {
3160 		log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
3161 		    "long\n", (long)pid, comm, (u_long)uid);
3162 		sbuf_delete(&sb);
3163 		free(name, M_TEMP);
3164 		return (ENOMEM);
3165 	}
3166 	sbuf_finish(&sb);
3167 	sbuf_delete(&sb);
3168 
3169 	cmode = S_IRUSR | S_IWUSR;
3170 	oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3171 	    (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3172 
3173 	/*
3174 	 * If the core format has a %I in it, then we need to check
3175 	 * for existing corefiles before returning a name.
3176 	 * To do this we iterate over 0..num_cores to find a
3177 	 * non-existing core file name to use.
3178 	 */
3179 	if (indexpos != -1) {
3180 		for (i = 0; i < num_cores; i++) {
3181 			flags = O_CREAT | O_EXCL | FWRITE | O_NOFOLLOW;
3182 			name[indexpos] = '0' + i;
3183 			NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3184 			error = vn_open_cred(&nd, &flags, cmode, oflags,
3185 			    td->td_ucred, NULL);
3186 			if (error) {
3187 				if (error == EEXIST)
3188 					continue;
3189 				log(LOG_ERR,
3190 				    "pid %d (%s), uid (%u):  Path `%s' failed "
3191 				    "on initial open test, error = %d\n",
3192 				    pid, comm, uid, name, error);
3193 			}
3194 			goto out;
3195 		}
3196 	}
3197 
3198 	flags = O_CREAT | FWRITE | O_NOFOLLOW;
3199 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3200 	error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred, NULL);
3201 out:
3202 	if (error) {
3203 #ifdef AUDIT
3204 		audit_proc_coredump(td, name, error);
3205 #endif
3206 		free(name, M_TEMP);
3207 		return (error);
3208 	}
3209 	NDFREE(&nd, NDF_ONLY_PNBUF);
3210 	*vpp = nd.ni_vp;
3211 	*namep = name;
3212 	return (0);
3213 }
3214 
3215 /*
3216  * Dump a process' core.  The main routine does some
3217  * policy checking, and creates the name of the coredump;
3218  * then it passes on a vnode and a size limit to the process-specific
3219  * coredump routine if there is one; if there _is not_ one, it returns
3220  * ENOSYS; otherwise it returns the error from the process-specific routine.
3221  */
3222 
3223 static int
3224 coredump(struct thread *td)
3225 {
3226 	struct proc *p = td->td_proc;
3227 	struct ucred *cred = td->td_ucred;
3228 	struct vnode *vp;
3229 	struct flock lf;
3230 	struct vattr vattr;
3231 	int error, error1, locked;
3232 	char *name;			/* name of corefile */
3233 	void *rl_cookie;
3234 	off_t limit;
3235 	int compress;
3236 
3237 #ifdef COMPRESS_USER_CORES
3238 	compress = compress_user_cores;
3239 #else
3240 	compress = 0;
3241 #endif
3242 	PROC_LOCK_ASSERT(p, MA_OWNED);
3243 	MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
3244 	_STOPEVENT(p, S_CORE, 0);
3245 
3246 	if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0)) {
3247 		PROC_UNLOCK(p);
3248 		return (EFAULT);
3249 	}
3250 
3251 	/*
3252 	 * Note that the bulk of limit checking is done after
3253 	 * the corefile is created.  The exception is if the limit
3254 	 * for corefiles is 0, in which case we don't bother
3255 	 * creating the corefile at all.  This layout means that
3256 	 * a corefile is truncated instead of not being created,
3257 	 * if it is larger than the limit.
3258 	 */
3259 	limit = (off_t)lim_cur(p, RLIMIT_CORE);
3260 	if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
3261 		PROC_UNLOCK(p);
3262 		return (EFBIG);
3263 	}
3264 	PROC_UNLOCK(p);
3265 
3266 	error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td, compress,
3267 	    &vp, &name);
3268 	if (error != 0)
3269 		return (error);
3270 
3271 	/*
3272 	 * Don't dump to non-regular files or files with links.
3273 	 * Do not dump into system files.
3274 	 */
3275 	if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
3276 	    vattr.va_nlink != 1 || (vp->v_vflag & VV_SYSTEM) != 0) {
3277 		VOP_UNLOCK(vp, 0);
3278 		error = EFAULT;
3279 		goto close;
3280 	}
3281 
3282 	VOP_UNLOCK(vp, 0);
3283 
3284 	/* Postpone other writers, including core dumps of other processes. */
3285 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3286 
3287 	lf.l_whence = SEEK_SET;
3288 	lf.l_start = 0;
3289 	lf.l_len = 0;
3290 	lf.l_type = F_WRLCK;
3291 	locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
3292 
3293 	VATTR_NULL(&vattr);
3294 	vattr.va_size = 0;
3295 	if (set_core_nodump_flag)
3296 		vattr.va_flags = UF_NODUMP;
3297 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3298 	VOP_SETATTR(vp, &vattr, cred);
3299 	VOP_UNLOCK(vp, 0);
3300 	PROC_LOCK(p);
3301 	p->p_acflag |= ACORE;
3302 	PROC_UNLOCK(p);
3303 
3304 	if (p->p_sysent->sv_coredump != NULL) {
3305 		error = p->p_sysent->sv_coredump(td, vp, limit,
3306 		    compress ? IMGACT_CORE_COMPRESS : 0);
3307 	} else {
3308 		error = ENOSYS;
3309 	}
3310 
3311 	if (locked) {
3312 		lf.l_type = F_UNLCK;
3313 		VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3314 	}
3315 	vn_rangelock_unlock(vp, rl_cookie);
3316 close:
3317 	error1 = vn_close(vp, FWRITE, cred, td);
3318 	if (error == 0)
3319 		error = error1;
3320 #ifdef AUDIT
3321 	audit_proc_coredump(td, name, error);
3322 #endif
3323 	free(name, M_TEMP);
3324 	return (error);
3325 }
3326 
3327 /*
3328  * Nonexistent system call-- signal process (may want to handle it).  Flag
3329  * error in case process won't see signal immediately (blocked or ignored).
3330  */
3331 #ifndef _SYS_SYSPROTO_H_
3332 struct nosys_args {
3333 	int	dummy;
3334 };
3335 #endif
3336 /* ARGSUSED */
3337 int
3338 nosys(td, args)
3339 	struct thread *td;
3340 	struct nosys_args *args;
3341 {
3342 	struct proc *p = td->td_proc;
3343 
3344 	PROC_LOCK(p);
3345 	tdsignal(td, SIGSYS);
3346 	PROC_UNLOCK(p);
3347 	return (ENOSYS);
3348 }
3349 
3350 /*
3351  * Send a SIGIO or SIGURG signal to a process or process group using stored
3352  * credentials rather than those of the current process.
3353  */
3354 void
3355 pgsigio(sigiop, sig, checkctty)
3356 	struct sigio **sigiop;
3357 	int sig, checkctty;
3358 {
3359 	ksiginfo_t ksi;
3360 	struct sigio *sigio;
3361 
3362 	ksiginfo_init(&ksi);
3363 	ksi.ksi_signo = sig;
3364 	ksi.ksi_code = SI_KERNEL;
3365 
3366 	SIGIO_LOCK();
3367 	sigio = *sigiop;
3368 	if (sigio == NULL) {
3369 		SIGIO_UNLOCK();
3370 		return;
3371 	}
3372 	if (sigio->sio_pgid > 0) {
3373 		PROC_LOCK(sigio->sio_proc);
3374 		if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
3375 			kern_psignal(sigio->sio_proc, sig);
3376 		PROC_UNLOCK(sigio->sio_proc);
3377 	} else if (sigio->sio_pgid < 0) {
3378 		struct proc *p;
3379 
3380 		PGRP_LOCK(sigio->sio_pgrp);
3381 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
3382 			PROC_LOCK(p);
3383 			if (p->p_state == PRS_NORMAL &&
3384 			    CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
3385 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
3386 				kern_psignal(p, sig);
3387 			PROC_UNLOCK(p);
3388 		}
3389 		PGRP_UNLOCK(sigio->sio_pgrp);
3390 	}
3391 	SIGIO_UNLOCK();
3392 }
3393 
3394 static int
3395 filt_sigattach(struct knote *kn)
3396 {
3397 	struct proc *p = curproc;
3398 
3399 	kn->kn_ptr.p_proc = p;
3400 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
3401 
3402 	knlist_add(&p->p_klist, kn, 0);
3403 
3404 	return (0);
3405 }
3406 
3407 static void
3408 filt_sigdetach(struct knote *kn)
3409 {
3410 	struct proc *p = kn->kn_ptr.p_proc;
3411 
3412 	knlist_remove(&p->p_klist, kn, 0);
3413 }
3414 
3415 /*
3416  * signal knotes are shared with proc knotes, so we apply a mask to
3417  * the hint in order to differentiate them from process hints.  This
3418  * could be avoided by using a signal-specific knote list, but probably
3419  * isn't worth the trouble.
3420  */
3421 static int
3422 filt_signal(struct knote *kn, long hint)
3423 {
3424 
3425 	if (hint & NOTE_SIGNAL) {
3426 		hint &= ~NOTE_SIGNAL;
3427 
3428 		if (kn->kn_id == hint)
3429 			kn->kn_data++;
3430 	}
3431 	return (kn->kn_data != 0);
3432 }
3433 
3434 struct sigacts *
3435 sigacts_alloc(void)
3436 {
3437 	struct sigacts *ps;
3438 
3439 	ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
3440 	refcount_init(&ps->ps_refcnt, 1);
3441 	mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
3442 	return (ps);
3443 }
3444 
3445 void
3446 sigacts_free(struct sigacts *ps)
3447 {
3448 
3449 	if (refcount_release(&ps->ps_refcnt) == 0)
3450 		return;
3451 	mtx_destroy(&ps->ps_mtx);
3452 	free(ps, M_SUBPROC);
3453 }
3454 
3455 struct sigacts *
3456 sigacts_hold(struct sigacts *ps)
3457 {
3458 
3459 	refcount_acquire(&ps->ps_refcnt);
3460 	return (ps);
3461 }
3462 
3463 void
3464 sigacts_copy(struct sigacts *dest, struct sigacts *src)
3465 {
3466 
3467 	KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
3468 	mtx_lock(&src->ps_mtx);
3469 	bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
3470 	mtx_unlock(&src->ps_mtx);
3471 }
3472 
3473 int
3474 sigacts_shared(struct sigacts *ps)
3475 {
3476 
3477 	return (ps->ps_refcnt > 1);
3478 }
3479