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