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