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