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