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