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