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