3fd22f3eb7c511b3cb1ab5f1cd88b8a276a1be57
[sbcl.git] / src / code / target-signal.lisp
1 ;;;; code for handling UNIX signals
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!UNIX")
13
14 (defmacro with-interrupt-bindings (&body body)
15   `(let*
16        ;; KLUDGE: Whatever is on the PCL stacks before the interrupt
17        ;; handler runs doesn't really matter, since we're not on the
18        ;; same call stack, really -- and if we don't bind these (esp.
19        ;; the cache one) we can get a bogus metacircle if an interrupt
20        ;; handler calls a GF that was being computed when the interrupt
21        ;; hit.
22        ((sb!pcl::*cache-miss-values-stack* nil)
23         (sb!pcl::*dfun-miss-gfs-on-stack* nil))
24      ,@body))
25
26 ;;; Evaluate CLEANUP-FORMS iff PROTECTED-FORM does a non-local exit.
27 (defmacro nlx-protect (protected-form &rest cleanup-froms)
28   (with-unique-names (completep)
29     `(let ((,completep nil))
30        (without-interrupts
31          (unwind-protect
32               (progn
33                 (allow-with-interrupts
34                   ,protected-form)
35                 (setq ,completep t))
36            (unless ,completep
37              ,@cleanup-froms))))))
38
39 (defun invoke-interruption (function)
40   (without-interrupts
41     ;; Reset signal mask: the C-side handler has blocked all
42     ;; deferrable signals before funcalling into lisp. They are to be
43     ;; unblocked the first time interrupts are enabled. With this
44     ;; mechanism there are no extra frames on the stack from a
45     ;; previous signal handler when the next signal is delivered
46     ;; provided there is no WITH-INTERRUPTS.
47     (let ((*unblock-deferrables-on-enabling-interrupts-p* t)
48           (sb!debug:*stack-top-hint* (or sb!debug:*stack-top-hint* 'invoke-interruption)))
49       (with-interrupt-bindings
50         (sb!thread::without-thread-waiting-for (:already-without-interrupts t)
51           (allow-with-interrupts
52             (nlx-protect (funcall function)
53                          ;; We've been running with deferrables
54                          ;; blocked in Lisp called by a C signal
55                          ;; handler. If we return normally the sigmask
56                          ;; in the interrupted context is restored.
57                          ;; However, if we do an nlx the operating
58                          ;; system will not restore it for us.
59                          (when *unblock-deferrables-on-enabling-interrupts-p*
60                            ;; This means that storms of interrupts
61                            ;; doing an nlx can still run out of stack.
62                            (unblock-deferrable-signals)))))))))
63
64 (defmacro in-interruption ((&key) &body body)
65   #!+sb-doc
66   "Convenience macro on top of INVOKE-INTERRUPTION."
67   `(dx-flet ((interruption () ,@body))
68      (invoke-interruption #'interruption)))
69 \f
70 ;;;; system calls that deal with signals
71
72 ;;; Send the signal SIGNAL to the process with process id PID. SIGNAL
73 ;;; should be a valid signal number
74 #!-sb-fluid (declaim (inline real-unix-kill))
75 (sb!alien:define-alien-routine ("kill" unix-kill) sb!alien:int
76   (pid sb!alien:int)
77   (signal sb!alien:int))
78
79 ;;; Send the signal SIGNAL to the all the process in process group
80 ;;; PGRP. SIGNAL should be a valid signal number
81 #!-sb-fluid (declaim (inline real-unix-killpg))
82 (sb!alien:define-alien-routine ("killpg" unix-killpg) sb!alien:int
83   (pgrp sb!alien:int)
84   (signal sb!alien:int))
85
86 ;;; Reset the current set of masked signals (those being blocked from
87 ;;; delivery).
88 ;;;
89 ;;; (Note: CMU CL had a more general SIGSETMASK call and a SIGMASK
90 ;;; operator to create masks, but since we only ever reset to 0, we no
91 ;;; longer support it. If you need it, you can pull it out of the CMU
92 ;;; CL sources, or the old SBCL sources; but you might also consider
93 ;;; doing things the SBCL way and moving this kind of C-level work
94 ;;; down to C wrapper functions.)
95
96 (declaim (inline %unblock-deferrable-signals %unblock-gc-signals))
97 (sb!alien:define-alien-routine ("unblock_deferrable_signals"
98                                 %unblock-deferrable-signals)
99     sb!alien:void
100   (where sb!alien:unsigned-long)
101   (old sb!alien:unsigned-long))
102 #!-sb-safepoint
103 (sb!alien:define-alien-routine ("unblock_gc_signals" %unblock-gc-signals)
104     sb!alien:void
105   (where sb!alien:unsigned-long)
106   (old sb!alien:unsigned-long))
107
108 (defun unblock-deferrable-signals ()
109   (%unblock-deferrable-signals 0 0))
110
111 #!-sb-safepoint
112 (defun unblock-gc-signals ()
113   (%unblock-gc-signals 0 0))
114
115 \f
116 ;;;; C routines that actually do all the work of establishing signal handlers
117 (sb!alien:define-alien-routine ("install_handler" install-handler)
118                                sb!alien:unsigned-long
119   (signal sb!alien:int)
120   (handler sb!alien:unsigned-long)
121   (synchronous boolean))
122
123 ;;;; interface to enabling and disabling signal handlers
124
125 ;;; Note on the SYNCHRONOUS argument: On builds without pseudo-atomic,
126 ;;; we have no way of knowing whether interrupted code was in an
127 ;;; allocation sequence, and cannot delay signals until after
128 ;;; allocation.  Any signal that can occur asynchronously must be
129 ;;; considered unsafe for immediate execution, and the invocation of its
130 ;;; lisp handler will get delayed into a newly spawned signal handler
131 ;;; thread.  However, there are signals which we must handle
132 ;;; immediately, because they occur synchonously (hence the boolean flag
133 ;;; SYNCHRONOUS to this function), luckily implying that the signal
134 ;;; happens only in specific places (illegal instructions, floating
135 ;;; point instructions, certain system calls), hopefully ruling out the
136 ;;; possibility that we would trigger it during allocation.
137
138 (defun enable-interrupt (signal handler &key synchronous)
139   (declare (type (or function fixnum (member :default :ignore)) handler))
140   (/show0 "enable-interrupt")
141   (flet ((run-handler (&rest args)
142            (declare (truly-dynamic-extent args))
143            (in-interruption ()
144              (apply handler args))))
145     (without-gcing
146       (let ((result (install-handler signal
147                                      (case handler
148                                        (:default sig-dfl)
149                                        (:ignore sig-ign)
150                                        (t
151                                         (sb!kernel:get-lisp-obj-address
152                                          #'run-handler)))
153                                      synchronous)))
154         (cond ((= result sig-dfl) :default)
155               ((= result sig-ign) :ignore)
156               (t (the (or function fixnum)
157                    (sb!kernel:make-lisp-obj result))))))))
158
159 (defun default-interrupt (signal)
160   (enable-interrupt signal :default))
161
162 (defun ignore-interrupt (signal)
163   (enable-interrupt signal :ignore))
164 \f
165 ;;;; Support for signal handlers which aren't.
166 ;;;;
167 ;;;; On safepoint builds, user-defined Lisp signal handlers do not run
168 ;;;; in the handler for their signal, because we have no pseudo atomic
169 ;;;; mechanism to prevent handlers from hitting during allocation.
170 ;;;; Rather, the signal spawns off a fresh native thread, which calls
171 ;;;; into lisp with a fake context through this callback:
172
173 #!+(and sb-safepoint-strictly (not win32))
174 (defun signal-handler-callback (run-handler signal args)
175   (sb!thread::initial-thread-function-trampoline
176    (sb!thread::make-signal-handling-thread :name "signal handler"
177                                            :signal-number signal)
178    nil (lambda ()
179          (let* ((info (sb!sys:sap-ref-sap args 0))
180                 (context (sb!sys:sap-ref-sap args sb!vm:n-word-bytes)))
181            (funcall run-handler signal info context)))
182    nil nil nil nil))
183
184 \f
185 ;;;; default LISP signal handlers
186 ;;;;
187 ;;;; Most of these just call ERROR to report the presence of the signal.
188
189 ;;; SIGINT is handled like BREAK, except that ANSI BREAK ignores
190 ;;; *DEBUGGER-HOOK*, but we want SIGINT's BREAK to respect it, so that
191 ;;; SIGINT in --disable-debugger mode will cleanly terminate the system
192 ;;; (by respecting the *DEBUGGER-HOOK* established in that mode).
193 (eval-when (:compile-toplevel :execute)
194   (sb!xc:defmacro define-signal-handler (name what &optional (function 'error))
195     `(defun ,name (signal info context)
196        (declare (ignore signal info))
197        (declare (type system-area-pointer context))
198        (/show "in Lisp-level signal handler" ,(symbol-name name)
199               (sap-int context))
200        (with-interrupts
201          (,function ,(concatenate 'simple-string what " at #X~X")
202                     (with-alien ((context (* os-context-t) context))
203                       (sap-int (sb!vm:context-pc context))))))))
204
205 (define-signal-handler sigill-handler "illegal instruction")
206 #!-linux
207 (define-signal-handler sigemt-handler "SIGEMT")
208 (define-signal-handler sigbus-handler "bus error")
209 #!-linux
210 (define-signal-handler sigsys-handler "bad argument to a system call")
211
212 (defun sigint-handler (signal info context)
213   (declare (ignore signal info))
214   (declare (type system-area-pointer context))
215   (/show "in Lisp-level SIGINT handler" (sap-int context))
216   (flet ((interrupt-it ()
217            (with-alien ((context (* os-context-t) context))
218              (with-interrupts
219                (let ((int (make-condition 'interactive-interrupt
220                                           :context context
221                                           :address (sap-int (sb!vm:context-pc context)))))
222                  ;; First SIGNAL, so that handlers can run.
223                  (signal int)
224                  ;; Then enter the debugger like BREAK.
225                  (%break 'sigint int))))))
226     #!+sb-safepoint
227     (let ((target (sb!thread::foreground-thread)))
228       ;; Note that INTERRUPT-THREAD on *CURRENT-THREAD* doesn't actually
229       ;; interrupt right away, because deferrables are blocked.  Rather,
230       ;; the kernel would arrange for the SIGPIPE to hit when the SIGINT
231       ;; handler is done.  However, on safepoint builds, we don't use
232       ;; SIGPIPE and lack an appropriate mechanism to handle pending
233       ;; thruptions upon exit from signal handlers (and this situation is
234       ;; unlike WITHOUT-INTERRUPTS, which handles pending interrupts
235       ;; explicitly at the end).  Only as long as safepoint builds pretend
236       ;; to cooperate with signals -- that is, as long as SIGINT-HANDLER
237       ;; is used at all -- detect this situation and work around it.
238       (if (eq target sb!thread:*current-thread*)
239           (interrupt-it)
240           (sb!thread:interrupt-thread target #'interrupt-it)))
241     #!-sb-safepoint
242     (sb!thread:interrupt-thread (sb!thread::foreground-thread)
243                                 #'interrupt-it)))
244
245 #!-sb-wtimer
246 (defun sigalrm-handler (signal info context)
247   (declare (ignore signal info context))
248   (declare (type system-area-pointer context))
249   (sb!impl::run-expired-timers))
250
251 (defun sigterm-handler (signal code context)
252   (declare (ignore signal code context))
253   (sb!ext:exit))
254
255 #!-sb-thruption
256 ;;; SIGPIPE is not used in SBCL for its original purpose, instead it's
257 ;;; for signalling a thread that it should look at its interruption
258 ;;; queue. The handler (RUN_INTERRUPTION) just returns if there is
259 ;;; nothing to do so it's safe to receive spurious SIGPIPEs coming
260 ;;; from the kernel.
261 (defun sigpipe-handler (signal code context)
262   (declare (ignore signal code context))
263   (sb!thread::run-interruption))
264
265 ;;; the handler for SIGCHLD signals for RUN-PROGRAM
266 (defun sigchld-handler  (signal code context)
267   (declare (ignore signal code context))
268   (sb!impl::get-processes-status-changes))
269
270 (defun sb!kernel:signal-cold-init-or-reinit ()
271   #!+sb-doc
272   "Enable all the default signals that Lisp knows how to deal with."
273   (enable-interrupt sigint #'sigint-handler)
274   (enable-interrupt sigterm #'sigterm-handler)
275   (enable-interrupt sigill #'sigill-handler :synchronous t)
276   #!-linux
277   (enable-interrupt sigemt #'sigemt-handler)
278   (enable-interrupt sigfpe #'sb!vm:sigfpe-handler :synchronous t)
279   (enable-interrupt sigbus #'sigbus-handler :synchronous t)
280   #!-linux
281   (enable-interrupt sigsys #'sigsys-handler :synchronous t)
282   #!-sb-wtimer
283   (enable-interrupt sigalrm #'sigalrm-handler)
284   #!-sb-thruption
285   (enable-interrupt sigpipe #'sigpipe-handler)
286   (enable-interrupt sigchld #'sigchld-handler)
287   #!+hpux (ignore-interrupt sigxcpu)
288   #!-sb-safepoint (unblock-gc-signals)
289   (unblock-deferrable-signals)
290   (values))
291 \f
292 ;;;; etc.
293
294 ;;; extract si_code from siginfo_t
295 (sb!alien:define-alien-routine ("siginfo_code" siginfo-code) sb!alien:int
296   (info system-area-pointer))
297
298 ;;; CMU CL comment:
299 ;;;   Magically converted by the compiler into a break instruction.
300 (defun receive-pending-interrupt ()
301   (receive-pending-interrupt))