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