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