0.9.4.53:
[sbcl.git] / src / runtime / interrupt.c
1 /*
2  * interrupt-handling magic
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15
16
17 /* As far as I can tell, what's going on here is:
18  *
19  * In the case of most signals, when Lisp asks us to handle the
20  * signal, the outermost handler (the one actually passed to UNIX) is
21  * either interrupt_handle_now(..) or maybe_now_maybe_later(..).
22  * In that case, the Lisp-level handler is stored in interrupt_handlers[..]
23  * and interrupt_low_level_handlers[..] is cleared.
24  *
25  * However, some signals need special handling, e.g.
26  *
27  * o the SIGSEGV (for e.g. Linux) or SIGBUS (for e.g. FreeBSD) used by the
28  *   garbage collector to detect violations of write protection,
29  *   because some cases of such signals (e.g. GC-related violations of
30  *   write protection) are handled at C level and never passed on to
31  *   Lisp. For such signals, we still store any Lisp-level handler
32  *   in interrupt_handlers[..], but for the outermost handle we use
33  *   the value from interrupt_low_level_handlers[..], instead of the
34  *   ordinary interrupt_handle_now(..) or interrupt_handle_later(..).
35  *
36  * o the SIGTRAP (Linux/Alpha) which Lisp code uses to handle breakpoints,
37  *   pseudo-atomic sections, and some classes of error (e.g. "function
38  *   not defined").  This never goes anywhere near the Lisp handlers at all.
39  *   See runtime/alpha-arch.c and code/signal.lisp
40  *
41  * - WHN 20000728, dan 20010128 */
42
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <signal.h>
48 #include <sys/types.h>
49 #include <sys/wait.h>
50 #include <errno.h>
51
52 #include "sbcl.h"
53 #include "runtime.h"
54 #include "arch.h"
55 #include "os.h"
56 #include "interrupt.h"
57 #include "globals.h"
58 #include "lispregs.h"
59 #include "validate.h"
60 #include "monitor.h"
61 #include "gc.h"
62 #include "alloc.h"
63 #include "dynbind.h"
64 #include "interr.h"
65 #include "genesis/fdefn.h"
66 #include "genesis/simple-fun.h"
67 #include "genesis/cons.h"
68
69
70
71 void run_deferred_handler(struct interrupt_data *data, void *v_context) ;
72 static void store_signal_data_for_later (struct interrupt_data *data,
73                                          void *handler, int signal,
74                                          siginfo_t *info,
75                                          os_context_t *context);
76 boolean interrupt_maybe_gc_int(int signal, siginfo_t *info, void *v_context);
77
78 void sigaddset_deferrable(sigset_t *s)
79 {
80     sigaddset(s, SIGHUP);
81     sigaddset(s, SIGINT);
82     sigaddset(s, SIGQUIT);
83     sigaddset(s, SIGPIPE);
84     sigaddset(s, SIGALRM);
85     sigaddset(s, SIGURG);
86     sigaddset(s, SIGTSTP);
87     sigaddset(s, SIGCHLD);
88     sigaddset(s, SIGIO);
89     sigaddset(s, SIGXCPU);
90     sigaddset(s, SIGXFSZ);
91     sigaddset(s, SIGVTALRM);
92     sigaddset(s, SIGPROF);
93     sigaddset(s, SIGWINCH);
94     sigaddset(s, SIGUSR1);
95     sigaddset(s, SIGUSR2);
96 #ifdef LISP_FEATURE_SB_THREAD
97     sigaddset(s, SIG_INTERRUPT_THREAD);
98 #endif
99 }
100
101 void sigaddset_blockable(sigset_t *s)
102 {
103     sigaddset_deferrable(s);
104 #ifdef LISP_FEATURE_SB_THREAD
105     sigaddset(s, SIG_STOP_FOR_GC);
106 #endif
107 }
108
109 /* initialized in interrupt_init */
110 static sigset_t deferrable_sigset;
111 static sigset_t blockable_sigset;
112
113 inline static void check_blockables_blocked_or_lose()
114 {
115     /* Get the current sigmask, by blocking the empty set. */
116     sigset_t empty,current;
117     int i;
118     sigemptyset(&empty);
119     thread_sigmask(SIG_BLOCK, &empty, &current);
120     for(i=0;i<NSIG;i++) {
121         if (sigismember(&blockable_sigset, i) && !sigismember(&current, i))
122             lose("blockable signal %d not blocked",i);
123     }
124 }
125
126 inline static void check_interrupts_enabled_or_lose(os_context_t *context)
127 {
128     struct thread *thread=arch_os_get_current_thread();
129     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
130         lose("interrupts not enabled");
131     if (
132 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
133         (!foreign_function_call_active) &&
134 #endif
135         arch_pseudo_atomic_atomic(context))
136         lose ("in pseudo atomic section");
137 }
138
139 /* When we catch an internal error, should we pass it back to Lisp to
140  * be handled in a high-level way? (Early in cold init, the answer is
141  * 'no', because Lisp is still too brain-dead to handle anything.
142  * After sufficient initialization has been completed, the answer
143  * becomes 'yes'.) */
144 boolean internal_errors_enabled = 0;
145
146 static void (*interrupt_low_level_handlers[NSIG]) (int, siginfo_t*, void*);
147 union interrupt_handler interrupt_handlers[NSIG];
148
149 /* At the toplevel repl we routinely call this function.  The signal
150  * mask ought to be clear anyway most of the time, but may be non-zero
151  * if we were interrupted e.g. while waiting for a queue.  */
152
153 void reset_signal_mask ()
154 {
155     sigset_t new;
156     sigemptyset(&new);
157     thread_sigmask(SIG_SETMASK,&new,0);
158 }
159
160 void block_blockable_signals ()
161 {
162     sigset_t block;
163     sigemptyset(&block);
164     sigaddset_blockable(&block);
165     thread_sigmask(SIG_BLOCK, &block, 0);
166 }
167
168 \f
169 /*
170  * utility routines used by various signal handlers
171  */
172
173 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 = 0;
303
304     check_blockables_blocked_or_lose();
305     fake_foreign_function_call(context);
306
307     /* Allocate the SAP object while the interrupts are still
308      * disabled. */
309     if (internal_errors_enabled) {
310         context_sap = alloc_sap(context);
311     }
312
313     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
314
315     if (internal_errors_enabled) {
316         SHOW("in interrupt_internal_error");
317 #ifdef QSHOW
318         /* Display some rudimentary debugging information about the
319          * error, so that even if the Lisp error handler gets badly
320          * confused, we have a chance to determine what's going on. */
321         describe_internal_error(context);
322 #endif
323         funcall2(SymbolFunction(INTERNAL_ERROR), context_sap,
324                  continuable ? T : NIL);
325     } else {
326         describe_internal_error(context);
327         /* There's no good way to recover from an internal error
328          * before the Lisp error handling mechanism is set up. */
329         lose("internal error too early in init, can't recover");
330     }
331     undo_fake_foreign_function_call(context); /* blocks signals again */
332     if (continuable) {
333         arch_skip_instruction(context);
334     }
335 }
336
337 void
338 interrupt_handle_pending(os_context_t *context)
339 {
340     struct thread *thread;
341     struct interrupt_data *data;
342
343     check_blockables_blocked_or_lose();
344
345     thread=arch_os_get_current_thread();
346     data=thread->interrupt_data;
347
348     if (SymbolValue(GC_INHIBIT,thread)==NIL) {
349 #ifdef LISP_FEATURE_SB_THREAD
350         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL) {
351             /* another thread has already initiated a gc, this attempt
352              * might as well be cancelled */
353             SetSymbolValue(GC_PENDING,NIL,thread);
354             SetSymbolValue(STOP_FOR_GC_PENDING,NIL,thread);
355             sig_stop_for_gc_handler(SIG_STOP_FOR_GC,NULL,context);
356         } else
357 #endif
358         if (SymbolValue(GC_PENDING,thread) != NIL) {
359             /* GC_PENDING is cleared in SUB-GC, or if another thread
360              * is doing a gc already we will get a SIG_STOP_FOR_GC and
361              * that will clear it. */
362             interrupt_maybe_gc_int(0,NULL,context);
363         }
364         check_blockables_blocked_or_lose();
365     }
366
367     /* we may be here only to do the gc stuff, if interrupts are
368      * enabled run the pending handler */
369     if (!((SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) ||
370           (
371 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
372            (!foreign_function_call_active) &&
373 #endif
374            arch_pseudo_atomic_atomic(context)))) {
375
376         /* There may be no pending handler, because it was only a gc
377          * that had to be executed or because pseudo atomic triggered
378          * twice for a single interrupt. For the interested reader,
379          * that may happen if an interrupt hits after the interrupted
380          * flag is cleared but before pseduo-atomic is set and a
381          * pseudo atomic is interrupted in that interrupt. */
382         if (data->pending_handler) {
383
384             /* If we're here as the result of a pseudo-atomic as opposed
385              * to WITHOUT-INTERRUPTS, then INTERRUPT_PENDING is already
386              * NIL, because maybe_defer_handler sets
387              * PSEUDO_ATOMIC_INTERRUPTED only if interrupts are enabled.*/
388             SetSymbolValue(INTERRUPT_PENDING, NIL,thread);
389
390             /* restore the saved signal mask from the original signal (the
391              * one that interrupted us during the critical section) into the
392              * os_context for the signal we're currently in the handler for.
393              * This should ensure that when we return from the handler the
394              * blocked signals are unblocked */
395             sigcopyset(os_context_sigmask_addr(context), &data->pending_mask);
396
397             sigemptyset(&data->pending_mask);
398             /* This will break on sparc linux: the deferred handler really wants
399              * to be called with a void_context */
400             run_deferred_handler(data,(void *)context);
401         }
402     }
403 }
404 \f
405 /*
406  * the two main signal handlers:
407  *   interrupt_handle_now(..)
408  *   maybe_now_maybe_later(..)
409  *
410  * to which we have added interrupt_handle_now_handler(..).  Why?
411  * Well, mostly because the SPARC/Linux platform doesn't quite do
412  * signals the way we want them done.  The third argument in the
413  * handler isn't filled in by the kernel properly, so we fix it up
414  * ourselves in the arch_os_get_context(..) function; however, we only
415  * want to do this when we first hit the handler, and not when
416  * interrupt_handle_now(..) is being called from some other handler
417  * (when the fixup will already have been done). -- CSR, 2002-07-23
418  */
419
420 void
421 interrupt_handle_now(int signal, siginfo_t *info, void *void_context)
422 {
423     os_context_t *context = (os_context_t*)void_context;
424 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
425     boolean were_in_lisp;
426 #endif
427     union interrupt_handler handler;
428     check_blockables_blocked_or_lose();
429     if (sigismember(&deferrable_sigset,signal))
430         check_interrupts_enabled_or_lose(context);
431
432 #ifdef LISP_FEATURE_LINUX
433     /* Under Linux on some architectures, we appear to have to restore
434        the FPU control word from the context, as after the signal is
435        delivered we appear to have a null FPU control word. */
436     os_restore_fp_control(context);
437 #endif
438     handler = interrupt_handlers[signal];
439
440     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
441         return;
442     }
443
444 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
445     were_in_lisp = !foreign_function_call_active;
446     if (were_in_lisp)
447 #endif
448     {
449         fake_foreign_function_call(context);
450     }
451
452     FSHOW_SIGNAL((stderr,
453                   "/entering interrupt_handle_now(%d, info, context)\n",
454                   signal));
455
456     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
457
458         /* This can happen if someone tries to ignore or default one
459          * of the signals we need for runtime support, and the runtime
460          * support decides to pass on it. */
461         lose("no handler for signal %d in interrupt_handle_now(..)", signal);
462
463     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
464         /* Once we've decided what to do about contexts in a
465          * return-elsewhere world (the original context will no longer
466          * be available; should we copy it or was nobody using it anyway?)
467          * then we should convert this to return-elsewhere */
468
469         /* CMUCL comment said "Allocate the SAPs while the interrupts
470          * are still disabled.".  I (dan, 2003.08.21) assume this is
471          * because we're not in pseudoatomic and allocation shouldn't
472          * be interrupted.  In which case it's no longer an issue as
473          * all our allocation from C now goes through a PA wrapper,
474          * but still, doesn't hurt.
475          *
476          * Yeah, but non-gencgc platforms that don't really wrap
477          * allocation in PA. MG - 2005-08-29  */
478
479         lispobj info_sap,context_sap = alloc_sap(context);
480         info_sap = alloc_sap(info);
481         /* Allow signals again. */
482         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
483
484         FSHOW_SIGNAL((stderr,"/calling Lisp-level handler\n"));
485
486         funcall3(handler.lisp,
487                  make_fixnum(signal),
488                  info_sap,
489                  context_sap);
490     } else {
491
492         FSHOW_SIGNAL((stderr,"/calling C-level handler\n"));
493
494         /* Allow signals again. */
495         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
496
497         (*handler.c)(signal, info, void_context);
498     }
499
500 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
501     if (were_in_lisp)
502 #endif
503     {
504         undo_fake_foreign_function_call(context); /* block signals again */
505     }
506
507     FSHOW_SIGNAL((stderr,
508                   "/returning from interrupt_handle_now(%d, info, context)\n",
509                   signal));
510 }
511
512 /* This is called at the end of a critical section if the indications
513  * are that some signal was deferred during the section.  Note that as
514  * far as C or the kernel is concerned we dealt with the signal
515  * already; we're just doing the Lisp-level processing now that we
516  * put off then */
517
518 void
519 run_deferred_handler(struct interrupt_data *data, void *v_context) {
520     /* The pending_handler may enable interrupts and then another
521      * interrupt may hit, overwrite interrupt_data, so reset the
522      * pending handler before calling it. Trust the handler to finish
523      * with the siginfo before enabling interrupts. */
524     void (*pending_handler) (int, siginfo_t*, void*)=data->pending_handler;
525     data->pending_handler=0;
526     (*pending_handler)(data->pending_signal,&(data->pending_info), v_context);
527 }
528
529 boolean
530 maybe_defer_handler(void *handler, struct interrupt_data *data,
531                     int signal, siginfo_t *info, os_context_t *context)
532 {
533     struct thread *thread=arch_os_get_current_thread();
534
535     check_blockables_blocked_or_lose();
536
537     if (SymbolValue(INTERRUPT_PENDING,thread) != NIL)
538         lose("interrupt already pending");
539     /* If interrupts are disabled then INTERRUPT_PENDING is set and
540      * not PSEDUO_ATOMIC_INTERRUPTED. This is important for a pseudo
541      * atomic section inside a WITHOUT-INTERRUPTS.
542      */
543     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) {
544         store_signal_data_for_later(data,handler,signal,info,context);
545         SetSymbolValue(INTERRUPT_PENDING, T,thread);
546         FSHOW_SIGNAL((stderr,
547                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred\n",
548                       (unsigned int)handler,signal,
549                       (unsigned long)thread->os_thread));
550         return 1;
551     }
552     /* a slightly confusing test.  arch_pseudo_atomic_atomic() doesn't
553      * actually use its argument for anything on x86, so this branch
554      * may succeed even when context is null (gencgc alloc()) */
555     if (
556 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
557         /* FIXME: this foreign_function_call_active test is dubious at
558          * best. If a foreign call is made in a pseudo atomic section
559          * (?) or more likely a pseudo atomic section is in a foreign
560          * call then an interrupt is executed immediately. Maybe it
561          * has to do with C code not maintaining pseudo atomic
562          * properly. MG - 2005-08-10 */
563         (!foreign_function_call_active) &&
564 #endif
565         arch_pseudo_atomic_atomic(context)) {
566         store_signal_data_for_later(data,handler,signal,info,context);
567         arch_set_pseudo_atomic_interrupted(context);
568         FSHOW_SIGNAL((stderr,
569                       "/maybe_defer_handler(%x,%d),thread=%lu: deferred(PA)\n",
570                       (unsigned int)handler,signal,
571                       (unsigned long)thread->os_thread));
572         return 1;
573     }
574     FSHOW_SIGNAL((stderr,
575                   "/maybe_defer_handler(%x,%d),thread=%lu: not deferred\n",
576                   (unsigned int)handler,signal,
577                   (unsigned long)thread->os_thread));
578     return 0;
579 }
580
581 static void
582 store_signal_data_for_later (struct interrupt_data *data, void *handler,
583                              int signal,
584                              siginfo_t *info, os_context_t *context)
585 {
586     if (data->pending_handler)
587         lose("tried to overwrite pending interrupt handler %x with %x\n",
588              data->pending_handler, handler);
589     if (!handler)
590         lose("tried to defer null interrupt handler\n");
591     data->pending_handler = handler;
592     data->pending_signal = signal;
593     if(info)
594         memcpy(&(data->pending_info), info, sizeof(siginfo_t));
595     if(context) {
596         /* the signal mask in the context (from before we were
597          * interrupted) is copied to be restored when
598          * run_deferred_handler happens.  Then the usually-blocked
599          * signals are added to the mask in the context so that we are
600          * running with blocked signals when the handler returns */
601         sigcopyset(&(data->pending_mask),os_context_sigmask_addr(context));
602         sigaddset_deferrable(os_context_sigmask_addr(context));
603     }
604 }
605
606 static void
607 maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
608 {
609     os_context_t *context = arch_os_get_context(&void_context);
610     struct thread *thread=arch_os_get_current_thread();
611     struct interrupt_data *data=thread->interrupt_data;
612 #ifdef LISP_FEATURE_LINUX
613     os_restore_fp_control(context);
614 #endif
615     if(maybe_defer_handler(interrupt_handle_now,data,signal,info,context))
616         return;
617     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 static void
625 low_level_interrupt_handle_now(int signal, siginfo_t *info, void *void_context)
626 {
627     os_context_t *context = (os_context_t*)void_context;
628
629 #ifdef LISP_FEATURE_LINUX
630     os_restore_fp_control(context);
631 #endif
632     check_blockables_blocked_or_lose();
633     check_interrupts_enabled_or_lose(context);
634     interrupt_low_level_handlers[signal](signal, info, void_context);
635 #ifdef LISP_FEATURE_DARWIN
636     /* Work around G5 bug */
637     DARWIN_FIX_CONTEXT(context);
638 #endif
639 }
640
641 static void
642 low_level_maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
643 {
644     os_context_t *context = arch_os_get_context(&void_context);
645     struct thread *thread=arch_os_get_current_thread();
646     struct interrupt_data *data=thread->interrupt_data;
647 #ifdef LISP_FEATURE_LINUX
648     os_restore_fp_control(context);
649 #endif
650     if(maybe_defer_handler(low_level_interrupt_handle_now,data,
651                            signal,info,context))
652         return;
653     low_level_interrupt_handle_now(signal, info, context);
654 #ifdef LISP_FEATURE_DARWIN
655     /* Work around G5 bug */
656     DARWIN_FIX_CONTEXT(context);
657 #endif
658 }
659
660 #ifdef LISP_FEATURE_SB_THREAD
661
662 void
663 sig_stop_for_gc_handler(int signal, siginfo_t *info, void *void_context)
664 {
665     os_context_t *context = arch_os_get_context(&void_context);
666     struct thread *thread=arch_os_get_current_thread();
667     sigset_t ss;
668     int i;
669
670     if ((arch_pseudo_atomic_atomic(context) ||
671          SymbolValue(GC_INHIBIT,thread) != NIL)) {
672         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
673         if (SymbolValue(GC_INHIBIT,thread) == NIL)
674             arch_set_pseudo_atomic_interrupted(context);
675         FSHOW_SIGNAL((stderr,"thread=%lu sig_stop_for_gc deferred\n",
676                       thread->os_thread));
677     } else {
678         /* need the context stored so it can have registers scavenged */
679         fake_foreign_function_call(context);
680
681         sigemptyset(&ss);
682         for(i=1;i<NSIG;i++) sigaddset(&ss,i); /* Block everything. */
683         thread_sigmask(SIG_BLOCK,&ss,0);
684
685         /* The GC can't tell if a thread is a zombie, so this would be a
686          * good time to let the kernel reap any of our children in that
687          * awful state, to stop them from being waited for indefinitely.
688          * Userland reaping is done later when GC is finished  */
689         if(thread->state!=STATE_RUNNING) {
690             lose("sig_stop_for_gc_handler: wrong thread state: %ld\n",
691                  fixnum_value(thread->state));
692         }
693         thread->state=STATE_SUSPENDED;
694         FSHOW_SIGNAL((stderr,"thread=%lu suspended\n",thread->os_thread));
695
696         sigemptyset(&ss); sigaddset(&ss,SIG_STOP_FOR_GC);
697         sigwaitinfo(&ss,0);
698         FSHOW_SIGNAL((stderr,"thread=%lu resumed\n",thread->os_thread));
699         if(thread->state!=STATE_RUNNING) {
700             lose("sig_stop_for_gc_handler: wrong thread state on wakeup: %ld\n",
701                  fixnum_value(thread->state));
702         }
703
704         undo_fake_foreign_function_call(context);
705     }
706 }
707 #endif
708
709 void
710 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
711 {
712     os_context_t *context = arch_os_get_context(&void_context);
713     interrupt_handle_now(signal, info, context);
714 #ifdef LISP_FEATURE_DARWIN
715     DARWIN_FIX_CONTEXT(context);
716 #endif
717 }
718
719 /*
720  * stuff to detect and handle hitting the GC trigger
721  */
722
723 #ifndef LISP_FEATURE_GENCGC
724 /* since GENCGC has its own way to record trigger */
725 static boolean
726 gc_trigger_hit(int signal, siginfo_t *info, os_context_t *context)
727 {
728     if (current_auto_gc_trigger == NULL)
729         return 0;
730     else{
731         void *badaddr=arch_get_bad_addr(signal,info,context);
732         return (badaddr >= (void *)current_auto_gc_trigger &&
733                 badaddr <((void *)current_dynamic_space + DYNAMIC_SPACE_SIZE));
734     }
735 }
736 #endif
737
738 /* manipulate the signal context and stack such that when the handler
739  * returns, it will call function instead of whatever it was doing
740  * previously
741  */
742
743 #if (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
744 int *context_eflags_addr(os_context_t *context);
745 #endif
746
747 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
748 extern void post_signal_tramp(void);
749 void arrange_return_to_lisp_function(os_context_t *context, lispobj function)
750 {
751 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
752     void * fun=native_pointer(function);
753     void *code = &(((struct simple_fun *) fun)->code);
754 #endif
755
756     /* Build a stack frame showing `interrupted' so that the
757      * user's backtrace makes (as much) sense (as usual) */
758
759     /* FIXME: what about restoring fp state? */
760     /* FIXME: what about restoring errno? */
761 #ifdef LISP_FEATURE_X86
762     /* Suppose the existence of some function that saved all
763      * registers, called call_into_lisp, then restored GP registers and
764      * returned.  It would look something like this:
765
766      push   ebp
767      mov    ebp esp
768      pushfl
769      pushal
770      push   $0
771      push   $0
772      pushl  {address of function to call}
773      call   0x8058db0 <call_into_lisp>
774      addl   $12,%esp
775      popal
776      popfl
777      leave
778      ret
779
780      * What we do here is set up the stack that call_into_lisp would
781      * expect to see if it had been called by this code, and frob the
782      * signal context so that signal return goes directly to call_into_lisp,
783      * and when that function (and the lisp function it invoked) returns,
784      * it returns to the second half of this imaginary function which
785      * restores all registers and returns to C
786
787      * For this to work, the latter part of the imaginary function
788      * must obviously exist in reality.  That would be post_signal_tramp
789      */
790
791     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
792
793     /* return address for call_into_lisp: */
794     *(sp-15) = (u32)post_signal_tramp;
795     *(sp-14) = function;        /* args for call_into_lisp : function*/
796     *(sp-13) = 0;               /*                           arg array */
797     *(sp-12) = 0;               /*                           no. args */
798     /* this order matches that used in POPAD */
799     *(sp-11)=*os_context_register_addr(context,reg_EDI);
800     *(sp-10)=*os_context_register_addr(context,reg_ESI);
801
802     *(sp-9)=*os_context_register_addr(context,reg_ESP)-8;
803     /* POPAD ignores the value of ESP:  */
804     *(sp-8)=0;
805     *(sp-7)=*os_context_register_addr(context,reg_EBX);
806
807     *(sp-6)=*os_context_register_addr(context,reg_EDX);
808     *(sp-5)=*os_context_register_addr(context,reg_ECX);
809     *(sp-4)=*os_context_register_addr(context,reg_EAX);
810     *(sp-3)=*context_eflags_addr(context);
811     *(sp-2)=*os_context_register_addr(context,reg_EBP);
812     *(sp-1)=*os_context_pc_addr(context);
813
814 #elif defined(LISP_FEATURE_X86_64)
815     u64 *sp=(u64 *)*os_context_register_addr(context,reg_RSP);
816     /* return address for call_into_lisp: */
817     *(sp-18) = (u64)post_signal_tramp;
818
819     *(sp-17)=*os_context_register_addr(context,reg_R15);
820     *(sp-16)=*os_context_register_addr(context,reg_R14);
821     *(sp-15)=*os_context_register_addr(context,reg_R13);
822     *(sp-14)=*os_context_register_addr(context,reg_R12);
823     *(sp-13)=*os_context_register_addr(context,reg_R11);
824     *(sp-12)=*os_context_register_addr(context,reg_R10);
825     *(sp-11)=*os_context_register_addr(context,reg_R9);
826     *(sp-10)=*os_context_register_addr(context,reg_R8);
827     *(sp-9)=*os_context_register_addr(context,reg_RDI);
828     *(sp-8)=*os_context_register_addr(context,reg_RSI);
829     /* skip RBP and RSP */
830     *(sp-7)=*os_context_register_addr(context,reg_RBX);
831     *(sp-6)=*os_context_register_addr(context,reg_RDX);
832     *(sp-5)=*os_context_register_addr(context,reg_RCX);
833     *(sp-4)=*os_context_register_addr(context,reg_RAX);
834     *(sp-3)=*context_eflags_addr(context);
835     *(sp-2)=*os_context_register_addr(context,reg_RBP);
836     *(sp-1)=*os_context_pc_addr(context);
837
838     *os_context_register_addr(context,reg_RDI) =
839         (os_context_register_t)function; /* function */
840     *os_context_register_addr(context,reg_RSI) = 0;        /* arg. array */
841     *os_context_register_addr(context,reg_RDX) = 0;        /* no. args */
842 #else
843     struct thread *th=arch_os_get_current_thread();
844     build_fake_control_stack_frames(th,context);
845 #endif
846
847 #ifdef LISP_FEATURE_X86
848     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
849     *os_context_register_addr(context,reg_ECX) = 0;
850     *os_context_register_addr(context,reg_EBP) = (os_context_register_t)(sp-2);
851 #ifdef __NetBSD__
852     *os_context_register_addr(context,reg_UESP) =
853         (os_context_register_t)(sp-15);
854 #else
855     *os_context_register_addr(context,reg_ESP) = (os_context_register_t)(sp-15);
856 #endif
857 #elif defined(LISP_FEATURE_X86_64)
858     *os_context_pc_addr(context) = (os_context_register_t)call_into_lisp;
859     *os_context_register_addr(context,reg_RCX) = 0;
860     *os_context_register_addr(context,reg_RBP) = (os_context_register_t)(sp-2);
861     *os_context_register_addr(context,reg_RSP) = (os_context_register_t)(sp-18);
862 #else
863     /* this much of the calling convention is common to all
864        non-x86 ports */
865     *os_context_pc_addr(context) = (os_context_register_t)(unsigned long)code;
866     *os_context_register_addr(context,reg_NARGS) = 0;
867     *os_context_register_addr(context,reg_LIP) =
868         (os_context_register_t)(unsigned long)code;
869     *os_context_register_addr(context,reg_CFP) =
870         (os_context_register_t)(unsigned long)current_control_frame_pointer;
871 #endif
872 #ifdef ARCH_HAS_NPC_REGISTER
873     *os_context_npc_addr(context) =
874         4 + *os_context_pc_addr(context);
875 #endif
876 #ifdef LISP_FEATURE_SPARC
877     *os_context_register_addr(context,reg_CODE) =
878         (os_context_register_t)(fun + FUN_POINTER_LOWTAG);
879 #endif
880 }
881
882 #ifdef LISP_FEATURE_SB_THREAD
883 void interrupt_thread_handler(int num, siginfo_t *info, void *v_context)
884 {
885     os_context_t *context = (os_context_t*)arch_os_get_context(&v_context);
886     /* The order of interrupt execution is peculiar. If thread A
887      * interrupts thread B with I1, I2 and B for some reason receives
888      * I1 when FUN2 is already on the list, then it is FUN2 that gets
889      * to run first. But when FUN2 is run SIG_INTERRUPT_THREAD is
890      * enabled again and I2 hits pretty soon in FUN2 and run
891      * FUN1. This is of course just one scenario, and the order of
892      * thread interrupt execution is undefined. */
893     struct thread *th=arch_os_get_current_thread();
894     struct cons *c;
895     lispobj function;
896     if (th->state != STATE_RUNNING)
897         lose("interrupt_thread_handler: thread %lu in wrong state: %d\n",
898              th->os_thread,fixnum_value(th->state));
899     get_spinlock(&th->interrupt_fun_lock,(long)th);
900     c=((struct cons *)native_pointer(th->interrupt_fun));
901     function=c->car;
902     th->interrupt_fun=c->cdr;
903     release_spinlock(&th->interrupt_fun_lock);
904     if (function==NIL)
905         lose("interrupt_thread_handler: NIL function\n");
906     arrange_return_to_lisp_function(context,function);
907 }
908
909 #endif
910
911 /* KLUDGE: Theoretically the approach we use for undefined alien
912  * variables should work for functions as well, but on PPC/Darwin
913  * we get bus error at bogus addresses instead, hence this workaround,
914  * that has the added benefit of automatically discriminating between
915  * functions and variables.
916  */
917 void undefined_alien_function() {
918     funcall0(SymbolFunction(UNDEFINED_ALIEN_FUNCTION_ERROR));
919 }
920
921 boolean handle_guard_page_triggered(os_context_t *context,os_vm_address_t addr)
922 {
923     struct thread *th=arch_os_get_current_thread();
924
925     /* note the os_context hackery here.  When the signal handler returns,
926      * it won't go back to what it was doing ... */
927     if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
928        addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
929         /* We hit the end of the control stack: disable guard page
930          * protection so the error handler has some headroom, protect the
931          * previous page so that we can catch returns from the guard page
932          * and restore it. */
933         protect_control_stack_guard_page(th,0);
934         protect_control_stack_return_guard_page(th,1);
935
936         arrange_return_to_lisp_function
937             (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
938         return 1;
939     }
940     else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
941             addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
942         /* We're returning from the guard page: reprotect it, and
943          * unprotect this one. This works even if we somehow missed
944          * the return-guard-page, and hit it on our way to new
945          * exhaustion instead. */
946         protect_control_stack_guard_page(th,1);
947         protect_control_stack_return_guard_page(th,0);
948         return 1;
949     }
950     else if (addr >= undefined_alien_address &&
951              addr < undefined_alien_address + os_vm_page_size) {
952         arrange_return_to_lisp_function
953           (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
954         return 1;
955     }
956     else return 0;
957 }
958
959 #ifndef LISP_FEATURE_GENCGC
960 /* This function gets called from the SIGSEGV (for e.g. Linux, NetBSD, &
961  * OpenBSD) or SIGBUS (for e.g. FreeBSD) handler. Here we check
962  * whether the signal was due to treading on the mprotect()ed zone -
963  * and if so, arrange for a GC to happen. */
964 extern unsigned long bytes_consed_between_gcs; /* gc-common.c */
965
966 boolean
967 interrupt_maybe_gc(int signal, siginfo_t *info, void *void_context)
968 {
969     os_context_t *context=(os_context_t *) void_context;
970
971     if(!foreign_function_call_active && gc_trigger_hit(signal, info, context)){
972         struct thread *thread=arch_os_get_current_thread();
973         clear_auto_gc_trigger();
974         /* Don't flood the system with interrupts if the need to gc is
975          * already noted. This can happen for example when SUB-GC
976          * allocates or after a gc triggered in a WITHOUT-GCING. */
977         if (SymbolValue(GC_PENDING,thread) == NIL) {
978             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
979                 if (arch_pseudo_atomic_atomic(context)) {
980                     /* set things up so that GC happens when we finish
981                      * the PA section */
982                     SetSymbolValue(GC_PENDING,T,thread);
983                     arch_set_pseudo_atomic_interrupted(context);
984                 } else {
985                     interrupt_maybe_gc_int(signal,info,void_context);
986                 }
987             } else {
988                 SetSymbolValue(GC_PENDING,T,thread);
989             }
990         }
991         return 1;
992     }
993     return 0;
994 }
995
996 #endif
997
998 /* this is also used by gencgc, in alloc() */
999 boolean
1000 interrupt_maybe_gc_int(int signal, siginfo_t *info, void *void_context)
1001 {
1002     os_context_t *context=(os_context_t *) void_context;
1003     struct thread *thread=arch_os_get_current_thread();
1004
1005     check_blockables_blocked_or_lose();
1006     fake_foreign_function_call(context);
1007
1008     /* SUB-GC may return without GCing if *GC-INHIBIT* is set, in
1009      * which case we will be running with no gc trigger barrier
1010      * thing for a while.  But it shouldn't be long until the end
1011      * of WITHOUT-GCING.
1012      *
1013      * FIXME: It would be good to protect the end of dynamic space
1014      * and signal a storage condition from there.
1015      */
1016
1017     /* Restore the signal mask from the interrupted context before
1018      * calling into Lisp if interrupts are enabled. Why not always?
1019      *
1020      * Suppose there is a WITHOUT-INTERRUPTS block far, far out. If an
1021      * interrupt hits while in SUB-GC, it is deferred and the
1022      * os_context_sigmask of that interrupt is set to block further
1023      * deferrable interrupts (until the first one is
1024      * handled). Unfortunately, that context refers to this place and
1025      * when we return from here the signals will not be blocked.
1026      *
1027      * A kludgy alternative is to propagate the sigmask change to the
1028      * outer context.
1029      */
1030     if(SymbolValue(INTERRUPTS_ENABLED,thread)!=NIL)
1031         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
1032 #ifdef LISP_FEATURE_SB_THREAD
1033     else {
1034         sigset_t new;
1035         sigaddset(&new,SIG_STOP_FOR_GC);
1036         thread_sigmask(SIG_UNBLOCK,&new,0);
1037     }
1038 #endif
1039     funcall0(SymbolFunction(SUB_GC));
1040
1041     undo_fake_foreign_function_call(context);
1042     return 1;
1043 }
1044
1045 \f
1046 /*
1047  * noise to install handlers
1048  */
1049
1050 void
1051 undoably_install_low_level_interrupt_handler (int signal,
1052                                               void handler(int,
1053                                                            siginfo_t*,
1054                                                            void*))
1055 {
1056     struct sigaction sa;
1057
1058     if (0 > signal || signal >= NSIG) {
1059         lose("bad signal number %d", signal);
1060     }
1061
1062     if (sigismember(&deferrable_sigset,signal))
1063         sa.sa_sigaction = low_level_maybe_now_maybe_later;
1064     else
1065         sa.sa_sigaction = handler;
1066
1067     sigemptyset(&sa.sa_mask);
1068     sigaddset_blockable(&sa.sa_mask);
1069     sa.sa_flags = SA_SIGINFO | SA_RESTART;
1070 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1071     if((signal==SIG_MEMORY_FAULT)
1072 #ifdef SIG_INTERRUPT_THREAD
1073        || (signal==SIG_INTERRUPT_THREAD)
1074 #endif
1075        )
1076         sa.sa_flags|= SA_ONSTACK;
1077 #endif
1078
1079     sigaction(signal, &sa, NULL);
1080     interrupt_low_level_handlers[signal] =
1081         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
1082 }
1083
1084 /* This is called from Lisp. */
1085 unsigned long
1086 install_handler(int signal, void handler(int, siginfo_t*, void*))
1087 {
1088     struct sigaction sa;
1089     sigset_t old, new;
1090     union interrupt_handler oldhandler;
1091
1092     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
1093
1094     sigemptyset(&new);
1095     sigaddset(&new, signal);
1096     thread_sigmask(SIG_BLOCK, &new, &old);
1097
1098     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%x\n",
1099            (unsigned int)interrupt_low_level_handlers[signal]));
1100     if (interrupt_low_level_handlers[signal]==0) {
1101         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
1102             ARE_SAME_HANDLER(handler, SIG_IGN)) {
1103             sa.sa_sigaction = handler;
1104         } else if (sigismember(&deferrable_sigset, signal)) {
1105             sa.sa_sigaction = maybe_now_maybe_later;
1106         } else {
1107             sa.sa_sigaction = interrupt_handle_now_handler;
1108         }
1109
1110         sigemptyset(&sa.sa_mask);
1111         sigaddset_blockable(&sa.sa_mask);
1112         sa.sa_flags = SA_SIGINFO | SA_RESTART;
1113         sigaction(signal, &sa, NULL);
1114     }
1115
1116     oldhandler = interrupt_handlers[signal];
1117     interrupt_handlers[signal].c = handler;
1118
1119     thread_sigmask(SIG_SETMASK, &old, 0);
1120
1121     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
1122
1123     return (unsigned long)oldhandler.lisp;
1124 }
1125
1126 void
1127 interrupt_init()
1128 {
1129     int i;
1130     SHOW("entering interrupt_init()");
1131     sigemptyset(&deferrable_sigset);
1132     sigemptyset(&blockable_sigset);
1133     sigaddset_deferrable(&deferrable_sigset);
1134     sigaddset_blockable(&blockable_sigset);
1135
1136     /* Set up high level handler information. */
1137     for (i = 0; i < NSIG; i++) {
1138         interrupt_handlers[i].c =
1139             /* (The cast here blasts away the distinction between
1140              * SA_SIGACTION-style three-argument handlers and
1141              * signal(..)-style one-argument handlers, which is OK
1142              * because it works to call the 1-argument form where the
1143              * 3-argument form is expected.) */
1144             (void (*)(int, siginfo_t*, void*))SIG_DFL;
1145     }
1146
1147     SHOW("returning from interrupt_init()");
1148 }