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