0.8.6.5
[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
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <signal.h>
48
49 #include "runtime.h"
50 #include "arch.h"
51 #include "sbcl.h"
52 #include "os.h"
53 #include "interrupt.h"
54 #include "globals.h"
55 #include "lispregs.h"
56 #include "validate.h"
57 #include "monitor.h"
58 #include "gc.h"
59 #include "alloc.h"
60 #include "dynbind.h"
61 #include "interr.h"
62 #include "genesis/fdefn.h"
63 #include "genesis/simple-fun.h"
64
65 void run_deferred_handler(struct interrupt_data *data, void *v_context) ;
66 static void store_signal_data_for_later (struct interrupt_data *data, 
67                                          void *handler, int signal,
68                                          siginfo_t *info, 
69                                          os_context_t *context);
70 boolean interrupt_maybe_gc_int(int signal, siginfo_t *info, void *v_context);
71
72 extern volatile lispobj all_threads_lock;
73 extern volatile int countdown_to_gc;
74
75 /*
76  * This is a workaround for some slightly silly Linux/GNU Libc
77  * behaviour: glibc defines sigset_t to support 1024 signals, which is
78  * more than the kernel.  This is usually not a problem, but becomes
79  * one when we want to save a signal mask from a ucontext, and restore
80  * it later into another ucontext: the ucontext is allocated on the
81  * stack by the kernel, so copying a libc-sized sigset_t into it will
82  * overflow and cause other data on the stack to be corrupted */
83
84 #define REAL_SIGSET_SIZE_BYTES ((NSIG/8))
85
86 void sigaddset_blockable(sigset_t *s)
87 {
88     sigaddset(s, SIGHUP);
89     sigaddset(s, SIGINT);
90     sigaddset(s, SIGQUIT);
91     sigaddset(s, SIGPIPE);
92     sigaddset(s, SIGALRM);
93     sigaddset(s, SIGURG);
94     sigaddset(s, SIGFPE);
95     sigaddset(s, SIGTSTP);
96     sigaddset(s, SIGCHLD);
97     sigaddset(s, SIGIO);
98     sigaddset(s, SIGXCPU);
99     sigaddset(s, SIGXFSZ);
100     sigaddset(s, SIGVTALRM);
101     sigaddset(s, SIGPROF);
102     sigaddset(s, SIGWINCH);
103     sigaddset(s, SIGUSR1);
104     sigaddset(s, SIGUSR2);
105 #ifdef LISP_FEATURE_SB_THREAD
106     sigaddset(s, SIG_STOP_FOR_GC);
107     sigaddset(s, SIG_INTERRUPT_THREAD);
108 #endif
109 }
110
111 /* When we catch an internal error, should we pass it back to Lisp to
112  * be handled in a high-level way? (Early in cold init, the answer is
113  * 'no', because Lisp is still too brain-dead to handle anything.
114  * After sufficient initialization has been completed, the answer
115  * becomes 'yes'.) */
116 boolean internal_errors_enabled = 0;
117
118 struct interrupt_data * global_interrupt_data;
119
120 /* At the toplevel repl we routinely call this function.  The signal
121  * mask ought to be clear anyway most of the time, but may be non-zero
122  * if we were interrupted e.g. while waiting for a queue.  */
123
124 #if 1
125 void reset_signal_mask () 
126 {
127     sigset_t new;
128     sigemptyset(&new);
129     sigprocmask(SIG_SETMASK,&new,0);
130 }
131 #else
132 void reset_signal_mask () 
133 {
134     sigset_t new,old;
135     int i;
136     int wrong=0;
137     sigemptyset(&new);
138     sigprocmask(SIG_SETMASK,&new,&old);
139     for(i=1; i<NSIG; i++) {
140         if(sigismember(&old,i)) {
141             fprintf(stderr,
142                     "Warning: signal %d is masked: this is unexpected\n",i);
143             wrong=1;
144         }
145     }
146     if(wrong) 
147         fprintf(stderr,"If this version of SBCL is less than three months old, please report this.\nOtherwise, please try a newer version first\n.  Reset signal mask.\n");
148 }
149 #endif
150
151
152
153 \f
154 /*
155  * utility routines used by various signal handlers
156  */
157
158 void 
159 build_fake_control_stack_frames(struct thread *th,os_context_t *context)
160 {
161 #ifndef LISP_FEATURE_X86
162     
163     lispobj oldcont;
164
165     /* Build a fake stack frame or frames */
166
167     current_control_frame_pointer =
168         (lispobj *)(*os_context_register_addr(context, reg_CSP));
169     if ((lispobj *)(*os_context_register_addr(context, reg_CFP))
170         == current_control_frame_pointer) {
171         /* There is a small window during call where the callee's
172          * frame isn't built yet. */
173         if (lowtag_of(*os_context_register_addr(context, reg_CODE))
174             == FUN_POINTER_LOWTAG) {
175             /* We have called, but not built the new frame, so
176              * build it for them. */
177             current_control_frame_pointer[0] =
178                 *os_context_register_addr(context, reg_OCFP);
179             current_control_frame_pointer[1] =
180                 *os_context_register_addr(context, reg_LRA);
181             current_control_frame_pointer += 8;
182             /* Build our frame on top of it. */
183             oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
184         }
185         else {
186             /* We haven't yet called, build our frame as if the
187              * partial frame wasn't there. */
188             oldcont = (lispobj)(*os_context_register_addr(context, reg_OCFP));
189         }
190     }
191     /* We can't tell whether we are still in the caller if it had to
192      * allocate a stack frame due to stack arguments. */
193     /* This observation provoked some past CMUCL maintainer to ask
194      * "Can anything strange happen during return?" */
195     else {
196         /* normal case */
197         oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
198     }
199
200     current_control_stack_pointer = current_control_frame_pointer + 8;
201
202     current_control_frame_pointer[0] = oldcont;
203     current_control_frame_pointer[1] = NIL;
204     current_control_frame_pointer[2] =
205         (lispobj)(*os_context_register_addr(context, reg_CODE));
206 #endif
207 }
208
209 void
210 fake_foreign_function_call(os_context_t *context)
211 {
212     int context_index;
213     struct thread *thread=arch_os_get_current_thread();
214
215     /* Get current Lisp state from context. */
216 #ifdef reg_ALLOC
217     dynamic_space_free_pointer =
218         (lispobj *)(*os_context_register_addr(context, reg_ALLOC));
219 #ifdef alpha
220     if ((long)dynamic_space_free_pointer & 1) {
221         lose("dead in fake_foreign_function_call, context = %x", context);
222     }
223 #endif
224 #endif
225 #ifdef reg_BSP
226     current_binding_stack_pointer =
227         (lispobj *)(*os_context_register_addr(context, reg_BSP));
228 #endif
229
230     build_fake_control_stack_frames(thread,context);
231
232     /* Do dynamic binding of the active interrupt context index
233      * and save the context in the context array. */
234     context_index =
235         fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,thread));
236     
237     if (context_index >= MAX_INTERRUPTS) {
238         lose("maximum interrupt nesting depth (%d) exceeded", MAX_INTERRUPTS);
239     }
240
241     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,
242                   make_fixnum(context_index + 1),thread);
243
244     thread->interrupt_contexts[context_index] = context;
245
246     /* no longer in Lisp now */
247     foreign_function_call_active = 1;
248 }
249
250 /* blocks all blockable signals.  If you are calling from a signal handler,
251  * the usual signal mask will be restored from the context when the handler 
252  * finishes.  Otherwise, be careful */
253
254 void
255 undo_fake_foreign_function_call(os_context_t *context)
256 {
257     struct thread *thread=arch_os_get_current_thread();
258     /* Block all blockable signals. */
259     sigset_t block;
260     sigemptyset(&block);
261     sigaddset_blockable(&block);
262     sigprocmask(SIG_BLOCK, &block, 0);
263
264     /* going back into Lisp */
265     foreign_function_call_active = 0;
266
267     /* Undo dynamic binding of FREE_INTERRUPT_CONTEXT_INDEX */
268     unbind(thread);
269
270 #ifdef reg_ALLOC
271     /* Put the dynamic space free pointer back into the context. */
272     *os_context_register_addr(context, reg_ALLOC) =
273         (unsigned long) dynamic_space_free_pointer;
274 #endif
275 }
276
277 /* a handler for the signal caused by execution of a trap opcode
278  * signalling an internal error */
279 void
280 interrupt_internal_error(int signal, siginfo_t *info, os_context_t *context,
281                          boolean continuable)
282 {
283     lispobj context_sap = 0;
284
285     fake_foreign_function_call(context);
286
287     /* Allocate the SAP object while the interrupts are still
288      * disabled. */
289     if (internal_errors_enabled) {
290         context_sap = alloc_sap(context);
291     }
292
293     sigprocmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
294
295     if (internal_errors_enabled) {
296         SHOW("in interrupt_internal_error");
297 #if QSHOW
298         /* Display some rudimentary debugging information about the
299          * error, so that even if the Lisp error handler gets badly
300          * confused, we have a chance to determine what's going on. */
301         describe_internal_error(context);
302 #endif
303         funcall2(SymbolFunction(INTERNAL_ERROR), context_sap,
304                  continuable ? T : NIL);
305     } else {
306         describe_internal_error(context);
307         /* There's no good way to recover from an internal error
308          * before the Lisp error handling mechanism is set up. */
309         lose("internal error too early in init, can't recover");
310     }
311     undo_fake_foreign_function_call(context); /* blocks signals again */
312     if (continuable) {
313         arch_skip_instruction(context);
314     }
315 }
316
317 void
318 interrupt_handle_pending(os_context_t *context)
319 {
320     struct thread *thread;
321     struct interrupt_data *data;
322
323     thread=arch_os_get_current_thread();
324     data=thread->interrupt_data;
325     /* FIXME I'm not altogether sure this is appropriate if we're
326      * here as the result of a pseudo-atomic */
327     SetSymbolValue(INTERRUPT_PENDING, NIL,thread);
328
329     /* restore the saved signal mask from the original signal (the
330      * one that interrupted us during the critical section) into the
331      * os_context for the signal we're currently in the handler for.
332      * This should ensure that when we return from the handler the
333      * blocked signals are unblocked */
334
335     memcpy(os_context_sigmask_addr(context), &data->pending_mask, 
336            REAL_SIGSET_SIZE_BYTES);
337
338     sigemptyset(&data->pending_mask);
339     /* This will break on sparc linux: the deferred handler really wants
340      * to be called with a void_context */
341     run_deferred_handler(data,(void *)context); 
342 }
343 \f
344 /*
345  * the two main signal handlers:
346  *   interrupt_handle_now(..)
347  *   maybe_now_maybe_later(..)
348  *
349  * to which we have added interrupt_handle_now_handler(..).  Why?
350  * Well, mostly because the SPARC/Linux platform doesn't quite do
351  * signals the way we want them done.  The third argument in the
352  * handler isn't filled in by the kernel properly, so we fix it up
353  * ourselves in the arch_os_get_context(..) function; however, we only
354  * want to do this when we first hit the handler, and not when
355  * interrupt_handle_now(..) is being called from some other handler
356  * (when the fixup will already have been done). -- CSR, 2002-07-23
357  */
358
359 void
360 interrupt_handle_now(int signal, siginfo_t *info, void *void_context)
361 {
362     os_context_t *context = (os_context_t*)void_context;
363     struct thread *thread=arch_os_get_current_thread();
364 #ifndef LISP_FEATURE_X86
365     boolean were_in_lisp;
366 #endif
367     union interrupt_handler handler;
368
369 #ifdef LISP_FEATURE_LINUX
370     /* Under Linux on some architectures, we appear to have to restore
371        the FPU control word from the context, as after the signal is
372        delivered we appear to have a null FPU control word. */
373     os_restore_fp_control(context);
374 #endif 
375     handler = thread->interrupt_data->interrupt_handlers[signal];
376
377     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
378         return;
379     }
380     
381 #ifndef LISP_FEATURE_X86
382     were_in_lisp = !foreign_function_call_active;
383     if (were_in_lisp)
384 #endif
385     {
386         fake_foreign_function_call(context);
387     }
388
389 #ifdef QSHOW_SIGNALS
390     FSHOW((stderr,
391            "/entering interrupt_handle_now(%d, info, context)\n",
392            signal));
393 #endif
394
395     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
396
397         /* This can happen if someone tries to ignore or default one
398          * of the signals we need for runtime support, and the runtime
399          * support decides to pass on it. */
400         lose("no handler for signal %d in interrupt_handle_now(..)", signal);
401
402     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
403         /* Once we've decided what to do about contexts in a 
404          * return-elsewhere world (the original context will no longer
405          * be available; should we copy it or was nobody using it anyway?)
406          * then we should convert this to return-elsewhere */
407
408         /* CMUCL comment said "Allocate the SAPs while the interrupts
409          * are still disabled.".  I (dan, 2003.08.21) assume this is 
410          * because we're not in pseudoatomic and allocation shouldn't
411          * be interrupted.  In which case it's no longer an issue as
412          * all our allocation from C now goes through a PA wrapper,
413          * but still, doesn't hurt */
414
415         lispobj info_sap,context_sap = alloc_sap(context);
416         info_sap = alloc_sap(info);
417         /* Allow signals again. */
418         sigprocmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
419
420 #ifdef QSHOW_SIGNALS
421         SHOW("calling Lisp-level handler");
422 #endif
423
424         funcall3(handler.lisp,
425                  make_fixnum(signal),
426                  info_sap,
427                  context_sap);
428     } else {
429
430 #ifdef QSHOW_SIGNALS
431         SHOW("calling C-level handler");
432 #endif
433
434         /* Allow signals again. */
435         sigprocmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
436         
437         (*handler.c)(signal, info, void_context);
438     }
439
440 #ifndef LISP_FEATURE_X86
441     if (were_in_lisp)
442 #endif
443     {
444         undo_fake_foreign_function_call(context); /* block signals again */
445     }
446
447 #ifdef QSHOW_SIGNALS
448     FSHOW((stderr,
449            "/returning from interrupt_handle_now(%d, info, context)\n",
450            signal));
451 #endif
452 }
453
454 /* This is called at the end of a critical section if the indications
455  * are that some signal was deferred during the section.  Note that as
456  * far as C or the kernel is concerned we dealt with the signal
457  * already; we're just doing the Lisp-level processing now that we
458  * put off then */
459
460 void
461 run_deferred_handler(struct interrupt_data *data, void *v_context) {
462     (*(data->pending_handler))
463         (data->pending_signal,&(data->pending_info), v_context);
464     data->pending_handler=0;
465 }
466
467 boolean
468 maybe_defer_handler(void *handler, struct interrupt_data *data,
469                     int signal, siginfo_t *info, os_context_t *context)
470 {
471     struct thread *thread=arch_os_get_current_thread();
472     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) {
473         store_signal_data_for_later(data,handler,signal,info,context);
474         SetSymbolValue(INTERRUPT_PENDING, T,thread);
475         return 1;
476     } 
477     /* a slightly confusing test.  arch_pseudo_atomic_atomic() doesn't
478      * actually use its argument for anything on x86, so this branch
479      * may succeed even when context is null (gencgc alloc()) */
480     if (
481 #ifndef LISP_FEATURE_X86
482         (!foreign_function_call_active) &&
483 #endif
484         arch_pseudo_atomic_atomic(context)) {
485         store_signal_data_for_later(data,handler,signal,info,context);
486         arch_set_pseudo_atomic_interrupted(context);
487         return 1;
488     }
489     return 0;
490 }
491 static void
492 store_signal_data_for_later (struct interrupt_data *data, void *handler,
493                              int signal, 
494                              siginfo_t *info, os_context_t *context)
495 {
496     data->pending_handler = handler;
497     data->pending_signal = signal;
498     if(info)
499         memcpy(&(data->pending_info), info, sizeof(siginfo_t));
500     if(context) {
501         /* the signal mask in the context (from before we were
502          * interrupted) is copied to be restored when
503          * run_deferred_handler happens.  Then the usually-blocked
504          * signals are added to the mask in the context so that we are
505          * running with blocked signals when the handler returns */
506         sigemptyset(&(data->pending_mask));
507         memcpy(&(data->pending_mask),
508                os_context_sigmask_addr(context),
509                REAL_SIGSET_SIZE_BYTES);
510         sigaddset_blockable(os_context_sigmask_addr(context));
511     } else {
512         /* this is also called from gencgc alloc(), in which case
513          * there has been no signal and is therefore no context. */
514         sigset_t new;
515         sigemptyset(&new);
516         sigaddset_blockable(&new);
517         sigprocmask(SIG_BLOCK,&new,&(data->pending_mask));
518     }
519 }
520
521
522 static void
523 maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
524 {
525     os_context_t *context = arch_os_get_context(&void_context);
526     struct thread *thread=arch_os_get_current_thread();
527     struct interrupt_data *data=thread->interrupt_data;
528 #ifdef LISP_FEATURE_LINUX
529     os_restore_fp_control(context);
530 #endif 
531     if(maybe_defer_handler(interrupt_handle_now,data,
532                            signal,info,context))
533         return;
534     interrupt_handle_now(signal, info, context);
535 }
536
537 void
538 sig_stop_for_gc_handler(int signal, siginfo_t *info, void *void_context)
539 {
540     os_context_t *context = arch_os_get_context(&void_context);
541     struct thread *thread=arch_os_get_current_thread();
542     struct interrupt_data *data=thread->interrupt_data;
543
544     
545     if(maybe_defer_handler(sig_stop_for_gc_handler,data,
546                            signal,info,context)){
547         return;
548     }
549     /* need the context stored so it can have registers scavenged */
550     fake_foreign_function_call(context); 
551
552     get_spinlock(&all_threads_lock,thread->pid);
553     countdown_to_gc--;
554     thread->state=STATE_STOPPED;
555     release_spinlock(&all_threads_lock);
556     kill(thread->pid,SIGSTOP);
557
558     undo_fake_foreign_function_call(context);
559 }
560
561 void
562 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
563 {
564     os_context_t *context = arch_os_get_context(&void_context);
565     interrupt_handle_now(signal, info, context);
566 }
567
568 /*
569  * stuff to detect and handle hitting the GC trigger
570  */
571
572 #ifndef LISP_FEATURE_GENCGC 
573 /* since GENCGC has its own way to record trigger */
574 static boolean
575 gc_trigger_hit(int signal, siginfo_t *info, os_context_t *context)
576 {
577     if (current_auto_gc_trigger == NULL)
578         return 0;
579     else{
580         void *badaddr=arch_get_bad_addr(signal,info,context);
581         return (badaddr >= (void *)current_auto_gc_trigger &&
582                 badaddr <((void *)current_dynamic_space + DYNAMIC_SPACE_SIZE));
583     }
584 }
585 #endif
586
587 /* manipulate the signal context and stack such that when the handler
588  * returns, it will call function instead of whatever it was doing
589  * previously
590  */
591
592 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
593 extern void post_signal_tramp(void);
594 void arrange_return_to_lisp_function(os_context_t *context, lispobj function)
595 {
596     void * fun=native_pointer(function);
597     char *code = &(((struct simple_fun *) fun)->code);
598     
599     /* Build a stack frame showing `interrupted' so that the
600      * user's backtrace makes (as much) sense (as usual) */
601 #ifdef LISP_FEATURE_X86
602     /* Suppose the existence of some function that saved all
603      * registers, called call_into_lisp, then restored GP registers and
604      * returned.  We shortcut this: fake the stack that call_into_lisp
605      * would see, then arrange to have it called directly.  post_signal_tramp
606      * is the second half of this function
607      */
608     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
609
610     *(sp-14) = post_signal_tramp; /* return address for call_into_lisp */
611     *(sp-13) = function;        /* args for call_into_lisp : function*/
612     *(sp-12) = 0;               /*                           arg array */
613     *(sp-11) = 0;               /*                           no. args */
614     /* this order matches that used in POPAD */
615     *(sp-10)=*os_context_register_addr(context,reg_EDI);
616     *(sp-9)=*os_context_register_addr(context,reg_ESI);
617     /* this gets overwritten again before it's used, anyway */
618     *(sp-8)=*os_context_register_addr(context,reg_EBP);
619     *(sp-7)=0 ; /* POPAD doesn't set ESP, but expects a gap for it anyway */
620     *(sp-6)=*os_context_register_addr(context,reg_EBX);
621
622     *(sp-5)=*os_context_register_addr(context,reg_EDX);
623     *(sp-4)=*os_context_register_addr(context,reg_ECX);
624     *(sp-3)=*os_context_register_addr(context,reg_EAX);
625     *(sp-2)=*os_context_register_addr(context,reg_EBP);
626     *(sp-1)=*os_context_pc_addr(context);
627
628 #else 
629     struct thread *th=arch_os_get_current_thread();
630     build_fake_control_stack_frames(th,context);
631 #endif
632
633 #ifdef LISP_FEATURE_X86
634     *os_context_pc_addr(context) = call_into_lisp;
635     *os_context_register_addr(context,reg_ECX) = 0; 
636     *os_context_register_addr(context,reg_EBP) = sp-2;
637     *os_context_register_addr(context,reg_ESP) = sp-14;
638 #else
639     /* this much of the calling convention is common to all
640        non-x86 ports */
641     *os_context_pc_addr(context) = code;
642     *os_context_register_addr(context,reg_NARGS) = 0; 
643     *os_context_register_addr(context,reg_LIP) = code;
644     *os_context_register_addr(context,reg_CFP) = 
645         current_control_frame_pointer;
646 #endif
647 #ifdef ARCH_HAS_NPC_REGISTER
648     *os_context_npc_addr(context) =
649         4 + *os_context_pc_addr(context);
650 #endif
651 #ifdef LISP_FEATURE_SPARC
652     *os_context_register_addr(context,reg_CODE) = 
653         fun + FUN_POINTER_LOWTAG;
654 #endif
655 }
656
657 #ifdef LISP_FEATURE_SB_THREAD
658 void interrupt_thread_handler(int num, siginfo_t *info, void *v_context)
659 {
660     os_context_t *context = (os_context_t*)arch_os_get_context(&v_context);
661     struct thread *th=arch_os_get_current_thread();
662     struct interrupt_data *data=
663         th ? th->interrupt_data : global_interrupt_data;
664     if(maybe_defer_handler(interrupt_thread_handler,data,num,info,context)){
665         return ;
666     }
667     arrange_return_to_lisp_function(context,info->si_value.sival_int);
668 }
669 #endif
670
671 boolean handle_control_stack_guard_triggered(os_context_t *context,void *addr){
672     struct thread *th=arch_os_get_current_thread();
673     /* note the os_context hackery here.  When the signal handler returns, 
674      * it won't go back to what it was doing ... */
675     if(addr>=(void *)CONTROL_STACK_GUARD_PAGE(th) && 
676        addr<(void *)(CONTROL_STACK_GUARD_PAGE(th)+os_vm_page_size)) {
677         /* we hit the end of the control stack.  disable protection
678          * temporarily so the error handler has some headroom */
679         protect_control_stack_guard_page(th->pid,0L);
680         
681         arrange_return_to_lisp_function
682             (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
683         return 1;
684     }
685     else return 0;
686 }
687
688 #ifndef LISP_FEATURE_GENCGC
689 /* This function gets called from the SIGSEGV (for e.g. Linux or
690  * OpenBSD) or SIGBUS (for e.g. FreeBSD) handler. Here we check
691  * whether the signal was due to treading on the mprotect()ed zone -
692  * and if so, arrange for a GC to happen. */
693 extern unsigned long bytes_consed_between_gcs; /* gc-common.c */
694
695 boolean
696 interrupt_maybe_gc(int signal, siginfo_t *info, void *void_context)
697 {
698     os_context_t *context=(os_context_t *) void_context;
699     struct thread *th=arch_os_get_current_thread();
700     struct interrupt_data *data=
701         th ? th->interrupt_data : global_interrupt_data;
702
703     if(!foreign_function_call_active && gc_trigger_hit(signal, info, context)){
704         clear_auto_gc_trigger();
705         if(!maybe_defer_handler
706            (interrupt_maybe_gc_int,data,signal,info,void_context))
707             interrupt_maybe_gc_int(signal,info,void_context);
708         return 1;
709     }
710     return 0;
711 }
712
713 #endif
714
715 /* this is also used by gencgc, in alloc() */
716 boolean
717 interrupt_maybe_gc_int(int signal, siginfo_t *info, void *void_context)
718 {
719     sigset_t new;
720     os_context_t *context=(os_context_t *) void_context;
721     fake_foreign_function_call(context);
722     /* SUB-GC may return without GCing if *GC-INHIBIT* is set, in
723      * which case we will be running with no gc trigger barrier
724      * thing for a while.  But it shouldn't be long until the end
725      * of WITHOUT-GCING. */
726
727     sigemptyset(&new);
728     sigaddset_blockable(&new);
729     /* enable signals before calling into Lisp */
730     sigprocmask(SIG_UNBLOCK,&new,0);
731     funcall0(SymbolFunction(SUB_GC));
732     undo_fake_foreign_function_call(context);
733     return 1;
734 }
735
736 \f
737 /*
738  * noise to install handlers
739  */
740
741 void
742 undoably_install_low_level_interrupt_handler (int signal,
743                                               void handler(int,
744                                                            siginfo_t*,
745                                                            void*))
746 {
747     struct sigaction sa;
748     struct thread *th=arch_os_get_current_thread();
749     struct interrupt_data *data=
750         th ? th->interrupt_data : global_interrupt_data;
751
752     if (0 > signal || signal >= NSIG) {
753         lose("bad signal number %d", signal);
754     }
755
756     sa.sa_sigaction = handler;
757     sigemptyset(&sa.sa_mask);
758     sigaddset_blockable(&sa.sa_mask);
759     sa.sa_flags = SA_SIGINFO | SA_RESTART;
760 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
761     if((signal==SIG_MEMORY_FAULT) 
762 #ifdef SIG_INTERRUPT_THREAD
763        || (signal==SIG_INTERRUPT_THREAD)
764 #endif
765        )
766         sa.sa_flags|= SA_ONSTACK;
767 #endif
768     
769     sigaction(signal, &sa, NULL);
770     data->interrupt_low_level_handlers[signal] =
771         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
772 }
773
774 /* This is called from Lisp. */
775 unsigned long
776 install_handler(int signal, void handler(int, siginfo_t*, void*))
777 {
778     struct sigaction sa;
779     sigset_t old, new;
780     union interrupt_handler oldhandler;
781     struct thread *th=arch_os_get_current_thread();
782     struct interrupt_data *data=
783         th ? th->interrupt_data : global_interrupt_data;
784
785     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
786
787     sigemptyset(&new);
788     sigaddset(&new, signal);
789     sigprocmask(SIG_BLOCK, &new, &old);
790
791     sigemptyset(&new);
792     sigaddset_blockable(&new);
793
794     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%d\n",
795            interrupt_low_level_handlers[signal]));
796     if (data->interrupt_low_level_handlers[signal]==0) {
797         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
798             ARE_SAME_HANDLER(handler, SIG_IGN)) {
799             sa.sa_sigaction = handler;
800         } else if (sigismember(&new, signal)) {
801             sa.sa_sigaction = maybe_now_maybe_later;
802         } else {
803             sa.sa_sigaction = interrupt_handle_now_handler;
804         }
805
806         sigemptyset(&sa.sa_mask);
807         sigaddset_blockable(&sa.sa_mask);
808         sa.sa_flags = SA_SIGINFO | SA_RESTART;
809         sigaction(signal, &sa, NULL);
810     }
811
812     oldhandler = data->interrupt_handlers[signal];
813     data->interrupt_handlers[signal].c = handler;
814
815     sigprocmask(SIG_SETMASK, &old, 0);
816
817     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
818
819     return (unsigned long)oldhandler.lisp;
820 }
821
822 void
823 interrupt_init()
824 {
825     int i;
826     SHOW("entering interrupt_init()");
827     global_interrupt_data=calloc(sizeof(struct interrupt_data), 1);
828
829     /* Set up high level handler information. */
830     for (i = 0; i < NSIG; i++) {
831         global_interrupt_data->interrupt_handlers[i].c =
832             /* (The cast here blasts away the distinction between
833              * SA_SIGACTION-style three-argument handlers and
834              * signal(..)-style one-argument handlers, which is OK
835              * because it works to call the 1-argument form where the
836              * 3-argument form is expected.) */
837             (void (*)(int, siginfo_t*, void*))SIG_DFL;
838     }
839
840     SHOW("returning from interrupt_init()");
841 }