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