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