1.0.4.21: merge redundant funcallN definitions in the runtime
[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     /* There are three ways we can get here.  First, if an interrupt
410      * occurs within pseudo-atomic, it will be deferred, and we'll
411      * trap to here at the end of the pseudo-atomic block.  Second, if
412      * the GC (in alloc()) decides that a GC is required, it will set
413      * *GC-PENDING* and pseudo-atomic-interrupted, and alloc() is
414      * always called from within pseudo-atomic, and thus we end up
415      * here again.  Third, when calling GC-ON or at the end of a
416      * WITHOUT-GCING, MAYBE-HANDLE-PENDING-GC will trap to here if
417      * there is a pending GC. */
418
419     /* Win32 only needs to handle the GC cases (for now?) */
420
421     struct thread *thread = arch_os_get_current_thread();
422
423     FSHOW_SIGNAL((stderr, "/entering interrupt_handle_pending\n"));
424
425     check_blockables_blocked_or_lose();
426
427     /* If pseudo_atomic_interrupted is set then the interrupt is going
428      * to be handled now, ergo it's safe to clear it. */
429     arch_clear_pseudo_atomic_interrupted(context);
430
431     if (SymbolValue(GC_INHIBIT,thread)==NIL) {
432 #ifdef LISP_FEATURE_SB_THREAD
433         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL) {
434             /* another thread has already initiated a gc, this attempt
435              * might as well be cancelled */
436             SetSymbolValue(GC_PENDING,NIL,thread);
437             SetSymbolValue(STOP_FOR_GC_PENDING,NIL,thread);
438             sig_stop_for_gc_handler(SIG_STOP_FOR_GC,NULL,context);
439         } else
440 #endif
441         if (SymbolValue(GC_PENDING,thread) != NIL) {
442             /* GC_PENDING is cleared in SUB-GC, or if another thread
443              * is doing a gc already we will get a SIG_STOP_FOR_GC and
444              * that will clear it. */
445             maybe_gc(context);
446         }
447         check_blockables_blocked_or_lose();
448     }
449
450 #ifndef LISP_FEATURE_WIN32
451     /* we may be here only to do the gc stuff, if interrupts are
452      * enabled run the pending handler */
453     if (!((SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) ||
454           (
455 #ifdef FOREIGN_FUNCTION_CALL_FLAG
456            (!foreign_function_call_active) &&
457 #endif
458            arch_pseudo_atomic_atomic(context)))) {
459         struct interrupt_data *data = thread->interrupt_data;
460
461         /* There may be no pending handler, because it was only a gc
462          * that had to be executed or because pseudo atomic triggered
463          * twice for a single interrupt. For the interested reader,
464          * that may happen if an interrupt hits after the interrupted
465          * flag is cleared but before pseduo-atomic is set and a
466          * pseudo atomic is interrupted in that interrupt. */
467         if (data->pending_handler) {
468
469             /* If we're here as the result of a pseudo-atomic as opposed
470              * to WITHOUT-INTERRUPTS, then INTERRUPT_PENDING is already
471              * NIL, because maybe_defer_handler sets
472              * PSEUDO_ATOMIC_INTERRUPTED only if interrupts are enabled.*/
473             SetSymbolValue(INTERRUPT_PENDING, NIL,thread);
474
475             /* restore the saved signal mask from the original signal (the
476              * one that interrupted us during the critical section) into the
477              * os_context for the signal we're currently in the handler for.
478              * This should ensure that when we return from the handler the
479              * blocked signals are unblocked */
480             sigcopyset(os_context_sigmask_addr(context), &data->pending_mask);
481
482             sigemptyset(&data->pending_mask);
483             /* This will break on sparc linux: the deferred handler really wants
484              * to be called with a void_context */
485             run_deferred_handler(data,(void *)context);
486         }
487     }
488 #endif
489 }
490 \f
491 /*
492  * the two main signal handlers:
493  *   interrupt_handle_now(..)
494  *   maybe_now_maybe_later(..)
495  *
496  * to which we have added interrupt_handle_now_handler(..).  Why?
497  * Well, mostly because the SPARC/Linux platform doesn't quite do
498  * signals the way we want them done.  The third argument in the
499  * handler isn't filled in by the kernel properly, so we fix it up
500  * ourselves in the arch_os_get_context(..) function; however, we only
501  * want to do this when we first hit the handler, and not when
502  * interrupt_handle_now(..) is being called from some other handler
503  * (when the fixup will already have been done). -- CSR, 2002-07-23
504  */
505
506 void
507 interrupt_handle_now(int signal, siginfo_t *info, os_context_t *context)
508 {
509 #ifdef FOREIGN_FUNCTION_CALL_FLAG
510     boolean were_in_lisp;
511 #endif
512     union interrupt_handler handler;
513
514     check_blockables_blocked_or_lose();
515
516 #ifndef LISP_FEATURE_WIN32
517     if (sigismember(&deferrable_sigset,signal))
518         check_interrupts_enabled_or_lose(context);
519 #endif
520
521 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
522     /* Under Linux on some architectures, we appear to have to restore
523        the FPU control word from the context, as after the signal is
524        delivered we appear to have a null FPU control word. */
525     os_restore_fp_control(context);
526 #endif
527
528     handler = interrupt_handlers[signal];
529
530     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
531         return;
532     }
533
534 #ifdef FOREIGN_FUNCTION_CALL_FLAG
535     were_in_lisp = !foreign_function_call_active;
536     if (were_in_lisp)
537 #endif
538     {
539         fake_foreign_function_call(context);
540     }
541
542     FSHOW_SIGNAL((stderr,
543                   "/entering interrupt_handle_now(%d, info, context)\n",
544                   signal));
545
546     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
547
548         /* This can happen if someone tries to ignore or default one
549          * of the signals we need for runtime support, and the runtime
550          * support decides to pass on it. */
551         lose("no handler for signal %d in interrupt_handle_now(..)\n", signal);
552
553     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
554         /* Once we've decided what to do about contexts in a
555          * return-elsewhere world (the original context will no longer
556          * be available; should we copy it or was nobody using it anyway?)
557          * then we should convert this to return-elsewhere */
558
559         /* CMUCL comment said "Allocate the SAPs while the interrupts
560          * are still disabled.".  I (dan, 2003.08.21) assume this is
561          * because we're not in pseudoatomic and allocation shouldn't
562          * be interrupted.  In which case it's no longer an issue as
563          * all our allocation from C now goes through a PA wrapper,
564          * but still, doesn't hurt.
565          *
566          * Yeah, but non-gencgc platforms don't really wrap allocation
567          * in PA. MG - 2005-08-29  */
568
569         lispobj info_sap,context_sap = alloc_sap(context);
570         info_sap = alloc_sap(info);
571         /* Leave deferrable signals blocked, the handler itself will
572          * allow signals again when it sees fit. */
573 #ifdef LISP_FEATURE_SB_THREAD
574         {
575             sigset_t unblock;
576             sigemptyset(&unblock);
577             sigaddset(&unblock, SIG_STOP_FOR_GC);
578 #ifdef SIG_RESUME_FROM_GC
579             sigaddset(&unblock, SIG_RESUME_FROM_GC);
580 #endif
581             thread_sigmask(SIG_UNBLOCK, &unblock, 0);
582         }
583 #endif
584
585         FSHOW_SIGNAL((stderr,"/calling Lisp-level handler\n"));
586
587         funcall3(handler.lisp,
588                  make_fixnum(signal),
589                  info_sap,
590                  context_sap);
591     } else {
592
593         FSHOW_SIGNAL((stderr,"/calling C-level handler\n"));
594
595 #ifndef LISP_FEATURE_WIN32
596         /* Allow signals again. */
597         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
598 #endif
599         (*handler.c)(signal, info, context);
600     }
601
602 #ifdef FOREIGN_FUNCTION_CALL_FLAG
603     if (were_in_lisp)
604 #endif
605     {
606         undo_fake_foreign_function_call(context); /* block signals again */
607     }
608
609     FSHOW_SIGNAL((stderr,
610                   "/returning from interrupt_handle_now(%d, info, context)\n",
611                   signal));
612 }
613
614 /* This is called at the end of a critical section if the indications
615  * are that some signal was deferred during the section.  Note that as
616  * far as C or the kernel is concerned we dealt with the signal
617  * already; we're just doing the Lisp-level processing now that we
618  * put off then */
619 static void
620 run_deferred_handler(struct interrupt_data *data, void *v_context) {
621     /* The pending_handler may enable interrupts and then another
622      * interrupt may hit, overwrite interrupt_data, so reset the
623      * pending handler before calling it. Trust the handler to finish
624      * with the siginfo before enabling interrupts. */
625     void (*pending_handler) (int, siginfo_t*, void*)=data->pending_handler;
626
627     data->pending_handler=0;
628     (*pending_handler)(data->pending_signal,&(data->pending_info), v_context);
629 }
630
631 #ifndef LISP_FEATURE_WIN32
632 boolean
633 maybe_defer_handler(void *handler, struct interrupt_data *data,
634                     int signal, siginfo_t *info, os_context_t *context)
635 {
636     struct thread *thread=arch_os_get_current_thread();
637
638     check_blockables_blocked_or_lose();
639
640     if (SymbolValue(INTERRUPT_PENDING,thread) != NIL)
641         lose("interrupt already pending\n");
642     /* If interrupts are disabled then INTERRUPT_PENDING is set and
643      * not PSEDUO_ATOMIC_INTERRUPTED. This is important for a pseudo
644      * atomic section inside a WITHOUT-INTERRUPTS.
645      */
646     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) {
647         store_signal_data_for_later(data,handler,signal,info,context);
648         SetSymbolValue(INTERRUPT_PENDING, T,thread);
649         FSHOW_SIGNAL((stderr,
650                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred\n",
651                       (unsigned int)handler,signal,
652                       (unsigned long)thread->os_thread));
653         return 1;
654     }
655     /* a slightly confusing test.  arch_pseudo_atomic_atomic() doesn't
656      * actually use its argument for anything on x86, so this branch
657      * may succeed even when context is null (gencgc alloc()) */
658     if (
659 #ifdef FOREIGN_FUNCTION_CALL_FLAG
660         /* FIXME: this foreign_function_call_active test is dubious at
661          * best. If a foreign call is made in a pseudo atomic section
662          * (?) or more likely a pseudo atomic section is in a foreign
663          * call then an interrupt is executed immediately. Maybe it
664          * has to do with C code not maintaining pseudo atomic
665          * properly. MG - 2005-08-10 */
666         (!foreign_function_call_active) &&
667 #endif
668         arch_pseudo_atomic_atomic(context)) {
669         store_signal_data_for_later(data,handler,signal,info,context);
670         arch_set_pseudo_atomic_interrupted(context);
671         FSHOW_SIGNAL((stderr,
672                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred(PA)\n",
673                       (unsigned int)handler,signal,
674                       (unsigned long)thread->os_thread));
675         return 1;
676     }
677     FSHOW_SIGNAL((stderr,
678                   "/maybe_defer_handler(%x,%d),thread=%lu: not deferred\n",
679                   (unsigned int)handler,signal,
680                   (unsigned long)thread->os_thread));
681     return 0;
682 }
683
684 static void
685 store_signal_data_for_later (struct interrupt_data *data, void *handler,
686                              int signal,
687                              siginfo_t *info, os_context_t *context)
688 {
689     if (data->pending_handler)
690         lose("tried to overwrite pending interrupt handler %x with %x\n",
691              data->pending_handler, handler);
692     if (!handler)
693         lose("tried to defer null interrupt handler\n");
694     data->pending_handler = handler;
695     data->pending_signal = signal;
696     if(info)
697         memcpy(&(data->pending_info), info, sizeof(siginfo_t));
698
699     FSHOW_SIGNAL((stderr, "/store_signal_data_for_later: signal: %d\n", signal));
700
701     if(context) {
702         /* the signal mask in the context (from before we were
703          * interrupted) is copied to be restored when
704          * run_deferred_handler happens.  Then the usually-blocked
705          * signals are added to the mask in the context so that we are
706          * running with blocked signals when the handler returns */
707         sigcopyset(&(data->pending_mask),os_context_sigmask_addr(context));
708         sigaddset_deferrable(os_context_sigmask_addr(context));
709     }
710 }
711
712 static void
713 maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
714 {
715     os_context_t *context = arch_os_get_context(&void_context);
716     struct thread *thread = arch_os_get_current_thread();
717     struct interrupt_data *data = thread->interrupt_data;
718
719 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
720     os_restore_fp_control(context);
721 #endif
722
723     if(!maybe_defer_handler(interrupt_handle_now,data,signal,info,context))
724         interrupt_handle_now(signal, info, context);
725
726 #ifdef LISP_FEATURE_DARWIN
727     DARWIN_FIX_CONTEXT(context);
728 #endif
729 }
730
731 static void
732 low_level_interrupt_handle_now(int signal, siginfo_t *info, os_context_t *context)
733 {
734     /* No FP control fixage needed, caller has done that. */
735     check_blockables_blocked_or_lose();
736     check_interrupts_enabled_or_lose(context);
737     interrupt_low_level_handlers[signal](signal, info, context);
738     /* No Darwin context fixage needed, caller does that. */
739 }
740
741 static void
742 low_level_maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
743 {
744     os_context_t *context = arch_os_get_context(&void_context);
745     struct thread *thread = arch_os_get_current_thread();
746     struct interrupt_data *data = thread->interrupt_data;
747
748 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
749     os_restore_fp_control(context);
750 #endif
751
752     if(!maybe_defer_handler(low_level_interrupt_handle_now,data,
753                             signal,info,context))
754         low_level_interrupt_handle_now(signal, info, context);
755
756 #ifdef LISP_FEATURE_DARWIN
757     DARWIN_FIX_CONTEXT(context);
758 #endif
759 }
760 #endif
761
762 #ifdef LISP_FEATURE_SB_THREAD
763
764 void
765 sig_stop_for_gc_handler(int signal, siginfo_t *info, void *void_context)
766 {
767     os_context_t *context = arch_os_get_context(&void_context);
768
769     struct thread *thread=arch_os_get_current_thread();
770     sigset_t ss;
771
772     if ((arch_pseudo_atomic_atomic(context) ||
773          SymbolValue(GC_INHIBIT,thread) != NIL)) {
774         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
775         if (SymbolValue(GC_INHIBIT,thread) == NIL)
776             arch_set_pseudo_atomic_interrupted(context);
777         FSHOW_SIGNAL((stderr,"thread=%lu sig_stop_for_gc deferred\n",
778                       thread->os_thread));
779     } else {
780         /* need the context stored so it can have registers scavenged */
781         fake_foreign_function_call(context);
782
783         sigfillset(&ss); /* Block everything. */
784         thread_sigmask(SIG_BLOCK,&ss,0);
785
786         if(thread->state!=STATE_RUNNING) {
787             lose("sig_stop_for_gc_handler: wrong thread state: %ld\n",
788                  fixnum_value(thread->state));
789         }
790         thread->state=STATE_SUSPENDED;
791         FSHOW_SIGNAL((stderr,"thread=%lu suspended\n",thread->os_thread));
792
793 #if defined(SIG_RESUME_FROM_GC)
794         sigemptyset(&ss); sigaddset(&ss,SIG_RESUME_FROM_GC);
795 #else
796         sigemptyset(&ss); sigaddset(&ss,SIG_STOP_FOR_GC);
797 #endif
798
799         /* It is possible to get SIGCONT (and probably other
800          * non-blockable signals) here. */
801 #ifdef SIG_RESUME_FROM_GC
802         {
803             int sigret;
804             do { sigwait(&ss, &sigret); }
805             while (sigret != SIG_RESUME_FROM_GC);
806         }
807 #else
808         while (sigwaitinfo(&ss,0) != SIG_STOP_FOR_GC);
809 #endif
810
811         FSHOW_SIGNAL((stderr,"thread=%lu resumed\n",thread->os_thread));
812         if(thread->state!=STATE_RUNNING) {
813             lose("sig_stop_for_gc_handler: wrong thread state on wakeup: %ld\n",
814                  fixnum_value(thread->state));
815         }
816
817         undo_fake_foreign_function_call(context);
818     }
819 }
820 #endif
821
822 void
823 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
824 {
825     os_context_t *context = arch_os_get_context(&void_context);
826 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
827     os_restore_fp_control(context);
828 #endif
829     interrupt_handle_now(signal, info, context);
830 #ifdef LISP_FEATURE_DARWIN
831     DARWIN_FIX_CONTEXT(context);
832 #endif
833 }
834
835 /*
836  * stuff to detect and handle hitting the GC trigger
837  */
838
839 #ifndef LISP_FEATURE_GENCGC
840 #endif
841
842 /* manipulate the signal context and stack such that when the handler
843  * returns, it will call function instead of whatever it was doing
844  * previously
845  */
846
847 #if (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
848 extern int *context_eflags_addr(os_context_t *context);
849 #endif
850
851 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
852 extern void post_signal_tramp(void);
853 extern void call_into_lisp_tramp(void);
854 void
855 arrange_return_to_lisp_function(os_context_t *context, lispobj function)
856 {
857 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
858     void * fun=native_pointer(function);
859     void *code = &(((struct simple_fun *) fun)->code);
860 #endif
861
862     /* Build a stack frame showing `interrupted' so that the
863      * user's backtrace makes (as much) sense (as usual) */
864
865     /* FIXME: what about restoring fp state? */
866     /* FIXME: what about restoring errno? */
867 #ifdef LISP_FEATURE_X86
868     /* Suppose the existence of some function that saved all
869      * registers, called call_into_lisp, then restored GP registers and
870      * returned.  It would look something like this:
871
872      push   ebp
873      mov    ebp esp
874      pushfl
875      pushal
876      push   $0
877      push   $0
878      pushl  {address of function to call}
879      call   0x8058db0 <call_into_lisp>
880      addl   $12,%esp
881      popal
882      popfl
883      leave
884      ret
885
886      * What we do here is set up the stack that call_into_lisp would
887      * expect to see if it had been called by this code, and frob the
888      * signal context so that signal return goes directly to call_into_lisp,
889      * and when that function (and the lisp function it invoked) returns,
890      * it returns to the second half of this imaginary function which
891      * restores all registers and returns to C
892
893      * For this to work, the latter part of the imaginary function
894      * must obviously exist in reality.  That would be post_signal_tramp
895      */
896
897     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
898
899 #if defined(LISP_FEATURE_DARWIN)
900     u32 *register_save_area = (u32 *)os_validate(0, 0x40);
901
902     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: preparing to go to function %x, sp: %x\n", function, sp));
903     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: context: %x, &context %x\n", context, &context));
904
905     /* 1. os_validate (malloc/mmap) register_save_block
906      * 2. copy register state into register_save_block
907      * 3. put a pointer to register_save_block in a register in the context
908      * 4. set the context's EIP to point to a trampoline which:
909      *    a. builds the fake stack frame from the block
910      *    b. frees the block
911      *    c. calls the function
912      */
913
914     *register_save_area = *os_context_pc_addr(context);
915     *(register_save_area + 1) = function;
916     *(register_save_area + 2) = *os_context_register_addr(context,reg_EDI);
917     *(register_save_area + 3) = *os_context_register_addr(context,reg_ESI);
918     *(register_save_area + 4) = *os_context_register_addr(context,reg_EDX);
919     *(register_save_area + 5) = *os_context_register_addr(context,reg_ECX);
920     *(register_save_area + 6) = *os_context_register_addr(context,reg_EBX);
921     *(register_save_area + 7) = *os_context_register_addr(context,reg_EAX);
922     *(register_save_area + 8) = *context_eflags_addr(context);
923
924     *os_context_pc_addr(context) = call_into_lisp_tramp;
925     *os_context_register_addr(context,reg_ECX) = register_save_area;
926 #else
927
928     /* return address for call_into_lisp: */
929     *(sp-15) = (u32)post_signal_tramp;
930     *(sp-14) = function;        /* args for call_into_lisp : function*/
931     *(sp-13) = 0;               /*                           arg array */
932     *(sp-12) = 0;               /*                           no. args */
933     /* this order matches that used in POPAD */
934     *(sp-11)=*os_context_register_addr(context,reg_EDI);
935     *(sp-10)=*os_context_register_addr(context,reg_ESI);
936
937     *(sp-9)=*os_context_register_addr(context,reg_ESP)-8;
938     /* POPAD ignores the value of ESP:  */
939     *(sp-8)=0;
940     *(sp-7)=*os_context_register_addr(context,reg_EBX);
941
942     *(sp-6)=*os_context_register_addr(context,reg_EDX);
943     *(sp-5)=*os_context_register_addr(context,reg_ECX);
944     *(sp-4)=*os_context_register_addr(context,reg_EAX);
945     *(sp-3)=*context_eflags_addr(context);
946     *(sp-2)=*os_context_register_addr(context,reg_EBP);
947     *(sp-1)=*os_context_pc_addr(context);
948
949 #endif
950
951 #elif defined(LISP_FEATURE_X86_64)
952     u64 *sp=(u64 *)*os_context_register_addr(context,reg_RSP);
953
954     /* return address for call_into_lisp: */
955     *(sp-18) = (u64)post_signal_tramp;
956
957     *(sp-17)=*os_context_register_addr(context,reg_R15);
958     *(sp-16)=*os_context_register_addr(context,reg_R14);
959     *(sp-15)=*os_context_register_addr(context,reg_R13);
960     *(sp-14)=*os_context_register_addr(context,reg_R12);
961     *(sp-13)=*os_context_register_addr(context,reg_R11);
962     *(sp-12)=*os_context_register_addr(context,reg_R10);
963     *(sp-11)=*os_context_register_addr(context,reg_R9);
964     *(sp-10)=*os_context_register_addr(context,reg_R8);
965     *(sp-9)=*os_context_register_addr(context,reg_RDI);
966     *(sp-8)=*os_context_register_addr(context,reg_RSI);
967     /* skip RBP and RSP */
968     *(sp-7)=*os_context_register_addr(context,reg_RBX);
969     *(sp-6)=*os_context_register_addr(context,reg_RDX);
970     *(sp-5)=*os_context_register_addr(context,reg_RCX);
971     *(sp-4)=*os_context_register_addr(context,reg_RAX);
972     *(sp-3)=*context_eflags_addr(context);
973     *(sp-2)=*os_context_register_addr(context,reg_RBP);
974     *(sp-1)=*os_context_pc_addr(context);
975
976     *os_context_register_addr(context,reg_RDI) =
977         (os_context_register_t)function; /* function */
978     *os_context_register_addr(context,reg_RSI) = 0;        /* arg. array */
979     *os_context_register_addr(context,reg_RDX) = 0;        /* no. args */
980 #else
981     struct thread *th=arch_os_get_current_thread();
982     build_fake_control_stack_frames(th,context);
983 #endif
984
985 #ifdef LISP_FEATURE_X86
986
987 #if !defined(LISP_FEATURE_DARWIN)
988     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
989     *os_context_register_addr(context,reg_ECX) = 0;
990     *os_context_register_addr(context,reg_EBP) = (os_context_register_t)(sp-2);
991 #ifdef __NetBSD__
992     *os_context_register_addr(context,reg_UESP) =
993         (os_context_register_t)(sp-15);
994 #else
995     *os_context_register_addr(context,reg_ESP) = (os_context_register_t)(sp-15);
996 #endif /* __NETBSD__ */
997 #endif /* LISP_FEATURE_DARWIN */
998
999 #elif defined(LISP_FEATURE_X86_64)
1000     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
1001     *os_context_register_addr(context,reg_RCX) = 0;
1002     *os_context_register_addr(context,reg_RBP) = (os_context_register_t)(sp-2);
1003     *os_context_register_addr(context,reg_RSP) = (os_context_register_t)(sp-18);
1004 #else
1005     /* this much of the calling convention is common to all
1006        non-x86 ports */
1007     *os_context_pc_addr(context) = (os_context_register_t)(unsigned long)code;
1008     *os_context_register_addr(context,reg_NARGS) = 0;
1009     *os_context_register_addr(context,reg_LIP) =
1010         (os_context_register_t)(unsigned long)code;
1011     *os_context_register_addr(context,reg_CFP) =
1012         (os_context_register_t)(unsigned long)current_control_frame_pointer;
1013 #endif
1014 #ifdef ARCH_HAS_NPC_REGISTER
1015     *os_context_npc_addr(context) =
1016         4 + *os_context_pc_addr(context);
1017 #endif
1018 #ifdef LISP_FEATURE_SPARC
1019     *os_context_register_addr(context,reg_CODE) =
1020         (os_context_register_t)(fun + FUN_POINTER_LOWTAG);
1021 #endif
1022 }
1023
1024 #ifdef LISP_FEATURE_SB_THREAD
1025
1026 /* FIXME: this function can go away when all lisp handlers are invoked
1027  * via arrange_return_to_lisp_function. */
1028 void
1029 interrupt_thread_handler(int num, siginfo_t *info, void *v_context)
1030 {
1031     os_context_t *context = (os_context_t*)arch_os_get_context(&v_context);
1032
1033     /* let the handler enable interrupts again when it sees fit */
1034     sigaddset_deferrable(os_context_sigmask_addr(context));
1035     arrange_return_to_lisp_function(context, SymbolFunction(RUN_INTERRUPTION));
1036 }
1037
1038 #endif
1039
1040 /* KLUDGE: Theoretically the approach we use for undefined alien
1041  * variables should work for functions as well, but on PPC/Darwin
1042  * we get bus error at bogus addresses instead, hence this workaround,
1043  * that has the added benefit of automatically discriminating between
1044  * functions and variables.
1045  */
1046 void
1047 undefined_alien_function() {
1048     funcall0(SymbolFunction(UNDEFINED_ALIEN_FUNCTION_ERROR));
1049 }
1050
1051 boolean
1052 handle_guard_page_triggered(os_context_t *context,os_vm_address_t addr)
1053 {
1054     struct thread *th=arch_os_get_current_thread();
1055
1056     /* note the os_context hackery here.  When the signal handler returns,
1057      * it won't go back to what it was doing ... */
1058     if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
1059        addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
1060         /* We hit the end of the control stack: disable guard page
1061          * protection so the error handler has some headroom, protect the
1062          * previous page so that we can catch returns from the guard page
1063          * and restore it. */
1064         protect_control_stack_guard_page(0);
1065         protect_control_stack_return_guard_page(1);
1066
1067         arrange_return_to_lisp_function
1068             (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
1069         return 1;
1070     }
1071     else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
1072             addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
1073         /* We're returning from the guard page: reprotect it, and
1074          * unprotect this one. This works even if we somehow missed
1075          * the return-guard-page, and hit it on our way to new
1076          * exhaustion instead. */
1077         protect_control_stack_guard_page(1);
1078         protect_control_stack_return_guard_page(0);
1079         return 1;
1080     }
1081     else if (addr >= undefined_alien_address &&
1082              addr < undefined_alien_address + os_vm_page_size) {
1083         arrange_return_to_lisp_function
1084           (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
1085         return 1;
1086     }
1087     else return 0;
1088 }
1089 \f
1090 /*
1091  * noise to install handlers
1092  */
1093
1094 #ifndef LISP_FEATURE_WIN32
1095 /* In Linux 2.4 synchronous signals (sigtrap & co) can be delivered if
1096  * they are blocked, in Linux 2.6 the default handler is invoked
1097  * instead that usually coredumps. One might hastily think that adding
1098  * SA_NODEFER helps, but until ~2.6.13 if SA_NODEFER is specified then
1099  * the whole sa_mask is ignored and instead of not adding the signal
1100  * in question to the mask. That means if it's not blockable the
1101  * signal must be unblocked at the beginning of signal handlers.
1102  *
1103  * It turns out that NetBSD's SA_NODEFER doesn't DTRT in a different
1104  * way: if SA_NODEFER is set and the signal is in sa_mask, the signal
1105  * will be unblocked in the sigmask during the signal handler.  -- RMK
1106  * X-mas day, 2005
1107  */
1108 static volatile int sigaction_nodefer_works = -1;
1109
1110 #define SA_NODEFER_TEST_BLOCK_SIGNAL SIGABRT
1111 #define SA_NODEFER_TEST_KILL_SIGNAL SIGUSR1
1112
1113 static void
1114 sigaction_nodefer_test_handler(int signal, siginfo_t *info, void *void_context)
1115 {
1116     sigset_t empty, current;
1117     int i;
1118     sigemptyset(&empty);
1119     thread_sigmask(SIG_BLOCK, &empty, &current);
1120     /* There should be exactly two blocked signals: the two we added
1121      * to sa_mask when setting up the handler.  NetBSD doesn't block
1122      * the signal we're handling when SA_NODEFER is set; Linux before
1123      * 2.6.13 or so also doesn't block the other signal when
1124      * SA_NODEFER is set. */
1125     for(i = 1; i < NSIG; i++)
1126         if (sigismember(&current, i) !=
1127             (((i == SA_NODEFER_TEST_BLOCK_SIGNAL) || (i == signal)) ? 1 : 0)) {
1128             FSHOW_SIGNAL((stderr, "SA_NODEFER doesn't work, signal %d\n", i));
1129             sigaction_nodefer_works = 0;
1130         }
1131     if (sigaction_nodefer_works == -1)
1132         sigaction_nodefer_works = 1;
1133 }
1134
1135 static void
1136 see_if_sigaction_nodefer_works()
1137 {
1138     struct sigaction sa, old_sa;
1139
1140     sa.sa_flags = SA_SIGINFO | SA_NODEFER;
1141     sa.sa_sigaction = sigaction_nodefer_test_handler;
1142     sigemptyset(&sa.sa_mask);
1143     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_BLOCK_SIGNAL);
1144     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_KILL_SIGNAL);
1145     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &sa, &old_sa);
1146     /* Make sure no signals are blocked. */
1147     {
1148         sigset_t empty;
1149         sigemptyset(&empty);
1150         thread_sigmask(SIG_SETMASK, &empty, 0);
1151     }
1152     kill(getpid(), SA_NODEFER_TEST_KILL_SIGNAL);
1153     while (sigaction_nodefer_works == -1);
1154     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &old_sa, NULL);
1155 }
1156
1157 #undef SA_NODEFER_TEST_BLOCK_SIGNAL
1158 #undef SA_NODEFER_TEST_KILL_SIGNAL
1159
1160 static void
1161 unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1162 {
1163     sigset_t unblock;
1164
1165     sigemptyset(&unblock);
1166     sigaddset(&unblock, signal);
1167     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1168     interrupt_handle_now_handler(signal, info, void_context);
1169 }
1170
1171 static void
1172 low_level_unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1173 {
1174     sigset_t unblock;
1175
1176     sigemptyset(&unblock);
1177     sigaddset(&unblock, signal);
1178     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1179     (*interrupt_low_level_handlers[signal])(signal, info, void_context);
1180 }
1181
1182 void
1183 undoably_install_low_level_interrupt_handler (int signal,
1184                                               void handler(int,
1185                                                            siginfo_t*,
1186                                                            void*))
1187 {
1188     struct sigaction sa;
1189
1190     if (0 > signal || signal >= NSIG) {
1191         lose("bad signal number %d\n", signal);
1192     }
1193
1194     if (ARE_SAME_HANDLER(handler, SIG_DFL))
1195         sa.sa_sigaction = handler;
1196     else if (sigismember(&deferrable_sigset,signal))
1197         sa.sa_sigaction = low_level_maybe_now_maybe_later;
1198     /* The use of a trampoline appears to break the
1199        arch_os_get_context() workaround for SPARC/Linux.  For now,
1200        don't use the trampoline (and so be vulnerable to the problems
1201        that SA_NODEFER is meant to solve. */
1202 #if !(defined(LISP_FEATURE_SPARC) && defined(LISP_FEATURE_LINUX))
1203     else if (!sigaction_nodefer_works &&
1204              !sigismember(&blockable_sigset, signal))
1205         sa.sa_sigaction = low_level_unblock_me_trampoline;
1206 #endif
1207     else
1208         sa.sa_sigaction = handler;
1209
1210     sigcopyset(&sa.sa_mask, &blockable_sigset);
1211     sa.sa_flags = SA_SIGINFO | SA_RESTART
1212         | (sigaction_nodefer_works ? SA_NODEFER : 0);
1213 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1214     if((signal==SIG_MEMORY_FAULT)
1215 #ifdef SIG_MEMORY_FAULT2
1216        || (signal==SIG_MEMORY_FAULT2)
1217 #endif
1218 #ifdef SIG_INTERRUPT_THREAD
1219        || (signal==SIG_INTERRUPT_THREAD)
1220 #endif
1221        )
1222         sa.sa_flags |= SA_ONSTACK;
1223 #endif
1224
1225     sigaction(signal, &sa, NULL);
1226     interrupt_low_level_handlers[signal] =
1227         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
1228 }
1229 #endif
1230
1231 /* This is called from Lisp. */
1232 unsigned long
1233 install_handler(int signal, void handler(int, siginfo_t*, void*))
1234 {
1235 #ifndef LISP_FEATURE_WIN32
1236     struct sigaction sa;
1237     sigset_t old, new;
1238     union interrupt_handler oldhandler;
1239
1240     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
1241
1242     sigemptyset(&new);
1243     sigaddset(&new, signal);
1244     thread_sigmask(SIG_BLOCK, &new, &old);
1245
1246     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%x\n",
1247            (unsigned int)interrupt_low_level_handlers[signal]));
1248     if (interrupt_low_level_handlers[signal]==0) {
1249         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
1250             ARE_SAME_HANDLER(handler, SIG_IGN))
1251             sa.sa_sigaction = handler;
1252         else if (sigismember(&deferrable_sigset, signal))
1253             sa.sa_sigaction = maybe_now_maybe_later;
1254         else if (!sigaction_nodefer_works &&
1255                  !sigismember(&blockable_sigset, signal))
1256             sa.sa_sigaction = unblock_me_trampoline;
1257         else
1258             sa.sa_sigaction = interrupt_handle_now_handler;
1259
1260         sigcopyset(&sa.sa_mask, &blockable_sigset);
1261         sa.sa_flags = SA_SIGINFO | SA_RESTART |
1262             (sigaction_nodefer_works ? SA_NODEFER : 0);
1263         sigaction(signal, &sa, NULL);
1264     }
1265
1266     oldhandler = interrupt_handlers[signal];
1267     interrupt_handlers[signal].c = handler;
1268
1269     thread_sigmask(SIG_SETMASK, &old, 0);
1270
1271     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
1272
1273     return (unsigned long)oldhandler.lisp;
1274 #else
1275     /* Probably-wrong Win32 hack */
1276     return 0;
1277 #endif
1278 }
1279
1280 void
1281 interrupt_init()
1282 {
1283 #ifndef LISP_FEATURE_WIN32
1284     int i;
1285     SHOW("entering interrupt_init()");
1286     see_if_sigaction_nodefer_works();
1287     sigemptyset(&deferrable_sigset);
1288     sigemptyset(&blockable_sigset);
1289     sigaddset_deferrable(&deferrable_sigset);
1290     sigaddset_blockable(&blockable_sigset);
1291
1292     /* Set up high level handler information. */
1293     for (i = 0; i < NSIG; i++) {
1294         interrupt_handlers[i].c =
1295             /* (The cast here blasts away the distinction between
1296              * SA_SIGACTION-style three-argument handlers and
1297              * signal(..)-style one-argument handlers, which is OK
1298              * because it works to call the 1-argument form where the
1299              * 3-argument form is expected.) */
1300             (void (*)(int, siginfo_t*, void*))SIG_DFL;
1301     }
1302
1303     SHOW("returning from interrupt_init()");
1304 #endif
1305 }
1306
1307 #ifndef LISP_FEATURE_WIN32
1308 int
1309 siginfo_code(siginfo_t *info)
1310 {
1311     return info->si_code;
1312 }
1313 os_vm_address_t current_memory_fault_address;
1314
1315 void
1316 lisp_memory_fault_error(os_context_t *context, os_vm_address_t addr)
1317 {
1318    /* FIXME: This is lossy: if we get another memory fault (eg. from
1319     * another thread) before lisp has read this, we the information.
1320     * However, since this is mostly informative, we'll live with that for
1321     * now -- some address is better then no address in this case.
1322     */
1323     current_memory_fault_address = addr;
1324     arrange_return_to_lisp_function(context, SymbolFunction(MEMORY_FAULT_ERROR));
1325 }
1326 #endif
1327
1328 void
1329 unhandled_trap_error(os_context_t *context)
1330 {
1331     lispobj context_sap;
1332     fake_foreign_function_call(context);
1333     context_sap = alloc_sap(context);
1334 #ifndef LISP_FEATURE_WIN32
1335     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
1336 #endif
1337     funcall1(SymbolFunction(UNHANDLED_TRAP_ERROR), context_sap);
1338     lose("UNHANDLED-TRAP-ERROR fell through");
1339 }
1340
1341 /* Common logic far trapping instructions. How we actually handle each
1342  * case is highly architecture dependant, but the overall shape is
1343  * this. */
1344 void
1345 handle_trap(os_context_t *context, int trap)
1346 {
1347     switch(trap) {
1348     case trap_PendingInterrupt:
1349         FSHOW((stderr, "/<trap pending interrupt>\n"));
1350         arch_skip_instruction(context);
1351         interrupt_handle_pending(context);
1352         break;
1353     case trap_Error:
1354     case trap_Cerror:
1355         FSHOW((stderr, "/<trap error/cerror %d>\n", trap));
1356         interrupt_internal_error(context, trap==trap_Cerror);
1357         break;
1358     case trap_Breakpoint:
1359         arch_handle_breakpoint(context);
1360         break;
1361     case trap_FunEndBreakpoint:
1362         arch_handle_fun_end_breakpoint(context);
1363         break;
1364 #ifdef trap_AfterBreakpoint
1365     case trap_AfterBreakpoint:
1366         arch_handle_after_breakpoint(context);
1367         break;
1368 #endif
1369 #ifdef trap_SingleStepAround
1370     case trap_SingleStepAround:
1371     case trap_SingleStepBefore:
1372         arch_handle_single_step_trap(context, trap);
1373         break;
1374 #endif
1375     case trap_Halt:
1376         fake_foreign_function_call(context);
1377         lose("%%PRIMITIVE HALT called; the party is over.\n");
1378     default:
1379         unhandled_trap_error(context);
1380     }
1381 }
1382