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