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