]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_sig.c
When queuing ignored signal, only abort target thread' sleep if it is inside sigwait()
[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 #define SIGPROP_CANTMASK        0x40    /* non-maskable, catchable */
218
219 static int sigproptbl[NSIG] = {
220         [SIGHUP] =      SIGPROP_KILL,
221         [SIGINT] =      SIGPROP_KILL,
222         [SIGQUIT] =     SIGPROP_KILL | SIGPROP_CORE,
223         [SIGILL] =      SIGPROP_KILL | SIGPROP_CORE,
224         [SIGTRAP] =     SIGPROP_KILL | SIGPROP_CORE,
225         [SIGABRT] =     SIGPROP_KILL | SIGPROP_CORE,
226         [SIGEMT] =      SIGPROP_KILL | SIGPROP_CORE,
227         [SIGFPE] =      SIGPROP_KILL | SIGPROP_CORE,
228         [SIGKILL] =     SIGPROP_KILL,
229         [SIGBUS] =      SIGPROP_KILL | SIGPROP_CORE,
230         [SIGSEGV] =     SIGPROP_KILL | SIGPROP_CORE,
231         [SIGSYS] =      SIGPROP_KILL | SIGPROP_CORE,
232         [SIGPIPE] =     SIGPROP_KILL,
233         [SIGALRM] =     SIGPROP_KILL,
234         [SIGTERM] =     SIGPROP_KILL,
235         [SIGURG] =      SIGPROP_IGNORE,
236         [SIGSTOP] =     SIGPROP_STOP,
237         [SIGTSTP] =     SIGPROP_STOP | SIGPROP_TTYSTOP,
238         [SIGCONT] =     SIGPROP_IGNORE | SIGPROP_CONT,
239         [SIGCHLD] =     SIGPROP_IGNORE,
240         [SIGTTIN] =     SIGPROP_STOP | SIGPROP_TTYSTOP,
241         [SIGTTOU] =     SIGPROP_STOP | SIGPROP_TTYSTOP,
242         [SIGIO] =       SIGPROP_IGNORE,
243         [SIGXCPU] =     SIGPROP_KILL,
244         [SIGXFSZ] =     SIGPROP_KILL,
245         [SIGVTALRM] =   SIGPROP_KILL,
246         [SIGPROF] =     SIGPROP_KILL,
247         [SIGWINCH] =    SIGPROP_IGNORE,
248         [SIGINFO] =     SIGPROP_IGNORE,
249         [SIGUSR1] =     SIGPROP_KILL,
250         [SIGUSR2] =     SIGPROP_KILL,
251 };
252
253 sigset_t fastblock_mask;
254
255 static void
256 sigqueue_start(void)
257 {
258         ksiginfo_zone = uma_zcreate("ksiginfo", sizeof(ksiginfo_t),
259                 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
260         uma_prealloc(ksiginfo_zone, preallocate_siginfo);
261         p31b_setcfg(CTL_P1003_1B_REALTIME_SIGNALS, _POSIX_REALTIME_SIGNALS);
262         p31b_setcfg(CTL_P1003_1B_RTSIG_MAX, SIGRTMAX - SIGRTMIN + 1);
263         p31b_setcfg(CTL_P1003_1B_SIGQUEUE_MAX, max_pending_per_proc);
264         SIGFILLSET(fastblock_mask);
265         SIG_CANTMASK(fastblock_mask);
266 }
267
268 ksiginfo_t *
269 ksiginfo_alloc(int wait)
270 {
271         int flags;
272
273         flags = M_ZERO;
274         if (! wait)
275                 flags |= M_NOWAIT;
276         if (ksiginfo_zone != NULL)
277                 return ((ksiginfo_t *)uma_zalloc(ksiginfo_zone, flags));
278         return (NULL);
279 }
280
281 void
282 ksiginfo_free(ksiginfo_t *ksi)
283 {
284         uma_zfree(ksiginfo_zone, ksi);
285 }
286
287 static __inline int
288 ksiginfo_tryfree(ksiginfo_t *ksi)
289 {
290         if (!(ksi->ksi_flags & KSI_EXT)) {
291                 uma_zfree(ksiginfo_zone, ksi);
292                 return (1);
293         }
294         return (0);
295 }
296
297 void
298 sigqueue_init(sigqueue_t *list, struct proc *p)
299 {
300         SIGEMPTYSET(list->sq_signals);
301         SIGEMPTYSET(list->sq_kill);
302         SIGEMPTYSET(list->sq_ptrace);
303         TAILQ_INIT(&list->sq_list);
304         list->sq_proc = p;
305         list->sq_flags = SQ_INIT;
306 }
307
308 /*
309  * Get a signal's ksiginfo.
310  * Return:
311  *      0       -       signal not found
312  *      others  -       signal number
313  */
314 static int
315 sigqueue_get(sigqueue_t *sq, int signo, ksiginfo_t *si)
316 {
317         struct proc *p = sq->sq_proc;
318         struct ksiginfo *ksi, *next;
319         int count = 0;
320
321         KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
322
323         if (!SIGISMEMBER(sq->sq_signals, signo))
324                 return (0);
325
326         if (SIGISMEMBER(sq->sq_ptrace, signo)) {
327                 count++;
328                 SIGDELSET(sq->sq_ptrace, signo);
329                 si->ksi_flags |= KSI_PTRACE;
330         }
331         if (SIGISMEMBER(sq->sq_kill, signo)) {
332                 count++;
333                 if (count == 1)
334                         SIGDELSET(sq->sq_kill, signo);
335         }
336
337         TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
338                 if (ksi->ksi_signo == signo) {
339                         if (count == 0) {
340                                 TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
341                                 ksi->ksi_sigq = NULL;
342                                 ksiginfo_copy(ksi, si);
343                                 if (ksiginfo_tryfree(ksi) && p != NULL)
344                                         p->p_pendingcnt--;
345                         }
346                         if (++count > 1)
347                                 break;
348                 }
349         }
350
351         if (count <= 1)
352                 SIGDELSET(sq->sq_signals, signo);
353         si->ksi_signo = signo;
354         return (signo);
355 }
356
357 void
358 sigqueue_take(ksiginfo_t *ksi)
359 {
360         struct ksiginfo *kp;
361         struct proc     *p;
362         sigqueue_t      *sq;
363
364         if (ksi == NULL || (sq = ksi->ksi_sigq) == NULL)
365                 return;
366
367         p = sq->sq_proc;
368         TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
369         ksi->ksi_sigq = NULL;
370         if (!(ksi->ksi_flags & KSI_EXT) && p != NULL)
371                 p->p_pendingcnt--;
372
373         for (kp = TAILQ_FIRST(&sq->sq_list); kp != NULL;
374              kp = TAILQ_NEXT(kp, ksi_link)) {
375                 if (kp->ksi_signo == ksi->ksi_signo)
376                         break;
377         }
378         if (kp == NULL && !SIGISMEMBER(sq->sq_kill, ksi->ksi_signo) &&
379             !SIGISMEMBER(sq->sq_ptrace, ksi->ksi_signo))
380                 SIGDELSET(sq->sq_signals, ksi->ksi_signo);
381 }
382
383 static int
384 sigqueue_add(sigqueue_t *sq, int signo, ksiginfo_t *si)
385 {
386         struct proc *p = sq->sq_proc;
387         struct ksiginfo *ksi;
388         int ret = 0;
389
390         KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
391
392         /*
393          * SIGKILL/SIGSTOP cannot be caught or masked, so take the fast path
394          * for these signals.
395          */
396         if (signo == SIGKILL || signo == SIGSTOP || si == NULL) {
397                 SIGADDSET(sq->sq_kill, signo);
398                 goto out_set_bit;
399         }
400
401         /* directly insert the ksi, don't copy it */
402         if (si->ksi_flags & KSI_INS) {
403                 if (si->ksi_flags & KSI_HEAD)
404                         TAILQ_INSERT_HEAD(&sq->sq_list, si, ksi_link);
405                 else
406                         TAILQ_INSERT_TAIL(&sq->sq_list, si, ksi_link);
407                 si->ksi_sigq = sq;
408                 goto out_set_bit;
409         }
410
411         if (__predict_false(ksiginfo_zone == NULL)) {
412                 SIGADDSET(sq->sq_kill, signo);
413                 goto out_set_bit;
414         }
415
416         if (p != NULL && p->p_pendingcnt >= max_pending_per_proc) {
417                 signal_overflow++;
418                 ret = EAGAIN;
419         } else if ((ksi = ksiginfo_alloc(0)) == NULL) {
420                 signal_alloc_fail++;
421                 ret = EAGAIN;
422         } else {
423                 if (p != NULL)
424                         p->p_pendingcnt++;
425                 ksiginfo_copy(si, ksi);
426                 ksi->ksi_signo = signo;
427                 if (si->ksi_flags & KSI_HEAD)
428                         TAILQ_INSERT_HEAD(&sq->sq_list, ksi, ksi_link);
429                 else
430                         TAILQ_INSERT_TAIL(&sq->sq_list, ksi, ksi_link);
431                 ksi->ksi_sigq = sq;
432         }
433
434         if (ret != 0) {
435                 if ((si->ksi_flags & KSI_PTRACE) != 0) {
436                         SIGADDSET(sq->sq_ptrace, signo);
437                         ret = 0;
438                         goto out_set_bit;
439                 } else if ((si->ksi_flags & KSI_TRAP) != 0 ||
440                     (si->ksi_flags & KSI_SIGQ) == 0) {
441                         SIGADDSET(sq->sq_kill, signo);
442                         ret = 0;
443                         goto out_set_bit;
444                 }
445                 return (ret);
446         }
447
448 out_set_bit:
449         SIGADDSET(sq->sq_signals, signo);
450         return (ret);
451 }
452
453 void
454 sigqueue_flush(sigqueue_t *sq)
455 {
456         struct proc *p = sq->sq_proc;
457         ksiginfo_t *ksi;
458
459         KASSERT(sq->sq_flags & SQ_INIT, ("sigqueue not inited"));
460
461         if (p != NULL)
462                 PROC_LOCK_ASSERT(p, MA_OWNED);
463
464         while ((ksi = TAILQ_FIRST(&sq->sq_list)) != NULL) {
465                 TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
466                 ksi->ksi_sigq = NULL;
467                 if (ksiginfo_tryfree(ksi) && p != NULL)
468                         p->p_pendingcnt--;
469         }
470
471         SIGEMPTYSET(sq->sq_signals);
472         SIGEMPTYSET(sq->sq_kill);
473         SIGEMPTYSET(sq->sq_ptrace);
474 }
475
476 static void
477 sigqueue_move_set(sigqueue_t *src, sigqueue_t *dst, const sigset_t *set)
478 {
479         sigset_t tmp;
480         struct proc *p1, *p2;
481         ksiginfo_t *ksi, *next;
482
483         KASSERT(src->sq_flags & SQ_INIT, ("src sigqueue not inited"));
484         KASSERT(dst->sq_flags & SQ_INIT, ("dst sigqueue not inited"));
485         p1 = src->sq_proc;
486         p2 = dst->sq_proc;
487         /* Move siginfo to target list */
488         TAILQ_FOREACH_SAFE(ksi, &src->sq_list, ksi_link, next) {
489                 if (SIGISMEMBER(*set, ksi->ksi_signo)) {
490                         TAILQ_REMOVE(&src->sq_list, ksi, ksi_link);
491                         if (p1 != NULL)
492                                 p1->p_pendingcnt--;
493                         TAILQ_INSERT_TAIL(&dst->sq_list, ksi, ksi_link);
494                         ksi->ksi_sigq = dst;
495                         if (p2 != NULL)
496                                 p2->p_pendingcnt++;
497                 }
498         }
499
500         /* Move pending bits to target list */
501         tmp = src->sq_kill;
502         SIGSETAND(tmp, *set);
503         SIGSETOR(dst->sq_kill, tmp);
504         SIGSETNAND(src->sq_kill, tmp);
505
506         tmp = src->sq_ptrace;
507         SIGSETAND(tmp, *set);
508         SIGSETOR(dst->sq_ptrace, tmp);
509         SIGSETNAND(src->sq_ptrace, tmp);
510
511         tmp = src->sq_signals;
512         SIGSETAND(tmp, *set);
513         SIGSETOR(dst->sq_signals, tmp);
514         SIGSETNAND(src->sq_signals, tmp);
515 }
516
517 #if 0
518 static void
519 sigqueue_move(sigqueue_t *src, sigqueue_t *dst, int signo)
520 {
521         sigset_t set;
522
523         SIGEMPTYSET(set);
524         SIGADDSET(set, signo);
525         sigqueue_move_set(src, dst, &set);
526 }
527 #endif
528
529 static void
530 sigqueue_delete_set(sigqueue_t *sq, const sigset_t *set)
531 {
532         struct proc *p = sq->sq_proc;
533         ksiginfo_t *ksi, *next;
534
535         KASSERT(sq->sq_flags & SQ_INIT, ("src sigqueue not inited"));
536
537         /* Remove siginfo queue */
538         TAILQ_FOREACH_SAFE(ksi, &sq->sq_list, ksi_link, next) {
539                 if (SIGISMEMBER(*set, ksi->ksi_signo)) {
540                         TAILQ_REMOVE(&sq->sq_list, ksi, ksi_link);
541                         ksi->ksi_sigq = NULL;
542                         if (ksiginfo_tryfree(ksi) && p != NULL)
543                                 p->p_pendingcnt--;
544                 }
545         }
546         SIGSETNAND(sq->sq_kill, *set);
547         SIGSETNAND(sq->sq_ptrace, *set);
548         SIGSETNAND(sq->sq_signals, *set);
549 }
550
551 void
552 sigqueue_delete(sigqueue_t *sq, int signo)
553 {
554         sigset_t set;
555
556         SIGEMPTYSET(set);
557         SIGADDSET(set, signo);
558         sigqueue_delete_set(sq, &set);
559 }
560
561 /* Remove a set of signals for a process */
562 static void
563 sigqueue_delete_set_proc(struct proc *p, const sigset_t *set)
564 {
565         sigqueue_t worklist;
566         struct thread *td0;
567
568         PROC_LOCK_ASSERT(p, MA_OWNED);
569
570         sigqueue_init(&worklist, NULL);
571         sigqueue_move_set(&p->p_sigqueue, &worklist, set);
572
573         FOREACH_THREAD_IN_PROC(p, td0)
574                 sigqueue_move_set(&td0->td_sigqueue, &worklist, set);
575
576         sigqueue_flush(&worklist);
577 }
578
579 void
580 sigqueue_delete_proc(struct proc *p, int signo)
581 {
582         sigset_t set;
583
584         SIGEMPTYSET(set);
585         SIGADDSET(set, signo);
586         sigqueue_delete_set_proc(p, &set);
587 }
588
589 static void
590 sigqueue_delete_stopmask_proc(struct proc *p)
591 {
592         sigset_t set;
593
594         SIGEMPTYSET(set);
595         SIGADDSET(set, SIGSTOP);
596         SIGADDSET(set, SIGTSTP);
597         SIGADDSET(set, SIGTTIN);
598         SIGADDSET(set, SIGTTOU);
599         sigqueue_delete_set_proc(p, &set);
600 }
601
602 /*
603  * Determine signal that should be delivered to thread td, the current
604  * thread, 0 if none.  If there is a pending stop signal with default
605  * action, the process stops in issignal().
606  */
607 int
608 cursig(struct thread *td)
609 {
610         PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
611         mtx_assert(&td->td_proc->p_sigacts->ps_mtx, MA_OWNED);
612         THREAD_LOCK_ASSERT(td, MA_NOTOWNED);
613         return (SIGPENDING(td) ? issignal(td) : 0);
614 }
615
616 /*
617  * Arrange for ast() to handle unmasked pending signals on return to user
618  * mode.  This must be called whenever a signal is added to td_sigqueue or
619  * unmasked in td_sigmask.
620  */
621 void
622 signotify(struct thread *td)
623 {
624
625         PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
626
627         if (SIGPENDING(td)) {
628                 thread_lock(td);
629                 td->td_flags |= TDF_NEEDSIGCHK | TDF_ASTPENDING;
630                 thread_unlock(td);
631         }
632 }
633
634 /*
635  * Returns 1 (true) if altstack is configured for the thread, and the
636  * passed stack bottom address falls into the altstack range.  Handles
637  * the 43 compat special case where the alt stack size is zero.
638  */
639 int
640 sigonstack(size_t sp)
641 {
642         struct thread *td;
643
644         td = curthread;
645         if ((td->td_pflags & TDP_ALTSTACK) == 0)
646                 return (0);
647 #if defined(COMPAT_43)
648         if (SV_PROC_FLAG(td->td_proc, SV_AOUT) && td->td_sigstk.ss_size == 0)
649                 return ((td->td_sigstk.ss_flags & SS_ONSTACK) != 0);
650 #endif
651         return (sp >= (size_t)td->td_sigstk.ss_sp &&
652             sp < td->td_sigstk.ss_size + (size_t)td->td_sigstk.ss_sp);
653 }
654
655 static __inline int
656 sigprop(int sig)
657 {
658
659         if (sig > 0 && sig < nitems(sigproptbl))
660                 return (sigproptbl[sig]);
661         return (0);
662 }
663
664 int
665 sig_ffs(sigset_t *set)
666 {
667         int i;
668
669         for (i = 0; i < _SIG_WORDS; i++)
670                 if (set->__bits[i])
671                         return (ffs(set->__bits[i]) + (i * 32));
672         return (0);
673 }
674
675 static bool
676 sigact_flag_test(const struct sigaction *act, int flag)
677 {
678
679         /*
680          * SA_SIGINFO is reset when signal disposition is set to
681          * ignore or default.  Other flags are kept according to user
682          * settings.
683          */
684         return ((act->sa_flags & flag) != 0 && (flag != SA_SIGINFO ||
685             ((__sighandler_t *)act->sa_sigaction != SIG_IGN &&
686             (__sighandler_t *)act->sa_sigaction != SIG_DFL)));
687 }
688
689 /*
690  * kern_sigaction
691  * sigaction
692  * freebsd4_sigaction
693  * osigaction
694  */
695 int
696 kern_sigaction(struct thread *td, int sig, const struct sigaction *act,
697     struct sigaction *oact, int flags)
698 {
699         struct sigacts *ps;
700         struct proc *p = td->td_proc;
701
702         if (!_SIG_VALID(sig))
703                 return (EINVAL);
704         if (act != NULL && act->sa_handler != SIG_DFL &&
705             act->sa_handler != SIG_IGN && (act->sa_flags & ~(SA_ONSTACK |
706             SA_RESTART | SA_RESETHAND | SA_NOCLDSTOP | SA_NODEFER |
707             SA_NOCLDWAIT | SA_SIGINFO)) != 0)
708                 return (EINVAL);
709
710         PROC_LOCK(p);
711         ps = p->p_sigacts;
712         mtx_lock(&ps->ps_mtx);
713         if (oact) {
714                 memset(oact, 0, sizeof(*oact));
715                 oact->sa_mask = ps->ps_catchmask[_SIG_IDX(sig)];
716                 if (SIGISMEMBER(ps->ps_sigonstack, sig))
717                         oact->sa_flags |= SA_ONSTACK;
718                 if (!SIGISMEMBER(ps->ps_sigintr, sig))
719                         oact->sa_flags |= SA_RESTART;
720                 if (SIGISMEMBER(ps->ps_sigreset, sig))
721                         oact->sa_flags |= SA_RESETHAND;
722                 if (SIGISMEMBER(ps->ps_signodefer, sig))
723                         oact->sa_flags |= SA_NODEFER;
724                 if (SIGISMEMBER(ps->ps_siginfo, sig)) {
725                         oact->sa_flags |= SA_SIGINFO;
726                         oact->sa_sigaction =
727                             (__siginfohandler_t *)ps->ps_sigact[_SIG_IDX(sig)];
728                 } else
729                         oact->sa_handler = ps->ps_sigact[_SIG_IDX(sig)];
730                 if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDSTOP)
731                         oact->sa_flags |= SA_NOCLDSTOP;
732                 if (sig == SIGCHLD && ps->ps_flag & PS_NOCLDWAIT)
733                         oact->sa_flags |= SA_NOCLDWAIT;
734         }
735         if (act) {
736                 if ((sig == SIGKILL || sig == SIGSTOP) &&
737                     act->sa_handler != SIG_DFL) {
738                         mtx_unlock(&ps->ps_mtx);
739                         PROC_UNLOCK(p);
740                         return (EINVAL);
741                 }
742
743                 /*
744                  * Change setting atomically.
745                  */
746
747                 ps->ps_catchmask[_SIG_IDX(sig)] = act->sa_mask;
748                 SIG_CANTMASK(ps->ps_catchmask[_SIG_IDX(sig)]);
749                 if (sigact_flag_test(act, SA_SIGINFO)) {
750                         ps->ps_sigact[_SIG_IDX(sig)] =
751                             (__sighandler_t *)act->sa_sigaction;
752                         SIGADDSET(ps->ps_siginfo, sig);
753                 } else {
754                         ps->ps_sigact[_SIG_IDX(sig)] = act->sa_handler;
755                         SIGDELSET(ps->ps_siginfo, sig);
756                 }
757                 if (!sigact_flag_test(act, SA_RESTART))
758                         SIGADDSET(ps->ps_sigintr, sig);
759                 else
760                         SIGDELSET(ps->ps_sigintr, sig);
761                 if (sigact_flag_test(act, SA_ONSTACK))
762                         SIGADDSET(ps->ps_sigonstack, sig);
763                 else
764                         SIGDELSET(ps->ps_sigonstack, sig);
765                 if (sigact_flag_test(act, SA_RESETHAND))
766                         SIGADDSET(ps->ps_sigreset, sig);
767                 else
768                         SIGDELSET(ps->ps_sigreset, sig);
769                 if (sigact_flag_test(act, SA_NODEFER))
770                         SIGADDSET(ps->ps_signodefer, sig);
771                 else
772                         SIGDELSET(ps->ps_signodefer, sig);
773                 if (sig == SIGCHLD) {
774                         if (act->sa_flags & SA_NOCLDSTOP)
775                                 ps->ps_flag |= PS_NOCLDSTOP;
776                         else
777                                 ps->ps_flag &= ~PS_NOCLDSTOP;
778                         if (act->sa_flags & SA_NOCLDWAIT) {
779                                 /*
780                                  * Paranoia: since SA_NOCLDWAIT is implemented
781                                  * by reparenting the dying child to PID 1 (and
782                                  * trust it to reap the zombie), PID 1 itself
783                                  * is forbidden to set SA_NOCLDWAIT.
784                                  */
785                                 if (p->p_pid == 1)
786                                         ps->ps_flag &= ~PS_NOCLDWAIT;
787                                 else
788                                         ps->ps_flag |= PS_NOCLDWAIT;
789                         } else
790                                 ps->ps_flag &= ~PS_NOCLDWAIT;
791                         if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
792                                 ps->ps_flag |= PS_CLDSIGIGN;
793                         else
794                                 ps->ps_flag &= ~PS_CLDSIGIGN;
795                 }
796                 /*
797                  * Set bit in ps_sigignore for signals that are set to SIG_IGN,
798                  * and for signals set to SIG_DFL where the default is to
799                  * ignore. However, don't put SIGCONT in ps_sigignore, as we
800                  * have to restart the process.
801                  */
802                 if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
803                     (sigprop(sig) & SIGPROP_IGNORE &&
804                      ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)) {
805                         /* never to be seen again */
806                         sigqueue_delete_proc(p, sig);
807                         if (sig != SIGCONT)
808                                 /* easier in psignal */
809                                 SIGADDSET(ps->ps_sigignore, sig);
810                         SIGDELSET(ps->ps_sigcatch, sig);
811                 } else {
812                         SIGDELSET(ps->ps_sigignore, sig);
813                         if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL)
814                                 SIGDELSET(ps->ps_sigcatch, sig);
815                         else
816                                 SIGADDSET(ps->ps_sigcatch, sig);
817                 }
818 #ifdef COMPAT_FREEBSD4
819                 if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
820                     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
821                     (flags & KSA_FREEBSD4) == 0)
822                         SIGDELSET(ps->ps_freebsd4, sig);
823                 else
824                         SIGADDSET(ps->ps_freebsd4, sig);
825 #endif
826 #ifdef COMPAT_43
827                 if (ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN ||
828                     ps->ps_sigact[_SIG_IDX(sig)] == SIG_DFL ||
829                     (flags & KSA_OSIGSET) == 0)
830                         SIGDELSET(ps->ps_osigset, sig);
831                 else
832                         SIGADDSET(ps->ps_osigset, sig);
833 #endif
834         }
835         mtx_unlock(&ps->ps_mtx);
836         PROC_UNLOCK(p);
837         return (0);
838 }
839
840 #ifndef _SYS_SYSPROTO_H_
841 struct sigaction_args {
842         int     sig;
843         struct  sigaction *act;
844         struct  sigaction *oact;
845 };
846 #endif
847 int
848 sys_sigaction(struct thread *td, struct sigaction_args *uap)
849 {
850         struct sigaction act, oact;
851         struct sigaction *actp, *oactp;
852         int error;
853
854         actp = (uap->act != NULL) ? &act : NULL;
855         oactp = (uap->oact != NULL) ? &oact : NULL;
856         if (actp) {
857                 error = copyin(uap->act, actp, sizeof(act));
858                 if (error)
859                         return (error);
860         }
861         error = kern_sigaction(td, uap->sig, actp, oactp, 0);
862         if (oactp && !error)
863                 error = copyout(oactp, uap->oact, sizeof(oact));
864         return (error);
865 }
866
867 #ifdef COMPAT_FREEBSD4
868 #ifndef _SYS_SYSPROTO_H_
869 struct freebsd4_sigaction_args {
870         int     sig;
871         struct  sigaction *act;
872         struct  sigaction *oact;
873 };
874 #endif
875 int
876 freebsd4_sigaction(struct thread *td, struct freebsd4_sigaction_args *uap)
877 {
878         struct sigaction act, oact;
879         struct sigaction *actp, *oactp;
880         int error;
881
882         actp = (uap->act != NULL) ? &act : NULL;
883         oactp = (uap->oact != NULL) ? &oact : NULL;
884         if (actp) {
885                 error = copyin(uap->act, actp, sizeof(act));
886                 if (error)
887                         return (error);
888         }
889         error = kern_sigaction(td, uap->sig, actp, oactp, KSA_FREEBSD4);
890         if (oactp && !error)
891                 error = copyout(oactp, uap->oact, sizeof(oact));
892         return (error);
893 }
894 #endif  /* COMAPT_FREEBSD4 */
895
896 #ifdef COMPAT_43        /* XXX - COMPAT_FBSD3 */
897 #ifndef _SYS_SYSPROTO_H_
898 struct osigaction_args {
899         int     signum;
900         struct  osigaction *nsa;
901         struct  osigaction *osa;
902 };
903 #endif
904 int
905 osigaction(struct thread *td, struct osigaction_args *uap)
906 {
907         struct osigaction sa;
908         struct sigaction nsa, osa;
909         struct sigaction *nsap, *osap;
910         int error;
911
912         if (uap->signum <= 0 || uap->signum >= ONSIG)
913                 return (EINVAL);
914
915         nsap = (uap->nsa != NULL) ? &nsa : NULL;
916         osap = (uap->osa != NULL) ? &osa : NULL;
917
918         if (nsap) {
919                 error = copyin(uap->nsa, &sa, sizeof(sa));
920                 if (error)
921                         return (error);
922                 nsap->sa_handler = sa.sa_handler;
923                 nsap->sa_flags = sa.sa_flags;
924                 OSIG2SIG(sa.sa_mask, nsap->sa_mask);
925         }
926         error = kern_sigaction(td, uap->signum, nsap, osap, KSA_OSIGSET);
927         if (osap && !error) {
928                 sa.sa_handler = osap->sa_handler;
929                 sa.sa_flags = osap->sa_flags;
930                 SIG2OSIG(osap->sa_mask, sa.sa_mask);
931                 error = copyout(&sa, uap->osa, sizeof(sa));
932         }
933         return (error);
934 }
935
936 #if !defined(__i386__)
937 /* Avoid replicating the same stub everywhere */
938 int
939 osigreturn(struct thread *td, struct osigreturn_args *uap)
940 {
941
942         return (nosys(td, (struct nosys_args *)uap));
943 }
944 #endif
945 #endif /* COMPAT_43 */
946
947 /*
948  * Initialize signal state for process 0;
949  * set to ignore signals that are ignored by default.
950  */
951 void
952 siginit(struct proc *p)
953 {
954         int i;
955         struct sigacts *ps;
956
957         PROC_LOCK(p);
958         ps = p->p_sigacts;
959         mtx_lock(&ps->ps_mtx);
960         for (i = 1; i <= NSIG; i++) {
961                 if (sigprop(i) & SIGPROP_IGNORE && i != SIGCONT) {
962                         SIGADDSET(ps->ps_sigignore, i);
963                 }
964         }
965         mtx_unlock(&ps->ps_mtx);
966         PROC_UNLOCK(p);
967 }
968
969 /*
970  * Reset specified signal to the default disposition.
971  */
972 static void
973 sigdflt(struct sigacts *ps, int sig)
974 {
975
976         mtx_assert(&ps->ps_mtx, MA_OWNED);
977         SIGDELSET(ps->ps_sigcatch, sig);
978         if ((sigprop(sig) & SIGPROP_IGNORE) != 0 && sig != SIGCONT)
979                 SIGADDSET(ps->ps_sigignore, sig);
980         ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
981         SIGDELSET(ps->ps_siginfo, sig);
982 }
983
984 /*
985  * Reset signals for an exec of the specified process.
986  */
987 void
988 execsigs(struct proc *p)
989 {
990         struct sigacts *ps;
991         struct thread *td;
992
993         /*
994          * Reset caught signals.  Held signals remain held
995          * through td_sigmask (unless they were caught,
996          * and are now ignored by default).
997          */
998         PROC_LOCK_ASSERT(p, MA_OWNED);
999         ps = p->p_sigacts;
1000         mtx_lock(&ps->ps_mtx);
1001         sig_drop_caught(p);
1002
1003         /*
1004          * Reset stack state to the user stack.
1005          * Clear set of signals caught on the signal stack.
1006          */
1007         td = curthread;
1008         MPASS(td->td_proc == p);
1009         td->td_sigstk.ss_flags = SS_DISABLE;
1010         td->td_sigstk.ss_size = 0;
1011         td->td_sigstk.ss_sp = 0;
1012         td->td_pflags &= ~TDP_ALTSTACK;
1013         /*
1014          * Reset no zombies if child dies flag as Solaris does.
1015          */
1016         ps->ps_flag &= ~(PS_NOCLDWAIT | PS_CLDSIGIGN);
1017         if (ps->ps_sigact[_SIG_IDX(SIGCHLD)] == SIG_IGN)
1018                 ps->ps_sigact[_SIG_IDX(SIGCHLD)] = SIG_DFL;
1019         mtx_unlock(&ps->ps_mtx);
1020 }
1021
1022 /*
1023  * kern_sigprocmask()
1024  *
1025  *      Manipulate signal mask.
1026  */
1027 int
1028 kern_sigprocmask(struct thread *td, int how, sigset_t *set, sigset_t *oset,
1029     int flags)
1030 {
1031         sigset_t new_block, oset1;
1032         struct proc *p;
1033         int error;
1034
1035         p = td->td_proc;
1036         if ((flags & SIGPROCMASK_PROC_LOCKED) != 0)
1037                 PROC_LOCK_ASSERT(p, MA_OWNED);
1038         else
1039                 PROC_LOCK(p);
1040         mtx_assert(&p->p_sigacts->ps_mtx, (flags & SIGPROCMASK_PS_LOCKED) != 0
1041             ? MA_OWNED : MA_NOTOWNED);
1042         if (oset != NULL)
1043                 *oset = td->td_sigmask;
1044
1045         error = 0;
1046         if (set != NULL) {
1047                 switch (how) {
1048                 case SIG_BLOCK:
1049                         SIG_CANTMASK(*set);
1050                         oset1 = td->td_sigmask;
1051                         SIGSETOR(td->td_sigmask, *set);
1052                         new_block = td->td_sigmask;
1053                         SIGSETNAND(new_block, oset1);
1054                         break;
1055                 case SIG_UNBLOCK:
1056                         SIGSETNAND(td->td_sigmask, *set);
1057                         signotify(td);
1058                         goto out;
1059                 case SIG_SETMASK:
1060                         SIG_CANTMASK(*set);
1061                         oset1 = td->td_sigmask;
1062                         if (flags & SIGPROCMASK_OLD)
1063                                 SIGSETLO(td->td_sigmask, *set);
1064                         else
1065                                 td->td_sigmask = *set;
1066                         new_block = td->td_sigmask;
1067                         SIGSETNAND(new_block, oset1);
1068                         signotify(td);
1069                         break;
1070                 default:
1071                         error = EINVAL;
1072                         goto out;
1073                 }
1074
1075                 /*
1076                  * The new_block set contains signals that were not previously
1077                  * blocked, but are blocked now.
1078                  *
1079                  * In case we block any signal that was not previously blocked
1080                  * for td, and process has the signal pending, try to schedule
1081                  * signal delivery to some thread that does not block the
1082                  * signal, possibly waking it up.
1083                  */
1084                 if (p->p_numthreads != 1)
1085                         reschedule_signals(p, new_block, flags);
1086         }
1087
1088 out:
1089         if (!(flags & SIGPROCMASK_PROC_LOCKED))
1090                 PROC_UNLOCK(p);
1091         return (error);
1092 }
1093
1094 #ifndef _SYS_SYSPROTO_H_
1095 struct sigprocmask_args {
1096         int     how;
1097         const sigset_t *set;
1098         sigset_t *oset;
1099 };
1100 #endif
1101 int
1102 sys_sigprocmask(struct thread *td, struct sigprocmask_args *uap)
1103 {
1104         sigset_t set, oset;
1105         sigset_t *setp, *osetp;
1106         int error;
1107
1108         setp = (uap->set != NULL) ? &set : NULL;
1109         osetp = (uap->oset != NULL) ? &oset : NULL;
1110         if (setp) {
1111                 error = copyin(uap->set, setp, sizeof(set));
1112                 if (error)
1113                         return (error);
1114         }
1115         error = kern_sigprocmask(td, uap->how, setp, osetp, 0);
1116         if (osetp && !error) {
1117                 error = copyout(osetp, uap->oset, sizeof(oset));
1118         }
1119         return (error);
1120 }
1121
1122 #ifdef COMPAT_43        /* XXX - COMPAT_FBSD3 */
1123 #ifndef _SYS_SYSPROTO_H_
1124 struct osigprocmask_args {
1125         int     how;
1126         osigset_t mask;
1127 };
1128 #endif
1129 int
1130 osigprocmask(struct thread *td, struct osigprocmask_args *uap)
1131 {
1132         sigset_t set, oset;
1133         int error;
1134
1135         OSIG2SIG(uap->mask, set);
1136         error = kern_sigprocmask(td, uap->how, &set, &oset, 1);
1137         SIG2OSIG(oset, td->td_retval[0]);
1138         return (error);
1139 }
1140 #endif /* COMPAT_43 */
1141
1142 int
1143 sys_sigwait(struct thread *td, struct sigwait_args *uap)
1144 {
1145         ksiginfo_t ksi;
1146         sigset_t set;
1147         int error;
1148
1149         error = copyin(uap->set, &set, sizeof(set));
1150         if (error) {
1151                 td->td_retval[0] = error;
1152                 return (0);
1153         }
1154
1155         error = kern_sigtimedwait(td, set, &ksi, NULL);
1156         if (error) {
1157                 /*
1158                  * sigwait() function shall not return EINTR, but
1159                  * the syscall does.  Non-ancient libc provides the
1160                  * wrapper which hides EINTR.  Otherwise, EINTR return
1161                  * is used by libthr to handle required cancellation
1162                  * point in the sigwait().
1163                  */
1164                 if (error == EINTR && td->td_proc->p_osrel < P_OSREL_SIGWAIT)
1165                         return (ERESTART);
1166                 td->td_retval[0] = error;
1167                 return (0);
1168         }
1169
1170         error = copyout(&ksi.ksi_signo, uap->sig, sizeof(ksi.ksi_signo));
1171         td->td_retval[0] = error;
1172         return (0);
1173 }
1174
1175 int
1176 sys_sigtimedwait(struct thread *td, struct sigtimedwait_args *uap)
1177 {
1178         struct timespec ts;
1179         struct timespec *timeout;
1180         sigset_t set;
1181         ksiginfo_t ksi;
1182         int error;
1183
1184         if (uap->timeout) {
1185                 error = copyin(uap->timeout, &ts, sizeof(ts));
1186                 if (error)
1187                         return (error);
1188
1189                 timeout = &ts;
1190         } else
1191                 timeout = NULL;
1192
1193         error = copyin(uap->set, &set, sizeof(set));
1194         if (error)
1195                 return (error);
1196
1197         error = kern_sigtimedwait(td, set, &ksi, timeout);
1198         if (error)
1199                 return (error);
1200
1201         if (uap->info)
1202                 error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1203
1204         if (error == 0)
1205                 td->td_retval[0] = ksi.ksi_signo;
1206         return (error);
1207 }
1208
1209 int
1210 sys_sigwaitinfo(struct thread *td, struct sigwaitinfo_args *uap)
1211 {
1212         ksiginfo_t ksi;
1213         sigset_t set;
1214         int error;
1215
1216         error = copyin(uap->set, &set, sizeof(set));
1217         if (error)
1218                 return (error);
1219
1220         error = kern_sigtimedwait(td, set, &ksi, NULL);
1221         if (error)
1222                 return (error);
1223
1224         if (uap->info)
1225                 error = copyout(&ksi.ksi_info, uap->info, sizeof(siginfo_t));
1226
1227         if (error == 0)
1228                 td->td_retval[0] = ksi.ksi_signo;
1229         return (error);
1230 }
1231
1232 static void
1233 proc_td_siginfo_capture(struct thread *td, siginfo_t *si)
1234 {
1235         struct thread *thr;
1236
1237         FOREACH_THREAD_IN_PROC(td->td_proc, thr) {
1238                 if (thr == td)
1239                         thr->td_si = *si;
1240                 else
1241                         thr->td_si.si_signo = 0;
1242         }
1243 }
1244
1245 int
1246 kern_sigtimedwait(struct thread *td, sigset_t waitset, ksiginfo_t *ksi,
1247         struct timespec *timeout)
1248 {
1249         struct sigacts *ps;
1250         sigset_t saved_mask, new_block;
1251         struct proc *p;
1252         int error, sig, timo, timevalid = 0;
1253         struct timespec rts, ets, ts;
1254         struct timeval tv;
1255         bool traced;
1256
1257         p = td->td_proc;
1258         error = 0;
1259         ets.tv_sec = 0;
1260         ets.tv_nsec = 0;
1261         traced = false;
1262
1263         /* Ensure the sigfastblock value is up to date. */
1264         sigfastblock_fetch(td);
1265
1266         if (timeout != NULL) {
1267                 if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) {
1268                         timevalid = 1;
1269                         getnanouptime(&rts);
1270                         timespecadd(&rts, timeout, &ets);
1271                 }
1272         }
1273         ksiginfo_init(ksi);
1274         /* Some signals can not be waited for. */
1275         SIG_CANTMASK(waitset);
1276         ps = p->p_sigacts;
1277         PROC_LOCK(p);
1278         saved_mask = td->td_sigmask;
1279         SIGSETNAND(td->td_sigmask, waitset);
1280         if ((p->p_sysent->sv_flags & SV_SIG_DISCIGN) != 0 ||
1281             !kern_sig_discard_ign) {
1282                 thread_lock(td);
1283                 td->td_flags |= TDF_SIGWAIT;
1284                 thread_unlock(td);
1285         }
1286         for (;;) {
1287                 mtx_lock(&ps->ps_mtx);
1288                 sig = cursig(td);
1289                 mtx_unlock(&ps->ps_mtx);
1290                 KASSERT(sig >= 0, ("sig %d", sig));
1291                 if (sig != 0 && SIGISMEMBER(waitset, sig)) {
1292                         if (sigqueue_get(&td->td_sigqueue, sig, ksi) != 0 ||
1293                             sigqueue_get(&p->p_sigqueue, sig, ksi) != 0) {
1294                                 error = 0;
1295                                 break;
1296                         }
1297                 }
1298
1299                 if (error != 0)
1300                         break;
1301
1302                 /*
1303                  * POSIX says this must be checked after looking for pending
1304                  * signals.
1305                  */
1306                 if (timeout != NULL) {
1307                         if (!timevalid) {
1308                                 error = EINVAL;
1309                                 break;
1310                         }
1311                         getnanouptime(&rts);
1312                         if (timespeccmp(&rts, &ets, >=)) {
1313                                 error = EAGAIN;
1314                                 break;
1315                         }
1316                         timespecsub(&ets, &rts, &ts);
1317                         TIMESPEC_TO_TIMEVAL(&tv, &ts);
1318                         timo = tvtohz(&tv);
1319                 } else {
1320                         timo = 0;
1321                 }
1322
1323                 if (traced) {
1324                         error = EINTR;
1325                         break;
1326                 }
1327
1328                 error = msleep(&p->p_sigacts, &p->p_mtx, PPAUSE | PCATCH,
1329                     "sigwait", timo);
1330
1331                 /* The syscalls can not be restarted. */
1332                 if (error == ERESTART)
1333                         error = EINTR;
1334
1335                 /* We will calculate timeout by ourself. */
1336                 if (timeout != NULL && error == EAGAIN)
1337                         error = 0;
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 code, sig;
2014
2015         p = td->td_proc;
2016         sig = ksi->ksi_signo;
2017         code = ksi->ksi_code;
2018         KASSERT(_SIG_VALID(sig), ("invalid signal"));
2019
2020         sigfastblock_fetch(td);
2021         PROC_LOCK(p);
2022         ps = p->p_sigacts;
2023         mtx_lock(&ps->ps_mtx);
2024         sigmask = td->td_sigmask;
2025         if (td->td_sigblock_val != 0)
2026                 SIGSETOR(sigmask, fastblock_mask);
2027         if ((p->p_flag & P_TRACED) == 0 && SIGISMEMBER(ps->ps_sigcatch, sig) &&
2028             !SIGISMEMBER(sigmask, sig)) {
2029 #ifdef KTRACE
2030                 if (KTRPOINT(curthread, KTR_PSIG))
2031                         ktrpsig(sig, ps->ps_sigact[_SIG_IDX(sig)],
2032                             &td->td_sigmask, code);
2033 #endif
2034                 (*p->p_sysent->sv_sendsig)(ps->ps_sigact[_SIG_IDX(sig)],
2035                                 ksi, &td->td_sigmask);
2036                 postsig_done(sig, td, ps);
2037                 mtx_unlock(&ps->ps_mtx);
2038         } else {
2039                 /*
2040                  * Avoid a possible infinite loop if the thread
2041                  * masking the signal or process is ignoring the
2042                  * signal.
2043                  */
2044                 if (kern_forcesigexit && (SIGISMEMBER(sigmask, sig) ||
2045                     ps->ps_sigact[_SIG_IDX(sig)] == SIG_IGN)) {
2046                         SIGDELSET(td->td_sigmask, sig);
2047                         SIGDELSET(ps->ps_sigcatch, sig);
2048                         SIGDELSET(ps->ps_sigignore, sig);
2049                         ps->ps_sigact[_SIG_IDX(sig)] = SIG_DFL;
2050                         td->td_pflags &= ~TDP_SIGFASTBLOCK;
2051                         td->td_sigblock_val = 0;
2052                 }
2053                 mtx_unlock(&ps->ps_mtx);
2054                 p->p_sig = sig;         /* XXX to verify code */
2055                 tdsendsignal(p, td, sig, ksi);
2056         }
2057         PROC_UNLOCK(p);
2058 }
2059
2060 static struct thread *
2061 sigtd(struct proc *p, int sig, bool fast_sigblock)
2062 {
2063         struct thread *td, *signal_td;
2064
2065         PROC_LOCK_ASSERT(p, MA_OWNED);
2066         MPASS(!fast_sigblock || p == curproc);
2067
2068         /*
2069          * Check if current thread can handle the signal without
2070          * switching context to another thread.
2071          */
2072         if (curproc == p && !SIGISMEMBER(curthread->td_sigmask, sig) &&
2073             (!fast_sigblock || curthread->td_sigblock_val == 0))
2074                 return (curthread);
2075         signal_td = NULL;
2076         FOREACH_THREAD_IN_PROC(p, td) {
2077                 if (!SIGISMEMBER(td->td_sigmask, sig) && (!fast_sigblock ||
2078                     td != curthread || td->td_sigblock_val == 0)) {
2079                         signal_td = td;
2080                         break;
2081                 }
2082         }
2083         if (signal_td == NULL)
2084                 signal_td = FIRST_THREAD_IN_PROC(p);
2085         return (signal_td);
2086 }
2087
2088 /*
2089  * Send the signal to the process.  If the signal has an action, the action
2090  * is usually performed by the target process rather than the caller; we add
2091  * the signal to the set of pending signals for the process.
2092  *
2093  * Exceptions:
2094  *   o When a stop signal is sent to a sleeping process that takes the
2095  *     default action, the process is stopped without awakening it.
2096  *   o SIGCONT restarts stopped processes (or puts them back to sleep)
2097  *     regardless of the signal action (eg, blocked or ignored).
2098  *
2099  * Other ignored signals are discarded immediately.
2100  *
2101  * NB: This function may be entered from the debugger via the "kill" DDB
2102  * command.  There is little that can be done to mitigate the possibly messy
2103  * side effects of this unwise possibility.
2104  */
2105 void
2106 kern_psignal(struct proc *p, int sig)
2107 {
2108         ksiginfo_t ksi;
2109
2110         ksiginfo_init(&ksi);
2111         ksi.ksi_signo = sig;
2112         ksi.ksi_code = SI_KERNEL;
2113         (void) tdsendsignal(p, NULL, sig, &ksi);
2114 }
2115
2116 int
2117 pksignal(struct proc *p, int sig, ksiginfo_t *ksi)
2118 {
2119
2120         return (tdsendsignal(p, NULL, sig, ksi));
2121 }
2122
2123 /* Utility function for finding a thread to send signal event to. */
2124 int
2125 sigev_findtd(struct proc *p ,struct sigevent *sigev, struct thread **ttd)
2126 {
2127         struct thread *td;
2128
2129         if (sigev->sigev_notify == SIGEV_THREAD_ID) {
2130                 td = tdfind(sigev->sigev_notify_thread_id, p->p_pid);
2131                 if (td == NULL)
2132                         return (ESRCH);
2133                 *ttd = td;
2134         } else {
2135                 *ttd = NULL;
2136                 PROC_LOCK(p);
2137         }
2138         return (0);
2139 }
2140
2141 void
2142 tdsignal(struct thread *td, int sig)
2143 {
2144         ksiginfo_t ksi;
2145
2146         ksiginfo_init(&ksi);
2147         ksi.ksi_signo = sig;
2148         ksi.ksi_code = SI_KERNEL;
2149         (void) tdsendsignal(td->td_proc, td, sig, &ksi);
2150 }
2151
2152 void
2153 tdksignal(struct thread *td, int sig, ksiginfo_t *ksi)
2154 {
2155
2156         (void) tdsendsignal(td->td_proc, td, sig, ksi);
2157 }
2158
2159 static int
2160 sig_sleepq_abort(struct thread *td, int intrval)
2161 {
2162         THREAD_LOCK_ASSERT(td, MA_OWNED);
2163
2164         if (intrval == 0 && (td->td_flags & TDF_SIGWAIT) == 0) {
2165                 thread_unlock(td);
2166                 return (0);
2167         }
2168         return (sleepq_abort(td, intrval));
2169 }
2170
2171 int
2172 tdsendsignal(struct proc *p, struct thread *td, int sig, ksiginfo_t *ksi)
2173 {
2174         sig_t action;
2175         sigqueue_t *sigqueue;
2176         int prop;
2177         struct sigacts *ps;
2178         int intrval;
2179         int ret = 0;
2180         int wakeup_swapper;
2181
2182         MPASS(td == NULL || p == td->td_proc);
2183         PROC_LOCK_ASSERT(p, MA_OWNED);
2184
2185         if (!_SIG_VALID(sig))
2186                 panic("%s(): invalid signal %d", __func__, sig);
2187
2188         KASSERT(ksi == NULL || !KSI_ONQ(ksi), ("%s: ksi on queue", __func__));
2189
2190         /*
2191          * IEEE Std 1003.1-2001: return success when killing a zombie.
2192          */
2193         if (p->p_state == PRS_ZOMBIE) {
2194                 if (ksi && (ksi->ksi_flags & KSI_INS))
2195                         ksiginfo_tryfree(ksi);
2196                 return (ret);
2197         }
2198
2199         ps = p->p_sigacts;
2200         KNOTE_LOCKED(p->p_klist, NOTE_SIGNAL | sig);
2201         prop = sigprop(sig);
2202
2203         if (td == NULL) {
2204                 td = sigtd(p, sig, false);
2205                 sigqueue = &p->p_sigqueue;
2206         } else
2207                 sigqueue = &td->td_sigqueue;
2208
2209         SDT_PROBE3(proc, , , signal__send, td, p, sig);
2210
2211         /*
2212          * If the signal is being ignored, then we forget about it
2213          * immediately, except when the target process executes
2214          * sigwait().  (Note: we don't set SIGCONT in ps_sigignore,
2215          * and if it is set to SIG_IGN, action will be SIG_DFL here.)
2216          */
2217         mtx_lock(&ps->ps_mtx);
2218         if (SIGISMEMBER(ps->ps_sigignore, sig)) {
2219                 if (kern_sig_discard_ign &&
2220                     (p->p_sysent->sv_flags & SV_SIG_DISCIGN) == 0) {
2221                         SDT_PROBE3(proc, , , signal__discard, td, p, sig);
2222
2223                         mtx_unlock(&ps->ps_mtx);
2224                         if (ksi && (ksi->ksi_flags & KSI_INS))
2225                                 ksiginfo_tryfree(ksi);
2226                         return (ret);
2227                 } else {
2228                         action = SIG_CATCH;
2229                         intrval = 0;
2230                 }
2231         } else {
2232                 if (SIGISMEMBER(td->td_sigmask, sig))
2233                         action = SIG_HOLD;
2234                 else if (SIGISMEMBER(ps->ps_sigcatch, sig))
2235                         action = SIG_CATCH;
2236                 else
2237                         action = SIG_DFL;
2238                 if (SIGISMEMBER(ps->ps_sigintr, sig))
2239                         intrval = EINTR;
2240                 else
2241                         intrval = ERESTART;
2242         }
2243         mtx_unlock(&ps->ps_mtx);
2244
2245         if (prop & SIGPROP_CONT)
2246                 sigqueue_delete_stopmask_proc(p);
2247         else if (prop & SIGPROP_STOP) {
2248                 /*
2249                  * If sending a tty stop signal to a member of an orphaned
2250                  * process group, discard the signal here if the action
2251                  * is default; don't stop the process below if sleeping,
2252                  * and don't clear any pending SIGCONT.
2253                  */
2254                 if ((prop & SIGPROP_TTYSTOP) != 0 &&
2255                     (p->p_pgrp->pg_flags & PGRP_ORPHANED) != 0 &&
2256                     action == SIG_DFL) {
2257                         if (ksi && (ksi->ksi_flags & KSI_INS))
2258                                 ksiginfo_tryfree(ksi);
2259                         return (ret);
2260                 }
2261                 sigqueue_delete_proc(p, SIGCONT);
2262                 if (p->p_flag & P_CONTINUED) {
2263                         p->p_flag &= ~P_CONTINUED;
2264                         PROC_LOCK(p->p_pptr);
2265                         sigqueue_take(p->p_ksi);
2266                         PROC_UNLOCK(p->p_pptr);
2267                 }
2268         }
2269
2270         ret = sigqueue_add(sigqueue, sig, ksi);
2271         if (ret != 0)
2272                 return (ret);
2273         signotify(td);
2274         /*
2275          * Defer further processing for signals which are held,
2276          * except that stopped processes must be continued by SIGCONT.
2277          */
2278         if (action == SIG_HOLD &&
2279             !((prop & SIGPROP_CONT) && (p->p_flag & P_STOPPED_SIG)))
2280                 return (ret);
2281
2282         wakeup_swapper = 0;
2283
2284         /*
2285          * Some signals have a process-wide effect and a per-thread
2286          * component.  Most processing occurs when the process next
2287          * tries to cross the user boundary, however there are some
2288          * times when processing needs to be done immediately, such as
2289          * waking up threads so that they can cross the user boundary.
2290          * We try to do the per-process part here.
2291          */
2292         if (P_SHOULDSTOP(p)) {
2293                 KASSERT(!(p->p_flag & P_WEXIT),
2294                     ("signal to stopped but exiting process"));
2295                 if (sig == SIGKILL) {
2296                         /*
2297                          * If traced process is already stopped,
2298                          * then no further action is necessary.
2299                          */
2300                         if (p->p_flag & P_TRACED)
2301                                 goto out;
2302                         /*
2303                          * SIGKILL sets process running.
2304                          * It will die elsewhere.
2305                          * All threads must be restarted.
2306                          */
2307                         p->p_flag &= ~P_STOPPED_SIG;
2308                         goto runfast;
2309                 }
2310
2311                 if (prop & SIGPROP_CONT) {
2312                         /*
2313                          * If traced process is already stopped,
2314                          * then no further action is necessary.
2315                          */
2316                         if (p->p_flag & P_TRACED)
2317                                 goto out;
2318                         /*
2319                          * If SIGCONT is default (or ignored), we continue the
2320                          * process but don't leave the signal in sigqueue as
2321                          * it has no further action.  If SIGCONT is held, we
2322                          * continue the process and leave the signal in
2323                          * sigqueue.  If the process catches SIGCONT, let it
2324                          * handle the signal itself.  If it isn't waiting on
2325                          * an event, it goes back to run state.
2326                          * Otherwise, process goes back to sleep state.
2327                          */
2328                         p->p_flag &= ~P_STOPPED_SIG;
2329                         PROC_SLOCK(p);
2330                         if (p->p_numthreads == p->p_suspcount) {
2331                                 PROC_SUNLOCK(p);
2332                                 p->p_flag |= P_CONTINUED;
2333                                 p->p_xsig = SIGCONT;
2334                                 PROC_LOCK(p->p_pptr);
2335                                 childproc_continued(p);
2336                                 PROC_UNLOCK(p->p_pptr);
2337                                 PROC_SLOCK(p);
2338                         }
2339                         if (action == SIG_DFL) {
2340                                 thread_unsuspend(p);
2341                                 PROC_SUNLOCK(p);
2342                                 sigqueue_delete(sigqueue, sig);
2343                                 goto out_cont;
2344                         }
2345                         if (action == SIG_CATCH) {
2346                                 /*
2347                                  * The process wants to catch it so it needs
2348                                  * to run at least one thread, but which one?
2349                                  */
2350                                 PROC_SUNLOCK(p);
2351                                 goto runfast;
2352                         }
2353                         /*
2354                          * The signal is not ignored or caught.
2355                          */
2356                         thread_unsuspend(p);
2357                         PROC_SUNLOCK(p);
2358                         goto out_cont;
2359                 }
2360
2361                 if (prop & SIGPROP_STOP) {
2362                         /*
2363                          * If traced process is already stopped,
2364                          * then no further action is necessary.
2365                          */
2366                         if (p->p_flag & P_TRACED)
2367                                 goto out;
2368                         /*
2369                          * Already stopped, don't need to stop again
2370                          * (If we did the shell could get confused).
2371                          * Just make sure the signal STOP bit set.
2372                          */
2373                         p->p_flag |= P_STOPPED_SIG;
2374                         sigqueue_delete(sigqueue, sig);
2375                         goto out;
2376                 }
2377
2378                 /*
2379                  * All other kinds of signals:
2380                  * If a thread is sleeping interruptibly, simulate a
2381                  * wakeup so that when it is continued it will be made
2382                  * runnable and can look at the signal.  However, don't make
2383                  * the PROCESS runnable, leave it stopped.
2384                  * It may run a bit until it hits a thread_suspend_check().
2385                  */
2386                 PROC_SLOCK(p);
2387                 thread_lock(td);
2388                 if (TD_CAN_ABORT(td))
2389                         wakeup_swapper = sig_sleepq_abort(td, intrval);
2390                 else
2391                         thread_unlock(td);
2392                 PROC_SUNLOCK(p);
2393                 goto out;
2394                 /*
2395                  * Mutexes are short lived. Threads waiting on them will
2396                  * hit thread_suspend_check() soon.
2397                  */
2398         } else if (p->p_state == PRS_NORMAL) {
2399                 if (p->p_flag & P_TRACED || action == SIG_CATCH) {
2400                         tdsigwakeup(td, sig, action, intrval);
2401                         goto out;
2402                 }
2403
2404                 MPASS(action == SIG_DFL);
2405
2406                 if (prop & SIGPROP_STOP) {
2407                         if (p->p_flag & (P_PPWAIT|P_WEXIT))
2408                                 goto out;
2409                         p->p_flag |= P_STOPPED_SIG;
2410                         p->p_xsig = sig;
2411                         PROC_SLOCK(p);
2412                         wakeup_swapper = sig_suspend_threads(td, p, 1);
2413                         if (p->p_numthreads == p->p_suspcount) {
2414                                 /*
2415                                  * only thread sending signal to another
2416                                  * process can reach here, if thread is sending
2417                                  * signal to its process, because thread does
2418                                  * not suspend itself here, p_numthreads
2419                                  * should never be equal to p_suspcount.
2420                                  */
2421                                 thread_stopped(p);
2422                                 PROC_SUNLOCK(p);
2423                                 sigqueue_delete_proc(p, p->p_xsig);
2424                         } else
2425                                 PROC_SUNLOCK(p);
2426                         goto out;
2427                 }
2428         } else {
2429                 /* Not in "NORMAL" state. discard the signal. */
2430                 sigqueue_delete(sigqueue, sig);
2431                 goto out;
2432         }
2433
2434         /*
2435          * The process is not stopped so we need to apply the signal to all the
2436          * running threads.
2437          */
2438 runfast:
2439         tdsigwakeup(td, sig, action, intrval);
2440         PROC_SLOCK(p);
2441         thread_unsuspend(p);
2442         PROC_SUNLOCK(p);
2443 out_cont:
2444         itimer_proc_continue(p);
2445         kqtimer_proc_continue(p);
2446 out:
2447         /* If we jump here, proc slock should not be owned. */
2448         PROC_SLOCK_ASSERT(p, MA_NOTOWNED);
2449         if (wakeup_swapper)
2450                 kick_proc0();
2451
2452         return (ret);
2453 }
2454
2455 /*
2456  * The force of a signal has been directed against a single
2457  * thread.  We need to see what we can do about knocking it
2458  * out of any sleep it may be in etc.
2459  */
2460 static void
2461 tdsigwakeup(struct thread *td, int sig, sig_t action, int intrval)
2462 {
2463         struct proc *p = td->td_proc;
2464         int prop, wakeup_swapper;
2465
2466         PROC_LOCK_ASSERT(p, MA_OWNED);
2467         prop = sigprop(sig);
2468
2469         PROC_SLOCK(p);
2470         thread_lock(td);
2471         /*
2472          * Bring the priority of a thread up if we want it to get
2473          * killed in this lifetime.  Be careful to avoid bumping the
2474          * priority of the idle thread, since we still allow to signal
2475          * kernel processes.
2476          */
2477         if (action == SIG_DFL && (prop & SIGPROP_KILL) != 0 &&
2478             td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2479                 sched_prio(td, PUSER);
2480         if (TD_ON_SLEEPQ(td)) {
2481                 /*
2482                  * If thread is sleeping uninterruptibly
2483                  * we can't interrupt the sleep... the signal will
2484                  * be noticed when the process returns through
2485                  * trap() or syscall().
2486                  */
2487                 if ((td->td_flags & TDF_SINTR) == 0)
2488                         goto out;
2489                 /*
2490                  * If SIGCONT is default (or ignored) and process is
2491                  * asleep, we are finished; the process should not
2492                  * be awakened.
2493                  */
2494                 if ((prop & SIGPROP_CONT) && action == SIG_DFL) {
2495                         thread_unlock(td);
2496                         PROC_SUNLOCK(p);
2497                         sigqueue_delete(&p->p_sigqueue, sig);
2498                         /*
2499                          * It may be on either list in this state.
2500                          * Remove from both for now.
2501                          */
2502                         sigqueue_delete(&td->td_sigqueue, sig);
2503                         return;
2504                 }
2505
2506                 /*
2507                  * Don't awaken a sleeping thread for SIGSTOP if the
2508                  * STOP signal is deferred.
2509                  */
2510                 if ((prop & SIGPROP_STOP) != 0 && (td->td_flags & (TDF_SBDRY |
2511                     TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2512                         goto out;
2513
2514                 /*
2515                  * Give low priority threads a better chance to run.
2516                  */
2517                 if (td->td_priority > PUSER && !TD_IS_IDLETHREAD(td))
2518                         sched_prio(td, PUSER);
2519
2520                 wakeup_swapper = sig_sleepq_abort(td, intrval);
2521                 PROC_SUNLOCK(p);
2522                 if (wakeup_swapper)
2523                         kick_proc0();
2524                 return;
2525         }
2526
2527         /*
2528          * Other states do nothing with the signal immediately,
2529          * other than kicking ourselves if we are running.
2530          * It will either never be noticed, or noticed very soon.
2531          */
2532 #ifdef SMP
2533         if (TD_IS_RUNNING(td) && td != curthread)
2534                 forward_signal(td);
2535 #endif
2536
2537 out:
2538         PROC_SUNLOCK(p);
2539         thread_unlock(td);
2540 }
2541
2542 static void
2543 ptrace_coredump(struct thread *td)
2544 {
2545         struct proc *p;
2546         struct thr_coredump_req *tcq;
2547         void *rl_cookie;
2548
2549         MPASS(td == curthread);
2550         p = td->td_proc;
2551         PROC_LOCK_ASSERT(p, MA_OWNED);
2552         if ((td->td_dbgflags & TDB_COREDUMPRQ) == 0)
2553                 return;
2554         KASSERT((p->p_flag & P_STOPPED_TRACE) != 0, ("not stopped"));
2555
2556         tcq = td->td_coredump;
2557         KASSERT(tcq != NULL, ("td_coredump is NULL"));
2558
2559         if (p->p_sysent->sv_coredump == NULL) {
2560                 tcq->tc_error = ENOSYS;
2561                 goto wake;
2562         }
2563
2564         PROC_UNLOCK(p);
2565         rl_cookie = vn_rangelock_wlock(tcq->tc_vp, 0, OFF_MAX);
2566
2567         tcq->tc_error = p->p_sysent->sv_coredump(td, tcq->tc_vp,
2568             tcq->tc_limit, tcq->tc_flags);
2569
2570         vn_rangelock_unlock(tcq->tc_vp, rl_cookie);
2571         PROC_LOCK(p);
2572 wake:
2573         td->td_dbgflags &= ~TDB_COREDUMPRQ;
2574         td->td_coredump = NULL;
2575         wakeup(p);
2576 }
2577
2578 static int
2579 sig_suspend_threads(struct thread *td, struct proc *p, int sending)
2580 {
2581         struct thread *td2;
2582         int wakeup_swapper;
2583
2584         PROC_LOCK_ASSERT(p, MA_OWNED);
2585         PROC_SLOCK_ASSERT(p, MA_OWNED);
2586         MPASS(sending || td == curthread);
2587
2588         wakeup_swapper = 0;
2589         FOREACH_THREAD_IN_PROC(p, td2) {
2590                 thread_lock(td2);
2591                 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
2592                 if ((TD_IS_SLEEPING(td2) || TD_IS_SWAPPED(td2)) &&
2593                     (td2->td_flags & TDF_SINTR)) {
2594                         if (td2->td_flags & TDF_SBDRY) {
2595                                 /*
2596                                  * Once a thread is asleep with
2597                                  * TDF_SBDRY and without TDF_SERESTART
2598                                  * or TDF_SEINTR set, it should never
2599                                  * become suspended due to this check.
2600                                  */
2601                                 KASSERT(!TD_IS_SUSPENDED(td2),
2602                                     ("thread with deferred stops suspended"));
2603                                 if (TD_SBDRY_INTR(td2)) {
2604                                         wakeup_swapper |= sleepq_abort(td2,
2605                                             TD_SBDRY_ERRNO(td2));
2606                                         continue;
2607                                 }
2608                         } else if (!TD_IS_SUSPENDED(td2))
2609                                 thread_suspend_one(td2);
2610                 } else if (!TD_IS_SUSPENDED(td2)) {
2611                         if (sending || td != td2)
2612                                 td2->td_flags |= TDF_ASTPENDING;
2613 #ifdef SMP
2614                         if (TD_IS_RUNNING(td2) && td2 != td)
2615                                 forward_signal(td2);
2616 #endif
2617                 }
2618                 thread_unlock(td2);
2619         }
2620         return (wakeup_swapper);
2621 }
2622
2623 /*
2624  * Stop the process for an event deemed interesting to the debugger. If si is
2625  * non-NULL, this is a signal exchange; the new signal requested by the
2626  * debugger will be returned for handling. If si is NULL, this is some other
2627  * type of interesting event. The debugger may request a signal be delivered in
2628  * that case as well, however it will be deferred until it can be handled.
2629  */
2630 int
2631 ptracestop(struct thread *td, int sig, ksiginfo_t *si)
2632 {
2633         struct proc *p = td->td_proc;
2634         struct thread *td2;
2635         ksiginfo_t ksi;
2636
2637         PROC_LOCK_ASSERT(p, MA_OWNED);
2638         KASSERT(!(p->p_flag & P_WEXIT), ("Stopping exiting process"));
2639         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
2640             &p->p_mtx.lock_object, "Stopping for traced signal");
2641
2642         td->td_xsig = sig;
2643
2644         if (si == NULL || (si->ksi_flags & KSI_PTRACE) == 0) {
2645                 td->td_dbgflags |= TDB_XSIG;
2646                 CTR4(KTR_PTRACE, "ptracestop: tid %d (pid %d) flags %#x sig %d",
2647                     td->td_tid, p->p_pid, td->td_dbgflags, sig);
2648                 PROC_SLOCK(p);
2649                 while ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_XSIG)) {
2650                         if (P_KILLED(p)) {
2651                                 /*
2652                                  * Ensure that, if we've been PT_KILLed, the
2653                                  * exit status reflects that. Another thread
2654                                  * may also be in ptracestop(), having just
2655                                  * received the SIGKILL, but this thread was
2656                                  * unsuspended first.
2657                                  */
2658                                 td->td_dbgflags &= ~TDB_XSIG;
2659                                 td->td_xsig = SIGKILL;
2660                                 p->p_ptevents = 0;
2661                                 break;
2662                         }
2663                         if (p->p_flag & P_SINGLE_EXIT &&
2664                             !(td->td_dbgflags & TDB_EXIT)) {
2665                                 /*
2666                                  * Ignore ptrace stops except for thread exit
2667                                  * events when the process exits.
2668                                  */
2669                                 td->td_dbgflags &= ~TDB_XSIG;
2670                                 PROC_SUNLOCK(p);
2671                                 return (0);
2672                         }
2673
2674                         /*
2675                          * Make wait(2) work.  Ensure that right after the
2676                          * attach, the thread which was decided to become the
2677                          * leader of attach gets reported to the waiter.
2678                          * Otherwise, just avoid overwriting another thread's
2679                          * assignment to p_xthread.  If another thread has
2680                          * already set p_xthread, the current thread will get
2681                          * a chance to report itself upon the next iteration.
2682                          */
2683                         if ((td->td_dbgflags & TDB_FSTP) != 0 ||
2684                             ((p->p_flag2 & P2_PTRACE_FSTP) == 0 &&
2685                             p->p_xthread == NULL)) {
2686                                 p->p_xsig = sig;
2687                                 p->p_xthread = td;
2688
2689                                 /*
2690                                  * If we are on sleepqueue already,
2691                                  * let sleepqueue code decide if it
2692                                  * needs to go sleep after attach.
2693                                  */
2694                                 if (td->td_wchan == NULL)
2695                                         td->td_dbgflags &= ~TDB_FSTP;
2696
2697                                 p->p_flag2 &= ~P2_PTRACE_FSTP;
2698                                 p->p_flag |= P_STOPPED_SIG | P_STOPPED_TRACE;
2699                                 sig_suspend_threads(td, p, 0);
2700                         }
2701                         if ((td->td_dbgflags & TDB_STOPATFORK) != 0) {
2702                                 td->td_dbgflags &= ~TDB_STOPATFORK;
2703                         }
2704 stopme:
2705                         td->td_dbgflags |= TDB_SSWITCH;
2706                         thread_suspend_switch(td, p);
2707                         td->td_dbgflags &= ~TDB_SSWITCH;
2708                         if ((td->td_dbgflags & TDB_COREDUMPRQ) != 0) {
2709                                 PROC_SUNLOCK(p);
2710                                 ptrace_coredump(td);
2711                                 PROC_SLOCK(p);
2712                                 goto stopme;
2713                         }
2714                         if (p->p_xthread == td)
2715                                 p->p_xthread = NULL;
2716                         if (!(p->p_flag & P_TRACED))
2717                                 break;
2718                         if (td->td_dbgflags & TDB_SUSPEND) {
2719                                 if (p->p_flag & P_SINGLE_EXIT)
2720                                         break;
2721                                 goto stopme;
2722                         }
2723                 }
2724                 PROC_SUNLOCK(p);
2725         }
2726
2727         if (si != NULL && sig == td->td_xsig) {
2728                 /* Parent wants us to take the original signal unchanged. */
2729                 si->ksi_flags |= KSI_HEAD;
2730                 if (sigqueue_add(&td->td_sigqueue, sig, si) != 0)
2731                         si->ksi_signo = 0;
2732         } else if (td->td_xsig != 0) {
2733                 /*
2734                  * If parent wants us to take a new signal, then it will leave
2735                  * it in td->td_xsig; otherwise we just look for signals again.
2736                  */
2737                 ksiginfo_init(&ksi);
2738                 ksi.ksi_signo = td->td_xsig;
2739                 ksi.ksi_flags |= KSI_PTRACE;
2740                 td2 = sigtd(p, td->td_xsig, false);
2741                 tdsendsignal(p, td2, td->td_xsig, &ksi);
2742                 if (td != td2)
2743                         return (0);
2744         }
2745
2746         return (td->td_xsig);
2747 }
2748
2749 static void
2750 reschedule_signals(struct proc *p, sigset_t block, int flags)
2751 {
2752         struct sigacts *ps;
2753         struct thread *td;
2754         int sig;
2755         bool fastblk, pslocked;
2756
2757         PROC_LOCK_ASSERT(p, MA_OWNED);
2758         ps = p->p_sigacts;
2759         pslocked = (flags & SIGPROCMASK_PS_LOCKED) != 0;
2760         mtx_assert(&ps->ps_mtx, pslocked ? MA_OWNED : MA_NOTOWNED);
2761         if (SIGISEMPTY(p->p_siglist))
2762                 return;
2763         SIGSETAND(block, p->p_siglist);
2764         fastblk = (flags & SIGPROCMASK_FASTBLK) != 0;
2765         while ((sig = sig_ffs(&block)) != 0) {
2766                 SIGDELSET(block, sig);
2767                 td = sigtd(p, sig, fastblk);
2768
2769                 /*
2770                  * If sigtd() selected us despite sigfastblock is
2771                  * blocking, do not activate AST or wake us, to avoid
2772                  * loop in AST handler.
2773                  */
2774                 if (fastblk && td == curthread)
2775                         continue;
2776
2777                 signotify(td);
2778                 if (!pslocked)
2779                         mtx_lock(&ps->ps_mtx);
2780                 if (p->p_flag & P_TRACED ||
2781                     (SIGISMEMBER(ps->ps_sigcatch, sig) &&
2782                     !SIGISMEMBER(td->td_sigmask, sig))) {
2783                         tdsigwakeup(td, sig, SIG_CATCH,
2784                             (SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR :
2785                             ERESTART));
2786                 }
2787                 if (!pslocked)
2788                         mtx_unlock(&ps->ps_mtx);
2789         }
2790 }
2791
2792 void
2793 tdsigcleanup(struct thread *td)
2794 {
2795         struct proc *p;
2796         sigset_t unblocked;
2797
2798         p = td->td_proc;
2799         PROC_LOCK_ASSERT(p, MA_OWNED);
2800
2801         sigqueue_flush(&td->td_sigqueue);
2802         if (p->p_numthreads == 1)
2803                 return;
2804
2805         /*
2806          * Since we cannot handle signals, notify signal post code
2807          * about this by filling the sigmask.
2808          *
2809          * Also, if needed, wake up thread(s) that do not block the
2810          * same signals as the exiting thread, since the thread might
2811          * have been selected for delivery and woken up.
2812          */
2813         SIGFILLSET(unblocked);
2814         SIGSETNAND(unblocked, td->td_sigmask);
2815         SIGFILLSET(td->td_sigmask);
2816         reschedule_signals(p, unblocked, 0);
2817
2818 }
2819
2820 static int
2821 sigdeferstop_curr_flags(int cflags)
2822 {
2823
2824         MPASS((cflags & (TDF_SEINTR | TDF_SERESTART)) == 0 ||
2825             (cflags & TDF_SBDRY) != 0);
2826         return (cflags & (TDF_SBDRY | TDF_SEINTR | TDF_SERESTART));
2827 }
2828
2829 /*
2830  * Defer the delivery of SIGSTOP for the current thread, according to
2831  * the requested mode.  Returns previous flags, which must be restored
2832  * by sigallowstop().
2833  *
2834  * TDF_SBDRY, TDF_SEINTR, and TDF_SERESTART flags are only set and
2835  * cleared by the current thread, which allow the lock-less read-only
2836  * accesses below.
2837  */
2838 int
2839 sigdeferstop_impl(int mode)
2840 {
2841         struct thread *td;
2842         int cflags, nflags;
2843
2844         td = curthread;
2845         cflags = sigdeferstop_curr_flags(td->td_flags);
2846         switch (mode) {
2847         case SIGDEFERSTOP_NOP:
2848                 nflags = cflags;
2849                 break;
2850         case SIGDEFERSTOP_OFF:
2851                 nflags = 0;
2852                 break;
2853         case SIGDEFERSTOP_SILENT:
2854                 nflags = (cflags | TDF_SBDRY) & ~(TDF_SEINTR | TDF_SERESTART);
2855                 break;
2856         case SIGDEFERSTOP_EINTR:
2857                 nflags = (cflags | TDF_SBDRY | TDF_SEINTR) & ~TDF_SERESTART;
2858                 break;
2859         case SIGDEFERSTOP_ERESTART:
2860                 nflags = (cflags | TDF_SBDRY | TDF_SERESTART) & ~TDF_SEINTR;
2861                 break;
2862         default:
2863                 panic("sigdeferstop: invalid mode %x", mode);
2864                 break;
2865         }
2866         if (cflags == nflags)
2867                 return (SIGDEFERSTOP_VAL_NCHG);
2868         thread_lock(td);
2869         td->td_flags = (td->td_flags & ~cflags) | nflags;
2870         thread_unlock(td);
2871         return (cflags);
2872 }
2873
2874 /*
2875  * Restores the STOP handling mode, typically permitting the delivery
2876  * of SIGSTOP for the current thread.  This does not immediately
2877  * suspend if a stop was posted.  Instead, the thread will suspend
2878  * either via ast() or a subsequent interruptible sleep.
2879  */
2880 void
2881 sigallowstop_impl(int prev)
2882 {
2883         struct thread *td;
2884         int cflags;
2885
2886         KASSERT(prev != SIGDEFERSTOP_VAL_NCHG, ("failed sigallowstop"));
2887         KASSERT((prev & ~(TDF_SBDRY | TDF_SEINTR | TDF_SERESTART)) == 0,
2888             ("sigallowstop: incorrect previous mode %x", prev));
2889         td = curthread;
2890         cflags = sigdeferstop_curr_flags(td->td_flags);
2891         if (cflags != prev) {
2892                 thread_lock(td);
2893                 td->td_flags = (td->td_flags & ~cflags) | prev;
2894                 thread_unlock(td);
2895         }
2896 }
2897
2898 /*
2899  * If the current process has received a signal (should be caught or cause
2900  * termination, should interrupt current syscall), return the signal number.
2901  * Stop signals with default action are processed immediately, then cleared;
2902  * they aren't returned.  This is checked after each entry to the system for
2903  * a syscall or trap (though this can usually be done without calling issignal
2904  * by checking the pending signal masks in cursig.) The normal call
2905  * sequence is
2906  *
2907  *      while (sig = cursig(curthread))
2908  *              postsig(sig);
2909  */
2910 static int
2911 issignal(struct thread *td)
2912 {
2913         struct proc *p;
2914         struct sigacts *ps;
2915         struct sigqueue *queue;
2916         sigset_t sigpending;
2917         ksiginfo_t ksi;
2918         int prop, sig;
2919
2920         p = td->td_proc;
2921         ps = p->p_sigacts;
2922         mtx_assert(&ps->ps_mtx, MA_OWNED);
2923         PROC_LOCK_ASSERT(p, MA_OWNED);
2924         for (;;) {
2925                 sigpending = td->td_sigqueue.sq_signals;
2926                 SIGSETOR(sigpending, p->p_sigqueue.sq_signals);
2927                 SIGSETNAND(sigpending, td->td_sigmask);
2928
2929                 if ((p->p_flag & P_PPWAIT) != 0 || (td->td_flags &
2930                     (TDF_SBDRY | TDF_SERESTART | TDF_SEINTR)) == TDF_SBDRY)
2931                         SIG_STOPSIGMASK(sigpending);
2932                 if (SIGISEMPTY(sigpending))     /* no signal to send */
2933                         return (0);
2934
2935                 /*
2936                  * Do fast sigblock if requested by usermode.  Since
2937                  * we do know that there was a signal pending at this
2938                  * point, set the FAST_SIGBLOCK_PEND as indicator for
2939                  * usermode to perform a dummy call to
2940                  * FAST_SIGBLOCK_UNBLOCK, which causes immediate
2941                  * delivery of postponed pending signal.
2942                  */
2943                 if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
2944                         if (td->td_sigblock_val != 0)
2945                                 SIGSETNAND(sigpending, fastblock_mask);
2946                         if (SIGISEMPTY(sigpending)) {
2947                                 td->td_pflags |= TDP_SIGFASTPENDING;
2948                                 return (0);
2949                         }
2950                 }
2951
2952                 if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED &&
2953                     (p->p_flag2 & P2_PTRACE_FSTP) != 0 &&
2954                     SIGISMEMBER(sigpending, SIGSTOP)) {
2955                         /*
2956                          * If debugger just attached, always consume
2957                          * SIGSTOP from ptrace(PT_ATTACH) first, to
2958                          * execute the debugger attach ritual in
2959                          * order.
2960                          */
2961                         sig = SIGSTOP;
2962                         td->td_dbgflags |= TDB_FSTP;
2963                 } else {
2964                         sig = sig_ffs(&sigpending);
2965                 }
2966
2967                 /*
2968                  * We should allow pending but ignored signals below
2969                  * only if there is sigwait() active, or P_TRACED was
2970                  * on when they were posted.
2971                  */
2972                 if (SIGISMEMBER(ps->ps_sigignore, sig) &&
2973                     (p->p_flag & P_TRACED) == 0 &&
2974                     (td->td_flags & TDF_SIGWAIT) == 0) {
2975                         sigqueue_delete(&td->td_sigqueue, sig);
2976                         sigqueue_delete(&p->p_sigqueue, sig);
2977                         continue;
2978                 }
2979                 if ((p->p_flag & (P_TRACED | P_PPTRACE)) == P_TRACED) {
2980                         /*
2981                          * If traced, always stop.
2982                          * Remove old signal from queue before the stop.
2983                          * XXX shrug off debugger, it causes siginfo to
2984                          * be thrown away.
2985                          */
2986                         queue = &td->td_sigqueue;
2987                         ksiginfo_init(&ksi);
2988                         if (sigqueue_get(queue, sig, &ksi) == 0) {
2989                                 queue = &p->p_sigqueue;
2990                                 sigqueue_get(queue, sig, &ksi);
2991                         }
2992                         td->td_si = ksi.ksi_info;
2993
2994                         mtx_unlock(&ps->ps_mtx);
2995                         sig = ptracestop(td, sig, &ksi);
2996                         mtx_lock(&ps->ps_mtx);
2997
2998                         td->td_si.si_signo = 0;
2999
3000                         /* 
3001                          * Keep looking if the debugger discarded or
3002                          * replaced the signal.
3003                          */
3004                         if (sig == 0)
3005                                 continue;
3006
3007                         /*
3008                          * If the signal became masked, re-queue it.
3009                          */
3010                         if (SIGISMEMBER(td->td_sigmask, sig)) {
3011                                 ksi.ksi_flags |= KSI_HEAD;
3012                                 sigqueue_add(&p->p_sigqueue, sig, &ksi);
3013                                 continue;
3014                         }
3015
3016                         /*
3017                          * If the traced bit got turned off, requeue
3018                          * the signal and go back up to the top to
3019                          * rescan signals.  This ensures that p_sig*
3020                          * and p_sigact are consistent.
3021                          */
3022                         if ((p->p_flag & P_TRACED) == 0) {
3023                                 ksi.ksi_flags |= KSI_HEAD;
3024                                 sigqueue_add(queue, sig, &ksi);
3025                                 continue;
3026                         }
3027                 }
3028
3029                 prop = sigprop(sig);
3030
3031                 /*
3032                  * Decide whether the signal should be returned.
3033                  * Return the signal's number, or fall through
3034                  * to clear it from the pending mask.
3035                  */
3036                 switch ((intptr_t)p->p_sigacts->ps_sigact[_SIG_IDX(sig)]) {
3037                 case (intptr_t)SIG_DFL:
3038                         /*
3039                          * Don't take default actions on system processes.
3040                          */
3041                         if (p->p_pid <= 1) {
3042 #ifdef DIAGNOSTIC
3043                                 /*
3044                                  * Are you sure you want to ignore SIGSEGV
3045                                  * in init? XXX
3046                                  */
3047                                 printf("Process (pid %lu) got signal %d\n",
3048                                         (u_long)p->p_pid, sig);
3049 #endif
3050                                 break;          /* == ignore */
3051                         }
3052                         /*
3053                          * If there is a pending stop signal to process with
3054                          * default action, stop here, then clear the signal.
3055                          * Traced or exiting processes should ignore stops.
3056                          * Additionally, a member of an orphaned process group
3057                          * should ignore tty stops.
3058                          */
3059                         if (prop & SIGPROP_STOP) {
3060                                 mtx_unlock(&ps->ps_mtx);
3061                                 if ((p->p_flag & (P_TRACED | P_WEXIT |
3062                                     P_SINGLE_EXIT)) != 0 || ((p->p_pgrp->
3063                                     pg_flags & PGRP_ORPHANED) != 0 &&
3064                                     (prop & SIGPROP_TTYSTOP) != 0)) {
3065                                         mtx_lock(&ps->ps_mtx);
3066                                         break;  /* == ignore */
3067                                 }
3068                                 if (TD_SBDRY_INTR(td)) {
3069                                         KASSERT((td->td_flags & TDF_SBDRY) != 0,
3070                                             ("lost TDF_SBDRY"));
3071                                         mtx_lock(&ps->ps_mtx);
3072                                         return (-1);
3073                                 }
3074                                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
3075                                     &p->p_mtx.lock_object, "Catching SIGSTOP");
3076                                 sigqueue_delete(&td->td_sigqueue, sig);
3077                                 sigqueue_delete(&p->p_sigqueue, sig);
3078                                 p->p_flag |= P_STOPPED_SIG;
3079                                 p->p_xsig = sig;
3080                                 PROC_SLOCK(p);
3081                                 sig_suspend_threads(td, p, 0);
3082                                 thread_suspend_switch(td, p);
3083                                 PROC_SUNLOCK(p);
3084                                 mtx_lock(&ps->ps_mtx);
3085                                 goto next;
3086                         } else if ((prop & SIGPROP_IGNORE) != 0 &&
3087                             (td->td_flags & TDF_SIGWAIT) == 0) {
3088                                 /*
3089                                  * Default action is to ignore; drop it if
3090                                  * not in kern_sigtimedwait().
3091                                  */
3092                                 break;          /* == ignore */
3093                         } else
3094                                 return (sig);
3095                         /*NOTREACHED*/
3096
3097                 case (intptr_t)SIG_IGN:
3098                         if ((td->td_flags & TDF_SIGWAIT) == 0)
3099                                 break;          /* == ignore */
3100                         else
3101                                 return (sig);
3102
3103                 default:
3104                         /*
3105                          * This signal has an action, let
3106                          * postsig() process it.
3107                          */
3108                         return (sig);
3109                 }
3110                 sigqueue_delete(&td->td_sigqueue, sig); /* take the signal! */
3111                 sigqueue_delete(&p->p_sigqueue, sig);
3112 next:;
3113         }
3114         /* NOTREACHED */
3115 }
3116
3117 void
3118 thread_stopped(struct proc *p)
3119 {
3120         int n;
3121
3122         PROC_LOCK_ASSERT(p, MA_OWNED);
3123         PROC_SLOCK_ASSERT(p, MA_OWNED);
3124         n = p->p_suspcount;
3125         if (p == curproc)
3126                 n++;
3127         if ((p->p_flag & P_STOPPED_SIG) && (n == p->p_numthreads)) {
3128                 PROC_SUNLOCK(p);
3129                 p->p_flag &= ~P_WAITED;
3130                 PROC_LOCK(p->p_pptr);
3131                 childproc_stopped(p, (p->p_flag & P_TRACED) ?
3132                         CLD_TRAPPED : CLD_STOPPED);
3133                 PROC_UNLOCK(p->p_pptr);
3134                 PROC_SLOCK(p);
3135         }
3136 }
3137
3138 /*
3139  * Take the action for the specified signal
3140  * from the current set of pending signals.
3141  */
3142 int
3143 postsig(int sig)
3144 {
3145         struct thread *td;
3146         struct proc *p;
3147         struct sigacts *ps;
3148         sig_t action;
3149         ksiginfo_t ksi;
3150         sigset_t returnmask;
3151
3152         KASSERT(sig != 0, ("postsig"));
3153
3154         td = curthread;
3155         p = td->td_proc;
3156         PROC_LOCK_ASSERT(p, MA_OWNED);
3157         ps = p->p_sigacts;
3158         mtx_assert(&ps->ps_mtx, MA_OWNED);
3159         ksiginfo_init(&ksi);
3160         if (sigqueue_get(&td->td_sigqueue, sig, &ksi) == 0 &&
3161             sigqueue_get(&p->p_sigqueue, sig, &ksi) == 0)
3162                 return (0);
3163         ksi.ksi_signo = sig;
3164         if (ksi.ksi_code == SI_TIMER)
3165                 itimer_accept(p, ksi.ksi_timerid, &ksi);
3166         action = ps->ps_sigact[_SIG_IDX(sig)];
3167 #ifdef KTRACE
3168         if (KTRPOINT(td, KTR_PSIG))
3169                 ktrpsig(sig, action, td->td_pflags & TDP_OLDMASK ?
3170                     &td->td_oldsigmask : &td->td_sigmask, ksi.ksi_code);
3171 #endif
3172
3173         if (action == SIG_DFL) {
3174                 /*
3175                  * Default action, where the default is to kill
3176                  * the process.  (Other cases were ignored above.)
3177                  */
3178                 mtx_unlock(&ps->ps_mtx);
3179                 proc_td_siginfo_capture(td, &ksi.ksi_info);
3180                 sigexit(td, sig);
3181                 /* NOTREACHED */
3182         } else {
3183                 /*
3184                  * If we get here, the signal must be caught.
3185                  */
3186                 KASSERT(action != SIG_IGN, ("postsig action %p", action));
3187                 KASSERT(!SIGISMEMBER(td->td_sigmask, sig),
3188                     ("postsig action: blocked sig %d", sig));
3189
3190                 /*
3191                  * Set the new mask value and also defer further
3192                  * occurrences of this signal.
3193                  *
3194                  * Special case: user has done a sigsuspend.  Here the
3195                  * current mask is not of interest, but rather the
3196                  * mask from before the sigsuspend is what we want
3197                  * restored after the signal processing is completed.
3198                  */
3199                 if (td->td_pflags & TDP_OLDMASK) {
3200                         returnmask = td->td_oldsigmask;
3201                         td->td_pflags &= ~TDP_OLDMASK;
3202                 } else
3203                         returnmask = td->td_sigmask;
3204
3205                 if (p->p_sig == sig) {
3206                         p->p_sig = 0;
3207                 }
3208                 (*p->p_sysent->sv_sendsig)(action, &ksi, &returnmask);
3209                 postsig_done(sig, td, ps);
3210         }
3211         return (1);
3212 }
3213
3214 int
3215 sig_ast_checksusp(struct thread *td)
3216 {
3217         struct proc *p;
3218         int ret;
3219
3220         p = td->td_proc;
3221         PROC_LOCK_ASSERT(p, MA_OWNED);
3222
3223         if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
3224                 return (0);
3225
3226         ret = thread_suspend_check(1);
3227         MPASS(ret == 0 || ret == EINTR || ret == ERESTART);
3228         return (ret);
3229 }
3230
3231 int
3232 sig_ast_needsigchk(struct thread *td)
3233 {
3234         struct proc *p;
3235         struct sigacts *ps;
3236         int ret, sig;
3237
3238         p = td->td_proc;
3239         PROC_LOCK_ASSERT(p, MA_OWNED);
3240
3241         if ((td->td_flags & TDF_NEEDSIGCHK) == 0)
3242                 return (0);
3243
3244         ps = p->p_sigacts;
3245         mtx_lock(&ps->ps_mtx);
3246         sig = cursig(td);
3247         if (sig == -1) {
3248                 mtx_unlock(&ps->ps_mtx);
3249                 KASSERT((td->td_flags & TDF_SBDRY) != 0, ("lost TDF_SBDRY"));
3250                 KASSERT(TD_SBDRY_INTR(td),
3251                     ("lost TDF_SERESTART of TDF_SEINTR"));
3252                 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
3253                     (TDF_SEINTR | TDF_SERESTART),
3254                     ("both TDF_SEINTR and TDF_SERESTART"));
3255                 ret = TD_SBDRY_ERRNO(td);
3256         } else if (sig != 0) {
3257                 ret = SIGISMEMBER(ps->ps_sigintr, sig) ? EINTR : ERESTART;
3258                 mtx_unlock(&ps->ps_mtx);
3259         } else {
3260                 mtx_unlock(&ps->ps_mtx);
3261                 ret = 0;
3262         }
3263
3264         /*
3265          * Do not go into sleep if this thread was the ptrace(2)
3266          * attach leader.  cursig() consumed SIGSTOP from PT_ATTACH,
3267          * but we usually act on the signal by interrupting sleep, and
3268          * should do that here as well.
3269          */
3270         if ((td->td_dbgflags & TDB_FSTP) != 0) {
3271                 if (ret == 0)
3272                         ret = EINTR;
3273                 td->td_dbgflags &= ~TDB_FSTP;
3274         }
3275
3276         return (ret);
3277 }
3278
3279 int
3280 sig_intr(void)
3281 {
3282         struct thread *td;
3283         struct proc *p;
3284         int ret;
3285
3286         td = curthread;
3287         if ((td->td_flags & (TDF_NEEDSIGCHK | TDF_NEEDSUSPCHK)) == 0)
3288                 return (0);
3289
3290         p = td->td_proc;
3291
3292         PROC_LOCK(p);
3293         ret = sig_ast_checksusp(td);
3294         if (ret == 0)
3295                 ret = sig_ast_needsigchk(td);
3296         PROC_UNLOCK(p);
3297         return (ret);
3298 }
3299
3300 void
3301 proc_wkilled(struct proc *p)
3302 {
3303
3304         PROC_LOCK_ASSERT(p, MA_OWNED);
3305         if ((p->p_flag & P_WKILLED) == 0) {
3306                 p->p_flag |= P_WKILLED;
3307                 /*
3308                  * Notify swapper that there is a process to swap in.
3309                  * The notification is racy, at worst it would take 10
3310                  * seconds for the swapper process to notice.
3311                  */
3312                 if ((p->p_flag & (P_INMEM | P_SWAPPINGIN)) == 0)
3313                         wakeup(&proc0);
3314         }
3315 }
3316
3317 /*
3318  * Kill the current process for stated reason.
3319  */
3320 void
3321 killproc(struct proc *p, const char *why)
3322 {
3323
3324         PROC_LOCK_ASSERT(p, MA_OWNED);
3325         CTR3(KTR_PROC, "killproc: proc %p (pid %d, %s)", p, p->p_pid,
3326             p->p_comm);
3327         log(LOG_ERR, "pid %d (%s), jid %d, uid %d, was killed: %s\n",
3328             p->p_pid, p->p_comm, p->p_ucred->cr_prison->pr_id,
3329             p->p_ucred->cr_uid, why);
3330         proc_wkilled(p);
3331         kern_psignal(p, SIGKILL);
3332 }
3333
3334 /*
3335  * Force the current process to exit with the specified signal, dumping core
3336  * if appropriate.  We bypass the normal tests for masked and caught signals,
3337  * allowing unrecoverable failures to terminate the process without changing
3338  * signal state.  Mark the accounting record with the signal termination.
3339  * If dumping core, save the signal number for the debugger.  Calls exit and
3340  * does not return.
3341  */
3342 void
3343 sigexit(struct thread *td, int sig)
3344 {
3345         struct proc *p = td->td_proc;
3346
3347         PROC_LOCK_ASSERT(p, MA_OWNED);
3348         p->p_acflag |= AXSIG;
3349         /*
3350          * We must be single-threading to generate a core dump.  This
3351          * ensures that the registers in the core file are up-to-date.
3352          * Also, the ELF dump handler assumes that the thread list doesn't
3353          * change out from under it.
3354          *
3355          * XXX If another thread attempts to single-thread before us
3356          *     (e.g. via fork()), we won't get a dump at all.
3357          */
3358         if ((sigprop(sig) & SIGPROP_CORE) &&
3359             thread_single(p, SINGLE_NO_EXIT) == 0) {
3360                 p->p_sig = sig;
3361                 /*
3362                  * Log signals which would cause core dumps
3363                  * (Log as LOG_INFO to appease those who don't want
3364                  * these messages.)
3365                  * XXX : Todo, as well as euid, write out ruid too
3366                  * Note that coredump() drops proc lock.
3367                  */
3368                 if (coredump(td) == 0)
3369                         sig |= WCOREFLAG;
3370                 if (kern_logsigexit)
3371                         log(LOG_INFO,
3372                             "pid %d (%s), jid %d, uid %d: exited on "
3373                             "signal %d%s\n", p->p_pid, p->p_comm,
3374                             p->p_ucred->cr_prison->pr_id,
3375                             td->td_ucred->cr_uid,
3376                             sig &~ WCOREFLAG,
3377                             sig & WCOREFLAG ? " (core dumped)" : "");
3378         } else
3379                 PROC_UNLOCK(p);
3380         exit1(td, 0, sig);
3381         /* NOTREACHED */
3382 }
3383
3384 /*
3385  * Send queued SIGCHLD to parent when child process's state
3386  * is changed.
3387  */
3388 static void
3389 sigparent(struct proc *p, int reason, int status)
3390 {
3391         PROC_LOCK_ASSERT(p, MA_OWNED);
3392         PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3393
3394         if (p->p_ksi != NULL) {
3395                 p->p_ksi->ksi_signo  = SIGCHLD;
3396                 p->p_ksi->ksi_code   = reason;
3397                 p->p_ksi->ksi_status = status;
3398                 p->p_ksi->ksi_pid    = p->p_pid;
3399                 p->p_ksi->ksi_uid    = p->p_ucred->cr_ruid;
3400                 if (KSI_ONQ(p->p_ksi))
3401                         return;
3402         }
3403         pksignal(p->p_pptr, SIGCHLD, p->p_ksi);
3404 }
3405
3406 static void
3407 childproc_jobstate(struct proc *p, int reason, int sig)
3408 {
3409         struct sigacts *ps;
3410
3411         PROC_LOCK_ASSERT(p, MA_OWNED);
3412         PROC_LOCK_ASSERT(p->p_pptr, MA_OWNED);
3413
3414         /*
3415          * Wake up parent sleeping in kern_wait(), also send
3416          * SIGCHLD to parent, but SIGCHLD does not guarantee
3417          * that parent will awake, because parent may masked
3418          * the signal.
3419          */
3420         p->p_pptr->p_flag |= P_STATCHILD;
3421         wakeup(p->p_pptr);
3422
3423         ps = p->p_pptr->p_sigacts;
3424         mtx_lock(&ps->ps_mtx);
3425         if ((ps->ps_flag & PS_NOCLDSTOP) == 0) {
3426                 mtx_unlock(&ps->ps_mtx);
3427                 sigparent(p, reason, sig);
3428         } else
3429                 mtx_unlock(&ps->ps_mtx);
3430 }
3431
3432 void
3433 childproc_stopped(struct proc *p, int reason)
3434 {
3435
3436         childproc_jobstate(p, reason, p->p_xsig);
3437 }
3438
3439 void
3440 childproc_continued(struct proc *p)
3441 {
3442         childproc_jobstate(p, CLD_CONTINUED, SIGCONT);
3443 }
3444
3445 void
3446 childproc_exited(struct proc *p)
3447 {
3448         int reason, status;
3449
3450         if (WCOREDUMP(p->p_xsig)) {
3451                 reason = CLD_DUMPED;
3452                 status = WTERMSIG(p->p_xsig);
3453         } else if (WIFSIGNALED(p->p_xsig)) {
3454                 reason = CLD_KILLED;
3455                 status = WTERMSIG(p->p_xsig);
3456         } else {
3457                 reason = CLD_EXITED;
3458                 status = p->p_xexit;
3459         }
3460         /*
3461          * XXX avoid calling wakeup(p->p_pptr), the work is
3462          * done in exit1().
3463          */
3464         sigparent(p, reason, status);
3465 }
3466
3467 #define MAX_NUM_CORE_FILES 100000
3468 #ifndef NUM_CORE_FILES
3469 #define NUM_CORE_FILES 5
3470 #endif
3471 CTASSERT(NUM_CORE_FILES >= 0 && NUM_CORE_FILES <= MAX_NUM_CORE_FILES);
3472 static int num_cores = NUM_CORE_FILES;
3473
3474 static int
3475 sysctl_debug_num_cores_check (SYSCTL_HANDLER_ARGS)
3476 {
3477         int error;
3478         int new_val;
3479
3480         new_val = num_cores;
3481         error = sysctl_handle_int(oidp, &new_val, 0, req);
3482         if (error != 0 || req->newptr == NULL)
3483                 return (error);
3484         if (new_val > MAX_NUM_CORE_FILES)
3485                 new_val = MAX_NUM_CORE_FILES;
3486         if (new_val < 0)
3487                 new_val = 0;
3488         num_cores = new_val;
3489         return (0);
3490 }
3491 SYSCTL_PROC(_debug, OID_AUTO, ncores,
3492     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 0, sizeof(int),
3493     sysctl_debug_num_cores_check, "I",
3494     "Maximum number of generated process corefiles while using index format");
3495
3496 #define GZIP_SUFFIX     ".gz"
3497 #define ZSTD_SUFFIX     ".zst"
3498
3499 int compress_user_cores = 0;
3500
3501 static int
3502 sysctl_compress_user_cores(SYSCTL_HANDLER_ARGS)
3503 {
3504         int error, val;
3505
3506         val = compress_user_cores;
3507         error = sysctl_handle_int(oidp, &val, 0, req);
3508         if (error != 0 || req->newptr == NULL)
3509                 return (error);
3510         if (val != 0 && !compressor_avail(val))
3511                 return (EINVAL);
3512         compress_user_cores = val;
3513         return (error);
3514 }
3515 SYSCTL_PROC(_kern, OID_AUTO, compress_user_cores,
3516     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, 0, sizeof(int),
3517     sysctl_compress_user_cores, "I",
3518     "Enable compression of user corefiles ("
3519     __XSTRING(COMPRESS_GZIP) " = gzip, "
3520     __XSTRING(COMPRESS_ZSTD) " = zstd)");
3521
3522 int compress_user_cores_level = 6;
3523 SYSCTL_INT(_kern, OID_AUTO, compress_user_cores_level, CTLFLAG_RWTUN,
3524     &compress_user_cores_level, 0,
3525     "Corefile compression level");
3526
3527 /*
3528  * Protect the access to corefilename[] by allproc_lock.
3529  */
3530 #define corefilename_lock       allproc_lock
3531
3532 static char corefilename[MAXPATHLEN] = {"%N.core"};
3533 TUNABLE_STR("kern.corefile", corefilename, sizeof(corefilename));
3534
3535 static int
3536 sysctl_kern_corefile(SYSCTL_HANDLER_ARGS)
3537 {
3538         int error;
3539
3540         sx_xlock(&corefilename_lock);
3541         error = sysctl_handle_string(oidp, corefilename, sizeof(corefilename),
3542             req);
3543         sx_xunlock(&corefilename_lock);
3544
3545         return (error);
3546 }
3547 SYSCTL_PROC(_kern, OID_AUTO, corefile, CTLTYPE_STRING | CTLFLAG_RW |
3548     CTLFLAG_MPSAFE, 0, 0, sysctl_kern_corefile, "A",
3549     "Process corefile name format string");
3550
3551 static void
3552 vnode_close_locked(struct thread *td, struct vnode *vp)
3553 {
3554
3555         VOP_UNLOCK(vp);
3556         vn_close(vp, FWRITE, td->td_ucred, td);
3557 }
3558
3559 /*
3560  * If the core format has a %I in it, then we need to check
3561  * for existing corefiles before defining a name.
3562  * To do this we iterate over 0..ncores to find a
3563  * non-existing core file name to use. If all core files are
3564  * already used we choose the oldest one.
3565  */
3566 static int
3567 corefile_open_last(struct thread *td, char *name, int indexpos,
3568     int indexlen, int ncores, struct vnode **vpp)
3569 {
3570         struct vnode *oldvp, *nextvp, *vp;
3571         struct vattr vattr;
3572         struct nameidata nd;
3573         int error, i, flags, oflags, cmode;
3574         char ch;
3575         struct timespec lasttime;
3576
3577         nextvp = oldvp = NULL;
3578         cmode = S_IRUSR | S_IWUSR;
3579         oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3580             (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3581
3582         for (i = 0; i < ncores; i++) {
3583                 flags = O_CREAT | FWRITE | O_NOFOLLOW;
3584
3585                 ch = name[indexpos + indexlen];
3586                 (void)snprintf(name + indexpos, indexlen + 1, "%.*u", indexlen,
3587                     i);
3588                 name[indexpos + indexlen] = ch;
3589
3590                 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3591                 error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3592                     NULL);
3593                 if (error != 0)
3594                         break;
3595
3596                 vp = nd.ni_vp;
3597                 NDFREE(&nd, NDF_ONLY_PNBUF);
3598                 if ((flags & O_CREAT) == O_CREAT) {
3599                         nextvp = vp;
3600                         break;
3601                 }
3602
3603                 error = VOP_GETATTR(vp, &vattr, td->td_ucred);
3604                 if (error != 0) {
3605                         vnode_close_locked(td, vp);
3606                         break;
3607                 }
3608
3609                 if (oldvp == NULL ||
3610                     lasttime.tv_sec > vattr.va_mtime.tv_sec ||
3611                     (lasttime.tv_sec == vattr.va_mtime.tv_sec &&
3612                     lasttime.tv_nsec >= vattr.va_mtime.tv_nsec)) {
3613                         if (oldvp != NULL)
3614                                 vn_close(oldvp, FWRITE, td->td_ucred, td);
3615                         oldvp = vp;
3616                         VOP_UNLOCK(oldvp);
3617                         lasttime = vattr.va_mtime;
3618                 } else {
3619                         vnode_close_locked(td, vp);
3620                 }
3621         }
3622
3623         if (oldvp != NULL) {
3624                 if (nextvp == NULL) {
3625                         if ((td->td_proc->p_flag & P_SUGID) != 0) {
3626                                 error = EFAULT;
3627                                 vn_close(oldvp, FWRITE, td->td_ucred, td);
3628                         } else {
3629                                 nextvp = oldvp;
3630                                 error = vn_lock(nextvp, LK_EXCLUSIVE);
3631                                 if (error != 0) {
3632                                         vn_close(nextvp, FWRITE, td->td_ucred,
3633                                             td);
3634                                         nextvp = NULL;
3635                                 }
3636                         }
3637                 } else {
3638                         vn_close(oldvp, FWRITE, td->td_ucred, td);
3639                 }
3640         }
3641         if (error != 0) {
3642                 if (nextvp != NULL)
3643                         vnode_close_locked(td, oldvp);
3644         } else {
3645                 *vpp = nextvp;
3646         }
3647
3648         return (error);
3649 }
3650
3651 /*
3652  * corefile_open(comm, uid, pid, td, compress, vpp, namep)
3653  * Expand the name described in corefilename, using name, uid, and pid
3654  * and open/create core file.
3655  * corefilename is a printf-like string, with three format specifiers:
3656  *      %N      name of process ("name")
3657  *      %P      process id (pid)
3658  *      %U      user id (uid)
3659  * For example, "%N.core" is the default; they can be disabled completely
3660  * by using "/dev/null", or all core files can be stored in "/cores/%U/%N-%P".
3661  * This is controlled by the sysctl variable kern.corefile (see above).
3662  */
3663 static int
3664 corefile_open(const char *comm, uid_t uid, pid_t pid, struct thread *td,
3665     int compress, int signum, struct vnode **vpp, char **namep)
3666 {
3667         struct sbuf sb;
3668         struct nameidata nd;
3669         const char *format;
3670         char *hostname, *name;
3671         int cmode, error, flags, i, indexpos, indexlen, oflags, ncores;
3672
3673         hostname = NULL;
3674         format = corefilename;
3675         name = malloc(MAXPATHLEN, M_TEMP, M_WAITOK | M_ZERO);
3676         indexlen = 0;
3677         indexpos = -1;
3678         ncores = num_cores;
3679         (void)sbuf_new(&sb, name, MAXPATHLEN, SBUF_FIXEDLEN);
3680         sx_slock(&corefilename_lock);
3681         for (i = 0; format[i] != '\0'; i++) {
3682                 switch (format[i]) {
3683                 case '%':       /* Format character */
3684                         i++;
3685                         switch (format[i]) {
3686                         case '%':
3687                                 sbuf_putc(&sb, '%');
3688                                 break;
3689                         case 'H':       /* hostname */
3690                                 if (hostname == NULL) {
3691                                         hostname = malloc(MAXHOSTNAMELEN,
3692                                             M_TEMP, M_WAITOK);
3693                                 }
3694                                 getcredhostname(td->td_ucred, hostname,
3695                                     MAXHOSTNAMELEN);
3696                                 sbuf_printf(&sb, "%s", hostname);
3697                                 break;
3698                         case 'I':       /* autoincrementing index */
3699                                 if (indexpos != -1) {
3700                                         sbuf_printf(&sb, "%%I");
3701                                         break;
3702                                 }
3703
3704                                 indexpos = sbuf_len(&sb);
3705                                 sbuf_printf(&sb, "%u", ncores - 1);
3706                                 indexlen = sbuf_len(&sb) - indexpos;
3707                                 break;
3708                         case 'N':       /* process name */
3709                                 sbuf_printf(&sb, "%s", comm);
3710                                 break;
3711                         case 'P':       /* process id */
3712                                 sbuf_printf(&sb, "%u", pid);
3713                                 break;
3714                         case 'S':       /* signal number */
3715                                 sbuf_printf(&sb, "%i", signum);
3716                                 break;
3717                         case 'U':       /* user id */
3718                                 sbuf_printf(&sb, "%u", uid);
3719                                 break;
3720                         default:
3721                                 log(LOG_ERR,
3722                                     "Unknown format character %c in "
3723                                     "corename `%s'\n", format[i], format);
3724                                 break;
3725                         }
3726                         break;
3727                 default:
3728                         sbuf_putc(&sb, format[i]);
3729                         break;
3730                 }
3731         }
3732         sx_sunlock(&corefilename_lock);
3733         free(hostname, M_TEMP);
3734         if (compress == COMPRESS_GZIP)
3735                 sbuf_printf(&sb, GZIP_SUFFIX);
3736         else if (compress == COMPRESS_ZSTD)
3737                 sbuf_printf(&sb, ZSTD_SUFFIX);
3738         if (sbuf_error(&sb) != 0) {
3739                 log(LOG_ERR, "pid %ld (%s), uid (%lu): corename is too "
3740                     "long\n", (long)pid, comm, (u_long)uid);
3741                 sbuf_delete(&sb);
3742                 free(name, M_TEMP);
3743                 return (ENOMEM);
3744         }
3745         sbuf_finish(&sb);
3746         sbuf_delete(&sb);
3747
3748         if (indexpos != -1) {
3749                 error = corefile_open_last(td, name, indexpos, indexlen, ncores,
3750                     vpp);
3751                 if (error != 0) {
3752                         log(LOG_ERR,
3753                             "pid %d (%s), uid (%u):  Path `%s' failed "
3754                             "on initial open test, error = %d\n",
3755                             pid, comm, uid, name, error);
3756                 }
3757         } else {
3758                 cmode = S_IRUSR | S_IWUSR;
3759                 oflags = VN_OPEN_NOAUDIT | VN_OPEN_NAMECACHE |
3760                     (capmode_coredump ? VN_OPEN_NOCAPCHECK : 0);
3761                 flags = O_CREAT | FWRITE | O_NOFOLLOW;
3762                 if ((td->td_proc->p_flag & P_SUGID) != 0)
3763                         flags |= O_EXCL;
3764
3765                 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, name, td);
3766                 error = vn_open_cred(&nd, &flags, cmode, oflags, td->td_ucred,
3767                     NULL);
3768                 if (error == 0) {
3769                         *vpp = nd.ni_vp;
3770                         NDFREE(&nd, NDF_ONLY_PNBUF);
3771                 }
3772         }
3773
3774         if (error != 0) {
3775 #ifdef AUDIT
3776                 audit_proc_coredump(td, name, error);
3777 #endif
3778                 free(name, M_TEMP);
3779                 return (error);
3780         }
3781         *namep = name;
3782         return (0);
3783 }
3784
3785 /*
3786  * Dump a process' core.  The main routine does some
3787  * policy checking, and creates the name of the coredump;
3788  * then it passes on a vnode and a size limit to the process-specific
3789  * coredump routine if there is one; if there _is not_ one, it returns
3790  * ENOSYS; otherwise it returns the error from the process-specific routine.
3791  */
3792
3793 static int
3794 coredump(struct thread *td)
3795 {
3796         struct proc *p = td->td_proc;
3797         struct ucred *cred = td->td_ucred;
3798         struct vnode *vp;
3799         struct flock lf;
3800         struct vattr vattr;
3801         size_t fullpathsize;
3802         int error, error1, locked;
3803         char *name;                     /* name of corefile */
3804         void *rl_cookie;
3805         off_t limit;
3806         char *fullpath, *freepath = NULL;
3807         struct sbuf *sb;
3808
3809         PROC_LOCK_ASSERT(p, MA_OWNED);
3810         MPASS((p->p_flag & P_HADTHREADS) == 0 || p->p_singlethread == td);
3811
3812         if (!do_coredump || (!sugid_coredump && (p->p_flag & P_SUGID) != 0) ||
3813             (p->p_flag2 & P2_NOTRACE) != 0) {
3814                 PROC_UNLOCK(p);
3815                 return (EFAULT);
3816         }
3817
3818         /*
3819          * Note that the bulk of limit checking is done after
3820          * the corefile is created.  The exception is if the limit
3821          * for corefiles is 0, in which case we don't bother
3822          * creating the corefile at all.  This layout means that
3823          * a corefile is truncated instead of not being created,
3824          * if it is larger than the limit.
3825          */
3826         limit = (off_t)lim_cur(td, RLIMIT_CORE);
3827         if (limit == 0 || racct_get_available(p, RACCT_CORE) == 0) {
3828                 PROC_UNLOCK(p);
3829                 return (EFBIG);
3830         }
3831         PROC_UNLOCK(p);
3832
3833         error = corefile_open(p->p_comm, cred->cr_uid, p->p_pid, td,
3834             compress_user_cores, p->p_sig, &vp, &name);
3835         if (error != 0)
3836                 return (error);
3837
3838         /*
3839          * Don't dump to non-regular files or files with links.
3840          * Do not dump into system files. Effective user must own the corefile.
3841          */
3842         if (vp->v_type != VREG || VOP_GETATTR(vp, &vattr, cred) != 0 ||
3843             vattr.va_nlink != 1 || (vp->v_vflag & VV_SYSTEM) != 0 ||
3844             vattr.va_uid != cred->cr_uid) {
3845                 VOP_UNLOCK(vp);
3846                 error = EFAULT;
3847                 goto out;
3848         }
3849
3850         VOP_UNLOCK(vp);
3851
3852         /* Postpone other writers, including core dumps of other processes. */
3853         rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3854
3855         lf.l_whence = SEEK_SET;
3856         lf.l_start = 0;
3857         lf.l_len = 0;
3858         lf.l_type = F_WRLCK;
3859         locked = (VOP_ADVLOCK(vp, (caddr_t)p, F_SETLK, &lf, F_FLOCK) == 0);
3860
3861         VATTR_NULL(&vattr);
3862         vattr.va_size = 0;
3863         if (set_core_nodump_flag)
3864                 vattr.va_flags = UF_NODUMP;
3865         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3866         VOP_SETATTR(vp, &vattr, cred);
3867         VOP_UNLOCK(vp);
3868         PROC_LOCK(p);
3869         p->p_acflag |= ACORE;
3870         PROC_UNLOCK(p);
3871
3872         if (p->p_sysent->sv_coredump != NULL) {
3873                 error = p->p_sysent->sv_coredump(td, vp, limit, 0);
3874         } else {
3875                 error = ENOSYS;
3876         }
3877
3878         if (locked) {
3879                 lf.l_type = F_UNLCK;
3880                 VOP_ADVLOCK(vp, (caddr_t)p, F_UNLCK, &lf, F_FLOCK);
3881         }
3882         vn_rangelock_unlock(vp, rl_cookie);
3883
3884         /*
3885          * Notify the userland helper that a process triggered a core dump.
3886          * This allows the helper to run an automated debugging session.
3887          */
3888         if (error != 0 || coredump_devctl == 0)
3889                 goto out;
3890         sb = sbuf_new_auto();
3891         if (vn_fullpath_global(p->p_textvp, &fullpath, &freepath) != 0)
3892                 goto out2;
3893         sbuf_printf(sb, "comm=\"");
3894         devctl_safe_quote_sb(sb, fullpath);
3895         free(freepath, M_TEMP);
3896         sbuf_printf(sb, "\" core=\"");
3897
3898         /*
3899          * We can't lookup core file vp directly. When we're replacing a core, and
3900          * other random times, we flush the name cache, so it will fail. Instead,
3901          * if the path of the core is relative, add the current dir in front if it.
3902          */
3903         if (name[0] != '/') {
3904                 fullpathsize = MAXPATHLEN;
3905                 freepath = malloc(fullpathsize, M_TEMP, M_WAITOK);
3906                 if (vn_getcwd(freepath, &fullpath, &fullpathsize) != 0) {
3907                         free(freepath, M_TEMP);
3908                         goto out2;
3909                 }
3910                 devctl_safe_quote_sb(sb, fullpath);
3911                 free(freepath, M_TEMP);
3912                 sbuf_putc(sb, '/');
3913         }
3914         devctl_safe_quote_sb(sb, name);
3915         sbuf_printf(sb, "\"");
3916         if (sbuf_finish(sb) == 0)
3917                 devctl_notify("kernel", "signal", "coredump", sbuf_data(sb));
3918 out2:
3919         sbuf_delete(sb);
3920 out:
3921         error1 = vn_close(vp, FWRITE, cred, td);
3922         if (error == 0)
3923                 error = error1;
3924 #ifdef AUDIT
3925         audit_proc_coredump(td, name, error);
3926 #endif
3927         free(name, M_TEMP);
3928         return (error);
3929 }
3930
3931 /*
3932  * Nonexistent system call-- signal process (may want to handle it).  Flag
3933  * error in case process won't see signal immediately (blocked or ignored).
3934  */
3935 #ifndef _SYS_SYSPROTO_H_
3936 struct nosys_args {
3937         int     dummy;
3938 };
3939 #endif
3940 /* ARGSUSED */
3941 int
3942 nosys(struct thread *td, struct nosys_args *args)
3943 {
3944         struct proc *p;
3945
3946         p = td->td_proc;
3947
3948         PROC_LOCK(p);
3949         tdsignal(td, SIGSYS);
3950         PROC_UNLOCK(p);
3951         if (kern_lognosys == 1 || kern_lognosys == 3) {
3952                 uprintf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
3953                     td->td_sa.code);
3954         }
3955         if (kern_lognosys == 2 || kern_lognosys == 3 ||
3956             (p->p_pid == 1 && (kern_lognosys & 3) == 0)) {
3957                 printf("pid %d comm %s: nosys %d\n", p->p_pid, p->p_comm,
3958                     td->td_sa.code);
3959         }
3960         return (ENOSYS);
3961 }
3962
3963 /*
3964  * Send a SIGIO or SIGURG signal to a process or process group using stored
3965  * credentials rather than those of the current process.
3966  */
3967 void
3968 pgsigio(struct sigio **sigiop, int sig, int checkctty)
3969 {
3970         ksiginfo_t ksi;
3971         struct sigio *sigio;
3972
3973         ksiginfo_init(&ksi);
3974         ksi.ksi_signo = sig;
3975         ksi.ksi_code = SI_KERNEL;
3976
3977         SIGIO_LOCK();
3978         sigio = *sigiop;
3979         if (sigio == NULL) {
3980                 SIGIO_UNLOCK();
3981                 return;
3982         }
3983         if (sigio->sio_pgid > 0) {
3984                 PROC_LOCK(sigio->sio_proc);
3985                 if (CANSIGIO(sigio->sio_ucred, sigio->sio_proc->p_ucred))
3986                         kern_psignal(sigio->sio_proc, sig);
3987                 PROC_UNLOCK(sigio->sio_proc);
3988         } else if (sigio->sio_pgid < 0) {
3989                 struct proc *p;
3990
3991                 PGRP_LOCK(sigio->sio_pgrp);
3992                 LIST_FOREACH(p, &sigio->sio_pgrp->pg_members, p_pglist) {
3993                         PROC_LOCK(p);
3994                         if (p->p_state == PRS_NORMAL &&
3995                             CANSIGIO(sigio->sio_ucred, p->p_ucred) &&
3996                             (checkctty == 0 || (p->p_flag & P_CONTROLT)))
3997                                 kern_psignal(p, sig);
3998                         PROC_UNLOCK(p);
3999                 }
4000                 PGRP_UNLOCK(sigio->sio_pgrp);
4001         }
4002         SIGIO_UNLOCK();
4003 }
4004
4005 static int
4006 filt_sigattach(struct knote *kn)
4007 {
4008         struct proc *p = curproc;
4009
4010         kn->kn_ptr.p_proc = p;
4011         kn->kn_flags |= EV_CLEAR;               /* automatically set */
4012
4013         knlist_add(p->p_klist, kn, 0);
4014
4015         return (0);
4016 }
4017
4018 static void
4019 filt_sigdetach(struct knote *kn)
4020 {
4021         struct proc *p = kn->kn_ptr.p_proc;
4022
4023         knlist_remove(p->p_klist, kn, 0);
4024 }
4025
4026 /*
4027  * signal knotes are shared with proc knotes, so we apply a mask to
4028  * the hint in order to differentiate them from process hints.  This
4029  * could be avoided by using a signal-specific knote list, but probably
4030  * isn't worth the trouble.
4031  */
4032 static int
4033 filt_signal(struct knote *kn, long hint)
4034 {
4035
4036         if (hint & NOTE_SIGNAL) {
4037                 hint &= ~NOTE_SIGNAL;
4038
4039                 if (kn->kn_id == hint)
4040                         kn->kn_data++;
4041         }
4042         return (kn->kn_data != 0);
4043 }
4044
4045 struct sigacts *
4046 sigacts_alloc(void)
4047 {
4048         struct sigacts *ps;
4049
4050         ps = malloc(sizeof(struct sigacts), M_SUBPROC, M_WAITOK | M_ZERO);
4051         refcount_init(&ps->ps_refcnt, 1);
4052         mtx_init(&ps->ps_mtx, "sigacts", NULL, MTX_DEF);
4053         return (ps);
4054 }
4055
4056 void
4057 sigacts_free(struct sigacts *ps)
4058 {
4059
4060         if (refcount_release(&ps->ps_refcnt) == 0)
4061                 return;
4062         mtx_destroy(&ps->ps_mtx);
4063         free(ps, M_SUBPROC);
4064 }
4065
4066 struct sigacts *
4067 sigacts_hold(struct sigacts *ps)
4068 {
4069
4070         refcount_acquire(&ps->ps_refcnt);
4071         return (ps);
4072 }
4073
4074 void
4075 sigacts_copy(struct sigacts *dest, struct sigacts *src)
4076 {
4077
4078         KASSERT(dest->ps_refcnt == 1, ("sigacts_copy to shared dest"));
4079         mtx_lock(&src->ps_mtx);
4080         bcopy(src, dest, offsetof(struct sigacts, ps_refcnt));
4081         mtx_unlock(&src->ps_mtx);
4082 }
4083
4084 int
4085 sigacts_shared(struct sigacts *ps)
4086 {
4087
4088         return (ps->ps_refcnt > 1);
4089 }
4090
4091 void
4092 sig_drop_caught(struct proc *p)
4093 {
4094         int sig;
4095         struct sigacts *ps;
4096
4097         ps = p->p_sigacts;
4098         PROC_LOCK_ASSERT(p, MA_OWNED);
4099         mtx_assert(&ps->ps_mtx, MA_OWNED);
4100         while (SIGNOTEMPTY(ps->ps_sigcatch)) {
4101                 sig = sig_ffs(&ps->ps_sigcatch);
4102                 sigdflt(ps, sig);
4103                 if ((sigprop(sig) & SIGPROP_IGNORE) != 0)
4104                         sigqueue_delete_proc(p, sig);
4105         }
4106 }
4107
4108 static void
4109 sigfastblock_failed(struct thread *td, bool sendsig, bool write)
4110 {
4111         ksiginfo_t ksi;
4112
4113         /*
4114          * Prevent further fetches and SIGSEGVs, allowing thread to
4115          * issue syscalls despite corruption.
4116          */
4117         sigfastblock_clear(td);
4118
4119         if (!sendsig)
4120                 return;
4121         ksiginfo_init_trap(&ksi);
4122         ksi.ksi_signo = SIGSEGV;
4123         ksi.ksi_code = write ? SEGV_ACCERR : SEGV_MAPERR;
4124         ksi.ksi_addr = td->td_sigblock_ptr;
4125         trapsignal(td, &ksi);
4126 }
4127
4128 static bool
4129 sigfastblock_fetch_sig(struct thread *td, bool sendsig, uint32_t *valp)
4130 {
4131         uint32_t res;
4132
4133         if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4134                 return (true);
4135         if (fueword32((void *)td->td_sigblock_ptr, &res) == -1) {
4136                 sigfastblock_failed(td, sendsig, false);
4137                 return (false);
4138         }
4139         *valp = res;
4140         td->td_sigblock_val = res & ~SIGFASTBLOCK_FLAGS;
4141         return (true);
4142 }
4143
4144 static void
4145 sigfastblock_resched(struct thread *td, bool resched)
4146 {
4147         struct proc *p;
4148
4149         if (resched) {
4150                 p = td->td_proc;
4151                 PROC_LOCK(p);
4152                 reschedule_signals(p, td->td_sigmask, 0);
4153                 PROC_UNLOCK(p);
4154         }
4155         thread_lock(td);
4156         td->td_flags |= TDF_ASTPENDING | TDF_NEEDSIGCHK;
4157         thread_unlock(td);
4158 }
4159
4160 int
4161 sys_sigfastblock(struct thread *td, struct sigfastblock_args *uap)
4162 {
4163         struct proc *p;
4164         int error, res;
4165         uint32_t oldval;
4166
4167         error = 0;
4168         p = td->td_proc;
4169         switch (uap->cmd) {
4170         case SIGFASTBLOCK_SETPTR:
4171                 if ((td->td_pflags & TDP_SIGFASTBLOCK) != 0) {
4172                         error = EBUSY;
4173                         break;
4174                 }
4175                 if (((uintptr_t)(uap->ptr) & (sizeof(uint32_t) - 1)) != 0) {
4176                         error = EINVAL;
4177                         break;
4178                 }
4179                 td->td_pflags |= TDP_SIGFASTBLOCK;
4180                 td->td_sigblock_ptr = uap->ptr;
4181                 break;
4182
4183         case SIGFASTBLOCK_UNBLOCK:
4184                 if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4185                         error = EINVAL;
4186                         break;
4187                 }
4188
4189                 for (;;) {
4190                         res = casueword32(td->td_sigblock_ptr,
4191                             SIGFASTBLOCK_PEND, &oldval, 0);
4192                         if (res == -1) {
4193                                 error = EFAULT;
4194                                 sigfastblock_failed(td, false, true);
4195                                 break;
4196                         }
4197                         if (res == 0)
4198                                 break;
4199                         MPASS(res == 1);
4200                         if (oldval != SIGFASTBLOCK_PEND) {
4201                                 error = EBUSY;
4202                                 break;
4203                         }
4204                         error = thread_check_susp(td, false);
4205                         if (error != 0)
4206                                 break;
4207                 }
4208                 if (error != 0)
4209                         break;
4210
4211                 /*
4212                  * td_sigblock_val is cleared there, but not on a
4213                  * syscall exit.  The end effect is that a single
4214                  * interruptible sleep, while user sigblock word is
4215                  * set, might return EINTR or ERESTART to usermode
4216                  * without delivering signal.  All further sleeps,
4217                  * until userspace clears the word and does
4218                  * sigfastblock(UNBLOCK), observe current word and no
4219                  * longer get interrupted.  It is slight
4220                  * non-conformance, with alternative to have read the
4221                  * sigblock word on each syscall entry.
4222                  */
4223                 td->td_sigblock_val = 0;
4224
4225                 /*
4226                  * Rely on normal ast mechanism to deliver pending
4227                  * signals to current thread.  But notify others about
4228                  * fake unblock.
4229                  */
4230                 sigfastblock_resched(td, error == 0 && p->p_numthreads != 1);
4231
4232                 break;
4233
4234         case SIGFASTBLOCK_UNSETPTR:
4235                 if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0) {
4236                         error = EINVAL;
4237                         break;
4238                 }
4239                 if (!sigfastblock_fetch_sig(td, false, &oldval)) {
4240                         error = EFAULT;
4241                         break;
4242                 }
4243                 if (oldval != 0 && oldval != SIGFASTBLOCK_PEND) {
4244                         error = EBUSY;
4245                         break;
4246                 }
4247                 sigfastblock_clear(td);
4248                 break;
4249
4250         default:
4251                 error = EINVAL;
4252                 break;
4253         }
4254         return (error);
4255 }
4256
4257 void
4258 sigfastblock_clear(struct thread *td)
4259 {
4260         bool resched;
4261
4262         if ((td->td_pflags & TDP_SIGFASTBLOCK) == 0)
4263                 return;
4264         td->td_sigblock_val = 0;
4265         resched = (td->td_pflags & TDP_SIGFASTPENDING) != 0 ||
4266             SIGPENDING(td);
4267         td->td_pflags &= ~(TDP_SIGFASTBLOCK | TDP_SIGFASTPENDING);
4268         sigfastblock_resched(td, resched);
4269 }
4270
4271 void
4272 sigfastblock_fetch(struct thread *td)
4273 {
4274         uint32_t val;
4275
4276         (void)sigfastblock_fetch_sig(td, true, &val);
4277 }
4278
4279 static void
4280 sigfastblock_setpend1(struct thread *td)
4281 {
4282         int res;
4283         uint32_t oldval;
4284
4285         if ((td->td_pflags & TDP_SIGFASTPENDING) == 0)
4286                 return;
4287         res = fueword32((void *)td->td_sigblock_ptr, &oldval);
4288         if (res == -1) {
4289                 sigfastblock_failed(td, true, false);
4290                 return;
4291         }
4292         for (;;) {
4293                 res = casueword32(td->td_sigblock_ptr, oldval, &oldval,
4294                     oldval | SIGFASTBLOCK_PEND);
4295                 if (res == -1) {
4296                         sigfastblock_failed(td, true, true);
4297                         return;
4298                 }
4299                 if (res == 0) {
4300                         td->td_sigblock_val = oldval & ~SIGFASTBLOCK_FLAGS;
4301                         td->td_pflags &= ~TDP_SIGFASTPENDING;
4302                         break;
4303                 }
4304                 MPASS(res == 1);
4305                 if (thread_check_susp(td, false) != 0)
4306                         break;
4307         }
4308 }
4309
4310 void
4311 sigfastblock_setpend(struct thread *td, bool resched)
4312 {
4313         struct proc *p;
4314
4315         sigfastblock_setpend1(td);
4316         if (resched) {
4317                 p = td->td_proc;
4318                 PROC_LOCK(p);
4319                 reschedule_signals(p, fastblock_mask, SIGPROCMASK_FASTBLK);
4320                 PROC_UNLOCK(p);
4321         }
4322 }