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