1.0.33.7: Indicate *DEBUGGER-HOOK* / SB-EXT:*INVOKE-DEBUGGER-HOOK* in backtrace.
[sbcl.git] / src / code / debug.lisp
1 ;;;; the debugger
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!DEBUG")
13 \f
14 ;;;; variables and constants
15
16 ;;; things to consider when tweaking these values:
17 ;;;   * We're afraid to just default them to NIL and NIL, in case the
18 ;;;     user inadvertently causes a hairy data structure to be printed
19 ;;;     when he inadvertently enters the debugger.
20 ;;;   * We don't want to truncate output too much. These days anyone
21 ;;;     can easily run their Lisp in a windowing system or under Emacs,
22 ;;;     so it's not the end of the world even if the worst case is a
23 ;;;     few thousand lines of output.
24 ;;;   * As condition :REPORT methods are converted to use the pretty
25 ;;;     printer, they acquire *PRINT-LEVEL* constraints, so e.g. under
26 ;;;     sbcl-0.7.1.28's old value of *DEBUG-PRINT-LEVEL*=3, an
27 ;;;     ARG-COUNT-ERROR printed as
28 ;;;       error while parsing arguments to DESTRUCTURING-BIND:
29 ;;;         invalid number of elements in
30 ;;;           #
31 ;;;         to satisfy lambda list
32 ;;;           #:
33 ;;;         exactly 2 expected, but 5 found
34 (defvar *debug-print-variable-alist* nil
35   #!+sb-doc
36   "an association list describing new bindings for special variables
37 to be used within the debugger. Eg.
38
39  ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
40
41 The variables in the CAR positions are bound to the values in the CDR
42 during the execution of some debug commands. When evaluating arbitrary
43 expressions in the debugger, the normal values of the printer control
44 variables are in effect.
45
46 Initially empty, *DEBUG-PRINT-VARIABLE-ALIST* is typically used to
47 provide bindings for printer control variables.")
48
49 (defvar *debug-readtable*
50   ;; KLUDGE: This can't be initialized in a cold toplevel form,
51   ;; because the *STANDARD-READTABLE* isn't initialized until after
52   ;; cold toplevel forms have run. So instead we initialize it
53   ;; immediately after *STANDARD-READTABLE*. -- WHN 20000205
54   nil
55   #!+sb-doc
56   "*READTABLE* for the debugger")
57
58 (defvar *in-the-debugger* nil
59   #!+sb-doc
60   "This is T while in the debugger.")
61
62 ;;; nestedness inside debugger command loops
63 (defvar *debug-command-level* 0)
64
65 ;;; If this is bound before the debugger is invoked, it is used as the
66 ;;; stack top by the debugger.
67 (defvar *stack-top-hint* nil)
68
69 (defvar *stack-top* nil)
70 (defvar *real-stack-top* nil)
71
72 (defvar *current-frame* nil)
73
74 ;;; Beginner-oriented help messages are important because you end up
75 ;;; in the debugger whenever something bad happens, or if you try to
76 ;;; get out of the system with Ctrl-C or (EXIT) or EXIT or whatever.
77 ;;; But after memorizing them the wasted screen space gets annoying..
78 (defvar *debug-beginner-help-p* t
79   "Should the debugger display beginner-oriented help messages?")
80
81 (defun debug-prompt (stream)
82   (sb!thread::get-foreground)
83   (format stream
84           "~%~W~:[~;[~W~]] "
85           (sb!di:frame-number *current-frame*)
86           (> *debug-command-level* 1)
87           *debug-command-level*))
88
89 (defparameter *debug-help-string*
90 "The debug prompt is square brackets, with number(s) indicating the current
91   control stack level and, if you've entered the debugger recursively, how
92   deeply recursed you are.
93 Any command -- including the name of a restart -- may be uniquely abbreviated.
94 The debugger rebinds various special variables for controlling i/o, sometimes
95   to defaults (much like WITH-STANDARD-IO-SYNTAX does) and sometimes to
96   its own special values, based on SB-EXT:*DEBUG-PRINT-VARIABLE-ALIST*.
97 Debug commands do not affect *, //, and similar variables, but evaluation in
98   the debug loop does affect these variables.
99 SB-DEBUG:*FLUSH-DEBUG-ERRORS* controls whether errors at the debug prompt
100   drop you deeper into the debugger. The default NIL allows recursive entry
101   to debugger.
102
103 Getting in and out of the debugger:
104   TOPLEVEL, TOP  exits debugger and returns to top level REPL
105   RESTART        invokes restart numbered as shown (prompt if not given).
106   ERROR          prints the error condition and restart cases.
107
108   The number of any restart, or its name, or a unique abbreviation for its
109    name, is a valid command, and is the same as using RESTART to invoke
110    that restart.
111
112 Changing frames:
113   UP     up frame         DOWN     down frame
114   BOTTOM bottom frame     FRAME n  frame n (n=0 for top frame)
115
116 Inspecting frames:
117   BACKTRACE [n]  shows n frames going down the stack.
118   LIST-LOCALS, L lists locals in current frame.
119   PRINT, P       displays function call for current frame.
120   SOURCE [n]     displays frame's source form with n levels of enclosing forms.
121
122 Stepping:
123   START Selects the CONTINUE restart if one exists and starts
124         single-stepping. Single stepping affects only code compiled with
125         under high DEBUG optimization quality. See User Manual for details.
126   STEP  Steps into the current form.
127   NEXT  Steps over the current form.
128   OUT   Stops stepping temporarily, but resumes it when the topmost frame that
129         was stepped into returns.
130   STOP  Stops single-stepping.
131
132 Function and macro commands:
133  (SB-DEBUG:ARG n)
134     Return the n'th argument in the current frame.
135  (SB-DEBUG:VAR string-or-symbol [id])
136     Returns the value of the specified variable in the current frame.
137
138 Other commands:
139   RETURN expr
140     Return the values resulting from evaluation of expr from the
141     current frame, if this frame was compiled with a sufficiently high
142     DEBUG optimization quality.
143
144   RESTART-FRAME
145     Restart execution of the current frame, if this frame is for a
146     global function which was compiled with a sufficiently high
147     DEBUG optimization quality.
148
149   SLURP
150     Discard all pending input on *STANDARD-INPUT*. (This can be
151     useful when the debugger was invoked to handle an error in
152     deeply nested input syntax, and now the reader is confused.)")
153 \f
154
155 ;;; If LOC is an unknown location, then try to find the block start
156 ;;; location. Used by source printing to some information instead of
157 ;;; none for the user.
158 (defun maybe-block-start-location (loc)
159   (if (sb!di:code-location-unknown-p loc)
160       (let* ((block (sb!di:code-location-debug-block loc))
161              (start (sb!di:do-debug-block-locations (loc block)
162                       (return loc))))
163         (cond ((and (not (sb!di:debug-block-elsewhere-p block))
164                     start)
165                (format *debug-io* "~%unknown location: using block start~%")
166                start)
167               (t
168                loc)))
169       loc))
170 \f
171 ;;;; BACKTRACE
172
173 (defun map-backtrace (thunk &key (start 0) (count most-positive-fixnum))
174   (loop
175      with result = nil
176      for index upfrom 0
177      for frame = (if *in-the-debugger*
178                      *current-frame*
179                      (sb!di:top-frame))
180                then (sb!di:frame-down frame)
181      until (null frame)
182      when (<= start index) do
183        (if (minusp (decf count))
184            (return result)
185            (setf result (funcall thunk frame)))
186      finally (return result)))
187
188 (defun backtrace (&optional (count most-positive-fixnum) (stream *debug-io*))
189   #!+sb-doc
190   "Show a listing of the call stack going down from the current frame.
191 In the debugger, the current frame is indicated by the prompt. COUNT
192 is how many frames to show."
193   (fresh-line stream)
194   (map-backtrace (lambda (frame)
195                    (print-frame-call frame stream :number t))
196                  :count count)
197   (fresh-line stream)
198   (values))
199
200 (defun backtrace-as-list (&optional (count most-positive-fixnum))
201   #!+sb-doc "Return a list representing the current BACKTRACE."
202   (let ((reversed-result (list)))
203     (map-backtrace (lambda (frame)
204                      (push (frame-call-as-list frame) reversed-result))
205                    :count count)
206     (nreverse reversed-result)))
207
208 (defun frame-call-as-list (frame)
209   (multiple-value-bind (name args) (frame-call frame)
210     (cons name args)))
211 \f
212 ;;;; frame printing
213
214 (eval-when (:compile-toplevel :execute)
215
216 ;;; This is a convenient way to express what to do for each type of
217 ;;; lambda-list element.
218 (sb!xc:defmacro lambda-list-element-dispatch (element
219                                               &key
220                                               required
221                                               optional
222                                               rest
223                                               keyword
224                                               deleted)
225   `(etypecase ,element
226      (sb!di:debug-var
227       ,@required)
228      (cons
229       (ecase (car ,element)
230         (:optional ,@optional)
231         (:rest ,@rest)
232         (:keyword ,@keyword)))
233      (symbol
234       (aver (eq ,element :deleted))
235       ,@deleted)))
236
237 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
238   (let ((var (gensym)))
239     `(let ((,var ,variable))
240        (cond ((eq ,var :deleted) ,deleted)
241              ((eq (sb!di:debug-var-validity ,var ,location) :valid)
242               ,valid)
243              (t ,other)))))
244
245 ) ; EVAL-WHEN
246
247 ;;; Extract the function argument values for a debug frame.
248 (defun map-frame-args (thunk frame)
249   (let ((debug-fun (sb!di:frame-debug-fun frame)))
250     (dolist (element (sb!di:debug-fun-lambda-list debug-fun))
251       (funcall thunk element))))
252
253 (defun frame-args-as-list (frame)
254   (handler-case
255       (let ((location (sb!di:frame-code-location frame))
256             (reversed-result nil))
257         (block enumerating
258           (map-frame-args
259            (lambda (element)
260              (lambda-list-element-dispatch element
261                :required ((push (frame-call-arg element location frame) reversed-result))
262                :optional ((push (frame-call-arg (second element) location frame)
263                                 reversed-result))
264                :keyword ((push (second element) reversed-result)
265                          (push (frame-call-arg (third element) location frame)
266                                reversed-result))
267                :deleted ((push (frame-call-arg element location frame) reversed-result))
268                :rest ((lambda-var-dispatch (second element) location
269                         nil
270                         (progn
271                           (setf reversed-result
272                                 (append (reverse (sb!di:debug-var-value
273                                                   (second element) frame))
274                                         reversed-result))
275                           (return-from enumerating))
276                         (push (make-unprintable-object
277                                "unavailable &REST argument")
278                               reversed-result)))))
279            frame))
280         (nreverse reversed-result))
281     (sb!di:lambda-list-unavailable ()
282       (make-unprintable-object "unavailable lambda list"))))
283
284 (defvar *show-entry-point-details* nil)
285
286 (defun clean-xep (name args)
287   (values (second name)
288           (if (consp args)
289               (let ((count (first args))
290                     (real-args (rest args)))
291                 (if (fixnump count)
292                     (subseq real-args 0
293                             (min count (length real-args)))
294                     real-args))
295               args)))
296
297 (defun clean-&more-processor (name args)
298   (values (second name)
299           (if (consp args)
300               (let* ((more (last args 2))
301                      (context (first more))
302                      (count (second more)))
303                 (append
304                  (butlast args 2)
305                  (if (fixnump count)
306                      (multiple-value-list
307                       (sb!c:%more-arg-values context 0 count))
308                      (list
309                       (make-unprintable-object "more unavailable arguments")))))
310               args)))
311
312 (defun frame-call (frame)
313   (labels ((clean-name-and-args (name args)
314              (if (and (consp name) (not *show-entry-point-details*))
315                  ;; FIXME: do we need to deal with
316                  ;; HAIRY-FUNCTION-ENTRY here? I can't make it or
317                  ;; &AUX-BINDINGS appear in backtraces, so they are
318                  ;; left alone for now. --NS 2005-02-28
319                  (case (first name)
320                    ((sb!c::xep sb!c::tl-xep)
321                     (clean-xep name args))
322                    ((sb!c::&more-processor)
323                     (clean-&more-processor name args))
324                    ((sb!c::hairy-arg-processor
325                      sb!c::varargs-entry sb!c::&optional-processor)
326                     (clean-name-and-args (second name) args))
327                    (t
328                     (values name args)))
329                  (values name args))))
330     (let ((debug-fun (sb!di:frame-debug-fun frame)))
331       (multiple-value-bind (name args)
332           (clean-name-and-args (sb!di:debug-fun-name debug-fun)
333                                 (frame-args-as-list frame))
334         (values name args (sb!di:debug-fun-kind debug-fun))))))
335
336 (defun ensure-printable-object (object)
337   (handler-case
338       (with-open-stream (out (make-broadcast-stream))
339         (prin1 object out)
340         object)
341     (error (cond)
342       (declare (ignore cond))
343       (make-unprintable-object "error printing object"))))
344
345 (defun frame-call-arg (var location frame)
346   (lambda-var-dispatch var location
347     (make-unprintable-object "unused argument")
348     (sb!di:debug-var-value var frame)
349     (make-unprintable-object "unavailable argument")))
350
351 ;;; Prints a representation of the function call causing FRAME to
352 ;;; exist. VERBOSITY indicates the level of information to output;
353 ;;; zero indicates just printing the DEBUG-FUN's name, and one
354 ;;; indicates displaying call-like, one-liner format with argument
355 ;;; values.
356 (defun print-frame-call (frame stream &key (verbosity 1) (number nil))
357   (when number
358     (format stream "~&~S: " (sb!di:frame-number frame)))
359   (if (zerop verbosity)
360       (let ((*print-readably* nil))
361         (prin1 frame stream))
362       (multiple-value-bind (name args kind) (frame-call frame)
363         (pprint-logical-block (stream nil :prefix "(" :suffix ")")
364           ;; Since we go to some trouble to make nice informative function
365           ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
366           ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
367           ;; For the function arguments, we can just print normally.
368           (let ((*print-length* nil)
369                 (*print-level* nil))
370             (prin1 (ensure-printable-object name) stream))
371           ;; If we hit a &REST arg, then print as many of the values as
372           ;; possible, punting the loop over lambda-list variables since any
373           ;; other arguments will be in the &REST arg's list of values.
374           (let ((args (ensure-printable-object args)))
375             (if (listp args)
376                 (format stream "~{ ~_~S~}" args)
377                 (format stream " ~S" args))))
378         (when kind
379           (format stream "[~S]" kind))))
380   (when (>= verbosity 2)
381     (let ((loc (sb!di:frame-code-location frame)))
382       (handler-case
383           (progn
384             ;; FIXME: Is this call really necessary here? If it is,
385             ;; then the reason for it should be unobscured.
386             (sb!di:code-location-debug-block loc)
387             (format stream "~%source: ")
388             (prin1 (code-location-source-form loc 0) stream))
389         (sb!di:debug-condition (ignore)
390           ignore)
391         (error (c)
392           (format stream "~&error finding source: ~A" c))))))
393 \f
394 ;;;; INVOKE-DEBUGGER
395
396 (defvar *debugger-hook* nil
397   #!+sb-doc
398   "This is either NIL or a function of two arguments, a condition and the value
399    of *DEBUGGER-HOOK*. This function can either handle the condition or return
400    which causes the standard debugger to execute. The system passes the value
401    of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
402    around the invocation.")
403
404 (defvar *invoke-debugger-hook* nil
405   #!+sb-doc
406   "This is either NIL or a designator for a function of two arguments,
407    to be run when the debugger is about to be entered.  The function is
408    run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
409    errors, and receives as arguments the condition that triggered
410    debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*
411
412    This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
413    In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
414    called by BREAK.")
415
416 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
417 (defvar *debug-restarts*)
418 (defvar *debug-condition*)
419 (defvar *nested-debug-condition*)
420
421 ;;; Oh, what a tangled web we weave when we preserve backwards
422 ;;; compatibility with 1968-style use of global variables to control
423 ;;; per-stream i/o properties; there's really no way to get this
424 ;;; quite right, but we do what we can.
425 (defun funcall-with-debug-io-syntax (fun &rest rest)
426   (declare (type function fun))
427   ;; Try to force the other special variables into a useful state.
428   (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
429         ;; any default we might use is less useful than just reusing
430         ;; the global values.
431         (original-package *package*)
432         (original-print-pretty *print-pretty*))
433     (with-standard-io-syntax
434       (with-sane-io-syntax
435           (let (;; We want the printer and reader to be in a useful
436                 ;; state, regardless of where the debugger was invoked
437                 ;; in the program. WITH-STANDARD-IO-SYNTAX and
438                 ;; WITH-SANE-IO-SYNTAX do much of what we want, but
439                 ;;   * It doesn't affect our internal special variables
440                 ;;     like *CURRENT-LEVEL-IN-PRINT*.
441                 ;;   * It isn't customizable.
442                 ;;   * It sets *PACKAGE* to COMMON-LISP-USER, which is not
443                 ;;     helpful behavior for a debugger.
444                 ;;   * There's no particularly good debugger default for
445                 ;;     *PRINT-PRETTY*, since T is usually what you want
446                 ;;     -- except absolutely not what you want when you're
447                 ;;     debugging failures in PRINT-OBJECT logic.
448                 ;; We try to address all these issues with explicit
449                 ;; rebindings here.
450                 (sb!kernel:*current-level-in-print* 0)
451                 (*package* original-package)
452                 (*print-pretty* original-print-pretty)
453                 ;; Clear the circularity machinery to try to to reduce the
454                 ;; pain from sharing the circularity table across all
455                 ;; streams; if these are not rebound here, then setting
456                 ;; *PRINT-CIRCLE* within the debugger when debugging in a
457                 ;; state where something circular was being printed (e.g.,
458                 ;; because the debugger was entered on an error in a
459                 ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
460                 ;; here does seem somewhat ugly because it makes it more
461                 ;; difficult to debug the printing-of-circularities code
462                 ;; itself; however, as far as I (WHN, 2004-05-29) can see,
463                 ;; that's almost entirely academic as long as there's one
464                 ;; shared *C-H-T* for all streams (i.e., it's already
465                 ;; unreasonably difficult to debug print-circle machinery
466                 ;; given the buggy crosstalk between the debugger streams
467                 ;; and the stream you're trying to watch), and any fix for
468                 ;; that buggy arrangement will likely let this hack go away
469                 ;; naturally.
470                 (sb!impl::*circularity-hash-table* . nil)
471                 (sb!impl::*circularity-counter* . nil)
472                 (*readtable* *debug-readtable*))
473             (progv
474                 ;; (Why NREVERSE? PROGV makes the later entries have
475                 ;; precedence over the earlier entries.
476                 ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
477                 ;; expected that its earlier entries have precedence. And
478                 ;; the earlier-has-precedence behavior is mostly more
479                 ;; convenient, so that programmers can use PUSH or LIST* to
480                 ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
481                 (nreverse (mapcar #'car *debug-print-variable-alist*))
482                 (nreverse (mapcar #'cdr *debug-print-variable-alist*))
483               (apply fun rest)))))))
484
485 ;;; This function is not inlined so it shows up in the backtrace; that
486 ;;; can be rather handy when one has to debug the interplay between
487 ;;; *INVOKE-DEBUGGER-HOOK* and *DEBUGGER-HOOK*.
488 (declaim (notinline run-hook))
489 (defun run-hook (variable condition)
490   (let ((old-hook (symbol-value variable)))
491     (when old-hook
492       (progv (list variable) (list nil)
493         (funcall old-hook condition old-hook)))))
494
495 (defun invoke-debugger (condition)
496   #!+sb-doc
497   "Enter the debugger."
498
499   ;; call *INVOKE-DEBUGGER-HOOK* first, so that *DEBUGGER-HOOK* is not
500   ;; called when the debugger is disabled
501   (run-hook '*invoke-debugger-hook* condition)
502   (run-hook '*debugger-hook* condition)
503
504   ;; We definitely want *PACKAGE* to be of valid type.
505   ;;
506   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
507   ;; this, but here causing an exception just as we're trying to handle
508   ;; an exception would be confusing, so instead we use a special hack.
509   (unless (and (packagep *package*)
510                (package-name *package*))
511     (setf *package* (find-package :cl-user))
512     (format *error-output*
513             "The value of ~S was not an undeleted PACKAGE. It has been
514 reset to ~S."
515             '*package* *package*))
516
517   ;; Before we start our own output, finish any pending output.
518   ;; Otherwise, if the user tried to track the progress of his program
519   ;; using PRINT statements, he'd tend to lose the last line of output
520   ;; or so, which'd be confusing.
521   (flush-standard-output-streams)
522
523   (funcall-with-debug-io-syntax #'%invoke-debugger condition))
524
525 (defun %print-debugger-invocation-reason (condition stream)
526   (format stream "~2&")
527   ;; Note: Ordinarily it's only a matter of taste whether to use
528   ;; FORMAT "~<...~:>" or to use PPRINT-LOGICAL-BLOCK directly, but
529   ;; until bug 403 is fixed, PPRINT-LOGICAL-BLOCK (STREAM NIL) is
530   ;; definitely preferred, because the FORMAT alternative was acting odd.
531   (pprint-logical-block (stream nil)
532     (format stream
533             "debugger invoked on a ~S~@[ in thread ~A~]: ~2I~_~A"
534             (type-of condition)
535             #!+sb-thread sb!thread:*current-thread*
536             #!-sb-thread nil
537             condition))
538   (terpri stream))
539
540 (defun %invoke-debugger (condition)
541   (let ((*debug-condition* condition)
542         (*debug-restarts* (compute-restarts condition))
543         (*nested-debug-condition* nil))
544     (handler-case
545         ;; (The initial output here goes to *ERROR-OUTPUT*, because the
546         ;; initial output is not interactive, just an error message, and
547         ;; when people redirect *ERROR-OUTPUT*, they could reasonably
548         ;; expect to see error messages logged there, regardless of what
549         ;; the debugger does afterwards.)
550         (unless (typep condition 'step-condition)
551           (%print-debugger-invocation-reason condition *error-output*))
552       (error (condition)
553         (setf *nested-debug-condition* condition)
554         (let ((ndc-type (type-of *nested-debug-condition*)))
555           (format *error-output*
556                   "~&~@<(A ~S was caught when trying to print ~S when ~
557                       entering the debugger. Printing was aborted and the ~
558                       ~S was stored in ~S.)~@:>~%"
559                   ndc-type
560                   '*debug-condition*
561                   ndc-type
562                   '*nested-debug-condition*))
563         (when (typep *nested-debug-condition* 'cell-error)
564           ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
565           (format *error-output*
566                   "~&(CELL-ERROR-NAME ~S) = ~S~%"
567                   '*nested-debug-condition*
568                   (cell-error-name *nested-debug-condition*)))))
569
570     (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
571                          *debug-io*)))
572
573       ;; After the initial error/condition/whatever announcement to
574       ;; *ERROR-OUTPUT*, we become interactive, and should talk on
575       ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
576       ;; statement, not a description of reality.:-| There's a lot of
577       ;; older debugger code which was written to do i/o on whatever
578       ;; stream was in fashion at the time, and not all of it has
579       ;; been converted to behave this way. -- WHN 2000-11-16)
580
581       (unwind-protect
582            (let (;; We used to bind *STANDARD-OUTPUT* to *DEBUG-IO*
583                  ;; here as well, but that is probably bogus since it
584                  ;; removes the users ability to do output to a redirected
585                  ;; *S-O*. Now we just rebind it so that users can temporarily
586                  ;; frob it. FIXME: This and other "what gets bound when"
587                  ;; behaviour should be documented in the manual.
588                  (*standard-output* *standard-output*)
589                  ;; This seems reasonable: e.g. if the user has redirected
590                  ;; *ERROR-OUTPUT* to some log file, it's probably wrong
591                  ;; to send errors which occur in interactive debugging to
592                  ;; that file, and right to send them to *DEBUG-IO*.
593                  (*error-output* *debug-io*))
594              (unless (typep condition 'step-condition)
595                (when *debug-beginner-help-p*
596                  (format *debug-io*
597                          "~%~@<Type HELP for debugger help, or ~
598                                (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
599                (show-restarts *debug-restarts* *debug-io*))
600              (internal-debug))
601         (when background-p
602           (sb!thread::release-foreground))))))
603
604 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
605 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
606 ;;; command-line option
607 (defun debugger-disabled-hook (condition me)
608   (declare (ignore me))
609   ;; There is no one there to interact with, so report the
610   ;; condition and terminate the program.
611   (flet ((failure-quit (&key recklessly-p)
612            (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
613            (quit :unix-status 1 :recklessly-p recklessly-p)))
614     ;; This HANDLER-CASE is here mostly to stop output immediately
615     ;; (and fall through to QUIT) when there's an I/O error. Thus,
616     ;; when we're run under a shell script or something, we can die
617     ;; cleanly when the script dies (and our pipes are cut), instead
618     ;; of falling into ldb or something messy like that. Similarly, we
619     ;; can terminate cleanly even if BACKTRACE dies because of bugs in
620     ;; user PRINT-OBJECT methods.
621     (handler-case
622         (progn
623           (format *error-output*
624                   "~&~@<unhandled ~S~@[ in thread ~S~]: ~2I~_~A~:>~2%"
625                   (type-of condition)
626                   #!+sb-thread sb!thread:*current-thread*
627                   #!-sb-thread nil
628                   condition)
629           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
630           ;; even if we hit an error within BACKTRACE (e.g. a bug in
631           ;; the debugger's own frame-walking code, or a bug in a user
632           ;; PRINT-OBJECT method) we'll at least have the CONDITION
633           ;; printed out before we die.
634           (finish-output *error-output*)
635           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
636           ;; it seems as though we should at least truncate it somewhere.)
637           (sb!debug:backtrace 128 *error-output*)
638           (format
639            *error-output*
640            "~%unhandled condition in --disable-debugger mode, quitting~%")
641           (finish-output *error-output*)
642           (failure-quit))
643       (condition ()
644         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
645         ;; fail when our output streams are blown away, as e.g. when
646         ;; we're running under a Unix shell script and it dies somehow
647         ;; (e.g. because of a SIGINT). In that case, we might as well
648         ;; just give it up for a bad job, and stop trying to notify
649         ;; the user of anything.
650         ;;
651         ;; Actually, the only way I've run across to exercise the
652         ;; problem is to have more than one layer of shell script.
653         ;; I have a shell script which does
654         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
655         ;; and the problem occurs when I interrupt this with Ctrl-C
656         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
657         ;; I haven't figured out whether it's bash, time, tee, Linux, or
658         ;; what that is responsible, but that it's possible at all
659         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
660         (ignore-errors
661          (%primitive print
662                      "Argh! error within --disable-debugger error handling"))
663         (failure-quit :recklessly-p t)))))
664
665 (defvar *old-debugger-hook* nil)
666
667 ;;; halt-on-failures and prompt-on-failures modes, suitable for
668 ;;; noninteractive and interactive use respectively
669 (defun disable-debugger ()
670   ;; *DEBUG-IO* used to be set here to *ERROR-OUTPUT* which is sort
671   ;; of unexpected but mostly harmless, but then ENABLE-DEBUGGER had
672   ;; to set it to a suitable value again and be very careful,
673   ;; especially if the user has also set it. -- MG 2005-07-15
674   (unless (eq *invoke-debugger-hook* 'debugger-disabled-hook)
675     (setf *old-debugger-hook* *invoke-debugger-hook*
676           *invoke-debugger-hook* 'debugger-disabled-hook))
677   ;; This is not inside the UNLESS to ensure that LDB is disabled
678   ;; regardless of what the old value of *INVOKE-DEBUGGER-HOOK* was.
679   ;; This might matter for example when restoring a core.
680   (sb!alien:alien-funcall (sb!alien:extern-alien "disable_lossage_handler"
681                                                  (function sb!alien:void))))
682
683 (defun enable-debugger ()
684   (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
685     (setf *invoke-debugger-hook* *old-debugger-hook*
686           *old-debugger-hook* nil))
687   (sb!alien:alien-funcall (sb!alien:extern-alien "enable_lossage_handler"
688                                                  (function sb!alien:void))))
689
690 (defun show-restarts (restarts s)
691   (cond ((null restarts)
692          (format s
693                  "~&(no restarts: If you didn't do this on purpose, ~
694                   please report it as a bug.)~%"))
695         (t
696          (format s "~&restarts (invokable by number or by ~
697                     possibly-abbreviated name):~%")
698          (let ((count 0)
699                (names-used '(nil))
700                (max-name-len 0))
701            (dolist (restart restarts)
702              (let ((name (restart-name restart)))
703                (when name
704                  (let ((len (length (princ-to-string name))))
705                    (when (> len max-name-len)
706                      (setf max-name-len len))))))
707            (unless (zerop max-name-len)
708              (incf max-name-len 3))
709            (dolist (restart restarts)
710              (let ((name (restart-name restart)))
711                ;; FIXME: maybe it would be better to display later names
712                ;; in parens instead of brakets, not just omit them fully.
713                ;; Call BREAK, call BREAK in the debugger, and tell me
714                ;; it's not confusing looking. --NS 20050310
715                (cond ((member name names-used)
716                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
717                      (t
718                       (format s "~& ~2D: [~VA] ~A~%"
719                               count (- max-name-len 3) name restart)
720                       (push name names-used))))
721              (incf count))))))
722
723 (defvar *debug-loop-fun* #'debug-loop-fun
724   "a function taking no parameters that starts the low-level debug loop")
725
726 ;;; When the debugger is invoked due to a stepper condition, we don't
727 ;;; want to print the current frame before the first prompt for aesthetic
728 ;;; reasons.
729 (defvar *suppress-frame-print* nil)
730
731 ;;; This calls DEBUG-LOOP, performing some simple initializations
732 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
733 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
734 ;;; to get into a debug prompt as quickly as possible with as little
735 ;;; risk as possible for stepping on whatever is causing recursive
736 ;;; errors.
737 (defun internal-debug ()
738   (let ((*in-the-debugger* t)
739         (*read-suppress* nil))
740     (unless (typep *debug-condition* 'step-condition)
741       (clear-input *debug-io*))
742     (let ((*suppress-frame-print* (typep *debug-condition* 'step-condition)))
743       (funcall *debug-loop-fun*))))
744 \f
745 ;;;; DEBUG-LOOP
746
747 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
748 ;;; was motivated by desire to play nicely with ILISP.
749 (defvar *flush-debug-errors* nil
750   #!+sb-doc
751   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
752    executing in the debugger.")
753
754 (defun debug-read (stream)
755   (declare (type stream stream))
756   (let* ((eof-marker (cons nil nil))
757          (form (read stream nil eof-marker)))
758     (if (eq form eof-marker)
759         (abort)
760         form)))
761
762 (defun debug-loop-fun ()
763   (let* ((*debug-command-level* (1+ *debug-command-level*))
764          (*real-stack-top* (sb!di:top-frame))
765          (*stack-top* (or *stack-top-hint* *real-stack-top*))
766          (*stack-top-hint* nil)
767          (*current-frame* *stack-top*))
768     (handler-bind ((sb!di:debug-condition
769                     (lambda (condition)
770                       (princ condition *debug-io*)
771                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
772                       (throw 'debug-loop-catcher nil))))
773       (cond (*suppress-frame-print*
774              (setf *suppress-frame-print* nil))
775             (t
776              (terpri *debug-io*)
777              (print-frame-call *current-frame* *debug-io* :verbosity 2)))
778       (loop
779        (catch 'debug-loop-catcher
780          (handler-bind ((error (lambda (condition)
781                                  (when *flush-debug-errors*
782                                    (clear-input *debug-io*)
783                                    (princ condition *debug-io*)
784                                    (format *debug-io*
785                                            "~&error flushed (because ~
786                                              ~S is set)"
787                                            '*flush-debug-errors*)
788                                    (/show0 "throwing DEBUG-LOOP-CATCHER")
789                                    (throw 'debug-loop-catcher nil)))))
790            ;; We have to bind LEVEL for the restart function created by
791            ;; WITH-SIMPLE-RESTART.
792            (let ((level *debug-command-level*)
793                  (restart-commands (make-restart-commands)))
794              (flush-standard-output-streams)
795              (debug-prompt *debug-io*)
796              (force-output *debug-io*)
797              (let* ((exp (debug-read *debug-io*))
798                     (cmd-fun (debug-command-p exp restart-commands)))
799                (with-simple-restart (abort
800                                      "~@<Reduce debugger level (to debug level ~W).~@:>"
801                                      level)
802                  (cond ((not cmd-fun)
803                         (debug-eval-print exp))
804                        ((consp cmd-fun)
805                         (format *debug-io*
806                                 "~&Your command, ~S, is ambiguous:~%"
807                                 exp)
808                         (dolist (ele cmd-fun)
809                           (format *debug-io* "   ~A~%" ele)))
810                        (t
811                         (funcall cmd-fun))))))))))))
812
813 (defvar *auto-eval-in-frame* t
814   #!+sb-doc
815   "When set (the default), evaluations in the debugger's command loop occur
816    relative to the current frame's environment without the need of debugger
817    forms that explicitly control this kind of evaluation.")
818
819 (defun debug-eval (expr)
820   (if (and (fboundp 'compile) *auto-eval-in-frame*)
821       (sb!di:eval-in-frame *current-frame* expr)
822       (eval expr)))
823
824 (defun debug-eval-print (expr)
825   (/noshow "entering DEBUG-EVAL-PRINT" expr)
826   (let ((values (multiple-value-list
827                  (interactive-eval expr :eval #'debug-eval))))
828     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
829     (dolist (value values)
830       (fresh-line *debug-io*)
831       (prin1 value *debug-io*)))
832   (force-output *debug-io*))
833 \f
834 ;;;; debug loop functions
835
836 ;;; These commands are functions, not really commands, so that users
837 ;;; can get their hands on the values returned.
838
839 (eval-when (:execute :compile-toplevel)
840
841 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
842   `(let* ((temp (etypecase name
843                   (symbol (sb!di:debug-fun-symbol-vars
844                            (sb!di:frame-debug-fun *current-frame*)
845                            name))
846                   (simple-string (sb!di:ambiguous-debug-vars
847                                   (sb!di:frame-debug-fun *current-frame*)
848                                   name))))
849           (location (sb!di:frame-code-location *current-frame*))
850           ;; Let's only deal with valid variables.
851           (vars (remove-if-not (lambda (v)
852                                  (eq (sb!di:debug-var-validity v location)
853                                      :valid))
854                                temp)))
855      (declare (list vars))
856      (cond ((null vars)
857             (error "No known valid variables match ~S." name))
858            ((= (length vars) 1)
859             ,(ecase ref-or-set
860                (:ref
861                 '(sb!di:debug-var-value (car vars) *current-frame*))
862                (:set
863                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
864                        ,value-var))))
865            (t
866             ;; Since we have more than one, first see whether we have
867             ;; any variables that exactly match the specification.
868             (let* ((name (etypecase name
869                            (symbol (symbol-name name))
870                            (simple-string name)))
871                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
872                    ;; instead.
873                    (exact (remove-if-not (lambda (v)
874                                            (string= (sb!di:debug-var-symbol-name v)
875                                                     name))
876                                          vars))
877                    (vars (or exact vars)))
878               (declare (simple-string name)
879                        (list exact vars))
880               (cond
881                ;; Check now for only having one variable.
882                ((= (length vars) 1)
883                 ,(ecase ref-or-set
884                    (:ref
885                     '(sb!di:debug-var-value (car vars) *current-frame*))
886                    (:set
887                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
888                            ,value-var))))
889                ;; If there weren't any exact matches, flame about
890                ;; ambiguity unless all the variables have the same
891                ;; name.
892                ((and (not exact)
893                      (find-if-not
894                       (lambda (v)
895                         (string= (sb!di:debug-var-symbol-name v)
896                                  (sb!di:debug-var-symbol-name (car vars))))
897                       (cdr vars)))
898                 (error "specification ambiguous:~%~{   ~A~%~}"
899                        (mapcar #'sb!di:debug-var-symbol-name
900                                (delete-duplicates
901                                 vars :test #'string=
902                                 :key #'sb!di:debug-var-symbol-name))))
903                ;; All names are the same, so see whether the user
904                ;; ID'ed one of them.
905                (id-supplied
906                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
907                   (unless v
908                     (error
909                      "invalid variable ID, ~W: should have been one of ~S"
910                      id
911                      (mapcar #'sb!di:debug-var-id vars)))
912                   ,(ecase ref-or-set
913                      (:ref
914                       '(sb!di:debug-var-value v *current-frame*))
915                      (:set
916                       `(setf (sb!di:debug-var-value v *current-frame*)
917                              ,value-var)))))
918                (t
919                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
920                        name
921                        (mapcar #'sb!di:debug-var-id vars)))))))))
922
923 ) ; EVAL-WHEN
924
925 ;;; FIXME: This doesn't work. It would be real nice we could make it
926 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
927 (defun var (name &optional (id 0 id-supplied))
928   #!+sb-doc
929   "Return a variable's value if possible. NAME is a simple-string or symbol.
930    If it is a simple-string, it is an initial substring of the variable's name.
931    If name is a symbol, it has the same name and package as the variable whose
932    value this function returns. If the symbol is uninterned, then the variable
933    has the same name as the symbol, but it has no package.
934
935    If name is the initial substring of variables with different names, then
936    this return no values after displaying the ambiguous names. If name
937    determines multiple variables with the same name, then you must use the
938    optional id argument to specify which one you want. If you left id
939    unspecified, then this returns no values after displaying the distinguishing
940    id values.
941
942    The result of this function is limited to the availability of variable
943    information. This is SETF'able."
944   (define-var-operation :ref))
945 (defun (setf var) (value name &optional (id 0 id-supplied))
946   (define-var-operation :set value))
947
948 ;;; This returns the COUNT'th arg as the user sees it from args, the
949 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
950 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
951 ;;; T. If this returns a keyword symbol or a value from a rest arg,
952 ;;; then the second value is NIL.
953 ;;;
954 ;;; FIXME: There's probably some way to merge the code here with
955 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
956 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
957 (declaim (ftype (function (index list)) nth-arg))
958 (defun nth-arg (count args)
959   (let ((n count))
960     (dolist (ele args (error "The argument specification ~S is out of range."
961                              n))
962       (lambda-list-element-dispatch ele
963         :required ((if (zerop n) (return (values ele t))))
964         :optional ((if (zerop n) (return (values (second ele) t))))
965         :keyword ((cond ((zerop n)
966                          (return (values (second ele) nil)))
967                         ((zerop (decf n))
968                          (return (values (third ele) t)))))
969         :deleted ((if (zerop n) (return (values ele t))))
970         :rest ((let ((var (second ele)))
971                  (lambda-var-dispatch var (sb!di:frame-code-location
972                                            *current-frame*)
973                    (error "unused &REST argument before n'th argument")
974                    (dolist (value
975                             (sb!di:debug-var-value var *current-frame*)
976                             (error
977                              "The argument specification ~S is out of range."
978                              n))
979                      (if (zerop n)
980                          (return-from nth-arg (values value nil))
981                          (decf n)))
982                    (error "invalid &REST argument before n'th argument")))))
983       (decf n))))
984
985 (defun arg (n)
986   #!+sb-doc
987   "Return the N'th argument's value if possible. Argument zero is the first
988    argument in a frame's default printed representation. Count keyword/value
989    pairs as separate arguments."
990   (multiple-value-bind (var lambda-var-p)
991       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
992                                 (sb!di:frame-debug-fun *current-frame*))
993                    (sb!di:lambda-list-unavailable ()
994                      (error "No argument values are available."))))
995     (if lambda-var-p
996         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
997           (error "Unused arguments have no values.")
998           (sb!di:debug-var-value var *current-frame*)
999           (error "invalid argument value"))
1000         var)))
1001 \f
1002 ;;;; machinery for definition of debug loop commands
1003
1004 (defvar *debug-commands* nil)
1005
1006 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1007 ;;; permitted.
1008 (defmacro !def-debug-command (name args &rest body)
1009   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1010     `(progn
1011        (setf *debug-commands*
1012              (remove ,name *debug-commands* :key #'car :test #'string=))
1013        (defun ,fun-name ,args
1014          (unless *in-the-debugger*
1015            (error "invoking debugger command while outside the debugger"))
1016          ,@body)
1017        (push (cons ,name #',fun-name) *debug-commands*)
1018        ',fun-name)))
1019
1020 (defun !def-debug-command-alias (new-name existing-name)
1021   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1022     (unless pair (error "unknown debug command name: ~S" existing-name))
1023     (push (cons new-name (cdr pair)) *debug-commands*))
1024   new-name)
1025
1026 ;;; This takes a symbol and uses its name to find a debugger command,
1027 ;;; using initial substring matching. It returns the command function
1028 ;;; if form identifies only one command, but if form is ambiguous,
1029 ;;; this returns a list of the command names. If there are no matches,
1030 ;;; this returns nil. Whenever the loop that looks for a set of
1031 ;;; possibilities encounters an exact name match, we return that
1032 ;;; command function immediately.
1033 (defun debug-command-p (form &optional other-commands)
1034   (if (or (symbolp form) (integerp form))
1035       (let* ((name
1036               (if (symbolp form)
1037                   (symbol-name form)
1038                   (format nil "~W" form)))
1039              (len (length name))
1040              (res nil))
1041         (declare (simple-string name)
1042                  (fixnum len)
1043                  (list res))
1044
1045         ;; Find matching commands, punting if exact match.
1046         (flet ((match-command (ele)
1047                  (let* ((str (car ele))
1048                         (str-len (length str)))
1049                    (declare (simple-string str)
1050                             (fixnum str-len))
1051                    (cond ((< str-len len))
1052                          ((= str-len len)
1053                           (when (string= name str :end1 len :end2 len)
1054                             (return-from debug-command-p (cdr ele))))
1055                          ((string= name str :end1 len :end2 len)
1056                           (push ele res))))))
1057           (mapc #'match-command *debug-commands*)
1058           (mapc #'match-command other-commands))
1059
1060         ;; Return the right value.
1061         (cond ((not res) nil)
1062               ((= (length res) 1)
1063                (cdar res))
1064               (t ; Just return the names.
1065                (do ((cmds res (cdr cmds)))
1066                    ((not cmds) res)
1067                  (setf (car cmds) (caar cmds))))))))
1068
1069 ;;; Return a list of debug commands (in the same format as
1070 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1071 ;;;
1072 ;;; Two commands are made for each restart: one for the number, and
1073 ;;; one for the restart name (unless it's been shadowed by an earlier
1074 ;;; restart of the same name, or it is NIL).
1075 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1076   (let ((commands)
1077         (num 0))                        ; better be the same as show-restarts!
1078     (dolist (restart restarts)
1079       (let ((name (string (restart-name restart))))
1080         (let ((restart-fun
1081                 (lambda ()
1082                   (/show0 "in restart-command closure, about to i-r-i")
1083                   (invoke-restart-interactively restart))))
1084           (push (cons (prin1-to-string num) restart-fun) commands)
1085           (unless (or (null (restart-name restart))
1086                       (find name commands :key #'car :test #'string=))
1087             (push (cons name restart-fun) commands))))
1088     (incf num))
1089   commands))
1090 \f
1091 ;;;; frame-changing commands
1092
1093 (!def-debug-command "UP" ()
1094   (let ((next (sb!di:frame-up *current-frame*)))
1095     (cond (next
1096            (setf *current-frame* next)
1097            (print-frame-call next *debug-io*))
1098           (t
1099            (format *debug-io* "~&Top of stack.")))))
1100
1101 (!def-debug-command "DOWN" ()
1102   (let ((next (sb!di:frame-down *current-frame*)))
1103     (cond (next
1104            (setf *current-frame* next)
1105            (print-frame-call next *debug-io*))
1106           (t
1107            (format *debug-io* "~&Bottom of stack.")))))
1108
1109 (!def-debug-command-alias "D" "DOWN")
1110
1111 (!def-debug-command "BOTTOM" ()
1112   (do ((prev *current-frame* lead)
1113        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1114       ((null lead)
1115        (setf *current-frame* prev)
1116        (print-frame-call prev *debug-io*))))
1117
1118 (!def-debug-command-alias "B" "BOTTOM")
1119
1120 (!def-debug-command "FRAME" (&optional
1121                              (n (read-prompting-maybe "frame number: ")))
1122   (setf *current-frame*
1123         (multiple-value-bind (next-frame-fun limit-string)
1124             (if (< n (sb!di:frame-number *current-frame*))
1125                 (values #'sb!di:frame-up "top")
1126               (values #'sb!di:frame-down "bottom"))
1127           (do ((frame *current-frame*))
1128               ((= n (sb!di:frame-number frame))
1129                frame)
1130             (let ((next-frame (funcall next-frame-fun frame)))
1131               (cond (next-frame
1132                      (setf frame next-frame))
1133                     (t
1134                      (format *debug-io*
1135                              "The ~A of the stack was encountered.~%"
1136                              limit-string)
1137                      (return frame)))))))
1138   (print-frame-call *current-frame* *debug-io*))
1139
1140 (!def-debug-command-alias "F" "FRAME")
1141 \f
1142 ;;;; commands for entering and leaving the debugger
1143
1144 (!def-debug-command "TOPLEVEL" ()
1145   (throw 'toplevel-catcher nil))
1146
1147 ;;; make T safe
1148 (!def-debug-command-alias "TOP" "TOPLEVEL")
1149
1150 (!def-debug-command "RESTART" ()
1151   (/show0 "doing RESTART debug-command")
1152   (let ((num (read-if-available :prompt)))
1153     (when (eq num :prompt)
1154       (show-restarts *debug-restarts* *debug-io*)
1155       (write-string "restart: " *debug-io*)
1156       (force-output *debug-io*)
1157       (setf num (read *debug-io*)))
1158     (let ((restart (typecase num
1159                      (unsigned-byte
1160                       (nth num *debug-restarts*))
1161                      (symbol
1162                       (find num *debug-restarts* :key #'restart-name
1163                             :test (lambda (sym1 sym2)
1164                                     (string= (symbol-name sym1)
1165                                              (symbol-name sym2)))))
1166                      (t
1167                       (format *debug-io* "~S is invalid as a restart name.~%"
1168                               num)
1169                       (return-from restart-debug-command nil)))))
1170       (/show0 "got RESTART")
1171       (if restart
1172           (invoke-restart-interactively restart)
1173           (princ "There is no such restart." *debug-io*)))))
1174 \f
1175 ;;;; information commands
1176
1177 (!def-debug-command "HELP" ()
1178   ;; CMU CL had a little toy pager here, but "if you aren't running
1179   ;; ILISP (or a smart windowing system, or something) you deserve to
1180   ;; lose", so we've dropped it in SBCL. However, in case some
1181   ;; desperate holdout is running this on a dumb terminal somewhere,
1182   ;; we tell him where to find the message stored as a string.
1183   (format *debug-io*
1184           "~&~A~2%(The HELP string is stored in ~S.)~%"
1185           *debug-help-string*
1186           '*debug-help-string*))
1187
1188 (!def-debug-command-alias "?" "HELP")
1189
1190 (!def-debug-command "ERROR" ()
1191   (format *debug-io* "~A~%" *debug-condition*)
1192   (show-restarts *debug-restarts* *debug-io*))
1193
1194 (!def-debug-command "BACKTRACE" ()
1195   (backtrace (read-if-available most-positive-fixnum)))
1196
1197 (!def-debug-command "PRINT" ()
1198   (print-frame-call *current-frame* *debug-io*))
1199
1200 (!def-debug-command-alias "P" "PRINT")
1201
1202 (!def-debug-command "LIST-LOCALS" ()
1203   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1204     (if (sb!di:debug-var-info-available d-fun)
1205         (let ((*standard-output* *debug-io*)
1206               (location (sb!di:frame-code-location *current-frame*))
1207               (prefix (read-if-available nil))
1208               (any-p nil)
1209               (any-valid-p nil))
1210           (dolist (v (sb!di:ambiguous-debug-vars
1211                         d-fun
1212                         (if prefix (string prefix) "")))
1213             (setf any-p t)
1214             (when (eq (sb!di:debug-var-validity v location) :valid)
1215               (setf any-valid-p t)
1216               (format *debug-io* "~S~:[#~W~;~*~]  =  ~S~%"
1217                       (sb!di:debug-var-symbol v)
1218                       (zerop (sb!di:debug-var-id v))
1219                       (sb!di:debug-var-id v)
1220                       (sb!di:debug-var-value v *current-frame*))))
1221
1222           (cond
1223            ((not any-p)
1224             (format *debug-io*
1225                     "There are no local variables ~@[starting with ~A ~]~
1226                     in the function."
1227                     prefix))
1228            ((not any-valid-p)
1229             (format *debug-io*
1230                     "All variables ~@[starting with ~A ~]currently ~
1231                     have invalid values."
1232                     prefix))))
1233         (write-line "There is no variable information available."
1234                     *debug-io*))))
1235
1236 (!def-debug-command-alias "L" "LIST-LOCALS")
1237
1238 (!def-debug-command "SOURCE" ()
1239   (print (code-location-source-form (sb!di:frame-code-location *current-frame*)
1240                                     (read-if-available 0))
1241          *debug-io*))
1242 \f
1243 ;;;; source location printing
1244
1245 ;;; We cache a stream to the last valid file debug source so that we
1246 ;;; won't have to repeatedly open the file.
1247 ;;;
1248 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1249 ;;; in the 1990s, so the benefit is negligible, less important than the
1250 ;;; potential of extra confusion if someone changes the source during
1251 ;;; a debug session and the change doesn't show up. And removing this
1252 ;;; would simplify the system, which I like. -- WHN 19990903
1253 (defvar *cached-debug-source* nil)
1254 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1255 (defvar *cached-source-stream* nil)
1256 (declaim (type (or stream null) *cached-source-stream*))
1257
1258 ;;; To suppress the read-time evaluation #. macro during source read,
1259 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1260 ;;; copying it each time, and invalidated when the
1261 ;;; *CACHED-DEBUG-SOURCE* has changed.
1262 (defvar *cached-readtable* nil)
1263 (declaim (type (or readtable null) *cached-readtable*))
1264
1265 ;;; Stuff to clean up before saving a core
1266 (defun debug-deinit ()
1267   (setf *cached-debug-source* nil
1268         *cached-source-stream* nil
1269         *cached-readtable* nil))
1270
1271 ;;; We also cache the last toplevel form that we printed a source for
1272 ;;; so that we don't have to do repeated reads and calls to
1273 ;;; FORM-NUMBER-TRANSLATIONS.
1274 (defvar *cached-toplevel-form-offset* nil)
1275 (declaim (type (or index null) *cached-toplevel-form-offset*))
1276 (defvar *cached-toplevel-form*)
1277 (defvar *cached-form-number-translations*)
1278
1279 ;;; Given a code location, return the associated form-number
1280 ;;; translations and the actual top level form. We check our cache ---
1281 ;;; if there is a miss, we dispatch on the kind of the debug source.
1282 (defun get-toplevel-form (location)
1283   (let ((d-source (sb!di:code-location-debug-source location)))
1284     (if (and (eq d-source *cached-debug-source*)
1285              (eql (sb!di:code-location-toplevel-form-offset location)
1286                   *cached-toplevel-form-offset*))
1287         (values *cached-form-number-translations* *cached-toplevel-form*)
1288         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1289                (res
1290                 (cond ((sb!di:debug-source-namestring d-source)
1291                        (get-file-toplevel-form location))
1292                       ((sb!di:debug-source-form d-source)
1293                        (sb!di:debug-source-form d-source))
1294                       (t (bug "Don't know how to use a DEBUG-SOURCE without ~
1295                                a namestring or a form.")))))
1296           (setq *cached-toplevel-form-offset* offset)
1297           (values (setq *cached-form-number-translations*
1298                         (sb!di:form-number-translations res offset))
1299                   (setq *cached-toplevel-form* res))))))
1300
1301 ;;; Locate the source file (if it still exists) and grab the top level
1302 ;;; form. If the file is modified, we use the top level form offset
1303 ;;; instead of the recorded character offset.
1304 (defun get-file-toplevel-form (location)
1305   (let* ((d-source (sb!di:code-location-debug-source location))
1306          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1307          (local-tlf-offset (- tlf-offset
1308                               (sb!di:debug-source-root-number d-source)))
1309          (char-offset
1310           (aref (or (sb!di:debug-source-start-positions d-source)
1311                     (error "no start positions map"))
1312                 local-tlf-offset))
1313          (name (sb!di:debug-source-namestring d-source)))
1314     (unless (eq d-source *cached-debug-source*)
1315       (unless (and *cached-source-stream*
1316                    (equal (pathname *cached-source-stream*)
1317                           (pathname name)))
1318         (setq *cached-readtable* nil)
1319         (when *cached-source-stream* (close *cached-source-stream*))
1320         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1321         (unless *cached-source-stream*
1322           (error "The source file no longer exists:~%  ~A" (namestring name)))
1323         (format *debug-io* "~%; file: ~A~%" (namestring name)))
1324
1325         (setq *cached-debug-source*
1326               (if (= (sb!di:debug-source-created d-source)
1327                      (file-write-date name))
1328                   d-source nil)))
1329
1330     (cond
1331      ((eq *cached-debug-source* d-source)
1332       (file-position *cached-source-stream* char-offset))
1333      (t
1334       (format *debug-io*
1335               "~%; File has been modified since compilation:~%;   ~A~@
1336                  ; Using form offset instead of character position.~%"
1337               (namestring name))
1338       (file-position *cached-source-stream* 0)
1339       (let ((*read-suppress* t))
1340         (dotimes (i local-tlf-offset)
1341           (read *cached-source-stream*)))))
1342     (unless *cached-readtable*
1343       (setq *cached-readtable* (copy-readtable))
1344       (set-dispatch-macro-character
1345        #\# #\.
1346        (lambda (stream sub-char &rest rest)
1347          (declare (ignore rest sub-char))
1348          (let ((token (read stream t nil t)))
1349            (format nil "#.~S" token)))
1350        *cached-readtable*))
1351     (let ((*readtable* *cached-readtable*))
1352       (read *cached-source-stream*))))
1353
1354 (defun code-location-source-form (location context)
1355   (let* ((location (maybe-block-start-location location))
1356          (form-num (sb!di:code-location-form-number location)))
1357     (multiple-value-bind (translations form) (get-toplevel-form location)
1358       (unless (< form-num (length translations))
1359         (error "The source path no longer exists."))
1360       (sb!di:source-path-context form
1361                                  (svref translations form-num)
1362                                  context))))
1363 \f
1364
1365 ;;; start single-stepping
1366 (!def-debug-command "START" ()
1367   (if (typep *debug-condition* 'step-condition)
1368       (format *debug-io* "~&Already single-stepping.~%")
1369       (let ((restart (find-restart 'continue *debug-condition*)))
1370         (cond (restart
1371                (sb!impl::enable-stepping)
1372                (invoke-restart restart))
1373               (t
1374                (format *debug-io* "~&Non-continuable error, cannot start stepping.~%"))))))
1375
1376 (defmacro def-step-command (command-name restart-name)
1377   `(!def-debug-command ,command-name ()
1378      (if (typep *debug-condition* 'step-condition)
1379          (let ((restart (find-restart ',restart-name *debug-condition*)))
1380            (aver restart)
1381            (invoke-restart restart))
1382          (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%"))))
1383
1384 (def-step-command "STEP" step-into)
1385 (def-step-command "NEXT" step-next)
1386 (def-step-command "STOP" step-continue)
1387
1388 (!def-debug-command-alias "S" "STEP")
1389 (!def-debug-command-alias "N" "NEXT")
1390
1391 (!def-debug-command "OUT" ()
1392   (if (typep *debug-condition* 'step-condition)
1393       (if sb!impl::*step-out*
1394           (let ((restart (find-restart 'step-out *debug-condition*)))
1395             (aver restart)
1396             (invoke-restart restart))
1397           (format *debug-io* "~&OUT can only be used step out of frames that were originally stepped into with STEP.~%"))
1398       (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%")))
1399
1400 ;;; miscellaneous commands
1401
1402 (!def-debug-command "DESCRIBE" ()
1403   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1404          (debug-fun (sb!di:code-location-debug-fun curloc))
1405          (function (sb!di:debug-fun-fun debug-fun)))
1406     (if function
1407         (describe function)
1408         (format *debug-io* "can't figure out the function for this frame"))))
1409
1410 (!def-debug-command "SLURP" ()
1411   (loop while (read-char-no-hang *standard-input*)))
1412
1413 ;;; RETURN-FROM-FRAME and RESTART-FRAME
1414
1415 (defun unwind-to-frame-and-call (frame thunk)
1416   #!+unwind-to-frame-and-call-vop
1417   (flet ((sap-int/fixnum (sap)
1418            ;; On unithreaded X86 *BINDING-STACK-POINTER* and
1419            ;; *CURRENT-CATCH-BLOCK* are negative, so we need to jump through
1420            ;; some hoops to make these calculated values negative too.
1421            (ash (truly-the (signed-byte #.sb!vm:n-word-bits)
1422                            (sap-int sap))
1423                 (- sb!vm::n-fixnum-tag-bits))))
1424     ;; To properly unwind the stack, we need three pieces of information:
1425     ;;   * The unwind block that should be active after the unwind
1426     ;;   * The catch block that should be active after the unwind
1427     ;;   * The values that the binding stack pointer should have after the
1428     ;;     unwind.
1429     (let* ((block (sap-int/fixnum (find-enclosing-catch-block frame)))
1430            (unbind-to (sap-int/fixnum (find-binding-stack-pointer frame))))
1431       ;; This VOP will run the neccessary cleanup forms, reset the fp, and
1432       ;; then call the supplied function.
1433       (sb!vm::%primitive sb!vm::unwind-to-frame-and-call
1434                          (sb!di::frame-pointer frame)
1435                          (find-enclosing-uwp frame)
1436                          (lambda ()
1437                            ;; Before calling the user-specified
1438                            ;; function, we need to restore the binding
1439                            ;; stack and the catch block. The unwind block
1440                            ;; is taken care of by the VOP.
1441                            (sb!vm::%primitive sb!vm::unbind-to-here
1442                                               unbind-to)
1443                            (setf sb!vm::*current-catch-block* block)
1444                            (funcall thunk)))))
1445   #!-unwind-to-frame-and-call-vop
1446   (let ((tag (gensym)))
1447     (sb!di:replace-frame-catch-tag frame
1448                                    'sb!c:debug-catch-tag
1449                                    tag)
1450     (throw tag thunk)))
1451
1452 (defun find-binding-stack-pointer (frame)
1453   #!-stack-grows-downward-not-upward
1454   (declare (ignore frame))
1455   #!-stack-grows-downward-not-upward
1456   (error "Not implemented on this architecture")
1457   #!+stack-grows-downward-not-upward
1458   (let ((bsp (sb!vm::binding-stack-pointer-sap))
1459         (unbind-to nil)
1460         (fp (sb!di::frame-pointer frame))
1461         (start (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1462                              (ash sb!vm:*binding-stack-start*
1463                                   sb!vm:n-fixnum-tag-bits)))))
1464     ;; Walk the binding stack looking for an entry where the symbol is
1465     ;; an unbound-symbol marker and the value is equal to the frame
1466     ;; pointer.  These entries are inserted into the stack by the
1467     ;; BIND-SENTINEL VOP and removed by UNBIND-SENTINEL (inserted into
1468     ;; the function during IR2). If an entry wasn't found, the
1469     ;; function that the frame corresponds to wasn't compiled with a
1470     ;; high enough debug setting, and can't be restarted / returned
1471     ;; from.
1472     (loop until (sap= bsp start)
1473           do (progn
1474                (setf bsp (sap+ bsp
1475                                (- (* sb!vm:binding-size sb!vm:n-word-bytes))))
1476                (let ((symbol (sap-ref-word bsp (* sb!vm:binding-symbol-slot
1477                                                   sb!vm:n-word-bytes)))
1478                      (value (sap-ref-sap bsp (* sb!vm:binding-value-slot
1479                                                 sb!vm:n-word-bytes))))
1480                  (when (eql symbol sb!vm:unbound-marker-widetag)
1481                    (when (sap= value fp)
1482                      (setf unbind-to bsp))))))
1483     unbind-to))
1484
1485 (defun find-enclosing-catch-block (frame)
1486   ;; Walk the catch block chain looking for the first entry with an address
1487   ;; higher than the pointer for FRAME or a null pointer.
1488   (let* ((frame-pointer (sb!di::frame-pointer frame))
1489          (current-block (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1490                                       (ash sb!vm::*current-catch-block*
1491                                            sb!vm:n-fixnum-tag-bits))))
1492          (enclosing-block (loop for block = current-block
1493                                 then (sap-ref-sap block
1494                                                   (* sb!vm:catch-block-previous-catch-slot
1495                                                      sb!vm::n-word-bytes))
1496                                 when (or (zerop (sap-int block))
1497                                          (sap> block frame-pointer))
1498                                 return block)))
1499     enclosing-block))
1500
1501 (defun find-enclosing-uwp (frame)
1502   ;; Walk the UWP chain looking for the first entry with an address
1503   ;; higher than the pointer for FRAME or a null pointer.
1504   (let* ((frame-pointer (sb!di::frame-pointer frame))
1505          (current-uwp (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1506                                     (ash sb!vm::*current-unwind-protect-block*
1507                                          sb!vm:n-fixnum-tag-bits))))
1508          (enclosing-uwp (loop for uwp-block = current-uwp
1509                               then (sap-ref-sap uwp-block
1510                                                 sb!vm:unwind-block-current-uwp-slot)
1511                               when (or (zerop (sap-int uwp-block))
1512                                        (sap> uwp-block frame-pointer))
1513                               return uwp-block)))
1514     enclosing-uwp))
1515
1516 (!def-debug-command "RETURN" (&optional
1517                               (return (read-prompting-maybe
1518                                        "return: ")))
1519    (if (frame-has-debug-tag-p *current-frame*)
1520        (let* ((code-location (sb!di:frame-code-location *current-frame*))
1521               (values (multiple-value-list
1522                        (funcall (sb!di:preprocess-for-eval return code-location)
1523                                 *current-frame*))))
1524          (unwind-to-frame-and-call *current-frame* (lambda ()
1525                                                      (values-list values))))
1526        (format *debug-io*
1527                "~@<can't find a tag for this frame ~
1528                  ~2I~_(hint: try increasing the DEBUG optimization quality ~
1529                  and recompiling)~:@>")))
1530
1531 (!def-debug-command "RESTART-FRAME" ()
1532   (if (frame-has-debug-tag-p *current-frame*)
1533       (let* ((call-list (frame-call-as-list *current-frame*))
1534              (fun (fdefinition (car call-list))))
1535         (unwind-to-frame-and-call *current-frame*
1536                                   (lambda ()
1537                                     (apply fun (cdr call-list)))))
1538       (format *debug-io*
1539               "~@<can't find a tag for this frame ~
1540                  ~2I~_(hint: try increasing the DEBUG optimization quality ~
1541                  and recompiling)~:@>")))
1542
1543 (defun frame-has-debug-tag-p (frame)
1544   #!+unwind-to-frame-and-call-vop
1545   (not (null (find-binding-stack-pointer frame)))
1546   #!-unwind-to-frame-and-call-vop
1547   (find 'sb!c:debug-catch-tag (sb!di::frame-catches frame) :key #'car))
1548
1549 ;; Hack: ensure that *U-T-F-F* has a tls index.
1550 #!+unwind-to-frame-and-call-vop
1551 (let ((sb!vm::*unwind-to-frame-function* (lambda ()))))
1552
1553 \f
1554 ;;;; debug loop command utilities
1555
1556 (defun read-prompting-maybe (prompt)
1557   (unless (sb!int:listen-skip-whitespace *debug-io*)
1558     (princ prompt *debug-io*)
1559     (force-output *debug-io*))
1560   (read *debug-io*))
1561
1562 (defun read-if-available (default)
1563   (if (sb!int:listen-skip-whitespace *debug-io*)
1564       (read *debug-io*)
1565       default))