xref: /dflybsd-src/sys/kern/kern_sig.c (revision 90ea502b8c5d21f908cedff6680ee2bc9e74ce74)
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.90 2008/06/09 04:33:08 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/signal2.h>
51 #include <sys/resourcevar.h>
52 #include <sys/vnode.h>
53 #include <sys/event.h>
54 #include <sys/proc.h>
55 #include <sys/nlookup.h>
56 #include <sys/pioctl.h>
57 #include <sys/systm.h>
58 #include <sys/acct.h>
59 #include <sys/fcntl.h>
60 #include <sys/lock.h>
61 #include <sys/wait.h>
62 #include <sys/ktrace.h>
63 #include <sys/syslog.h>
64 #include <sys/stat.h>
65 #include <sys/sysent.h>
66 #include <sys/sysctl.h>
67 #include <sys/malloc.h>
68 #include <sys/interrupt.h>
69 #include <sys/unistd.h>
70 #include <sys/kern_syscall.h>
71 #include <sys/vkernel.h>
72 #include <sys/thread2.h>
73 
74 #include <machine/cpu.h>
75 #include <machine/smp.h>
76 
77 static int	coredump(struct lwp *, int);
78 static char	*expand_name(const char *, uid_t, pid_t);
79 static int	dokillpg(int sig, int pgid, int all);
80 static int	sig_ffs(sigset_t *set);
81 static int	sigprop(int sig);
82 #ifdef SMP
83 static void	signotify_remote(void *arg);
84 #endif
85 static int	kern_sigtimedwait(sigset_t set, siginfo_t *info,
86 		    struct timespec *timeout);
87 
88 static int	filt_sigattach(struct knote *kn);
89 static void	filt_sigdetach(struct knote *kn);
90 static int	filt_signal(struct knote *kn, long hint);
91 
92 struct filterops sig_filtops =
93 	{ 0, filt_sigattach, filt_sigdetach, filt_signal };
94 
95 static int	kern_logsigexit = 1;
96 SYSCTL_INT(_kern, KERN_LOGSIGEXIT, logsigexit, CTLFLAG_RW,
97     &kern_logsigexit, 0,
98     "Log processes quitting on abnormal signals to syslog(3)");
99 
100 /*
101  * Can process p, with pcred pc, send the signal sig to process q?
102  */
103 #define CANSIGNAL(q, sig) \
104 	(!p_trespass(curproc->p_ucred, (q)->p_ucred) || \
105 	((sig) == SIGCONT && (q)->p_session == curproc->p_session))
106 
107 /*
108  * Policy -- Can real uid ruid with ucred uc send a signal to process q?
109  */
110 #define CANSIGIO(ruid, uc, q) \
111 	((uc)->cr_uid == 0 || \
112 	    (ruid) == (q)->p_ucred->cr_ruid || \
113 	    (uc)->cr_uid == (q)->p_ucred->cr_ruid || \
114 	    (ruid) == (q)->p_ucred->cr_uid || \
115 	    (uc)->cr_uid == (q)->p_ucred->cr_uid)
116 
117 int sugid_coredump;
118 SYSCTL_INT(_kern, OID_AUTO, sugid_coredump, CTLFLAG_RW,
119 	&sugid_coredump, 0, "Enable coredumping set user/group ID processes");
120 
121 static int	do_coredump = 1;
122 SYSCTL_INT(_kern, OID_AUTO, coredump, CTLFLAG_RW,
123 	&do_coredump, 0, "Enable/Disable coredumps");
124 
125 /*
126  * Signal properties and actions.
127  * The array below categorizes the signals and their default actions
128  * according to the following properties:
129  */
130 #define	SA_KILL		0x01		/* terminates process by default */
131 #define	SA_CORE		0x02		/* ditto and coredumps */
132 #define	SA_STOP		0x04		/* suspend process */
133 #define	SA_TTYSTOP	0x08		/* ditto, from tty */
134 #define	SA_IGNORE	0x10		/* ignore by default */
135 #define	SA_CONT		0x20		/* continue if suspended */
136 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
137 #define SA_CKPT         0x80            /* checkpoint process */
138 
139 
140 static int sigproptbl[NSIG] = {
141         SA_KILL,                /* SIGHUP */
142         SA_KILL,                /* SIGINT */
143         SA_KILL|SA_CORE,        /* SIGQUIT */
144         SA_KILL|SA_CORE,        /* SIGILL */
145         SA_KILL|SA_CORE,        /* SIGTRAP */
146         SA_KILL|SA_CORE,        /* SIGABRT */
147         SA_KILL|SA_CORE,        /* SIGEMT */
148         SA_KILL|SA_CORE,        /* SIGFPE */
149         SA_KILL,                /* SIGKILL */
150         SA_KILL|SA_CORE,        /* SIGBUS */
151         SA_KILL|SA_CORE,        /* SIGSEGV */
152         SA_KILL|SA_CORE,        /* SIGSYS */
153         SA_KILL,                /* SIGPIPE */
154         SA_KILL,                /* SIGALRM */
155         SA_KILL,                /* SIGTERM */
156         SA_IGNORE,              /* SIGURG */
157         SA_STOP,                /* SIGSTOP */
158         SA_STOP|SA_TTYSTOP,     /* SIGTSTP */
159         SA_IGNORE|SA_CONT,      /* SIGCONT */
160         SA_IGNORE,              /* SIGCHLD */
161         SA_STOP|SA_TTYSTOP,     /* SIGTTIN */
162         SA_STOP|SA_TTYSTOP,     /* SIGTTOU */
163         SA_IGNORE,              /* SIGIO */
164         SA_KILL,                /* SIGXCPU */
165         SA_KILL,                /* SIGXFSZ */
166         SA_KILL,                /* SIGVTALRM */
167         SA_KILL,                /* SIGPROF */
168         SA_IGNORE,              /* SIGWINCH  */
169         SA_IGNORE,              /* SIGINFO */
170         SA_KILL,                /* SIGUSR1 */
171         SA_KILL,                /* SIGUSR2 */
172 	SA_IGNORE,              /* SIGTHR */
173 	SA_CKPT,                /* SIGCKPT */
174 	SA_KILL|SA_CKPT,        /* SIGCKPTEXIT */
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 	SA_IGNORE,
205 
206 };
207 
208 static __inline int
209 sigprop(int sig)
210 {
211 
212 	if (sig > 0 && sig < NSIG)
213 		return (sigproptbl[_SIG_IDX(sig)]);
214 	return (0);
215 }
216 
217 static __inline int
218 sig_ffs(sigset_t *set)
219 {
220 	int i;
221 
222 	for (i = 0; i < _SIG_WORDS; i++)
223 		if (set->__bits[i])
224 			return (ffs(set->__bits[i]) + (i * 32));
225 	return (0);
226 }
227 
228 int
229 kern_sigaction(int sig, struct sigaction *act, struct sigaction *oact)
230 {
231 	struct thread *td = curthread;
232 	struct proc *p = td->td_proc;
233 	struct lwp *lp;
234 	struct sigacts *ps = p->p_sigacts;
235 
236 	if (sig <= 0 || sig > _SIG_MAXSIG)
237 		return (EINVAL);
238 
239 	if (oact) {
240 		oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
241 		oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
242 		oact->sa_flags = 0;
243 		if (SIGISMEMBER(ps->ps_sigonstack, sig))
244 			oact->sa_flags |= SA_ONSTACK;
245 		if (!SIGISMEMBER(ps->ps_sigintr, sig))
246 			oact->sa_flags |= SA_RESTART;
247 		if (SIGISMEMBER(ps->ps_sigreset, sig))
248 			oact->sa_flags |= SA_RESETHAND;
249 		if (SIGISMEMBER(ps->ps_signodefer, sig))
250 			oact->sa_flags |= SA_NODEFER;
251 		if (SIGISMEMBER(ps->ps_siginfo, sig))
252 			oact->sa_flags |= SA_SIGINFO;
253 		if (SIGISMEMBER(ps->ps_sigmailbox, sig))
254 			oact->sa_flags |= SA_MAILBOX;
255 		if (sig == SIGCHLD && p->p_sigacts->ps_flag & PS_NOCLDSTOP)
256 			oact->sa_flags |= SA_NOCLDSTOP;
257 		if (sig == SIGCHLD && p->p_sigacts->ps_flag & PS_NOCLDWAIT)
258 			oact->sa_flags |= SA_NOCLDWAIT;
259 	}
260 	if (act) {
261 		/*
262 		 * Check for invalid requests.  KILL and STOP cannot be
263 		 * caught.
264 		 */
265 		if (sig == SIGKILL || sig == SIGSTOP) {
266 			if (act->sa_handler != SIG_DFL)
267 				return (EINVAL);
268 #if 0
269 			/* (not needed, SIG_DFL forces action to occur) */
270 			if (act->sa_flags & SA_MAILBOX)
271 				return (EINVAL);
272 #endif
273 		}
274 
275 		/*
276 		 * Change setting atomically.
277 		 */
278 		crit_enter();
279 
280 		ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
281 		SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
282 		if (act->sa_flags & SA_SIGINFO) {
283 			ps->ps_sigact[_SIG_IDX(sig)] =
284 			    (__sighandler_t *)act->sa_sigaction;
285 			SIGADDSET(ps->ps_siginfo, sig);
286 		} else {
287 			ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
288 			SIGDELSET(ps->ps_siginfo, sig);
289 		}
290 		if (!(act->sa_flags & SA_RESTART))
291 			SIGADDSET(ps->ps_sigintr, sig);
292 		else
293 			SIGDELSET(ps->ps_sigintr, sig);
294 		if (act->sa_flags & SA_ONSTACK)
295 			SIGADDSET(ps->ps_sigonstack, sig);
296 		else
297 			SIGDELSET(ps->ps_sigonstack, sig);
298 		if (act->sa_flags & SA_RESETHAND)
299 			SIGADDSET(ps->ps_sigreset, sig);
300 		else
301 			SIGDELSET(ps->ps_sigreset, sig);
302 		if (act->sa_flags & SA_NODEFER)
303 			SIGADDSET(ps->ps_signodefer, sig);
304 		else
305 			SIGDELSET(ps->ps_signodefer, sig);
306 		if (act->sa_flags & SA_MAILBOX)
307 			SIGADDSET(ps->ps_sigmailbox, sig);
308 		else
309 			SIGDELSET(ps->ps_sigmailbox, sig);
310 		if (sig == SIGCHLD) {
311 			if (act->sa_flags & SA_NOCLDSTOP)
312 				p->p_sigacts->ps_flag |= PS_NOCLDSTOP;
313 			else
314 				p->p_sigacts->ps_flag &= ~PS_NOCLDSTOP;
315 			if (act->sa_flags & SA_NOCLDWAIT) {
316 				/*
317 				 * Paranoia: since SA_NOCLDWAIT is implemented
318 				 * by reparenting the dying child to PID 1 (and
319 				 * trust it to reap the zombie), PID 1 itself
320 				 * is forbidden to set SA_NOCLDWAIT.
321 				 */
322 				if (p->p_pid == 1)
323 					p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
324 				else
325 					p->p_sigacts->ps_flag |= PS_NOCLDWAIT;
326 			} else {
327 				p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
328 			}
329 		}
330 		/*
331 		 * Set bit in p_sigignore for signals that are set to SIG_IGN,
332 		 * and for signals set to SIG_DFL where the default is to
333 		 * ignore. However, don't put SIGCONT in p_sigignore, as we
334 		 * have to restart the process.
335 		 */
336 		if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
337 		    (sigprop(sig) & SA_IGNORE &&
338 		     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
339 			/* never to be seen again */
340 			SIGDELSET(p->p_siglist, sig);
341 			/*
342 			 * Remove the signal also from the thread lists.
343 			 */
344 			FOREACH_LWP_IN_PROC(lp, p) {
345 				SIGDELSET(lp->lwp_siglist, sig);
346 			}
347 			if (sig != SIGCONT)
348 				/* easier in ksignal */
349 				SIGADDSET(p->p_sigignore, sig);
350 			SIGDELSET(p->p_sigcatch, sig);
351 		} else {
352 			SIGDELSET(p->p_sigignore, sig);
353 			if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
354 				SIGDELSET(p->p_sigcatch, sig);
355 			else
356 				SIGADDSET(p->p_sigcatch, sig);
357 		}
358 
359 		crit_exit();
360 	}
361 	return (0);
362 }
363 
364 /*
365  * MPALMOSTSAFE
366  */
367 int
368 sys_sigaction(struct sigaction_args *uap)
369 {
370 	struct sigaction act, oact;
371 	struct sigaction *actp, *oactp;
372 	int error;
373 
374 	actp = (uap->act != NULL) ? &act : NULL;
375 	oactp = (uap->oact != NULL) ? &oact : NULL;
376 	if (actp) {
377 		error = copyin(uap->act, actp, sizeof(act));
378 		if (error)
379 			return (error);
380 	}
381 	get_mplock();
382 	error = kern_sigaction(uap->sig, actp, oactp);
383 	rel_mplock();
384 	if (oactp && !error) {
385 		error = copyout(oactp, uap->oact, sizeof(oact));
386 	}
387 	return (error);
388 }
389 
390 /*
391  * Initialize signal state for process 0;
392  * set to ignore signals that are ignored by default.
393  */
394 void
395 siginit(struct proc *p)
396 {
397 	int i;
398 
399 	for (i = 1; i <= NSIG; i++)
400 		if (sigprop(i) & SA_IGNORE && i != SIGCONT)
401 			SIGADDSET(p->p_sigignore, i);
402 }
403 
404 /*
405  * Reset signals for an exec of the specified process.
406  */
407 void
408 execsigs(struct proc *p)
409 {
410 	struct sigacts *ps = p->p_sigacts;
411 	struct lwp *lp;
412 	int sig;
413 
414 	lp = ONLY_LWP_IN_PROC(p);
415 
416 	/*
417 	 * Reset caught signals.  Held signals remain held
418 	 * through p_sigmask (unless they were caught,
419 	 * and are now ignored by default).
420 	 */
421 	while (SIGNOTEMPTY(p->p_sigcatch)) {
422 		sig = sig_ffs(&p->p_sigcatch);
423 		SIGDELSET(p->p_sigcatch, sig);
424 		if (sigprop(sig) & SA_IGNORE) {
425 			if (sig != SIGCONT)
426 				SIGADDSET(p->p_sigignore, sig);
427 			SIGDELSET(p->p_siglist, sig);
428 			SIGDELSET(lp->lwp_siglist, sig);
429 		}
430 		ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
431 	}
432 
433 	/*
434 	 * Reset stack state to the user stack.
435 	 * Clear set of signals caught on the signal stack.
436 	 */
437 	lp->lwp_sigstk.ss_flags = SS_DISABLE;
438 	lp->lwp_sigstk.ss_size = 0;
439 	lp->lwp_sigstk.ss_sp = 0;
440 	lp->lwp_flag &= ~LWP_ALTSTACK;
441 	/*
442 	 * Reset no zombies if child dies flag as Solaris does.
443 	 */
444 	p->p_sigacts->ps_flag &= ~PS_NOCLDWAIT;
445 }
446 
447 /*
448  * kern_sigprocmask() - MP SAFE ONLY IF p == curproc
449  *
450  *	Manipulate signal mask.  This routine is MP SAFE *ONLY* if
451  *	p == curproc.
452  */
453 int
454 kern_sigprocmask(int how, sigset_t *set, sigset_t *oset)
455 {
456 	struct thread *td = curthread;
457 	struct lwp *lp = td->td_lwp;
458 	int error;
459 
460 	if (oset != NULL)
461 		*oset = lp->lwp_sigmask;
462 
463 	error = 0;
464 	if (set != NULL) {
465 		switch (how) {
466 		case SIG_BLOCK:
467 			SIG_CANTMASK(*set);
468 			SIGSETOR(lp->lwp_sigmask, *set);
469 			break;
470 		case SIG_UNBLOCK:
471 			SIGSETNAND(lp->lwp_sigmask, *set);
472 			break;
473 		case SIG_SETMASK:
474 			SIG_CANTMASK(*set);
475 			lp->lwp_sigmask = *set;
476 			break;
477 		default:
478 			error = EINVAL;
479 			break;
480 		}
481 	}
482 	return (error);
483 }
484 
485 /*
486  * sigprocmask()
487  *
488  * MPSAFE
489  */
490 int
491 sys_sigprocmask(struct sigprocmask_args *uap)
492 {
493 	sigset_t set, oset;
494 	sigset_t *setp, *osetp;
495 	int error;
496 
497 	setp = (uap->set != NULL) ? &set : NULL;
498 	osetp = (uap->oset != NULL) ? &oset : NULL;
499 	if (setp) {
500 		error = copyin(uap->set, setp, sizeof(set));
501 		if (error)
502 			return (error);
503 	}
504 	error = kern_sigprocmask(uap->how, setp, osetp);
505 	if (osetp && !error) {
506 		error = copyout(osetp, uap->oset, sizeof(oset));
507 	}
508 	return (error);
509 }
510 
511 /*
512  * MPSAFE
513  */
514 int
515 kern_sigpending(struct __sigset *set)
516 {
517 	struct lwp *lp = curthread->td_lwp;
518 
519 	*set = lwp_sigpend(lp);
520 
521 	return (0);
522 }
523 
524 /*
525  * MPSAFE
526  */
527 int
528 sys_sigpending(struct sigpending_args *uap)
529 {
530 	sigset_t set;
531 	int error;
532 
533 	error = kern_sigpending(&set);
534 
535 	if (error == 0)
536 		error = copyout(&set, uap->set, sizeof(set));
537 	return (error);
538 }
539 
540 /*
541  * Suspend process until signal, providing mask to be set
542  * in the meantime.
543  *
544  * MPSAFE
545  */
546 int
547 kern_sigsuspend(struct __sigset *set)
548 {
549 	struct thread *td = curthread;
550 	struct lwp *lp = td->td_lwp;
551 	struct proc *p = td->td_proc;
552 	struct sigacts *ps = p->p_sigacts;
553 
554 	/*
555 	 * When returning from sigsuspend, we want
556 	 * the old mask to be restored after the
557 	 * signal handler has finished.  Thus, we
558 	 * save it here and mark the sigacts structure
559 	 * to indicate this.
560 	 */
561 	lp->lwp_oldsigmask = lp->lwp_sigmask;
562 	lp->lwp_flag |= LWP_OLDMASK;
563 
564 	SIG_CANTMASK(*set);
565 	lp->lwp_sigmask = *set;
566 	while (tsleep(ps, PCATCH, "pause", 0) == 0)
567 		/* void */;
568 	/* always return EINTR rather than ERESTART... */
569 	return (EINTR);
570 }
571 
572 /*
573  * Note nonstandard calling convention: libc stub passes mask, not
574  * pointer, to save a copyin.
575  *
576  * MPSAFE
577  */
578 int
579 sys_sigsuspend(struct sigsuspend_args *uap)
580 {
581 	sigset_t mask;
582 	int error;
583 
584 	error = copyin(uap->sigmask, &mask, sizeof(mask));
585 	if (error)
586 		return (error);
587 
588 	error = kern_sigsuspend(&mask);
589 
590 	return (error);
591 }
592 
593 /*
594  * MPSAFE
595  */
596 int
597 kern_sigaltstack(struct sigaltstack *ss, struct sigaltstack *oss)
598 {
599 	struct thread *td = curthread;
600 	struct lwp *lp = td->td_lwp;
601 	struct proc *p = td->td_proc;
602 
603 	if ((lp->lwp_flag & LWP_ALTSTACK) == 0)
604 		lp->lwp_sigstk.ss_flags |= SS_DISABLE;
605 
606 	if (oss)
607 		*oss = lp->lwp_sigstk;
608 
609 	if (ss) {
610 		if (ss->ss_flags & SS_DISABLE) {
611 			if (lp->lwp_sigstk.ss_flags & SS_ONSTACK)
612 				return (EINVAL);
613 			lp->lwp_flag &= ~LWP_ALTSTACK;
614 			lp->lwp_sigstk.ss_flags = ss->ss_flags;
615 		} else {
616 			if (ss->ss_size < p->p_sysent->sv_minsigstksz)
617 				return (ENOMEM);
618 			lp->lwp_flag |= LWP_ALTSTACK;
619 			lp->lwp_sigstk = *ss;
620 		}
621 	}
622 
623 	return (0);
624 }
625 
626 /*
627  * MPSAFE
628  */
629 int
630 sys_sigaltstack(struct sigaltstack_args *uap)
631 {
632 	stack_t ss, oss;
633 	int error;
634 
635 	if (uap->ss) {
636 		error = copyin(uap->ss, &ss, sizeof(ss));
637 		if (error)
638 			return (error);
639 	}
640 
641 	error = kern_sigaltstack(uap->ss ? &ss : NULL,
642 	    uap->oss ? &oss : NULL);
643 
644 	if (error == 0 && uap->oss)
645 		error = copyout(&oss, uap->oss, sizeof(*uap->oss));
646 	return (error);
647 }
648 
649 /*
650  * Common code for kill process group/broadcast kill.
651  * cp is calling process.
652  */
653 struct killpg_info {
654 	int nfound;
655 	int sig;
656 };
657 
658 static int killpg_all_callback(struct proc *p, void *data);
659 
660 static int
661 dokillpg(int sig, int pgid, int all)
662 {
663 	struct killpg_info info;
664 	struct proc *cp = curproc;
665 	struct proc *p;
666 	struct pgrp *pgrp;
667 
668 	info.nfound = 0;
669 	info.sig = sig;
670 
671 	if (all) {
672 		/*
673 		 * broadcast
674 		 */
675 		allproc_scan(killpg_all_callback, &info);
676 	} else {
677 		if (pgid == 0) {
678 			/*
679 			 * zero pgid means send to my process group.
680 			 */
681 			pgrp = cp->p_pgrp;
682 		} else {
683 			pgrp = pgfind(pgid);
684 			if (pgrp == NULL)
685 				return (ESRCH);
686 		}
687 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
688 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
689 			if (p->p_pid <= 1 ||
690 			    p->p_stat == SZOMB ||
691 			    (p->p_flag & P_SYSTEM) ||
692 			    !CANSIGNAL(p, sig)) {
693 				continue;
694 			}
695 			++info.nfound;
696 			if (sig)
697 				ksignal(p, sig);
698 		}
699 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
700 	}
701 	return (info.nfound ? 0 : ESRCH);
702 }
703 
704 static int
705 killpg_all_callback(struct proc *p, void *data)
706 {
707 	struct killpg_info *info = data;
708 
709 	if (p->p_pid <= 1 || (p->p_flag & P_SYSTEM) ||
710 	    p == curproc || !CANSIGNAL(p, info->sig)) {
711 		return (0);
712 	}
713 	++info->nfound;
714 	if (info->sig)
715 		ksignal(p, info->sig);
716 	return(0);
717 }
718 
719 /*
720  * Send a general signal to a process or LWPs within that process.  Note
721  * that new signals cannot be sent if a process is exiting.
722  */
723 int
724 kern_kill(int sig, pid_t pid, lwpid_t tid)
725 {
726 	if ((u_int)sig > _SIG_MAXSIG)
727 		return (EINVAL);
728 	if (pid > 0) {
729 		struct proc *p;
730 		struct lwp *lp = NULL;
731 
732 		/* kill single process */
733 		if ((p = pfind(pid)) == NULL)
734 			return (ESRCH);
735 		if (!CANSIGNAL(p, sig))
736 			return (EPERM);
737 
738 		/*
739 		 * NOP if the process is exiting.  Note that lwpsignal() is
740 		 * called directly with P_WEXIT set to kill individual LWPs
741 		 * during exit, which is allowed.
742 		 */
743 		if (p->p_flag & P_WEXIT)
744 			return (0);
745 		if (tid != -1) {
746 			lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, tid);
747 			if (lp == NULL)
748 				return (ESRCH);
749 		}
750 		if (sig)
751 			lwpsignal(p, lp, sig);
752 		return (0);
753 	}
754 	/*
755 	 * If we come here, pid is a special broadcast pid.
756 	 * This doesn't mix with a tid.
757 	 */
758 	if (tid != -1)
759 		return (EINVAL);
760 	switch (pid) {
761 	case -1:		/* broadcast signal */
762 		return (dokillpg(sig, 0, 1));
763 	case 0:			/* signal own process group */
764 		return (dokillpg(sig, 0, 0));
765 	default:		/* negative explicit process group */
766 		return (dokillpg(sig, -pid, 0));
767 	}
768 	/* NOTREACHED */
769 }
770 
771 /*
772  * MPALMOSTSAFE
773  */
774 int
775 sys_kill(struct kill_args *uap)
776 {
777 	int error;
778 
779 	get_mplock();
780 	error = kern_kill(uap->signum, uap->pid, -1);
781 	rel_mplock();
782 	return (error);
783 }
784 
785 /*
786  * MPALMOSTSAFE
787  */
788 int
789 sys_lwp_kill(struct lwp_kill_args *uap)
790 {
791 	int error;
792 	pid_t pid = uap->pid;
793 
794 	/*
795 	 * A tid is mandatory for lwp_kill(), otherwise
796 	 * you could simply use kill().
797 	 */
798 	if (uap->tid == -1)
799 		return (EINVAL);
800 
801 	/*
802 	 * To save on a getpid() function call for intra-process
803 	 * signals, pid == -1 means current process.
804 	 */
805 	if (pid == -1)
806 		pid = curproc->p_pid;
807 
808 	get_mplock();
809 	error = kern_kill(uap->signum, pid, uap->tid);
810 	rel_mplock();
811 	return (error);
812 }
813 
814 /*
815  * Send a signal to a process group.
816  */
817 void
818 gsignal(int pgid, int sig)
819 {
820 	struct pgrp *pgrp;
821 
822 	if (pgid && (pgrp = pgfind(pgid)))
823 		pgsignal(pgrp, sig, 0);
824 }
825 
826 /*
827  * Send a signal to a process group.  If checktty is 1,
828  * limit to members which have a controlling terminal.
829  *
830  * pg_lock interlocks against a fork that might be in progress, to
831  * ensure that the new child process picks up the signal.
832  */
833 void
834 pgsignal(struct pgrp *pgrp, int sig, int checkctty)
835 {
836 	struct proc *p;
837 
838 	if (pgrp) {
839 		lockmgr(&pgrp->pg_lock, LK_EXCLUSIVE);
840 		LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
841 			if (checkctty == 0 || p->p_flag & P_CONTROLT)
842 				ksignal(p, sig);
843 		}
844 		lockmgr(&pgrp->pg_lock, LK_RELEASE);
845 	}
846 }
847 
848 /*
849  * Send a signal caused by a trap to the current lwp.  If it will be caught
850  * immediately, deliver it with correct code.  Otherwise, post it normally.
851  *
852  * These signals may ONLY be delivered to the specified lwp and may never
853  * be delivered to the process generically.
854  */
855 void
856 trapsignal(struct lwp *lp, int sig, u_long code)
857 {
858 	struct proc *p = lp->lwp_proc;
859 	struct sigacts *ps = p->p_sigacts;
860 
861 	/*
862 	 * If we are a virtual kernel running an emulated user process
863 	 * context, switch back to the virtual kernel context before
864 	 * trying to post the signal.
865 	 */
866 	if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
867 		struct trapframe *tf = lp->lwp_md.md_regs;
868 		tf->tf_trapno = 0;
869 		vkernel_trap(lp, tf);
870 	}
871 
872 
873 	if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(p->p_sigcatch, sig) &&
874 	    !SIGISMEMBER(lp->lwp_sigmask, sig)) {
875 		lp->lwp_ru.ru_nsignals++;
876 #ifdef KTRACE
877 		if (KTRPOINT(lp->lwp_thread, KTR_PSIG))
878 			ktrpsig(lp, sig, ps->ps_sigact[_SIG_IDX(sig)],
879 				&lp->lwp_sigmask, code);
880 #endif
881 		(*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)], sig,
882 						&lp->lwp_sigmask, code);
883 		SIGSETOR(lp->lwp_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
884 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
885 			SIGADDSET(lp->lwp_sigmask, sig);
886 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
887 			/*
888 			 * See kern_sigaction() for origin of this code.
889 			 */
890 			SIGDELSET(p->p_sigcatch, sig);
891 			if (sig != SIGCONT &&
892 			    sigprop(sig) & SA_IGNORE)
893 				SIGADDSET(p->p_sigignore, sig);
894 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
895 		}
896 	} else {
897 		lp->lwp_code = code;	/* XXX for core dump/debugger */
898 		lp->lwp_sig = sig;	/* XXX to verify code */
899 		lwpsignal(p, lp, sig);
900 	}
901 }
902 
903 /*
904  * Find a suitable lwp to deliver the signal to.
905  *
906  * Returns NULL if all lwps hold the signal blocked.
907  */
908 static struct lwp *
909 find_lwp_for_signal(struct proc *p, int sig)
910 {
911 	struct lwp *lp;
912 	struct lwp *run, *sleep, *stop;
913 
914 	/*
915 	 * If the running/preempted thread belongs to the proc to which
916 	 * the signal is being delivered and this thread does not block
917 	 * the signal, then we can avoid a context switch by delivering
918 	 * the signal to this thread, because it will return to userland
919 	 * soon anyways.
920 	 */
921 	lp = lwkt_preempted_proc();
922 	if (lp != NULL && lp->lwp_proc == p && !SIGISMEMBER(lp->lwp_sigmask, sig))
923 		return (lp);
924 
925 	run = sleep = stop = NULL;
926 	FOREACH_LWP_IN_PROC(lp, p) {
927 		/*
928 		 * If the signal is being blocked by the lwp, then this
929 		 * lwp is not eligible for receiving the signal.
930 		 */
931 		if (SIGISMEMBER(lp->lwp_sigmask, sig))
932 			continue;
933 
934 		switch (lp->lwp_stat) {
935 		case LSRUN:
936 			run = lp;
937 			break;
938 
939 		case LSSTOP:
940 			stop = lp;
941 			break;
942 
943 		case LSSLEEP:
944 			if (lp->lwp_flag & LWP_SINTR)
945 				sleep = lp;
946 			break;
947 		}
948 	}
949 
950 	if (run != NULL)
951 		return (run);
952 	else if (sleep != NULL)
953 		return (sleep);
954 	else
955 		return (stop);
956 }
957 
958 /*
959  * Send the signal to the process.  If the signal has an action, the action
960  * is usually performed by the target process rather than the caller; we add
961  * the signal to the set of pending signals for the process.
962  *
963  * Exceptions:
964  *   o When a stop signal is sent to a sleeping process that takes the
965  *     default action, the process is stopped without awakening it.
966  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
967  *     regardless of the signal action (eg, blocked or ignored).
968  *
969  * Other ignored signals are discarded immediately.
970  */
971 void
972 ksignal(struct proc *p, int sig)
973 {
974 	lwpsignal(p, NULL, sig);
975 }
976 
977 /*
978  * The core for ksignal.  lp may be NULL, then a suitable thread
979  * will be chosen.  If not, lp MUST be a member of p.
980  */
981 void
982 lwpsignal(struct proc *p, struct lwp *lp, int sig)
983 {
984 	int prop;
985 	sig_t action;
986 
987 	if (sig > _SIG_MAXSIG || sig <= 0) {
988 		kprintf("lwpsignal: signal %d\n", sig);
989 		panic("lwpsignal signal number");
990 	}
991 
992 	KKASSERT(lp == NULL || lp->lwp_proc == p);
993 
994 	crit_enter();
995 	KNOTE(&p->p_klist, NOTE_SIGNAL | sig);
996 	crit_exit();
997 
998 	prop = sigprop(sig);
999 
1000 	/*
1001 	 * If proc is traced, always give parent a chance;
1002 	 * if signal event is tracked by procfs, give *that*
1003 	 * a chance, as well.
1004 	 */
1005 	if ((p->p_flag & P_TRACED) || (p->p_stops & S_SIG)) {
1006 		action = SIG_DFL;
1007 	} else {
1008 		/*
1009 		 * Do not try to deliver signals to an exiting lwp.  Note
1010 		 * that we must still deliver the signal if P_WEXIT is set
1011 		 * in the process flags.
1012 		 */
1013 		if (lp && (lp->lwp_flag & LWP_WEXIT))
1014 			return;
1015 
1016 		/*
1017 		 * If the signal is being ignored, then we forget about
1018 		 * it immediately.  NOTE: We don't set SIGCONT in p_sigignore,
1019 		 * and if it is set to SIG_IGN, action will be SIG_DFL here.
1020 		 */
1021 		if (SIGISMEMBER(p->p_sigignore, sig))
1022 			return;
1023 		if (SIGISMEMBER(p->p_sigcatch, sig))
1024 			action = SIG_CATCH;
1025 		else
1026 			action = SIG_DFL;
1027 	}
1028 
1029 	/*
1030 	 * If continuing, clear any pending STOP signals.
1031 	 */
1032 	if (prop & SA_CONT)
1033 		SIG_STOPSIGMASK(p->p_siglist);
1034 
1035 	if (prop & SA_STOP) {
1036 		/*
1037 		 * If sending a tty stop signal to a member of an orphaned
1038 		 * process group, discard the signal here if the action
1039 		 * is default; don't stop the process below if sleeping,
1040 		 * and don't clear any pending SIGCONT.
1041 		 */
1042 		if (prop & SA_TTYSTOP && p->p_pgrp->pg_jobc == 0 &&
1043 		    action == SIG_DFL) {
1044 		        return;
1045 		}
1046 		SIG_CONTSIGMASK(p->p_siglist);
1047 		p->p_flag &= ~P_CONTINUED;
1048 	}
1049 
1050 	crit_enter();
1051 
1052 	if (p->p_stat == SSTOP) {
1053 		/*
1054 		 * Nobody can handle this signal, add it to the lwp or
1055 		 * process pending list
1056 		 */
1057 		if (lp)
1058 			SIGADDSET(lp->lwp_siglist, sig);
1059 		else
1060 			SIGADDSET(p->p_siglist, sig);
1061 
1062 		/*
1063 		 * If the process is stopped and is being traced, then no
1064 		 * further action is necessary.
1065 		 */
1066 		if (p->p_flag & P_TRACED)
1067 			goto out;
1068 
1069 		/*
1070 		 * If the process is stopped and receives a KILL signal,
1071 		 * make the process runnable.
1072 		 */
1073 		if (sig == SIGKILL) {
1074 			proc_unstop(p);
1075 			goto active_process;
1076 		}
1077 
1078 		/*
1079 		 * If the process is stopped and receives a CONT signal,
1080 		 * then try to make the process runnable again.
1081 		 */
1082 		if (prop & SA_CONT) {
1083 			/*
1084 			 * If SIGCONT is default (or ignored), we continue the
1085 			 * process but don't leave the signal in p_siglist, as
1086 			 * it has no further action.  If SIGCONT is held, we
1087 			 * continue the process and leave the signal in
1088 			 * p_siglist.  If the process catches SIGCONT, let it
1089 			 * handle the signal itself.
1090 			 */
1091 			/* XXX what if the signal is being held blocked? */
1092 			p->p_flag |= P_CONTINUED;
1093 			wakeup(p->p_pptr);
1094 			if (action == SIG_DFL)
1095 				SIGDELSET(p->p_siglist, sig);
1096 			proc_unstop(p);
1097 			if (action == SIG_CATCH)
1098 				goto active_process;
1099 			goto out;
1100 		}
1101 
1102 		/*
1103 		 * If the process is stopped and receives another STOP
1104 		 * signal, we do not need to stop it again.  If we did
1105 		 * the shell could get confused.
1106 		 *
1107 		 * However, if the current/preempted lwp is part of the
1108 		 * process receiving the signal, we need to keep it,
1109 		 * so that this lwp can stop in issignal() later, as
1110 		 * we don't want to wait until it reaches userret!
1111 		 */
1112 		if (prop & SA_STOP) {
1113 			if (lwkt_preempted_proc() == NULL ||
1114 			    lwkt_preempted_proc()->lwp_proc != p)
1115 				SIGDELSET(p->p_siglist, sig);
1116 		}
1117 
1118 		/*
1119 		 * Otherwise the process is stopped and it received some
1120 		 * signal, which does not change its stopped state.
1121 		 *
1122 		 * We have to select one thread to set LWP_BREAKTSLEEP,
1123 		 * so that the current signal will break the sleep
1124 		 * as soon as a SA_CONT signal will unstop the process.
1125 		 */
1126 		if (lp == NULL)
1127 			lp = find_lwp_for_signal(p, sig);
1128 		if (lp != NULL &&
1129 		    (lp->lwp_stat == LSSLEEP || lp->lwp_stat == LSSTOP))
1130 			lp->lwp_flag |= LWP_BREAKTSLEEP;
1131 		goto out;
1132 
1133 		/* NOTREACHED */
1134 	}
1135 	/* else not stopped */
1136 active_process:
1137 
1138 	/*
1139 	 * Never deliver a lwp-specific signal to a random lwp.
1140 	 */
1141 	if (lp == NULL) {
1142 		lp = find_lwp_for_signal(p, sig);
1143 		if (lp && SIGISMEMBER(lp->lwp_sigmask, sig))
1144 			lp = NULL;
1145 	}
1146 
1147 	/*
1148 	 * Deliver to the process generically if (1) the signal is being
1149 	 * sent to any thread or (2) we could not find a thread to deliver
1150 	 * it to.
1151 	 */
1152 	if (lp == NULL) {
1153 		SIGADDSET(p->p_siglist, sig);
1154 		goto out;
1155 	}
1156 
1157 	/*
1158 	 * Deliver to a specific LWP whether it masks it or not.  It will
1159 	 * not be dispatched if masked but we must still deliver it.
1160 	 */
1161 	if (p->p_nice > NZERO && action == SIG_DFL && (prop & SA_KILL) &&
1162 	    (p->p_flag & P_TRACED) == 0) {
1163 		p->p_nice = NZERO;
1164 	}
1165 
1166 	/*
1167 	 * If the process receives a STOP signal which indeed needs to
1168 	 * stop the process, do so.  If the process chose to catch the
1169 	 * signal, it will be treated like any other signal.
1170 	 */
1171 	if ((prop & SA_STOP) && action == SIG_DFL) {
1172 		/*
1173 		 * If a child holding parent blocked, stopping
1174 		 * could cause deadlock.  Take no action at this
1175 		 * time.
1176 		 */
1177 		if (p->p_flag & P_PPWAIT) {
1178 			SIGADDSET(p->p_siglist, sig);
1179 			goto out;
1180 		}
1181 
1182 		/*
1183 		 * Do not actually try to manipulate the process, but simply
1184 		 * stop it.  Lwps will stop as soon as they safely can.
1185 		 */
1186 		p->p_xstat = sig;
1187 		proc_stop(p);
1188 		goto out;
1189 	}
1190 
1191 	/*
1192 	 * If it is a CONT signal with default action, just ignore it.
1193 	 */
1194 	if ((prop & SA_CONT) && action == SIG_DFL)
1195 		goto out;
1196 
1197 	/*
1198 	 * Mark signal pending at this specific thread.
1199 	 */
1200 	SIGADDSET(lp->lwp_siglist, sig);
1201 
1202 	lwp_signotify(lp);
1203 
1204 out:
1205 	crit_exit();
1206 }
1207 
1208 void
1209 lwp_signotify(struct lwp *lp)
1210 {
1211 	crit_enter();
1212 	if (lp->lwp_stat == LSSLEEP || lp->lwp_stat == LSSTOP) {
1213 		/*
1214 		 * Thread is in tsleep.
1215 		 */
1216 
1217 		/*
1218 		 * If the thread is sleeping uninterruptibly
1219 		 * we can't interrupt the sleep... the signal will
1220 		 * be noticed when the lwp returns through
1221 		 * trap() or syscall().
1222 		 *
1223 		 * Otherwise the signal can interrupt the sleep.
1224 		 *
1225 		 * If the process is traced, the lwp will handle the
1226 		 * tracing in issignal() when it returns to userland.
1227 		 */
1228 		if (lp->lwp_flag & LWP_SINTR) {
1229 			/*
1230 			 * Make runnable and break out of any tsleep as well.
1231 			 */
1232 			lp->lwp_flag |= LWP_BREAKTSLEEP;
1233 			setrunnable(lp);
1234 		}
1235 	} else {
1236 		/*
1237 		 * Otherwise the thread is running
1238 		 *
1239 		 * LSRUN does nothing with the signal, other than kicking
1240 		 * ourselves if we are running.
1241 		 * SZOMB and SIDL mean that it will either never be noticed,
1242 		 * or noticed very soon.
1243 		 *
1244 		 * Note that lwp_thread may be NULL or may not be completely
1245 		 * initialized if the process is in the SIDL or SZOMB state.
1246 		 *
1247 		 * For SMP we may have to forward the request to another cpu.
1248 		 * YYY the MP lock prevents the target process from moving
1249 		 * to another cpu, see kern/kern_switch.c
1250 		 *
1251 		 * If the target thread is waiting on its message port,
1252 		 * wakeup the target thread so it can check (or ignore)
1253 		 * the new signal.  YYY needs cleanup.
1254 		 */
1255 		if (lp == lwkt_preempted_proc()) {
1256 			signotify();
1257 		} else if (lp->lwp_stat == LSRUN) {
1258 			struct thread *td = lp->lwp_thread;
1259 			struct proc *p __debugvar = lp->lwp_proc;
1260 
1261 			KASSERT(td != NULL,
1262 			    ("pid %d/%d NULL lwp_thread stat %d flags %08x/%08x",
1263 			    p->p_pid, lp->lwp_tid, lp->lwp_stat,
1264 			    p->p_flag, lp->lwp_flag));
1265 
1266 			/*
1267 			 * To prevent a MP race with TDF_SINTR we must
1268 			 * schedule the thread on the correct cpu.
1269 			 */
1270 #ifdef SMP
1271 			if (td->td_gd != mycpu) {
1272 				LWPHOLD(lp);
1273 				lwkt_send_ipiq(td->td_gd, signotify_remote, lp);
1274 			} else
1275 #endif
1276 			if (td->td_flags & TDF_SINTR)
1277 				lwkt_schedule(td);
1278 		}
1279 	}
1280 	crit_exit();
1281 }
1282 
1283 #ifdef SMP
1284 
1285 /*
1286  * This function is called via an IPI.  We will be in a critical section but
1287  * the MP lock will NOT be held.  Also note that by the time the ipi message
1288  * gets to us the process 'p' (arg) may no longer be scheduled or even valid.
1289  */
1290 static void
1291 signotify_remote(void *arg)
1292 {
1293 	struct lwp *lp = arg;
1294 
1295 	if (lp == lwkt_preempted_proc()) {
1296 		signotify();
1297 	} else {
1298 		struct thread *td = lp->lwp_thread;
1299 		if (td->td_flags & TDF_SINTR)
1300 			lwkt_schedule(td);
1301 	}
1302 	LWPRELE(lp);
1303 }
1304 
1305 #endif
1306 
1307 void
1308 proc_stop(struct proc *p)
1309 {
1310 	struct lwp *lp;
1311 
1312 	/* If somebody raced us, be happy with it */
1313 	if (p->p_stat == SSTOP || p->p_stat == SZOMB)
1314 		return;
1315 
1316 	crit_enter();
1317 	p->p_stat = SSTOP;
1318 
1319 	FOREACH_LWP_IN_PROC(lp, p) {
1320 		switch (lp->lwp_stat) {
1321 		case LSSTOP:
1322 			/*
1323 			 * Do nothing, we are already counted in
1324 			 * p_nstopped.
1325 			 */
1326 			break;
1327 
1328 		case LSSLEEP:
1329 			/*
1330 			 * We're sleeping, but we will stop before
1331 			 * returning to userspace, so count us
1332 			 * as stopped as well.  We set LWP_WSTOP
1333 			 * to signal the lwp that it should not
1334 			 * increase p_nstopped when reaching tstop().
1335 			 */
1336 			if ((lp->lwp_flag & LWP_WSTOP) == 0) {
1337 				lp->lwp_flag |= LWP_WSTOP;
1338 				++p->p_nstopped;
1339 			}
1340 			break;
1341 
1342 		case LSRUN:
1343 			/*
1344 			 * We might notify ourself, but that's not
1345 			 * a problem.
1346 			 */
1347 			lwp_signotify(lp);
1348 			break;
1349 		}
1350 	}
1351 
1352 	if (p->p_nstopped == p->p_nthreads) {
1353 		p->p_flag &= ~P_WAITED;
1354 		wakeup(p->p_pptr);
1355 		if ((p->p_pptr->p_sigacts->ps_flag & PS_NOCLDSTOP) == 0)
1356 			ksignal(p->p_pptr, SIGCHLD);
1357 	}
1358 	crit_exit();
1359 }
1360 
1361 void
1362 proc_unstop(struct proc *p)
1363 {
1364 	struct lwp *lp;
1365 
1366 	if (p->p_stat != SSTOP)
1367 		return;
1368 
1369 	crit_enter();
1370 	p->p_stat = SACTIVE;
1371 
1372 	FOREACH_LWP_IN_PROC(lp, p) {
1373 		switch (lp->lwp_stat) {
1374 		case LSRUN:
1375 			/*
1376 			 * Uh?  Not stopped?  Well, I guess that's okay.
1377 			 */
1378 			if (bootverbose)
1379 				kprintf("proc_unstop: lwp %d/%d not sleeping\n",
1380 					p->p_pid, lp->lwp_tid);
1381 			break;
1382 
1383 		case LSSLEEP:
1384 			/*
1385 			 * Still sleeping.  Don't bother waking it up.
1386 			 * However, if this thread was counted as
1387 			 * stopped, undo this.
1388 			 *
1389 			 * Nevertheless we call setrunnable() so that it
1390 			 * will wake up in case a signal or timeout arrived
1391 			 * in the meantime.
1392 			 */
1393 			if (lp->lwp_flag & LWP_WSTOP) {
1394 				lp->lwp_flag &= ~LWP_WSTOP;
1395 				--p->p_nstopped;
1396 			} else {
1397 				if (bootverbose)
1398 					kprintf("proc_unstop: lwp %d/%d sleeping, not stopped\n",
1399 						p->p_pid, lp->lwp_tid);
1400 			}
1401 			/* FALLTHROUGH */
1402 
1403 		case LSSTOP:
1404 			setrunnable(lp);
1405 			break;
1406 
1407 		}
1408 	}
1409 	crit_exit();
1410 }
1411 
1412 static int
1413 kern_sigtimedwait(sigset_t waitset, siginfo_t *info, struct timespec *timeout)
1414 {
1415 	sigset_t savedmask, set;
1416 	struct proc *p = curproc;
1417 	struct lwp *lp = curthread->td_lwp;
1418 	int error, sig, hz, timevalid = 0;
1419 	struct timespec rts, ets, ts;
1420 	struct timeval tv;
1421 
1422 	error = 0;
1423 	sig = 0;
1424 	ets.tv_sec = 0;		/* silence compiler warning */
1425 	ets.tv_nsec = 0;	/* silence compiler warning */
1426 	SIG_CANTMASK(waitset);
1427 	savedmask = lp->lwp_sigmask;
1428 
1429 	if (timeout) {
1430 		if (timeout->tv_sec >= 0 && timeout->tv_nsec >= 0 &&
1431 		    timeout->tv_nsec < 1000000000) {
1432 			timevalid = 1;
1433 			getnanouptime(&rts);
1434 		 	ets = rts;
1435 			timespecadd(&ets, timeout);
1436 		}
1437 	}
1438 
1439 	for (;;) {
1440 		set = lwp_sigpend(lp);
1441 		SIGSETAND(set, waitset);
1442 		if ((sig = sig_ffs(&set)) != 0) {
1443 			SIGFILLSET(lp->lwp_sigmask);
1444 			SIGDELSET(lp->lwp_sigmask, sig);
1445 			SIG_CANTMASK(lp->lwp_sigmask);
1446 			sig = issignal(lp, 1);
1447 			/*
1448 			 * It may be a STOP signal, in the case, issignal
1449 			 * returns 0, because we may stop there, and new
1450 			 * signal can come in, we should restart if we got
1451 			 * nothing.
1452 			 */
1453 			if (sig == 0)
1454 				continue;
1455 			else
1456 				break;
1457 		}
1458 
1459 		/*
1460 		 * Previous checking got nothing, and we retried but still
1461 		 * got nothing, we should return the error status.
1462 		 */
1463 		if (error)
1464 			break;
1465 
1466 		/*
1467 		 * POSIX says this must be checked after looking for pending
1468 		 * signals.
1469 		 */
1470 		if (timeout) {
1471 			if (timevalid == 0) {
1472 				error = EINVAL;
1473 				break;
1474 			}
1475 			getnanouptime(&rts);
1476 			if (timespeccmp(&rts, &ets, >=)) {
1477 				error = EAGAIN;
1478 				break;
1479 			}
1480 			ts = ets;
1481 			timespecsub(&ts, &rts);
1482 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1483 			hz = tvtohz_high(&tv);
1484 		} else
1485 			hz = 0;
1486 
1487 		lp->lwp_sigmask = savedmask;
1488 		SIGSETNAND(lp->lwp_sigmask, waitset);
1489 		/*
1490 		 * We won't ever be woken up.  Instead, our sleep will
1491 		 * be broken in lwpsignal().
1492 		 */
1493 		error = tsleep(&p->p_sigacts, PCATCH, "sigwt", hz);
1494 		if (timeout) {
1495 			if (error == ERESTART) {
1496 				/* can not restart a timeout wait. */
1497 				error = EINTR;
1498 			} else if (error == EAGAIN) {
1499 				/* will calculate timeout by ourself. */
1500 				error = 0;
1501 			}
1502 		}
1503 		/* Retry ... */
1504 	}
1505 
1506 	lp->lwp_sigmask = savedmask;
1507 	if (sig) {
1508 		error = 0;
1509 		bzero(info, sizeof(*info));
1510 		info->si_signo = sig;
1511 		lwp_delsig(lp, sig);	/* take the signal! */
1512 
1513 		if (sig == SIGKILL)
1514 			sigexit(lp, sig);
1515 	}
1516 	return (error);
1517 }
1518 
1519 /*
1520  * MPALMOSTSAFE
1521  */
1522 int
1523 sys_sigtimedwait(struct sigtimedwait_args *uap)
1524 {
1525 	struct timespec ts;
1526 	struct timespec *timeout;
1527 	sigset_t set;
1528 	siginfo_t info;
1529 	int error;
1530 
1531 	if (uap->timeout) {
1532 		error = copyin(uap->timeout, &ts, sizeof(ts));
1533 		if (error)
1534 			return (error);
1535 		timeout = &ts;
1536 	} else {
1537 		timeout = NULL;
1538 	}
1539 	error = copyin(uap->set, &set, sizeof(set));
1540 	if (error)
1541 		return (error);
1542 	get_mplock();
1543 	error = kern_sigtimedwait(set, &info, timeout);
1544 	rel_mplock();
1545 	if (error)
1546 		return (error);
1547  	if (uap->info)
1548 		error = copyout(&info, uap->info, sizeof(info));
1549 	/* Repost if we got an error. */
1550 	/*
1551 	 * XXX lwp
1552 	 *
1553 	 * This could transform a thread-specific signal to another
1554 	 * thread / process pending signal.
1555 	 */
1556 	if (error) {
1557 		get_mplock();
1558 		ksignal(curproc, info.si_signo);
1559 		rel_mplock();
1560 	} else {
1561 		uap->sysmsg_result = info.si_signo;
1562 	}
1563 	return (error);
1564 }
1565 
1566 /*
1567  * MPALMOSTSAFE
1568  */
1569 int
1570 sys_sigwaitinfo(struct sigwaitinfo_args *uap)
1571 {
1572 	siginfo_t info;
1573 	sigset_t set;
1574 	int error;
1575 
1576 	error = copyin(uap->set, &set, sizeof(set));
1577 	if (error)
1578 		return (error);
1579 	get_mplock();
1580 	error = kern_sigtimedwait(set, &info, NULL);
1581 	rel_mplock();
1582 	if (error)
1583 		return (error);
1584 	if (uap->info)
1585 		error = copyout(&info, uap->info, sizeof(info));
1586 	/* Repost if we got an error. */
1587 	/*
1588 	 * XXX lwp
1589 	 *
1590 	 * This could transform a thread-specific signal to another
1591 	 * thread / process pending signal.
1592 	 */
1593 	if (error) {
1594 		get_mplock();
1595 		ksignal(curproc, info.si_signo);
1596 		rel_mplock();
1597 	} else {
1598 		uap->sysmsg_result = info.si_signo;
1599 	}
1600 	return (error);
1601 }
1602 
1603 /*
1604  * If the current process has received a signal that would interrupt a
1605  * system call, return EINTR or ERESTART as appropriate.
1606  */
1607 int
1608 iscaught(struct lwp *lp)
1609 {
1610 	struct proc *p = lp->lwp_proc;
1611 	int sig;
1612 
1613 	if (p) {
1614 		if ((sig = CURSIG(lp)) != 0) {
1615 			if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
1616 				return (EINTR);
1617 			return (ERESTART);
1618 		}
1619 	}
1620 	return(EWOULDBLOCK);
1621 }
1622 
1623 /*
1624  * If the current process has received a signal (should be caught or cause
1625  * termination, should interrupt current syscall), return the signal number.
1626  * Stop signals with default action are processed immediately, then cleared;
1627  * they aren't returned.  This is checked after each entry to the system for
1628  * a syscall or trap (though this can usually be done without calling issignal
1629  * by checking the pending signal masks in the CURSIG macro.) The normal call
1630  * sequence is
1631  *
1632  * This routine is called via CURSIG/__cursig and the MP lock might not be
1633  * held.  Obtain the MP lock for the duration of the operation.
1634  *
1635  *	while (sig = CURSIG(curproc))
1636  *		postsig(sig);
1637  */
1638 int
1639 issignal(struct lwp *lp, int maytrace)
1640 {
1641 	struct proc *p = lp->lwp_proc;
1642 	sigset_t mask;
1643 	int sig, prop;
1644 
1645 	get_mplock();
1646 	for (;;) {
1647 		int traced = (p->p_flag & P_TRACED) || (p->p_stops & S_SIG);
1648 
1649 		/*
1650 		 * If this process is supposed to stop, stop this thread.
1651 		 */
1652 		if (p->p_stat == SSTOP)
1653 			tstop();
1654 
1655 		mask = lwp_sigpend(lp);
1656 		SIGSETNAND(mask, lp->lwp_sigmask);
1657 		if (p->p_flag & P_PPWAIT)
1658 			SIG_STOPSIGMASK(mask);
1659 		if (SIGISEMPTY(mask)) {		/* no signal to send */
1660 			rel_mplock();
1661 			return (0);
1662 		}
1663 		sig = sig_ffs(&mask);
1664 
1665 		STOPEVENT(p, S_SIG, sig);
1666 
1667 		/*
1668 		 * We should see pending but ignored signals
1669 		 * only if P_TRACED was on when they were posted.
1670 		 */
1671 		if (SIGISMEMBER(p->p_sigignore, sig) && (traced == 0)) {
1672 			lwp_delsig(lp, sig);
1673 			continue;
1674 		}
1675 		if (maytrace && (p->p_flag & P_TRACED) && (p->p_flag & P_PPWAIT) == 0) {
1676 			/*
1677 			 * If traced, always stop, and stay stopped until
1678 			 * released by the parent.
1679 			 *
1680 			 * NOTE: SSTOP may get cleared during the loop,
1681 			 * but we do not re-notify the parent if we have
1682 			 * to loop several times waiting for the parent
1683 			 * to let us continue.
1684 			 *
1685 			 * XXX not sure if this is still true
1686 			 */
1687 			p->p_xstat = sig;
1688 			proc_stop(p);
1689 			do {
1690 				tstop();
1691 			} while (!trace_req(p) && (p->p_flag & P_TRACED));
1692 
1693 			/*
1694 			 * If parent wants us to take the signal,
1695 			 * then it will leave it in p->p_xstat;
1696 			 * otherwise we just look for signals again.
1697 			 */
1698 			lwp_delsig(lp, sig);	/* clear old signal */
1699 			sig = p->p_xstat;
1700 			if (sig == 0)
1701 				continue;
1702 
1703 			/*
1704 			 * Put the new signal into p_siglist.  If the
1705 			 * signal is being masked, look for other signals.
1706 			 *
1707 			 * XXX lwp might need a call to ksignal()
1708 			 */
1709 			SIGADDSET(p->p_siglist, sig);
1710 			if (SIGISMEMBER(lp->lwp_sigmask, sig))
1711 				continue;
1712 
1713 			/*
1714 			 * If the traced bit got turned off, go back up
1715 			 * to the top to rescan signals.  This ensures
1716 			 * that p_sig* and ps_sigact are consistent.
1717 			 */
1718 			if ((p->p_flag & P_TRACED) == 0)
1719 				continue;
1720 		}
1721 
1722 		prop = sigprop(sig);
1723 
1724 		/*
1725 		 * Decide whether the signal should be returned.
1726 		 * Return the signal's number, or fall through
1727 		 * to clear it from the pending mask.
1728 		 */
1729 		switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
1730 		case (intptr_t)SIG_DFL:
1731 			/*
1732 			 * Don't take default actions on system processes.
1733 			 */
1734 			if (p->p_pid <= 1) {
1735 #ifdef DIAGNOSTIC
1736 				/*
1737 				 * Are you sure you want to ignore SIGSEGV
1738 				 * in init? XXX
1739 				 */
1740 				kprintf("Process (pid %lu) got signal %d\n",
1741 					(u_long)p->p_pid, sig);
1742 #endif
1743 				break;		/* == ignore */
1744 			}
1745 
1746 			/*
1747 			 * Handle the in-kernel checkpoint action
1748 			 */
1749 			if (prop & SA_CKPT) {
1750 				checkpoint_signal_handler(lp);
1751 				break;
1752 			}
1753 
1754 			/*
1755 			 * If there is a pending stop signal to process
1756 			 * with default action, stop here,
1757 			 * then clear the signal.  However,
1758 			 * if process is member of an orphaned
1759 			 * process group, ignore tty stop signals.
1760 			 */
1761 			if (prop & SA_STOP) {
1762 				if (p->p_flag & P_TRACED ||
1763 		    		    (p->p_pgrp->pg_jobc == 0 &&
1764 				    prop & SA_TTYSTOP))
1765 					break;	/* == ignore */
1766 				p->p_xstat = sig;
1767 				proc_stop(p);
1768 				tstop();
1769 				break;
1770 			} else if (prop & SA_IGNORE) {
1771 				/*
1772 				 * Except for SIGCONT, shouldn't get here.
1773 				 * Default action is to ignore; drop it.
1774 				 */
1775 				break;		/* == ignore */
1776 			} else {
1777 				rel_mplock();
1778 				return (sig);
1779 			}
1780 
1781 			/*NOTREACHED*/
1782 
1783 		case (intptr_t)SIG_IGN:
1784 			/*
1785 			 * Masking above should prevent us ever trying
1786 			 * to take action on an ignored signal other
1787 			 * than SIGCONT, unless process is traced.
1788 			 */
1789 			if ((prop & SA_CONT) == 0 &&
1790 			    (p->p_flag & P_TRACED) == 0)
1791 				kprintf("issignal\n");
1792 			break;		/* == ignore */
1793 
1794 		default:
1795 			/*
1796 			 * This signal has an action, let
1797 			 * postsig() process it.
1798 			 */
1799 			rel_mplock();
1800 			return (sig);
1801 		}
1802 		lwp_delsig(lp, sig);		/* take the signal! */
1803 	}
1804 	/* NOTREACHED */
1805 }
1806 
1807 /*
1808  * Take the action for the specified signal
1809  * from the current set of pending signals.
1810  */
1811 void
1812 postsig(int sig)
1813 {
1814 	struct lwp *lp = curthread->td_lwp;
1815 	struct proc *p = lp->lwp_proc;
1816 	struct sigacts *ps = p->p_sigacts;
1817 	sig_t action;
1818 	sigset_t returnmask;
1819 	int code;
1820 
1821 	KASSERT(sig != 0, ("postsig"));
1822 
1823 	/*
1824 	 * If we are a virtual kernel running an emulated user process
1825 	 * context, switch back to the virtual kernel context before
1826 	 * trying to post the signal.
1827 	 */
1828 	if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
1829 		struct trapframe *tf = lp->lwp_md.md_regs;
1830 		tf->tf_trapno = 0;
1831 		vkernel_trap(lp, tf);
1832 	}
1833 
1834 	lwp_delsig(lp, sig);
1835 	action = ps->ps_sigact[_SIG_IDX(sig)];
1836 #ifdef KTRACE
1837 	if (KTRPOINT(lp->lwp_thread, KTR_PSIG))
1838 		ktrpsig(lp, sig, action, lp->lwp_flag & LWP_OLDMASK ?
1839 			&lp->lwp_oldsigmask : &lp->lwp_sigmask, 0);
1840 #endif
1841 	STOPEVENT(p, S_SIG, sig);
1842 
1843 	if (action == SIG_DFL) {
1844 		/*
1845 		 * Default action, where the default is to kill
1846 		 * the process.  (Other cases were ignored above.)
1847 		 */
1848 		sigexit(lp, sig);
1849 		/* NOTREACHED */
1850 	} else {
1851 		/*
1852 		 * If we get here, the signal must be caught.
1853 		 */
1854 		KASSERT(action != SIG_IGN && !SIGISMEMBER(lp->lwp_sigmask, sig),
1855 		    ("postsig action"));
1856 
1857 		crit_enter();
1858 
1859 		/*
1860 		 * Reset the signal handler if asked to
1861 		 */
1862 		if (SIGISMEMBER(ps->ps_sigreset, sig)) {
1863 			/*
1864 			 * See kern_sigaction() for origin of this code.
1865 			 */
1866 			SIGDELSET(p->p_sigcatch, sig);
1867 			if (sig != SIGCONT &&
1868 			    sigprop(sig) & SA_IGNORE)
1869 				SIGADDSET(p->p_sigignore, sig);
1870 			ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
1871 		}
1872 
1873 		/*
1874 		 * Handle the mailbox case.  Copyout to the appropriate
1875 		 * location but do not generate a signal frame.  The system
1876 		 * call simply returns EINTR and the user is responsible for
1877 		 * polling the mailbox.
1878 		 */
1879 		if (SIGISMEMBER(ps->ps_sigmailbox, sig)) {
1880 			int sig_copy = sig;
1881 			copyout(&sig_copy, (void *)action, sizeof(int));
1882 			curproc->p_flag |= P_MAILBOX;
1883 			crit_exit();
1884 			goto done;
1885 		}
1886 
1887 		/*
1888 		 * Set the signal mask and calculate the mask to restore
1889 		 * when the signal function returns.
1890 		 *
1891 		 * Special case: user has done a sigsuspend.  Here the
1892 		 * current mask is not of interest, but rather the
1893 		 * mask from before the sigsuspend is what we want
1894 		 * restored after the signal processing is completed.
1895 		 */
1896 		if (lp->lwp_flag & LWP_OLDMASK) {
1897 			returnmask = lp->lwp_oldsigmask;
1898 			lp->lwp_flag &= ~LWP_OLDMASK;
1899 		} else {
1900 			returnmask = lp->lwp_sigmask;
1901 		}
1902 
1903 		SIGSETOR(lp->lwp_sigmask, ps->ps_catchmask[_SIG_IDX(sig)]);
1904 		if (!SIGISMEMBER(ps->ps_signodefer, sig))
1905 			SIGADDSET(lp->lwp_sigmask, sig);
1906 
1907 		crit_exit();
1908 		lp->lwp_ru.ru_nsignals++;
1909 		if (lp->lwp_sig != sig) {
1910 			code = 0;
1911 		} else {
1912 			code = lp->lwp_code;
1913 			lp->lwp_code = 0;
1914 			lp->lwp_sig = 0;
1915 		}
1916 		(*p->p_sysent->sv_sendsig)(action, sig, &returnmask, code);
1917 	}
1918 done:
1919 	;
1920 }
1921 
1922 /*
1923  * Kill the current process for stated reason.
1924  */
1925 void
1926 killproc(struct proc *p, char *why)
1927 {
1928 	log(LOG_ERR, "pid %d (%s), uid %d, was killed: %s\n",
1929 		p->p_pid, p->p_comm,
1930 		p->p_ucred ? p->p_ucred->cr_uid : -1, why);
1931 	ksignal(p, SIGKILL);
1932 }
1933 
1934 /*
1935  * Force the current process to exit with the specified signal, dumping core
1936  * if appropriate.  We bypass the normal tests for masked and caught signals,
1937  * allowing unrecoverable failures to terminate the process without changing
1938  * signal state.  Mark the accounting record with the signal termination.
1939  * If dumping core, save the signal number for the debugger.  Calls exit and
1940  * does not return.
1941  */
1942 void
1943 sigexit(struct lwp *lp, int sig)
1944 {
1945 	struct proc *p = lp->lwp_proc;
1946 
1947 	p->p_acflag |= AXSIG;
1948 	if (sigprop(sig) & SA_CORE) {
1949 		lp->lwp_sig = sig;
1950 		/*
1951 		 * Log signals which would cause core dumps
1952 		 * (Log as LOG_INFO to appease those who don't want
1953 		 * these messages.)
1954 		 * XXX : Todo, as well as euid, write out ruid too
1955 		 */
1956 		if (coredump(lp, sig) == 0)
1957 			sig |= WCOREFLAG;
1958 		if (kern_logsigexit)
1959 			log(LOG_INFO,
1960 			    "pid %d (%s), uid %d: exited on signal %d%s\n",
1961 			    p->p_pid, p->p_comm,
1962 			    p->p_ucred ? p->p_ucred->cr_uid : -1,
1963 			    sig &~ WCOREFLAG,
1964 			    sig & WCOREFLAG ? " (core dumped)" : "");
1965 	}
1966 	exit1(W_EXITCODE(0, sig));
1967 	/* NOTREACHED */
1968 }
1969 
1970 static char corefilename[MAXPATHLEN+1] = {"%N.core"};
1971 SYSCTL_STRING(_kern, OID_AUTO, corefile, CTLFLAG_RW, corefilename,
1972 	      sizeof(corefilename), "process corefile name format string");
1973 
1974 /*
1975  * expand_name(name, uid, pid)
1976  * Expand the name described in corefilename, using name, uid, and pid.
1977  * corefilename is a kprintf-like string, with three format specifiers:
1978  *	%N	name of process ("name")
1979  *	%P	process id (pid)
1980  *	%U	user id (uid)
1981  * For example, "%N.core" is the default; they can be disabled completely
1982  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
1983  * This is controlled by the sysctl variable kern.corefile (see above).
1984  */
1985 
1986 static char *
1987 expand_name(const char *name, uid_t uid, pid_t pid)
1988 {
1989 	char *temp;
1990 	char buf[11];		/* Buffer for pid/uid -- max 4B */
1991 	int i, n;
1992 	char *format = corefilename;
1993 	size_t namelen;
1994 
1995 	temp = kmalloc(MAXPATHLEN + 1, M_TEMP, M_NOWAIT);
1996 	if (temp == NULL)
1997 		return NULL;
1998 	namelen = strlen(name);
1999 	for (i = 0, n = 0; n < MAXPATHLEN && format[i]; i++) {
2000 		int l;
2001 		switch (format[i]) {
2002 		case '%':	/* Format character */
2003 			i++;
2004 			switch (format[i]) {
2005 			case '%':
2006 				temp[n++] = '%';
2007 				break;
2008 			case 'N':	/* process name */
2009 				if ((n + namelen) > MAXPATHLEN) {
2010 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2011 					    pid, name, uid, temp, name);
2012 					kfree(temp, M_TEMP);
2013 					return NULL;
2014 				}
2015 				memcpy(temp+n, name, namelen);
2016 				n += namelen;
2017 				break;
2018 			case 'P':	/* process id */
2019 				l = ksprintf(buf, "%u", pid);
2020 				if ((n + l) > MAXPATHLEN) {
2021 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2022 					    pid, name, uid, temp, name);
2023 					kfree(temp, M_TEMP);
2024 					return NULL;
2025 				}
2026 				memcpy(temp+n, buf, l);
2027 				n += l;
2028 				break;
2029 			case 'U':	/* user id */
2030 				l = ksprintf(buf, "%u", uid);
2031 				if ((n + l) > MAXPATHLEN) {
2032 					log(LOG_ERR, "pid %d (%s), uid (%u):  Path `%s%s' is too long\n",
2033 					    pid, name, uid, temp, name);
2034 					kfree(temp, M_TEMP);
2035 					return NULL;
2036 				}
2037 				memcpy(temp+n, buf, l);
2038 				n += l;
2039 				break;
2040 			default:
2041 			  	log(LOG_ERR, "Unknown format character %c in `%s'\n", format[i], format);
2042 			}
2043 			break;
2044 		default:
2045 			temp[n++] = format[i];
2046 		}
2047 	}
2048 	temp[n] = '\0';
2049 	return temp;
2050 }
2051 
2052 /*
2053  * Dump a process' core.  The main routine does some
2054  * policy checking, and creates the name of the coredump;
2055  * then it passes on a vnode and a size limit to the process-specific
2056  * coredump routine if there is one; if there _is not_ one, it returns
2057  * ENOSYS; otherwise it returns the error from the process-specific routine.
2058  *
2059  * The parameter `lp' is the lwp which triggered the coredump.
2060  */
2061 
2062 static int
2063 coredump(struct lwp *lp, int sig)
2064 {
2065 	struct proc *p = lp->lwp_proc;
2066 	struct vnode *vp;
2067 	struct ucred *cred = p->p_ucred;
2068 	struct flock lf;
2069 	struct nlookupdata nd;
2070 	struct vattr vattr;
2071 	int error, error1;
2072 	char *name;			/* name of corefile */
2073 	off_t limit;
2074 
2075 	STOPEVENT(p, S_CORE, 0);
2076 
2077 	if (((sugid_coredump == 0) && p->p_flag & P_SUGID) || do_coredump == 0)
2078 		return (EFAULT);
2079 
2080 	/*
2081 	 * Note that the bulk of limit checking is done after
2082 	 * the corefile is created.  The exception is if the limit
2083 	 * for corefiles is 0, in which case we don't bother
2084 	 * creating the corefile at all.  This layout means that
2085 	 * a corefile is truncated instead of not being created,
2086 	 * if it is larger than the limit.
2087 	 */
2088 	limit = p->p_rlimit[RLIMIT_CORE].rlim_cur;
2089 	if (limit == 0)
2090 		return EFBIG;
2091 
2092 	name = expand_name(p->p_comm, p->p_ucred->cr_uid, p->p_pid);
2093 	if (name == NULL)
2094 		return (EINVAL);
2095 	error = nlookup_init(&nd, name, UIO_SYSSPACE, NLC_LOCKVP);
2096 	if (error == 0)
2097 		error = vn_open(&nd, NULL, O_CREAT | FWRITE | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2098 	kfree(name, M_TEMP);
2099 	if (error) {
2100 		nlookup_done(&nd);
2101 		return (error);
2102 	}
2103 	vp = nd.nl_open_vp;
2104 	nd.nl_open_vp = NULL;
2105 	nlookup_done(&nd);
2106 
2107 	vn_unlock(vp);
2108 	lf.l_whence = SEEK_SET;
2109 	lf.l_start = 0;
2110 	lf.l_len = 0;
2111 	lf.l_type = F_WRLCK;
2112 	error = VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, 0);
2113 	if (error)
2114 		goto out2;
2115 
2116 	/* Don't dump to non-regular files or files with links. */
2117 	if (vp->v_type != VREG ||
2118 	    VOP_GETATTR(vp, &vattr) || vattr.va_nlink != 1) {
2119 		error = EFAULT;
2120 		goto out1;
2121 	}
2122 
2123 	/* Don't dump to files current user does not own */
2124 	if (vattr.va_uid != p->p_ucred->cr_uid) {
2125 		error = EFAULT;
2126 		goto out1;
2127 	}
2128 
2129 	VATTR_NULL(&vattr);
2130 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2131 	vattr.va_size = 0;
2132 	VOP_SETATTR(vp, &vattr, cred);
2133 	p->p_acflag |= ACORE;
2134 	vn_unlock(vp);
2135 
2136 	error = p->p_sysent->sv_coredump ?
2137 		  p->p_sysent->sv_coredump(lp, sig, vp, limit) : ENOSYS;
2138 
2139 out1:
2140 	lf.l_type = F_UNLCK;
2141 	VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, 0);
2142 out2:
2143 	error1 = vn_close(vp, FWRITE);
2144 	if (error == 0)
2145 		error = error1;
2146 	return (error);
2147 }
2148 
2149 /*
2150  * Nonexistent system call-- signal process (may want to handle it).
2151  * Flag error in case process won't see signal immediately (blocked or ignored).
2152  *
2153  * MPALMOSTSAFE
2154  */
2155 /* ARGSUSED */
2156 int
2157 sys_nosys(struct nosys_args *args)
2158 {
2159 	get_mplock();
2160 	lwpsignal(curproc, curthread->td_lwp, SIGSYS);
2161 	rel_mplock();
2162 	return (EINVAL);
2163 }
2164 
2165 /*
2166  * Send a SIGIO or SIGURG signal to a process or process group using
2167  * stored credentials rather than those of the current process.
2168  */
2169 void
2170 pgsigio(struct sigio *sigio, int sig, int checkctty)
2171 {
2172 	if (sigio == NULL)
2173 		return;
2174 
2175 	if (sigio->sio_pgid > 0) {
2176 		if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred,
2177 		             sigio->sio_proc))
2178 			ksignal(sigio->sio_proc, sig);
2179 	} else if (sigio->sio_pgid < 0) {
2180 		struct proc *p;
2181 
2182 		lockmgr(&sigio->sio_pgrp->pg_lock, LK_EXCLUSIVE);
2183 		LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
2184 			if (CANSIGIO(sigio->sio_ruid, sigio->sio_ucred, p) &&
2185 			    (checkctty == 0 || (p->p_flag & P_CONTROLT)))
2186 				ksignal(p, sig);
2187 		}
2188 		lockmgr(&sigio->sio_pgrp->pg_lock, LK_RELEASE);
2189 	}
2190 }
2191 
2192 static int
2193 filt_sigattach(struct knote *kn)
2194 {
2195 	struct proc *p = curproc;
2196 
2197 	kn->kn_ptr.p_proc = p;
2198 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
2199 
2200 	/* XXX lock the proc here while adding to the list? */
2201 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
2202 
2203 	return (0);
2204 }
2205 
2206 static void
2207 filt_sigdetach(struct knote *kn)
2208 {
2209 	struct proc *p = kn->kn_ptr.p_proc;
2210 
2211 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
2212 }
2213 
2214 /*
2215  * signal knotes are shared with proc knotes, so we apply a mask to
2216  * the hint in order to differentiate them from process hints.  This
2217  * could be avoided by using a signal-specific knote list, but probably
2218  * isn't worth the trouble.
2219  */
2220 static int
2221 filt_signal(struct knote *kn, long hint)
2222 {
2223 	if (hint & NOTE_SIGNAL) {
2224 		hint &= ~NOTE_SIGNAL;
2225 
2226 		if (kn->kn_id == hint)
2227 			kn->kn_data++;
2228 	}
2229 	return (kn->kn_data != 0);
2230 }
2231