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