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