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