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