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