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