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