xref: /openbmc/qemu/bsd-user/signal.c (revision 5f69e42d)
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/log.h"
23 #include "qemu.h"
24 #include "exec/page-protection.h"
25 #include "user/tswap-target.h"
26 #include "gdbstub/user.h"
27 #include "signal-common.h"
28 #include "trace.h"
29 #include "hw/core/tcg-cpu-ops.h"
30 #include "host-signal.h"
31 
32 /* target_siginfo_t must fit in gdbstub's siginfo save area. */
33 QEMU_BUILD_BUG_ON(sizeof(target_siginfo_t) > MAX_SIGINFO_LENGTH);
34 
35 static struct target_sigaction sigact_table[TARGET_NSIG];
36 static void host_signal_handler(int host_sig, siginfo_t *info, void *puc);
37 static void target_to_host_sigset_internal(sigset_t *d,
38         const target_sigset_t *s);
39 
40 static inline int on_sig_stack(TaskState *ts, unsigned long sp)
41 {
42     return sp - ts->sigaltstack_used.ss_sp < ts->sigaltstack_used.ss_size;
43 }
44 
45 static inline int sas_ss_flags(TaskState *ts, unsigned long sp)
46 {
47     return ts->sigaltstack_used.ss_size == 0 ? SS_DISABLE :
48         on_sig_stack(ts, sp) ? SS_ONSTACK : 0;
49 }
50 
51 /*
52  * The BSD ABIs use the same signal numbers across all the CPU architectures, so
53  * (unlike Linux) these functions are just the identity mapping. This might not
54  * be true for XyzBSD running on AbcBSD, which doesn't currently work.
55  */
56 int host_to_target_signal(int sig)
57 {
58     return sig;
59 }
60 
61 int target_to_host_signal(int sig)
62 {
63     return sig;
64 }
65 
66 static inline void target_sigemptyset(target_sigset_t *set)
67 {
68     memset(set, 0, sizeof(*set));
69 }
70 
71 static inline void target_sigaddset(target_sigset_t *set, int signum)
72 {
73     signum--;
74     uint32_t mask = (uint32_t)1 << (signum % TARGET_NSIG_BPW);
75     set->__bits[signum / TARGET_NSIG_BPW] |= mask;
76 }
77 
78 static inline int target_sigismember(const target_sigset_t *set, int signum)
79 {
80     signum--;
81     abi_ulong mask = (abi_ulong)1 << (signum % TARGET_NSIG_BPW);
82     return (set->__bits[signum / TARGET_NSIG_BPW] & mask) != 0;
83 }
84 
85 /* Adjust the signal context to rewind out of safe-syscall if we're in it */
86 static inline void rewind_if_in_safe_syscall(void *puc)
87 {
88     ucontext_t *uc = (ucontext_t *)puc;
89     uintptr_t pcreg = host_signal_pc(uc);
90 
91     if (pcreg > (uintptr_t)safe_syscall_start
92         && pcreg < (uintptr_t)safe_syscall_end) {
93         host_signal_set_pc(uc, (uintptr_t)safe_syscall_start);
94     }
95 }
96 
97 /*
98  * Note: The following take advantage of the BSD signal property that all
99  * signals are available on all architectures.
100  */
101 static void host_to_target_sigset_internal(target_sigset_t *d,
102         const sigset_t *s)
103 {
104     int i;
105 
106     target_sigemptyset(d);
107     for (i = 1; i <= NSIG; i++) {
108         if (sigismember(s, i)) {
109             target_sigaddset(d, host_to_target_signal(i));
110         }
111     }
112 }
113 
114 void host_to_target_sigset(target_sigset_t *d, const sigset_t *s)
115 {
116     target_sigset_t d1;
117     int i;
118 
119     host_to_target_sigset_internal(&d1, s);
120     for (i = 0; i < _SIG_WORDS; i++) {
121         d->__bits[i] = tswap32(d1.__bits[i]);
122     }
123 }
124 
125 static void target_to_host_sigset_internal(sigset_t *d,
126         const target_sigset_t *s)
127 {
128     int i;
129 
130     sigemptyset(d);
131     for (i = 1; i <= TARGET_NSIG; i++) {
132         if (target_sigismember(s, i)) {
133             sigaddset(d, target_to_host_signal(i));
134         }
135     }
136 }
137 
138 void target_to_host_sigset(sigset_t *d, const target_sigset_t *s)
139 {
140     target_sigset_t s1;
141     int i;
142 
143     for (i = 0; i < TARGET_NSIG_WORDS; i++) {
144         s1.__bits[i] = tswap32(s->__bits[i]);
145     }
146     target_to_host_sigset_internal(d, &s1);
147 }
148 
149 static bool has_trapno(int tsig)
150 {
151     return tsig == TARGET_SIGILL ||
152         tsig == TARGET_SIGFPE ||
153         tsig == TARGET_SIGSEGV ||
154         tsig == TARGET_SIGBUS ||
155         tsig == TARGET_SIGTRAP;
156 }
157 
158 /* Siginfo conversion. */
159 
160 /*
161  * Populate tinfo w/o swapping based on guessing which fields are valid.
162  */
163 static inline void host_to_target_siginfo_noswap(target_siginfo_t *tinfo,
164         const siginfo_t *info)
165 {
166     int sig = host_to_target_signal(info->si_signo);
167     int si_code = info->si_code;
168     int si_type;
169 
170     /*
171      * Make sure we that the variable portion of the target siginfo is zeroed
172      * out so we don't leak anything into that.
173      */
174     memset(&tinfo->_reason, 0, sizeof(tinfo->_reason));
175 
176     /*
177      * This is awkward, because we have to use a combination of the si_code and
178      * si_signo to figure out which of the union's members are valid.o We
179      * therefore make our best guess.
180      *
181      * Once we have made our guess, we record it in the top 16 bits of
182      * the si_code, so that tswap_siginfo() later can use it.
183      * tswap_siginfo() will strip these top bits out before writing
184      * si_code to the guest (sign-extending the lower bits).
185      */
186     tinfo->si_signo = sig;
187     tinfo->si_errno = info->si_errno;
188     tinfo->si_code = info->si_code;
189     tinfo->si_pid = info->si_pid;
190     tinfo->si_uid = info->si_uid;
191     tinfo->si_status = info->si_status;
192     tinfo->si_addr = (abi_ulong)(unsigned long)info->si_addr;
193     /*
194      * si_value is opaque to kernel. On all FreeBSD platforms,
195      * sizeof(sival_ptr) >= sizeof(sival_int) so the following
196      * always will copy the larger element.
197      */
198     tinfo->si_value.sival_ptr =
199         (abi_ulong)(unsigned long)info->si_value.sival_ptr;
200 
201     switch (si_code) {
202         /*
203          * All the SI_xxx codes that are defined here are global to
204          * all the signals (they have values that none of the other,
205          * more specific signal info will set).
206          */
207     case SI_USER:
208     case SI_LWP:
209     case SI_KERNEL:
210     case SI_QUEUE:
211     case SI_ASYNCIO:
212         /*
213          * Only the fixed parts are valid (though FreeBSD doesn't always
214          * set all the fields to non-zero values.
215          */
216         si_type = QEMU_SI_NOINFO;
217         break;
218     case SI_TIMER:
219         tinfo->_reason._timer._timerid = info->_reason._timer._timerid;
220         tinfo->_reason._timer._overrun = info->_reason._timer._overrun;
221         si_type = QEMU_SI_TIMER;
222         break;
223     case SI_MESGQ:
224         tinfo->_reason._mesgq._mqd = info->_reason._mesgq._mqd;
225         si_type = QEMU_SI_MESGQ;
226         break;
227     default:
228         /*
229          * We have to go based on the signal number now to figure out
230          * what's valid.
231          */
232         si_type = QEMU_SI_NOINFO;
233         if (has_trapno(sig)) {
234             tinfo->_reason._fault._trapno = info->_reason._fault._trapno;
235             si_type = QEMU_SI_FAULT;
236         }
237 #ifdef TARGET_SIGPOLL
238         /*
239          * FreeBSD never had SIGPOLL, but emulates it for Linux so there's
240          * a chance it may popup in the future.
241          */
242         if (sig == TARGET_SIGPOLL) {
243             tinfo->_reason._poll._band = info->_reason._poll._band;
244             si_type = QEMU_SI_POLL;
245         }
246 #endif
247         /*
248          * Unsure that this can actually be generated, and our support for
249          * capsicum is somewhere between weak and non-existent, but if we get
250          * one, then we know what to save.
251          */
252 #ifdef QEMU_SI_CAPSICUM
253         if (sig == TARGET_SIGTRAP) {
254             tinfo->_reason._capsicum._syscall =
255                 info->_reason._capsicum._syscall;
256             si_type = QEMU_SI_CAPSICUM;
257         }
258 #endif
259         break;
260     }
261     tinfo->si_code = deposit32(si_code, 24, 8, si_type);
262 }
263 
264 static void tswap_siginfo(target_siginfo_t *tinfo, const target_siginfo_t *info)
265 {
266     int si_type = extract32(info->si_code, 24, 8);
267     int si_code = sextract32(info->si_code, 0, 24);
268 
269     __put_user(info->si_signo, &tinfo->si_signo);
270     __put_user(info->si_errno, &tinfo->si_errno);
271     __put_user(si_code, &tinfo->si_code); /* Zero out si_type, it's internal */
272     __put_user(info->si_pid, &tinfo->si_pid);
273     __put_user(info->si_uid, &tinfo->si_uid);
274     __put_user(info->si_status, &tinfo->si_status);
275     __put_user(info->si_addr, &tinfo->si_addr);
276     /*
277      * Unswapped, because we passed it through mostly untouched.  si_value is
278      * opaque to the kernel, so we didn't bother with potentially wasting cycles
279      * to swap it into host byte order.
280      */
281     tinfo->si_value.sival_ptr = info->si_value.sival_ptr;
282 
283     /*
284      * We can use our internal marker of which fields in the structure
285      * are valid, rather than duplicating the guesswork of
286      * host_to_target_siginfo_noswap() here.
287      */
288     switch (si_type) {
289     case QEMU_SI_NOINFO:        /* No additional info */
290         break;
291     case QEMU_SI_FAULT:
292         __put_user(info->_reason._fault._trapno,
293                    &tinfo->_reason._fault._trapno);
294         break;
295     case QEMU_SI_TIMER:
296         __put_user(info->_reason._timer._timerid,
297                    &tinfo->_reason._timer._timerid);
298         __put_user(info->_reason._timer._overrun,
299                    &tinfo->_reason._timer._overrun);
300         break;
301     case QEMU_SI_MESGQ:
302         __put_user(info->_reason._mesgq._mqd, &tinfo->_reason._mesgq._mqd);
303         break;
304     case QEMU_SI_POLL:
305         /* Note: Not generated on FreeBSD */
306         __put_user(info->_reason._poll._band, &tinfo->_reason._poll._band);
307         break;
308 #ifdef QEMU_SI_CAPSICUM
309     case QEMU_SI_CAPSICUM:
310         __put_user(info->_reason._capsicum._syscall,
311                    &tinfo->_reason._capsicum._syscall);
312         break;
313 #endif
314     default:
315         g_assert_not_reached();
316     }
317 }
318 
319 void host_to_target_siginfo(target_siginfo_t *tinfo, const siginfo_t *info)
320 {
321     host_to_target_siginfo_noswap(tinfo, info);
322     tswap_siginfo(tinfo, tinfo);
323 }
324 
325 int block_signals(void)
326 {
327     TaskState *ts = get_task_state(thread_cpu);
328     sigset_t set;
329 
330     /*
331      * It's OK to block everything including SIGSEGV, because we won't run any
332      * further guest code before unblocking signals in
333      * process_pending_signals(). We depend on the FreeBSD behavior here where
334      * this will only affect this thread's signal mask. We don't use
335      * pthread_sigmask which might seem more correct because that routine also
336      * does odd things with SIGCANCEL to implement pthread_cancel().
337      */
338     sigfillset(&set);
339     sigprocmask(SIG_SETMASK, &set, 0);
340 
341     return qatomic_xchg(&ts->signal_pending, 1);
342 }
343 
344 /* Returns 1 if given signal should dump core if not handled. */
345 static int core_dump_signal(int sig)
346 {
347     switch (sig) {
348     case TARGET_SIGABRT:
349     case TARGET_SIGFPE:
350     case TARGET_SIGILL:
351     case TARGET_SIGQUIT:
352     case TARGET_SIGSEGV:
353     case TARGET_SIGTRAP:
354     case TARGET_SIGBUS:
355         return 1;
356     default:
357         return 0;
358     }
359 }
360 
361 /* Abort execution with signal. */
362 static G_NORETURN
363 void dump_core_and_abort(int target_sig)
364 {
365     CPUState *cpu = thread_cpu;
366     CPUArchState *env = cpu_env(cpu);
367     TaskState *ts = get_task_state(cpu);
368     int core_dumped = 0;
369     int host_sig;
370     struct sigaction act;
371 
372     host_sig = target_to_host_signal(target_sig);
373     gdb_signalled(env, target_sig);
374 
375     /* Dump core if supported by target binary format */
376     if (core_dump_signal(target_sig) && (ts->bprm->core_dump != NULL)) {
377         stop_all_tasks();
378         core_dumped =
379             ((*ts->bprm->core_dump)(target_sig, env) == 0);
380     }
381     if (core_dumped) {
382         struct rlimit nodump;
383 
384         /*
385          * We already dumped the core of target process, we don't want
386          * a coredump of qemu itself.
387          */
388          getrlimit(RLIMIT_CORE, &nodump);
389          nodump.rlim_cur = 0;
390          setrlimit(RLIMIT_CORE, &nodump);
391          (void) fprintf(stderr, "qemu: uncaught target signal %d (%s) "
392              "- %s\n", target_sig, strsignal(host_sig), "core dumped");
393     }
394 
395     /*
396      * The proper exit code for dying from an uncaught signal is
397      * -<signal>.  The kernel doesn't allow exit() or _exit() to pass
398      * a negative value.  To get the proper exit code we need to
399      * actually die from an uncaught signal.  Here the default signal
400      * handler is installed, we send ourself a signal and we wait for
401      * it to arrive.
402      */
403     memset(&act, 0, sizeof(act));
404     sigfillset(&act.sa_mask);
405     act.sa_handler = SIG_DFL;
406     sigaction(host_sig, &act, NULL);
407 
408     kill(getpid(), host_sig);
409 
410     /*
411      * Make sure the signal isn't masked (just reuse the mask inside
412      * of act).
413      */
414     sigdelset(&act.sa_mask, host_sig);
415     sigsuspend(&act.sa_mask);
416 
417     /* unreachable */
418     abort();
419 }
420 
421 /*
422  * Queue a signal so that it will be send to the virtual CPU as soon as
423  * possible.
424  */
425 void queue_signal(CPUArchState *env, int sig, int si_type,
426                   target_siginfo_t *info)
427 {
428     CPUState *cpu = env_cpu(env);
429     TaskState *ts = get_task_state(cpu);
430 
431     trace_user_queue_signal(env, sig);
432 
433     info->si_code = deposit32(info->si_code, 24, 8, si_type);
434 
435     ts->sync_signal.info = *info;
436     ts->sync_signal.pending = sig;
437     /* Signal that a new signal is pending. */
438     qatomic_set(&ts->signal_pending, 1);
439     return;
440 }
441 
442 static int fatal_signal(int sig)
443 {
444 
445     switch (sig) {
446     case TARGET_SIGCHLD:
447     case TARGET_SIGURG:
448     case TARGET_SIGWINCH:
449     case TARGET_SIGINFO:
450         /* Ignored by default. */
451         return 0;
452     case TARGET_SIGCONT:
453     case TARGET_SIGSTOP:
454     case TARGET_SIGTSTP:
455     case TARGET_SIGTTIN:
456     case TARGET_SIGTTOU:
457         /* Job control signals.  */
458         return 0;
459     default:
460         return 1;
461     }
462 }
463 
464 /*
465  * Force a synchronously taken QEMU_SI_FAULT signal. For QEMU the
466  * 'force' part is handled in process_pending_signals().
467  */
468 void force_sig_fault(int sig, int code, abi_ulong addr)
469 {
470     CPUState *cpu = thread_cpu;
471     target_siginfo_t info = {};
472 
473     info.si_signo = sig;
474     info.si_errno = 0;
475     info.si_code = code;
476     info.si_addr = addr;
477     queue_signal(cpu_env(cpu), sig, QEMU_SI_FAULT, &info);
478 }
479 
480 static void host_signal_handler(int host_sig, siginfo_t *info, void *puc)
481 {
482     CPUState *cpu = thread_cpu;
483     TaskState *ts = get_task_state(cpu);
484     target_siginfo_t tinfo;
485     ucontext_t *uc = puc;
486     struct emulated_sigtable *k;
487     int guest_sig;
488     uintptr_t pc = 0;
489     bool sync_sig = false;
490 
491     /*
492      * Non-spoofed SIGSEGV and SIGBUS are synchronous, and need special
493      * handling wrt signal blocking and unwinding.
494      */
495     if ((host_sig == SIGSEGV || host_sig == SIGBUS) && info->si_code > 0) {
496         MMUAccessType access_type;
497         uintptr_t host_addr;
498         abi_ptr guest_addr;
499         bool is_write;
500 
501         host_addr = (uintptr_t)info->si_addr;
502 
503         /*
504          * Convert forcefully to guest address space: addresses outside
505          * reserved_va are still valid to report via SEGV_MAPERR.
506          */
507         guest_addr = h2g_nocheck(host_addr);
508 
509         pc = host_signal_pc(uc);
510         is_write = host_signal_write(info, uc);
511         access_type = adjust_signal_pc(&pc, is_write);
512 
513         if (host_sig == SIGSEGV) {
514             bool maperr = true;
515 
516             if (info->si_code == SEGV_ACCERR && h2g_valid(host_addr)) {
517                 /* If this was a write to a TB protected page, restart. */
518                 if (is_write &&
519                     handle_sigsegv_accerr_write(cpu, &uc->uc_sigmask,
520                                                 pc, guest_addr)) {
521                     return;
522                 }
523 
524                 /*
525                  * With reserved_va, the whole address space is PROT_NONE,
526                  * which means that we may get ACCERR when we want MAPERR.
527                  */
528                 if (page_get_flags(guest_addr) & PAGE_VALID) {
529                     maperr = false;
530                 } else {
531                     info->si_code = SEGV_MAPERR;
532                 }
533             }
534 
535             sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
536             cpu_loop_exit_sigsegv(cpu, guest_addr, access_type, maperr, pc);
537         } else {
538             sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
539             if (info->si_code == BUS_ADRALN) {
540                 cpu_loop_exit_sigbus(cpu, guest_addr, access_type, pc);
541             }
542         }
543 
544         sync_sig = true;
545     }
546 
547     /* Get the target signal number. */
548     guest_sig = host_to_target_signal(host_sig);
549     if (guest_sig < 1 || guest_sig > TARGET_NSIG) {
550         return;
551     }
552     trace_user_host_signal(cpu, host_sig, guest_sig);
553 
554     host_to_target_siginfo_noswap(&tinfo, info);
555 
556     k = &ts->sigtab[guest_sig - 1];
557     k->info = tinfo;
558     k->pending = guest_sig;
559     ts->signal_pending = 1;
560 
561     /*
562      * For synchronous signals, unwind the cpu state to the faulting
563      * insn and then exit back to the main loop so that the signal
564      * is delivered immediately.
565      */
566     if (sync_sig) {
567         cpu->exception_index = EXCP_INTERRUPT;
568         cpu_loop_exit_restore(cpu, pc);
569     }
570 
571     rewind_if_in_safe_syscall(puc);
572 
573     /*
574      * Block host signals until target signal handler entered. We
575      * can't block SIGSEGV or SIGBUS while we're executing guest
576      * code in case the guest code provokes one in the window between
577      * now and it getting out to the main loop. Signals will be
578      * unblocked again in process_pending_signals().
579      */
580     sigfillset(&uc->uc_sigmask);
581     sigdelset(&uc->uc_sigmask, SIGSEGV);
582     sigdelset(&uc->uc_sigmask, SIGBUS);
583 
584     /* Interrupt the virtual CPU as soon as possible. */
585     cpu_exit(thread_cpu);
586 }
587 
588 /* do_sigaltstack() returns target values and errnos. */
589 /* compare to kern/kern_sig.c sys_sigaltstack() and kern_sigaltstack() */
590 abi_long do_sigaltstack(abi_ulong uss_addr, abi_ulong uoss_addr, abi_ulong sp)
591 {
592     TaskState *ts = get_task_state(thread_cpu);
593     int ret;
594     target_stack_t oss;
595 
596     if (uoss_addr) {
597         /* Save current signal stack params */
598         oss.ss_sp = tswapl(ts->sigaltstack_used.ss_sp);
599         oss.ss_size = tswapl(ts->sigaltstack_used.ss_size);
600         oss.ss_flags = tswapl(sas_ss_flags(ts, sp));
601     }
602 
603     if (uss_addr) {
604         target_stack_t *uss;
605         target_stack_t ss;
606         size_t minstacksize = TARGET_MINSIGSTKSZ;
607 
608         ret = -TARGET_EFAULT;
609         if (!lock_user_struct(VERIFY_READ, uss, uss_addr, 1)) {
610             goto out;
611         }
612         __get_user(ss.ss_sp, &uss->ss_sp);
613         __get_user(ss.ss_size, &uss->ss_size);
614         __get_user(ss.ss_flags, &uss->ss_flags);
615         unlock_user_struct(uss, uss_addr, 0);
616 
617         ret = -TARGET_EPERM;
618         if (on_sig_stack(ts, sp)) {
619             goto out;
620         }
621 
622         ret = -TARGET_EINVAL;
623         if (ss.ss_flags != TARGET_SS_DISABLE
624             && ss.ss_flags != TARGET_SS_ONSTACK
625             && ss.ss_flags != 0) {
626             goto out;
627         }
628 
629         if (ss.ss_flags == TARGET_SS_DISABLE) {
630             ss.ss_size = 0;
631             ss.ss_sp = 0;
632         } else {
633             ret = -TARGET_ENOMEM;
634             if (ss.ss_size < minstacksize) {
635                 goto out;
636             }
637         }
638 
639         ts->sigaltstack_used.ss_sp = ss.ss_sp;
640         ts->sigaltstack_used.ss_size = ss.ss_size;
641     }
642 
643     if (uoss_addr) {
644         ret = -TARGET_EFAULT;
645         if (copy_to_user(uoss_addr, &oss, sizeof(oss))) {
646             goto out;
647         }
648     }
649 
650     ret = 0;
651 out:
652     return ret;
653 }
654 
655 /* do_sigaction() return host values and errnos */
656 int do_sigaction(int sig, const struct target_sigaction *act,
657         struct target_sigaction *oact)
658 {
659     struct target_sigaction *k;
660     struct sigaction act1;
661     int host_sig;
662     int ret = 0;
663 
664     if (sig < 1 || sig > TARGET_NSIG) {
665         return -TARGET_EINVAL;
666     }
667 
668     if ((sig == TARGET_SIGKILL || sig == TARGET_SIGSTOP) &&
669         act != NULL && act->_sa_handler != TARGET_SIG_DFL) {
670         return -TARGET_EINVAL;
671     }
672 
673     if (block_signals()) {
674         return -TARGET_ERESTART;
675     }
676 
677     k = &sigact_table[sig - 1];
678     if (oact) {
679         oact->_sa_handler = tswapal(k->_sa_handler);
680         oact->sa_flags = tswap32(k->sa_flags);
681         oact->sa_mask = k->sa_mask;
682     }
683     if (act) {
684         k->_sa_handler = tswapal(act->_sa_handler);
685         k->sa_flags = tswap32(act->sa_flags);
686         k->sa_mask = act->sa_mask;
687 
688         /* Update the host signal state. */
689         host_sig = target_to_host_signal(sig);
690         if (host_sig != SIGSEGV && host_sig != SIGBUS) {
691             memset(&act1, 0, sizeof(struct sigaction));
692             sigfillset(&act1.sa_mask);
693             act1.sa_flags = SA_SIGINFO;
694             if (k->sa_flags & TARGET_SA_RESTART) {
695                 act1.sa_flags |= SA_RESTART;
696             }
697             /*
698              *  Note: It is important to update the host kernel signal mask to
699              *  avoid getting unexpected interrupted system calls.
700              */
701             if (k->_sa_handler == TARGET_SIG_IGN) {
702                 act1.sa_sigaction = (void *)SIG_IGN;
703             } else if (k->_sa_handler == TARGET_SIG_DFL) {
704                 if (fatal_signal(sig)) {
705                     act1.sa_sigaction = host_signal_handler;
706                 } else {
707                     act1.sa_sigaction = (void *)SIG_DFL;
708                 }
709             } else {
710                 act1.sa_sigaction = host_signal_handler;
711             }
712             ret = sigaction(host_sig, &act1, NULL);
713         }
714     }
715     return ret;
716 }
717 
718 static inline abi_ulong get_sigframe(struct target_sigaction *ka,
719         CPUArchState *env, size_t frame_size)
720 {
721     TaskState *ts = get_task_state(thread_cpu);
722     abi_ulong sp;
723 
724     /* Use default user stack */
725     sp = get_sp_from_cpustate(env);
726 
727     if ((ka->sa_flags & TARGET_SA_ONSTACK) && sas_ss_flags(ts, sp) == 0) {
728         sp = ts->sigaltstack_used.ss_sp + ts->sigaltstack_used.ss_size;
729     }
730 
731 /* TODO: make this a target_arch function / define */
732 #if defined(TARGET_ARM)
733     return (sp - frame_size) & ~7;
734 #elif defined(TARGET_AARCH64)
735     return (sp - frame_size) & ~15;
736 #else
737     return sp - frame_size;
738 #endif
739 }
740 
741 /* compare to $M/$M/exec_machdep.c sendsig and sys/kern/kern_sig.c sigexit */
742 
743 static void setup_frame(int sig, int code, struct target_sigaction *ka,
744     target_sigset_t *set, target_siginfo_t *tinfo, CPUArchState *env)
745 {
746     struct target_sigframe *frame;
747     abi_ulong frame_addr;
748     int i;
749 
750     frame_addr = get_sigframe(ka, env, sizeof(*frame));
751     trace_user_setup_frame(env, frame_addr);
752     if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {
753         unlock_user_struct(frame, frame_addr, 1);
754         dump_core_and_abort(TARGET_SIGILL);
755         return;
756     }
757 
758     memset(frame, 0, sizeof(*frame));
759     setup_sigframe_arch(env, frame_addr, frame, 0);
760 
761     for (i = 0; i < TARGET_NSIG_WORDS; i++) {
762         __put_user(set->__bits[i], &frame->sf_uc.uc_sigmask.__bits[i]);
763     }
764 
765     if (tinfo) {
766         frame->sf_si.si_signo = tinfo->si_signo;
767         frame->sf_si.si_errno = tinfo->si_errno;
768         frame->sf_si.si_code = tinfo->si_code;
769         frame->sf_si.si_pid = tinfo->si_pid;
770         frame->sf_si.si_uid = tinfo->si_uid;
771         frame->sf_si.si_status = tinfo->si_status;
772         frame->sf_si.si_addr = tinfo->si_addr;
773         /* see host_to_target_siginfo_noswap() for more details */
774         frame->sf_si.si_value.sival_ptr = tinfo->si_value.sival_ptr;
775         /*
776          * At this point, whatever is in the _reason union is complete
777          * and in target order, so just copy the whole thing over, even
778          * if it's too large for this specific signal.
779          * host_to_target_siginfo_noswap() and tswap_siginfo() have ensured
780          * that's so.
781          */
782         memcpy(&frame->sf_si._reason, &tinfo->_reason,
783                sizeof(tinfo->_reason));
784     }
785 
786     set_sigtramp_args(env, sig, frame, frame_addr, ka);
787 
788     unlock_user_struct(frame, frame_addr, 1);
789 }
790 
791 static int reset_signal_mask(target_ucontext_t *ucontext)
792 {
793     int i;
794     sigset_t blocked;
795     target_sigset_t target_set;
796     TaskState *ts = get_task_state(thread_cpu);
797 
798     for (i = 0; i < TARGET_NSIG_WORDS; i++) {
799         __get_user(target_set.__bits[i], &ucontext->uc_sigmask.__bits[i]);
800     }
801     target_to_host_sigset_internal(&blocked, &target_set);
802     ts->signal_mask = blocked;
803 
804     return 0;
805 }
806 
807 /* See sys/$M/$M/exec_machdep.c sigreturn() */
808 long do_sigreturn(CPUArchState *env, abi_ulong addr)
809 {
810     long ret;
811     abi_ulong target_ucontext;
812     target_ucontext_t *ucontext = NULL;
813 
814     /* Get the target ucontext address from the stack frame */
815     ret = get_ucontext_sigreturn(env, addr, &target_ucontext);
816     if (is_error(ret)) {
817         return ret;
818     }
819     trace_user_do_sigreturn(env, addr);
820     if (!lock_user_struct(VERIFY_READ, ucontext, target_ucontext, 0)) {
821         goto badframe;
822     }
823 
824     /* Set the register state back to before the signal. */
825     if (set_mcontext(env, &ucontext->uc_mcontext, 1)) {
826         goto badframe;
827     }
828 
829     /* And reset the signal mask. */
830     if (reset_signal_mask(ucontext)) {
831         goto badframe;
832     }
833 
834     unlock_user_struct(ucontext, target_ucontext, 0);
835     return -TARGET_EJUSTRETURN;
836 
837 badframe:
838     if (ucontext != NULL) {
839         unlock_user_struct(ucontext, target_ucontext, 0);
840     }
841     return -TARGET_EFAULT;
842 }
843 
844 void signal_init(void)
845 {
846     TaskState *ts = get_task_state(thread_cpu);
847     struct sigaction act;
848     struct sigaction oact;
849     int i;
850     int host_sig;
851 
852     /* Set the signal mask from the host mask. */
853     sigprocmask(0, 0, &ts->signal_mask);
854 
855     sigfillset(&act.sa_mask);
856     act.sa_sigaction = host_signal_handler;
857     act.sa_flags = SA_SIGINFO;
858 
859     for (i = 1; i <= TARGET_NSIG; i++) {
860         host_sig = target_to_host_signal(i);
861         sigaction(host_sig, NULL, &oact);
862         if (oact.sa_sigaction == (void *)SIG_IGN) {
863             sigact_table[i - 1]._sa_handler = TARGET_SIG_IGN;
864         } else if (oact.sa_sigaction == (void *)SIG_DFL) {
865             sigact_table[i - 1]._sa_handler = TARGET_SIG_DFL;
866         }
867         /*
868          * If there's already a handler installed then something has
869          * gone horribly wrong, so don't even try to handle that case.
870          * Install some handlers for our own use.  We need at least
871          * SIGSEGV and SIGBUS, to detect exceptions.  We can not just
872          * trap all signals because it affects syscall interrupt
873          * behavior.  But do trap all default-fatal signals.
874          */
875         if (fatal_signal(i)) {
876             sigaction(host_sig, &act, NULL);
877         }
878     }
879 }
880 
881 static void handle_pending_signal(CPUArchState *env, int sig,
882                                   struct emulated_sigtable *k)
883 {
884     CPUState *cpu = env_cpu(env);
885     TaskState *ts = get_task_state(cpu);
886     struct target_sigaction *sa;
887     int code;
888     sigset_t set;
889     abi_ulong handler;
890     target_siginfo_t tinfo;
891     target_sigset_t target_old_set;
892 
893     trace_user_handle_signal(env, sig);
894 
895     k->pending = 0;
896 
897     sig = gdb_handlesig(cpu, sig, NULL, &k->info, sizeof(k->info));
898     if (!sig) {
899         sa = NULL;
900         handler = TARGET_SIG_IGN;
901     } else {
902         sa = &sigact_table[sig - 1];
903         handler = sa->_sa_handler;
904     }
905 
906     if (do_strace) {
907         print_taken_signal(sig, &k->info);
908     }
909 
910     if (handler == TARGET_SIG_DFL) {
911         /*
912          * default handler : ignore some signal. The other are job
913          * control or fatal.
914          */
915         if (sig == TARGET_SIGTSTP || sig == TARGET_SIGTTIN ||
916             sig == TARGET_SIGTTOU) {
917             kill(getpid(), SIGSTOP);
918         } else if (sig != TARGET_SIGCHLD && sig != TARGET_SIGURG &&
919                    sig != TARGET_SIGINFO && sig != TARGET_SIGWINCH &&
920                    sig != TARGET_SIGCONT) {
921             dump_core_and_abort(sig);
922         }
923     } else if (handler == TARGET_SIG_IGN) {
924         /* ignore sig */
925     } else if (handler == TARGET_SIG_ERR) {
926         dump_core_and_abort(sig);
927     } else {
928         /* compute the blocked signals during the handler execution */
929         sigset_t *blocked_set;
930 
931         target_to_host_sigset(&set, &sa->sa_mask);
932         /*
933          * SA_NODEFER indicates that the current signal should not be
934          * blocked during the handler.
935          */
936         if (!(sa->sa_flags & TARGET_SA_NODEFER)) {
937             sigaddset(&set, target_to_host_signal(sig));
938         }
939 
940         /*
941          * Save the previous blocked signal state to restore it at the
942          * end of the signal execution (see do_sigreturn).
943          */
944         host_to_target_sigset_internal(&target_old_set, &ts->signal_mask);
945 
946         blocked_set = ts->in_sigsuspend ?
947             &ts->sigsuspend_mask : &ts->signal_mask;
948         sigorset(&ts->signal_mask, blocked_set, &set);
949         ts->in_sigsuspend = false;
950         sigprocmask(SIG_SETMASK, &ts->signal_mask, NULL);
951 
952         /* XXX VM86 on x86 ??? */
953 
954         code = k->info.si_code; /* From host, so no si_type */
955         /* prepare the stack frame of the virtual CPU */
956         if (sa->sa_flags & TARGET_SA_SIGINFO) {
957             tswap_siginfo(&tinfo, &k->info);
958             setup_frame(sig, code, sa, &target_old_set, &tinfo, env);
959         } else {
960             setup_frame(sig, code, sa, &target_old_set, NULL, env);
961         }
962         if (sa->sa_flags & TARGET_SA_RESETHAND) {
963             sa->_sa_handler = TARGET_SIG_DFL;
964         }
965     }
966 }
967 
968 void process_pending_signals(CPUArchState *env)
969 {
970     CPUState *cpu = env_cpu(env);
971     int sig;
972     sigset_t *blocked_set, set;
973     struct emulated_sigtable *k;
974     TaskState *ts = get_task_state(cpu);
975 
976     while (qatomic_read(&ts->signal_pending)) {
977         sigfillset(&set);
978         sigprocmask(SIG_SETMASK, &set, 0);
979 
980     restart_scan:
981         sig = ts->sync_signal.pending;
982         if (sig) {
983             /*
984              * Synchronous signals are forced by the emulated CPU in some way.
985              * If they are set to ignore, restore the default handler (see
986              * sys/kern_sig.c trapsignal() and execsigs() for this behavior)
987              * though maybe this is done only when forcing exit for non SIGCHLD.
988              */
989             if (sigismember(&ts->signal_mask, target_to_host_signal(sig)) ||
990                 sigact_table[sig - 1]._sa_handler == TARGET_SIG_IGN) {
991                 sigdelset(&ts->signal_mask, target_to_host_signal(sig));
992                 sigact_table[sig - 1]._sa_handler = TARGET_SIG_DFL;
993             }
994             handle_pending_signal(env, sig, &ts->sync_signal);
995         }
996 
997         k = ts->sigtab;
998         for (sig = 1; sig <= TARGET_NSIG; sig++, k++) {
999             blocked_set = ts->in_sigsuspend ?
1000                 &ts->sigsuspend_mask : &ts->signal_mask;
1001             if (k->pending &&
1002                 !sigismember(blocked_set, target_to_host_signal(sig))) {
1003                 handle_pending_signal(env, sig, k);
1004                 /*
1005                  * Restart scan from the beginning, as handle_pending_signal
1006                  * might have resulted in a new synchronous signal (eg SIGSEGV).
1007                  */
1008                 goto restart_scan;
1009             }
1010         }
1011 
1012         /*
1013          * Unblock signals and check one more time. Unblocking signals may cause
1014          * us to take another host signal, which will set signal_pending again.
1015          */
1016         qatomic_set(&ts->signal_pending, 0);
1017         ts->in_sigsuspend = false;
1018         set = ts->signal_mask;
1019         sigdelset(&set, SIGSEGV);
1020         sigdelset(&set, SIGBUS);
1021         sigprocmask(SIG_SETMASK, &set, 0);
1022     }
1023     ts->in_sigsuspend = false;
1024 }
1025 
1026 void cpu_loop_exit_sigsegv(CPUState *cpu, target_ulong addr,
1027                            MMUAccessType access_type, bool maperr, uintptr_t ra)
1028 {
1029     const TCGCPUOps *tcg_ops = CPU_GET_CLASS(cpu)->tcg_ops;
1030 
1031     if (tcg_ops->record_sigsegv) {
1032         tcg_ops->record_sigsegv(cpu, addr, access_type, maperr, ra);
1033     }
1034 
1035     force_sig_fault(TARGET_SIGSEGV,
1036                     maperr ? TARGET_SEGV_MAPERR : TARGET_SEGV_ACCERR,
1037                     addr);
1038     cpu->exception_index = EXCP_INTERRUPT;
1039     cpu_loop_exit_restore(cpu, ra);
1040 }
1041 
1042 void cpu_loop_exit_sigbus(CPUState *cpu, target_ulong addr,
1043                           MMUAccessType access_type, uintptr_t ra)
1044 {
1045     const TCGCPUOps *tcg_ops = CPU_GET_CLASS(cpu)->tcg_ops;
1046 
1047     if (tcg_ops->record_sigbus) {
1048         tcg_ops->record_sigbus(cpu, addr, access_type, ra);
1049     }
1050 
1051     force_sig_fault(TARGET_SIGBUS, TARGET_BUS_ADRALN, addr);
1052     cpu->exception_index = EXCP_INTERRUPT;
1053     cpu_loop_exit_restore(cpu, ra);
1054 }
1055