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