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