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