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