1.0.4.17: interrupt handler spring cleaning
[sbcl.git] / src / runtime / interrupt.c
1 /*
2  * interrupt-handling magic
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15
16
17 /* As far as I can tell, what's going on here is:
18  *
19  * In the case of most signals, when Lisp asks us to handle the
20  * signal, the outermost handler (the one actually passed to UNIX) is
21  * either interrupt_handle_now(..) or maybe_now_maybe_later(..).
22  * In that case, the Lisp-level handler is stored in interrupt_handlers[..]
23  * and interrupt_low_level_handlers[..] is cleared.
24  *
25  * However, some signals need special handling, e.g.
26  *
27  * o the SIGSEGV (for e.g. Linux) or SIGBUS (for e.g. FreeBSD) used by the
28  *   garbage collector to detect violations of write protection,
29  *   because some cases of such signals (e.g. GC-related violations of
30  *   write protection) are handled at C level and never passed on to
31  *   Lisp. For such signals, we still store any Lisp-level handler
32  *   in interrupt_handlers[..], but for the outermost handle we use
33  *   the value from interrupt_low_level_handlers[..], instead of the
34  *   ordinary interrupt_handle_now(..) or interrupt_handle_later(..).
35  *
36  * o the SIGTRAP (Linux/Alpha) which Lisp code uses to handle breakpoints,
37  *   pseudo-atomic sections, and some classes of error (e.g. "function
38  *   not defined").  This never goes anywhere near the Lisp handlers at all.
39  *   See runtime/alpha-arch.c and code/signal.lisp
40  *
41  * - WHN 20000728, dan 20010128 */
42
43 #include "sbcl.h"
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <signal.h>
49 #include <sys/types.h>
50 #ifndef LISP_FEATURE_WIN32
51 #include <sys/wait.h>
52 #endif
53 #include <errno.h>
54
55 #include "runtime.h"
56 #include "arch.h"
57 #include "os.h"
58 #include "interrupt.h"
59 #include "globals.h"
60 #include "lispregs.h"
61 #include "validate.h"
62 #include "gc.h"
63 #include "alloc.h"
64 #include "dynbind.h"
65 #include "interr.h"
66 #include "genesis/fdefn.h"
67 #include "genesis/simple-fun.h"
68 #include "genesis/cons.h"
69
70 static void run_deferred_handler(struct interrupt_data *data, void *v_context);
71 #ifndef LISP_FEATURE_WIN32
72 static void store_signal_data_for_later (struct interrupt_data *data,
73                                          void *handler, int signal,
74                                          siginfo_t *info,
75                                          os_context_t *context);
76
77 void
78 sigaddset_deferrable(sigset_t *s)
79 {
80     sigaddset(s, SIGHUP);
81     sigaddset(s, SIGINT);
82     sigaddset(s, SIGQUIT);
83     sigaddset(s, SIGPIPE);
84     sigaddset(s, SIGALRM);
85     sigaddset(s, SIGURG);
86     sigaddset(s, SIGTSTP);
87     sigaddset(s, SIGCHLD);
88     sigaddset(s, SIGIO);
89     sigaddset(s, SIGXCPU);
90     sigaddset(s, SIGXFSZ);
91     sigaddset(s, SIGVTALRM);
92     sigaddset(s, SIGPROF);
93     sigaddset(s, SIGWINCH);
94
95 #if !((defined(LISP_FEATURE_DARWIN) || defined(LISP_FEATURE_FREEBSD)) && defined(LISP_FEATURE_SB_THREAD))
96     sigaddset(s, SIGUSR1);
97     sigaddset(s, SIGUSR2);
98 #endif
99
100 #ifdef LISP_FEATURE_SB_THREAD
101     sigaddset(s, SIG_INTERRUPT_THREAD);
102 #endif
103 }
104
105 void
106 sigaddset_blockable(sigset_t *s)
107 {
108     sigaddset_deferrable(s);
109 #ifdef LISP_FEATURE_SB_THREAD
110 #ifdef SIG_RESUME_FROM_GC
111     sigaddset(s, SIG_RESUME_FROM_GC);
112 #endif
113     sigaddset(s, SIG_STOP_FOR_GC);
114 #endif
115 }
116
117 /* initialized in interrupt_init */
118 static sigset_t deferrable_sigset;
119 static sigset_t blockable_sigset;
120 #endif
121
122 void
123 check_blockables_blocked_or_lose(void)
124 {
125 #if !defined(LISP_FEATURE_WIN32)
126     /* Get the current sigmask, by blocking the empty set. */
127     sigset_t empty,current;
128     int i;
129     sigemptyset(&empty);
130     thread_sigmask(SIG_BLOCK, &empty, &current);
131     for(i = 1; i < NSIG; i++) {
132         if (sigismember(&blockable_sigset, i) && !sigismember(&current, i))
133             lose("blockable signal %d not blocked\n",i);
134     }
135 #endif
136 }
137
138 void
139 check_gc_signals_unblocked_or_lose(void)
140 {
141 #ifdef LISP_FEATURE_SB_THREAD
142 # if !defined(LISP_FEATURE_WIN32)
143     /* Get the current sigmask, by blocking the empty set. */
144     sigset_t empty,current;
145     sigemptyset(&empty);
146     thread_sigmask(SIG_BLOCK, &empty, &current);
147     if (sigismember(&current, SIG_STOP_FOR_GC))
148         lose("SIG_STOP_FOR_GC blocked in thread %p at a bad place\n",
149              arch_os_get_current_thread());
150 #  if defined(SIG_RESUME_FROM_GC)
151     if (sigismember(&current, SIG_RESUME_FROM_GC))
152         lose("SIG_RESUME_FROM_GC blocked in thread %p at a bad place\n",
153              arch_os_get_current_thread());
154 #  endif
155 # endif
156 #endif
157 }
158
159 void
160 unblock_gc_signals(void)
161 {
162 #ifdef LISP_FEATURE_SB_THREAD
163     sigset_t new;
164     sigemptyset(&new);
165 #if defined(SIG_RESUME_FROM_GC)
166     sigaddset(&new,SIG_RESUME_FROM_GC);
167 #endif
168     sigaddset(&new,SIG_STOP_FOR_GC);
169     thread_sigmask(SIG_UNBLOCK,&new,0);
170 #endif
171 }
172
173 inline static void
174 check_interrupts_enabled_or_lose(os_context_t *context)
175 {
176     struct thread *thread=arch_os_get_current_thread();
177     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
178         lose("interrupts not enabled\n");
179     if (
180 #ifdef FOREIGN_FUNCTION_CALL_FLAG
181         (!foreign_function_call_active) &&
182 #endif
183         arch_pseudo_atomic_atomic(context))
184         lose ("in pseudo atomic section\n");
185 }
186
187 /* When we catch an internal error, should we pass it back to Lisp to
188  * be handled in a high-level way? (Early in cold init, the answer is
189  * 'no', because Lisp is still too brain-dead to handle anything.
190  * After sufficient initialization has been completed, the answer
191  * becomes 'yes'.) */
192 boolean internal_errors_enabled = 0;
193
194 #ifndef LISP_FEATURE_WIN32
195 static void (*interrupt_low_level_handlers[NSIG]) (int, siginfo_t*, void*);
196 #endif
197 union interrupt_handler interrupt_handlers[NSIG];
198
199 /* At the toplevel repl we routinely call this function.  The signal
200  * mask ought to be clear anyway most of the time, but may be non-zero
201  * if we were interrupted e.g. while waiting for a queue.  */
202
203 void
204 reset_signal_mask(void)
205 {
206 #ifndef LISP_FEATURE_WIN32
207     sigset_t new;
208     sigemptyset(&new);
209     thread_sigmask(SIG_SETMASK,&new,0);
210 #endif
211 }
212
213 void
214 block_blockable_signals(void)
215 {
216 #ifndef LISP_FEATURE_WIN32
217     thread_sigmask(SIG_BLOCK, &blockable_sigset, 0);
218 #endif
219 }
220
221 void
222 block_deferrable_signals(void)
223 {
224 #ifndef LISP_FEATURE_WIN32
225     thread_sigmask(SIG_BLOCK, &deferrable_sigset, 0);
226 #endif
227 }
228
229 \f
230 /*
231  * utility routines used by various signal handlers
232  */
233
234 static void
235 build_fake_control_stack_frames(struct thread *th,os_context_t *context)
236 {
237 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
238
239     lispobj oldcont;
240
241     /* Build a fake stack frame or frames */
242
243     current_control_frame_pointer =
244         (lispobj *)(unsigned long)
245             (*os_context_register_addr(context, reg_CSP));
246     if ((lispobj *)(unsigned long)
247             (*os_context_register_addr(context, reg_CFP))
248         == current_control_frame_pointer) {
249         /* There is a small window during call where the callee's
250          * frame isn't built yet. */
251         if (lowtag_of(*os_context_register_addr(context, reg_CODE))
252             == FUN_POINTER_LOWTAG) {
253             /* We have called, but not built the new frame, so
254              * build it for them. */
255             current_control_frame_pointer[0] =
256                 *os_context_register_addr(context, reg_OCFP);
257             current_control_frame_pointer[1] =
258                 *os_context_register_addr(context, reg_LRA);
259             current_control_frame_pointer += 8;
260             /* Build our frame on top of it. */
261             oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
262         }
263         else {
264             /* We haven't yet called, build our frame as if the
265              * partial frame wasn't there. */
266             oldcont = (lispobj)(*os_context_register_addr(context, reg_OCFP));
267         }
268     }
269     /* We can't tell whether we are still in the caller if it had to
270      * allocate a stack frame due to stack arguments. */
271     /* This observation provoked some past CMUCL maintainer to ask
272      * "Can anything strange happen during return?" */
273     else {
274         /* normal case */
275         oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
276     }
277
278     current_control_stack_pointer = current_control_frame_pointer + 8;
279
280     current_control_frame_pointer[0] = oldcont;
281     current_control_frame_pointer[1] = NIL;
282     current_control_frame_pointer[2] =
283         (lispobj)(*os_context_register_addr(context, reg_CODE));
284 #endif
285 }
286
287 /* Stores the context for gc to scavange and builds fake stack
288  * frames. */
289 void
290 fake_foreign_function_call(os_context_t *context)
291 {
292     int context_index;
293     struct thread *thread=arch_os_get_current_thread();
294
295     /* context_index incrementing must not be interrupted */
296     check_blockables_blocked_or_lose();
297
298     /* Get current Lisp state from context. */
299 #ifdef reg_ALLOC
300     dynamic_space_free_pointer =
301         (lispobj *)(unsigned long)
302             (*os_context_register_addr(context, reg_ALLOC));
303     /* fprintf(stderr,"dynamic_space_free_pointer: %p\n", dynamic_space_free_pointer); */
304 #if defined(LISP_FEATURE_ALPHA)
305     if ((long)dynamic_space_free_pointer & 1) {
306         lose("dead in fake_foreign_function_call, context = %x\n", context);
307     }
308 #endif
309 #endif
310 #ifdef reg_BSP
311     current_binding_stack_pointer =
312         (lispobj *)(unsigned long)
313             (*os_context_register_addr(context, reg_BSP));
314 #endif
315
316     build_fake_control_stack_frames(thread,context);
317
318     /* Do dynamic binding of the active interrupt context index
319      * and save the context in the context array. */
320     context_index =
321         fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,thread));
322
323     if (context_index >= MAX_INTERRUPTS) {
324         lose("maximum interrupt nesting depth (%d) exceeded\n", MAX_INTERRUPTS);
325     }
326
327     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,
328                   make_fixnum(context_index + 1),thread);
329
330     thread->interrupt_contexts[context_index] = context;
331
332 #ifdef FOREIGN_FUNCTION_CALL_FLAG
333     foreign_function_call_active = 1;
334 #endif
335 }
336
337 /* blocks all blockable signals.  If you are calling from a signal handler,
338  * the usual signal mask will be restored from the context when the handler
339  * finishes.  Otherwise, be careful */
340 void
341 undo_fake_foreign_function_call(os_context_t *context)
342 {
343     struct thread *thread=arch_os_get_current_thread();
344     /* Block all blockable signals. */
345     block_blockable_signals();
346
347 #ifdef FOREIGN_FUNCTION_CALL_FLAG
348     foreign_function_call_active = 0;
349 #endif
350
351     /* Undo dynamic binding of FREE_INTERRUPT_CONTEXT_INDEX */
352     unbind(thread);
353
354 #ifdef reg_ALLOC
355     /* Put the dynamic space free pointer back into the context. */
356     *os_context_register_addr(context, reg_ALLOC) =
357         (unsigned long) dynamic_space_free_pointer
358         | (*os_context_register_addr(context, reg_ALLOC)
359            & LOWTAG_MASK);
360     /*
361       ((unsigned long)(*os_context_register_addr(context, reg_ALLOC)) & ~LOWTAG_MASK)
362       | ((unsigned long) dynamic_space_free_pointer & LOWTAG_MASK);
363     */
364 #endif
365 }
366
367 /* a handler for the signal caused by execution of a trap opcode
368  * signalling an internal error */
369 void
370 interrupt_internal_error(os_context_t *context, boolean continuable)
371 {
372     lispobj context_sap;
373
374     fake_foreign_function_call(context);
375
376     if (!internal_errors_enabled) {
377         describe_internal_error(context);
378         /* There's no good way to recover from an internal error
379          * before the Lisp error handling mechanism is set up. */
380         lose("internal error too early in init, can't recover\n");
381     }
382
383     /* Allocate the SAP object while the interrupts are still
384      * disabled. */
385     context_sap = alloc_sap(context);
386
387 #ifndef LISP_FEATURE_WIN32
388     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
389 #endif
390
391     SHOW("in interrupt_internal_error");
392 #ifdef QSHOW
393     /* Display some rudimentary debugging information about the
394      * error, so that even if the Lisp error handler gets badly
395      * confused, we have a chance to determine what's going on. */
396     describe_internal_error(context);
397 #endif
398     funcall2(SymbolFunction(INTERNAL_ERROR), context_sap,
399              continuable ? T : NIL);
400
401     undo_fake_foreign_function_call(context); /* blocks signals again */
402     if (continuable)
403         arch_skip_instruction(context);
404 }
405
406 void
407 interrupt_handle_pending(os_context_t *context)
408 {
409     struct thread *thread;
410     struct interrupt_data *data;
411
412     FSHOW_SIGNAL((stderr, "/entering interrupt_handle_pending\n"));
413
414     check_blockables_blocked_or_lose();
415     thread=arch_os_get_current_thread();
416     data=thread->interrupt_data;
417
418     /* If pseudo_atomic_interrupted is set then the interrupt is going
419      * to be handled now, ergo it's safe to clear it. */
420     arch_clear_pseudo_atomic_interrupted(context);
421
422     if (SymbolValue(GC_INHIBIT,thread)==NIL) {
423 #ifdef LISP_FEATURE_SB_THREAD
424         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL) {
425             /* another thread has already initiated a gc, this attempt
426              * might as well be cancelled */
427             SetSymbolValue(GC_PENDING,NIL,thread);
428             SetSymbolValue(STOP_FOR_GC_PENDING,NIL,thread);
429             sig_stop_for_gc_handler(SIG_STOP_FOR_GC,NULL,context);
430         } else
431 #endif
432         if (SymbolValue(GC_PENDING,thread) != NIL) {
433             /* GC_PENDING is cleared in SUB-GC, or if another thread
434              * is doing a gc already we will get a SIG_STOP_FOR_GC and
435              * that will clear it. */
436             maybe_gc(context);
437         }
438         check_blockables_blocked_or_lose();
439     }
440
441     /* we may be here only to do the gc stuff, if interrupts are
442      * enabled run the pending handler */
443     if (!((SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) ||
444           (
445 #ifdef FOREIGN_FUNCTION_CALL_FLAG
446            (!foreign_function_call_active) &&
447 #endif
448            arch_pseudo_atomic_atomic(context)))) {
449
450         /* There may be no pending handler, because it was only a gc
451          * that had to be executed or because pseudo atomic triggered
452          * twice for a single interrupt. For the interested reader,
453          * that may happen if an interrupt hits after the interrupted
454          * flag is cleared but before pseduo-atomic is set and a
455          * pseudo atomic is interrupted in that interrupt. */
456         if (data->pending_handler) {
457
458             /* If we're here as the result of a pseudo-atomic as opposed
459              * to WITHOUT-INTERRUPTS, then INTERRUPT_PENDING is already
460              * NIL, because maybe_defer_handler sets
461              * PSEUDO_ATOMIC_INTERRUPTED only if interrupts are enabled.*/
462             SetSymbolValue(INTERRUPT_PENDING, NIL,thread);
463
464 #ifndef LISP_FEATURE_WIN32
465             /* restore the saved signal mask from the original signal (the
466              * one that interrupted us during the critical section) into the
467              * os_context for the signal we're currently in the handler for.
468              * This should ensure that when we return from the handler the
469              * blocked signals are unblocked */
470             sigcopyset(os_context_sigmask_addr(context), &data->pending_mask);
471
472             sigemptyset(&data->pending_mask);
473 #endif
474             /* This will break on sparc linux: the deferred handler really wants
475              * to be called with a void_context */
476             run_deferred_handler(data,(void *)context);
477         }
478     }
479 }
480 \f
481 /*
482  * the two main signal handlers:
483  *   interrupt_handle_now(..)
484  *   maybe_now_maybe_later(..)
485  *
486  * to which we have added interrupt_handle_now_handler(..).  Why?
487  * Well, mostly because the SPARC/Linux platform doesn't quite do
488  * signals the way we want them done.  The third argument in the
489  * handler isn't filled in by the kernel properly, so we fix it up
490  * ourselves in the arch_os_get_context(..) function; however, we only
491  * want to do this when we first hit the handler, and not when
492  * interrupt_handle_now(..) is being called from some other handler
493  * (when the fixup will already have been done). -- CSR, 2002-07-23
494  */
495
496 void
497 interrupt_handle_now(int signal, siginfo_t *info, os_context_t *context)
498 {
499 #ifdef FOREIGN_FUNCTION_CALL_FLAG
500     boolean were_in_lisp;
501 #endif
502     union interrupt_handler handler;
503
504     check_blockables_blocked_or_lose();
505
506 #ifndef LISP_FEATURE_WIN32
507     if (sigismember(&deferrable_sigset,signal))
508         check_interrupts_enabled_or_lose(context);
509 #endif
510
511 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
512     /* Under Linux on some architectures, we appear to have to restore
513        the FPU control word from the context, as after the signal is
514        delivered we appear to have a null FPU control word. */
515     os_restore_fp_control(context);
516 #endif
517
518     handler = interrupt_handlers[signal];
519
520     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
521         return;
522     }
523
524 #ifdef FOREIGN_FUNCTION_CALL_FLAG
525     were_in_lisp = !foreign_function_call_active;
526     if (were_in_lisp)
527 #endif
528     {
529         fake_foreign_function_call(context);
530     }
531
532     FSHOW_SIGNAL((stderr,
533                   "/entering interrupt_handle_now(%d, info, context)\n",
534                   signal));
535
536     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
537
538         /* This can happen if someone tries to ignore or default one
539          * of the signals we need for runtime support, and the runtime
540          * support decides to pass on it. */
541         lose("no handler for signal %d in interrupt_handle_now(..)\n", signal);
542
543     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
544         /* Once we've decided what to do about contexts in a
545          * return-elsewhere world (the original context will no longer
546          * be available; should we copy it or was nobody using it anyway?)
547          * then we should convert this to return-elsewhere */
548
549         /* CMUCL comment said "Allocate the SAPs while the interrupts
550          * are still disabled.".  I (dan, 2003.08.21) assume this is
551          * because we're not in pseudoatomic and allocation shouldn't
552          * be interrupted.  In which case it's no longer an issue as
553          * all our allocation from C now goes through a PA wrapper,
554          * but still, doesn't hurt.
555          *
556          * Yeah, but non-gencgc platforms don't really wrap allocation
557          * in PA. MG - 2005-08-29  */
558
559         lispobj info_sap,context_sap = alloc_sap(context);
560         info_sap = alloc_sap(info);
561         /* Leave deferrable signals blocked, the handler itself will
562          * allow signals again when it sees fit. */
563 #ifdef LISP_FEATURE_SB_THREAD
564         {
565             sigset_t unblock;
566             sigemptyset(&unblock);
567             sigaddset(&unblock, SIG_STOP_FOR_GC);
568 #ifdef SIG_RESUME_FROM_GC
569             sigaddset(&unblock, SIG_RESUME_FROM_GC);
570 #endif
571             thread_sigmask(SIG_UNBLOCK, &unblock, 0);
572         }
573 #endif
574
575         FSHOW_SIGNAL((stderr,"/calling Lisp-level handler\n"));
576
577         funcall3(handler.lisp,
578                  make_fixnum(signal),
579                  info_sap,
580                  context_sap);
581     } else {
582
583         FSHOW_SIGNAL((stderr,"/calling C-level handler\n"));
584
585 #ifndef LISP_FEATURE_WIN32
586         /* Allow signals again. */
587         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
588 #endif
589         (*handler.c)(signal, info, context);
590     }
591
592 #ifdef FOREIGN_FUNCTION_CALL_FLAG
593     if (were_in_lisp)
594 #endif
595     {
596         undo_fake_foreign_function_call(context); /* block signals again */
597     }
598
599     FSHOW_SIGNAL((stderr,
600                   "/returning from interrupt_handle_now(%d, info, context)\n",
601                   signal));
602 }
603
604 /* This is called at the end of a critical section if the indications
605  * are that some signal was deferred during the section.  Note that as
606  * far as C or the kernel is concerned we dealt with the signal
607  * already; we're just doing the Lisp-level processing now that we
608  * put off then */
609 static void
610 run_deferred_handler(struct interrupt_data *data, void *v_context) {
611     /* The pending_handler may enable interrupts and then another
612      * interrupt may hit, overwrite interrupt_data, so reset the
613      * pending handler before calling it. Trust the handler to finish
614      * with the siginfo before enabling interrupts. */
615     void (*pending_handler) (int, siginfo_t*, void*)=data->pending_handler;
616
617     data->pending_handler=0;
618     (*pending_handler)(data->pending_signal,&(data->pending_info), v_context);
619 }
620
621 #ifndef LISP_FEATURE_WIN32
622 boolean
623 maybe_defer_handler(void *handler, struct interrupt_data *data,
624                     int signal, siginfo_t *info, os_context_t *context)
625 {
626     struct thread *thread=arch_os_get_current_thread();
627
628     check_blockables_blocked_or_lose();
629
630     if (SymbolValue(INTERRUPT_PENDING,thread) != NIL)
631         lose("interrupt already pending\n");
632     /* If interrupts are disabled then INTERRUPT_PENDING is set and
633      * not PSEDUO_ATOMIC_INTERRUPTED. This is important for a pseudo
634      * atomic section inside a WITHOUT-INTERRUPTS.
635      */
636     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) {
637         store_signal_data_for_later(data,handler,signal,info,context);
638         SetSymbolValue(INTERRUPT_PENDING, T,thread);
639         FSHOW_SIGNAL((stderr,
640                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred\n",
641                       (unsigned int)handler,signal,
642                       (unsigned long)thread->os_thread));
643         return 1;
644     }
645     /* a slightly confusing test.  arch_pseudo_atomic_atomic() doesn't
646      * actually use its argument for anything on x86, so this branch
647      * may succeed even when context is null (gencgc alloc()) */
648     if (
649 #ifdef FOREIGN_FUNCTION_CALL_FLAG
650         /* FIXME: this foreign_function_call_active test is dubious at
651          * best. If a foreign call is made in a pseudo atomic section
652          * (?) or more likely a pseudo atomic section is in a foreign
653          * call then an interrupt is executed immediately. Maybe it
654          * has to do with C code not maintaining pseudo atomic
655          * properly. MG - 2005-08-10 */
656         (!foreign_function_call_active) &&
657 #endif
658         arch_pseudo_atomic_atomic(context)) {
659         store_signal_data_for_later(data,handler,signal,info,context);
660         arch_set_pseudo_atomic_interrupted(context);
661         FSHOW_SIGNAL((stderr,
662                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred(PA)\n",
663                       (unsigned int)handler,signal,
664                       (unsigned long)thread->os_thread));
665         return 1;
666     }
667     FSHOW_SIGNAL((stderr,
668                   "/maybe_defer_handler(%x,%d),thread=%lu: not deferred\n",
669                   (unsigned int)handler,signal,
670                   (unsigned long)thread->os_thread));
671     return 0;
672 }
673
674 static void
675 store_signal_data_for_later (struct interrupt_data *data, void *handler,
676                              int signal,
677                              siginfo_t *info, os_context_t *context)
678 {
679     if (data->pending_handler)
680         lose("tried to overwrite pending interrupt handler %x with %x\n",
681              data->pending_handler, handler);
682     if (!handler)
683         lose("tried to defer null interrupt handler\n");
684     data->pending_handler = handler;
685     data->pending_signal = signal;
686     if(info)
687         memcpy(&(data->pending_info), info, sizeof(siginfo_t));
688
689     FSHOW_SIGNAL((stderr, "/store_signal_data_for_later: signal: %d\n", signal));
690
691     if(context) {
692         /* the signal mask in the context (from before we were
693          * interrupted) is copied to be restored when
694          * run_deferred_handler happens.  Then the usually-blocked
695          * signals are added to the mask in the context so that we are
696          * running with blocked signals when the handler returns */
697         sigcopyset(&(data->pending_mask),os_context_sigmask_addr(context));
698         sigaddset_deferrable(os_context_sigmask_addr(context));
699     }
700 }
701
702 static void
703 maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
704 {
705     os_context_t *context = arch_os_get_context(&void_context);
706     struct thread *thread = arch_os_get_current_thread();
707     struct interrupt_data *data = thread->interrupt_data;
708
709 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
710     os_restore_fp_control(context);
711 #endif
712
713     if(!maybe_defer_handler(interrupt_handle_now,data,signal,info,context))
714         interrupt_handle_now(signal, info, context);
715
716 #ifdef LISP_FEATURE_DARWIN
717     DARWIN_FIX_CONTEXT(context);
718 #endif
719 }
720
721 static void
722 low_level_interrupt_handle_now(int signal, siginfo_t *info, os_context_t *context)
723 {
724     /* No FP control fixage needed, caller has done that. */
725     check_blockables_blocked_or_lose();
726     check_interrupts_enabled_or_lose(context);
727     interrupt_low_level_handlers[signal](signal, info, context);
728     /* No Darwin context fixage needed, caller does that. */
729 }
730
731 static void
732 low_level_maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
733 {
734     os_context_t *context = arch_os_get_context(&void_context);
735     struct thread *thread = arch_os_get_current_thread();
736     struct interrupt_data *data = thread->interrupt_data;
737
738 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
739     os_restore_fp_control(context);
740 #endif
741
742     if(!maybe_defer_handler(low_level_interrupt_handle_now,data,
743                             signal,info,context))
744         low_level_interrupt_handle_now(signal, info, context);
745
746 #ifdef LISP_FEATURE_DARWIN
747     DARWIN_FIX_CONTEXT(context);
748 #endif
749 }
750 #endif
751
752 #ifdef LISP_FEATURE_SB_THREAD
753
754 void
755 sig_stop_for_gc_handler(int signal, siginfo_t *info, void *void_context)
756 {
757     os_context_t *context = arch_os_get_context(&void_context);
758
759     struct thread *thread=arch_os_get_current_thread();
760     sigset_t ss;
761
762     if ((arch_pseudo_atomic_atomic(context) ||
763          SymbolValue(GC_INHIBIT,thread) != NIL)) {
764         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
765         if (SymbolValue(GC_INHIBIT,thread) == NIL)
766             arch_set_pseudo_atomic_interrupted(context);
767         FSHOW_SIGNAL((stderr,"thread=%lu sig_stop_for_gc deferred\n",
768                       thread->os_thread));
769     } else {
770         /* need the context stored so it can have registers scavenged */
771         fake_foreign_function_call(context);
772
773         sigfillset(&ss); /* Block everything. */
774         thread_sigmask(SIG_BLOCK,&ss,0);
775
776         if(thread->state!=STATE_RUNNING) {
777             lose("sig_stop_for_gc_handler: wrong thread state: %ld\n",
778                  fixnum_value(thread->state));
779         }
780         thread->state=STATE_SUSPENDED;
781         FSHOW_SIGNAL((stderr,"thread=%lu suspended\n",thread->os_thread));
782
783 #if defined(SIG_RESUME_FROM_GC)
784         sigemptyset(&ss); sigaddset(&ss,SIG_RESUME_FROM_GC);
785 #else
786         sigemptyset(&ss); sigaddset(&ss,SIG_STOP_FOR_GC);
787 #endif
788
789         /* It is possible to get SIGCONT (and probably other
790          * non-blockable signals) here. */
791 #ifdef SIG_RESUME_FROM_GC
792         {
793             int sigret;
794             do { sigwait(&ss, &sigret); }
795             while (sigret != SIG_RESUME_FROM_GC);
796         }
797 #else
798         while (sigwaitinfo(&ss,0) != SIG_STOP_FOR_GC);
799 #endif
800
801         FSHOW_SIGNAL((stderr,"thread=%lu resumed\n",thread->os_thread));
802         if(thread->state!=STATE_RUNNING) {
803             lose("sig_stop_for_gc_handler: wrong thread state on wakeup: %ld\n",
804                  fixnum_value(thread->state));
805         }
806
807         undo_fake_foreign_function_call(context);
808     }
809 }
810 #endif
811
812 void
813 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
814 {
815     os_context_t *context = arch_os_get_context(&void_context);
816 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
817     os_restore_fp_control(context);
818 #endif
819     interrupt_handle_now(signal, info, context);
820 #ifdef LISP_FEATURE_DARWIN
821     DARWIN_FIX_CONTEXT(context);
822 #endif
823 }
824
825 /*
826  * stuff to detect and handle hitting the GC trigger
827  */
828
829 #ifndef LISP_FEATURE_GENCGC
830 #endif
831
832 /* manipulate the signal context and stack such that when the handler
833  * returns, it will call function instead of whatever it was doing
834  * previously
835  */
836
837 #if (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
838 extern int *context_eflags_addr(os_context_t *context);
839 #endif
840
841 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
842 extern void post_signal_tramp(void);
843 extern void call_into_lisp_tramp(void);
844 void
845 arrange_return_to_lisp_function(os_context_t *context, lispobj function)
846 {
847 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
848     void * fun=native_pointer(function);
849     void *code = &(((struct simple_fun *) fun)->code);
850 #endif
851
852     /* Build a stack frame showing `interrupted' so that the
853      * user's backtrace makes (as much) sense (as usual) */
854
855     /* FIXME: what about restoring fp state? */
856     /* FIXME: what about restoring errno? */
857 #ifdef LISP_FEATURE_X86
858     /* Suppose the existence of some function that saved all
859      * registers, called call_into_lisp, then restored GP registers and
860      * returned.  It would look something like this:
861
862      push   ebp
863      mov    ebp esp
864      pushfl
865      pushal
866      push   $0
867      push   $0
868      pushl  {address of function to call}
869      call   0x8058db0 <call_into_lisp>
870      addl   $12,%esp
871      popal
872      popfl
873      leave
874      ret
875
876      * What we do here is set up the stack that call_into_lisp would
877      * expect to see if it had been called by this code, and frob the
878      * signal context so that signal return goes directly to call_into_lisp,
879      * and when that function (and the lisp function it invoked) returns,
880      * it returns to the second half of this imaginary function which
881      * restores all registers and returns to C
882
883      * For this to work, the latter part of the imaginary function
884      * must obviously exist in reality.  That would be post_signal_tramp
885      */
886
887     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
888
889 #if defined(LISP_FEATURE_DARWIN)
890     u32 *register_save_area = (u32 *)os_validate(0, 0x40);
891
892     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: preparing to go to function %x, sp: %x\n", function, sp));
893     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: context: %x, &context %x\n", context, &context));
894
895     /* 1. os_validate (malloc/mmap) register_save_block
896      * 2. copy register state into register_save_block
897      * 3. put a pointer to register_save_block in a register in the context
898      * 4. set the context's EIP to point to a trampoline which:
899      *    a. builds the fake stack frame from the block
900      *    b. frees the block
901      *    c. calls the function
902      */
903
904     *register_save_area = *os_context_pc_addr(context);
905     *(register_save_area + 1) = function;
906     *(register_save_area + 2) = *os_context_register_addr(context,reg_EDI);
907     *(register_save_area + 3) = *os_context_register_addr(context,reg_ESI);
908     *(register_save_area + 4) = *os_context_register_addr(context,reg_EDX);
909     *(register_save_area + 5) = *os_context_register_addr(context,reg_ECX);
910     *(register_save_area + 6) = *os_context_register_addr(context,reg_EBX);
911     *(register_save_area + 7) = *os_context_register_addr(context,reg_EAX);
912     *(register_save_area + 8) = *context_eflags_addr(context);
913
914     *os_context_pc_addr(context) = call_into_lisp_tramp;
915     *os_context_register_addr(context,reg_ECX) = register_save_area;
916 #else
917
918     /* return address for call_into_lisp: */
919     *(sp-15) = (u32)post_signal_tramp;
920     *(sp-14) = function;        /* args for call_into_lisp : function*/
921     *(sp-13) = 0;               /*                           arg array */
922     *(sp-12) = 0;               /*                           no. args */
923     /* this order matches that used in POPAD */
924     *(sp-11)=*os_context_register_addr(context,reg_EDI);
925     *(sp-10)=*os_context_register_addr(context,reg_ESI);
926
927     *(sp-9)=*os_context_register_addr(context,reg_ESP)-8;
928     /* POPAD ignores the value of ESP:  */
929     *(sp-8)=0;
930     *(sp-7)=*os_context_register_addr(context,reg_EBX);
931
932     *(sp-6)=*os_context_register_addr(context,reg_EDX);
933     *(sp-5)=*os_context_register_addr(context,reg_ECX);
934     *(sp-4)=*os_context_register_addr(context,reg_EAX);
935     *(sp-3)=*context_eflags_addr(context);
936     *(sp-2)=*os_context_register_addr(context,reg_EBP);
937     *(sp-1)=*os_context_pc_addr(context);
938
939 #endif
940
941 #elif defined(LISP_FEATURE_X86_64)
942     u64 *sp=(u64 *)*os_context_register_addr(context,reg_RSP);
943
944     /* return address for call_into_lisp: */
945     *(sp-18) = (u64)post_signal_tramp;
946
947     *(sp-17)=*os_context_register_addr(context,reg_R15);
948     *(sp-16)=*os_context_register_addr(context,reg_R14);
949     *(sp-15)=*os_context_register_addr(context,reg_R13);
950     *(sp-14)=*os_context_register_addr(context,reg_R12);
951     *(sp-13)=*os_context_register_addr(context,reg_R11);
952     *(sp-12)=*os_context_register_addr(context,reg_R10);
953     *(sp-11)=*os_context_register_addr(context,reg_R9);
954     *(sp-10)=*os_context_register_addr(context,reg_R8);
955     *(sp-9)=*os_context_register_addr(context,reg_RDI);
956     *(sp-8)=*os_context_register_addr(context,reg_RSI);
957     /* skip RBP and RSP */
958     *(sp-7)=*os_context_register_addr(context,reg_RBX);
959     *(sp-6)=*os_context_register_addr(context,reg_RDX);
960     *(sp-5)=*os_context_register_addr(context,reg_RCX);
961     *(sp-4)=*os_context_register_addr(context,reg_RAX);
962     *(sp-3)=*context_eflags_addr(context);
963     *(sp-2)=*os_context_register_addr(context,reg_RBP);
964     *(sp-1)=*os_context_pc_addr(context);
965
966     *os_context_register_addr(context,reg_RDI) =
967         (os_context_register_t)function; /* function */
968     *os_context_register_addr(context,reg_RSI) = 0;        /* arg. array */
969     *os_context_register_addr(context,reg_RDX) = 0;        /* no. args */
970 #else
971     struct thread *th=arch_os_get_current_thread();
972     build_fake_control_stack_frames(th,context);
973 #endif
974
975 #ifdef LISP_FEATURE_X86
976
977 #if !defined(LISP_FEATURE_DARWIN)
978     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
979     *os_context_register_addr(context,reg_ECX) = 0;
980     *os_context_register_addr(context,reg_EBP) = (os_context_register_t)(sp-2);
981 #ifdef __NetBSD__
982     *os_context_register_addr(context,reg_UESP) =
983         (os_context_register_t)(sp-15);
984 #else
985     *os_context_register_addr(context,reg_ESP) = (os_context_register_t)(sp-15);
986 #endif /* __NETBSD__ */
987 #endif /* LISP_FEATURE_DARWIN */
988
989 #elif defined(LISP_FEATURE_X86_64)
990     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
991     *os_context_register_addr(context,reg_RCX) = 0;
992     *os_context_register_addr(context,reg_RBP) = (os_context_register_t)(sp-2);
993     *os_context_register_addr(context,reg_RSP) = (os_context_register_t)(sp-18);
994 #else
995     /* this much of the calling convention is common to all
996        non-x86 ports */
997     *os_context_pc_addr(context) = (os_context_register_t)(unsigned long)code;
998     *os_context_register_addr(context,reg_NARGS) = 0;
999     *os_context_register_addr(context,reg_LIP) =
1000         (os_context_register_t)(unsigned long)code;
1001     *os_context_register_addr(context,reg_CFP) =
1002         (os_context_register_t)(unsigned long)current_control_frame_pointer;
1003 #endif
1004 #ifdef ARCH_HAS_NPC_REGISTER
1005     *os_context_npc_addr(context) =
1006         4 + *os_context_pc_addr(context);
1007 #endif
1008 #ifdef LISP_FEATURE_SPARC
1009     *os_context_register_addr(context,reg_CODE) =
1010         (os_context_register_t)(fun + FUN_POINTER_LOWTAG);
1011 #endif
1012 }
1013
1014 #ifdef LISP_FEATURE_SB_THREAD
1015
1016 /* FIXME: this function can go away when all lisp handlers are invoked
1017  * via arrange_return_to_lisp_function. */
1018 void
1019 interrupt_thread_handler(int num, siginfo_t *info, void *v_context)
1020 {
1021     os_context_t *context = (os_context_t*)arch_os_get_context(&v_context);
1022
1023     /* let the handler enable interrupts again when it sees fit */
1024     sigaddset_deferrable(os_context_sigmask_addr(context));
1025     arrange_return_to_lisp_function(context, SymbolFunction(RUN_INTERRUPTION));
1026 }
1027
1028 #endif
1029
1030 /* KLUDGE: Theoretically the approach we use for undefined alien
1031  * variables should work for functions as well, but on PPC/Darwin
1032  * we get bus error at bogus addresses instead, hence this workaround,
1033  * that has the added benefit of automatically discriminating between
1034  * functions and variables.
1035  */
1036 void
1037 undefined_alien_function() {
1038     funcall0(SymbolFunction(UNDEFINED_ALIEN_FUNCTION_ERROR));
1039 }
1040
1041 boolean
1042 handle_guard_page_triggered(os_context_t *context,os_vm_address_t addr)
1043 {
1044     struct thread *th=arch_os_get_current_thread();
1045
1046     /* note the os_context hackery here.  When the signal handler returns,
1047      * it won't go back to what it was doing ... */
1048     if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
1049        addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
1050         /* We hit the end of the control stack: disable guard page
1051          * protection so the error handler has some headroom, protect the
1052          * previous page so that we can catch returns from the guard page
1053          * and restore it. */
1054         protect_control_stack_guard_page(0);
1055         protect_control_stack_return_guard_page(1);
1056
1057         arrange_return_to_lisp_function
1058             (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
1059         return 1;
1060     }
1061     else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
1062             addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
1063         /* We're returning from the guard page: reprotect it, and
1064          * unprotect this one. This works even if we somehow missed
1065          * the return-guard-page, and hit it on our way to new
1066          * exhaustion instead. */
1067         protect_control_stack_guard_page(1);
1068         protect_control_stack_return_guard_page(0);
1069         return 1;
1070     }
1071     else if (addr >= undefined_alien_address &&
1072              addr < undefined_alien_address + os_vm_page_size) {
1073         arrange_return_to_lisp_function
1074           (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
1075         return 1;
1076     }
1077     else return 0;
1078 }
1079 \f
1080 /*
1081  * noise to install handlers
1082  */
1083
1084 #ifndef LISP_FEATURE_WIN32
1085 /* In Linux 2.4 synchronous signals (sigtrap & co) can be delivered if
1086  * they are blocked, in Linux 2.6 the default handler is invoked
1087  * instead that usually coredumps. One might hastily think that adding
1088  * SA_NODEFER helps, but until ~2.6.13 if SA_NODEFER is specified then
1089  * the whole sa_mask is ignored and instead of not adding the signal
1090  * in question to the mask. That means if it's not blockable the
1091  * signal must be unblocked at the beginning of signal handlers.
1092  *
1093  * It turns out that NetBSD's SA_NODEFER doesn't DTRT in a different
1094  * way: if SA_NODEFER is set and the signal is in sa_mask, the signal
1095  * will be unblocked in the sigmask during the signal handler.  -- RMK
1096  * X-mas day, 2005
1097  */
1098 static volatile int sigaction_nodefer_works = -1;
1099
1100 #define SA_NODEFER_TEST_BLOCK_SIGNAL SIGABRT
1101 #define SA_NODEFER_TEST_KILL_SIGNAL SIGUSR1
1102
1103 static void
1104 sigaction_nodefer_test_handler(int signal, siginfo_t *info, void *void_context)
1105 {
1106     sigset_t empty, current;
1107     int i;
1108     sigemptyset(&empty);
1109     thread_sigmask(SIG_BLOCK, &empty, &current);
1110     /* There should be exactly two blocked signals: the two we added
1111      * to sa_mask when setting up the handler.  NetBSD doesn't block
1112      * the signal we're handling when SA_NODEFER is set; Linux before
1113      * 2.6.13 or so also doesn't block the other signal when
1114      * SA_NODEFER is set. */
1115     for(i = 1; i < NSIG; i++)
1116         if (sigismember(&current, i) !=
1117             (((i == SA_NODEFER_TEST_BLOCK_SIGNAL) || (i == signal)) ? 1 : 0)) {
1118             FSHOW_SIGNAL((stderr, "SA_NODEFER doesn't work, signal %d\n", i));
1119             sigaction_nodefer_works = 0;
1120         }
1121     if (sigaction_nodefer_works == -1)
1122         sigaction_nodefer_works = 1;
1123 }
1124
1125 static void
1126 see_if_sigaction_nodefer_works()
1127 {
1128     struct sigaction sa, old_sa;
1129
1130     sa.sa_flags = SA_SIGINFO | SA_NODEFER;
1131     sa.sa_sigaction = sigaction_nodefer_test_handler;
1132     sigemptyset(&sa.sa_mask);
1133     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_BLOCK_SIGNAL);
1134     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_KILL_SIGNAL);
1135     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &sa, &old_sa);
1136     /* Make sure no signals are blocked. */
1137     {
1138         sigset_t empty;
1139         sigemptyset(&empty);
1140         thread_sigmask(SIG_SETMASK, &empty, 0);
1141     }
1142     kill(getpid(), SA_NODEFER_TEST_KILL_SIGNAL);
1143     while (sigaction_nodefer_works == -1);
1144     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &old_sa, NULL);
1145 }
1146
1147 #undef SA_NODEFER_TEST_BLOCK_SIGNAL
1148 #undef SA_NODEFER_TEST_KILL_SIGNAL
1149
1150 static void
1151 unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1152 {
1153     sigset_t unblock;
1154
1155     sigemptyset(&unblock);
1156     sigaddset(&unblock, signal);
1157     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1158     interrupt_handle_now_handler(signal, info, void_context);
1159 }
1160
1161 static void
1162 low_level_unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1163 {
1164     sigset_t unblock;
1165
1166     sigemptyset(&unblock);
1167     sigaddset(&unblock, signal);
1168     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1169     (*interrupt_low_level_handlers[signal])(signal, info, void_context);
1170 }
1171
1172 void
1173 undoably_install_low_level_interrupt_handler (int signal,
1174                                               void handler(int,
1175                                                            siginfo_t*,
1176                                                            void*))
1177 {
1178     struct sigaction sa;
1179
1180     if (0 > signal || signal >= NSIG) {
1181         lose("bad signal number %d\n", signal);
1182     }
1183
1184     if (ARE_SAME_HANDLER(handler, SIG_DFL))
1185         sa.sa_sigaction = handler;
1186     else if (sigismember(&deferrable_sigset,signal))
1187         sa.sa_sigaction = low_level_maybe_now_maybe_later;
1188     /* The use of a trampoline appears to break the
1189        arch_os_get_context() workaround for SPARC/Linux.  For now,
1190        don't use the trampoline (and so be vulnerable to the problems
1191        that SA_NODEFER is meant to solve. */
1192 #if !(defined(LISP_FEATURE_SPARC) && defined(LISP_FEATURE_LINUX))
1193     else if (!sigaction_nodefer_works &&
1194              !sigismember(&blockable_sigset, signal))
1195         sa.sa_sigaction = low_level_unblock_me_trampoline;
1196 #endif
1197     else
1198         sa.sa_sigaction = handler;
1199
1200     sigcopyset(&sa.sa_mask, &blockable_sigset);
1201     sa.sa_flags = SA_SIGINFO | SA_RESTART
1202         | (sigaction_nodefer_works ? SA_NODEFER : 0);
1203 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1204     if((signal==SIG_MEMORY_FAULT)
1205 #ifdef SIG_MEMORY_FAULT2
1206        || (signal==SIG_MEMORY_FAULT2)
1207 #endif
1208 #ifdef SIG_INTERRUPT_THREAD
1209        || (signal==SIG_INTERRUPT_THREAD)
1210 #endif
1211        )
1212         sa.sa_flags |= SA_ONSTACK;
1213 #endif
1214
1215     sigaction(signal, &sa, NULL);
1216     interrupt_low_level_handlers[signal] =
1217         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
1218 }
1219 #endif
1220
1221 /* This is called from Lisp. */
1222 unsigned long
1223 install_handler(int signal, void handler(int, siginfo_t*, void*))
1224 {
1225 #ifndef LISP_FEATURE_WIN32
1226     struct sigaction sa;
1227     sigset_t old, new;
1228     union interrupt_handler oldhandler;
1229
1230     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
1231
1232     sigemptyset(&new);
1233     sigaddset(&new, signal);
1234     thread_sigmask(SIG_BLOCK, &new, &old);
1235
1236     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%x\n",
1237            (unsigned int)interrupt_low_level_handlers[signal]));
1238     if (interrupt_low_level_handlers[signal]==0) {
1239         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
1240             ARE_SAME_HANDLER(handler, SIG_IGN))
1241             sa.sa_sigaction = handler;
1242         else if (sigismember(&deferrable_sigset, signal))
1243             sa.sa_sigaction = maybe_now_maybe_later;
1244         else if (!sigaction_nodefer_works &&
1245                  !sigismember(&blockable_sigset, signal))
1246             sa.sa_sigaction = unblock_me_trampoline;
1247         else
1248             sa.sa_sigaction = interrupt_handle_now_handler;
1249
1250         sigcopyset(&sa.sa_mask, &blockable_sigset);
1251         sa.sa_flags = SA_SIGINFO | SA_RESTART |
1252             (sigaction_nodefer_works ? SA_NODEFER : 0);
1253         sigaction(signal, &sa, NULL);
1254     }
1255
1256     oldhandler = interrupt_handlers[signal];
1257     interrupt_handlers[signal].c = handler;
1258
1259     thread_sigmask(SIG_SETMASK, &old, 0);
1260
1261     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
1262
1263     return (unsigned long)oldhandler.lisp;
1264 #else
1265     /* Probably-wrong Win32 hack */
1266     return 0;
1267 #endif
1268 }
1269
1270 void
1271 interrupt_init()
1272 {
1273 #ifndef LISP_FEATURE_WIN32
1274     int i;
1275     SHOW("entering interrupt_init()");
1276     see_if_sigaction_nodefer_works();
1277     sigemptyset(&deferrable_sigset);
1278     sigemptyset(&blockable_sigset);
1279     sigaddset_deferrable(&deferrable_sigset);
1280     sigaddset_blockable(&blockable_sigset);
1281
1282     /* Set up high level handler information. */
1283     for (i = 0; i < NSIG; i++) {
1284         interrupt_handlers[i].c =
1285             /* (The cast here blasts away the distinction between
1286              * SA_SIGACTION-style three-argument handlers and
1287              * signal(..)-style one-argument handlers, which is OK
1288              * because it works to call the 1-argument form where the
1289              * 3-argument form is expected.) */
1290             (void (*)(int, siginfo_t*, void*))SIG_DFL;
1291     }
1292
1293     SHOW("returning from interrupt_init()");
1294 #endif
1295 }
1296
1297 #ifndef LISP_FEATURE_WIN32
1298 int
1299 siginfo_code(siginfo_t *info)
1300 {
1301     return info->si_code;
1302 }
1303 os_vm_address_t current_memory_fault_address;
1304
1305 void
1306 lisp_memory_fault_error(os_context_t *context, os_vm_address_t addr)
1307 {
1308    /* FIXME: This is lossy: if we get another memory fault (eg. from
1309     * another thread) before lisp has read this, we the information.
1310     * However, since this is mostly informative, we'll live with that for
1311     * now -- some address is better then no address in this case.
1312     */
1313     current_memory_fault_address = addr;
1314     arrange_return_to_lisp_function(context, SymbolFunction(MEMORY_FAULT_ERROR));
1315 }
1316 #endif
1317
1318 /* Common logic far trapping instructions. How we actually handle each
1319  * case is highly architecture dependant, but the overall shape is
1320  * this. */
1321 boolean
1322 maybe_handle_trap(os_context_t *context, int trap)
1323 {
1324     switch(trap) {
1325     case trap_PendingInterrupt:
1326         FSHOW((stderr, "/<trap pending interrupt>\n"));
1327         arch_skip_instruction(context);
1328         interrupt_handle_pending(context);
1329         break;
1330     case trap_Error:
1331     case trap_Cerror:
1332         FSHOW((stderr, "/<trap error/cerror %d>\n", trap));
1333         interrupt_internal_error(context, trap==trap_Cerror);
1334         break;
1335     case trap_Breakpoint:
1336         arch_handle_breakpoint(context);
1337         break;
1338     case trap_FunEndBreakpoint:
1339         arch_handle_fun_end_breakpoint(context);
1340         break;
1341 #ifdef trap_AfterBreakpoint
1342     case trap_AfterBreakpoint:
1343         arch_handle_after_breakpoint(context);
1344         break;
1345 #endif
1346 #ifdef trap_SingleStepAround
1347     case trap_SingleStepAround:
1348     case trap_SingleStepBefore:
1349         arch_handle_single_step_trap(context, trap);
1350         break;
1351 #endif
1352     case trap_Halt:
1353         fake_foreign_function_call(context);
1354         lose("%%PRIMITIVE HALT called; the party is over.\n");
1355     default:
1356         FSHOW((stderr,"/[C--trap default %d %d %x]\n",
1357                signal, trap, context));
1358         /* Not our trap! */
1359         return 0;
1360     }
1361     return 1;
1362 }
1363