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