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