132e9b2f2b4dff0f8e91ba38f096b7e01989a177
[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 #include "sbcl.h"
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <signal.h>
49 #include <sys/types.h>
50 #ifndef LISP_FEATURE_WIN32
51 #include <sys/wait.h>
52 #endif
53 #include <errno.h>
54
55 #include "runtime.h"
56 #include "arch.h"
57 #include "os.h"
58 #include "interrupt.h"
59 #include "globals.h"
60 #include "lispregs.h"
61 #include "validate.h"
62 #include "interr.h"
63 #include "gc.h"
64 #include "alloc.h"
65 #include "dynbind.h"
66 #include "pseudo-atomic.h"
67 #include "genesis/fdefn.h"
68 #include "genesis/simple-fun.h"
69 #include "genesis/cons.h"
70
71 /* When we catch an internal error, should we pass it back to Lisp to
72  * be handled in a high-level way? (Early in cold init, the answer is
73  * 'no', because Lisp is still too brain-dead to handle anything.
74  * After sufficient initialization has been completed, the answer
75  * becomes 'yes'.) */
76 boolean internal_errors_enabled = 0;
77
78 #ifndef LISP_FEATURE_WIN32
79 static
80 void (*interrupt_low_level_handlers[NSIG]) (int, siginfo_t*, os_context_t*);
81 #endif
82 union interrupt_handler interrupt_handlers[NSIG];
83
84 /* Under Linux on some architectures, we appear to have to restore the
85  * FPU control word from the context, as after the signal is delivered
86  * we appear to have a null FPU control word. */
87 #if defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
88 #define RESTORE_FP_CONTROL_WORD(context,void_context)           \
89     os_context_t *context = arch_os_get_context(&void_context); \
90     os_restore_fp_control(context);
91 #else
92 #define RESTORE_FP_CONTROL_WORD(context,void_context)           \
93     os_context_t *context = arch_os_get_context(&void_context);
94 #endif
95
96 /* Foreign code may want to start some threads on its own.
97  * Non-targetted, truly asynchronous signals can be delivered to
98  * basically any thread, but invoking Lisp handlers in such foregign
99  * threads is really bad, so let's resignal it.
100  *
101  * This should at least bring attention to the problem, but it cannot
102  * work for SIGSEGV and similar. It is good enough for timers, and
103  * maybe all deferrables. */
104
105 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_WIN32)
106 static void
107 add_handled_signals(sigset_t *sigset)
108 {
109     int i;
110     for(i = 1; i < NSIG; i++) {
111         if (!(ARE_SAME_HANDLER(interrupt_low_level_handlers[i], SIG_DFL)) ||
112             !(ARE_SAME_HANDLER(interrupt_handlers[i].c, SIG_DFL))) {
113             sigaddset(sigset, i);
114         }
115     }
116 }
117
118 void block_signals(sigset_t *what, sigset_t *where, sigset_t *old);
119 #endif
120
121 static boolean
122 maybe_resignal_to_lisp_thread(int signal, os_context_t *context)
123 {
124 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_WIN32)
125     if (!pthread_getspecific(lisp_thread)) {
126         if (!(sigismember(&deferrable_sigset,signal))) {
127             corruption_warning_and_maybe_lose
128                 ("Received signal %d in non-lisp thread %lu, resignalling to a lisp thread.",
129                  signal,
130                  pthread_self());
131         }
132         {
133             sigset_t sigset;
134             sigemptyset(&sigset);
135             add_handled_signals(&sigset);
136             block_signals(&sigset, 0, 0);
137             block_signals(&sigset, os_context_sigmask_addr(context), 0);
138             kill(getpid(), signal);
139         }
140         return 1;
141     } else
142 #endif
143         return 0;
144 }
145
146 /* These are to be used in signal handlers. Currently all handlers are
147  * called from one of:
148  *
149  * interrupt_handle_now_handler
150  * maybe_now_maybe_later
151  * unblock_me_trampoline
152  * low_level_handle_now_handler
153  * low_level_maybe_now_maybe_later
154  * low_level_unblock_me_trampoline
155  *
156  * This gives us a single point of control (or six) over errno, fp
157  * control word, and fixing up signal context on sparc.
158  *
159  * The SPARC/Linux platform doesn't quite do signals the way we want
160  * them done. The third argument in the handler isn't filled in by the
161  * kernel properly, so we fix it up ourselves in the
162  * arch_os_get_context(..) function. -- CSR, 2002-07-23
163  */
164 #define SAVE_ERRNO(signal,context,void_context)                 \
165     {                                                           \
166         int _saved_errno = errno;                               \
167         RESTORE_FP_CONTROL_WORD(context,void_context);          \
168         if (!maybe_resignal_to_lisp_thread(signal, context))    \
169         {
170
171 #define RESTORE_ERRNO                                           \
172         }                                                       \
173         errno = _saved_errno;                                   \
174     }
175
176 static void run_deferred_handler(struct interrupt_data *data,
177                                  os_context_t *context);
178 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
179 static void store_signal_data_for_later (struct interrupt_data *data,
180                                          void *handler, int signal,
181                                          siginfo_t *info,
182                                          os_context_t *context);
183 \f
184
185 /* Generic signal related utilities. */
186
187 void
188 get_current_sigmask(sigset_t *sigset)
189 {
190     /* Get the current sigmask, by blocking the empty set. */
191     thread_sigmask(SIG_BLOCK, 0, sigset);
192 }
193
194 void
195 block_signals(sigset_t *what, sigset_t *where, sigset_t *old)
196 {
197     if (where) {
198         int i;
199         if (old)
200             sigcopyset(old, where);
201         for(i = 1; i < NSIG; i++) {
202             if (sigismember(what, i))
203                 sigaddset(where, i);
204         }
205     } else {
206         thread_sigmask(SIG_BLOCK, what, old);
207     }
208 }
209
210 void
211 unblock_signals(sigset_t *what, sigset_t *where, sigset_t *old)
212 {
213     if (where) {
214         int i;
215         if (old)
216             sigcopyset(old, where);
217         for(i = 1; i < NSIG; i++) {
218             if (sigismember(what, i))
219                 sigdelset(where, i);
220         }
221     } else {
222         thread_sigmask(SIG_UNBLOCK, what, old);
223     }
224 }
225
226 static void
227 print_sigset(sigset_t *sigset)
228 {
229   int i;
230   for(i = 1; i < NSIG; i++) {
231     if (sigismember(sigset, i))
232       fprintf(stderr, "Signal %d masked\n", i);
233   }
234 }
235
236 /* Return 1 is all signals is sigset2 are masked in sigset, return 0
237  * if all re unmasked else die. Passing NULL for sigset is a shorthand
238  * for the current sigmask. */
239 boolean
240 all_signals_blocked_p(sigset_t *sigset, sigset_t *sigset2,
241                                 const char *name)
242 {
243 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
244     int i;
245     boolean has_blocked = 0, has_unblocked = 0;
246     sigset_t current;
247     if (sigset == 0) {
248         get_current_sigmask(&current);
249         sigset = &current;
250     }
251     for(i = 1; i < NSIG; i++) {
252         if (sigismember(sigset2, i)) {
253             if (sigismember(sigset, i))
254                 has_blocked = 1;
255             else
256                 has_unblocked = 1;
257         }
258     }
259     if (has_blocked && has_unblocked) {
260         print_sigset(sigset);
261         lose("some %s signals blocked, some unblocked\n", name);
262     }
263     if (has_blocked)
264         return 1;
265     else
266         return 0;
267 #endif
268 }
269 \f
270
271 /* Deferrables, blockables, gc signals. */
272
273 void
274 sigaddset_deferrable(sigset_t *s)
275 {
276     sigaddset(s, SIGHUP);
277     sigaddset(s, SIGINT);
278     sigaddset(s, SIGTERM);
279     sigaddset(s, SIGQUIT);
280     sigaddset(s, SIGPIPE);
281     sigaddset(s, SIGALRM);
282     sigaddset(s, SIGURG);
283     sigaddset(s, SIGTSTP);
284     sigaddset(s, SIGCHLD);
285     sigaddset(s, SIGIO);
286 #ifndef LISP_FEATURE_HPUX
287     sigaddset(s, SIGXCPU);
288     sigaddset(s, SIGXFSZ);
289 #endif
290     sigaddset(s, SIGVTALRM);
291     sigaddset(s, SIGPROF);
292     sigaddset(s, SIGWINCH);
293 }
294
295 void
296 sigaddset_blockable(sigset_t *sigset)
297 {
298     sigaddset_deferrable(sigset);
299     sigaddset_gc(sigset);
300 }
301
302 void
303 sigaddset_gc(sigset_t *sigset)
304 {
305 #ifdef THREADS_USING_GCSIGNAL
306     sigaddset(sigset,SIG_STOP_FOR_GC);
307 #endif
308 }
309
310 /* initialized in interrupt_init */
311 sigset_t deferrable_sigset;
312 sigset_t blockable_sigset;
313 sigset_t gc_sigset;
314
315 #endif
316
317 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
318 boolean
319 deferrables_blocked_p(sigset_t *sigset)
320 {
321     return all_signals_blocked_p(sigset, &deferrable_sigset, "deferrable");
322 }
323 #endif
324
325 void
326 check_deferrables_unblocked_or_lose(sigset_t *sigset)
327 {
328 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
329     if (deferrables_blocked_p(sigset))
330         lose("deferrables blocked\n");
331 #endif
332 }
333
334 void
335 check_deferrables_blocked_or_lose(sigset_t *sigset)
336 {
337 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
338     if (!deferrables_blocked_p(sigset))
339         lose("deferrables unblocked\n");
340 #endif
341 }
342
343 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
344 boolean
345 blockables_blocked_p(sigset_t *sigset)
346 {
347     return all_signals_blocked_p(sigset, &blockable_sigset, "blockable");
348 }
349 #endif
350
351 void
352 check_blockables_unblocked_or_lose(sigset_t *sigset)
353 {
354 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
355     if (blockables_blocked_p(sigset))
356         lose("blockables blocked\n");
357 #endif
358 }
359
360 void
361 check_blockables_blocked_or_lose(sigset_t *sigset)
362 {
363 #if !defined(LISP_FEATURE_WIN32)
364     /* On Windows, there are no actual signals, but since the win32 port
365      * tracks the sigmask and checks it explicitly, some functions are
366      * still required to keep the mask set up properly.  (After all, the
367      * goal of the sigmask emulation is to not have to change all the
368      * call sites in the first place.)
369      *
370      * However, this does not hold for all signals equally: While
371      * deferrables matter ("is interrupt-thread okay?"), it is not worth
372      * having to set up blockables properly (which include the
373      * non-existing GC signals).
374      *
375      * Yet, as the original comment explains it:
376      *   Adjusting FREE-INTERRUPT-CONTEXT-INDEX* and other aspecs of
377      *   fake_foreign_function_call machinery are sometimes useful here[...].
378      *
379      * So we merely skip this assertion.
380      *   -- DFL, trying to expand on a comment by AK.
381      */
382     if (!blockables_blocked_p(sigset))
383         lose("blockables unblocked\n");
384 #endif
385 }
386
387 #ifndef LISP_FEATURE_SB_SAFEPOINT
388 #if !defined(LISP_FEATURE_WIN32)
389 boolean
390 gc_signals_blocked_p(sigset_t *sigset)
391 {
392     return all_signals_blocked_p(sigset, &gc_sigset, "gc");
393 }
394 #endif
395
396 void
397 check_gc_signals_unblocked_or_lose(sigset_t *sigset)
398 {
399 #if !defined(LISP_FEATURE_WIN32)
400     if (gc_signals_blocked_p(sigset))
401         lose("gc signals blocked\n");
402 #endif
403 }
404
405 void
406 check_gc_signals_blocked_or_lose(sigset_t *sigset)
407 {
408 #if !defined(LISP_FEATURE_WIN32)
409     if (!gc_signals_blocked_p(sigset))
410         lose("gc signals unblocked\n");
411 #endif
412 }
413 #endif
414
415 void
416 block_deferrable_signals(sigset_t *where, sigset_t *old)
417 {
418 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
419     block_signals(&deferrable_sigset, where, old);
420 #endif
421 }
422
423 void
424 block_blockable_signals(sigset_t *where, sigset_t *old)
425 {
426 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
427     block_signals(&blockable_sigset, where, old);
428 #endif
429 }
430
431 #ifndef LISP_FEATURE_SB_SAFEPOINT
432 void
433 block_gc_signals(sigset_t *where, sigset_t *old)
434 {
435 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
436     block_signals(&gc_sigset, where, old);
437 #endif
438 }
439 #endif
440
441 void
442 unblock_deferrable_signals(sigset_t *where, sigset_t *old)
443 {
444 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
445     if (interrupt_handler_pending_p())
446         lose("unblock_deferrable_signals: losing proposition\n");
447 #ifndef LISP_FEATURE_SB_SAFEPOINT
448     check_gc_signals_unblocked_or_lose(where);
449 #endif
450     unblock_signals(&deferrable_sigset, where, old);
451 #endif
452 }
453
454 void
455 unblock_blockable_signals(sigset_t *where, sigset_t *old)
456 {
457 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
458     unblock_signals(&blockable_sigset, where, old);
459 #endif
460 }
461
462 #ifndef LISP_FEATURE_SB_SAFEPOINT
463 void
464 unblock_gc_signals(sigset_t *where, sigset_t *old)
465 {
466 #ifndef LISP_FEATURE_WIN32
467     unblock_signals(&gc_sigset, where, old);
468 #endif
469 }
470 #endif
471
472 void
473 unblock_signals_in_context_and_maybe_warn(os_context_t *context)
474 {
475 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
476     sigset_t *sigset = os_context_sigmask_addr(context);
477 #ifndef LISP_FEATURE_SB_SAFEPOINT
478     if (all_signals_blocked_p(sigset, &gc_sigset, "gc")) {
479         corruption_warning_and_maybe_lose(
480 "Enabling blocked gc signals to allow returning to Lisp without risking\n\
481 gc deadlocks. Since GC signals are only blocked in signal handlers when \n\
482 they are not safe to interrupt at all, this is a pretty severe occurrence.\n");
483         unblock_gc_signals(sigset, 0);
484     }
485 #endif
486     if (!interrupt_handler_pending_p()) {
487         unblock_deferrable_signals(sigset, 0);
488     }
489 #endif
490 }
491 \f
492
493 inline static void
494 check_interrupts_enabled_or_lose(os_context_t *context)
495 {
496     struct thread *thread=arch_os_get_current_thread();
497     if (SymbolValue(INTERRUPTS_ENABLED,thread) == NIL)
498         lose("interrupts not enabled\n");
499     if (arch_pseudo_atomic_atomic(context))
500         lose ("in pseudo atomic section\n");
501 }
502
503 /* Save sigset (or the current sigmask if 0) if there is no pending
504  * handler, because that means that deferabbles are already blocked.
505  * The purpose is to avoid losing the pending gc signal if a
506  * deferrable interrupt async unwinds between clearing the pseudo
507  * atomic and trapping to GC.*/
508 #ifndef LISP_FEATURE_SB_SAFEPOINT
509 void
510 maybe_save_gc_mask_and_block_deferrables(sigset_t *sigset)
511 {
512 #ifndef LISP_FEATURE_WIN32
513     struct thread *thread = arch_os_get_current_thread();
514     struct interrupt_data *data = thread->interrupt_data;
515     sigset_t oldset;
516     /* Obviously, this function is called when signals may not be
517      * blocked. Let's make sure we are not interrupted. */
518     block_blockable_signals(0, &oldset);
519 #ifndef LISP_FEATURE_SB_THREAD
520     /* With threads a SIG_STOP_FOR_GC and a normal GC may also want to
521      * block. */
522     if (data->gc_blocked_deferrables)
523         lose("gc_blocked_deferrables already true\n");
524 #endif
525     if ((!data->pending_handler) &&
526         (!data->gc_blocked_deferrables)) {
527         FSHOW_SIGNAL((stderr,"/setting gc_blocked_deferrables\n"));
528         data->gc_blocked_deferrables = 1;
529         if (sigset) {
530             /* This is the sigmask of some context. */
531             sigcopyset(&data->pending_mask, sigset);
532             sigaddset_deferrable(sigset);
533             thread_sigmask(SIG_SETMASK,&oldset,0);
534             return;
535         } else {
536             /* Operating on the current sigmask. Save oldset and
537              * unblock gc signals. In the end, this is equivalent to
538              * blocking the deferrables. */
539             sigcopyset(&data->pending_mask, &oldset);
540             thread_sigmask(SIG_UNBLOCK, &gc_sigset, 0);
541             return;
542         }
543     }
544     thread_sigmask(SIG_SETMASK,&oldset,0);
545 #endif
546 }
547 #endif
548
549 /* Are we leaving WITH-GCING and already running with interrupts
550  * enabled, without the protection of *GC-INHIBIT* T and there is gc
551  * (or stop for gc) pending, but we haven't trapped yet? */
552 int
553 in_leaving_without_gcing_race_p(struct thread *thread)
554 {
555     return ((SymbolValue(IN_WITHOUT_GCING,thread) != NIL) &&
556             (SymbolValue(INTERRUPTS_ENABLED,thread) != NIL) &&
557             (SymbolValue(GC_INHIBIT,thread) == NIL) &&
558             ((SymbolValue(GC_PENDING,thread) != NIL)
559 #if defined(LISP_FEATURE_SB_THREAD)
560              || (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL)
561 #endif
562              ));
563 }
564
565 /* Check our baroque invariants. */
566 void
567 check_interrupt_context_or_lose(os_context_t *context)
568 {
569 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
570     struct thread *thread = arch_os_get_current_thread();
571     struct interrupt_data *data = thread->interrupt_data;
572     int interrupt_deferred_p = (data->pending_handler != 0);
573     int interrupt_pending = (SymbolValue(INTERRUPT_PENDING,thread) != NIL);
574     sigset_t *sigset = os_context_sigmask_addr(context);
575     /* On PPC pseudo_atomic_interrupted is cleared when coming out of
576      * handle_allocation_trap. */
577 #if defined(LISP_FEATURE_GENCGC) && !defined(GENCGC_IS_PRECISE)
578     int interrupts_enabled = (SymbolValue(INTERRUPTS_ENABLED,thread) != NIL);
579     int gc_inhibit = (SymbolValue(GC_INHIBIT,thread) != NIL);
580     int gc_pending = (SymbolValue(GC_PENDING,thread) == T);
581     int pseudo_atomic_interrupted = get_pseudo_atomic_interrupted(thread);
582     int in_race_p = in_leaving_without_gcing_race_p(thread);
583     /* In the time window between leaving the *INTERRUPTS-ENABLED* NIL
584      * section and trapping, a SIG_STOP_FOR_GC would see the next
585      * check fail, for this reason sig_stop_for_gc handler does not
586      * call this function. */
587     if (interrupt_deferred_p) {
588         if (!(!interrupts_enabled || pseudo_atomic_interrupted || in_race_p))
589             lose("Stray deferred interrupt.\n");
590     }
591     if (gc_pending)
592         if (!(pseudo_atomic_interrupted || gc_inhibit || in_race_p))
593             lose("GC_PENDING, but why?\n");
594 #if defined(LISP_FEATURE_SB_THREAD)
595     {
596         int stop_for_gc_pending =
597             (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL);
598         if (stop_for_gc_pending)
599             if (!(pseudo_atomic_interrupted || gc_inhibit || in_race_p))
600                 lose("STOP_FOR_GC_PENDING, but why?\n");
601         if (pseudo_atomic_interrupted)
602             if (!(gc_pending || stop_for_gc_pending || interrupt_deferred_p))
603                 lose("pseudo_atomic_interrupted, but why?\n");
604     }
605 #else
606     if (pseudo_atomic_interrupted)
607         if (!(gc_pending || interrupt_deferred_p))
608             lose("pseudo_atomic_interrupted, but why?\n");
609 #endif
610 #endif
611     if (interrupt_pending && !interrupt_deferred_p)
612         lose("INTERRUPT_PENDING but not pending handler.\n");
613     if ((data->gc_blocked_deferrables) && interrupt_pending)
614         lose("gc_blocked_deferrables and interrupt pending\n.");
615     if (data->gc_blocked_deferrables)
616         check_deferrables_blocked_or_lose(sigset);
617     if (interrupt_pending || interrupt_deferred_p ||
618         data->gc_blocked_deferrables)
619         check_deferrables_blocked_or_lose(sigset);
620     else {
621         check_deferrables_unblocked_or_lose(sigset);
622 #ifndef LISP_FEATURE_SB_SAFEPOINT
623         /* If deferrables are unblocked then we are open to signals
624          * that run lisp code. */
625         check_gc_signals_unblocked_or_lose(sigset);
626 #endif
627     }
628 #endif
629 }
630 \f
631 /*
632  * utility routines used by various signal handlers
633  */
634
635 static void
636 build_fake_control_stack_frames(struct thread *th,os_context_t *context)
637 {
638 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
639
640     lispobj oldcont;
641
642     /* Build a fake stack frame or frames */
643
644     access_control_frame_pointer(th) =
645         (lispobj *)(unsigned long)
646             (*os_context_register_addr(context, reg_CSP));
647     if ((lispobj *)(unsigned long)
648             (*os_context_register_addr(context, reg_CFP))
649         == access_control_frame_pointer(th)) {
650         /* There is a small window during call where the callee's
651          * frame isn't built yet. */
652         if (lowtag_of(*os_context_register_addr(context, reg_CODE))
653             == FUN_POINTER_LOWTAG) {
654             /* We have called, but not built the new frame, so
655              * build it for them. */
656             access_control_frame_pointer(th)[0] =
657                 *os_context_register_addr(context, reg_OCFP);
658             access_control_frame_pointer(th)[1] =
659                 *os_context_register_addr(context, reg_LRA);
660             access_control_frame_pointer(th) += 8;
661             /* Build our frame on top of it. */
662             oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
663         }
664         else {
665             /* We haven't yet called, build our frame as if the
666              * partial frame wasn't there. */
667             oldcont = (lispobj)(*os_context_register_addr(context, reg_OCFP));
668         }
669     }
670     /* We can't tell whether we are still in the caller if it had to
671      * allocate a stack frame due to stack arguments. */
672     /* This observation provoked some past CMUCL maintainer to ask
673      * "Can anything strange happen during return?" */
674     else {
675         /* normal case */
676         oldcont = (lispobj)(*os_context_register_addr(context, reg_CFP));
677     }
678
679     access_control_stack_pointer(th) = access_control_frame_pointer(th) + 8;
680
681     access_control_frame_pointer(th)[0] = oldcont;
682     access_control_frame_pointer(th)[1] = NIL;
683     access_control_frame_pointer(th)[2] =
684         (lispobj)(*os_context_register_addr(context, reg_CODE));
685 #endif
686 }
687
688 /* Stores the context for gc to scavange and builds fake stack
689  * frames. */
690 void
691 fake_foreign_function_call(os_context_t *context)
692 {
693     int context_index;
694     struct thread *thread=arch_os_get_current_thread();
695
696     /* context_index incrementing must not be interrupted */
697     check_blockables_blocked_or_lose(0);
698
699     /* Get current Lisp state from context. */
700 #ifdef reg_ALLOC
701 #ifdef LISP_FEATURE_SB_THREAD
702     thread->pseudo_atomic_bits =
703 #else
704     dynamic_space_free_pointer =
705         (lispobj *)(unsigned long)
706 #endif
707             (*os_context_register_addr(context, reg_ALLOC));
708 /*     fprintf(stderr,"dynamic_space_free_pointer: %p\n", */
709 /*             dynamic_space_free_pointer); */
710 #if defined(LISP_FEATURE_ALPHA) || defined(LISP_FEATURE_MIPS)
711     if ((long)dynamic_space_free_pointer & 1) {
712         lose("dead in fake_foreign_function_call, context = %x\n", context);
713     }
714 #endif
715 /* why doesnt PPC and SPARC do something like this: */
716 #if defined(LISP_FEATURE_HPPA)
717     if ((long)dynamic_space_free_pointer & 4) {
718         lose("dead in fake_foreign_function_call, context = %x, d_s_f_p = %x\n", context, dynamic_space_free_pointer);
719     }
720 #endif
721 #endif
722 #ifdef reg_BSP
723     set_binding_stack_pointer(thread,
724         *os_context_register_addr(context, reg_BSP));
725 #endif
726
727     build_fake_control_stack_frames(thread,context);
728
729     /* Do dynamic binding of the active interrupt context index
730      * and save the context in the context array. */
731     context_index =
732         fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,thread));
733
734     if (context_index >= MAX_INTERRUPTS) {
735         lose("maximum interrupt nesting depth (%d) exceeded\n", MAX_INTERRUPTS);
736     }
737
738     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,
739                   make_fixnum(context_index + 1),thread);
740
741     thread->interrupt_contexts[context_index] = context;
742
743 #if !defined(LISP_FEATURE_X86) && !defined(LISP_FEATURE_X86_64)
744     /* x86oid targets don't maintain the foreign function call flag at
745      * all, so leave them to believe that they are never in foreign
746      * code. */
747     foreign_function_call_active_p(thread) = 1;
748 #endif
749 }
750
751 /* blocks all blockable signals.  If you are calling from a signal handler,
752  * the usual signal mask will be restored from the context when the handler
753  * finishes.  Otherwise, be careful */
754 void
755 undo_fake_foreign_function_call(os_context_t *context)
756 {
757     struct thread *thread=arch_os_get_current_thread();
758     /* Block all blockable signals. */
759     block_blockable_signals(0, 0);
760
761     foreign_function_call_active_p(thread) = 0;
762
763     /* Undo dynamic binding of FREE_INTERRUPT_CONTEXT_INDEX */
764     unbind(thread);
765
766 #if defined(reg_ALLOC) && !defined(LISP_FEATURE_SB_THREAD)
767     /* Put the dynamic space free pointer back into the context. */
768     *os_context_register_addr(context, reg_ALLOC) =
769         (unsigned long) dynamic_space_free_pointer
770         | (*os_context_register_addr(context, reg_ALLOC)
771            & LOWTAG_MASK);
772     /*
773       ((unsigned long)(*os_context_register_addr(context, reg_ALLOC))
774       & ~LOWTAG_MASK)
775       | ((unsigned long) dynamic_space_free_pointer & LOWTAG_MASK);
776     */
777 #endif
778 #if defined(reg_ALLOC) && defined(LISP_FEATURE_SB_THREAD)
779     /* Put the pseudo-atomic bits and dynamic space free pointer back
780      * into the context (p-a-bits for p-a, and dynamic space free
781      * pointer for ROOM). */
782     *os_context_register_addr(context, reg_ALLOC) =
783         (unsigned long) dynamic_space_free_pointer
784         | (thread->pseudo_atomic_bits & LOWTAG_MASK);
785     /* And clear them so we don't get bit later by call-in/call-out
786      * not updating them. */
787     thread->pseudo_atomic_bits = 0;
788 #endif
789 }
790
791 /* a handler for the signal caused by execution of a trap opcode
792  * signalling an internal error */
793 void
794 interrupt_internal_error(os_context_t *context, boolean continuable)
795 {
796     lispobj context_sap;
797
798     fake_foreign_function_call(context);
799
800     if (!internal_errors_enabled) {
801         describe_internal_error(context);
802         /* There's no good way to recover from an internal error
803          * before the Lisp error handling mechanism is set up. */
804         lose("internal error too early in init, can't recover\n");
805     }
806
807     /* Allocate the SAP object while the interrupts are still
808      * disabled. */
809 #ifndef LISP_FEATURE_SB_SAFEPOINT
810     unblock_gc_signals(0, 0);
811 #endif
812     context_sap = alloc_sap(context);
813
814 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
815     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
816 #endif
817
818 #if defined(LISP_FEATURE_LINUX) && defined(LISP_FEATURE_MIPS)
819     /* Workaround for blocked SIGTRAP. */
820     {
821         sigset_t newset;
822         sigemptyset(&newset);
823         sigaddset(&newset, SIGTRAP);
824         thread_sigmask(SIG_UNBLOCK, &newset, 0);
825     }
826 #endif
827
828     SHOW("in interrupt_internal_error");
829 #if QSHOW == 2
830     /* Display some rudimentary debugging information about the
831      * error, so that even if the Lisp error handler gets badly
832      * confused, we have a chance to determine what's going on. */
833     describe_internal_error(context);
834 #endif
835     funcall2(StaticSymbolFunction(INTERNAL_ERROR), context_sap,
836              continuable ? T : NIL);
837
838     undo_fake_foreign_function_call(context); /* blocks signals again */
839     if (continuable)
840         arch_skip_instruction(context);
841 }
842
843 boolean
844 interrupt_handler_pending_p(void)
845 {
846     struct thread *thread = arch_os_get_current_thread();
847     struct interrupt_data *data = thread->interrupt_data;
848     return (data->pending_handler != 0);
849 }
850
851 void
852 interrupt_handle_pending(os_context_t *context)
853 {
854     /* There are three ways we can get here. First, if an interrupt
855      * occurs within pseudo-atomic, it will be deferred, and we'll
856      * trap to here at the end of the pseudo-atomic block. Second, if
857      * the GC (in alloc()) decides that a GC is required, it will set
858      * *GC-PENDING* and pseudo-atomic-interrupted if not *GC-INHIBIT*,
859      * and alloc() is always called from within pseudo-atomic, and
860      * thus we end up here again. Third, when calling GC-ON or at the
861      * end of a WITHOUT-GCING, MAYBE-HANDLE-PENDING-GC will trap to
862      * here if there is a pending GC. Fourth, ahem, at the end of
863      * WITHOUT-INTERRUPTS (bar complications with nesting).
864      *
865      * A fourth way happens with safepoints: In addition to a stop for
866      * GC that is pending, there are thruptions.  Both mechanisms are
867      * mostly signal-free, yet also of an asynchronous nature, so it makes
868      * sense to let interrupt_handle_pending take care of running them:
869      * It gets run precisely at those places where it is safe to process
870      * pending asynchronous tasks. */
871
872     struct thread *thread = arch_os_get_current_thread();
873     struct interrupt_data *data = thread->interrupt_data;
874
875     if (arch_pseudo_atomic_atomic(context)) {
876         lose("Handling pending interrupt in pseudo atomic.");
877     }
878
879     FSHOW_SIGNAL((stderr, "/entering interrupt_handle_pending\n"));
880
881     check_blockables_blocked_or_lose(0);
882 #ifndef LISP_FEATURE_SB_SAFEPOINT
883     /*
884      * (On safepoint builds, there is no gc_blocked_deferrables nor
885      * SIG_STOP_FOR_GC.)
886      */
887     /* If GC/SIG_STOP_FOR_GC struck during PA and there was no pending
888      * handler, then the pending mask was saved and
889      * gc_blocked_deferrables set. Hence, there can be no pending
890      * handler and it's safe to restore the pending mask.
891      *
892      * Note, that if gc_blocked_deferrables is false we may still have
893      * to GC. In this case, we are coming out of a WITHOUT-GCING or a
894      * pseudo atomic was interrupt be a deferrable first. */
895     if (data->gc_blocked_deferrables) {
896         if (data->pending_handler)
897             lose("GC blocked deferrables but still got a pending handler.");
898         if (SymbolValue(GC_INHIBIT,thread)!=NIL)
899             lose("GC blocked deferrables while GC is inhibited.");
900         /* Restore the saved signal mask from the original signal (the
901          * one that interrupted us during the critical section) into
902          * the os_context for the signal we're currently in the
903          * handler for. This should ensure that when we return from
904          * the handler the blocked signals are unblocked. */
905 #ifndef LISP_FEATURE_WIN32
906         sigcopyset(os_context_sigmask_addr(context), &data->pending_mask);
907 #endif
908         data->gc_blocked_deferrables = 0;
909     }
910 #endif
911
912     if (SymbolValue(GC_INHIBIT,thread)==NIL) {
913         void *original_pending_handler = data->pending_handler;
914
915 #ifdef LISP_FEATURE_SB_SAFEPOINT
916         /* handles the STOP_FOR_GC_PENDING case, plus THRUPTIONS */
917         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL
918 # ifdef LISP_FEATURE_SB_THRUPTION
919             || SymbolValue(THRUPTION_PENDING,thread) != NIL
920 # endif
921             )
922         {
923             /* We ought to take this chance to do a pitstop now. */
924
925             /* Now, it goes without saying that the context sigmask
926              * tweaking around this call is not pretty.  However, it
927              * currently seems to be "needed" for the following
928              * situation.  (So let's find a better solution and remove
929              * this comment afterwards.)
930              *
931              * Suppose we are in a signal handler (let's say SIGALRM).
932              * At the end of a WITHOUT-INTERRUPTS, the lisp code notices
933              * that a thruption is pending, and says to itself "let's
934              * receive pending interrupts then".  We trust that the
935              * caller is happy to run those sorts of things now,
936              * including thruptions, otherwise it wouldn't have called
937              * us.  But that's the problem: Even though we can guess the
938              * caller's intention, may_thrupt() would see that signals
939              * are blocked in the signal context (because that context
940              * itself points to a signal handler).  So we cheat and
941              * pretend that signals weren't blocked.
942              * --DFL */
943 #ifndef LISP_FEATURE_WIN32
944             sigset_t old, *ctxset = os_context_sigmask_addr(context);
945             unblock_signals(&deferrable_sigset, ctxset, &old);
946 #endif
947             thread_in_lisp_raised(context);
948 #ifndef LISP_FEATURE_WIN32
949             sigcopyset(&old, ctxset);
950 #endif
951         }
952 #elif defined(LISP_FEATURE_SB_THREAD)
953         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL) {
954             /* STOP_FOR_GC_PENDING and GC_PENDING are cleared by
955              * the signal handler if it actually stops us. */
956             arch_clear_pseudo_atomic_interrupted(context);
957             sig_stop_for_gc_handler(SIG_STOP_FOR_GC,NULL,context);
958         } else
959 #endif
960          /* Test for T and not for != NIL since the value :IN-PROGRESS
961           * is used in SUB-GC as part of the mechanism to supress
962           * recursive gcs.*/
963         if (SymbolValue(GC_PENDING,thread) == T) {
964
965             /* Two reasons for doing this. First, if there is a
966              * pending handler we don't want to run. Second, we are
967              * going to clear pseudo atomic interrupted to avoid
968              * spurious trapping on every allocation in SUB_GC and
969              * having a pending handler with interrupts enabled and
970              * without pseudo atomic interrupted breaks an
971              * invariant. */
972             if (data->pending_handler) {
973                 bind_variable(ALLOW_WITH_INTERRUPTS, NIL, thread);
974                 bind_variable(INTERRUPTS_ENABLED, NIL, thread);
975             }
976
977             arch_clear_pseudo_atomic_interrupted(context);
978
979             /* GC_PENDING is cleared in SUB-GC, or if another thread
980              * is doing a gc already we will get a SIG_STOP_FOR_GC and
981              * that will clear it.
982              *
983              * If there is a pending handler or gc was triggerred in a
984              * signal handler then maybe_gc won't run POST_GC and will
985              * return normally. */
986             if (!maybe_gc(context))
987                 lose("GC not inhibited but maybe_gc did not GC.");
988
989             if (data->pending_handler) {
990                 unbind(thread);
991                 unbind(thread);
992             }
993         } else if (SymbolValue(GC_PENDING,thread) != NIL) {
994             /* It's not NIL or T so GC_PENDING is :IN-PROGRESS. If
995              * GC-PENDING is not NIL then we cannot trap on pseudo
996              * atomic due to GC (see if(GC_PENDING) logic in
997              * cheneygc.c an gengcgc.c), plus there is a outer
998              * WITHOUT-INTERRUPTS SUB_GC, so how did we end up
999              * here? */
1000             lose("Trapping to run pending handler while GC in progress.");
1001         }
1002
1003         check_blockables_blocked_or_lose(0);
1004
1005         /* No GC shall be lost. If SUB_GC triggers another GC then
1006          * that should be handled on the spot. */
1007         if (SymbolValue(GC_PENDING,thread) != NIL)
1008             lose("GC_PENDING after doing gc.");
1009 #ifdef THREADS_USING_GCSIGNAL
1010         if (SymbolValue(STOP_FOR_GC_PENDING,thread) != NIL)
1011             lose("STOP_FOR_GC_PENDING after doing gc.");
1012 #endif
1013         /* Check two things. First, that gc does not clobber a handler
1014          * that's already pending. Second, that there is no interrupt
1015          * lossage: if original_pending_handler was NULL then even if
1016          * an interrupt arrived during GC (POST-GC, really) it was
1017          * handled. */
1018         if (original_pending_handler != data->pending_handler)
1019             lose("pending handler changed in gc: %x -> %d.",
1020                  original_pending_handler, data->pending_handler);
1021     }
1022
1023 #ifndef LISP_FEATURE_WIN32
1024     /* There may be no pending handler, because it was only a gc that
1025      * had to be executed or because Lisp is a bit too eager to call
1026      * DO-PENDING-INTERRUPT. */
1027     if ((SymbolValue(INTERRUPTS_ENABLED,thread) != NIL) &&
1028         (data->pending_handler))  {
1029         /* No matter how we ended up here, clear both
1030          * INTERRUPT_PENDING and pseudo atomic interrupted. It's safe
1031          * because we checked above that there is no GC pending. */
1032         SetSymbolValue(INTERRUPT_PENDING, NIL, thread);
1033         arch_clear_pseudo_atomic_interrupted(context);
1034         /* Restore the sigmask in the context. */
1035         sigcopyset(os_context_sigmask_addr(context), &data->pending_mask);
1036         run_deferred_handler(data, context);
1037     }
1038 #ifdef LISP_FEATURE_SB_THRUPTION
1039     if (SymbolValue(THRUPTION_PENDING,thread)==T)
1040         /* Special case for the following situation: There is a
1041          * thruption pending, but a signal had been deferred.  The
1042          * pitstop at the top of this function could only take care
1043          * of GC, and skipped the thruption, so we need to try again
1044          * now that INTERRUPT_PENDING and the sigmask have been
1045          * reset. */
1046         while (check_pending_thruptions(context))
1047             ;
1048 #endif
1049 #endif
1050 #ifdef LISP_FEATURE_GENCGC
1051     if (get_pseudo_atomic_interrupted(thread))
1052         lose("pseudo_atomic_interrupted after interrupt_handle_pending\n");
1053 #endif
1054     /* It is possible that the end of this function was reached
1055      * without never actually doing anything, the tests in Lisp for
1056      * when to call receive-pending-interrupt are not exact. */
1057     FSHOW_SIGNAL((stderr, "/exiting interrupt_handle_pending\n"));
1058 }
1059 \f
1060
1061 void
1062 interrupt_handle_now(int signal, siginfo_t *info, os_context_t *context)
1063 {
1064     boolean were_in_lisp;
1065     union interrupt_handler handler;
1066
1067     check_blockables_blocked_or_lose(0);
1068
1069 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
1070     if (sigismember(&deferrable_sigset,signal))
1071         check_interrupts_enabled_or_lose(context);
1072 #endif
1073
1074     handler = interrupt_handlers[signal];
1075
1076     if (ARE_SAME_HANDLER(handler.c, SIG_IGN)) {
1077         return;
1078     }
1079
1080     were_in_lisp = !foreign_function_call_active_p(arch_os_get_current_thread());
1081     if (were_in_lisp)
1082     {
1083         fake_foreign_function_call(context);
1084     }
1085
1086     FSHOW_SIGNAL((stderr,
1087                   "/entering interrupt_handle_now(%d, info, context)\n",
1088                   signal));
1089
1090     if (ARE_SAME_HANDLER(handler.c, SIG_DFL)) {
1091
1092         /* This can happen if someone tries to ignore or default one
1093          * of the signals we need for runtime support, and the runtime
1094          * support decides to pass on it. */
1095         lose("no handler for signal %d in interrupt_handle_now(..)\n", signal);
1096
1097     } else if (lowtag_of(handler.lisp) == FUN_POINTER_LOWTAG) {
1098         /* Once we've decided what to do about contexts in a
1099          * return-elsewhere world (the original context will no longer
1100          * be available; should we copy it or was nobody using it anyway?)
1101          * then we should convert this to return-elsewhere */
1102
1103         /* CMUCL comment said "Allocate the SAPs while the interrupts
1104          * are still disabled.".  I (dan, 2003.08.21) assume this is
1105          * because we're not in pseudoatomic and allocation shouldn't
1106          * be interrupted.  In which case it's no longer an issue as
1107          * all our allocation from C now goes through a PA wrapper,
1108          * but still, doesn't hurt.
1109          *
1110          * Yeah, but non-gencgc platforms don't really wrap allocation
1111          * in PA. MG - 2005-08-29  */
1112
1113         lispobj info_sap, context_sap;
1114         /* Leave deferrable signals blocked, the handler itself will
1115          * allow signals again when it sees fit. */
1116 #ifndef LISP_FEATURE_SB_SAFEPOINT
1117         unblock_gc_signals(0, 0);
1118 #endif
1119         context_sap = alloc_sap(context);
1120         info_sap = alloc_sap(info);
1121
1122         FSHOW_SIGNAL((stderr,"/calling Lisp-level handler\n"));
1123
1124 #ifdef LISP_FEATURE_SB_SAFEPOINT
1125         WITH_GC_AT_SAFEPOINTS_ONLY()
1126 #endif
1127         funcall3(handler.lisp,
1128                  make_fixnum(signal),
1129                  info_sap,
1130                  context_sap);
1131     } else {
1132         /* This cannot happen in sane circumstances. */
1133
1134         FSHOW_SIGNAL((stderr,"/calling C-level handler\n"));
1135
1136 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
1137         /* Allow signals again. */
1138         thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
1139         (*handler.c)(signal, info, context);
1140 #endif
1141     }
1142
1143     if (were_in_lisp)
1144     {
1145         undo_fake_foreign_function_call(context); /* block signals again */
1146     }
1147
1148     FSHOW_SIGNAL((stderr,
1149                   "/returning from interrupt_handle_now(%d, info, context)\n",
1150                   signal));
1151 }
1152
1153 /* This is called at the end of a critical section if the indications
1154  * are that some signal was deferred during the section.  Note that as
1155  * far as C or the kernel is concerned we dealt with the signal
1156  * already; we're just doing the Lisp-level processing now that we
1157  * put off then */
1158 static void
1159 run_deferred_handler(struct interrupt_data *data, os_context_t *context)
1160 {
1161     /* The pending_handler may enable interrupts and then another
1162      * interrupt may hit, overwrite interrupt_data, so reset the
1163      * pending handler before calling it. Trust the handler to finish
1164      * with the siginfo before enabling interrupts. */
1165     void (*pending_handler) (int, siginfo_t*, os_context_t*) =
1166         data->pending_handler;
1167
1168     data->pending_handler=0;
1169     FSHOW_SIGNAL((stderr, "/running deferred handler %p\n", pending_handler));
1170     (*pending_handler)(data->pending_signal,&(data->pending_info), context);
1171 }
1172
1173 #ifndef LISP_FEATURE_WIN32
1174 boolean
1175 maybe_defer_handler(void *handler, struct interrupt_data *data,
1176                     int signal, siginfo_t *info, os_context_t *context)
1177 {
1178     struct thread *thread=arch_os_get_current_thread();
1179
1180     check_blockables_blocked_or_lose(0);
1181
1182     if (SymbolValue(INTERRUPT_PENDING,thread) != NIL)
1183         lose("interrupt already pending\n");
1184     if (thread->interrupt_data->pending_handler)
1185         lose("there is a pending handler already (PA)\n");
1186     if (data->gc_blocked_deferrables)
1187         lose("maybe_defer_handler: gc_blocked_deferrables true\n");
1188     check_interrupt_context_or_lose(context);
1189     /* If interrupts are disabled then INTERRUPT_PENDING is set and
1190      * not PSEDUO_ATOMIC_INTERRUPTED. This is important for a pseudo
1191      * atomic section inside a WITHOUT-INTERRUPTS.
1192      *
1193      * Also, if in_leaving_without_gcing_race_p then
1194      * interrupt_handle_pending is going to be called soon, so
1195      * stashing the signal away is safe.
1196      */
1197     if ((SymbolValue(INTERRUPTS_ENABLED,thread) == NIL) ||
1198         in_leaving_without_gcing_race_p(thread)) {
1199         FSHOW_SIGNAL((stderr,
1200                       "/maybe_defer_handler(%x,%d): deferred (RACE=%d)\n",
1201                       (unsigned int)handler,signal,
1202                       in_leaving_without_gcing_race_p(thread)));
1203         store_signal_data_for_later(data,handler,signal,info,context);
1204         SetSymbolValue(INTERRUPT_PENDING, T,thread);
1205         check_interrupt_context_or_lose(context);
1206         return 1;
1207     }
1208     /* a slightly confusing test. arch_pseudo_atomic_atomic() doesn't
1209      * actually use its argument for anything on x86, so this branch
1210      * may succeed even when context is null (gencgc alloc()) */
1211     if (arch_pseudo_atomic_atomic(context)) {
1212         FSHOW_SIGNAL((stderr,
1213                       "/maybe_defer_handler(%x,%d): deferred(PA)\n",
1214                       (unsigned int)handler,signal));
1215         store_signal_data_for_later(data,handler,signal,info,context);
1216         arch_set_pseudo_atomic_interrupted(context);
1217         check_interrupt_context_or_lose(context);
1218         return 1;
1219     }
1220     FSHOW_SIGNAL((stderr,
1221                   "/maybe_defer_handler(%x,%d): not deferred\n",
1222                   (unsigned int)handler,signal));
1223     return 0;
1224 }
1225
1226 static void
1227 store_signal_data_for_later (struct interrupt_data *data, void *handler,
1228                              int signal,
1229                              siginfo_t *info, os_context_t *context)
1230 {
1231     if (data->pending_handler)
1232         lose("tried to overwrite pending interrupt handler %x with %x\n",
1233              data->pending_handler, handler);
1234     if (!handler)
1235         lose("tried to defer null interrupt handler\n");
1236     data->pending_handler = handler;
1237     data->pending_signal = signal;
1238     if(info)
1239         memcpy(&(data->pending_info), info, sizeof(siginfo_t));
1240
1241     FSHOW_SIGNAL((stderr, "/store_signal_data_for_later: signal: %d\n",
1242                   signal));
1243
1244     if(!context)
1245         lose("Null context");
1246
1247     /* the signal mask in the context (from before we were
1248      * interrupted) is copied to be restored when run_deferred_handler
1249      * happens. Then the usually-blocked signals are added to the mask
1250      * in the context so that we are running with blocked signals when
1251      * the handler returns */
1252     sigcopyset(&(data->pending_mask),os_context_sigmask_addr(context));
1253     sigaddset_deferrable(os_context_sigmask_addr(context));
1254 }
1255
1256 static void
1257 maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
1258 {
1259     SAVE_ERRNO(signal,context,void_context);
1260     struct thread *thread = arch_os_get_current_thread();
1261     struct interrupt_data *data = thread->interrupt_data;
1262     if(!maybe_defer_handler(interrupt_handle_now,data,signal,info,context))
1263         interrupt_handle_now(signal, info, context);
1264     RESTORE_ERRNO;
1265 }
1266
1267 static void
1268 low_level_interrupt_handle_now(int signal, siginfo_t *info,
1269                                os_context_t *context)
1270 {
1271     /* No FP control fixage needed, caller has done that. */
1272     check_blockables_blocked_or_lose(0);
1273     check_interrupts_enabled_or_lose(context);
1274     (*interrupt_low_level_handlers[signal])(signal, info, context);
1275     /* No Darwin context fixage needed, caller does that. */
1276 }
1277
1278 static void
1279 low_level_maybe_now_maybe_later(int signal, siginfo_t *info, void *void_context)
1280 {
1281     SAVE_ERRNO(signal,context,void_context);
1282     struct thread *thread = arch_os_get_current_thread();
1283     struct interrupt_data *data = thread->interrupt_data;
1284
1285     if(!maybe_defer_handler(low_level_interrupt_handle_now,data,
1286                             signal,info,context))
1287         low_level_interrupt_handle_now(signal, info, context);
1288     RESTORE_ERRNO;
1289 }
1290 #endif
1291
1292 #ifdef THREADS_USING_GCSIGNAL
1293
1294 /* This function must not cons, because that may trigger a GC. */
1295 void
1296 sig_stop_for_gc_handler(int signal, siginfo_t *info, os_context_t *context)
1297 {
1298     struct thread *thread=arch_os_get_current_thread();
1299     boolean was_in_lisp;
1300
1301     /* Test for GC_INHIBIT _first_, else we'd trap on every single
1302      * pseudo atomic until gc is finally allowed. */
1303     if (SymbolValue(GC_INHIBIT,thread) != NIL) {
1304         FSHOW_SIGNAL((stderr, "sig_stop_for_gc deferred (*GC-INHIBIT*)\n"));
1305         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
1306         return;
1307     } else if (arch_pseudo_atomic_atomic(context)) {
1308         FSHOW_SIGNAL((stderr,"sig_stop_for_gc deferred (PA)\n"));
1309         SetSymbolValue(STOP_FOR_GC_PENDING,T,thread);
1310         arch_set_pseudo_atomic_interrupted(context);
1311         maybe_save_gc_mask_and_block_deferrables
1312             (os_context_sigmask_addr(context));
1313         return;
1314     }
1315
1316     FSHOW_SIGNAL((stderr, "/sig_stop_for_gc_handler\n"));
1317
1318     /* Not PA and GC not inhibited -- we can stop now. */
1319
1320     was_in_lisp = !foreign_function_call_active_p(arch_os_get_current_thread());
1321
1322     if (was_in_lisp) {
1323         /* need the context stored so it can have registers scavenged */
1324         fake_foreign_function_call(context);
1325     }
1326
1327     /* Not pending anymore. */
1328     SetSymbolValue(GC_PENDING,NIL,thread);
1329     SetSymbolValue(STOP_FOR_GC_PENDING,NIL,thread);
1330
1331     /* Consider this: in a PA section GC is requested: GC_PENDING,
1332      * pseudo_atomic_interrupted and gc_blocked_deferrables are set,
1333      * deferrables are blocked then pseudo_atomic_atomic is cleared,
1334      * but a SIG_STOP_FOR_GC arrives before trapping to
1335      * interrupt_handle_pending. Here, GC_PENDING is cleared but
1336      * pseudo_atomic_interrupted is not and we go on running with
1337      * pseudo_atomic_interrupted but without a pending interrupt or
1338      * GC. GC_BLOCKED_DEFERRABLES is also left at 1. So let's tidy it
1339      * up. */
1340     if (thread->interrupt_data->gc_blocked_deferrables) {
1341         FSHOW_SIGNAL((stderr,"cleaning up after gc_blocked_deferrables\n"));
1342         clear_pseudo_atomic_interrupted(thread);
1343         sigcopyset(os_context_sigmask_addr(context),
1344                    &thread->interrupt_data->pending_mask);
1345         thread->interrupt_data->gc_blocked_deferrables = 0;
1346     }
1347
1348     if(thread_state(thread)!=STATE_RUNNING) {
1349         lose("sig_stop_for_gc_handler: wrong thread state: %ld\n",
1350              fixnum_value(thread->state));
1351     }
1352
1353     set_thread_state(thread,STATE_STOPPED);
1354     FSHOW_SIGNAL((stderr,"suspended\n"));
1355
1356     /* While waiting for gc to finish occupy ourselves with zeroing
1357      * the unused portion of the control stack to reduce conservatism.
1358      * On hypothetic platforms with threads and exact gc it is
1359      * actually a must. */
1360     scrub_control_stack();
1361
1362     wait_for_thread_state_change(thread, STATE_STOPPED);
1363     FSHOW_SIGNAL((stderr,"resumed\n"));
1364
1365     if(thread_state(thread)!=STATE_RUNNING) {
1366         lose("sig_stop_for_gc_handler: wrong thread state on wakeup: %ld\n",
1367              fixnum_value(thread_state(thread)));
1368     }
1369
1370     if (was_in_lisp) {
1371         undo_fake_foreign_function_call(context);
1372     }
1373 }
1374
1375 #endif
1376
1377 void
1378 interrupt_handle_now_handler(int signal, siginfo_t *info, void *void_context)
1379 {
1380     SAVE_ERRNO(signal,context,void_context);
1381 #ifndef LISP_FEATURE_WIN32
1382     if ((signal == SIGILL) || (signal == SIGBUS)
1383 #ifndef LISP_FEATURE_LINUX
1384         || (signal == SIGEMT)
1385 #endif
1386         )
1387         corruption_warning_and_maybe_lose("Signal %d received", signal);
1388 #endif
1389     interrupt_handle_now(signal, info, context);
1390     RESTORE_ERRNO;
1391 }
1392
1393 /* manipulate the signal context and stack such that when the handler
1394  * returns, it will call function instead of whatever it was doing
1395  * previously
1396  */
1397
1398 #if (defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
1399 extern int *context_eflags_addr(os_context_t *context);
1400 #endif
1401
1402 extern lispobj call_into_lisp(lispobj fun, lispobj *args, int nargs);
1403 extern void post_signal_tramp(void);
1404 extern void call_into_lisp_tramp(void);
1405
1406 void
1407 arrange_return_to_c_function(os_context_t *context,
1408                              call_into_lisp_lookalike funptr,
1409                              lispobj function)
1410 {
1411 #if !(defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_SAFEPOINT))
1412     check_gc_signals_unblocked_or_lose
1413         (os_context_sigmask_addr(context));
1414 #endif
1415 #if !(defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64))
1416     void * fun=native_pointer(function);
1417     void *code = &(((struct simple_fun *) fun)->code);
1418 #endif
1419
1420     /* Build a stack frame showing `interrupted' so that the
1421      * user's backtrace makes (as much) sense (as usual) */
1422
1423     /* fp state is saved and restored by call_into_lisp */
1424     /* FIXME: errno is not restored, but since current uses of this
1425      * function only call Lisp code that signals an error, it's not
1426      * much of a problem. In other words, running out of the control
1427      * stack between a syscall and (GET-ERRNO) may clobber errno if
1428      * something fails during signalling or in the handler. But I
1429      * can't see what can go wrong as long as there is no CONTINUE
1430      * like restart on them. */
1431 #ifdef LISP_FEATURE_X86
1432     /* Suppose the existence of some function that saved all
1433      * registers, called call_into_lisp, then restored GP registers and
1434      * returned.  It would look something like this:
1435
1436      push   ebp
1437      mov    ebp esp
1438      pushfl
1439      pushal
1440      push   $0
1441      push   $0
1442      pushl  {address of function to call}
1443      call   0x8058db0 <call_into_lisp>
1444      addl   $12,%esp
1445      popal
1446      popfl
1447      leave
1448      ret
1449
1450      * What we do here is set up the stack that call_into_lisp would
1451      * expect to see if it had been called by this code, and frob the
1452      * signal context so that signal return goes directly to call_into_lisp,
1453      * and when that function (and the lisp function it invoked) returns,
1454      * it returns to the second half of this imaginary function which
1455      * restores all registers and returns to C
1456
1457      * For this to work, the latter part of the imaginary function
1458      * must obviously exist in reality.  That would be post_signal_tramp
1459      */
1460
1461     u32 *sp=(u32 *)*os_context_register_addr(context,reg_ESP);
1462
1463 #if defined(LISP_FEATURE_DARWIN)
1464     u32 *register_save_area = (u32 *)os_validate(0, 0x40);
1465
1466     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: preparing to go to function %x, sp: %x\n", function, sp));
1467     FSHOW_SIGNAL((stderr, "/arrange_return_to_lisp_function: context: %x, &context %x\n", context, &context));
1468
1469     /* 1. os_validate (malloc/mmap) register_save_block
1470      * 2. copy register state into register_save_block
1471      * 3. put a pointer to register_save_block in a register in the context
1472      * 4. set the context's EIP to point to a trampoline which:
1473      *    a. builds the fake stack frame from the block
1474      *    b. frees the block
1475      *    c. calls the function
1476      */
1477
1478     *register_save_area = *os_context_pc_addr(context);
1479     *(register_save_area + 1) = function;
1480     *(register_save_area + 2) = *os_context_register_addr(context,reg_EDI);
1481     *(register_save_area + 3) = *os_context_register_addr(context,reg_ESI);
1482     *(register_save_area + 4) = *os_context_register_addr(context,reg_EDX);
1483     *(register_save_area + 5) = *os_context_register_addr(context,reg_ECX);
1484     *(register_save_area + 6) = *os_context_register_addr(context,reg_EBX);
1485     *(register_save_area + 7) = *os_context_register_addr(context,reg_EAX);
1486     *(register_save_area + 8) = *context_eflags_addr(context);
1487
1488     *os_context_pc_addr(context) =
1489       (os_context_register_t) funptr;
1490     *os_context_register_addr(context,reg_ECX) =
1491       (os_context_register_t) register_save_area;
1492 #else
1493
1494     /* return address for call_into_lisp: */
1495     *(sp-15) = (u32)post_signal_tramp;
1496     *(sp-14) = function;        /* args for call_into_lisp : function*/
1497     *(sp-13) = 0;               /*                           arg array */
1498     *(sp-12) = 0;               /*                           no. args */
1499     /* this order matches that used in POPAD */
1500     *(sp-11)=*os_context_register_addr(context,reg_EDI);
1501     *(sp-10)=*os_context_register_addr(context,reg_ESI);
1502
1503     *(sp-9)=*os_context_register_addr(context,reg_ESP)-8;
1504     /* POPAD ignores the value of ESP:  */
1505     *(sp-8)=0;
1506     *(sp-7)=*os_context_register_addr(context,reg_EBX);
1507
1508     *(sp-6)=*os_context_register_addr(context,reg_EDX);
1509     *(sp-5)=*os_context_register_addr(context,reg_ECX);
1510     *(sp-4)=*os_context_register_addr(context,reg_EAX);
1511     *(sp-3)=*context_eflags_addr(context);
1512     *(sp-2)=*os_context_register_addr(context,reg_EBP);
1513     *(sp-1)=*os_context_pc_addr(context);
1514
1515 #endif
1516
1517 #elif defined(LISP_FEATURE_X86_64)
1518     u64 *sp=(u64 *)*os_context_register_addr(context,reg_RSP);
1519
1520     /* return address for call_into_lisp: */
1521     *(sp-18) = (u64)post_signal_tramp;
1522
1523     *(sp-17)=*os_context_register_addr(context,reg_R15);
1524     *(sp-16)=*os_context_register_addr(context,reg_R14);
1525     *(sp-15)=*os_context_register_addr(context,reg_R13);
1526     *(sp-14)=*os_context_register_addr(context,reg_R12);
1527     *(sp-13)=*os_context_register_addr(context,reg_R11);
1528     *(sp-12)=*os_context_register_addr(context,reg_R10);
1529     *(sp-11)=*os_context_register_addr(context,reg_R9);
1530     *(sp-10)=*os_context_register_addr(context,reg_R8);
1531     *(sp-9)=*os_context_register_addr(context,reg_RDI);
1532     *(sp-8)=*os_context_register_addr(context,reg_RSI);
1533     /* skip RBP and RSP */
1534     *(sp-7)=*os_context_register_addr(context,reg_RBX);
1535     *(sp-6)=*os_context_register_addr(context,reg_RDX);
1536     *(sp-5)=*os_context_register_addr(context,reg_RCX);
1537     *(sp-4)=*os_context_register_addr(context,reg_RAX);
1538     *(sp-3)=*context_eflags_addr(context);
1539     *(sp-2)=*os_context_register_addr(context,reg_RBP);
1540     *(sp-1)=*os_context_pc_addr(context);
1541
1542     *os_context_register_addr(context,reg_RDI) =
1543         (os_context_register_t)function; /* function */
1544     *os_context_register_addr(context,reg_RSI) = 0;        /* arg. array */
1545     *os_context_register_addr(context,reg_RDX) = 0;        /* no. args */
1546 #else
1547     struct thread *th=arch_os_get_current_thread();
1548     build_fake_control_stack_frames(th,context);
1549 #endif
1550
1551 #ifdef LISP_FEATURE_X86
1552
1553 #if !defined(LISP_FEATURE_DARWIN)
1554     *os_context_pc_addr(context) = (os_context_register_t)funptr;
1555     *os_context_register_addr(context,reg_ECX) = 0;
1556     *os_context_register_addr(context,reg_EBP) = (os_context_register_t)(sp-2);
1557 #ifdef __NetBSD__
1558     *os_context_register_addr(context,reg_UESP) =
1559         (os_context_register_t)(sp-15);
1560 #else
1561     *os_context_register_addr(context,reg_ESP) = (os_context_register_t)(sp-15);
1562 #endif /* __NETBSD__ */
1563 #endif /* LISP_FEATURE_DARWIN */
1564
1565 #elif defined(LISP_FEATURE_X86_64)
1566     *os_context_pc_addr(context) = (os_context_register_t)funptr;
1567     *os_context_register_addr(context,reg_RCX) = 0;
1568     *os_context_register_addr(context,reg_RBP) = (os_context_register_t)(sp-2);
1569     *os_context_register_addr(context,reg_RSP) = (os_context_register_t)(sp-18);
1570 #else
1571     /* this much of the calling convention is common to all
1572        non-x86 ports */
1573     *os_context_pc_addr(context) = (os_context_register_t)(unsigned long)code;
1574     *os_context_register_addr(context,reg_NARGS) = 0;
1575     *os_context_register_addr(context,reg_LIP) =
1576         (os_context_register_t)(unsigned long)code;
1577     *os_context_register_addr(context,reg_CFP) =
1578         (os_context_register_t)(unsigned long)access_control_frame_pointer(th);
1579 #endif
1580 #ifdef ARCH_HAS_NPC_REGISTER
1581     *os_context_npc_addr(context) =
1582         4 + *os_context_pc_addr(context);
1583 #endif
1584 #ifdef LISP_FEATURE_SPARC
1585     *os_context_register_addr(context,reg_CODE) =
1586         (os_context_register_t)(fun + FUN_POINTER_LOWTAG);
1587 #endif
1588     FSHOW((stderr, "/arranged return to Lisp function (0x%lx)\n",
1589            (long)function));
1590 }
1591
1592 void
1593 arrange_return_to_lisp_function(os_context_t *context, lispobj function)
1594 {
1595 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_X86)
1596     arrange_return_to_c_function(context, call_into_lisp_tramp, function);
1597 #else
1598     arrange_return_to_c_function(context, call_into_lisp, function);
1599 #endif
1600 }
1601
1602 /* KLUDGE: Theoretically the approach we use for undefined alien
1603  * variables should work for functions as well, but on PPC/Darwin
1604  * we get bus error at bogus addresses instead, hence this workaround,
1605  * that has the added benefit of automatically discriminating between
1606  * functions and variables.
1607  */
1608 void
1609 undefined_alien_function(void)
1610 {
1611     funcall0(StaticSymbolFunction(UNDEFINED_ALIEN_FUNCTION_ERROR));
1612 }
1613
1614 void lower_thread_control_stack_guard_page(struct thread *th)
1615 {
1616     protect_control_stack_guard_page(0, th);
1617     protect_control_stack_return_guard_page(1, th);
1618     th->control_stack_guard_page_protected = NIL;
1619     fprintf(stderr, "INFO: Control stack guard page unprotected\n");
1620 }
1621
1622 void reset_thread_control_stack_guard_page(struct thread *th)
1623 {
1624     memset(CONTROL_STACK_GUARD_PAGE(th), 0, os_vm_page_size);
1625     protect_control_stack_guard_page(1, th);
1626     protect_control_stack_return_guard_page(0, th);
1627     th->control_stack_guard_page_protected = T;
1628     fprintf(stderr, "INFO: Control stack guard page reprotected\n");
1629 }
1630
1631 /* Called from the REPL, too. */
1632 void reset_control_stack_guard_page(void)
1633 {
1634     struct thread *th=arch_os_get_current_thread();
1635     if (th->control_stack_guard_page_protected == NIL) {
1636         reset_thread_control_stack_guard_page(th);
1637     }
1638 }
1639
1640 void lower_control_stack_guard_page(void)
1641 {
1642     lower_thread_control_stack_guard_page(arch_os_get_current_thread());
1643 }
1644
1645 boolean
1646 handle_guard_page_triggered(os_context_t *context,os_vm_address_t addr)
1647 {
1648     struct thread *th=arch_os_get_current_thread();
1649
1650     if(addr >= CONTROL_STACK_HARD_GUARD_PAGE(th) &&
1651        addr < CONTROL_STACK_HARD_GUARD_PAGE(th) + os_vm_page_size) {
1652         lose("Control stack exhausted");
1653     }
1654     else if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
1655             addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
1656         /* We hit the end of the control stack: disable guard page
1657          * protection so the error handler has some headroom, protect the
1658          * previous page so that we can catch returns from the guard page
1659          * and restore it. */
1660         if (th->control_stack_guard_page_protected == NIL)
1661             lose("control_stack_guard_page_protected NIL");
1662         lower_control_stack_guard_page();
1663 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1664         /* For the unfortunate case, when the control stack is
1665          * exhausted in a signal handler. */
1666         unblock_signals_in_context_and_maybe_warn(context);
1667 #endif
1668         arrange_return_to_lisp_function
1669             (context, StaticSymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
1670         return 1;
1671     }
1672     else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
1673             addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
1674         /* We're returning from the guard page: reprotect it, and
1675          * unprotect this one. This works even if we somehow missed
1676          * the return-guard-page, and hit it on our way to new
1677          * exhaustion instead. */
1678         if (th->control_stack_guard_page_protected != NIL)
1679             lose("control_stack_guard_page_protected not NIL");
1680         reset_control_stack_guard_page();
1681         return 1;
1682     }
1683     else if(addr >= BINDING_STACK_HARD_GUARD_PAGE(th) &&
1684             addr < BINDING_STACK_HARD_GUARD_PAGE(th) + os_vm_page_size) {
1685         lose("Binding stack exhausted");
1686     }
1687     else if(addr >= BINDING_STACK_GUARD_PAGE(th) &&
1688             addr < BINDING_STACK_GUARD_PAGE(th) + os_vm_page_size) {
1689         protect_binding_stack_guard_page(0, NULL);
1690         protect_binding_stack_return_guard_page(1, NULL);
1691         fprintf(stderr, "INFO: Binding stack guard page unprotected\n");
1692
1693         /* For the unfortunate case, when the binding stack is
1694          * exhausted in a signal handler. */
1695         unblock_signals_in_context_and_maybe_warn(context);
1696         arrange_return_to_lisp_function
1697             (context, StaticSymbolFunction(BINDING_STACK_EXHAUSTED_ERROR));
1698         return 1;
1699     }
1700     else if(addr >= BINDING_STACK_RETURN_GUARD_PAGE(th) &&
1701             addr < BINDING_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
1702         protect_binding_stack_guard_page(1, NULL);
1703         protect_binding_stack_return_guard_page(0, NULL);
1704         fprintf(stderr, "INFO: Binding stack guard page reprotected\n");
1705         return 1;
1706     }
1707     else if(addr >= ALIEN_STACK_HARD_GUARD_PAGE(th) &&
1708             addr < ALIEN_STACK_HARD_GUARD_PAGE(th) + os_vm_page_size) {
1709         lose("Alien stack exhausted");
1710     }
1711     else if(addr >= ALIEN_STACK_GUARD_PAGE(th) &&
1712             addr < ALIEN_STACK_GUARD_PAGE(th) + os_vm_page_size) {
1713         protect_alien_stack_guard_page(0, NULL);
1714         protect_alien_stack_return_guard_page(1, NULL);
1715         fprintf(stderr, "INFO: Alien stack guard page unprotected\n");
1716
1717         /* For the unfortunate case, when the alien stack is
1718          * exhausted in a signal handler. */
1719         unblock_signals_in_context_and_maybe_warn(context);
1720         arrange_return_to_lisp_function
1721             (context, StaticSymbolFunction(ALIEN_STACK_EXHAUSTED_ERROR));
1722         return 1;
1723     }
1724     else if(addr >= ALIEN_STACK_RETURN_GUARD_PAGE(th) &&
1725             addr < ALIEN_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
1726         protect_alien_stack_guard_page(1, NULL);
1727         protect_alien_stack_return_guard_page(0, NULL);
1728         fprintf(stderr, "INFO: Alien stack guard page reprotected\n");
1729         return 1;
1730     }
1731     else if (addr >= undefined_alien_address &&
1732              addr < undefined_alien_address + os_vm_page_size) {
1733         arrange_return_to_lisp_function
1734             (context, StaticSymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
1735         return 1;
1736     }
1737     else return 0;
1738 }
1739 \f
1740 /*
1741  * noise to install handlers
1742  */
1743
1744 #ifndef LISP_FEATURE_WIN32
1745 /* In Linux 2.4 synchronous signals (sigtrap & co) can be delivered if
1746  * they are blocked, in Linux 2.6 the default handler is invoked
1747  * instead that usually coredumps. One might hastily think that adding
1748  * SA_NODEFER helps, but until ~2.6.13 if SA_NODEFER is specified then
1749  * the whole sa_mask is ignored and instead of not adding the signal
1750  * in question to the mask. That means if it's not blockable the
1751  * signal must be unblocked at the beginning of signal handlers.
1752  *
1753  * It turns out that NetBSD's SA_NODEFER doesn't DTRT in a different
1754  * way: if SA_NODEFER is set and the signal is in sa_mask, the signal
1755  * will be unblocked in the sigmask during the signal handler.  -- RMK
1756  * X-mas day, 2005
1757  */
1758 static volatile int sigaction_nodefer_works = -1;
1759
1760 #define SA_NODEFER_TEST_BLOCK_SIGNAL SIGABRT
1761 #define SA_NODEFER_TEST_KILL_SIGNAL SIGUSR1
1762
1763 static void
1764 sigaction_nodefer_test_handler(int signal, siginfo_t *info, void *void_context)
1765 {
1766     sigset_t current;
1767     int i;
1768     get_current_sigmask(&current);
1769     /* There should be exactly two blocked signals: the two we added
1770      * to sa_mask when setting up the handler.  NetBSD doesn't block
1771      * the signal we're handling when SA_NODEFER is set; Linux before
1772      * 2.6.13 or so also doesn't block the other signal when
1773      * SA_NODEFER is set. */
1774     for(i = 1; i < NSIG; i++)
1775         if (sigismember(&current, i) !=
1776             (((i == SA_NODEFER_TEST_BLOCK_SIGNAL) || (i == signal)) ? 1 : 0)) {
1777             FSHOW_SIGNAL((stderr, "SA_NODEFER doesn't work, signal %d\n", i));
1778             sigaction_nodefer_works = 0;
1779         }
1780     if (sigaction_nodefer_works == -1)
1781         sigaction_nodefer_works = 1;
1782 }
1783
1784 static void
1785 see_if_sigaction_nodefer_works(void)
1786 {
1787     struct sigaction sa, old_sa;
1788
1789     sa.sa_flags = SA_SIGINFO | SA_NODEFER;
1790     sa.sa_sigaction = sigaction_nodefer_test_handler;
1791     sigemptyset(&sa.sa_mask);
1792     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_BLOCK_SIGNAL);
1793     sigaddset(&sa.sa_mask, SA_NODEFER_TEST_KILL_SIGNAL);
1794     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &sa, &old_sa);
1795     /* Make sure no signals are blocked. */
1796     {
1797         sigset_t empty;
1798         sigemptyset(&empty);
1799         thread_sigmask(SIG_SETMASK, &empty, 0);
1800     }
1801     kill(getpid(), SA_NODEFER_TEST_KILL_SIGNAL);
1802     while (sigaction_nodefer_works == -1);
1803     sigaction(SA_NODEFER_TEST_KILL_SIGNAL, &old_sa, NULL);
1804 }
1805
1806 #undef SA_NODEFER_TEST_BLOCK_SIGNAL
1807 #undef SA_NODEFER_TEST_KILL_SIGNAL
1808
1809 static void
1810 unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1811 {
1812     SAVE_ERRNO(signal,context,void_context);
1813     sigset_t unblock;
1814
1815     sigemptyset(&unblock);
1816     sigaddset(&unblock, signal);
1817     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1818     interrupt_handle_now(signal, info, context);
1819     RESTORE_ERRNO;
1820 }
1821
1822 static void
1823 low_level_unblock_me_trampoline(int signal, siginfo_t *info, void *void_context)
1824 {
1825     SAVE_ERRNO(signal,context,void_context);
1826     sigset_t unblock;
1827
1828     sigemptyset(&unblock);
1829     sigaddset(&unblock, signal);
1830     thread_sigmask(SIG_UNBLOCK, &unblock, 0);
1831     (*interrupt_low_level_handlers[signal])(signal, info, context);
1832     RESTORE_ERRNO;
1833 }
1834
1835 static void
1836 low_level_handle_now_handler(int signal, siginfo_t *info, void *void_context)
1837 {
1838     SAVE_ERRNO(signal,context,void_context);
1839     (*interrupt_low_level_handlers[signal])(signal, info, context);
1840     RESTORE_ERRNO;
1841 }
1842
1843 void
1844 undoably_install_low_level_interrupt_handler (int signal,
1845                                               interrupt_handler_t handler)
1846 {
1847     struct sigaction sa;
1848
1849     if (0 > signal || signal >= NSIG) {
1850         lose("bad signal number %d\n", signal);
1851     }
1852
1853     if (ARE_SAME_HANDLER(handler, SIG_DFL))
1854         sa.sa_sigaction = (void (*)(int, siginfo_t*, void*))handler;
1855     else if (sigismember(&deferrable_sigset,signal))
1856         sa.sa_sigaction = low_level_maybe_now_maybe_later;
1857     else if (!sigaction_nodefer_works &&
1858              !sigismember(&blockable_sigset, signal))
1859         sa.sa_sigaction = low_level_unblock_me_trampoline;
1860     else
1861         sa.sa_sigaction = low_level_handle_now_handler;
1862
1863 #ifdef LISP_FEATURE_SB_THRUPTION
1864     /* It's in `deferrable_sigset' so that we block&unblock it properly,
1865      * but we don't actually want to defer it.  And if we put it only
1866      * into blockable_sigset, we'd have to special-case it around thread
1867      * creation at least. */
1868     if (signal == SIGPIPE)
1869         sa.sa_sigaction = low_level_handle_now_handler;
1870 #endif
1871
1872     sigcopyset(&sa.sa_mask, &blockable_sigset);
1873     sa.sa_flags = SA_SIGINFO | SA_RESTART
1874         | (sigaction_nodefer_works ? SA_NODEFER : 0);
1875 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
1876     if(signal==SIG_MEMORY_FAULT) {
1877         sa.sa_flags |= SA_ONSTACK;
1878 # ifdef LISP_FEATURE_SB_SAFEPOINT
1879         sigaddset(&sa.sa_mask, SIGRTMIN);
1880         sigaddset(&sa.sa_mask, SIGRTMIN+1);
1881 # endif
1882     }
1883 #endif
1884
1885     sigaction(signal, &sa, NULL);
1886     interrupt_low_level_handlers[signal] =
1887         (ARE_SAME_HANDLER(handler, SIG_DFL) ? 0 : handler);
1888 }
1889 #endif
1890
1891 /* This is called from Lisp. */
1892 unsigned long
1893 install_handler(int signal, void handler(int, siginfo_t*, os_context_t*))
1894 {
1895 #ifndef LISP_FEATURE_WIN32
1896     struct sigaction sa;
1897     sigset_t old;
1898     union interrupt_handler oldhandler;
1899
1900     FSHOW((stderr, "/entering POSIX install_handler(%d, ..)\n", signal));
1901
1902     block_blockable_signals(0, &old);
1903
1904     FSHOW((stderr, "/interrupt_low_level_handlers[signal]=%x\n",
1905            (unsigned int)interrupt_low_level_handlers[signal]));
1906     if (interrupt_low_level_handlers[signal]==0) {
1907         if (ARE_SAME_HANDLER(handler, SIG_DFL) ||
1908             ARE_SAME_HANDLER(handler, SIG_IGN))
1909             sa.sa_sigaction = (void (*)(int, siginfo_t*, void*))handler;
1910         else if (sigismember(&deferrable_sigset, signal))
1911             sa.sa_sigaction = maybe_now_maybe_later;
1912         else if (!sigaction_nodefer_works &&
1913                  !sigismember(&blockable_sigset, signal))
1914             sa.sa_sigaction = unblock_me_trampoline;
1915         else
1916             sa.sa_sigaction = interrupt_handle_now_handler;
1917
1918         sigcopyset(&sa.sa_mask, &blockable_sigset);
1919         sa.sa_flags = SA_SIGINFO | SA_RESTART |
1920             (sigaction_nodefer_works ? SA_NODEFER : 0);
1921         sigaction(signal, &sa, NULL);
1922     }
1923
1924     oldhandler = interrupt_handlers[signal];
1925     interrupt_handlers[signal].c = handler;
1926
1927     thread_sigmask(SIG_SETMASK, &old, 0);
1928
1929     FSHOW((stderr, "/leaving POSIX install_handler(%d, ..)\n", signal));
1930
1931     return (unsigned long)oldhandler.lisp;
1932 #else
1933     /* Probably-wrong Win32 hack */
1934     return 0;
1935 #endif
1936 }
1937
1938 /* This must not go through lisp as it's allowed anytime, even when on
1939  * the altstack. */
1940 void
1941 sigabrt_handler(int signal, siginfo_t *info, os_context_t *context)
1942 {
1943     lose("SIGABRT received.\n");
1944 }
1945
1946 void
1947 interrupt_init(void)
1948 {
1949 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
1950     int i;
1951     SHOW("entering interrupt_init()");
1952 #ifndef LISP_FEATURE_WIN32
1953     see_if_sigaction_nodefer_works();
1954 #endif
1955     sigemptyset(&deferrable_sigset);
1956     sigemptyset(&blockable_sigset);
1957     sigemptyset(&gc_sigset);
1958     sigaddset_deferrable(&deferrable_sigset);
1959     sigaddset_blockable(&blockable_sigset);
1960     sigaddset_gc(&gc_sigset);
1961 #endif
1962
1963 #ifndef LISP_FEATURE_WIN32
1964     /* Set up high level handler information. */
1965     for (i = 0; i < NSIG; i++) {
1966         interrupt_handlers[i].c =
1967             /* (The cast here blasts away the distinction between
1968              * SA_SIGACTION-style three-argument handlers and
1969              * signal(..)-style one-argument handlers, which is OK
1970              * because it works to call the 1-argument form where the
1971              * 3-argument form is expected.) */
1972             (void (*)(int, siginfo_t*, os_context_t*))SIG_DFL;
1973     }
1974     undoably_install_low_level_interrupt_handler(SIGABRT, sigabrt_handler);
1975 #endif
1976     SHOW("returning from interrupt_init()");
1977 }
1978
1979 #ifndef LISP_FEATURE_WIN32
1980 int
1981 siginfo_code(siginfo_t *info)
1982 {
1983     return info->si_code;
1984 }
1985 os_vm_address_t current_memory_fault_address;
1986
1987 void
1988 lisp_memory_fault_error(os_context_t *context, os_vm_address_t addr)
1989 {
1990    /* FIXME: This is lossy: if we get another memory fault (eg. from
1991     * another thread) before lisp has read this, we lose the information.
1992     * However, since this is mostly informative, we'll live with that for
1993     * now -- some address is better then no address in this case.
1994     */
1995     current_memory_fault_address = addr;
1996     /* To allow debugging memory faults in signal handlers and such. */
1997     corruption_warning_and_maybe_lose("Memory fault at %x (pc=%p, sp=%p)",
1998                                       addr,
1999                                       *os_context_pc_addr(context),
2000 #ifdef ARCH_HAS_STACK_POINTER
2001                                       *os_context_sp_addr(context)
2002 #else
2003                                       0
2004 #endif
2005                                       );
2006     unblock_signals_in_context_and_maybe_warn(context);
2007 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
2008     arrange_return_to_lisp_function(context,
2009                                     StaticSymbolFunction(MEMORY_FAULT_ERROR));
2010 #else
2011     funcall0(StaticSymbolFunction(MEMORY_FAULT_ERROR));
2012 #endif
2013 }
2014 #endif
2015
2016 static void
2017 unhandled_trap_error(os_context_t *context)
2018 {
2019     lispobj context_sap;
2020     fake_foreign_function_call(context);
2021 #ifndef LISP_FEATURE_SB_SAFEPOINT
2022     unblock_gc_signals(0, 0);
2023 #endif
2024     context_sap = alloc_sap(context);
2025 #if !defined(LISP_FEATURE_WIN32) || defined(LISP_FEATURE_SB_THREAD)
2026     thread_sigmask(SIG_SETMASK, os_context_sigmask_addr(context), 0);
2027 #endif
2028     funcall1(StaticSymbolFunction(UNHANDLED_TRAP_ERROR), context_sap);
2029     lose("UNHANDLED-TRAP-ERROR fell through");
2030 }
2031
2032 /* Common logic for trapping instructions. How we actually handle each
2033  * case is highly architecture dependent, but the overall shape is
2034  * this. */
2035 void
2036 handle_trap(os_context_t *context, int trap)
2037 {
2038     switch(trap) {
2039 #if !(defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD))
2040     case trap_PendingInterrupt:
2041         FSHOW((stderr, "/<trap pending interrupt>\n"));
2042         arch_skip_instruction(context);
2043         interrupt_handle_pending(context);
2044         break;
2045 #endif
2046     case trap_Error:
2047     case trap_Cerror:
2048         FSHOW((stderr, "/<trap error/cerror %d>\n", trap));
2049         interrupt_internal_error(context, trap==trap_Cerror);
2050         break;
2051     case trap_Breakpoint:
2052         arch_handle_breakpoint(context);
2053         break;
2054     case trap_FunEndBreakpoint:
2055         arch_handle_fun_end_breakpoint(context);
2056         break;
2057 #ifdef trap_AfterBreakpoint
2058     case trap_AfterBreakpoint:
2059         arch_handle_after_breakpoint(context);
2060         break;
2061 #endif
2062 #ifdef trap_SingleStepAround
2063     case trap_SingleStepAround:
2064     case trap_SingleStepBefore:
2065         arch_handle_single_step_trap(context, trap);
2066         break;
2067 #endif
2068 #ifdef LISP_FEATURE_SB_SAFEPOINT
2069     case trap_GlobalSafepoint:
2070         fake_foreign_function_call(context);
2071         thread_in_lisp_raised(context);
2072         undo_fake_foreign_function_call(context);
2073         arch_skip_instruction(context);
2074         break;
2075     case trap_CspSafepoint:
2076         fake_foreign_function_call(context);
2077         thread_in_safety_transition(context);
2078         undo_fake_foreign_function_call(context);
2079         arch_skip_instruction(context);
2080         break;
2081 #endif
2082 #if defined(LISP_FEATURE_SPARC) && defined(LISP_FEATURE_GENCGC)
2083     case trap_Allocation:
2084         arch_handle_allocation_trap(context);
2085         arch_skip_instruction(context);
2086         break;
2087 #endif
2088     case trap_Halt:
2089         fake_foreign_function_call(context);
2090         lose("%%PRIMITIVE HALT called; the party is over.\n");
2091     default:
2092         unhandled_trap_error(context);
2093     }
2094 }