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