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