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