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