dd54548b03b7f5903b52696bcb9ff0c58bc84afb
[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   STEP  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
127 Function and macro commands:
128  (SB-DEBUG:ARG n)
129     Return the n'th argument in the current frame.
130  (SB-DEBUG:VAR string-or-symbol [id])
131     Returns the value of the specified variable in the current frame.
132
133 Other commands:
134   RETURN expr
135     Return the values resulting from evaluation of expr from the
136     current frame, if this frame was compiled with a sufficiently high
137     DEBUG optimization quality.
138
139   SLURP
140     Discard all pending input on *STANDARD-INPUT*. (This can be
141     useful when the debugger was invoked to handle an error in
142     deeply nested input syntax, and now the reader is confused.)")
143 \f
144
145 ;;; If LOC is an unknown location, then try to find the block start
146 ;;; location. Used by source printing to some information instead of
147 ;;; none for the user.
148 (defun maybe-block-start-location (loc)
149   (if (sb!di:code-location-unknown-p loc)
150       (let* ((block (sb!di:code-location-debug-block loc))
151              (start (sb!di:do-debug-block-locations (loc block)
152                       (return loc))))
153         (cond ((and (not (sb!di:debug-block-elsewhere-p block))
154                     start)
155                (format *debug-io* "~%unknown location: using block start~%")
156                start)
157               (t
158                loc)))
159       loc))
160 \f
161 ;;;; BACKTRACE
162
163 (defun backtrace (&optional (count most-positive-fixnum) (stream *debug-io*))
164   #!+sb-doc
165   "Show a listing of the call stack going down from the current frame.
166 In the debugger, the current frame is indicated by the prompt. COUNT
167 is how many frames to show."
168   (fresh-line stream)
169   (do ((frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
170               (sb!di:frame-down frame))
171        (count count (1- count)))
172       ((or (null frame) (zerop count)))
173     (print-frame-call frame stream :number t))
174   (fresh-line stream)
175   (values))
176
177 (defun backtrace-as-list (&optional (count most-positive-fixnum))
178   #!+sb-doc "Return a list representing the current BACKTRACE."
179   (do ((reversed-result nil)
180        (frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
181               (sb!di:frame-down frame))
182        (count count (1- count)))
183       ((or (null frame) (zerop count))
184        (nreverse reversed-result))
185     (push (frame-call-as-list frame) reversed-result)))
186
187 (defun frame-call-as-list (frame)
188   (multiple-value-bind (name args) (frame-call frame)
189     (cons name args)))
190 \f
191 ;;;; frame printing
192
193 (eval-when (:compile-toplevel :execute)
194
195 ;;; This is a convenient way to express what to do for each type of
196 ;;; lambda-list element.
197 (sb!xc:defmacro lambda-list-element-dispatch (element
198                                               &key
199                                               required
200                                               optional
201                                               rest
202                                               keyword
203                                               deleted)
204   `(etypecase ,element
205      (sb!di:debug-var
206       ,@required)
207      (cons
208       (ecase (car ,element)
209         (:optional ,@optional)
210         (:rest ,@rest)
211         (:keyword ,@keyword)))
212      (symbol
213       (aver (eq ,element :deleted))
214       ,@deleted)))
215
216 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
217   (let ((var (gensym)))
218     `(let ((,var ,variable))
219        (cond ((eq ,var :deleted) ,deleted)
220              ((eq (sb!di:debug-var-validity ,var ,location) :valid)
221               ,valid)
222              (t ,other)))))
223
224 ) ; EVAL-WHEN
225
226 ;;; This is used in constructing arg lists for debugger printing when
227 ;;; the arg list is unavailable, some arg is unavailable or unused, etc.
228 (defstruct (unprintable-object
229             (:constructor make-unprintable-object (string))
230             (:print-object (lambda (x s)
231                              (print-unreadable-object (x s)
232                                (write-string (unprintable-object-string x)
233                                              s))))
234             (:copier nil))
235   string)
236
237 ;;; Extract the function argument values for a debug frame.
238 (defun frame-args-as-list (frame)
239   (let ((debug-fun (sb!di:frame-debug-fun frame))
240         (loc (sb!di:frame-code-location frame))
241         (reversed-result nil))
242     (handler-case
243         (progn
244           (dolist (ele (sb!di:debug-fun-lambda-list debug-fun))
245             (lambda-list-element-dispatch ele
246              :required ((push (frame-call-arg ele loc frame) reversed-result))
247              :optional ((push (frame-call-arg (second ele) loc frame)
248                               reversed-result))
249              :keyword ((push (second ele) reversed-result)
250                        (push (frame-call-arg (third ele) loc frame)
251                              reversed-result))
252              :deleted ((push (frame-call-arg ele loc frame) reversed-result))
253              :rest ((lambda-var-dispatch (second ele) loc
254                      nil
255                      (progn
256                        (setf reversed-result
257                              (append (reverse (sb!di:debug-var-value
258                                                (second ele) frame))
259                                      reversed-result))
260                        (return))
261                      (push (make-unprintable-object
262                             "unavailable &REST argument")
263                      reversed-result)))))
264           ;; As long as we do an ordinary return (as opposed to SIGNALing
265           ;; a CONDITION) from the DOLIST above:
266           (nreverse reversed-result))
267       (sb!di:lambda-list-unavailable
268        ()
269        (make-unprintable-object "unavailable lambda list")))))
270 (legal-fun-name-p '(lambda ()))
271 (defvar *show-entry-point-details* nil)
272
273 (defun clean-xep (name args)
274   (values (second name)
275           (if (consp args)
276               (let ((count (first args))
277                     (real-args (rest args)))
278                 (if (fixnump count)
279                     (subseq real-args 0 
280                             (min count (length real-args)))
281                     real-args))
282               args)))
283
284 (defun clean-&more-processor (name args)
285   (values (second name)
286           (if (consp args)
287               (let* ((more (last args 2))
288                      (context (first more))
289                      (count (second more)))             
290                 (append
291                  (butlast args 2)
292                  (if (fixnump count)
293                      (multiple-value-list 
294                       (sb!c:%more-arg-values context 0 count))
295                      (list
296                       (make-unprintable-object "more unavailable arguments")))))
297               args)))
298
299 (defun frame-call (frame)
300   (labels ((clean-name-and-args (name args)
301              (if (and (consp name) (not *show-entry-point-details*))
302                  ;; FIXME: do we need to deal with
303                  ;; HAIRY-FUNCTION-ENTRY here? I can't make it or
304                  ;; &AUX-BINDINGS appear in backtraces, so they are
305                  ;; left alone for now. --NS 2005-02-28
306                  (case (first name)
307                    ((sb!c::xep sb!c::tl-xep)
308                     (clean-xep name args))
309                    ((sb!c::&more-processor)
310                     (clean-&more-processor name args))
311                    ((sb!c::hairy-arg-processor 
312                      sb!c::varargs-entry sb!c::&optional-processor)
313                     (clean-name-and-args (second name) args))
314                    (t
315                     (values name args)))
316                  (values name args))))
317     (let ((debug-fun (sb!di:frame-debug-fun frame)))
318       (multiple-value-bind (name args)
319           (clean-name-and-args (sb!di:debug-fun-name debug-fun)
320                                 (frame-args-as-list frame))
321         (values name args
322                 (when *show-entry-point-details*
323                   (sb!di:debug-fun-kind debug-fun)))))))
324
325 (defun ensure-printable-object (object)
326   (handler-case
327       (with-open-stream (out (make-broadcast-stream))
328         (prin1 object out)
329         object)
330     (error (cond)
331       (declare (ignore cond))
332       (make-unprintable-object "error printing object"))))
333
334 (defun frame-call-arg (var location frame)
335   (lambda-var-dispatch var location
336     (make-unprintable-object "unused argument")
337     (sb!di:debug-var-value var frame)
338     (make-unprintable-object "unavailable argument")))
339
340 ;;; Prints a representation of the function call causing FRAME to
341 ;;; exist. VERBOSITY indicates the level of information to output;
342 ;;; zero indicates just printing the DEBUG-FUN's name, and one
343 ;;; indicates displaying call-like, one-liner format with argument
344 ;;; values.
345 (defun print-frame-call (frame stream &key (verbosity 1) (number nil))
346   (when number
347     (format stream "~&~S: " (sb!di:frame-number frame)))
348   (if (zerop verbosity)
349       (let ((*print-readably* nil))
350         (prin1 frame stream))
351       (multiple-value-bind (name args kind) (frame-call frame)
352         (pprint-logical-block (stream nil :prefix "(" :suffix ")")
353           ;; Since we go to some trouble to make nice informative function
354           ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
355           ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
356           ;; For the function arguments, we can just print normally.
357           (let ((*print-length* nil)
358                 (*print-level* nil))
359             (prin1 (ensure-printable-object name) stream))
360           ;; If we hit a &REST arg, then print as many of the values as
361           ;; possible, punting the loop over lambda-list variables since any
362           ;; other arguments will be in the &REST arg's list of values.
363           (let ((args (ensure-printable-object args)))
364             (if (listp args)
365                 (format stream "~{ ~_~S~}" args)
366                 (format stream " ~S" args))))
367         (when kind
368           (format stream "[~S]" kind))))
369   (when (>= verbosity 2)
370     (let ((loc (sb!di:frame-code-location frame)))
371       (handler-case
372           (progn
373             ;; FIXME: Is this call really necessary here? If it is,
374             ;; then the reason for it should be unobscured.
375             (sb!di:code-location-debug-block loc)
376             (format stream "~%source: ")
377             (prin1 (code-location-source-form loc 0) stream))
378         (sb!di:debug-condition (ignore) 
379           ignore)
380         (error (c) 
381           (format stream "~&error finding source: ~A" c))))))
382 \f
383 ;;;; INVOKE-DEBUGGER
384
385 (defvar *debugger-hook* nil
386   #!+sb-doc
387   "This is either NIL or a function of two arguments, a condition and the value
388    of *DEBUGGER-HOOK*. This function can either handle the condition or return
389    which causes the standard debugger to execute. The system passes the value
390    of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
391    around the invocation.")
392
393 (defvar *invoke-debugger-hook* nil
394   #!+sb-doc
395   "This is either NIL or a designator for a function of two arguments,
396    to be run when the debugger is about to be entered.  The function is
397    run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
398    errors, and receives as arguments the condition that triggered 
399    debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*   
400
401    This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
402    In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
403    called by BREAK.")
404
405 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
406 (defvar *debug-restarts*)
407 (defvar *debug-condition*)
408 (defvar *nested-debug-condition*)
409
410 ;;; Oh, what a tangled web we weave when we preserve backwards
411 ;;; compatibility with 1968-style use of global variables to control
412 ;;; per-stream i/o properties; there's really no way to get this
413 ;;; quite right, but we do what we can.
414 (defun funcall-with-debug-io-syntax (fun &rest rest)
415   (declare (type function fun))
416   ;; Try to force the other special variables into a useful state.
417   (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
418         ;; any default we might use is less useful than just reusing
419         ;; the global values.
420         (original-package *package*)
421         (original-print-pretty *print-pretty*))
422     (with-standard-io-syntax
423       (with-sane-io-syntax
424           (let (;; We want the printer and reader to be in a useful
425                 ;; state, regardless of where the debugger was invoked
426                 ;; in the program. WITH-STANDARD-IO-SYNTAX and
427                 ;; WITH-SANE-IO-SYNTAX do much of what we want, but
428                 ;;   * It doesn't affect our internal special variables 
429                 ;;     like *CURRENT-LEVEL-IN-PRINT*.
430                 ;;   * It isn't customizable.
431                 ;;   * It sets *PACKAGE* to COMMON-LISP-USER, which is not
432                 ;;     helpful behavior for a debugger.
433                 ;;   * There's no particularly good debugger default for
434                 ;;     *PRINT-PRETTY*, since T is usually what you want
435                 ;;     -- except absolutely not what you want when you're
436                 ;;     debugging failures in PRINT-OBJECT logic.
437                 ;; We try to address all these issues with explicit
438                 ;; rebindings here.
439                 (sb!kernel:*current-level-in-print* 0)
440                 (*package* original-package)
441                 (*print-pretty* original-print-pretty)
442                 ;; Clear the circularity machinery to try to to reduce the
443                 ;; pain from sharing the circularity table across all
444                 ;; streams; if these are not rebound here, then setting
445                 ;; *PRINT-CIRCLE* within the debugger when debugging in a
446                 ;; state where something circular was being printed (e.g.,
447                 ;; because the debugger was entered on an error in a
448                 ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
449                 ;; here does seem somewhat ugly because it makes it more
450                 ;; difficult to debug the printing-of-circularities code
451                 ;; itself; however, as far as I (WHN, 2004-05-29) can see,
452                 ;; that's almost entirely academic as long as there's one
453                 ;; shared *C-H-T* for all streams (i.e., it's already
454                 ;; unreasonably difficult to debug print-circle machinery
455                 ;; given the buggy crosstalk between the debugger streams
456                 ;; and the stream you're trying to watch), and any fix for
457                 ;; that buggy arrangement will likely let this hack go away
458                 ;; naturally.
459                 (sb!impl::*circularity-hash-table* . nil)
460                 (sb!impl::*circularity-counter* . nil)
461                 (*readtable* *debug-readtable*))
462             (progv
463                 ;; (Why NREVERSE? PROGV makes the later entries have
464                 ;; precedence over the earlier entries.
465                 ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
466                 ;; expected that its earlier entries have precedence. And
467                 ;; the earlier-has-precedence behavior is mostly more
468                 ;; convenient, so that programmers can use PUSH or LIST* to
469                 ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
470                 (nreverse (mapcar #'car *debug-print-variable-alist*))
471                 (nreverse (mapcar #'cdr *debug-print-variable-alist*))
472               (apply fun rest)))))))
473
474 ;;; the ordinary ANSI case of INVOKE-DEBUGGER, when not suppressed by
475 ;;; command-line --disable-debugger option
476 (defun invoke-debugger (condition)
477   #!+sb-doc
478   "Enter the debugger."
479
480   (let ((old-hook *debugger-hook*))
481     (when old-hook
482       (let ((*debugger-hook* nil))
483         (funcall old-hook condition old-hook))))
484   (let ((old-hook *invoke-debugger-hook*))
485     (when old-hook
486       (let ((*invoke-debugger-hook* nil))
487         (funcall old-hook condition old-hook))))
488
489   ;; Note: CMU CL had (SB-UNIX:UNIX-SIGSETMASK 0) here, to reset the
490   ;; signal state in the case that we wind up in the debugger as a
491   ;; result of something done by a signal handler.  It's not
492   ;; altogether obvious that this is necessary, and indeed SBCL has
493   ;; not been doing it since 0.7.8.5.  But nobody seems altogether
494   ;; convinced yet
495   ;; -- dan 2003.11.11, based on earlier comment of WHN 2002-09-28
496
497   ;; We definitely want *PACKAGE* to be of valid type.
498   ;;
499   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
500   ;; this, but here causing an exception just as we're trying to handle
501   ;; an exception would be confusing, so instead we use a special hack.
502   (unless (and (packagep *package*)
503                (package-name *package*))
504     (setf *package* (find-package :cl-user))
505     (format *error-output*
506             "The value of ~S was not an undeleted PACKAGE. It has been
507 reset to ~S."
508             '*package* *package*))
509
510   ;; Before we start our own output, finish any pending output.
511   ;; Otherwise, if the user tried to track the progress of his program
512   ;; using PRINT statements, he'd tend to lose the last line of output
513   ;; or so, which'd be confusing.
514   (flush-standard-output-streams)
515
516   (funcall-with-debug-io-syntax #'%invoke-debugger condition))
517
518 (defun %invoke-debugger (condition)
519   
520   (let ((*debug-condition* condition)
521         (*debug-restarts* (compute-restarts condition))
522         (*nested-debug-condition* nil))
523     (handler-case
524         ;; (The initial output here goes to *ERROR-OUTPUT*, because the
525         ;; initial output is not interactive, just an error message, and
526         ;; when people redirect *ERROR-OUTPUT*, they could reasonably
527         ;; expect to see error messages logged there, regardless of what
528         ;; the debugger does afterwards.)
529         (format *error-output*
530                 "~2&~@<debugger invoked on a ~S~@[ in thread ~A~]: ~
531                     ~2I~_~A~:>~%"
532                 (type-of *debug-condition*)
533                 #!+sb-thread sb!thread:*current-thread*
534                 #!-sb-thread nil
535                 *debug-condition*)
536       (error (condition)
537         (setf *nested-debug-condition* condition)
538         (let ((ndc-type (type-of *nested-debug-condition*)))
539           (format *error-output*
540                   "~&~@<(A ~S was caught when trying to print ~S when ~
541                       entering the debugger. Printing was aborted and the ~
542                       ~S was stored in ~S.)~@:>~%"
543                   ndc-type
544                   '*debug-condition*
545                   ndc-type
546                   '*nested-debug-condition*))
547         (when (typep condition 'cell-error)
548           ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
549           (format *error-output*
550                   "~&(CELL-ERROR-NAME ~S) = ~S~%"
551                   '*debug-condition*
552                   (cell-error-name *debug-condition*)))))
553
554     (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
555                          *debug-io*)))
556
557       ;; After the initial error/condition/whatever announcement to
558       ;; *ERROR-OUTPUT*, we become interactive, and should talk on
559       ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
560       ;; statement, not a description of reality.:-| There's a lot of
561       ;; older debugger code which was written to do i/o on whatever
562       ;; stream was in fashion at the time, and not all of it has
563       ;; been converted to behave this way. -- WHN 2000-11-16)
564
565       (unwind-protect
566            (let (;; We used to bind *STANDARD-OUTPUT* to *DEBUG-IO*
567                  ;; here as well, but that is probably bogus since it
568                  ;; removes the users ability to do output to a redirected
569                  ;; *S-O*. Now we just rebind it so that users can temporarily
570                  ;; frob it. FIXME: This and other "what gets bound when"
571                  ;; behaviour should be documented in the manual.
572                  (*standard-output* *standard-output*)
573                  ;; This seems reasonable: e.g. if the user has redirected
574                  ;; *ERROR-OUTPUT* to some log file, it's probably wrong
575                  ;; to send errors which occur in interactive debugging to
576                  ;; that file, and right to send them to *DEBUG-IO*.
577                  (*error-output* *debug-io*))
578              (unless (typep condition 'step-condition)
579                (when *debug-beginner-help-p*
580                  (format *debug-io*
581                          "~%~@<Type HELP for debugger help, or ~
582                                (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
583                (show-restarts *debug-restarts* *debug-io*))
584              (internal-debug))
585         (when background-p
586           (sb!thread::release-foreground))))))
587
588 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
589 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
590 ;;; command-line option
591 (defun debugger-disabled-hook (condition me)
592   (declare (ignore me))
593   ;; There is no one there to interact with, so report the
594   ;; condition and terminate the program.
595   (flet ((failure-quit (&key recklessly-p)
596            (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
597            (quit :unix-status 1 :recklessly-p recklessly-p)))
598     ;; This HANDLER-CASE is here mostly to stop output immediately
599     ;; (and fall through to QUIT) when there's an I/O error. Thus,
600     ;; when we're run under a shell script or something, we can die
601     ;; cleanly when the script dies (and our pipes are cut), instead
602     ;; of falling into ldb or something messy like that. Similarly, we
603     ;; can terminate cleanly even if BACKTRACE dies because of bugs in
604     ;; user PRINT-OBJECT methods.
605     (handler-case
606         (progn
607           (format *error-output*
608                   "~&~@<unhandled ~S~@[ in thread ~S~]: ~2I~_~A~:>~2%"
609                   (type-of condition)
610                   #!+sb-thread sb!thread:*current-thread*
611                   #!-sb-thread nil
612                   condition)
613           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
614           ;; even if we hit an error within BACKTRACE (e.g. a bug in
615           ;; the debugger's own frame-walking code, or a bug in a user
616           ;; PRINT-OBJECT method) we'll at least have the CONDITION
617           ;; printed out before we die.
618           (finish-output *error-output*)
619           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
620           ;; it seems as though we should at least truncate it somewhere.)
621           (sb!debug:backtrace 128 *error-output*)
622           (format
623            *error-output*
624            "~%unhandled condition in --disable-debugger mode, quitting~%")
625           (finish-output *error-output*)
626           (failure-quit))
627       (condition ()
628         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
629         ;; fail when our output streams are blown away, as e.g. when
630         ;; we're running under a Unix shell script and it dies somehow
631         ;; (e.g. because of a SIGINT). In that case, we might as well
632         ;; just give it up for a bad job, and stop trying to notify
633         ;; the user of anything.
634         ;;
635         ;; Actually, the only way I've run across to exercise the
636         ;; problem is to have more than one layer of shell script.
637         ;; I have a shell script which does
638         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
639         ;; and the problem occurs when I interrupt this with Ctrl-C
640         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
641         ;; I haven't figured out whether it's bash, time, tee, Linux, or
642         ;; what that is responsible, but that it's possible at all
643         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
644         (ignore-errors
645          (%primitive print
646                      "Argh! error within --disable-debugger error handling"))
647         (failure-quit :recklessly-p t)))))
648
649 ;;; halt-on-failures and prompt-on-failures modes, suitable for
650 ;;; noninteractive and interactive use respectively
651 (defun disable-debugger ()
652   (when (eql *invoke-debugger-hook* nil)
653     (setf *debug-io* *error-output*
654           *invoke-debugger-hook* 'debugger-disabled-hook)))
655
656 (defun enable-debugger ()
657   (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
658     (setf *invoke-debugger-hook* nil)))
659
660 (setf *debug-io* *query-io*)
661
662 (defun show-restarts (restarts s)
663   (cond ((null restarts)
664          (format s
665                  "~&(no restarts: If you didn't do this on purpose, ~
666                   please report it as a bug.)~%"))
667         (t
668          (format s "~&restarts (invokable by number or by ~
669                     possibly-abbreviated name):~%")
670          (let ((count 0)
671                (names-used '(nil))
672                (max-name-len 0))
673            (dolist (restart restarts)
674              (let ((name (restart-name restart)))
675                (when name
676                  (let ((len (length (princ-to-string name))))
677                    (when (> len max-name-len)
678                      (setf max-name-len len))))))
679            (unless (zerop max-name-len)
680              (incf max-name-len 3))
681            (dolist (restart restarts)
682              (let ((name (restart-name restart)))
683                ;; FIXME: maybe it would be better to display later names
684                ;; in parens instead of brakets, not just omit them fully.
685                ;; Call BREAK, call BREAK in the debugger, and tell me
686                ;; it's not confusing looking. --NS 20050310
687                (cond ((member name names-used)
688                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
689                      (t
690                       (format s "~& ~2D: [~VA] ~A~%"
691                               count (- max-name-len 3) name restart)
692                       (push name names-used))))
693              (incf count))))))
694
695 (defvar *debug-loop-fun* #'debug-loop-fun
696   "a function taking no parameters that starts the low-level debug loop")
697
698 ;;; This calls DEBUG-LOOP, performing some simple initializations
699 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
700 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
701 ;;; to get into a debug prompt as quickly as possible with as little
702 ;;; risk as possible for stepping on whatever is causing recursive
703 ;;; errors.
704 (defun internal-debug ()
705   (let ((*in-the-debugger* t)
706         (*read-suppress* nil))
707     (unless (typep *debug-condition* 'step-condition)
708       (clear-input *debug-io*))
709     (funcall *debug-loop-fun*)))
710 \f
711 ;;;; DEBUG-LOOP
712
713 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
714 ;;; was motivated by desire to play nicely with ILISP.
715 (defvar *flush-debug-errors* nil
716   #!+sb-doc
717   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
718    executing in the debugger.")
719
720 (defun debug-loop-fun ()
721   (let* ((*debug-command-level* (1+ *debug-command-level*))
722          (*real-stack-top* (sb!di:top-frame))
723          (*stack-top* (or *stack-top-hint* *real-stack-top*))
724          (*stack-top-hint* nil)
725          (*current-frame* *stack-top*))
726     (handler-bind ((sb!di:debug-condition
727                     (lambda (condition)
728                       (princ condition *debug-io*)
729                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
730                       (throw 'debug-loop-catcher nil))))
731       (terpri *debug-io*)
732       (print-frame-call *current-frame* *debug-io* :verbosity 2)
733       (loop
734         (catch 'debug-loop-catcher
735           (handler-bind ((error (lambda (condition)
736                                   (when *flush-debug-errors*
737                                     (clear-input *debug-io*)
738                                     (princ condition *debug-io*)
739                                     (format *debug-io*
740                                             "~&error flushed (because ~
741                                              ~S is set)"
742                                             '*flush-debug-errors*)
743                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
744                                     (throw 'debug-loop-catcher nil)))))
745             ;; We have to bind LEVEL for the restart function created by
746             ;; WITH-SIMPLE-RESTART.
747             (let ((level *debug-command-level*)
748                   (restart-commands (make-restart-commands)))
749               (with-simple-restart (abort
750                                    "~@<Reduce debugger level (to debug level ~W).~@:>"
751                                     level)
752                 (debug-prompt *debug-io*)
753                 (force-output *debug-io*)
754                 (let* ((exp (read *debug-io*))
755                        (cmd-fun (debug-command-p exp restart-commands)))
756                   (cond ((not cmd-fun)
757                          (debug-eval-print exp))
758                         ((consp cmd-fun)
759                          (format *debug-io* 
760                                  "~&Your command, ~S, is ambiguous:~%"
761                                  exp)
762                          (dolist (ele cmd-fun)
763                            (format *debug-io* "   ~A~%" ele)))
764                         (t
765                          (funcall cmd-fun))))))))))))
766
767 (defun debug-eval-print (expr)
768   (/noshow "entering DEBUG-EVAL-PRINT" expr)
769   (let ((values (multiple-value-list (interactive-eval expr))))
770     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
771     (dolist (value values)
772       (fresh-line *debug-io*)
773       (prin1 value *debug-io*)))
774   (force-output *debug-io*))
775 \f
776 ;;;; debug loop functions
777
778 ;;; These commands are functions, not really commands, so that users
779 ;;; can get their hands on the values returned.
780
781 (eval-when (:execute :compile-toplevel)
782
783 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
784   `(let* ((temp (etypecase name
785                   (symbol (sb!di:debug-fun-symbol-vars
786                            (sb!di:frame-debug-fun *current-frame*)
787                            name))
788                   (simple-string (sb!di:ambiguous-debug-vars
789                                   (sb!di:frame-debug-fun *current-frame*)
790                                   name))))
791           (location (sb!di:frame-code-location *current-frame*))
792           ;; Let's only deal with valid variables.
793           (vars (remove-if-not (lambda (v)
794                                  (eq (sb!di:debug-var-validity v location)
795                                      :valid))
796                                temp)))
797      (declare (list vars))
798      (cond ((null vars)
799             (error "No known valid variables match ~S." name))
800            ((= (length vars) 1)
801             ,(ecase ref-or-set
802                (:ref
803                 '(sb!di:debug-var-value (car vars) *current-frame*))
804                (:set
805                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
806                        ,value-var))))
807            (t
808             ;; Since we have more than one, first see whether we have
809             ;; any variables that exactly match the specification.
810             (let* ((name (etypecase name
811                            (symbol (symbol-name name))
812                            (simple-string name)))
813                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
814                    ;; instead.
815                    (exact (remove-if-not (lambda (v)
816                                            (string= (sb!di:debug-var-symbol-name v)
817                                                     name))
818                                          vars))
819                    (vars (or exact vars)))
820               (declare (simple-string name)
821                        (list exact vars))
822               (cond
823                ;; Check now for only having one variable.
824                ((= (length vars) 1)
825                 ,(ecase ref-or-set
826                    (:ref
827                     '(sb!di:debug-var-value (car vars) *current-frame*))
828                    (:set
829                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
830                            ,value-var))))
831                ;; If there weren't any exact matches, flame about
832                ;; ambiguity unless all the variables have the same
833                ;; name.
834                ((and (not exact)
835                      (find-if-not
836                       (lambda (v)
837                         (string= (sb!di:debug-var-symbol-name v)
838                                  (sb!di:debug-var-symbol-name (car vars))))
839                       (cdr vars)))
840                 (error "specification ambiguous:~%~{   ~A~%~}"
841                        (mapcar #'sb!di:debug-var-symbol-name
842                                (delete-duplicates
843                                 vars :test #'string=
844                                 :key #'sb!di:debug-var-symbol-name))))
845                ;; All names are the same, so see whether the user
846                ;; ID'ed one of them.
847                (id-supplied
848                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
849                   (unless v
850                     (error
851                      "invalid variable ID, ~W: should have been one of ~S"
852                      id
853                      (mapcar #'sb!di:debug-var-id vars)))
854                   ,(ecase ref-or-set
855                      (:ref
856                       '(sb!di:debug-var-value v *current-frame*))
857                      (:set
858                       `(setf (sb!di:debug-var-value v *current-frame*)
859                              ,value-var)))))
860                (t
861                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
862                        name
863                        (mapcar #'sb!di:debug-var-id vars)))))))))
864
865 ) ; EVAL-WHEN
866
867 ;;; FIXME: This doesn't work. It would be real nice we could make it
868 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
869 (defun var (name &optional (id 0 id-supplied))
870   #!+sb-doc
871   "Return a variable's value if possible. NAME is a simple-string or symbol.
872    If it is a simple-string, it is an initial substring of the variable's name.
873    If name is a symbol, it has the same name and package as the variable whose
874    value this function returns. If the symbol is uninterned, then the variable
875    has the same name as the symbol, but it has no package.
876
877    If name is the initial substring of variables with different names, then
878    this return no values after displaying the ambiguous names. If name
879    determines multiple variables with the same name, then you must use the
880    optional id argument to specify which one you want. If you left id
881    unspecified, then this returns no values after displaying the distinguishing
882    id values.
883
884    The result of this function is limited to the availability of variable
885    information. This is SETF'able."
886   (define-var-operation :ref))
887 (defun (setf var) (value name &optional (id 0 id-supplied))
888   (define-var-operation :set value))
889
890 ;;; This returns the COUNT'th arg as the user sees it from args, the
891 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
892 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
893 ;;; T. If this returns a keyword symbol or a value from a rest arg,
894 ;;; then the second value is NIL.
895 ;;;
896 ;;; FIXME: There's probably some way to merge the code here with
897 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
898 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
899 (declaim (ftype (function (index list)) nth-arg))
900 (defun nth-arg (count args)
901   (let ((n count))
902     (dolist (ele args (error "The argument specification ~S is out of range."
903                              n))
904       (lambda-list-element-dispatch ele
905         :required ((if (zerop n) (return (values ele t))))
906         :optional ((if (zerop n) (return (values (second ele) t))))
907         :keyword ((cond ((zerop n)
908                          (return (values (second ele) nil)))
909                         ((zerop (decf n))
910                          (return (values (third ele) t)))))
911         :deleted ((if (zerop n) (return (values ele t))))
912         :rest ((let ((var (second ele)))
913                  (lambda-var-dispatch var (sb!di:frame-code-location
914                                            *current-frame*)
915                    (error "unused &REST argument before n'th argument")
916                    (dolist (value
917                             (sb!di:debug-var-value var *current-frame*)
918                             (error
919                              "The argument specification ~S is out of range."
920                              n))
921                      (if (zerop n)
922                          (return-from nth-arg (values value nil))
923                          (decf n)))
924                    (error "invalid &REST argument before n'th argument")))))
925       (decf n))))
926
927 (defun arg (n)
928   #!+sb-doc
929   "Return the N'th argument's value if possible. Argument zero is the first
930    argument in a frame's default printed representation. Count keyword/value
931    pairs as separate arguments."
932   (multiple-value-bind (var lambda-var-p)
933       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
934                                 (sb!di:frame-debug-fun *current-frame*))
935                    (sb!di:lambda-list-unavailable ()
936                      (error "No argument values are available."))))
937     (if lambda-var-p
938         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
939           (error "Unused arguments have no values.")
940           (sb!di:debug-var-value var *current-frame*)
941           (error "invalid argument value"))
942         var)))
943 \f
944 ;;;; machinery for definition of debug loop commands
945
946 (defvar *debug-commands* nil)
947
948 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
949 ;;; permitted.
950 (defmacro !def-debug-command (name args &rest body)
951   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
952     `(progn
953        (setf *debug-commands*
954              (remove ,name *debug-commands* :key #'car :test #'string=))
955        (defun ,fun-name ,args
956          (unless *in-the-debugger*
957            (error "invoking debugger command while outside the debugger"))
958          ,@body)
959        (push (cons ,name #',fun-name) *debug-commands*)
960        ',fun-name)))
961
962 (defun !def-debug-command-alias (new-name existing-name)
963   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
964     (unless pair (error "unknown debug command name: ~S" existing-name))
965     (push (cons new-name (cdr pair)) *debug-commands*))
966   new-name)
967
968 ;;; This takes a symbol and uses its name to find a debugger command,
969 ;;; using initial substring matching. It returns the command function
970 ;;; if form identifies only one command, but if form is ambiguous,
971 ;;; this returns a list of the command names. If there are no matches,
972 ;;; this returns nil. Whenever the loop that looks for a set of
973 ;;; possibilities encounters an exact name match, we return that
974 ;;; command function immediately.
975 (defun debug-command-p (form &optional other-commands)
976   (if (or (symbolp form) (integerp form))
977       (let* ((name
978               (if (symbolp form)
979                   (symbol-name form)
980                   (format nil "~W" form)))
981              (len (length name))
982              (res nil))
983         (declare (simple-string name)
984                  (fixnum len)
985                  (list res))
986
987         ;; Find matching commands, punting if exact match.
988         (flet ((match-command (ele)
989                  (let* ((str (car ele))
990                         (str-len (length str)))
991                    (declare (simple-string str)
992                             (fixnum str-len))
993                    (cond ((< str-len len))
994                          ((= str-len len)
995                           (when (string= name str :end1 len :end2 len)
996                             (return-from debug-command-p (cdr ele))))
997                          ((string= name str :end1 len :end2 len)
998                           (push ele res))))))
999           (mapc #'match-command *debug-commands*)
1000           (mapc #'match-command other-commands))
1001
1002         ;; Return the right value.
1003         (cond ((not res) nil)
1004               ((= (length res) 1)
1005                (cdar res))
1006               (t ; Just return the names.
1007                (do ((cmds res (cdr cmds)))
1008                    ((not cmds) res)
1009                  (setf (car cmds) (caar cmds))))))))
1010
1011 ;;; Return a list of debug commands (in the same format as
1012 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1013 ;;;
1014 ;;; Two commands are made for each restart: one for the number, and
1015 ;;; one for the restart name (unless it's been shadowed by an earlier
1016 ;;; restart of the same name, or it is NIL).
1017 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1018   (let ((commands)
1019         (num 0))                        ; better be the same as show-restarts!
1020     (dolist (restart restarts)
1021       (let ((name (string (restart-name restart))))
1022         (let ((restart-fun
1023                 (lambda ()
1024                   (/show0 "in restart-command closure, about to i-r-i")
1025                   (invoke-restart-interactively restart))))
1026           (push (cons (prin1-to-string num) restart-fun) commands)
1027           (unless (or (null (restart-name restart)) 
1028                       (find name commands :key #'car :test #'string=))
1029             (push (cons name restart-fun) commands))))
1030     (incf num))
1031   commands))
1032 \f
1033 ;;;; frame-changing commands
1034
1035 (!def-debug-command "UP" ()
1036   (let ((next (sb!di:frame-up *current-frame*)))
1037     (cond (next
1038            (setf *current-frame* next)
1039            (print-frame-call next *debug-io*))
1040           (t
1041            (format *debug-io* "~&Top of stack.")))))
1042
1043 (!def-debug-command "DOWN" ()
1044   (let ((next (sb!di:frame-down *current-frame*)))
1045     (cond (next
1046            (setf *current-frame* next)
1047            (print-frame-call next *debug-io*))
1048           (t
1049            (format *debug-io* "~&Bottom of stack.")))))
1050
1051 (!def-debug-command-alias "D" "DOWN")
1052
1053 (!def-debug-command "BOTTOM" ()
1054   (do ((prev *current-frame* lead)
1055        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1056       ((null lead)
1057        (setf *current-frame* prev)
1058        (print-frame-call prev *debug-io*))))
1059
1060 (!def-debug-command-alias "B" "BOTTOM")
1061
1062 (!def-debug-command "FRAME" (&optional
1063                              (n (read-prompting-maybe "frame number: ")))
1064   (setf *current-frame*
1065         (multiple-value-bind (next-frame-fun limit-string)
1066             (if (< n (sb!di:frame-number *current-frame*))
1067                 (values #'sb!di:frame-up "top")
1068               (values #'sb!di:frame-down "bottom"))
1069           (do ((frame *current-frame*))
1070               ((= n (sb!di:frame-number frame))
1071                frame)
1072             (let ((next-frame (funcall next-frame-fun frame)))
1073               (cond (next-frame
1074                      (setf frame next-frame))
1075                     (t
1076                      (format *debug-io*
1077                              "The ~A of the stack was encountered.~%"
1078                              limit-string)
1079                      (return frame)))))))
1080   (print-frame-call *current-frame* *debug-io*))
1081
1082 (!def-debug-command-alias "F" "FRAME")
1083 \f
1084 ;;;; commands for entering and leaving the debugger
1085
1086 (!def-debug-command "TOPLEVEL" ()
1087   (throw 'toplevel-catcher nil))
1088
1089 ;;; make T safe
1090 (!def-debug-command-alias "TOP" "TOPLEVEL")
1091
1092 (!def-debug-command "RESTART" ()
1093   (/show0 "doing RESTART debug-command")
1094   (let ((num (read-if-available :prompt)))
1095     (when (eq num :prompt)
1096       (show-restarts *debug-restarts* *debug-io*)
1097       (write-string "restart: ")
1098       (force-output)
1099       (setf num (read *debug-io*)))
1100     (let ((restart (typecase num
1101                      (unsigned-byte
1102                       (nth num *debug-restarts*))
1103                      (symbol
1104                       (find num *debug-restarts* :key #'restart-name
1105                             :test (lambda (sym1 sym2)
1106                                     (string= (symbol-name sym1)
1107                                              (symbol-name sym2)))))
1108                      (t
1109                       (format *debug-io* "~S is invalid as a restart name.~%" 
1110                               num)
1111                       (return-from restart-debug-command nil)))))
1112       (/show0 "got RESTART")
1113       (if restart
1114           (invoke-restart-interactively restart)
1115           (princ "There is no such restart." *debug-io*)))))
1116 \f
1117 ;;;; information commands
1118
1119 (!def-debug-command "HELP" ()
1120   ;; CMU CL had a little toy pager here, but "if you aren't running
1121   ;; ILISP (or a smart windowing system, or something) you deserve to
1122   ;; lose", so we've dropped it in SBCL. However, in case some
1123   ;; desperate holdout is running this on a dumb terminal somewhere,
1124   ;; we tell him where to find the message stored as a string.
1125   (format *debug-io*
1126           "~&~A~2%(The HELP string is stored in ~S.)~%"
1127           *debug-help-string*
1128           '*debug-help-string*))
1129
1130 (!def-debug-command-alias "?" "HELP")
1131
1132 (!def-debug-command "ERROR" ()
1133   (format *debug-io* "~A~%" *debug-condition*)
1134   (show-restarts *debug-restarts* *debug-io*))
1135
1136 (!def-debug-command "BACKTRACE" ()
1137   (backtrace (read-if-available most-positive-fixnum)))
1138
1139 (!def-debug-command "PRINT" ()
1140   (print-frame-call *current-frame* *debug-io*))
1141
1142 (!def-debug-command-alias "P" "PRINT")
1143
1144 (!def-debug-command "LIST-LOCALS" ()
1145   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1146     (if (sb!di:debug-var-info-available d-fun)
1147         (let ((*standard-output* *debug-io*)
1148               (location (sb!di:frame-code-location *current-frame*))
1149               (prefix (read-if-available nil))
1150               (any-p nil)
1151               (any-valid-p nil))
1152           (dolist (v (sb!di:ambiguous-debug-vars
1153                         d-fun
1154                         (if prefix (string prefix) "")))
1155             (setf any-p t)
1156             (when (eq (sb!di:debug-var-validity v location) :valid)
1157               (setf any-valid-p t)
1158               (format *debug-io* "~S~:[#~W~;~*~]  =  ~S~%"
1159                       (sb!di:debug-var-symbol v)
1160                       (zerop (sb!di:debug-var-id v))
1161                       (sb!di:debug-var-id v)
1162                       (sb!di:debug-var-value v *current-frame*))))
1163
1164           (cond
1165            ((not any-p)
1166             (format *debug-io* 
1167                     "There are no local variables ~@[starting with ~A ~]~
1168                     in the function."
1169                     prefix))
1170            ((not any-valid-p)
1171             (format *debug-io* 
1172                     "All variables ~@[starting with ~A ~]currently ~
1173                     have invalid values."
1174                     prefix))))
1175         (write-line "There is no variable information available."
1176                     *debug-io*))))
1177
1178 (!def-debug-command-alias "L" "LIST-LOCALS")
1179
1180 (!def-debug-command "SOURCE" ()
1181   (print (code-location-source-form (sb!di:frame-code-location *current-frame*)
1182                                     (read-if-available 0))
1183          *debug-io*))
1184 \f
1185 ;;;; source location printing
1186
1187 ;;; We cache a stream to the last valid file debug source so that we
1188 ;;; won't have to repeatedly open the file.
1189 ;;;
1190 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1191 ;;; in the 1990s, so the benefit is negligible, less important than the
1192 ;;; potential of extra confusion if someone changes the source during
1193 ;;; a debug session and the change doesn't show up. And removing this
1194 ;;; would simplify the system, which I like. -- WHN 19990903
1195 (defvar *cached-debug-source* nil)
1196 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1197 (defvar *cached-source-stream* nil)
1198 (declaim (type (or stream null) *cached-source-stream*))
1199
1200 ;;; To suppress the read-time evaluation #. macro during source read,
1201 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1202 ;;; copying it each time, and invalidated when the
1203 ;;; *CACHED-DEBUG-SOURCE* has changed.
1204 (defvar *cached-readtable* nil)
1205 (declaim (type (or readtable null) *cached-readtable*))
1206
1207 ;;; Stuff to clean up before saving a core
1208 (defun debug-deinit ()
1209   (setf *cached-debug-source* nil
1210         *cached-source-stream* nil
1211         *cached-readtable* nil))
1212
1213 ;;; We also cache the last toplevel form that we printed a source for
1214 ;;; so that we don't have to do repeated reads and calls to
1215 ;;; FORM-NUMBER-TRANSLATIONS.
1216 (defvar *cached-toplevel-form-offset* nil)
1217 (declaim (type (or index null) *cached-toplevel-form-offset*))
1218 (defvar *cached-toplevel-form*)
1219 (defvar *cached-form-number-translations*)
1220
1221 ;;; Given a code location, return the associated form-number
1222 ;;; translations and the actual top level form. We check our cache ---
1223 ;;; if there is a miss, we dispatch on the kind of the debug source.
1224 (defun get-toplevel-form (location)
1225   (let ((d-source (sb!di:code-location-debug-source location)))
1226     (if (and (eq d-source *cached-debug-source*)
1227              (eql (sb!di:code-location-toplevel-form-offset location)
1228                   *cached-toplevel-form-offset*))
1229         (values *cached-form-number-translations* *cached-toplevel-form*)
1230         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1231                (res
1232                 (ecase (sb!di:debug-source-from d-source)
1233                   (:file (get-file-toplevel-form location))
1234                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1235           (setq *cached-toplevel-form-offset* offset)
1236           (values (setq *cached-form-number-translations*
1237                         (sb!di:form-number-translations res offset))
1238                   (setq *cached-toplevel-form* res))))))
1239
1240 ;;; Locate the source file (if it still exists) and grab the top level
1241 ;;; form. If the file is modified, we use the top level form offset
1242 ;;; instead of the recorded character offset.
1243 (defun get-file-toplevel-form (location)
1244   (let* ((d-source (sb!di:code-location-debug-source location))
1245          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1246          (local-tlf-offset (- tlf-offset
1247                               (sb!di:debug-source-root-number d-source)))
1248          (char-offset
1249           (aref (or (sb!di:debug-source-start-positions d-source)
1250                     (error "no start positions map"))
1251                 local-tlf-offset))
1252          (name (sb!di:debug-source-name d-source)))
1253     (unless (eq d-source *cached-debug-source*)
1254       (unless (and *cached-source-stream*
1255                    (equal (pathname *cached-source-stream*)
1256                           (pathname name)))
1257         (setq *cached-readtable* nil)
1258         (when *cached-source-stream* (close *cached-source-stream*))
1259         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1260         (unless *cached-source-stream*
1261           (error "The source file no longer exists:~%  ~A" (namestring name)))
1262         (format *debug-io* "~%; file: ~A~%" (namestring name)))
1263
1264         (setq *cached-debug-source*
1265               (if (= (sb!di:debug-source-created d-source)
1266                      (file-write-date name))
1267                   d-source nil)))
1268
1269     (cond
1270      ((eq *cached-debug-source* d-source)
1271       (file-position *cached-source-stream* char-offset))
1272      (t
1273       (format *debug-io*
1274               "~%; File has been modified since compilation:~%;   ~A~@
1275                  ; Using form offset instead of character position.~%"
1276               (namestring name))
1277       (file-position *cached-source-stream* 0)
1278       (let ((*read-suppress* t))
1279         (dotimes (i local-tlf-offset)
1280           (read *cached-source-stream*)))))
1281     (unless *cached-readtable*
1282       (setq *cached-readtable* (copy-readtable))
1283       (set-dispatch-macro-character
1284        #\# #\.
1285        (lambda (stream sub-char &rest rest)
1286          (declare (ignore rest sub-char))
1287          (let ((token (read stream t nil t)))
1288            (format nil "#.~S" token)))
1289        *cached-readtable*))
1290     (let ((*readtable* *cached-readtable*))
1291       (read *cached-source-stream*))))
1292
1293 (defun code-location-source-form (location context)
1294   (let* ((location (maybe-block-start-location location))
1295          (form-num (sb!di:code-location-form-number location)))
1296     (multiple-value-bind (translations form) (get-toplevel-form location)
1297       (unless (< form-num (length translations))
1298         (error "The source path no longer exists."))
1299       (sb!di:source-path-context form
1300                                  (svref translations form-num)
1301                                  context))))
1302 \f
1303 ;;; step to the next steppable form
1304 (!def-debug-command "STEP" ()
1305   (let ((restart (find-restart 'continue *debug-condition*)))
1306     (cond (restart
1307            (setf *stepping* t
1308                  *step* t)
1309            (invoke-restart restart))
1310           (t
1311            (format *debug-io* "~&Non-continuable error, cannot step.~%")))))
1312
1313 ;;; miscellaneous commands
1314
1315 (!def-debug-command "DESCRIBE" ()
1316   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1317          (debug-fun (sb!di:code-location-debug-fun curloc))
1318          (function (sb!di:debug-fun-fun debug-fun)))
1319     (if function
1320         (describe function)
1321         (format *debug-io* "can't figure out the function for this frame"))))
1322
1323 (!def-debug-command "SLURP" ()
1324   (loop while (read-char-no-hang *standard-input*)))
1325
1326 (!def-debug-command "RETURN" (&optional
1327                               (return (read-prompting-maybe
1328                                        "return: ")))
1329   (let ((tag (find-if (lambda (x)
1330                         (and (typep (car x) 'symbol)
1331                              (not (symbol-package (car x)))
1332                              (string= (car x) "SB-DEBUG-CATCH-TAG")))
1333                       (sb!di::frame-catches *current-frame*))))
1334     (if tag
1335         (throw (car tag)
1336           (funcall (sb!di:preprocess-for-eval
1337                     return
1338                     (sb!di:frame-code-location *current-frame*))
1339                    *current-frame*))
1340         (format *debug-io* 
1341                 "~@<can't find a tag for this frame ~
1342                  ~2I~_(hint: try increasing the DEBUG optimization quality ~
1343                  and recompiling)~:@>"))))
1344 \f
1345 ;;;; debug loop command utilities
1346
1347 (defun read-prompting-maybe (prompt)
1348   (unless (sb!int:listen-skip-whitespace *debug-io*)
1349     (princ prompt *debug-io*)
1350     (force-output *debug-io*))
1351   (read *debug-io*))
1352
1353 (defun read-if-available (default)
1354   (if (sb!int:listen-skip-whitespace *debug-io*)
1355       (read *debug-io*)
1356       default))