xref: /qemu/linux-user/signal.c (revision 824f4bac)
1 /*
2  *  Emulation of Linux signals
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 #include "qemu/osdep.h"
20 #include "qemu/bitops.h"
21 #include <sys/ucontext.h>
22 #include <sys/resource.h>
23 
24 #include "qemu.h"
25 #include "trace.h"
26 #include "signal-common.h"
27 
28 static struct target_sigaction sigact_table[TARGET_NSIG];
29 
30 static void host_signal_handler(int host_signum, siginfo_t *info,
31                                 void *puc);
32 
33 
34 /*
35  * System includes define _NSIG as SIGRTMAX + 1,
36  * but qemu (like the kernel) defines TARGET_NSIG as TARGET_SIGRTMAX
37  * and the first signal is SIGHUP defined as 1
38  * Signal number 0 is reserved for use as kill(pid, 0), to test whether
39  * a process exists without sending it a signal.
40  */
41 QEMU_BUILD_BUG_ON(__SIGRTMAX + 1 != _NSIG);
42 static uint8_t host_to_target_signal_table[_NSIG] = {
43     [SIGHUP] = TARGET_SIGHUP,
44     [SIGINT] = TARGET_SIGINT,
45     [SIGQUIT] = TARGET_SIGQUIT,
46     [SIGILL] = TARGET_SIGILL,
47     [SIGTRAP] = TARGET_SIGTRAP,
48     [SIGABRT] = TARGET_SIGABRT,
49 /*    [SIGIOT] = TARGET_SIGIOT,*/
50     [SIGBUS] = TARGET_SIGBUS,
51     [SIGFPE] = TARGET_SIGFPE,
52     [SIGKILL] = TARGET_SIGKILL,
53     [SIGUSR1] = TARGET_SIGUSR1,
54     [SIGSEGV] = TARGET_SIGSEGV,
55     [SIGUSR2] = TARGET_SIGUSR2,
56     [SIGPIPE] = TARGET_SIGPIPE,
57     [SIGALRM] = TARGET_SIGALRM,
58     [SIGTERM] = TARGET_SIGTERM,
59 #ifdef SIGSTKFLT
60     [SIGSTKFLT] = TARGET_SIGSTKFLT,
61 #endif
62     [SIGCHLD] = TARGET_SIGCHLD,
63     [SIGCONT] = TARGET_SIGCONT,
64     [SIGSTOP] = TARGET_SIGSTOP,
65     [SIGTSTP] = TARGET_SIGTSTP,
66     [SIGTTIN] = TARGET_SIGTTIN,
67     [SIGTTOU] = TARGET_SIGTTOU,
68     [SIGURG] = TARGET_SIGURG,
69     [SIGXCPU] = TARGET_SIGXCPU,
70     [SIGXFSZ] = TARGET_SIGXFSZ,
71     [SIGVTALRM] = TARGET_SIGVTALRM,
72     [SIGPROF] = TARGET_SIGPROF,
73     [SIGWINCH] = TARGET_SIGWINCH,
74     [SIGIO] = TARGET_SIGIO,
75     [SIGPWR] = TARGET_SIGPWR,
76     [SIGSYS] = TARGET_SIGSYS,
77     /* next signals stay the same */
78 };
79 
80 static uint8_t target_to_host_signal_table[TARGET_NSIG + 1];
81 
82 /* valid sig is between 1 and _NSIG - 1 */
83 int host_to_target_signal(int sig)
84 {
85     if (sig < 1 || sig >= _NSIG) {
86         return sig;
87     }
88     return host_to_target_signal_table[sig];
89 }
90 
91 /* valid sig is between 1 and TARGET_NSIG */
92 int target_to_host_signal(int sig)
93 {
94     if (sig < 1 || sig > TARGET_NSIG) {
95         return sig;
96     }
97     return target_to_host_signal_table[sig];
98 }
99 
100 static inline void target_sigaddset(target_sigset_t *set, int signum)
101 {
102     signum--;
103     abi_ulong mask = (abi_ulong)1 << (signum % TARGET_NSIG_BPW);
104     set->sig[signum / TARGET_NSIG_BPW] |= mask;
105 }
106 
107 static inline int target_sigismember(const target_sigset_t *set, int signum)
108 {
109     signum--;
110     abi_ulong mask = (abi_ulong)1 << (signum % TARGET_NSIG_BPW);
111     return ((set->sig[signum / TARGET_NSIG_BPW] & mask) != 0);
112 }
113 
114 void host_to_target_sigset_internal(target_sigset_t *d,
115                                     const sigset_t *s)
116 {
117     int host_sig, target_sig;
118     target_sigemptyset(d);
119     for (host_sig = 1; host_sig < _NSIG; host_sig++) {
120         target_sig = host_to_target_signal(host_sig);
121         if (target_sig < 1 || target_sig > TARGET_NSIG) {
122             continue;
123         }
124         if (sigismember(s, host_sig)) {
125             target_sigaddset(d, target_sig);
126         }
127     }
128 }
129 
130 void host_to_target_sigset(target_sigset_t *d, const sigset_t *s)
131 {
132     target_sigset_t d1;
133     int i;
134 
135     host_to_target_sigset_internal(&d1, s);
136     for(i = 0;i < TARGET_NSIG_WORDS; i++)
137         d->sig[i] = tswapal(d1.sig[i]);
138 }
139 
140 void target_to_host_sigset_internal(sigset_t *d,
141                                     const target_sigset_t *s)
142 {
143     int host_sig, target_sig;
144     sigemptyset(d);
145     for (target_sig = 1; target_sig <= TARGET_NSIG; target_sig++) {
146         host_sig = target_to_host_signal(target_sig);
147         if (host_sig < 1 || host_sig >= _NSIG) {
148             continue;
149         }
150         if (target_sigismember(s, target_sig)) {
151             sigaddset(d, host_sig);
152         }
153     }
154 }
155 
156 void target_to_host_sigset(sigset_t *d, const target_sigset_t *s)
157 {
158     target_sigset_t s1;
159     int i;
160 
161     for(i = 0;i < TARGET_NSIG_WORDS; i++)
162         s1.sig[i] = tswapal(s->sig[i]);
163     target_to_host_sigset_internal(d, &s1);
164 }
165 
166 void host_to_target_old_sigset(abi_ulong *old_sigset,
167                                const sigset_t *sigset)
168 {
169     target_sigset_t d;
170     host_to_target_sigset(&d, sigset);
171     *old_sigset = d.sig[0];
172 }
173 
174 void target_to_host_old_sigset(sigset_t *sigset,
175                                const abi_ulong *old_sigset)
176 {
177     target_sigset_t d;
178     int i;
179 
180     d.sig[0] = *old_sigset;
181     for(i = 1;i < TARGET_NSIG_WORDS; i++)
182         d.sig[i] = 0;
183     target_to_host_sigset(sigset, &d);
184 }
185 
186 int block_signals(void)
187 {
188     TaskState *ts = (TaskState *)thread_cpu->opaque;
189     sigset_t set;
190 
191     /* It's OK to block everything including SIGSEGV, because we won't
192      * run any further guest code before unblocking signals in
193      * process_pending_signals().
194      */
195     sigfillset(&set);
196     sigprocmask(SIG_SETMASK, &set, 0);
197 
198     return qatomic_xchg(&ts->signal_pending, 1);
199 }
200 
201 /* Wrapper for sigprocmask function
202  * Emulates a sigprocmask in a safe way for the guest. Note that set and oldset
203  * are host signal set, not guest ones. Returns -TARGET_ERESTARTSYS if
204  * a signal was already pending and the syscall must be restarted, or
205  * 0 on success.
206  * If set is NULL, this is guaranteed not to fail.
207  */
208 int do_sigprocmask(int how, const sigset_t *set, sigset_t *oldset)
209 {
210     TaskState *ts = (TaskState *)thread_cpu->opaque;
211 
212     if (oldset) {
213         *oldset = ts->signal_mask;
214     }
215 
216     if (set) {
217         int i;
218 
219         if (block_signals()) {
220             return -TARGET_ERESTARTSYS;
221         }
222 
223         switch (how) {
224         case SIG_BLOCK:
225             sigorset(&ts->signal_mask, &ts->signal_mask, set);
226             break;
227         case SIG_UNBLOCK:
228             for (i = 1; i <= NSIG; ++i) {
229                 if (sigismember(set, i)) {
230                     sigdelset(&ts->signal_mask, i);
231                 }
232             }
233             break;
234         case SIG_SETMASK:
235             ts->signal_mask = *set;
236             break;
237         default:
238             g_assert_not_reached();
239         }
240 
241         /* Silently ignore attempts to change blocking status of KILL or STOP */
242         sigdelset(&ts->signal_mask, SIGKILL);
243         sigdelset(&ts->signal_mask, SIGSTOP);
244     }
245     return 0;
246 }
247 
248 #if !defined(TARGET_NIOS2)
249 /* Just set the guest's signal mask to the specified value; the
250  * caller is assumed to have called block_signals() already.
251  */
252 void set_sigmask(const sigset_t *set)
253 {
254     TaskState *ts = (TaskState *)thread_cpu->opaque;
255 
256     ts->signal_mask = *set;
257 }
258 #endif
259 
260 /* sigaltstack management */
261 
262 int on_sig_stack(unsigned long sp)
263 {
264     TaskState *ts = (TaskState *)thread_cpu->opaque;
265 
266     return (sp - ts->sigaltstack_used.ss_sp
267             < ts->sigaltstack_used.ss_size);
268 }
269 
270 int sas_ss_flags(unsigned long sp)
271 {
272     TaskState *ts = (TaskState *)thread_cpu->opaque;
273 
274     return (ts->sigaltstack_used.ss_size == 0 ? SS_DISABLE
275             : on_sig_stack(sp) ? SS_ONSTACK : 0);
276 }
277 
278 abi_ulong target_sigsp(abi_ulong sp, struct target_sigaction *ka)
279 {
280     /*
281      * This is the X/Open sanctioned signal stack switching.
282      */
283     TaskState *ts = (TaskState *)thread_cpu->opaque;
284 
285     if ((ka->sa_flags & TARGET_SA_ONSTACK) && !sas_ss_flags(sp)) {
286         return ts->sigaltstack_used.ss_sp + ts->sigaltstack_used.ss_size;
287     }
288     return sp;
289 }
290 
291 void target_save_altstack(target_stack_t *uss, CPUArchState *env)
292 {
293     TaskState *ts = (TaskState *)thread_cpu->opaque;
294 
295     __put_user(ts->sigaltstack_used.ss_sp, &uss->ss_sp);
296     __put_user(sas_ss_flags(get_sp_from_cpustate(env)), &uss->ss_flags);
297     __put_user(ts->sigaltstack_used.ss_size, &uss->ss_size);
298 }
299 
300 abi_long target_restore_altstack(target_stack_t *uss, CPUArchState *env)
301 {
302     TaskState *ts = (TaskState *)thread_cpu->opaque;
303     size_t minstacksize = TARGET_MINSIGSTKSZ;
304     target_stack_t ss;
305 
306 #if defined(TARGET_PPC64)
307     /* ELF V2 for PPC64 has a 4K minimum stack size for signal handlers */
308     struct image_info *image = ts->info;
309     if (get_ppc64_abi(image) > 1) {
310         minstacksize = 4096;
311     }
312 #endif
313 
314     __get_user(ss.ss_sp, &uss->ss_sp);
315     __get_user(ss.ss_size, &uss->ss_size);
316     __get_user(ss.ss_flags, &uss->ss_flags);
317 
318     if (on_sig_stack(get_sp_from_cpustate(env))) {
319         return -TARGET_EPERM;
320     }
321 
322     switch (ss.ss_flags) {
323     default:
324         return -TARGET_EINVAL;
325 
326     case TARGET_SS_DISABLE:
327         ss.ss_size = 0;
328         ss.ss_sp = 0;
329         break;
330 
331     case TARGET_SS_ONSTACK:
332     case 0:
333         if (ss.ss_size < minstacksize) {
334             return -TARGET_ENOMEM;
335         }
336         break;
337     }
338 
339     ts->sigaltstack_used.ss_sp = ss.ss_sp;
340     ts->sigaltstack_used.ss_size = ss.ss_size;
341     return 0;
342 }
343 
344 /* siginfo conversion */
345 
346 static inline void host_to_target_siginfo_noswap(target_siginfo_t *tinfo,
347                                                  const siginfo_t *info)
348 {
349     int sig = host_to_target_signal(info->si_signo);
350     int si_code = info->si_code;
351     int si_type;
352     tinfo->si_signo = sig;
353     tinfo->si_errno = 0;
354     tinfo->si_code = info->si_code;
355 
356     /* This memset serves two purposes:
357      * (1) ensure we don't leak random junk to the guest later
358      * (2) placate false positives from gcc about fields
359      *     being used uninitialized if it chooses to inline both this
360      *     function and tswap_siginfo() into host_to_target_siginfo().
361      */
362     memset(tinfo->_sifields._pad, 0, sizeof(tinfo->_sifields._pad));
363 
364     /* This is awkward, because we have to use a combination of
365      * the si_code and si_signo to figure out which of the union's
366      * members are valid. (Within the host kernel it is always possible
367      * to tell, but the kernel carefully avoids giving userspace the
368      * high 16 bits of si_code, so we don't have the information to
369      * do this the easy way...) We therefore make our best guess,
370      * bearing in mind that a guest can spoof most of the si_codes
371      * via rt_sigqueueinfo() if it likes.
372      *
373      * Once we have made our guess, we record it in the top 16 bits of
374      * the si_code, so that tswap_siginfo() later can use it.
375      * tswap_siginfo() will strip these top bits out before writing
376      * si_code to the guest (sign-extending the lower bits).
377      */
378 
379     switch (si_code) {
380     case SI_USER:
381     case SI_TKILL:
382     case SI_KERNEL:
383         /* Sent via kill(), tkill() or tgkill(), or direct from the kernel.
384          * These are the only unspoofable si_code values.
385          */
386         tinfo->_sifields._kill._pid = info->si_pid;
387         tinfo->_sifields._kill._uid = info->si_uid;
388         si_type = QEMU_SI_KILL;
389         break;
390     default:
391         /* Everything else is spoofable. Make best guess based on signal */
392         switch (sig) {
393         case TARGET_SIGCHLD:
394             tinfo->_sifields._sigchld._pid = info->si_pid;
395             tinfo->_sifields._sigchld._uid = info->si_uid;
396             tinfo->_sifields._sigchld._status = info->si_status;
397             tinfo->_sifields._sigchld._utime = info->si_utime;
398             tinfo->_sifields._sigchld._stime = info->si_stime;
399             si_type = QEMU_SI_CHLD;
400             break;
401         case TARGET_SIGIO:
402             tinfo->_sifields._sigpoll._band = info->si_band;
403             tinfo->_sifields._sigpoll._fd = info->si_fd;
404             si_type = QEMU_SI_POLL;
405             break;
406         default:
407             /* Assume a sigqueue()/mq_notify()/rt_sigqueueinfo() source. */
408             tinfo->_sifields._rt._pid = info->si_pid;
409             tinfo->_sifields._rt._uid = info->si_uid;
410             /* XXX: potential problem if 64 bit */
411             tinfo->_sifields._rt._sigval.sival_ptr
412                 = (abi_ulong)(unsigned long)info->si_value.sival_ptr;
413             si_type = QEMU_SI_RT;
414             break;
415         }
416         break;
417     }
418 
419     tinfo->si_code = deposit32(si_code, 16, 16, si_type);
420 }
421 
422 void tswap_siginfo(target_siginfo_t *tinfo,
423                    const target_siginfo_t *info)
424 {
425     int si_type = extract32(info->si_code, 16, 16);
426     int si_code = sextract32(info->si_code, 0, 16);
427 
428     __put_user(info->si_signo, &tinfo->si_signo);
429     __put_user(info->si_errno, &tinfo->si_errno);
430     __put_user(si_code, &tinfo->si_code);
431 
432     /* We can use our internal marker of which fields in the structure
433      * are valid, rather than duplicating the guesswork of
434      * host_to_target_siginfo_noswap() here.
435      */
436     switch (si_type) {
437     case QEMU_SI_KILL:
438         __put_user(info->_sifields._kill._pid, &tinfo->_sifields._kill._pid);
439         __put_user(info->_sifields._kill._uid, &tinfo->_sifields._kill._uid);
440         break;
441     case QEMU_SI_TIMER:
442         __put_user(info->_sifields._timer._timer1,
443                    &tinfo->_sifields._timer._timer1);
444         __put_user(info->_sifields._timer._timer2,
445                    &tinfo->_sifields._timer._timer2);
446         break;
447     case QEMU_SI_POLL:
448         __put_user(info->_sifields._sigpoll._band,
449                    &tinfo->_sifields._sigpoll._band);
450         __put_user(info->_sifields._sigpoll._fd,
451                    &tinfo->_sifields._sigpoll._fd);
452         break;
453     case QEMU_SI_FAULT:
454         __put_user(info->_sifields._sigfault._addr,
455                    &tinfo->_sifields._sigfault._addr);
456         break;
457     case QEMU_SI_CHLD:
458         __put_user(info->_sifields._sigchld._pid,
459                    &tinfo->_sifields._sigchld._pid);
460         __put_user(info->_sifields._sigchld._uid,
461                    &tinfo->_sifields._sigchld._uid);
462         __put_user(info->_sifields._sigchld._status,
463                    &tinfo->_sifields._sigchld._status);
464         __put_user(info->_sifields._sigchld._utime,
465                    &tinfo->_sifields._sigchld._utime);
466         __put_user(info->_sifields._sigchld._stime,
467                    &tinfo->_sifields._sigchld._stime);
468         break;
469     case QEMU_SI_RT:
470         __put_user(info->_sifields._rt._pid, &tinfo->_sifields._rt._pid);
471         __put_user(info->_sifields._rt._uid, &tinfo->_sifields._rt._uid);
472         __put_user(info->_sifields._rt._sigval.sival_ptr,
473                    &tinfo->_sifields._rt._sigval.sival_ptr);
474         break;
475     default:
476         g_assert_not_reached();
477     }
478 }
479 
480 void host_to_target_siginfo(target_siginfo_t *tinfo, const siginfo_t *info)
481 {
482     target_siginfo_t tgt_tmp;
483     host_to_target_siginfo_noswap(&tgt_tmp, info);
484     tswap_siginfo(tinfo, &tgt_tmp);
485 }
486 
487 /* XXX: we support only POSIX RT signals are used. */
488 /* XXX: find a solution for 64 bit (additional malloced data is needed) */
489 void target_to_host_siginfo(siginfo_t *info, const target_siginfo_t *tinfo)
490 {
491     /* This conversion is used only for the rt_sigqueueinfo syscall,
492      * and so we know that the _rt fields are the valid ones.
493      */
494     abi_ulong sival_ptr;
495 
496     __get_user(info->si_signo, &tinfo->si_signo);
497     __get_user(info->si_errno, &tinfo->si_errno);
498     __get_user(info->si_code, &tinfo->si_code);
499     __get_user(info->si_pid, &tinfo->_sifields._rt._pid);
500     __get_user(info->si_uid, &tinfo->_sifields._rt._uid);
501     __get_user(sival_ptr, &tinfo->_sifields._rt._sigval.sival_ptr);
502     info->si_value.sival_ptr = (void *)(long)sival_ptr;
503 }
504 
505 static int fatal_signal (int sig)
506 {
507     switch (sig) {
508     case TARGET_SIGCHLD:
509     case TARGET_SIGURG:
510     case TARGET_SIGWINCH:
511         /* Ignored by default.  */
512         return 0;
513     case TARGET_SIGCONT:
514     case TARGET_SIGSTOP:
515     case TARGET_SIGTSTP:
516     case TARGET_SIGTTIN:
517     case TARGET_SIGTTOU:
518         /* Job control signals.  */
519         return 0;
520     default:
521         return 1;
522     }
523 }
524 
525 /* returns 1 if given signal should dump core if not handled */
526 static int core_dump_signal(int sig)
527 {
528     switch (sig) {
529     case TARGET_SIGABRT:
530     case TARGET_SIGFPE:
531     case TARGET_SIGILL:
532     case TARGET_SIGQUIT:
533     case TARGET_SIGSEGV:
534     case TARGET_SIGTRAP:
535     case TARGET_SIGBUS:
536         return (1);
537     default:
538         return (0);
539     }
540 }
541 
542 static void signal_table_init(void)
543 {
544     int host_sig, target_sig, count;
545 
546     /*
547      * Signals are supported starting from TARGET_SIGRTMIN and going up
548      * until we run out of host realtime signals.
549      * glibc at least uses only the lower 2 rt signals and probably
550      * nobody's using the upper ones.
551      * it's why SIGRTMIN (34) is generally greater than __SIGRTMIN (32)
552      * To fix this properly we need to do manual signal delivery multiplexed
553      * over a single host signal.
554      * Attempts for configure "missing" signals via sigaction will be
555      * silently ignored.
556      */
557     for (host_sig = SIGRTMIN; host_sig <= SIGRTMAX; host_sig++) {
558         target_sig = host_sig - SIGRTMIN + TARGET_SIGRTMIN;
559         if (target_sig <= TARGET_NSIG) {
560             host_to_target_signal_table[host_sig] = target_sig;
561         }
562     }
563 
564     /* generate signal conversion tables */
565     for (target_sig = 1; target_sig <= TARGET_NSIG; target_sig++) {
566         target_to_host_signal_table[target_sig] = _NSIG; /* poison */
567     }
568     for (host_sig = 1; host_sig < _NSIG; host_sig++) {
569         if (host_to_target_signal_table[host_sig] == 0) {
570             host_to_target_signal_table[host_sig] = host_sig;
571         }
572         target_sig = host_to_target_signal_table[host_sig];
573         if (target_sig <= TARGET_NSIG) {
574             target_to_host_signal_table[target_sig] = host_sig;
575         }
576     }
577 
578     if (trace_event_get_state_backends(TRACE_SIGNAL_TABLE_INIT)) {
579         for (target_sig = 1, count = 0; target_sig <= TARGET_NSIG; target_sig++) {
580             if (target_to_host_signal_table[target_sig] == _NSIG) {
581                 count++;
582             }
583         }
584         trace_signal_table_init(count);
585     }
586 }
587 
588 void signal_init(void)
589 {
590     TaskState *ts = (TaskState *)thread_cpu->opaque;
591     struct sigaction act;
592     struct sigaction oact;
593     int i;
594     int host_sig;
595 
596     /* initialize signal conversion tables */
597     signal_table_init();
598 
599     /* Set the signal mask from the host mask. */
600     sigprocmask(0, 0, &ts->signal_mask);
601 
602     sigfillset(&act.sa_mask);
603     act.sa_flags = SA_SIGINFO;
604     act.sa_sigaction = host_signal_handler;
605     for(i = 1; i <= TARGET_NSIG; i++) {
606 #ifdef CONFIG_GPROF
607         if (i == TARGET_SIGPROF) {
608             continue;
609         }
610 #endif
611         host_sig = target_to_host_signal(i);
612         sigaction(host_sig, NULL, &oact);
613         if (oact.sa_sigaction == (void *)SIG_IGN) {
614             sigact_table[i - 1]._sa_handler = TARGET_SIG_IGN;
615         } else if (oact.sa_sigaction == (void *)SIG_DFL) {
616             sigact_table[i - 1]._sa_handler = TARGET_SIG_DFL;
617         }
618         /* If there's already a handler installed then something has
619            gone horribly wrong, so don't even try to handle that case.  */
620         /* Install some handlers for our own use.  We need at least
621            SIGSEGV and SIGBUS, to detect exceptions.  We can not just
622            trap all signals because it affects syscall interrupt
623            behavior.  But do trap all default-fatal signals.  */
624         if (fatal_signal (i))
625             sigaction(host_sig, &act, NULL);
626     }
627 }
628 
629 /* Force a synchronously taken signal. The kernel force_sig() function
630  * also forces the signal to "not blocked, not ignored", but for QEMU
631  * that work is done in process_pending_signals().
632  */
633 void force_sig(int sig)
634 {
635     CPUState *cpu = thread_cpu;
636     CPUArchState *env = cpu->env_ptr;
637     target_siginfo_t info;
638 
639     info.si_signo = sig;
640     info.si_errno = 0;
641     info.si_code = TARGET_SI_KERNEL;
642     info._sifields._kill._pid = 0;
643     info._sifields._kill._uid = 0;
644     queue_signal(env, info.si_signo, QEMU_SI_KILL, &info);
645 }
646 
647 /* Force a SIGSEGV if we couldn't write to memory trying to set
648  * up the signal frame. oldsig is the signal we were trying to handle
649  * at the point of failure.
650  */
651 #if !defined(TARGET_RISCV)
652 void force_sigsegv(int oldsig)
653 {
654     if (oldsig == SIGSEGV) {
655         /* Make sure we don't try to deliver the signal again; this will
656          * end up with handle_pending_signal() calling dump_core_and_abort().
657          */
658         sigact_table[oldsig - 1]._sa_handler = TARGET_SIG_DFL;
659     }
660     force_sig(TARGET_SIGSEGV);
661 }
662 
663 #endif
664 
665 /* abort execution with signal */
666 static void QEMU_NORETURN dump_core_and_abort(int target_sig)
667 {
668     CPUState *cpu = thread_cpu;
669     CPUArchState *env = cpu->env_ptr;
670     TaskState *ts = (TaskState *)cpu->opaque;
671     int host_sig, core_dumped = 0;
672     struct sigaction act;
673 
674     host_sig = target_to_host_signal(target_sig);
675     trace_user_force_sig(env, target_sig, host_sig);
676     gdb_signalled(env, target_sig);
677 
678     /* dump core if supported by target binary format */
679     if (core_dump_signal(target_sig) && (ts->bprm->core_dump != NULL)) {
680         stop_all_tasks();
681         core_dumped =
682             ((*ts->bprm->core_dump)(target_sig, env) == 0);
683     }
684     if (core_dumped) {
685         /* we already dumped the core of target process, we don't want
686          * a coredump of qemu itself */
687         struct rlimit nodump;
688         getrlimit(RLIMIT_CORE, &nodump);
689         nodump.rlim_cur=0;
690         setrlimit(RLIMIT_CORE, &nodump);
691         (void) fprintf(stderr, "qemu: uncaught target signal %d (%s) - %s\n",
692             target_sig, strsignal(host_sig), "core dumped" );
693     }
694 
695     /* The proper exit code for dying from an uncaught signal is
696      * -<signal>.  The kernel doesn't allow exit() or _exit() to pass
697      * a negative value.  To get the proper exit code we need to
698      * actually die from an uncaught signal.  Here the default signal
699      * handler is installed, we send ourself a signal and we wait for
700      * it to arrive. */
701     sigfillset(&act.sa_mask);
702     act.sa_handler = SIG_DFL;
703     act.sa_flags = 0;
704     sigaction(host_sig, &act, NULL);
705 
706     /* For some reason raise(host_sig) doesn't send the signal when
707      * statically linked on x86-64. */
708     kill(getpid(), host_sig);
709 
710     /* Make sure the signal isn't masked (just reuse the mask inside
711     of act) */
712     sigdelset(&act.sa_mask, host_sig);
713     sigsuspend(&act.sa_mask);
714 
715     /* unreachable */
716     abort();
717 }
718 
719 /* queue a signal so that it will be send to the virtual CPU as soon
720    as possible */
721 int queue_signal(CPUArchState *env, int sig, int si_type,
722                  target_siginfo_t *info)
723 {
724     CPUState *cpu = env_cpu(env);
725     TaskState *ts = cpu->opaque;
726 
727     trace_user_queue_signal(env, sig);
728 
729     info->si_code = deposit32(info->si_code, 16, 16, si_type);
730 
731     ts->sync_signal.info = *info;
732     ts->sync_signal.pending = sig;
733     /* signal that a new signal is pending */
734     qatomic_set(&ts->signal_pending, 1);
735     return 1; /* indicates that the signal was queued */
736 }
737 
738 #ifndef HAVE_SAFE_SYSCALL
739 static inline void rewind_if_in_safe_syscall(void *puc)
740 {
741     /* Default version: never rewind */
742 }
743 #endif
744 
745 static void host_signal_handler(int host_signum, siginfo_t *info,
746                                 void *puc)
747 {
748     CPUArchState *env = thread_cpu->env_ptr;
749     CPUState *cpu = env_cpu(env);
750     TaskState *ts = cpu->opaque;
751 
752     int sig;
753     target_siginfo_t tinfo;
754     ucontext_t *uc = puc;
755     struct emulated_sigtable *k;
756 
757     /* the CPU emulator uses some host signals to detect exceptions,
758        we forward to it some signals */
759     if ((host_signum == SIGSEGV || host_signum == SIGBUS)
760         && info->si_code > 0) {
761         if (cpu_signal_handler(host_signum, info, puc))
762             return;
763     }
764 
765     /* get target signal number */
766     sig = host_to_target_signal(host_signum);
767     if (sig < 1 || sig > TARGET_NSIG)
768         return;
769     trace_user_host_signal(env, host_signum, sig);
770 
771     rewind_if_in_safe_syscall(puc);
772 
773     host_to_target_siginfo_noswap(&tinfo, info);
774     k = &ts->sigtab[sig - 1];
775     k->info = tinfo;
776     k->pending = sig;
777     ts->signal_pending = 1;
778 
779     /* Block host signals until target signal handler entered. We
780      * can't block SIGSEGV or SIGBUS while we're executing guest
781      * code in case the guest code provokes one in the window between
782      * now and it getting out to the main loop. Signals will be
783      * unblocked again in process_pending_signals().
784      *
785      * WARNING: we cannot use sigfillset() here because the uc_sigmask
786      * field is a kernel sigset_t, which is much smaller than the
787      * libc sigset_t which sigfillset() operates on. Using sigfillset()
788      * would write 0xff bytes off the end of the structure and trash
789      * data on the struct.
790      * We can't use sizeof(uc->uc_sigmask) either, because the libc
791      * headers define the struct field with the wrong (too large) type.
792      */
793     memset(&uc->uc_sigmask, 0xff, SIGSET_T_SIZE);
794     sigdelset(&uc->uc_sigmask, SIGSEGV);
795     sigdelset(&uc->uc_sigmask, SIGBUS);
796 
797     /* interrupt the virtual CPU as soon as possible */
798     cpu_exit(thread_cpu);
799 }
800 
801 /* do_sigaltstack() returns target values and errnos. */
802 /* compare linux/kernel/signal.c:do_sigaltstack() */
803 abi_long do_sigaltstack(abi_ulong uss_addr, abi_ulong uoss_addr,
804                         CPUArchState *env)
805 {
806     target_stack_t oss, *uoss = NULL;
807     abi_long ret = -TARGET_EFAULT;
808 
809     if (uoss_addr) {
810         /* Verify writability now, but do not alter user memory yet. */
811         if (!lock_user_struct(VERIFY_WRITE, uoss, uoss_addr, 0)) {
812             goto out;
813         }
814         target_save_altstack(&oss, env);
815     }
816 
817     if (uss_addr) {
818         target_stack_t *uss;
819 
820         if (!lock_user_struct(VERIFY_READ, uss, uss_addr, 1)) {
821             goto out;
822         }
823         ret = target_restore_altstack(uss, env);
824         if (ret) {
825             goto out;
826         }
827     }
828 
829     if (uoss_addr) {
830         memcpy(uoss, &oss, sizeof(oss));
831         unlock_user_struct(uoss, uoss_addr, 1);
832         uoss = NULL;
833     }
834     ret = 0;
835 
836  out:
837     if (uoss) {
838         unlock_user_struct(uoss, uoss_addr, 0);
839     }
840     return ret;
841 }
842 
843 /* do_sigaction() return target values and host errnos */
844 int do_sigaction(int sig, const struct target_sigaction *act,
845                  struct target_sigaction *oact, abi_ulong ka_restorer)
846 {
847     struct target_sigaction *k;
848     struct sigaction act1;
849     int host_sig;
850     int ret = 0;
851 
852     trace_signal_do_sigaction_guest(sig, TARGET_NSIG);
853 
854     if (sig < 1 || sig > TARGET_NSIG || sig == TARGET_SIGKILL || sig == TARGET_SIGSTOP) {
855         return -TARGET_EINVAL;
856     }
857 
858     if (block_signals()) {
859         return -TARGET_ERESTARTSYS;
860     }
861 
862     k = &sigact_table[sig - 1];
863     if (oact) {
864         __put_user(k->_sa_handler, &oact->_sa_handler);
865         __put_user(k->sa_flags, &oact->sa_flags);
866 #ifdef TARGET_ARCH_HAS_SA_RESTORER
867         __put_user(k->sa_restorer, &oact->sa_restorer);
868 #endif
869         /* Not swapped.  */
870         oact->sa_mask = k->sa_mask;
871     }
872     if (act) {
873         /* FIXME: This is not threadsafe.  */
874         __get_user(k->_sa_handler, &act->_sa_handler);
875         __get_user(k->sa_flags, &act->sa_flags);
876 #ifdef TARGET_ARCH_HAS_SA_RESTORER
877         __get_user(k->sa_restorer, &act->sa_restorer);
878 #endif
879 #ifdef TARGET_ARCH_HAS_KA_RESTORER
880         k->ka_restorer = ka_restorer;
881 #endif
882         /* To be swapped in target_to_host_sigset.  */
883         k->sa_mask = act->sa_mask;
884 
885         /* we update the host linux signal state */
886         host_sig = target_to_host_signal(sig);
887         trace_signal_do_sigaction_host(host_sig, TARGET_NSIG);
888         if (host_sig > SIGRTMAX) {
889             /* we don't have enough host signals to map all target signals */
890             qemu_log_mask(LOG_UNIMP, "Unsupported target signal #%d, ignored\n",
891                           sig);
892             /*
893              * we don't return an error here because some programs try to
894              * register an handler for all possible rt signals even if they
895              * don't need it.
896              * An error here can abort them whereas there can be no problem
897              * to not have the signal available later.
898              * This is the case for golang,
899              *   See https://github.com/golang/go/issues/33746
900              * So we silently ignore the error.
901              */
902             return 0;
903         }
904         if (host_sig != SIGSEGV && host_sig != SIGBUS) {
905             sigfillset(&act1.sa_mask);
906             act1.sa_flags = SA_SIGINFO;
907             if (k->sa_flags & TARGET_SA_RESTART)
908                 act1.sa_flags |= SA_RESTART;
909             /* NOTE: it is important to update the host kernel signal
910                ignore state to avoid getting unexpected interrupted
911                syscalls */
912             if (k->_sa_handler == TARGET_SIG_IGN) {
913                 act1.sa_sigaction = (void *)SIG_IGN;
914             } else if (k->_sa_handler == TARGET_SIG_DFL) {
915                 if (fatal_signal (sig))
916                     act1.sa_sigaction = host_signal_handler;
917                 else
918                     act1.sa_sigaction = (void *)SIG_DFL;
919             } else {
920                 act1.sa_sigaction = host_signal_handler;
921             }
922             ret = sigaction(host_sig, &act1, NULL);
923         }
924     }
925     return ret;
926 }
927 
928 static void handle_pending_signal(CPUArchState *cpu_env, int sig,
929                                   struct emulated_sigtable *k)
930 {
931     CPUState *cpu = env_cpu(cpu_env);
932     abi_ulong handler;
933     sigset_t set;
934     target_sigset_t target_old_set;
935     struct target_sigaction *sa;
936     TaskState *ts = cpu->opaque;
937 
938     trace_user_handle_signal(cpu_env, sig);
939     /* dequeue signal */
940     k->pending = 0;
941 
942     sig = gdb_handlesig(cpu, sig);
943     if (!sig) {
944         sa = NULL;
945         handler = TARGET_SIG_IGN;
946     } else {
947         sa = &sigact_table[sig - 1];
948         handler = sa->_sa_handler;
949     }
950 
951     if (unlikely(qemu_loglevel_mask(LOG_STRACE))) {
952         print_taken_signal(sig, &k->info);
953     }
954 
955     if (handler == TARGET_SIG_DFL) {
956         /* default handler : ignore some signal. The other are job control or fatal */
957         if (sig == TARGET_SIGTSTP || sig == TARGET_SIGTTIN || sig == TARGET_SIGTTOU) {
958             kill(getpid(),SIGSTOP);
959         } else if (sig != TARGET_SIGCHLD &&
960                    sig != TARGET_SIGURG &&
961                    sig != TARGET_SIGWINCH &&
962                    sig != TARGET_SIGCONT) {
963             dump_core_and_abort(sig);
964         }
965     } else if (handler == TARGET_SIG_IGN) {
966         /* ignore sig */
967     } else if (handler == TARGET_SIG_ERR) {
968         dump_core_and_abort(sig);
969     } else {
970         /* compute the blocked signals during the handler execution */
971         sigset_t *blocked_set;
972 
973         target_to_host_sigset(&set, &sa->sa_mask);
974         /* SA_NODEFER indicates that the current signal should not be
975            blocked during the handler */
976         if (!(sa->sa_flags & TARGET_SA_NODEFER))
977             sigaddset(&set, target_to_host_signal(sig));
978 
979         /* save the previous blocked signal state to restore it at the
980            end of the signal execution (see do_sigreturn) */
981         host_to_target_sigset_internal(&target_old_set, &ts->signal_mask);
982 
983         /* block signals in the handler */
984         blocked_set = ts->in_sigsuspend ?
985             &ts->sigsuspend_mask : &ts->signal_mask;
986         sigorset(&ts->signal_mask, blocked_set, &set);
987         ts->in_sigsuspend = 0;
988 
989         /* if the CPU is in VM86 mode, we restore the 32 bit values */
990 #if defined(TARGET_I386) && !defined(TARGET_X86_64)
991         {
992             CPUX86State *env = cpu_env;
993             if (env->eflags & VM_MASK)
994                 save_v86_state(env);
995         }
996 #endif
997         /* prepare the stack frame of the virtual CPU */
998 #if defined(TARGET_ARCH_HAS_SETUP_FRAME)
999         if (sa->sa_flags & TARGET_SA_SIGINFO) {
1000             setup_rt_frame(sig, sa, &k->info, &target_old_set, cpu_env);
1001         } else {
1002             setup_frame(sig, sa, &target_old_set, cpu_env);
1003         }
1004 #else
1005         /* These targets do not have traditional signals.  */
1006         setup_rt_frame(sig, sa, &k->info, &target_old_set, cpu_env);
1007 #endif
1008         if (sa->sa_flags & TARGET_SA_RESETHAND) {
1009             sa->_sa_handler = TARGET_SIG_DFL;
1010         }
1011     }
1012 }
1013 
1014 void process_pending_signals(CPUArchState *cpu_env)
1015 {
1016     CPUState *cpu = env_cpu(cpu_env);
1017     int sig;
1018     TaskState *ts = cpu->opaque;
1019     sigset_t set;
1020     sigset_t *blocked_set;
1021 
1022     while (qatomic_read(&ts->signal_pending)) {
1023         /* FIXME: This is not threadsafe.  */
1024         sigfillset(&set);
1025         sigprocmask(SIG_SETMASK, &set, 0);
1026 
1027     restart_scan:
1028         sig = ts->sync_signal.pending;
1029         if (sig) {
1030             /* Synchronous signals are forced,
1031              * see force_sig_info() and callers in Linux
1032              * Note that not all of our queue_signal() calls in QEMU correspond
1033              * to force_sig_info() calls in Linux (some are send_sig_info()).
1034              * However it seems like a kernel bug to me to allow the process
1035              * to block a synchronous signal since it could then just end up
1036              * looping round and round indefinitely.
1037              */
1038             if (sigismember(&ts->signal_mask, target_to_host_signal_table[sig])
1039                 || sigact_table[sig - 1]._sa_handler == TARGET_SIG_IGN) {
1040                 sigdelset(&ts->signal_mask, target_to_host_signal_table[sig]);
1041                 sigact_table[sig - 1]._sa_handler = TARGET_SIG_DFL;
1042             }
1043 
1044             handle_pending_signal(cpu_env, sig, &ts->sync_signal);
1045         }
1046 
1047         for (sig = 1; sig <= TARGET_NSIG; sig++) {
1048             blocked_set = ts->in_sigsuspend ?
1049                 &ts->sigsuspend_mask : &ts->signal_mask;
1050 
1051             if (ts->sigtab[sig - 1].pending &&
1052                 (!sigismember(blocked_set,
1053                               target_to_host_signal_table[sig]))) {
1054                 handle_pending_signal(cpu_env, sig, &ts->sigtab[sig - 1]);
1055                 /* Restart scan from the beginning, as handle_pending_signal
1056                  * might have resulted in a new synchronous signal (eg SIGSEGV).
1057                  */
1058                 goto restart_scan;
1059             }
1060         }
1061 
1062         /* if no signal is pending, unblock signals and recheck (the act
1063          * of unblocking might cause us to take another host signal which
1064          * will set signal_pending again).
1065          */
1066         qatomic_set(&ts->signal_pending, 0);
1067         ts->in_sigsuspend = 0;
1068         set = ts->signal_mask;
1069         sigdelset(&set, SIGSEGV);
1070         sigdelset(&set, SIGBUS);
1071         sigprocmask(SIG_SETMASK, &set, 0);
1072     }
1073     ts->in_sigsuspend = 0;
1074 }
1075