xref: /dflybsd-src/sys/kern/kern_sig.c (revision 07caec20a93f40352fd28eec40bb9b40199edf40)
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_sig.c	8.7 (Berkeley) 4/18/94
39  * $FreeBSD: src/sys/kern/kern_sig.c,v 1.72.2.17 2003/05/16 16:34:34 obrien Exp $
40  * $DragonFly: src/sys/kern/kern_sig.c,v 1.55 2006/10/10 15:40:46 dillon Exp $
41  */
42 
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/sysproto.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vnode.h>
52 #include <sys/event.h>
53 #include <sys/proc.h>
54 #include <sys/nlookup.h>
55 #include <sys/pioctl.h>
56 #include <sys/systm.h>
57 #include <sys/acct.h>
58 #include <sys/fcntl.h>
59 #include <sys/lock.h>
60 #include <sys/wait.h>
61 #include <sys/ktrace.h>
62 #include <sys/syslog.h>
63 #include <sys/stat.h>
64 #include <sys/sysent.h>
65 #include <sys/sysctl.h>
66 #include <sys/malloc.h>
67 #include <sys/unistd.h>
68 #include <sys/kern_syscall.h>
69 #include <sys/thread2.h>
70 
71 
72 #include <machine/ipl.h>
73 #include <machine/cpu.h>
74 #include <machine/smp.h>
75 
76 static int	coredump(struct proc *);
77 static char	*expand_name(const char *, uid_t, pid_t);
78 static int	killpg(int sig, int pgid, int all);
79 static int	sig_ffs(sigset_t *set);
80 static int	sigprop(int sig);
81 #ifdef SMP
82 static void	signotify_remote(void *arg);
83 #endif
84 static int	kern_sigtimedwait(sigset_t set, siginfo_t *info,
85 		    struct timespec *timeout);
86 
87 static int	filt_sigattach(struct knote *kn);
88 static void	filt_sigdetach(struct knote *kn);
89 static int	filt_signal(struct knote *kn, long hint);
90 
91 struct filterops sig_filtops =
92 	{ 0, filt_sigattach, filt_sigdetach, filt_signal };
93 
94 static int	kern_logsigexit = 1;
95 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
96     &kern_logsigexit, 0,
97     "Log processes quitting on abnormal signals to syslog(3)");
98 
99 /*
100  * Can process p, with pcred pc, send the signal sig to process q?
101  */
102 #define CANSIGNAL(q, sig) \
103 	(!p_trespass(curproc->p_ucred, (q)->p_ucred) || \
104 	((sig) == SIGCONT && (q)->p_session == curproc->p_session))
105 
106 /*
107  * Policy -- Can real uid ruid with ucred uc send a signal to process q?
108  */
109 #define CANSIGIO(ruid, uc, q) \
110 	((uc)->cr_uid == 0 || \
111 	    (ruid) == (q)->p_ucred->cr_ruid || \
112 	    (uc)->cr_uid == (q)->p_ucred->cr_ruid || \
113 	    (ruid) == (q)->p_ucred->cr_uid || \
114 	    (uc)->cr_uid == (q)->p_ucred->cr_uid)
115 
116 int sugid_coredump;
117 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RW,
118 	&sugid_coredump, 0, "Enable coredumping set user/group ID processes");
119 
120 static int	do_coredump = 1;
121 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
122 	&do_coredump, 0, "Enable/Disable coredumps");
123 
124 /*
125  * Signal properties and actions.
126  * The array below categorizes the signals and their default actions
127  * according to the following properties:
128  */
129 #define	SA_KILL		0x01		/* terminates process by default */
130 #define	SA_CORE		0x02		/* ditto and coredumps */
131 #define	SA_STOP		0x04		/* suspend process */
132 #define	SA_TTYSTOP	0x08		/* ditto, from tty */
133 #define	SA_IGNORE	0x10		/* ignore by default */
134 #define	SA_CONT		0x20		/* continue if suspended */
135 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
136 #define SA_CKPT         0x80            /* checkpoint process */
137 
138 
139 static int sigproptbl[NSIG] = {
140         SA_KILL,                /* SIGHUP */
141         SA_KILL,                /* SIGINT */
142         SA_KILL|SA_CORE,        /* SIGQUIT */
143         SA_KILL|SA_CORE,        /* SIGILL */
144         SA_KILL|SA_CORE,        /* SIGTRAP */
145         SA_KILL|SA_CORE,        /* SIGABRT */
146         SA_KILL|SA_CORE,        /* SIGEMT */
147         SA_KILL|SA_CORE,        /* SIGFPE */
148         SA_KILL,                /* SIGKILL */
149         SA_KILL|SA_CORE,        /* SIGBUS */
150         SA_KILL|SA_CORE,        /* SIGSEGV */
151         SA_KILL|SA_CORE,        /* SIGSYS */
152         SA_KILL,                /* SIGPIPE */
153         SA_KILL,                /* SIGALRM */
154         SA_KILL,                /* SIGTERM */
155         SA_IGNORE,              /* SIGURG */
156         SA_STOP,                /* SIGSTOP */
157         SA_STOP|SA_TTYSTOP,     /* SIGTSTP */
158         SA_IGNORE|SA_CONT,      /* SIGCONT */
159         SA_IGNORE,              /* SIGCHLD */
160         SA_STOP|SA_TTYSTOP,     /* SIGTTIN */
161         SA_STOP|SA_TTYSTOP,     /* SIGTTOU */
162         SA_IGNORE,              /* SIGIO */
163         SA_KILL,                /* SIGXCPU */
164         SA_KILL,                /* SIGXFSZ */
165         SA_KILL,                /* SIGVTALRM */
166         SA_KILL,                /* SIGPROF */
167         SA_IGNORE,              /* SIGWINCH  */
168         SA_IGNORE,              /* SIGINFO */
169         SA_KILL,                /* SIGUSR1 */
170         SA_KILL,                /* SIGUSR2 */
171 	SA_IGNORE,              /* SIGTHR */
172 	SA_CKPT,                /* SIGCKPT */
173 	SA_KILL|SA_CKPT,        /* SIGCKPTEXIT */
174 	SA_IGNORE,
175 	SA_IGNORE,
176 	SA_IGNORE,
177 	SA_IGNORE,
178 	SA_IGNORE,
179 	SA_IGNORE,
180 	SA_IGNORE,
181 	SA_IGNORE,
182 	SA_IGNORE,
183 	SA_IGNORE,
184 	SA_IGNORE,
185 	SA_IGNORE,
186 	SA_IGNORE,
187 	SA_IGNORE,
188 	SA_IGNORE,
189 	SA_IGNORE,
190 	SA_IGNORE,
191 	SA_IGNORE,
192 	SA_IGNORE,
193 	SA_IGNORE,
194 	SA_IGNORE,
195 	SA_IGNORE,
196 	SA_IGNORE,
197 	SA_IGNORE,
198 	SA_IGNORE,
199 	SA_IGNORE,
200 	SA_IGNORE,
201 	SA_IGNORE,
202 	SA_IGNORE,
203 	SA_IGNORE,
204 
205 };
206 
207 static __inline int
208 sigprop(int sig)
209 {
210 
211 	if (sig > 0 && sig < NSIG)
212 		return (sigproptbl[_SIG_IDX(sig)]);
213 	return (0);
214 }
215 
216 static __inline int
217 sig_ffs(sigset_t *set)
218 {
219 	int i;
220 
221 	for (i = 0; i < _SIG_WORDS; i++)
222 		if (set->__bits[i])
223 			return (ffs(set->__bits[i]) + (i * 32));
224 	return (0);
225 }
226 
227 int
228 kern_sigaction(int sig, struct sigaction *act, struct sigaction *oact)
229 {
230 	struct thread *td = curthread;
231 	struct proc *p = td->td_proc;
232 	struct sigacts *ps = p->p_sigacts;
233 
234 	if (sig <= 0 || sig > _SIG_MAXSIG)
235 		return (EINVAL);
236 
237 	if (oact) {
238 		oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
239 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
240 		oact->sa_flags = 0;
241 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
242 			oact->sa_flags |= SA_ONSTACK;
243 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
244 			oact->sa_flags |= SA_RESTART;
245 		if (SIGISMEMBER(ps->ps_sigreset, sig))
246 			oact->sa_flags |= SA_RESETHAND;
247 		if (SIGISMEMBER(ps->ps_signodefer, sig))
248 			oact->sa_flags |= SA_NODEFER;
249 		if (SIGISMEMBER(ps->ps_siginfo, sig))
250 			oact->sa_flags |= SA_SIGINFO;
251 		if (sig == SIGCHLD && p->p_procsig->ps_flag & PS_NOCLDSTOP)
252 			oact->sa_flags |= SA_NOCLDSTOP;
253 		if (sig == SIGCHLD && p->p_procsig->ps_flag & PS_NOCLDWAIT)
254 			oact->sa_flags |= SA_NOCLDWAIT;
255 	}
256 	if (act) {
257 		if ((sig == SIGKILL || sig == SIGSTOP) &&
258 		    act->sa_handler != SIG_DFL)
259 			return (EINVAL);
260 
261 		/*
262 		 * Change setting atomically.
263 		 */
264 		crit_enter();
265 
266 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
267 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
268 		if (act->sa_flags & SA_SIGINFO) {
269 			ps->ps_sigact[_SIG_IDX(sig)] =
270 			    (__sighandler_t *)act->sa_sigaction;
271 			SIGADDSET(ps->ps_siginfo, sig);
272 		} else {
273 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
274 			SIGDELSET(ps->ps_siginfo, sig);
275 		}
276 		if (!(act->sa_flags & SA_RESTART))
277 			SIGADDSET(ps->ps_sigintr, sig);
278 		else
279 			SIGDELSET(ps->ps_sigintr, sig);
280 		if (act->sa_flags & SA_ONSTACK)
281 			SIGADDSET(ps->ps_sigonstack, sig);
282 		else
283 			SIGDELSET(ps->ps_sigonstack, sig);
284 		if (act->sa_flags & SA_RESETHAND)
285 			SIGADDSET(ps->ps_sigreset, sig);
286 		else
287 			SIGDELSET(ps->ps_sigreset, sig);
288 		if (act->sa_flags & SA_NODEFER)
289 			SIGADDSET(ps->ps_signodefer, sig);
290 		else
291 			SIGDELSET(ps->ps_signodefer, sig);
292 		if (sig == SIGCHLD) {
293 			if (act->sa_flags & SA_NOCLDSTOP)
294 				p->p_procsig->ps_flag |= PS_NOCLDSTOP;
295 			else
296 				p->p_procsig->ps_flag &= ~PS_NOCLDSTOP;
297 			if (act->sa_flags & SA_NOCLDWAIT) {
298 				/*
299 				 * Paranoia: since SA_NOCLDWAIT is implemented
300 				 * by reparenting the dying child to PID 1 (and
301 				 * trust it to reap the zombie), PID 1 itself
302 				 * is forbidden to set SA_NOCLDWAIT.
303 				 */
304 				if (p->p_pid == 1)
305 					p->p_procsig->ps_flag &= ~PS_NOCLDWAIT;
306 				else
307 					p->p_procsig->ps_flag |= PS_NOCLDWAIT;
308 			} else {
309 				p->p_procsig->ps_flag &= ~PS_NOCLDWAIT;
310 			}
311 		}
312 		/*
313 		 * Set bit in p_sigignore for signals that are set to SIG_IGN,
314 		 * and for signals set to SIG_DFL where the default is to
315 		 * ignore. However, don't put SIGCONT in p_sigignore, as we
316 		 * have to restart the process.
317 		 */
318 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
319 		    (sigprop(sig) & SA_IGNORE &&
320 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
321 			/* never to be seen again */
322 			SIGDELSET(p->p_siglist, sig);
323 			if (sig != SIGCONT)
324 				/* easier in ksignal */
325 				SIGADDSET(p->p_sigignore, sig);
326 			SIGDELSET(p->p_sigcatch, sig);
327 		} else {
328 			SIGDELSET(p->p_sigignore, sig);
329 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
330 				SIGDELSET(p->p_sigcatch, sig);
331 			else
332 				SIGADDSET(p->p_sigcatch, sig);
333 		}
334 
335 		crit_exit();
336 	}
337 	return (0);
338 }
339 
340 int
341 sys_sigaction(struct sigaction_args *uap)
342 {
343 	struct sigaction act, oact;
344 	struct sigaction *actp, *oactp;
345 	int error;
346 
347 	actp = (uap->act != NULL) ? &act : NULL;
348 	oactp = (uap->oact != NULL) ? &oact : NULL;
349 	if (actp) {
350 		error = copyin(uap->act, actp, sizeof(act));
351 		if (error)
352 			return (error);
353 	}
354 	error = kern_sigaction(uap->sig, actp, oactp);
355 	if (oactp && !error) {
356 		error = copyout(oactp, uap->oact, sizeof(oact));
357 	}
358 	return (error);
359 }
360 
361 /*
362  * Initialize signal state for process 0;
363  * set to ignore signals that are ignored by default.
364  */
365 void
366 siginit(struct proc *p)
367 {
368 	int i;
369 
370 	for (i = 1; i <= NSIG; i++)
371 		if (sigprop(i) & SA_IGNORE && i != SIGCONT)
372 			SIGADDSET(p->p_sigignore, i);
373 }
374 
375 /*
376  * Reset signals for an exec of the specified process.
377  */
378 void
379 execsigs(struct proc *p)
380 {
381 	struct sigacts *ps = p->p_sigacts;
382 	int sig;
383 
384 	/*
385 	 * Reset caught signals.  Held signals remain held
386 	 * through p_sigmask (unless they were caught,
387 	 * and are now ignored by default).
388 	 */
389 	while (SIGNOTEMPTY(p->p_sigcatch)) {
390 		sig = sig_ffs(&p->p_sigcatch);
391 		SIGDELSET(p->p_sigcatch, sig);
392 		if (sigprop(sig) & SA_IGNORE) {
393 			if (sig != SIGCONT)
394 				SIGADDSET(p->p_sigignore, sig);
395 			SIGDELSET(p->p_siglist, sig);
396 		}
397 		ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
398 	}
399 	/*
400 	 * Reset stack state to the user stack.
401 	 * Clear set of signals caught on the signal stack.
402 	 */
403 	p->p_sigstk.ss_flags = SS_DISABLE;
404 	p->p_sigstk.ss_size = 0;
405 	p->p_sigstk.ss_sp = 0;
406 	p->p_flag &= ~P_ALTSTACK;
407 	/*
408 	 * Reset no zombies if child dies flag as Solaris does.
409 	 */
410 	p->p_procsig->ps_flag &= ~PS_NOCLDWAIT;
411 }
412 
413 /*
414  * kern_sigprocmask() - MP SAFE ONLY IF p == curproc
415  *
416  *	Manipulate signal mask.  This routine is MP SAFE *ONLY* if
417  *	p == curproc.
418  */
419 int
420 kern_sigprocmask(int how, sigset_t *set, sigset_t *oset)
421 {
422 	struct thread *td = curthread;
423 	struct proc *p = td->td_proc;
424 	int error;
425 
426 	if (oset != NULL)
427 		*oset = p->p_sigmask;
428 
429 	error = 0;
430 	if (set != NULL) {
431 		switch (how) {
432 		case SIG_BLOCK:
433 			SIG_CANTMASK(*set);
434 			SIGSETOR(p->p_sigmask, *set);
435 			break;
436 		case SIG_UNBLOCK:
437 			SIGSETNAND(p->p_sigmask, *set);
438 			break;
439 		case SIG_SETMASK:
440 			SIG_CANTMASK(*set);
441 			p->p_sigmask = *set;
442 			break;
443 		default:
444 			error = EINVAL;
445 			break;
446 		}
447 	}
448 	return (error);
449 }
450 
451 /*
452  * sigprocmask() - MP SAFE
453  */
454 int
455 sys_sigprocmask(struct sigprocmask_args *uap)
456 {
457 	sigset_t set, oset;
458 	sigset_t *setp, *osetp;
459 	int error;
460 
461 	setp = (uap->set != NULL) ? &set : NULL;
462 	osetp = (uap->oset != NULL) ? &oset : NULL;
463 	if (setp) {
464 		error = copyin(uap->set, setp, sizeof(set));
465 		if (error)
466 			return (error);
467 	}
468 	error = kern_sigprocmask(uap->how, setp, osetp);
469 	if (osetp && !error) {
470 		error = copyout(osetp, uap->oset, sizeof(oset));
471 	}
472 	return (error);
473 }
474 
475 int
476 kern_sigpending(struct __sigset *set)
477 {
478 	struct thread *td = curthread;
479 	struct proc *p = td->td_proc;
480 
481 	*set = p->p_siglist;
482 
483 	return (0);
484 }
485 
486 int
487 sys_sigpending(struct sigpending_args *uap)
488 {
489 	sigset_t set;
490 	int error;
491 
492 	error = kern_sigpending(&set);
493 
494 	if (error == 0)
495 		error = copyout(&set, uap->set, sizeof(set));
496 	return (error);
497 }
498 
499 /*
500  * Suspend process until signal, providing mask to be set
501  * in the meantime.
502  */
503 int
504 kern_sigsuspend(struct __sigset *set)
505 {
506 	struct thread *td = curthread;
507 	struct proc *p = td->td_proc;
508 	struct sigacts *ps = p->p_sigacts;
509 
510 	/*
511 	 * When returning from sigsuspend, we want
512 	 * the old mask to be restored after the
513 	 * signal handler has finished.  Thus, we
514 	 * save it here and mark the sigacts structure
515 	 * to indicate this.
516 	 */
517 	p->p_oldsigmask = p->p_sigmask;
518 	p->p_flag |= P_OLDMASK;
519 
520 	SIG_CANTMASK(*set);
521 	p->p_sigmask = *set;
522 	while (tsleep(ps, PCATCH, "pause", 0) == 0)
523 		/* void */;
524 	/* always return EINTR rather than ERESTART... */
525 	return (EINTR);
526 }
527 
528 /*
529  * Note nonstandard calling convention: libc stub passes mask, not
530  * pointer, to save a copyin.
531  */
532 int
533 sys_sigsuspend(struct sigsuspend_args *uap)
534 {
535 	sigset_t mask;
536 	int error;
537 
538 	error = copyin(uap->sigmask, &mask, sizeof(mask));
539 	if (error)
540 		return (error);
541 
542 	error = kern_sigsuspend(&mask);
543 
544 	return (error);
545 }
546 
547 int
548 kern_sigaltstack(struct sigaltstack *ss, struct sigaltstack *oss)
549 {
550 	struct thread *td = curthread;
551 	struct proc *p = td->td_proc;
552 
553 	if ((p->p_flag & P_ALTSTACK) == 0)
554 		p->p_sigstk.ss_flags |= SS_DISABLE;
555 
556 	if (oss)
557 		*oss = p->p_sigstk;
558 
559 	if (ss) {
560 		if (ss->ss_flags & SS_DISABLE) {
561 			if (p->p_sigstk.ss_flags & SS_ONSTACK)
562 				return (EINVAL);
563 			p->p_flag &= ~P_ALTSTACK;
564 			p->p_sigstk.ss_flags = ss->ss_flags;
565 		} else {
566 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
567 				return (ENOMEM);
568 			p->p_flag |= P_ALTSTACK;
569 			p->p_sigstk = *ss;
570 		}
571 	}
572 
573 	return (0);
574 }
575 
576 int
577 sys_sigaltstack(struct sigaltstack_args *uap)
578 {
579 	stack_t ss, oss;
580 	int error;
581 
582 	if (uap->ss) {
583 		error = copyin(uap->ss, &ss, sizeof(ss));
584 		if (error)
585 			return (error);
586 	}
587 
588 	error = kern_sigaltstack(uap->ss ? &ss : NULL,
589 	    uap->oss ? &oss : NULL);
590 
591 	if (error == 0 && uap->oss)
592 		error = copyout(&oss, uap->oss, sizeof(*uap->oss));
593 	return (error);
594 }
595 
596 /*
597  * Common code for kill process group/broadcast kill.
598  * cp is calling process.
599  */
600 struct killpg_info {
601 	int nfound;
602 	int sig;
603 };
604 
605 static int killpg_all_callback(struct proc *p, void *data);
606 
607 static int
608 killpg(int sig, int pgid, int all)
609 {
610 	struct killpg_info info;
611 	struct proc *cp = curproc;
612 	struct proc *p;
613 	struct pgrp *pgrp;
614 
615 	info.nfound = 0;
616 	info.sig = sig;
617 
618 	if (all) {
619 		/*
620 		 * broadcast
621 		 */
622 		allproc_scan(killpg_all_callback, &info);
623 	} else {
624 		if (pgid == 0) {
625 			/*
626 			 * zero pgid means send to my process group.
627 			 */
628 			pgrp = cp->p_pgrp;
629 		} else {
630 			pgrp = pgfind(pgid);
631 			if (pgrp == NULL)
632 				return (ESRCH);
633 		}
634 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
635 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
636 			if (p->p_pid <= 1 ||
637 			    (p->p_flag & (P_SYSTEM | P_ZOMBIE)) ||
638 			    !CANSIGNAL(p, sig)) {
639 				continue;
640 			}
641 			++info.nfound;
642 			if (sig)
643 				ksignal(p, sig);
644 		}
645 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
646 	}
647 	return (info.nfound ? 0 : ESRCH);
648 }
649 
650 static int
651 killpg_all_callback(struct proc *p, void *data)
652 {
653 	struct killpg_info *info = data;
654 
655 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) ||
656 	    p == curproc || !CANSIGNAL(p, info->sig)) {
657 		return (0);
658 	}
659 	++info->nfound;
660 	if (info->sig)
661 		ksignal(p, info->sig);
662 	return(0);
663 }
664 
665 int
666 kern_kill(int sig, int pid)
667 {
668 	struct thread *td = curthread;
669 	struct proc *p = td->td_proc;
670 
671 	if ((u_int)sig > _SIG_MAXSIG)
672 		return (EINVAL);
673 	if (pid > 0) {
674 		/* kill single process */
675 		if ((p = pfind(pid)) == NULL)
676 			return (ESRCH);
677 		if (!CANSIGNAL(p, sig))
678 			return (EPERM);
679 		if (sig)
680 			ksignal(p, sig);
681 		return (0);
682 	}
683 	switch (pid) {
684 	case -1:		/* broadcast signal */
685 		return (killpg(sig, 0, 1));
686 	case 0:			/* signal own process group */
687 		return (killpg(sig, 0, 0));
688 	default:		/* negative explicit process group */
689 		return (killpg(sig, -pid, 0));
690 	}
691 	/* NOTREACHED */
692 }
693 
694 int
695 sys_kill(struct kill_args *uap)
696 {
697 	int error;
698 
699 	error = kern_kill(uap->signum, uap->pid);
700 
701 	return (error);
702 }
703 
704 /*
705  * Send a signal to a process group.
706  */
707 void
708 gsignal(int pgid, int sig)
709 {
710 	struct pgrp *pgrp;
711 
712 	if (pgid && (pgrp = pgfind(pgid)))
713 		pgsignal(pgrp, sig, 0);
714 }
715 
716 /*
717  * Send a signal to a process group.  If checktty is 1,
718  * limit to members which have a controlling terminal.
719  *
720  * pg_lock interlocks against a fork that might be in progress, to
721  * ensure that the new child process picks up the signal.
722  */
723 void
724 pgsignal(struct pgrp *pgrp, int sig, int checkctty)
725 {
726 	struct proc *p;
727 
728 	if (pgrp) {
729 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
730 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
731 			if (checkctty == 0 || p->p_flag & P_CONTROLT)
732 				ksignal(p, sig);
733 		}
734 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
735 	}
736 }
737 
738 /*
739  * Send a signal caused by a trap to the current process.
740  * If it will be caught immediately, deliver it with correct code.
741  * Otherwise, post it normally.
742  */
743 void
744 trapsignal(struct proc *p, int sig, u_long code)
745 {
746 	struct sigacts *ps = p->p_sigacts;
747 
748 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(p->p_sigcatch, sig) &&
749 	    !SIGISMEMBER(p->p_sigmask, sig)) {
750 		p->p_stats->p_ru.ru_nsignals++;
751 #ifdef KTRACE
752 		if (KTRPOINT(p->p_thread, KTR_PSIG))
753 			ktrpsig(p, sig, ps->ps_sigact[_SIG_IDX(sig)],
754 				&p->p_sigmask, code);
755 #endif
756 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)], sig,
757 						&p->p_sigmask, code);
758 		SIGSETOR(p->p_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
759 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
760 			SIGADDSET(p->p_sigmask, sig);
761 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
762 			/*
763 			 * See kern_sigaction() for origin of this code.
764 			 */
765 			SIGDELSET(p->p_sigcatch, sig);
766 			if (sig != SIGCONT &&
767 			    sigprop(sig) & SA_IGNORE)
768 				SIGADDSET(p->p_sigignore, sig);
769 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
770 		}
771 	} else {
772 		p->p_code = code;	/* XXX for core dump/debugger */
773 		p->p_sig = sig;		/* XXX to verify code */
774 		ksignal(p, sig);
775 	}
776 }
777 
778 /*
779  * Send the signal to the process.  If the signal has an action, the action
780  * is usually performed by the target process rather than the caller; we add
781  * the signal to the set of pending signals for the process.
782  *
783  * Exceptions:
784  *   o When a stop signal is sent to a sleeping process that takes the
785  *     default action, the process is stopped without awakening it.
786  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
787  *     regardless of the signal action (eg, blocked or ignored).
788  *
789  * Other ignored signals are discarded immediately.
790  */
791 void
792 ksignal(struct proc *p, int sig)
793 {
794 	struct lwp *lp = &p->p_lwp;
795 	int prop;
796 	sig_t action;
797 
798 	if (sig > _SIG_MAXSIG || sig <= 0) {
799 		printf("ksignal: signal %d\n", sig);
800 		panic("ksignal signal number");
801 	}
802 
803 	crit_enter();
804 	KNOTE(&p->p_klist, NOTE_SIGNAL | sig);
805 	crit_exit();
806 
807 	prop = sigprop(sig);
808 
809 	/*
810 	 * If proc is traced, always give parent a chance;
811 	 * if signal event is tracked by procfs, give *that*
812 	 * a chance, as well.
813 	 */
814 	if ((p->p_flag & P_TRACED) || (p->p_stops & S_SIG)) {
815 		action = SIG_DFL;
816 	} else {
817 		/*
818 		 * If the signal is being ignored,
819 		 * then we forget about it immediately.
820 		 * (Note: we don't set SIGCONT in p_sigignore,
821 		 * and if it is set to SIG_IGN,
822 		 * action will be SIG_DFL here.)
823 		 */
824 		if (SIGISMEMBER(p->p_sigignore, sig) || (p->p_flag & P_WEXIT))
825 			return;
826 		if (SIGISMEMBER(p->p_sigmask, sig))
827 			action = SIG_HOLD;
828 		else if (SIGISMEMBER(p->p_sigcatch, sig))
829 			action = SIG_CATCH;
830 		else
831 			action = SIG_DFL;
832 	}
833 
834 	if (p->p_nice > NZERO && action == SIG_DFL && (prop & SA_KILL) &&
835 	    (p->p_flag & P_TRACED) == 0) {
836 		p->p_nice = NZERO;
837 	}
838 
839 	/*
840 	 * If continuing, clear any pending STOP signals.
841 	 */
842 	if (prop & SA_CONT)
843 		SIG_STOPSIGMASK(p->p_siglist);
844 
845 	if (prop & SA_STOP) {
846 		/*
847 		 * If sending a tty stop signal to a member of an orphaned
848 		 * process group, discard the signal here if the action
849 		 * is default; don't stop the process below if sleeping,
850 		 * and don't clear any pending SIGCONT.
851 		 */
852 		if (prop & SA_TTYSTOP && p->p_pgrp->pg_jobc == 0 &&
853 		    action == SIG_DFL) {
854 		        return;
855 		}
856 		SIG_CONTSIGMASK(p->p_siglist);
857 	}
858 	SIGADDSET(p->p_siglist, sig);
859 
860 	/*
861 	 * Defer further processing for signals which are held,
862 	 * except that stopped processes must be continued by SIGCONT.
863 	 */
864 	if (action == SIG_HOLD) {
865 		if ((prop & SA_CONT) == 0 || (p->p_flag & P_STOPPED) == 0)
866 			return;
867 	}
868 
869 	crit_enter();
870 
871 	/*
872 	 * Process is in tsleep and not stopped
873 	 */
874 	if (p->p_stat == SSLEEP && (p->p_flag & P_STOPPED) == 0) {
875 		/*
876 		 * If the process is sleeping uninterruptibly
877 		 * we can't interrupt the sleep... the signal will
878 		 * be noticed when the process returns through
879 		 * trap() or syscall().
880 		 */
881 		if ((p->p_flag & P_SINTR) == 0)
882 			goto out;
883 
884 		/*
885 		 * If the process is sleeping and traced, make it runnable
886 		 * so it can discover the signal in issignal() and stop
887 		 * for the parent.
888 		 *
889 		 * If the process is stopped and traced, no further action
890 		 * is necessary.
891 		 */
892 		if (p->p_flag & P_TRACED)
893 			goto run;
894 
895 		/*
896 		 * If the process is sleeping and SA_CONT, and the signal
897 		 * mode is SIG_DFL, then make the process runnable.
898 		 *
899 		 * However, do *NOT* set P_BREAKTSLEEP.  We do not want
900 		 * a SIGCONT to terminate an interruptable tsleep early
901 		 * and generate a spurious EINTR.
902 		 */
903 		if ((prop & SA_CONT) && action == SIG_DFL) {
904 			SIGDELSET(p->p_siglist, sig);
905 			goto run_no_break;
906 		}
907 
908 		/*
909 		 * If the process is sleeping and receives a STOP signal,
910 		 * process immediately if possible.  All other (caught or
911 		 * default) signals cause the process to run.
912 		 */
913 		if (prop & SA_STOP) {
914 			if (action != SIG_DFL)
915 				goto run;
916 
917 			/*
918 			 * If a child holding parent blocked, stopping
919 			 * could cause deadlock.  Take no action at this
920 			 * time.
921 			 */
922 			if (p->p_flag & P_PPWAIT)
923 				goto out;
924 
925 			/*
926 			 * Do not actually try to manipulate the process
927 			 * while it is sleeping, simply set P_STOPPED to
928 			 * indicate that it should stop as soon as it safely
929 			 * can.
930 			 */
931 			SIGDELSET(p->p_siglist, sig);
932 			p->p_flag |= P_STOPPED;
933 			p->p_flag &= ~P_WAITED;
934 			p->p_xstat = sig;
935 			wakeup(p->p_pptr);
936 			if ((p->p_pptr->p_procsig->ps_flag & PS_NOCLDSTOP) == 0)
937 				ksignal(p->p_pptr, SIGCHLD);
938 			goto out;
939 		}
940 
941 		/*
942 		 * Otherwise the signal can interrupt the sleep.
943 		 */
944 		goto run;
945 	}
946 
947 	/*
948 	 * Process is in tsleep and is stopped
949 	 */
950 	if (p->p_stat == SSLEEP && (p->p_flag & P_STOPPED)) {
951 		/*
952 		 * If the process is stopped and is being traced, then no
953 		 * further action is necessary.
954 		 */
955 		if (p->p_flag & P_TRACED)
956 			goto out;
957 
958 		/*
959 		 * If the process is stopped and receives a KILL signal,
960 		 * make the process runnable.
961 		 */
962 		if (sig == SIGKILL)
963 			goto run;
964 
965 		/*
966 		 * If the process is stopped and receives a CONT signal,
967 		 * then try to make the process runnable again.
968 		 */
969 		if (prop & SA_CONT) {
970 			/*
971 			 * If SIGCONT is default (or ignored), we continue the
972 			 * process but don't leave the signal in p_siglist, as
973 			 * it has no further action.  If SIGCONT is held, we
974 			 * continue the process and leave the signal in
975 			 * p_siglist.  If the process catches SIGCONT, let it
976 			 * handle the signal itself.
977 			 */
978 			if (action == SIG_DFL)
979 				SIGDELSET(p->p_siglist, sig);
980 			if (action == SIG_CATCH)
981 				goto run;
982 
983 			/*
984 			 * Make runnable but do not break a tsleep unless
985 			 * some other signal was pending.
986 			 */
987 			goto run_no_break;
988 		}
989 
990 		/*
991 		 * If the process is stopped and receives another STOP
992 		 * signal, we do not need to stop it again.  If we did
993 		 * the shell could get confused.
994 		 */
995 		if (prop & SA_STOP) {
996 			SIGDELSET(p->p_siglist, sig);
997 			goto out;
998 		}
999 
1000 		/*
1001 		 * Otherwise the process is sleeping interruptably but
1002 		 * is stopped, just set the P_BREAKTSLEEP flag and take
1003 		 * no further action.  The next runnable action will wake
1004 		 * the process up.
1005 		 */
1006 		p->p_flag |= P_BREAKTSLEEP;
1007 		goto out;
1008 	}
1009 
1010 	/*
1011 	 * Otherwise the process is running
1012 	 *
1013 	 * SRUN, SIDL, SZOMB do nothing with the signal,
1014 	 * other than kicking ourselves if we are running.
1015 	 * It will either never be noticed, or noticed very soon.
1016 	 *
1017 	 * Note that p_thread may be NULL or may not be completely
1018 	 * initialized if the process is in the SIDL or SZOMB state.
1019 	 *
1020 	 * For SMP we may have to forward the request to another cpu.
1021 	 * YYY the MP lock prevents the target process from moving
1022 	 * to another cpu, see kern/kern_switch.c
1023 	 *
1024 	 * If the target thread is waiting on its message port,
1025 	 * wakeup the target thread so it can check (or ignore)
1026 	 * the new signal.  YYY needs cleanup.
1027 	 */
1028 	if (lp == lwkt_preempted_proc()) {
1029 		signotify();
1030 	} else if (p->p_stat == SRUN) {
1031 		struct thread *td = p->p_thread;
1032 
1033 		KASSERT(td != NULL,
1034 		    ("pid %d NULL p_thread stat %d flags %08x",
1035 		    p->p_pid, p->p_stat, p->p_flag));
1036 
1037 #ifdef SMP
1038 		if (td->td_gd != mycpu)
1039 			lwkt_send_ipiq(td->td_gd, signotify_remote, lp);
1040 		else
1041 #endif
1042 		if (td->td_msgport.mp_flags & MSGPORTF_WAITING)
1043 			lwkt_schedule(td);
1044 	}
1045 	goto out;
1046 	/*NOTREACHED*/
1047 run:
1048 	/*
1049 	 * Make runnable and break out of any tsleep as well.
1050 	 */
1051 	p->p_flag |= P_BREAKTSLEEP;
1052 run_no_break:
1053 	setrunnable(p);
1054 out:
1055 	crit_exit();
1056 }
1057 
1058 #ifdef SMP
1059 
1060 /*
1061  * This function is called via an IPI.  We will be in a critical section but
1062  * the MP lock will NOT be held.  Also note that by the time the ipi message
1063  * gets to us the process 'p' (arg) may no longer be scheduled or even valid.
1064  */
1065 static void
1066 signotify_remote(void *arg)
1067 {
1068 	struct lwp *lp = arg;
1069 
1070 	if (lp == lwkt_preempted_proc()) {
1071 		signotify();
1072 	} else {
1073 		struct thread *td = lp->lwp_thread;
1074 		if (td->td_msgport.mp_flags & MSGPORTF_WAITING)
1075 			lwkt_schedule(td);
1076 	}
1077 }
1078 
1079 #endif
1080 
1081 static int
1082 kern_sigtimedwait(sigset_t waitset, siginfo_t *info, struct timespec *timeout)
1083 {
1084 	sigset_t savedmask, set;
1085 	struct proc *p = curproc;
1086 	int error, sig, hz, timevalid = 0;
1087 	struct timespec rts, ets, ts;
1088 	struct timeval tv;
1089 
1090 	error = 0;
1091 	sig = 0;
1092 	SIG_CANTMASK(waitset);
1093 	savedmask = p->p_sigmask;
1094 
1095 	if (timeout) {
1096 		if (timeout->tv_sec >= 0 && timeout->tv_nsec >= 0 &&
1097 		    timeout->tv_nsec < 1000000000) {
1098 			timevalid = 1;
1099 			getnanouptime(&rts);
1100 		 	ets = rts;
1101 			timespecadd(&ets, timeout);
1102 		}
1103 	}
1104 
1105 	for (;;) {
1106 		set = p->p_siglist;
1107 		SIGSETAND(set, waitset);
1108 		if ((sig = sig_ffs(&set)) != 0) {
1109 			SIGFILLSET(p->p_sigmask);
1110 			SIGDELSET(p->p_sigmask, sig);
1111 			SIG_CANTMASK(p->p_sigmask);
1112 			sig = issignal(p);
1113 			/*
1114 			 * It may be a STOP signal, in the case, issignal
1115 			 * returns 0, because we may stop there, and new
1116 			 * signal can come in, we should restart if we got
1117 			 * nothing.
1118 			 */
1119 			if (sig == 0)
1120 				continue;
1121 			else
1122 				break;
1123 		}
1124 
1125 		/*
1126 		 * Previous checking got nothing, and we retried but still
1127 		 * got nothing, we should return the error status.
1128 		 */
1129 		if (error)
1130 			break;
1131 
1132 		/*
1133 		 * POSIX says this must be checked after looking for pending
1134 		 * signals.
1135 		 */
1136 		if (timeout) {
1137 			if (!timevalid) {
1138 				error = EINVAL;
1139 				break;
1140 			}
1141 			getnanouptime(&rts);
1142 			if (timespeccmp(&rts, &ets, >=)) {
1143 				error = EAGAIN;
1144 				break;
1145 			}
1146 			ts = ets;
1147 			timespecsub(&ts, &rts);
1148 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1149 			hz = tvtohz_high(&tv);
1150 		} else
1151 			hz = 0;
1152 
1153 		p->p_sigmask = savedmask;
1154 		SIGSETNAND(p->p_sigmask, waitset);
1155 		error = tsleep(&p->p_sigacts, PCATCH, "sigwt", hz);
1156 		if (timeout) {
1157 			if (error == ERESTART) {
1158 				/* can not restart a timeout wait. */
1159 				error = EINTR;
1160 			} else if (error == EAGAIN) {
1161 				/* will calculate timeout by ourself. */
1162 				error = 0;
1163 			}
1164 		}
1165 		/* Retry ... */
1166 	}
1167 
1168 	p->p_sigmask = savedmask;
1169 	if (sig) {
1170 		error = 0;
1171 		bzero(info, sizeof(*info));
1172 		info->si_signo = sig;
1173 		SIGDELSET(p->p_siglist, sig);	/* take the signal! */
1174 
1175 		if (sig == SIGKILL)
1176 			sigexit(p, sig);
1177 	}
1178 	return (error);
1179 }
1180 
1181 int
1182 sys_sigtimedwait(struct sigtimedwait_args *uap)
1183 {
1184 	struct timespec ts;
1185 	struct timespec *timeout;
1186 	sigset_t set;
1187 	siginfo_t info;
1188 	int error;
1189 
1190 	if (uap->timeout) {
1191 		error = copyin(uap->timeout, &ts, sizeof(ts));
1192 		if (error)
1193 			return (error);
1194 		timeout = &ts;
1195 	} else {
1196 		timeout = NULL;
1197 	}
1198 	error = copyin(uap->set, &set, sizeof(set));
1199 	if (error)
1200 		return (error);
1201 	error = kern_sigtimedwait(set, &info, timeout);
1202 	if (error)
1203 		return (error);
1204  	if (uap->info)
1205 		error = copyout(&info, uap->info, sizeof(info));
1206 	/* Repost if we got an error. */
1207 	if (error)
1208 		ksignal(curproc, info.si_signo);
1209 	else
1210 		uap->sysmsg_result = info.si_signo;
1211 	return (error);
1212 }
1213 
1214 int
1215 sys_sigwaitinfo(struct sigwaitinfo_args *uap)
1216 {
1217 	siginfo_t info;
1218 	sigset_t set;
1219 	int error;
1220 
1221 	error = copyin(uap->set, &set, sizeof(set));
1222 	if (error)
1223 		return (error);
1224 	error = kern_sigtimedwait(set, &info, NULL);
1225 	if (error)
1226 		return (error);
1227 	if (uap->info)
1228 		error = copyout(&info, uap->info, sizeof(info));
1229 	/* Repost if we got an error. */
1230 	if (error)
1231 		ksignal(curproc, info.si_signo);
1232 	else
1233 		uap->sysmsg_result = info.si_signo;
1234 	return (error);
1235 }
1236 
1237 /*
1238  * If the current process has received a signal that would interrupt a
1239  * system call, return EINTR or ERESTART as appropriate.
1240  */
1241 int
1242 iscaught(struct proc *p)
1243 {
1244 	int sig;
1245 
1246 	if (p) {
1247 		if ((sig = CURSIG(p)) != 0) {
1248 			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
1249 				return (EINTR);
1250 			return (ERESTART);
1251 		}
1252 	}
1253 	return(EWOULDBLOCK);
1254 }
1255 
1256 /*
1257  * If the current process has received a signal (should be caught or cause
1258  * termination, should interrupt current syscall), return the signal number.
1259  * Stop signals with default action are processed immediately, then cleared;
1260  * they aren't returned.  This is checked after each entry to the system for
1261  * a syscall or trap (though this can usually be done without calling issignal
1262  * by checking the pending signal masks in the CURSIG macro.) The normal call
1263  * sequence is
1264  *
1265  * This routine is called via CURSIG/__cursig and the MP lock might not be
1266  * held.  Obtain the MP lock for the duration of the operation.
1267  *
1268  *	while (sig = CURSIG(curproc))
1269  *		postsig(sig);
1270  */
1271 int
1272 issignal(struct proc *p)
1273 {
1274 	sigset_t mask;
1275 	int sig, prop;
1276 
1277 	get_mplock();
1278 	for (;;) {
1279 		int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
1280 
1281 		mask = p->p_siglist;
1282 		SIGSETNAND(mask, p->p_sigmask);
1283 		if (p->p_flag & P_PPWAIT)
1284 			SIG_STOPSIGMASK(mask);
1285 		if (!SIGNOTEMPTY(mask)) { 	/* no signal to send */
1286 			rel_mplock();
1287 			return (0);
1288 		}
1289 		sig = sig_ffs(&mask);
1290 
1291 		STOPEVENT(p, S_SIG, sig);
1292 
1293 		/*
1294 		 * We should see pending but ignored signals
1295 		 * only if P_TRACED was on when they were posted.
1296 		 */
1297 		if (SIGISMEMBER(p->p_sigignore, sig) && (traced == 0)) {
1298 			SIGDELSET(p->p_siglist, sig);
1299 			continue;
1300 		}
1301 		if ((p->p_flag & P_TRACED) && (p->p_flag & P_PPWAIT) == 0) {
1302 			/*
1303 			 * If traced, always stop, and stay stopped until
1304 			 * released by the parent.
1305 			 *
1306 			 * NOTE: P_STOPPED may get cleared during the loop,
1307 			 * but we do not re-notify the parent if we have
1308 			 * to loop several times waiting for the parent
1309 			 * to let us continue.
1310 			 */
1311 			p->p_xstat = sig;
1312 			p->p_flag |= P_STOPPED;
1313 			p->p_flag &= ~P_WAITED;
1314 			ksignal(p->p_pptr, SIGCHLD);
1315 			do {
1316 				tstop(p);
1317 			} while (!trace_req(p) && (p->p_flag & P_TRACED));
1318 			p->p_flag &= ~P_STOPPED;
1319 
1320 			/*
1321 			 * If parent wants us to take the signal,
1322 			 * then it will leave it in p->p_xstat;
1323 			 * otherwise we just look for signals again.
1324 			 */
1325 			SIGDELSET(p->p_siglist, sig);	/* clear old signal */
1326 			sig = p->p_xstat;
1327 			if (sig == 0)
1328 				continue;
1329 
1330 			/*
1331 			 * Put the new signal into p_siglist.  If the
1332 			 * signal is being masked, look for other signals.
1333 			 */
1334 			SIGADDSET(p->p_siglist, sig);
1335 			if (SIGISMEMBER(p->p_sigmask, sig))
1336 				continue;
1337 
1338 			/*
1339 			 * If the traced bit got turned off, go back up
1340 			 * to the top to rescan signals.  This ensures
1341 			 * that p_sig* and ps_sigact are consistent.
1342 			 */
1343 			if ((p->p_flag & P_TRACED) == 0)
1344 				continue;
1345 		}
1346 
1347 		prop = sigprop(sig);
1348 
1349 		/*
1350 		 * Decide whether the signal should be returned.
1351 		 * Return the signal's number, or fall through
1352 		 * to clear it from the pending mask.
1353 		 */
1354 		switch ((int)(intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
1355 		case (int)SIG_DFL:
1356 			/*
1357 			 * Don't take default actions on system processes.
1358 			 */
1359 			if (p->p_pid <= 1) {
1360 #ifdef DIAGNOSTIC
1361 				/*
1362 				 * Are you sure you want to ignore SIGSEGV
1363 				 * in init? XXX
1364 				 */
1365 				printf("Process (pid %lu) got signal %d\n",
1366 					(u_long)p->p_pid, sig);
1367 #endif
1368 				break;		/* == ignore */
1369 			}
1370 
1371 			/*
1372 			 * Handle the in-kernel checkpoint action
1373 			 */
1374 			if (prop & SA_CKPT) {
1375 				checkpoint_signal_handler(p);
1376 				break;
1377 			}
1378 
1379 			/*
1380 			 * If there is a pending stop signal to process
1381 			 * with default action, stop here,
1382 			 * then clear the signal.  However,
1383 			 * if process is member of an orphaned
1384 			 * process group, ignore tty stop signals.
1385 			 */
1386 			if (prop & SA_STOP) {
1387 				if (p->p_flag & P_TRACED ||
1388 		    		    (p->p_pgrp->pg_jobc == 0 &&
1389 				    prop & SA_TTYSTOP))
1390 					break;	/* == ignore */
1391 				p->p_xstat = sig;
1392 				p->p_flag |= P_STOPPED;
1393 				p->p_flag &= ~P_WAITED;
1394 
1395 				if ((p->p_pptr->p_procsig->ps_flag & PS_NOCLDSTOP) == 0)
1396 					ksignal(p->p_pptr, SIGCHLD);
1397 				while (p->p_flag & P_STOPPED) {
1398 					tstop(p);
1399 				}
1400 				break;
1401 			} else if (prop & SA_IGNORE) {
1402 				/*
1403 				 * Except for SIGCONT, shouldn't get here.
1404 				 * Default action is to ignore; drop it.
1405 				 */
1406 				break;		/* == ignore */
1407 			} else {
1408 				rel_mplock();
1409 				return (sig);
1410 			}
1411 
1412 			/*NOTREACHED*/
1413 
1414 		case (int)SIG_IGN:
1415 			/*
1416 			 * Masking above should prevent us ever trying
1417 			 * to take action on an ignored signal other
1418 			 * than SIGCONT, unless process is traced.
1419 			 */
1420 			if ((prop & SA_CONT) == 0 &&
1421 			    (p->p_flag & P_TRACED) == 0)
1422 				printf("issignal\n");
1423 			break;		/* == ignore */
1424 
1425 		default:
1426 			/*
1427 			 * This signal has an action, let
1428 			 * postsig() process it.
1429 			 */
1430 			rel_mplock();
1431 			return (sig);
1432 		}
1433 		SIGDELSET(p->p_siglist, sig);		/* take the signal! */
1434 	}
1435 	/* NOTREACHED */
1436 }
1437 
1438 /*
1439  * Take the action for the specified signal
1440  * from the current set of pending signals.
1441  */
1442 void
1443 postsig(int sig)
1444 {
1445 	struct thread *td = curthread;
1446 	struct proc *p = td->td_proc;
1447 	struct sigacts *ps = p->p_sigacts;
1448 	sig_t action;
1449 	sigset_t returnmask;
1450 	int code;
1451 
1452 	KASSERT(sig != 0, ("postsig"));
1453 
1454 	SIGDELSET(p->p_siglist, sig);
1455 	action = ps->ps_sigact[_SIG_IDX(sig)];
1456 #ifdef KTRACE
1457 	if (KTRPOINT(td, KTR_PSIG))
1458 		ktrpsig(p, sig, action, p->p_flag & P_OLDMASK ?
1459 			&p->p_oldsigmask : &p->p_sigmask, 0);
1460 #endif
1461 	STOPEVENT(p, S_SIG, sig);
1462 
1463 	if (action == SIG_DFL) {
1464 		/*
1465 		 * Default action, where the default is to kill
1466 		 * the process.  (Other cases were ignored above.)
1467 		 */
1468 		sigexit(p, sig);
1469 		/* NOTREACHED */
1470 	} else {
1471 		/*
1472 		 * If we get here, the signal must be caught.
1473 		 */
1474 		KASSERT(action != SIG_IGN && !SIGISMEMBER(p->p_sigmask, sig),
1475 		    ("postsig action"));
1476 		/*
1477 		 * Set the new mask value and also defer further
1478 		 * occurrences of this signal.
1479 		 *
1480 		 * Special case: user has done a sigsuspend.  Here the
1481 		 * current mask is not of interest, but rather the
1482 		 * mask from before the sigsuspend is what we want
1483 		 * restored after the signal processing is completed.
1484 		 */
1485 		crit_enter();
1486 		if (p->p_flag & P_OLDMASK) {
1487 			returnmask = p->p_oldsigmask;
1488 			p->p_flag &= ~P_OLDMASK;
1489 		} else {
1490 			returnmask = p->p_sigmask;
1491 		}
1492 
1493 		SIGSETOR(p->p_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
1494 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
1495 			SIGADDSET(p->p_sigmask, sig);
1496 
1497 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
1498 			/*
1499 			 * See kern_sigaction() for origin of this code.
1500 			 */
1501 			SIGDELSET(p->p_sigcatch, sig);
1502 			if (sig != SIGCONT &&
1503 			    sigprop(sig) & SA_IGNORE)
1504 				SIGADDSET(p->p_sigignore, sig);
1505 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1506 		}
1507 		crit_exit();
1508 		p->p_stats->p_ru.ru_nsignals++;
1509 		if (p->p_sig != sig) {
1510 			code = 0;
1511 		} else {
1512 			code = p->p_code;
1513 			p->p_code = 0;
1514 			p->p_sig = 0;
1515 		}
1516 		(*p->p_sysent->sv_sendsig)(action, sig, &returnmask, code);
1517 	}
1518 }
1519 
1520 /*
1521  * Kill the current process for stated reason.
1522  */
1523 void
1524 killproc(struct proc *p, char *why)
1525 {
1526 	log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n", p->p_pid, p->p_comm,
1527 		p->p_ucred ? p->p_ucred->cr_uid : -1, why);
1528 	ksignal(p, SIGKILL);
1529 }
1530 
1531 /*
1532  * Force the current process to exit with the specified signal, dumping core
1533  * if appropriate.  We bypass the normal tests for masked and caught signals,
1534  * allowing unrecoverable failures to terminate the process without changing
1535  * signal state.  Mark the accounting record with the signal termination.
1536  * If dumping core, save the signal number for the debugger.  Calls exit and
1537  * does not return.
1538  */
1539 void
1540 sigexit(struct proc *p, int sig)
1541 {
1542 	p->p_acflag |= AXSIG;
1543 	if (sigprop(sig) & SA_CORE) {
1544 		p->p_sig = sig;
1545 		/*
1546 		 * Log signals which would cause core dumps
1547 		 * (Log as LOG_INFO to appease those who don't want
1548 		 * these messages.)
1549 		 * XXX : Todo, as well as euid, write out ruid too
1550 		 */
1551 		if (coredump(p) == 0)
1552 			sig |= WCOREFLAG;
1553 		if (kern_logsigexit)
1554 			log(LOG_INFO,
1555 			    "pid %d (%s), uid %d: exited on signal %d%s\n",
1556 			    p->p_pid, p->p_comm,
1557 			    p->p_ucred ? p->p_ucred->cr_uid : -1,
1558 			    sig &~ WCOREFLAG,
1559 			    sig & WCOREFLAG ? " (core dumped)" : "");
1560 	}
1561 	exit1(W_EXITCODE(0, sig));
1562 	/* NOTREACHED */
1563 }
1564 
1565 static char corefilename[MAXPATHLEN+1] = {"%N.core"};
1566 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RW, corefilename,
1567 	      sizeof(corefilename), "process corefile name format string");
1568 
1569 /*
1570  * expand_name(name, uid, pid)
1571  * Expand the name described in corefilename, using name, uid, and pid.
1572  * corefilename is a printf-like string, with three format specifiers:
1573  *	%N	name of process ("name")
1574  *	%P	process id (pid)
1575  *	%U	user id (uid)
1576  * For example, "%N.core" is the default; they can be disabled completely
1577  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
1578  * This is controlled by the sysctl variable kern.corefile (see above).
1579  */
1580 
1581 static char *
1582 expand_name(const char *name, uid_t uid, pid_t pid)
1583 {
1584 	char *temp;
1585 	char buf[11];		/* Buffer for pid/uid -- max 4B */
1586 	int i, n;
1587 	char *format = corefilename;
1588 	size_t namelen;
1589 
1590 	temp = kmalloc(MAXPATHLEN + 1, M_TEMP, M_NOWAIT);
1591 	if (temp == NULL)
1592 		return NULL;
1593 	namelen = strlen(name);
1594 	for (i = 0, n = 0; n < MAXPATHLEN && format[i]; i++) {
1595 		int l;
1596 		switch (format[i]) {
1597 		case '%':	/* Format character */
1598 			i++;
1599 			switch (format[i]) {
1600 			case '%':
1601 				temp[n++] = '%';
1602 				break;
1603 			case 'N':	/* process name */
1604 				if ((n + namelen) > MAXPATHLEN) {
1605 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
1606 					    pid, name, uid, temp, name);
1607 					kfree(temp, M_TEMP);
1608 					return NULL;
1609 				}
1610 				memcpy(temp+n, name, namelen);
1611 				n += namelen;
1612 				break;
1613 			case 'P':	/* process id */
1614 				l = sprintf(buf, "%u", pid);
1615 				if ((n + l) > MAXPATHLEN) {
1616 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
1617 					    pid, name, uid, temp, name);
1618 					kfree(temp, M_TEMP);
1619 					return NULL;
1620 				}
1621 				memcpy(temp+n, buf, l);
1622 				n += l;
1623 				break;
1624 			case 'U':	/* user id */
1625 				l = sprintf(buf, "%u", uid);
1626 				if ((n + l) > MAXPATHLEN) {
1627 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
1628 					    pid, name, uid, temp, name);
1629 					kfree(temp, M_TEMP);
1630 					return NULL;
1631 				}
1632 				memcpy(temp+n, buf, l);
1633 				n += l;
1634 				break;
1635 			default:
1636 			  	log(LOG_ERR, "Unknown format character %c in `%s'\n", format[i], format);
1637 			}
1638 			break;
1639 		default:
1640 			temp[n++] = format[i];
1641 		}
1642 	}
1643 	temp[n] = '\0';
1644 	return temp;
1645 }
1646 
1647 /*
1648  * Dump a process' core.  The main routine does some
1649  * policy checking, and creates the name of the coredump;
1650  * then it passes on a vnode and a size limit to the process-specific
1651  * coredump routine if there is one; if there _is not_ one, it returns
1652  * ENOSYS; otherwise it returns the error from the process-specific routine.
1653  */
1654 
1655 static int
1656 coredump(struct proc *p)
1657 {
1658 	struct vnode *vp;
1659 	struct ucred *cred = p->p_ucred;
1660 	struct flock lf;
1661 	struct nlookupdata nd;
1662 	struct vattr vattr;
1663 	int error, error1;
1664 	char *name;			/* name of corefile */
1665 	off_t limit;
1666 
1667 	STOPEVENT(p, S_CORE, 0);
1668 
1669 	if (((sugid_coredump == 0) && p->p_flag & P_SUGID) || do_coredump == 0)
1670 		return (EFAULT);
1671 
1672 	/*
1673 	 * Note that the bulk of limit checking is done after
1674 	 * the corefile is created.  The exception is if the limit
1675 	 * for corefiles is 0, in which case we don't bother
1676 	 * creating the corefile at all.  This layout means that
1677 	 * a corefile is truncated instead of not being created,
1678 	 * if it is larger than the limit.
1679 	 */
1680 	limit = p->p_rlimit[RLIMIT_CORE].rlim_cur;
1681 	if (limit == 0)
1682 		return EFBIG;
1683 
1684 	name = expand_name(p->p_comm, p->p_ucred->cr_uid, p->p_pid);
1685 	if (name == NULL)
1686 		return (EINVAL);
1687 	error = nlookup_init(&nd, name, UIO_SYSSPACE, NLC_LOCKVP);
1688 	if (error == 0)
1689 		error = vn_open(&nd, NULL, O_CREAT | FWRITE | O_NOFOLLOW, S_IRUSR | S_IWUSR);
1690 	kfree(name, M_TEMP);
1691 	if (error) {
1692 		nlookup_done(&nd);
1693 		return (error);
1694 	}
1695 	vp = nd.nl_open_vp;
1696 	nd.nl_open_vp = NULL;
1697 	nlookup_done(&nd);
1698 
1699 	vn_unlock(vp);
1700 	lf.l_whence = SEEK_SET;
1701 	lf.l_start = 0;
1702 	lf.l_len = 0;
1703 	lf.l_type = F_WRLCK;
1704 	error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, 0);
1705 	if (error)
1706 		goto out2;
1707 
1708 	/* Don't dump to non-regular files or files with links. */
1709 	if (vp->v_type != VREG ||
1710 	    VOP_GETATTR(vp, &vattr) || vattr.va_nlink != 1) {
1711 		error = EFAULT;
1712 		goto out1;
1713 	}
1714 
1715 	VATTR_NULL(&vattr);
1716 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1717 	vattr.va_size = 0;
1718 	VOP_SETATTR(vp, &vattr, cred);
1719 	p->p_acflag |= ACORE;
1720 	vn_unlock(vp);
1721 
1722 	error = p->p_sysent->sv_coredump ?
1723 		  p->p_sysent->sv_coredump(p, vp, limit) : ENOSYS;
1724 
1725 out1:
1726 	lf.l_type = F_UNLCK;
1727 	VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, 0);
1728 out2:
1729 	error1 = vn_close(vp, FWRITE);
1730 	if (error == 0)
1731 		error = error1;
1732 	return (error);
1733 }
1734 
1735 /*
1736  * Nonexistent system call-- signal process (may want to handle it).
1737  * Flag error in case process won't see signal immediately (blocked or ignored).
1738  */
1739 /* ARGSUSED */
1740 int
1741 sys_nosys(struct nosys_args *args)
1742 {
1743 	ksignal(curproc, SIGSYS);
1744 	return (EINVAL);
1745 }
1746 
1747 /*
1748  * Send a SIGIO or SIGURG signal to a process or process group using
1749  * stored credentials rather than those of the current process.
1750  */
1751 void
1752 pgsigio(struct sigio *sigio, int sig, int checkctty)
1753 {
1754 	if (sigio == NULL)
1755 		return;
1756 
1757 	if (sigio->sio_pgid > 0) {
1758 		if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred,
1759 		             sigio->sio_proc))
1760 			ksignal(sigio->sio_proc, sig);
1761 	} else if (sigio->sio_pgid < 0) {
1762 		struct proc *p;
1763 
1764 		lockmgr(&sigio->sio_pgrp->pg_lock, LK_EXCLUSIVE);
1765 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
1766 			if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred, p) &&
1767 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
1768 				ksignal(p, sig);
1769 		}
1770 		lockmgr(&sigio->sio_pgrp->pg_lock, LK_RELEASE);
1771 	}
1772 }
1773 
1774 static int
1775 filt_sigattach(struct knote *kn)
1776 {
1777 	struct proc *p = curproc;
1778 
1779 	kn->kn_ptr.p_proc = p;
1780 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
1781 
1782 	/* XXX lock the proc here while adding to the list? */
1783 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
1784 
1785 	return (0);
1786 }
1787 
1788 static void
1789 filt_sigdetach(struct knote *kn)
1790 {
1791 	struct proc *p = kn->kn_ptr.p_proc;
1792 
1793 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
1794 }
1795 
1796 /*
1797  * signal knotes are shared with proc knotes, so we apply a mask to
1798  * the hint in order to differentiate them from process hints.  This
1799  * could be avoided by using a signal-specific knote list, but probably
1800  * isn't worth the trouble.
1801  */
1802 static int
1803 filt_signal(struct knote *kn, long hint)
1804 {
1805 	if (hint & NOTE_SIGNAL) {
1806 		hint &= ~NOTE_SIGNAL;
1807 
1808 		if (kn->kn_id == hint)
1809 			kn->kn_data++;
1810 	}
1811 	return (kn->kn_data != 0);
1812 }
1813