0.9.5.58:
[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 void
114 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 = 1; 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 static void (*interrupt_low_level_handlers[NSIG]) (int, siginfo_t*, void*);
148 union interrupt_handler interrupt_handlers[NSIG];
149
150 /* At the toplevel repl we routinely call this function.  The signal
151  * mask ought to be clear anyway most of the time, but may be non-zero
152  * if we were interrupted e.g. while waiting for a queue.  */
153
154 void reset_signal_mask(void)
155 {
156     sigset_t new;
157     sigemptyset(&new);
158     thread_sigmask(SIG_SETMASK,&new,0);
159 }
160
161 void block_blockable_signals(void)
162 {
163     thread_sigmask(SIG_BLOCK, &blockable_sigset, 0);
164 }
165
166 \f
167 /*
168  * utility routines used by various signal handlers
169  */
170
171 static void
172 build_fake_control_stack_frames(struct thread *th,os_context_t *context)
173 {
174 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
175
176     lispobj oldcont;
177
178     /* Build a fake stack frame or frames */
179
180     current_control_frame_pointer =
181         (lispobj *)(unsigned long)
182             (*os_context_register_addr(context, reg_CSP));
183     if ((lispobj *)(unsigned long)
184             (*os_context_register_addr(context, reg_CFP))
185         == current_control_frame_pointer) {
186         /* There is a small window during call where the callee's
187          * frame isn't built yet. */
188         if (lowtag_of(*os_context_register_addr(context, reg_CODE))
189             == FUN_POINTER_LOWTAG) {
190             /* We have called, but not built the new frame, so
191              * build it for them. */
192             current_control_frame_pointer[0] =
193                 *os_context_register_addr(context, reg_OCFP);
194             current_control_frame_pointer[1] =
195                 *os_context_register_addr(context, reg_LRA);
196             current_control_frame_pointer += 8;
197             /* Build our frame on top of it. */
198             oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
199         }
200         else {
201             /* We haven't yet called, build our frame as if the
202              * partial frame wasn't there. */
203             oldcont = (lispobj)(*os_context_register_addr(context, reg_OCFP));
204         }
205     }
206     /* We can't tell whether we are still in the caller if it had to
207      * allocate a stack frame due to stack arguments. */
208     /* This observation provoked some past CMUCL maintainer to ask
209      * "Can anything strange happen during return?" */
210     else {
211         /* normal case */
212         oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
213     }
214
215     current_control_stack_pointer = current_control_frame_pointer + 8;
216
217     current_control_frame_pointer[0] = oldcont;
218     current_control_frame_pointer[1] = NIL;
219     current_control_frame_pointer[2] =
220         (lispobj)(*os_context_register_addr(context, reg_CODE));
221 #endif
222 }
223
224 void
225 fake_foreign_function_call(os_context_t *context)
226 {
227     int context_index;
228     struct thread *thread=arch_os_get_current_thread();
229
230     /* context_index incrementing must not be interrupted */
231     check_blockables_blocked_or_lose();
232
233     /* Get current Lisp state from context. */
234 #ifdef reg_ALLOC
235     dynamic_space_free_pointer =
236         (lispobj *)(unsigned long)
237             (*os_context_register_addr(context, reg_ALLOC));
238 #if defined(LISP_FEATURE_ALPHA)
239     if ((long)dynamic_space_free_pointer & 1) {
240         lose("dead in fake_foreign_function_call, context = %x", context);
241     }
242 #endif
243 #endif
244 #ifdef reg_BSP
245     current_binding_stack_pointer =
246         (lispobj *)(unsigned long)
247             (*os_context_register_addr(context, reg_BSP));
248 #endif
249
250     build_fake_control_stack_frames(thread,context);
251
252     /* Do dynamic binding of the active interrupt context index
253      * and save the context in the context array. */
254     context_index =
255         fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,thread));
256
257     if (context_index >= MAX_INTERRUPTS) {
258         lose("maximum interrupt nesting depth (%d) exceeded", MAX_INTERRUPTS);
259     }
260
261     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,
262                   make_fixnum(context_index + 1),thread);
263
264     thread->interrupt_contexts[context_index] = context;
265
266     /* no longer in Lisp now */
267     foreign_function_call_active = 1;
268 }
269
270 /* blocks all blockable signals.  If you are calling from a signal handler,
271  * the usual signal mask will be restored from the context when the handler
272  * finishes.  Otherwise, be careful */
273
274 void
275 undo_fake_foreign_function_call(os_context_t *context)
276 {
277     struct thread *thread=arch_os_get_current_thread();
278     /* Block all blockable signals. */
279     block_blockable_signals();
280
281     /* going back into Lisp */
282     foreign_function_call_active = 0;
283
284     /* Undo dynamic binding of FREE_INTERRUPT_CONTEXT_INDEX */
285     unbind(thread);
286
287 #ifdef reg_ALLOC
288     /* Put the dynamic space free pointer back into the context. */
289     *os_context_register_addr(context, reg_ALLOC) =
290         (unsigned long) dynamic_space_free_pointer;
291 #endif
292 }
293
294 /* a handler for the signal caused by execution of a trap opcode
295  * signalling an internal error */
296 void
297 interrupt_internal_error(int signal, siginfo_t *info, os_context_t *context,
298                          boolean continuable)
299 {
300     lispobj context_sap;
301
302     fake_foreign_function_call(context);
303
304     if (!internal_errors_enabled) {
305         describe_internal_error(context);
306         /* There's no good way to recover from an internal error
307          * before the Lisp error handling mechanism is set up. */
308         lose("internal error too early in init, can't recover");
309     }
310
311     /* Allocate the SAP object while the interrupts are still
312      * disabled. */
313     context_sap = alloc_sap(context);
314
315     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
316
317     SHOW("in interrupt_internal_error");
318 #ifdef QSHOW
319     /* Display some rudimentary debugging information about the
320      * error, so that even if the Lisp error handler gets badly
321      * confused, we have a chance to determine what's going on. */
322     describe_internal_error(context);
323 #endif
324     funcall2(SymbolFunction(INTERNAL_ERROR), context_sap,
325              continuable ? T : NIL);
326
327     undo_fake_foreign_function_call(context); /* blocks signals again */
328     if (continuable)
329         arch_skip_instruction(context);
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 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
420     boolean were_in_lisp;
421 #endif
422     union interrupt_handler handler;
423     check_blockables_blocked_or_lose();
424     if (sigismember(&deferrable_sigset,signal))
425         check_interrupts_enabled_or_lose(context);
426
427 #ifdef LISP_FEATURE_LINUX
428     /* Under Linux on some architectures, we appear to have to restore
429        the FPU control word from the context, as after the signal is
430        delivered we appear to have a null FPU control word. */
431     os_restore_fp_control(context);
432 #endif
433     handler = interrupt_handlers[signal];
434
435     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
436         return;
437     }
438
439 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
440     were_in_lisp = !foreign_function_call_active;
441     if (were_in_lisp)
442 #endif
443     {
444         fake_foreign_function_call(context);
445     }
446
447     FSHOW_SIGNAL((stderr,
448                   "/entering interrupt_handle_now(%d, info, context)\n",
449                   signal));
450
451     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
452
453         /* This can happen if someone tries to ignore or default one
454          * of the signals we need for runtime support, and the runtime
455          * support decides to pass on it. */
456         lose("no handler for signal %d in interrupt_handle_now(..)", signal);
457
458     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
459         /* Once we've decided what to do about contexts in a
460          * return-elsewhere world (the original context will no longer
461          * be available; should we copy it or was nobody using it anyway?)
462          * then we should convert this to return-elsewhere */
463
464         /* CMUCL comment said "Allocate the SAPs while the interrupts
465          * are still disabled.".  I (dan, 2003.08.21) assume this is
466          * because we're not in pseudoatomic and allocation shouldn't
467          * be interrupted.  In which case it's no longer an issue as
468          * all our allocation from C now goes through a PA wrapper,
469          * but still, doesn't hurt.
470          *
471          * Yeah, but non-gencgc platforms that don't really wrap
472          * allocation in PA. MG - 2005-08-29  */
473
474         lispobj info_sap,context_sap = alloc_sap(context);
475         info_sap = alloc_sap(info);
476         /* Leave deferrable signals blocked, the handler itself will
477          * allow signals again when it sees fit. */
478 #ifdef LISP_FEATURE_SB_THREAD
479         {
480             sigset_t unblock;
481             sigemptyset(&unblock);
482             sigaddset(&unblock, SIG_STOP_FOR_GC);
483             thread_sigmask(SIG_UNBLOCK, &unblock, 0);
484         }
485 #endif
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,signal,info,context))
619         return;
620     interrupt_handle_now(signal, info, context);
621 #ifdef LISP_FEATURE_DARWIN
622     /* Work around G5 bug */
623     DARWIN_FIX_CONTEXT(context);
624 #endif
625 }
626
627 static void
628 low_level_interrupt_handle_now(int signal, siginfo_t *info, void *void_context)
629 {
630     os_context_t *context = (os_context_t*)void_context;
631
632 #ifdef LISP_FEATURE_LINUX
633     os_restore_fp_control(context);
634 #endif
635     check_blockables_blocked_or_lose();
636     check_interrupts_enabled_or_lose(context);
637     interrupt_low_level_handlers[signal](signal, info, void_context);
638 #ifdef LISP_FEATURE_DARWIN
639     /* Work around G5 bug */
640     DARWIN_FIX_CONTEXT(context);
641 #endif
642 }
643
644 static void
645 low_level_maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
646 {
647     os_context_t *context = arch_os_get_context(&void_context);
648     struct thread *thread=arch_os_get_current_thread();
649     struct interrupt_data *data=thread->interrupt_data;
650 #ifdef LISP_FEATURE_LINUX
651     os_restore_fp_control(context);
652 #endif
653     if(maybe_defer_handler(low_level_interrupt_handle_now,data,
654                            signal,info,context))
655         return;
656     low_level_interrupt_handle_now(signal, info, context);
657 #ifdef LISP_FEATURE_DARWIN
658     /* Work around G5 bug */
659     DARWIN_FIX_CONTEXT(context);
660 #endif
661 }
662
663 #ifdef LISP_FEATURE_SB_THREAD
664
665 void
666 sig_stop_for_gc_handler(int signal, siginfo_t *info, void *void_context)
667 {
668     os_context_t *context = arch_os_get_context(&void_context);
669     struct thread *thread=arch_os_get_current_thread();
670     sigset_t ss;
671
672     if ((arch_pseudo_atomic_atomic(context) ||
673          SymbolValue(GC_INHIBIT,thread) != NIL)) {
674         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
675         if (SymbolValue(GC_INHIBIT,thread) == NIL)
676             arch_set_pseudo_atomic_interrupted(context);
677         FSHOW_SIGNAL((stderr,"thread=%lu sig_stop_for_gc deferred\n",
678                       thread->os_thread));
679     } else {
680         /* need the context stored so it can have registers scavenged */
681         fake_foreign_function_call(context);
682
683         sigfillset(&ss); /* Block everything. */
684         thread_sigmask(SIG_BLOCK,&ss,0);
685
686         /* The GC can't tell if a thread is a zombie, so this would be a
687          * good time to let the kernel reap any of our children in that
688          * awful state, to stop them from being waited for indefinitely.
689          * Userland reaping is done later when GC is finished  */
690         if(thread->state!=STATE_RUNNING) {
691             lose("sig_stop_for_gc_handler: wrong thread state: %ld\n",
692                  fixnum_value(thread->state));
693         }
694         thread->state=STATE_SUSPENDED;
695         FSHOW_SIGNAL((stderr,"thread=%lu suspended\n",thread->os_thread));
696
697         sigemptyset(&ss); sigaddset(&ss,SIG_STOP_FOR_GC);
698         /* It is possible to get SIGCONT (and probably other
699          * non-blockable signals) here. */
700         while (sigwaitinfo(&ss,0) != SIG_STOP_FOR_GC);
701         FSHOW_SIGNAL((stderr,"thread=%lu resumed\n",thread->os_thread));
702         if(thread->state!=STATE_RUNNING) {
703             lose("sig_stop_for_gc_handler: wrong thread state on wakeup: %ld\n",
704                  fixnum_value(thread->state));
705         }
706
707         undo_fake_foreign_function_call(context);
708     }
709 }
710 #endif
711
712 void
713 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
714 {
715     os_context_t *context = arch_os_get_context(&void_context);
716     interrupt_handle_now(signal, info, context);
717 #ifdef LISP_FEATURE_DARWIN
718     DARWIN_FIX_CONTEXT(context);
719 #endif
720 }
721
722 /*
723  * stuff to detect and handle hitting the GC trigger
724  */
725
726 #ifndef LISP_FEATURE_GENCGC
727 /* since GENCGC has its own way to record trigger */
728 static boolean
729 gc_trigger_hit(int signal, siginfo_t *info, os_context_t *context)
730 {
731     if (current_auto_gc_trigger == NULL)
732         return 0;
733     else{
734         void *badaddr=arch_get_bad_addr(signal,info,context);
735         return (badaddr >= (void *)current_auto_gc_trigger &&
736                 badaddr <((void *)current_dynamic_space + DYNAMIC_SPACE_SIZE));
737     }
738 }
739 #endif
740
741 /* manipulate the signal context and stack such that when the handler
742  * returns, it will call function instead of whatever it was doing
743  * previously
744  */
745
746 #if (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
747 int *context_eflags_addr(os_context_t *context);
748 #endif
749
750 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
751 extern void post_signal_tramp(void);
752 void arrange_return_to_lisp_function(os_context_t *context, lispobj function)
753 {
754 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
755     void * fun=native_pointer(function);
756     void *code = &(((struct simple_fun *) fun)->code);
757 #endif
758
759     /* Build a stack frame showing `interrupted' so that the
760      * user's backtrace makes (as much) sense (as usual) */
761
762     /* FIXME: what about restoring fp state? */
763     /* FIXME: what about restoring errno? */
764 #ifdef LISP_FEATURE_X86
765     /* Suppose the existence of some function that saved all
766      * registers, called call_into_lisp, then restored GP registers and
767      * returned.  It would look something like this:
768
769      push   ebp
770      mov    ebp esp
771      pushfl
772      pushal
773      push   $0
774      push   $0
775      pushl  {address of function to call}
776      call   0x8058db0 <call_into_lisp>
777      addl   $12,%esp
778      popal
779      popfl
780      leave
781      ret
782
783      * What we do here is set up the stack that call_into_lisp would
784      * expect to see if it had been called by this code, and frob the
785      * signal context so that signal return goes directly to call_into_lisp,
786      * and when that function (and the lisp function it invoked) returns,
787      * it returns to the second half of this imaginary function which
788      * restores all registers and returns to C
789
790      * For this to work, the latter part of the imaginary function
791      * must obviously exist in reality.  That would be post_signal_tramp
792      */
793
794     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
795
796     /* return address for call_into_lisp: */
797     *(sp-15) = (u32)post_signal_tramp;
798     *(sp-14) = function;        /* args for call_into_lisp : function*/
799     *(sp-13) = 0;               /*                           arg array */
800     *(sp-12) = 0;               /*                           no. args */
801     /* this order matches that used in POPAD */
802     *(sp-11)=*os_context_register_addr(context,reg_EDI);
803     *(sp-10)=*os_context_register_addr(context,reg_ESI);
804
805     *(sp-9)=*os_context_register_addr(context,reg_ESP)-8;
806     /* POPAD ignores the value of ESP:  */
807     *(sp-8)=0;
808     *(sp-7)=*os_context_register_addr(context,reg_EBX);
809
810     *(sp-6)=*os_context_register_addr(context,reg_EDX);
811     *(sp-5)=*os_context_register_addr(context,reg_ECX);
812     *(sp-4)=*os_context_register_addr(context,reg_EAX);
813     *(sp-3)=*context_eflags_addr(context);
814     *(sp-2)=*os_context_register_addr(context,reg_EBP);
815     *(sp-1)=*os_context_pc_addr(context);
816
817 #elif defined(LISP_FEATURE_X86_64)
818     u64 *sp=(u64 *)*os_context_register_addr(context,reg_RSP);
819     /* return address for call_into_lisp: */
820     *(sp-18) = (u64)post_signal_tramp;
821
822     *(sp-17)=*os_context_register_addr(context,reg_R15);
823     *(sp-16)=*os_context_register_addr(context,reg_R14);
824     *(sp-15)=*os_context_register_addr(context,reg_R13);
825     *(sp-14)=*os_context_register_addr(context,reg_R12);
826     *(sp-13)=*os_context_register_addr(context,reg_R11);
827     *(sp-12)=*os_context_register_addr(context,reg_R10);
828     *(sp-11)=*os_context_register_addr(context,reg_R9);
829     *(sp-10)=*os_context_register_addr(context,reg_R8);
830     *(sp-9)=*os_context_register_addr(context,reg_RDI);
831     *(sp-8)=*os_context_register_addr(context,reg_RSI);
832     /* skip RBP and RSP */
833     *(sp-7)=*os_context_register_addr(context,reg_RBX);
834     *(sp-6)=*os_context_register_addr(context,reg_RDX);
835     *(sp-5)=*os_context_register_addr(context,reg_RCX);
836     *(sp-4)=*os_context_register_addr(context,reg_RAX);
837     *(sp-3)=*context_eflags_addr(context);
838     *(sp-2)=*os_context_register_addr(context,reg_RBP);
839     *(sp-1)=*os_context_pc_addr(context);
840
841     *os_context_register_addr(context,reg_RDI) =
842         (os_context_register_t)function; /* function */
843     *os_context_register_addr(context,reg_RSI) = 0;        /* arg. array */
844     *os_context_register_addr(context,reg_RDX) = 0;        /* no. args */
845 #else
846     struct thread *th=arch_os_get_current_thread();
847     build_fake_control_stack_frames(th,context);
848 #endif
849
850 #ifdef LISP_FEATURE_X86
851     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
852     *os_context_register_addr(context,reg_ECX) = 0;
853     *os_context_register_addr(context,reg_EBP) = (os_context_register_t)(sp-2);
854 #ifdef __NetBSD__
855     *os_context_register_addr(context,reg_UESP) =
856         (os_context_register_t)(sp-15);
857 #else
858     *os_context_register_addr(context,reg_ESP) = (os_context_register_t)(sp-15);
859 #endif
860 #elif defined(LISP_FEATURE_X86_64)
861     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
862     *os_context_register_addr(context,reg_RCX) = 0;
863     *os_context_register_addr(context,reg_RBP) = (os_context_register_t)(sp-2);
864     *os_context_register_addr(context,reg_RSP) = (os_context_register_t)(sp-18);
865 #else
866     /* this much of the calling convention is common to all
867        non-x86 ports */
868     *os_context_pc_addr(context) = (os_context_register_t)(unsigned long)code;
869     *os_context_register_addr(context,reg_NARGS) = 0;
870     *os_context_register_addr(context,reg_LIP) =
871         (os_context_register_t)(unsigned long)code;
872     *os_context_register_addr(context,reg_CFP) =
873         (os_context_register_t)(unsigned long)current_control_frame_pointer;
874 #endif
875 #ifdef ARCH_HAS_NPC_REGISTER
876     *os_context_npc_addr(context) =
877         4 + *os_context_pc_addr(context);
878 #endif
879 #ifdef LISP_FEATURE_SPARC
880     *os_context_register_addr(context,reg_CODE) =
881         (os_context_register_t)(fun + FUN_POINTER_LOWTAG);
882 #endif
883 }
884
885 #ifdef LISP_FEATURE_SB_THREAD
886
887 /* FIXME: this function can go away when all lisp handlers are invoked
888  * via arrange_return_to_lisp_function. */
889 void interrupt_thread_handler(int num, siginfo_t *info, void *v_context)
890 {
891     os_context_t *context = (os_context_t*)arch_os_get_context(&v_context);
892     /* let the handler enable interrupts again when it sees fit */
893     sigaddset_deferrable(os_context_sigmask_addr(context));
894     arrange_return_to_lisp_function(context, SymbolFunction(RUN_INTERRUPTION));
895 }
896
897 #endif
898
899 /* KLUDGE: Theoretically the approach we use for undefined alien
900  * variables should work for functions as well, but on PPC/Darwin
901  * we get bus error at bogus addresses instead, hence this workaround,
902  * that has the added benefit of automatically discriminating between
903  * functions and variables.
904  */
905 void undefined_alien_function() {
906     funcall0(SymbolFunction(UNDEFINED_ALIEN_FUNCTION_ERROR));
907 }
908
909 boolean handle_guard_page_triggered(os_context_t *context,os_vm_address_t addr)
910 {
911     struct thread *th=arch_os_get_current_thread();
912
913     /* note the os_context hackery here.  When the signal handler returns,
914      * it won't go back to what it was doing ... */
915     if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
916        addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
917         /* We hit the end of the control stack: disable guard page
918          * protection so the error handler has some headroom, protect the
919          * previous page so that we can catch returns from the guard page
920          * and restore it. */
921         protect_control_stack_guard_page(0);
922         protect_control_stack_return_guard_page(1);
923
924         arrange_return_to_lisp_function
925             (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
926         return 1;
927     }
928     else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
929             addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
930         /* We're returning from the guard page: reprotect it, and
931          * unprotect this one. This works even if we somehow missed
932          * the return-guard-page, and hit it on our way to new
933          * exhaustion instead. */
934         protect_control_stack_guard_page(1);
935         protect_control_stack_return_guard_page(0);
936         return 1;
937     }
938     else if (addr >= undefined_alien_address &&
939              addr < undefined_alien_address + os_vm_page_size) {
940         arrange_return_to_lisp_function
941           (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
942         return 1;
943     }
944     else return 0;
945 }
946
947 #ifndef LISP_FEATURE_GENCGC
948 /* This function gets called from the SIGSEGV (for e.g. Linux, NetBSD, &
949  * OpenBSD) or SIGBUS (for e.g. FreeBSD) handler. Here we check
950  * whether the signal was due to treading on the mprotect()ed zone -
951  * and if so, arrange for a GC to happen. */
952 extern unsigned long bytes_consed_between_gcs; /* gc-common.c */
953
954 boolean
955 interrupt_maybe_gc(int signal, siginfo_t *info, void *void_context)
956 {
957     os_context_t *context=(os_context_t *) void_context;
958
959     if(!foreign_function_call_active && gc_trigger_hit(signal, info, context)){
960         struct thread *thread=arch_os_get_current_thread();
961         clear_auto_gc_trigger();
962         /* Don't flood the system with interrupts if the need to gc is
963          * already noted. This can happen for example when SUB-GC
964          * allocates or after a gc triggered in a WITHOUT-GCING. */
965         if (SymbolValue(GC_PENDING,thread) == NIL) {
966             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
967                 if (arch_pseudo_atomic_atomic(context)) {
968                     /* set things up so that GC happens when we finish
969                      * the PA section */
970                     SetSymbolValue(GC_PENDING,T,thread);
971                     arch_set_pseudo_atomic_interrupted(context);
972                 } else {
973                     interrupt_maybe_gc_int(signal,info,void_context);
974                 }
975             } else {
976                 SetSymbolValue(GC_PENDING,T,thread);
977             }
978         }
979         return 1;
980     }
981     return 0;
982 }
983
984 #endif
985
986 /* this is also used by gencgc, in alloc() */
987 boolean
988 interrupt_maybe_gc_int(int signal, siginfo_t *info, void *void_context)
989 {
990     os_context_t *context=(os_context_t *) void_context;
991     struct thread *thread=arch_os_get_current_thread();
992
993     fake_foreign_function_call(context);
994
995     /* SUB-GC may return without GCing if *GC-INHIBIT* is set, in
996      * which case we will be running with no gc trigger barrier
997      * thing for a while.  But it shouldn't be long until the end
998      * of WITHOUT-GCING.
999      *
1000      * FIXME: It would be good to protect the end of dynamic space
1001      * and signal a storage condition from there.
1002      */
1003
1004     /* Restore the signal mask from the interrupted context before
1005      * calling into Lisp if interrupts are enabled. Why not always?
1006      *
1007      * Suppose there is a WITHOUT-INTERRUPTS block far, far out. If an
1008      * interrupt hits while in SUB-GC, it is deferred and the
1009      * os_context_sigmask of that interrupt is set to block further
1010      * deferrable interrupts (until the first one is
1011      * handled). Unfortunately, that context refers to this place and
1012      * when we return from here the signals will not be blocked.
1013      *
1014      * A kludgy alternative is to propagate the sigmask change to the
1015      * outer context.
1016      */
1017     if(SymbolValue(INTERRUPTS_ENABLED,thread)!=NIL)
1018         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
1019 #ifdef LISP_FEATURE_SB_THREAD
1020     else {
1021         sigset_t new;
1022         sigemptyset(&new);
1023         sigaddset(&new,SIG_STOP_FOR_GC);
1024         thread_sigmask(SIG_UNBLOCK,&new,0);
1025     }
1026 #endif
1027     funcall0(SymbolFunction(SUB_GC));
1028
1029     undo_fake_foreign_function_call(context);
1030     return 1;
1031 }
1032
1033 #ifndef LISP_FEATURE_SIGACTION_NODEFER_WORKS
1034
1035 /* In Linux 2.4 synchronous signals (sigtrap & co) can be delivered if
1036  * they are blocked, in Linux 2.6 the default handler is invoked
1037  * instead that usually coredumps. One might hastily think that adding
1038  * SA_NODEFER helps, but until ~2.6.13 if SA_NODEFER is specified then
1039  * the whole sa_mask is ignored and instead of not adding the signal
1040  * in question to the mask. That means if it's not blockable the
1041  * signal must be unblocked at the beginning of signal handlers.
1042  */
1043 void
1044 unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1045 {
1046     sigset_t unblock;
1047     sigemptyset(&unblock);
1048     sigaddset(&unblock, signal);
1049     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1050     (*interrupt_low_level_handlers[signal])(signal, info, void_context);
1051 }
1052
1053 #endif
1054
1055 \f
1056 /*
1057  * noise to install handlers
1058  */
1059
1060 void
1061 undoably_install_low_level_interrupt_handler (int signal,
1062                                               void handler(int,
1063                                                            siginfo_t*,
1064                                                            void*))
1065 {
1066     struct sigaction sa;
1067
1068     if (0 > signal || signal >= NSIG) {
1069         lose("bad signal number %d", signal);
1070     }
1071
1072     if (sigismember(&deferrable_sigset,signal))
1073         sa.sa_sigaction = low_level_maybe_now_maybe_later;
1074 #ifndef LISP_FEATURE_SIGACTION_NODEFER_WORKS
1075     else if (!sigismember(&blockable_sigset, signal))
1076         sa.sa_sigaction = unblock_me_trampoline;
1077 #endif
1078     else
1079         sa.sa_sigaction = handler;
1080
1081     sigcopyset(&sa.sa_mask, &blockable_sigset);
1082     sa.sa_flags = SA_SIGINFO | SA_RESTART
1083 #ifdef LISP_FEATURE_SIGACTION_NODEFER_WORKS
1084             | SA_NODEFER
1085 #endif
1086         ;
1087 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1088     if((signal==SIG_MEMORY_FAULT)
1089 #ifdef SIG_INTERRUPT_THREAD
1090        || (signal==SIG_INTERRUPT_THREAD)
1091 #endif
1092        )
1093         sa.sa_flags |= SA_ONSTACK;
1094 #endif
1095
1096     sigaction(signal, &sa, NULL);
1097     interrupt_low_level_handlers[signal] =
1098         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
1099 }
1100
1101 /* This is called from Lisp. */
1102 unsigned long
1103 install_handler(int signal, void handler(int, siginfo_t*, void*))
1104 {
1105     struct sigaction sa;
1106     sigset_t old, new;
1107     union interrupt_handler oldhandler;
1108
1109     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
1110
1111     sigemptyset(&new);
1112     sigaddset(&new, signal);
1113     thread_sigmask(SIG_BLOCK, &new, &old);
1114
1115     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%x\n",
1116            (unsigned int)interrupt_low_level_handlers[signal]));
1117     if (interrupt_low_level_handlers[signal]==0) {
1118         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
1119             ARE_SAME_HANDLER(handler, SIG_IGN)) {
1120             sa.sa_sigaction = handler;
1121         } else if (sigismember(&deferrable_sigset, signal)) {
1122             sa.sa_sigaction = maybe_now_maybe_later;
1123         } else {
1124             sa.sa_sigaction = interrupt_handle_now_handler;
1125         }
1126
1127         sigcopyset(&sa.sa_mask, &blockable_sigset);
1128         sa.sa_flags = SA_SIGINFO | SA_RESTART
1129 #ifdef LISP_FEATURE_SIGACTION_NODEFER_WORKS
1130             | SA_NODEFER
1131 #endif
1132             ;
1133         sigaction(signal, &sa, NULL);
1134     }
1135
1136     oldhandler = interrupt_handlers[signal];
1137     interrupt_handlers[signal].c = handler;
1138
1139     thread_sigmask(SIG_SETMASK, &old, 0);
1140
1141     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
1142
1143     return (unsigned long)oldhandler.lisp;
1144 }
1145
1146 void
1147 interrupt_init()
1148 {
1149     int i;
1150     SHOW("entering interrupt_init()");
1151     sigemptyset(&deferrable_sigset);
1152     sigemptyset(&blockable_sigset);
1153     sigaddset_deferrable(&deferrable_sigset);
1154     sigaddset_blockable(&blockable_sigset);
1155
1156     /* Set up high level handler information. */
1157     for (i = 0; i < NSIG; i++) {
1158         interrupt_handlers[i].c =
1159             /* (The cast here blasts away the distinction between
1160              * SA_SIGACTION-style three-argument handlers and
1161              * signal(..)-style one-argument handlers, which is OK
1162              * because it works to call the 1-argument form where the
1163              * 3-argument form is expected.) */
1164             (void (*)(int, siginfo_t*, void*))SIG_DFL;
1165     }
1166
1167     SHOW("returning from interrupt_init()");
1168 }