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