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