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