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