xref: /qemu/bsd-user/signal.c (revision 46f4f76d332d8c2b4eb24c8e6f91ac8bdc205733)
1 /*
2  *  Emulation of BSD signals
3  *
4  *  Copyright (c) 2003 - 2008 Fabrice Bellard
5  *  Copyright (c) 2013 Stacey Son
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include "qemu/osdep.h"
22 #include "qemu.h"
23 #include "signal-common.h"
24 #include "trace.h"
25 #include "hw/core/tcg-cpu-ops.h"
26 #include "host-signal.h"
27 
28 /*
29  * Stubbed out routines until we merge signal support from bsd-user
30  * fork.
31  */
32 
33 static struct target_sigaction sigact_table[TARGET_NSIG];
34 static void host_signal_handler(int host_sig, siginfo_t *info, void *puc);
35 static void target_to_host_sigset_internal(sigset_t *d,
36         const target_sigset_t *s);
37 
38 static inline int on_sig_stack(TaskState *ts, unsigned long sp)
39 {
40     return sp - ts->sigaltstack_used.ss_sp < ts->sigaltstack_used.ss_size;
41 }
42 
43 static inline int sas_ss_flags(TaskState *ts, unsigned long sp)
44 {
45     return ts->sigaltstack_used.ss_size == 0 ? SS_DISABLE :
46         on_sig_stack(ts, sp) ? SS_ONSTACK : 0;
47 }
48 
49 /*
50  * The BSD ABIs use the same singal numbers across all the CPU architectures, so
51  * (unlike Linux) these functions are just the identity mapping. This might not
52  * be true for XyzBSD running on AbcBSD, which doesn't currently work.
53  */
54 int host_to_target_signal(int sig)
55 {
56     return sig;
57 }
58 
59 int target_to_host_signal(int sig)
60 {
61     return sig;
62 }
63 
64 static inline void target_sigemptyset(target_sigset_t *set)
65 {
66     memset(set, 0, sizeof(*set));
67 }
68 
69 static inline void target_sigaddset(target_sigset_t *set, int signum)
70 {
71     signum--;
72     uint32_t mask = (uint32_t)1 << (signum % TARGET_NSIG_BPW);
73     set->__bits[signum / TARGET_NSIG_BPW] |= mask;
74 }
75 
76 static inline int target_sigismember(const target_sigset_t *set, int signum)
77 {
78     signum--;
79     abi_ulong mask = (abi_ulong)1 << (signum % TARGET_NSIG_BPW);
80     return (set->__bits[signum / TARGET_NSIG_BPW] & mask) != 0;
81 }
82 
83 /* Adjust the signal context to rewind out of safe-syscall if we're in it */
84 static inline void rewind_if_in_safe_syscall(void *puc)
85 {
86     ucontext_t *uc = (ucontext_t *)puc;
87     uintptr_t pcreg = host_signal_pc(uc);
88 
89     if (pcreg > (uintptr_t)safe_syscall_start
90         && pcreg < (uintptr_t)safe_syscall_end) {
91         host_signal_set_pc(uc, (uintptr_t)safe_syscall_start);
92     }
93 }
94 
95 /*
96  * Note: The following take advantage of the BSD signal property that all
97  * signals are available on all architectures.
98  */
99 static void host_to_target_sigset_internal(target_sigset_t *d,
100         const sigset_t *s)
101 {
102     int i;
103 
104     target_sigemptyset(d);
105     for (i = 1; i <= NSIG; i++) {
106         if (sigismember(s, i)) {
107             target_sigaddset(d, host_to_target_signal(i));
108         }
109     }
110 }
111 
112 void host_to_target_sigset(target_sigset_t *d, const sigset_t *s)
113 {
114     target_sigset_t d1;
115     int i;
116 
117     host_to_target_sigset_internal(&d1, s);
118     for (i = 0; i < _SIG_WORDS; i++) {
119         d->__bits[i] = tswap32(d1.__bits[i]);
120     }
121 }
122 
123 static void target_to_host_sigset_internal(sigset_t *d,
124         const target_sigset_t *s)
125 {
126     int i;
127 
128     sigemptyset(d);
129     for (i = 1; i <= TARGET_NSIG; i++) {
130         if (target_sigismember(s, i)) {
131             sigaddset(d, target_to_host_signal(i));
132         }
133     }
134 }
135 
136 void target_to_host_sigset(sigset_t *d, const target_sigset_t *s)
137 {
138     target_sigset_t s1;
139     int i;
140 
141     for (i = 0; i < TARGET_NSIG_WORDS; i++) {
142         s1.__bits[i] = tswap32(s->__bits[i]);
143     }
144     target_to_host_sigset_internal(d, &s1);
145 }
146 
147 static bool has_trapno(int tsig)
148 {
149     return tsig == TARGET_SIGILL ||
150         tsig == TARGET_SIGFPE ||
151         tsig == TARGET_SIGSEGV ||
152         tsig == TARGET_SIGBUS ||
153         tsig == TARGET_SIGTRAP;
154 }
155 
156 /* Siginfo conversion. */
157 
158 /*
159  * Populate tinfo w/o swapping based on guessing which fields are valid.
160  */
161 static inline void host_to_target_siginfo_noswap(target_siginfo_t *tinfo,
162         const siginfo_t *info)
163 {
164     int sig = host_to_target_signal(info->si_signo);
165     int si_code = info->si_code;
166     int si_type;
167 
168     /*
169      * Make sure we that the variable portion of the target siginfo is zeroed
170      * out so we don't leak anything into that.
171      */
172     memset(&tinfo->_reason, 0, sizeof(tinfo->_reason));
173 
174     /*
175      * This is awkward, because we have to use a combination of the si_code and
176      * si_signo to figure out which of the union's members are valid.o We
177      * therefore make our best guess.
178      *
179      * Once we have made our guess, we record it in the top 16 bits of
180      * the si_code, so that tswap_siginfo() later can use it.
181      * tswap_siginfo() will strip these top bits out before writing
182      * si_code to the guest (sign-extending the lower bits).
183      */
184     tinfo->si_signo = sig;
185     tinfo->si_errno = info->si_errno;
186     tinfo->si_code = info->si_code;
187     tinfo->si_pid = info->si_pid;
188     tinfo->si_uid = info->si_uid;
189     tinfo->si_status = info->si_status;
190     tinfo->si_addr = (abi_ulong)(unsigned long)info->si_addr;
191     /*
192      * si_value is opaque to kernel. On all FreeBSD platforms,
193      * sizeof(sival_ptr) >= sizeof(sival_int) so the following
194      * always will copy the larger element.
195      */
196     tinfo->si_value.sival_ptr =
197         (abi_ulong)(unsigned long)info->si_value.sival_ptr;
198 
199     switch (si_code) {
200         /*
201          * All the SI_xxx codes that are defined here are global to
202          * all the signals (they have values that none of the other,
203          * more specific signal info will set).
204          */
205     case SI_USER:
206     case SI_LWP:
207     case SI_KERNEL:
208     case SI_QUEUE:
209     case SI_ASYNCIO:
210         /*
211          * Only the fixed parts are valid (though FreeBSD doesn't always
212          * set all the fields to non-zero values.
213          */
214         si_type = QEMU_SI_NOINFO;
215         break;
216     case SI_TIMER:
217         tinfo->_reason._timer._timerid = info->_reason._timer._timerid;
218         tinfo->_reason._timer._overrun = info->_reason._timer._overrun;
219         si_type = QEMU_SI_TIMER;
220         break;
221     case SI_MESGQ:
222         tinfo->_reason._mesgq._mqd = info->_reason._mesgq._mqd;
223         si_type = QEMU_SI_MESGQ;
224         break;
225     default:
226         /*
227          * We have to go based on the signal number now to figure out
228          * what's valid.
229          */
230         if (has_trapno(sig)) {
231             tinfo->_reason._fault._trapno = info->_reason._fault._trapno;
232             si_type = QEMU_SI_FAULT;
233         }
234 #ifdef TARGET_SIGPOLL
235         /*
236          * FreeBSD never had SIGPOLL, but emulates it for Linux so there's
237          * a chance it may popup in the future.
238          */
239         if (sig == TARGET_SIGPOLL) {
240             tinfo->_reason._poll._band = info->_reason._poll._band;
241             si_type = QEMU_SI_POLL;
242         }
243 #endif
244         /*
245          * Unsure that this can actually be generated, and our support for
246          * capsicum is somewhere between weak and non-existant, but if we get
247          * one, then we know what to save.
248          */
249         if (sig == TARGET_SIGTRAP) {
250             tinfo->_reason._capsicum._syscall =
251                 info->_reason._capsicum._syscall;
252             si_type = QEMU_SI_CAPSICUM;
253         }
254         break;
255     }
256     tinfo->si_code = deposit32(si_code, 24, 8, si_type);
257 }
258 
259 /* Returns 1 if given signal should dump core if not handled. */
260 static int core_dump_signal(int sig)
261 {
262     switch (sig) {
263     case TARGET_SIGABRT:
264     case TARGET_SIGFPE:
265     case TARGET_SIGILL:
266     case TARGET_SIGQUIT:
267     case TARGET_SIGSEGV:
268     case TARGET_SIGTRAP:
269     case TARGET_SIGBUS:
270         return 1;
271     default:
272         return 0;
273     }
274 }
275 
276 /* Abort execution with signal. */
277 static void QEMU_NORETURN dump_core_and_abort(int target_sig)
278 {
279     CPUArchState *env = thread_cpu->env_ptr;
280     CPUState *cpu = env_cpu(env);
281     TaskState *ts = cpu->opaque;
282     int core_dumped = 0;
283     int host_sig;
284     struct sigaction act;
285 
286     host_sig = target_to_host_signal(target_sig);
287     gdb_signalled(env, target_sig);
288 
289     /* Dump core if supported by target binary format */
290     if (core_dump_signal(target_sig) && (ts->bprm->core_dump != NULL)) {
291         stop_all_tasks();
292         core_dumped =
293             ((*ts->bprm->core_dump)(target_sig, env) == 0);
294     }
295     if (core_dumped) {
296         struct rlimit nodump;
297 
298         /*
299          * We already dumped the core of target process, we don't want
300          * a coredump of qemu itself.
301          */
302          getrlimit(RLIMIT_CORE, &nodump);
303          nodump.rlim_cur = 0;
304          setrlimit(RLIMIT_CORE, &nodump);
305          (void) fprintf(stderr, "qemu: uncaught target signal %d (%s) "
306              "- %s\n", target_sig, strsignal(host_sig), "core dumped");
307     }
308 
309     /*
310      * The proper exit code for dying from an uncaught signal is
311      * -<signal>.  The kernel doesn't allow exit() or _exit() to pass
312      * a negative value.  To get the proper exit code we need to
313      * actually die from an uncaught signal.  Here the default signal
314      * handler is installed, we send ourself a signal and we wait for
315      * it to arrive.
316      */
317     memset(&act, 0, sizeof(act));
318     sigfillset(&act.sa_mask);
319     act.sa_handler = SIG_DFL;
320     sigaction(host_sig, &act, NULL);
321 
322     kill(getpid(), host_sig);
323 
324     /*
325      * Make sure the signal isn't masked (just reuse the mask inside
326      * of act).
327      */
328     sigdelset(&act.sa_mask, host_sig);
329     sigsuspend(&act.sa_mask);
330 
331     /* unreachable */
332     abort();
333 }
334 
335 /*
336  * Queue a signal so that it will be send to the virtual CPU as soon as
337  * possible.
338  */
339 void queue_signal(CPUArchState *env, int sig, int si_type,
340                   target_siginfo_t *info)
341 {
342     CPUState *cpu = env_cpu(env);
343     TaskState *ts = cpu->opaque;
344 
345     trace_user_queue_signal(env, sig);
346 
347     info->si_code = deposit32(info->si_code, 24, 8, si_type);
348 
349     ts->sync_signal.info = *info;
350     ts->sync_signal.pending = sig;
351     /* Signal that a new signal is pending. */
352     qatomic_set(&ts->signal_pending, 1);
353     return;
354 }
355 
356 static int fatal_signal(int sig)
357 {
358 
359     switch (sig) {
360     case TARGET_SIGCHLD:
361     case TARGET_SIGURG:
362     case TARGET_SIGWINCH:
363     case TARGET_SIGINFO:
364         /* Ignored by default. */
365         return 0;
366     case TARGET_SIGCONT:
367     case TARGET_SIGSTOP:
368     case TARGET_SIGTSTP:
369     case TARGET_SIGTTIN:
370     case TARGET_SIGTTOU:
371         /* Job control signals.  */
372         return 0;
373     default:
374         return 1;
375     }
376 }
377 
378 /*
379  * Force a synchronously taken QEMU_SI_FAULT signal. For QEMU the
380  * 'force' part is handled in process_pending_signals().
381  */
382 void force_sig_fault(int sig, int code, abi_ulong addr)
383 {
384     CPUState *cpu = thread_cpu;
385     CPUArchState *env = cpu->env_ptr;
386     target_siginfo_t info = {};
387 
388     info.si_signo = sig;
389     info.si_errno = 0;
390     info.si_code = code;
391     info.si_addr = addr;
392     queue_signal(env, sig, QEMU_SI_FAULT, &info);
393 }
394 
395 static void host_signal_handler(int host_sig, siginfo_t *info, void *puc)
396 {
397     CPUArchState *env = thread_cpu->env_ptr;
398     CPUState *cpu = env_cpu(env);
399     TaskState *ts = cpu->opaque;
400     target_siginfo_t tinfo;
401     ucontext_t *uc = puc;
402     struct emulated_sigtable *k;
403     int guest_sig;
404     uintptr_t pc = 0;
405     bool sync_sig = false;
406 
407     /*
408      * Non-spoofed SIGSEGV and SIGBUS are synchronous, and need special
409      * handling wrt signal blocking and unwinding.
410      */
411     if ((host_sig == SIGSEGV || host_sig == SIGBUS) && info->si_code > 0) {
412         MMUAccessType access_type;
413         uintptr_t host_addr;
414         abi_ptr guest_addr;
415         bool is_write;
416 
417         host_addr = (uintptr_t)info->si_addr;
418 
419         /*
420          * Convert forcefully to guest address space: addresses outside
421          * reserved_va are still valid to report via SEGV_MAPERR.
422          */
423         guest_addr = h2g_nocheck(host_addr);
424 
425         pc = host_signal_pc(uc);
426         is_write = host_signal_write(info, uc);
427         access_type = adjust_signal_pc(&pc, is_write);
428 
429         if (host_sig == SIGSEGV) {
430             bool maperr = true;
431 
432             if (info->si_code == SEGV_ACCERR && h2g_valid(host_addr)) {
433                 /* If this was a write to a TB protected page, restart. */
434                 if (is_write &&
435                     handle_sigsegv_accerr_write(cpu, &uc->uc_sigmask,
436                                                 pc, guest_addr)) {
437                     return;
438                 }
439 
440                 /*
441                  * With reserved_va, the whole address space is PROT_NONE,
442                  * which means that we may get ACCERR when we want MAPERR.
443                  */
444                 if (page_get_flags(guest_addr) & PAGE_VALID) {
445                     maperr = false;
446                 } else {
447                     info->si_code = SEGV_MAPERR;
448                 }
449             }
450 
451             sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
452             cpu_loop_exit_sigsegv(cpu, guest_addr, access_type, maperr, pc);
453         } else {
454             sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
455             if (info->si_code == BUS_ADRALN) {
456                 cpu_loop_exit_sigbus(cpu, guest_addr, access_type, pc);
457             }
458         }
459 
460         sync_sig = true;
461     }
462 
463     /* Get the target signal number. */
464     guest_sig = host_to_target_signal(host_sig);
465     if (guest_sig < 1 || guest_sig > TARGET_NSIG) {
466         return;
467     }
468     trace_user_host_signal(cpu, host_sig, guest_sig);
469 
470     host_to_target_siginfo_noswap(&tinfo, info);
471 
472     k = &ts->sigtab[guest_sig - 1];
473     k->info = tinfo;
474     k->pending = guest_sig;
475     ts->signal_pending = 1;
476 
477     /*
478      * For synchronous signals, unwind the cpu state to the faulting
479      * insn and then exit back to the main loop so that the signal
480      * is delivered immediately.
481      */
482     if (sync_sig) {
483         cpu->exception_index = EXCP_INTERRUPT;
484         cpu_loop_exit_restore(cpu, pc);
485     }
486 
487     rewind_if_in_safe_syscall(puc);
488 
489     /*
490      * Block host signals until target signal handler entered. We
491      * can't block SIGSEGV or SIGBUS while we're executing guest
492      * code in case the guest code provokes one in the window between
493      * now and it getting out to the main loop. Signals will be
494      * unblocked again in process_pending_signals().
495      */
496     sigfillset(&uc->uc_sigmask);
497     sigdelset(&uc->uc_sigmask, SIGSEGV);
498     sigdelset(&uc->uc_sigmask, SIGBUS);
499 
500     /* Interrupt the virtual CPU as soon as possible. */
501     cpu_exit(thread_cpu);
502 }
503 
504 static inline abi_ulong get_sigframe(struct target_sigaction *ka,
505         CPUArchState *env, size_t frame_size)
506 {
507     TaskState *ts = (TaskState *)thread_cpu->opaque;
508     abi_ulong sp;
509 
510     /* Use default user stack */
511     sp = get_sp_from_cpustate(env);
512 
513     if ((ka->sa_flags & TARGET_SA_ONSTACK) && sas_ss_flags(ts, sp) == 0) {
514         sp = ts->sigaltstack_used.ss_sp + ts->sigaltstack_used.ss_size;
515     }
516 
517 /* TODO: make this a target_arch function / define */
518 #if defined(TARGET_ARM)
519     return (sp - frame_size) & ~7;
520 #elif defined(TARGET_AARCH64)
521     return (sp - frame_size) & ~15;
522 #else
523     return sp - frame_size;
524 #endif
525 }
526 
527 /* compare to $M/$M/exec_machdep.c sendsig and sys/kern/kern_sig.c sigexit */
528 
529 static void setup_frame(int sig, int code, struct target_sigaction *ka,
530     target_sigset_t *set, target_siginfo_t *tinfo, CPUArchState *env)
531 {
532     struct target_sigframe *frame;
533     abi_ulong frame_addr;
534     int i;
535 
536     frame_addr = get_sigframe(ka, env, sizeof(*frame));
537     trace_user_setup_frame(env, frame_addr);
538     if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {
539         unlock_user_struct(frame, frame_addr, 1);
540         dump_core_and_abort(TARGET_SIGILL);
541         return;
542     }
543 
544     memset(frame, 0, sizeof(*frame));
545     setup_sigframe_arch(env, frame_addr, frame, 0);
546 
547     for (i = 0; i < TARGET_NSIG_WORDS; i++) {
548         __put_user(set->__bits[i], &frame->sf_uc.uc_sigmask.__bits[i]);
549     }
550 
551     if (tinfo) {
552         frame->sf_si.si_signo = tinfo->si_signo;
553         frame->sf_si.si_errno = tinfo->si_errno;
554         frame->sf_si.si_code = tinfo->si_code;
555         frame->sf_si.si_pid = tinfo->si_pid;
556         frame->sf_si.si_uid = tinfo->si_uid;
557         frame->sf_si.si_status = tinfo->si_status;
558         frame->sf_si.si_addr = tinfo->si_addr;
559         /* see host_to_target_siginfo_noswap() for more details */
560         frame->sf_si.si_value.sival_ptr = tinfo->si_value.sival_ptr;
561         /*
562          * At this point, whatever is in the _reason union is complete
563          * and in target order, so just copy the whole thing over, even
564          * if it's too large for this specific signal.
565          * host_to_target_siginfo_noswap() and tswap_siginfo() have ensured
566          * that's so.
567          */
568         memcpy(&frame->sf_si._reason, &tinfo->_reason,
569                sizeof(tinfo->_reason));
570     }
571 
572     set_sigtramp_args(env, sig, frame, frame_addr, ka);
573 
574     unlock_user_struct(frame, frame_addr, 1);
575 }
576 
577 void signal_init(void)
578 {
579     TaskState *ts = (TaskState *)thread_cpu->opaque;
580     struct sigaction act;
581     struct sigaction oact;
582     int i;
583     int host_sig;
584 
585     /* Set the signal mask from the host mask. */
586     sigprocmask(0, 0, &ts->signal_mask);
587 
588     sigfillset(&act.sa_mask);
589     act.sa_sigaction = host_signal_handler;
590     act.sa_flags = SA_SIGINFO;
591 
592     for (i = 1; i <= TARGET_NSIG; i++) {
593 #ifdef CONFIG_GPROF
594         if (i == TARGET_SIGPROF) {
595             continue;
596         }
597 #endif
598         host_sig = target_to_host_signal(i);
599         sigaction(host_sig, NULL, &oact);
600         if (oact.sa_sigaction == (void *)SIG_IGN) {
601             sigact_table[i - 1]._sa_handler = TARGET_SIG_IGN;
602         } else if (oact.sa_sigaction == (void *)SIG_DFL) {
603             sigact_table[i - 1]._sa_handler = TARGET_SIG_DFL;
604         }
605         /*
606          * If there's already a handler installed then something has
607          * gone horribly wrong, so don't even try to handle that case.
608          * Install some handlers for our own use.  We need at least
609          * SIGSEGV and SIGBUS, to detect exceptions.  We can not just
610          * trap all signals because it affects syscall interrupt
611          * behavior.  But do trap all default-fatal signals.
612          */
613         if (fatal_signal(i)) {
614             sigaction(host_sig, &act, NULL);
615         }
616     }
617 }
618 
619 void process_pending_signals(CPUArchState *cpu_env)
620 {
621 }
622 
623 void cpu_loop_exit_sigsegv(CPUState *cpu, target_ulong addr,
624                            MMUAccessType access_type, bool maperr, uintptr_t ra)
625 {
626     const struct TCGCPUOps *tcg_ops = CPU_GET_CLASS(cpu)->tcg_ops;
627 
628     if (tcg_ops->record_sigsegv) {
629         tcg_ops->record_sigsegv(cpu, addr, access_type, maperr, ra);
630     }
631 
632     force_sig_fault(TARGET_SIGSEGV,
633                     maperr ? TARGET_SEGV_MAPERR : TARGET_SEGV_ACCERR,
634                     addr);
635     cpu->exception_index = EXCP_INTERRUPT;
636     cpu_loop_exit_restore(cpu, ra);
637 }
638 
639 void cpu_loop_exit_sigbus(CPUState *cpu, target_ulong addr,
640                           MMUAccessType access_type, uintptr_t ra)
641 {
642     const struct TCGCPUOps *tcg_ops = CPU_GET_CLASS(cpu)->tcg_ops;
643 
644     if (tcg_ops->record_sigbus) {
645         tcg_ops->record_sigbus(cpu, addr, access_type, ra);
646     }
647 
648     force_sig_fault(TARGET_SIGBUS, TARGET_BUS_ADRALN, addr);
649     cpu->exception_index = EXCP_INTERRUPT;
650     cpu_loop_exit_restore(cpu, ra);
651 }
652