0e33618d699a43b9bb43bf3cef4d247efd062a99
[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-level* 5
35   #!+sb-doc
36   "*PRINT-LEVEL* for the debugger")
37 (defvar *debug-print-length* 7
38   #!+sb-doc
39   "*PRINT-LENGTH* for the debugger")
40
41 (defvar *debug-readtable*
42   ;; KLUDGE: This can't be initialized in a cold toplevel form,
43   ;; because the *STANDARD-READTABLE* isn't initialized until after
44   ;; cold toplevel forms have run. So instead we initialize it
45   ;; immediately after *STANDARD-READTABLE*. -- WHN 20000205
46   nil
47   #!+sb-doc
48   "*READTABLE* for the debugger")
49
50 (defvar *in-the-debugger* nil
51   #!+sb-doc
52   "This is T while in the debugger.")
53
54 ;;; nestedness inside debugger command loops
55 (defvar *debug-command-level* 0)
56
57 ;;; If this is bound before the debugger is invoked, it is used as the
58 ;;; stack top by the debugger.
59 (defvar *stack-top-hint* nil)
60
61 (defvar *stack-top* nil)
62 (defvar *real-stack-top* nil)
63
64 (defvar *current-frame* nil)
65
66 ;;; Beginner-oriented help messages are important because you end up
67 ;;; in the debugger whenever something bad happens, or if you try to
68 ;;; get out of the system with Ctrl-C or (EXIT) or EXIT or whatever.
69 ;;; But after memorizing them the wasted screen space gets annoying..
70 (defvar *debug-beginner-help-p* t
71   "Should the debugger display beginner-oriented help messages?")
72
73 (defun debug-prompt (stream)
74   (format stream
75           "~%~W~:[~;[~W~]] "
76           (sb!di:frame-number *current-frame*)
77           (> *debug-command-level* 1)
78           *debug-command-level*))
79   
80 (defparameter *debug-help-string*
81 "The debug prompt is square brackets, with number(s) indicating the current
82   control stack level and, if you've entered the debugger recursively, how
83   deeply recursed you are.
84 Any command -- including the name of a restart -- may be uniquely abbreviated.
85 The debugger rebinds various special variables for controlling i/o, sometimes
86   to defaults (much like WITH-STANDARD-IO-SYNTAX does) and sometimes to 
87   its own special values, e.g. SB-DEBUG:*DEBUG-PRINT-LEVEL*.
88 Debug commands do not affect *, //, and similar variables, but evaluation in
89   the debug loop does affect these variables.
90 SB-DEBUG:*FLUSH-DEBUG-ERRORS* controls whether errors at the debug prompt
91   drop you deeper into the debugger.
92
93 Getting in and out of the debugger:
94   RESTART  invokes restart numbered as shown (prompt if not given).
95   ERROR    prints the error condition and restart cases.
96   The number of any restart, or its name, or a unique abbreviation for its
97     name, is a valid command, and is the same as using RESTART to invoke
98     that restart.
99
100 Changing frames:
101   U      up frame     D    down frame
102   B  bottom frame     F n  frame n (n=0 for top frame)
103
104 Inspecting frames:
105   BACKTRACE [n]  shows n frames going down the stack.
106   LIST-LOCALS, L lists locals in current function.
107   PRINT, P       displays current function call.
108   SOURCE [n]     displays frame's source form with n levels of enclosing forms.
109
110 Breakpoints and steps:
111   LIST-LOCATIONS [{function | :C}]   List the locations for breakpoints.
112                                      Specify :C for the current frame.
113     Abbreviation: LL
114   LIST-BREAKPOINTS                   List the active breakpoints.
115     Abbreviations: LB, LBP
116   DELETE-BREAKPOINT [n]              Remove breakpoint n or all breakpoints.
117     Abbreviations: DEL, DBP
118   BREAKPOINT {n | :end | :start} [:break form] [:function function]
119              [{:print form}*] [:condition form]
120                                      Set a breakpoint.
121     Abbreviations: BR, BP
122   STEP [n]                           Step to the next location or step n times.
123
124 Function and macro commands:
125  (SB-DEBUG:ARG n)
126     Return the n'th argument in the current frame.
127  (SB-DEBUG:VAR string-or-symbol [id])
128     Returns the value of the specified variable in the current frame.
129
130 Other commands:
131   RETURN expr
132     [EXPERIMENTAL] Return the values resulting from evaluation of expr
133     from the current frame, if this frame was compiled with a sufficiently
134     high DEBUG optimization quality.
135   SLURP
136     Discard all pending input on *STANDARD-INPUT*. (This can be
137     useful when the debugger was invoked to handle an error in
138     deeply nested input syntax, and now the reader is confused.)")
139 \f
140 ;;; This is used to communicate to DEBUG-LOOP that we are at a step breakpoint.
141 (define-condition step-condition (simple-condition) ())
142 \f
143 ;;;; breakpoint state
144
145 (defvar *only-block-start-locations* nil
146   #!+sb-doc
147   "When true, the LIST-LOCATIONS command only displays block start locations.
148    Otherwise, all locations are displayed.")
149
150 (defvar *print-location-kind* nil
151   #!+sb-doc
152   "When true, list the code location type in the LIST-LOCATIONS command.")
153
154 ;;; a list of the types of code-locations that should not be stepped
155 ;;; to and should not be listed when listing breakpoints
156 (defvar *bad-code-location-types* '(:call-site :internal-error))
157 (declaim (type list *bad-code-location-types*))
158
159 ;;; code locations of the possible breakpoints
160 (defvar *possible-breakpoints*)
161 (declaim (type list *possible-breakpoints*))
162
163 ;;; a list of the made and active breakpoints, each is a
164 ;;; BREAKPOINT-INFO structure
165 (defvar *breakpoints* nil)
166 (declaim (type list *breakpoints*))
167
168 ;;; a list of BREAKPOINT-INFO structures of the made and active step
169 ;;; breakpoints
170 (defvar *step-breakpoints* nil)
171 (declaim (type list *step-breakpoints*))
172
173 ;;; the number of times left to step
174 (defvar *number-of-steps* 1)
175 (declaim (type integer *number-of-steps*))
176
177 ;;; This is used when listing and setting breakpoints.
178 (defvar *default-breakpoint-debug-fun* nil)
179 (declaim (type (or list sb!di:debug-fun) *default-breakpoint-debug-fun*))
180 \f
181 ;;;; code location utilities
182
183 ;;; Return the first code-location in the passed debug block.
184 (defun first-code-location (debug-block)
185   (let ((found nil)
186         (first-code-location nil))
187     (sb!di:do-debug-block-locations (code-location debug-block)
188       (unless found
189         (setf first-code-location code-location)
190         (setf found t)))
191     first-code-location))
192
193 ;;; Return a list of the next code-locations following the one passed.
194 ;;; One of the *BAD-CODE-LOCATION-TYPES* will not be returned.
195 (defun next-code-locations (code-location)
196   (let ((debug-block (sb!di:code-location-debug-block code-location))
197         (block-code-locations nil))
198     (sb!di:do-debug-block-locations (block-code-location debug-block)
199       (unless (member (sb!di:code-location-kind block-code-location)
200                       *bad-code-location-types*)
201         (push block-code-location block-code-locations)))
202     (setf block-code-locations (nreverse block-code-locations))
203     (let* ((code-loc-list (rest (member code-location block-code-locations
204                                         :test #'sb!di:code-location=)))
205            (next-list (cond (code-loc-list
206                              (list (first code-loc-list)))
207                             ((map 'list #'first-code-location
208                                   (sb!di:debug-block-successors debug-block)))
209                             (t nil))))
210       (when (and (= (length next-list) 1)
211                  (sb!di:code-location= (first next-list) code-location))
212         (setf next-list (next-code-locations (first next-list))))
213       next-list)))
214
215 ;;; Return a list of code-locations of the possible breakpoints of DEBUG-FUN.
216 (defun possible-breakpoints (debug-fun)
217   (let ((possible-breakpoints nil))
218     (sb!di:do-debug-fun-blocks (debug-block debug-fun)
219       (unless (sb!di:debug-block-elsewhere-p debug-block)
220         (if *only-block-start-locations*
221             (push (first-code-location debug-block) possible-breakpoints)
222             (sb!di:do-debug-block-locations (code-location debug-block)
223               (when (not (member (sb!di:code-location-kind code-location)
224                                  *bad-code-location-types*))
225                 (push code-location possible-breakpoints))))))
226     (nreverse possible-breakpoints)))
227
228 ;;; Search the info-list for the item passed (CODE-LOCATION,
229 ;;; DEBUG-FUN, or BREAKPOINT-INFO). If the item passed is a debug
230 ;;; function then kind will be compared if it was specified. The kind
231 ;;; if also compared if a breakpoint-info is passed since it's in the
232 ;;; breakpoint. The info structure is returned if found.
233 (defun location-in-list (place info-list &optional (kind nil))
234   (when (breakpoint-info-p place)
235     (setf kind (sb!di:breakpoint-kind (breakpoint-info-breakpoint place)))
236     (setf place (breakpoint-info-place place)))
237   (cond ((sb!di:code-location-p place)
238          (find place info-list
239                :key #'breakpoint-info-place
240                :test (lambda (x y) (and (sb!di:code-location-p y)
241                                         (sb!di:code-location= x y)))))
242         (t
243          (find place info-list
244                :test (lambda (x-debug-fun y-info)
245                        (let ((y-place (breakpoint-info-place y-info))
246                              (y-breakpoint (breakpoint-info-breakpoint
247                                             y-info)))
248                          (and (sb!di:debug-fun-p y-place)
249                               (eq x-debug-fun y-place)
250                               (or (not kind)
251                                   (eq kind (sb!di:breakpoint-kind
252                                             y-breakpoint))))))))))
253
254 ;;; If LOC is an unknown location, then try to find the block start
255 ;;; location. Used by source printing to some information instead of
256 ;;; none for the user.
257 (defun maybe-block-start-location (loc)
258   (if (sb!di:code-location-unknown-p loc)
259       (let* ((block (sb!di:code-location-debug-block loc))
260              (start (sb!di:do-debug-block-locations (loc block)
261                       (return loc))))
262         (cond ((and (not (sb!di:debug-block-elsewhere-p block))
263                     start)
264                ;; FIXME: Why output on T instead of *DEBUG-FOO* or something?
265                (format t "~%unknown location: using block start~%")
266                start)
267               (t
268                loc)))
269       loc))
270 \f
271 ;;;; the BREAKPOINT-INFO structure
272
273 ;;; info about a made breakpoint
274 (defstruct (breakpoint-info (:copier nil)
275                             (:constructor %make-breakpoint-info))
276   ;; where we are going to stop
277   (place (missing-arg)
278          :type (or sb!di:code-location sb!di:debug-fun)
279          :read-only t)
280   ;; the breakpoint returned by SB!DI:MAKE-BREAKPOINT
281   (breakpoint (missing-arg) :type sb!di:breakpoint :read-only t)
282   ;; the function returned from SB!DI:PREPROCESS-FOR-EVAL. If result is
283   ;; non-NIL, drop into the debugger.
284   (break #'identity :type function :read-only t)
285   ;; the function returned from SB!DI:PREPROCESS-FOR-EVAL. If result is
286   ;; non-NIL, eval (each) print and print results.
287   (condition #'identity :type function :read-only t)
288   ;; the list of functions from SB!DI:PREPROCESS-FOR-EVAL to evaluate.
289   ;; Results are conditionally printed. CAR of each element is the
290   ;; function, CDR is the form it goes with.
291   (print nil :type list :read-only t)
292   ;; the number used when listing the possible breakpoints within a
293   ;; function; or could also be a symbol such as START or END
294   (code-location-selector (missing-arg) :type (or symbol integer) :read-only t)
295   ;; the number used when listing the active breakpoints, and when
296   ;; deleting breakpoints
297   (breakpoint-number (missing-arg) :type integer :read-only t))
298
299 (defun create-breakpoint-info (place breakpoint code-location-selector
300                                      &key (break #'identity)
301                                      (condition #'identity) (print nil))
302   (setf *breakpoints*
303         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
304   (let ((breakpoint-number
305          (do ((i 1 (incf i)) (breakpoints *breakpoints* (rest breakpoints)))
306              ((or (> i (length *breakpoints*))
307                   (not (= i (breakpoint-info-breakpoint-number
308                              (first breakpoints)))))
309
310               i))))
311     (%make-breakpoint-info :place place
312                            :breakpoint breakpoint
313                            :code-location-selector code-location-selector
314                            :breakpoint-number breakpoint-number
315                            :break break
316                            :condition condition
317                            :print print)))
318
319 (defun print-breakpoint-info (breakpoint-info)
320   (let ((place (breakpoint-info-place breakpoint-info))
321         (bp-number (breakpoint-info-breakpoint-number breakpoint-info)))
322     (case (sb!di:breakpoint-kind (breakpoint-info-breakpoint breakpoint-info))
323       (:code-location
324        (print-code-location-source-form place 0)
325        (format t
326                "~&~S: ~S in ~S"
327                bp-number
328                (breakpoint-info-code-location-selector breakpoint-info)
329                (sb!di:debug-fun-name (sb!di:code-location-debug-fun place))))
330       (:fun-start
331        (format t "~&~S: FUN-START in ~S" bp-number
332                (sb!di:debug-fun-name place)))
333       (:fun-end
334        (format t "~&~S: FUN-END in ~S" bp-number
335                (sb!di:debug-fun-name place))))))
336 \f
337 ;;;; MAIN-HOOK-FUN for steps and breakpoints
338
339 ;;; This must be passed as the hook function. It keeps track of where
340 ;;; STEP breakpoints are.
341 (defun main-hook-fun (current-frame breakpoint &optional return-vals
342                                     fun-end-cookie)
343   (setf *default-breakpoint-debug-fun*
344         (sb!di:frame-debug-fun current-frame))
345   (dolist (step-info *step-breakpoints*)
346     (sb!di:delete-breakpoint (breakpoint-info-breakpoint step-info))
347     (let ((bp-info (location-in-list step-info *breakpoints*)))
348       (when bp-info
349         (sb!di:activate-breakpoint (breakpoint-info-breakpoint bp-info)))))
350   (let ((*stack-top-hint* current-frame)
351         (step-hit-info
352          (location-in-list (sb!di:breakpoint-what breakpoint)
353                            *step-breakpoints*
354                            (sb!di:breakpoint-kind breakpoint)))
355         (bp-hit-info
356          (location-in-list (sb!di:breakpoint-what breakpoint)
357                            *breakpoints*
358                            (sb!di:breakpoint-kind breakpoint)))
359         (break)
360         (condition)
361         (string ""))
362     (setf *step-breakpoints* nil)
363     (labels ((build-string (str)
364                (setf string (concatenate 'string string str)))
365              (print-common-info ()
366                (build-string
367                 (with-output-to-string (*standard-output*)
368                   (when fun-end-cookie
369                     (format t "~%Return values: ~S" return-vals))
370                   (when condition
371                     (when (breakpoint-info-print bp-hit-info)
372                       (format t "~%")
373                       (print-frame-call current-frame))
374                     (dolist (print (breakpoint-info-print bp-hit-info))
375                       (format t "~& ~S = ~S" (rest print)
376                               (funcall (first print) current-frame))))))))
377       (when bp-hit-info
378         (setf break (funcall (breakpoint-info-break bp-hit-info)
379                              current-frame))
380         (setf condition (funcall (breakpoint-info-condition bp-hit-info)
381                                  current-frame)))
382       (cond ((and bp-hit-info step-hit-info (= 1 *number-of-steps*))
383              (build-string (format nil "~&*Step (to a breakpoint)*"))
384              (print-common-info)
385              (break string))
386             ((and bp-hit-info step-hit-info break)
387              (build-string (format nil "~&*Step (to a breakpoint)*"))
388              (print-common-info)
389              (break string))
390             ((and bp-hit-info step-hit-info)
391              (print-common-info)
392              (format t "~A" string)
393              (decf *number-of-steps*)
394              (set-step-breakpoint current-frame))
395             ((and step-hit-info (= 1 *number-of-steps*))
396              (build-string "*Step*")
397              (break (make-condition 'step-condition :format-control string)))
398             (step-hit-info
399              (decf *number-of-steps*)
400              (set-step-breakpoint current-frame))
401             (bp-hit-info
402              (when break
403                (build-string (format nil "~&*Breakpoint hit*")))
404              (print-common-info)
405              (if break
406                  (break string)
407                  (format t "~A" string)))
408             (t
409              (break "unknown breakpoint"))))))
410 \f
411 ;;; Set breakpoints at the next possible code-locations. After calling
412 ;;; this, either (CONTINUE) if in the debugger or just let program flow
413 ;;; return if in a hook function.
414 (defun set-step-breakpoint (frame)
415   (cond
416    ((sb!di:debug-block-elsewhere-p (sb!di:code-location-debug-block
417                                     (sb!di:frame-code-location frame)))
418     ;; FIXME: FORMAT T is used for error output here and elsewhere in
419     ;; the debug code.
420     (format t "cannot step, in elsewhere code~%"))
421    (t
422     (let* ((code-location (sb!di:frame-code-location frame))
423            (next-code-locations (next-code-locations code-location)))
424       (cond
425        (next-code-locations
426         (dolist (code-location next-code-locations)
427           (let ((bp-info (location-in-list code-location *breakpoints*)))
428             (when bp-info
429               (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
430                                             bp-info))))
431           (let ((bp (sb!di:make-breakpoint #'main-hook-fun code-location
432                                            :kind :code-location)))
433             (sb!di:activate-breakpoint bp)
434             (push (create-breakpoint-info code-location bp 0)
435                   *step-breakpoints*))))
436        (t
437         (let* ((debug-fun (sb!di:frame-debug-fun *current-frame*))
438                (bp (sb!di:make-breakpoint #'main-hook-fun debug-fun
439                                           :kind :fun-end)))
440           (sb!di:activate-breakpoint bp)
441           (push (create-breakpoint-info debug-fun bp 0)
442                 *step-breakpoints*))))))))
443 \f
444 ;;;; STEP
445
446 ;;; ANSI specifies that this macro shall exist, even if only as a
447 ;;; trivial placeholder like this.
448 (defmacro step (form)
449   "a trivial placeholder implementation of the CL:STEP macro required by
450    the ANSI spec"
451   `(progn
452      ,form))
453 \f
454 ;;;; BACKTRACE
455
456 (defun backtrace (&optional (count most-positive-fixnum)
457                             (*standard-output* *debug-io*))
458   #!+sb-doc
459   "Show a listing of the call stack going down from the current frame. In the
460    debugger, the current frame is indicated by the prompt. COUNT is how many
461    frames to show."
462   (fresh-line *standard-output*)
463   (do ((frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
464               (sb!di:frame-down frame))
465        (count count (1- count)))
466       ((or (null frame) (zerop count)))
467     (print-frame-call frame :number t))
468   (fresh-line *standard-output*)
469   (values))
470
471 (defun backtrace-as-list (&optional (count most-positive-fixnum))
472   #!+sb-doc "Return a list representing the current BACKTRACE."
473   (do ((reversed-result nil)
474        (frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
475               (sb!di:frame-down frame))
476        (count count (1- count)))
477       ((or (null frame) (zerop count))
478        (nreverse reversed-result))
479     (push (frame-call-as-list frame) reversed-result)))
480
481 (defun frame-call-as-list (frame)
482   (cons (sb!di:debug-fun-name (sb!di:frame-debug-fun frame))
483         (frame-args-as-list frame)))
484 \f
485 ;;;; frame printing
486
487 (eval-when (:compile-toplevel :execute)
488
489 ;;; This is a convenient way to express what to do for each type of
490 ;;; lambda-list element.
491 (sb!xc:defmacro lambda-list-element-dispatch (element
492                                               &key
493                                               required
494                                               optional
495                                               rest
496                                               keyword
497                                               deleted)
498   `(etypecase ,element
499      (sb!di:debug-var
500       ,@required)
501      (cons
502       (ecase (car ,element)
503         (:optional ,@optional)
504         (:rest ,@rest)
505         (:keyword ,@keyword)))
506      (symbol
507       (aver (eq ,element :deleted))
508       ,@deleted)))
509
510 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
511   (let ((var (gensym)))
512     `(let ((,var ,variable))
513        (cond ((eq ,var :deleted) ,deleted)
514              ((eq (sb!di:debug-var-validity ,var ,location) :valid)
515               ,valid)
516              (t ,other)))))
517
518 ) ; EVAL-WHEN
519
520 ;;; This is used in constructing arg lists for debugger printing when
521 ;;; the arg list is unavailable, some arg is unavailable or unused, etc.
522 (defstruct (unprintable-object
523             (:constructor make-unprintable-object (string))
524             (:print-object (lambda (x s)
525                              (print-unreadable-object (x s)
526                                (write-string (unprintable-object-string x)
527                                              s))))
528             (:copier nil))
529   string)
530
531 ;;; Extract the function argument values for a debug frame.
532 (defun frame-args-as-list (frame)
533   (let ((debug-fun (sb!di:frame-debug-fun frame))
534         (loc (sb!di:frame-code-location frame))
535         (reversed-result nil))
536     (handler-case
537         (progn
538           (dolist (ele (sb!di:debug-fun-lambda-list debug-fun))
539             (lambda-list-element-dispatch ele
540              :required ((push (frame-call-arg ele loc frame) reversed-result))
541              :optional ((push (frame-call-arg (second ele) loc frame)
542                               reversed-result))
543              :keyword ((push (second ele) reversed-result)
544                        (push (frame-call-arg (third ele) loc frame)
545                              reversed-result))
546              :deleted ((push (frame-call-arg ele loc frame) reversed-result))
547              :rest ((lambda-var-dispatch (second ele) loc
548                      nil
549                      (progn
550                        (setf reversed-result
551                              (append (reverse (sb!di:debug-var-value
552                                                (second ele) frame))
553                                      reversed-result))
554                        (return))
555                      (push (make-unprintable-object
556                             "unavailable &REST argument")
557                      reversed-result)))))
558           ;; As long as we do an ordinary return (as opposed to SIGNALing
559           ;; a CONDITION) from the DOLIST above:
560           (nreverse reversed-result))
561       (sb!di:lambda-list-unavailable
562        ()
563        (make-unprintable-object "unavailable lambda list")))))
564
565 ;;; Print FRAME with verbosity level 1. If we hit a &REST arg, then
566 ;;; print as many of the values as possible, punting the loop over
567 ;;; lambda-list variables since any other arguments will be in the
568 ;;; &REST arg's list of values.
569 (defun print-frame-call-1 (frame)
570   (let ((debug-fun (sb!di:frame-debug-fun frame)))
571
572     (pprint-logical-block (*standard-output* nil :prefix "(" :suffix ")")
573       (let ((args (ensure-printable-object (frame-args-as-list frame))))
574         ;; Since we go to some trouble to make nice informative function
575         ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
576         ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
577         (let ((*print-length* nil)
578               (*print-level* nil))
579           (prin1 (ensure-printable-object (sb!di:debug-fun-name debug-fun))))
580         ;; For the function arguments, we can just print normally.
581         (if (listp args)
582             (format t "~{ ~_~S~}" args)
583             (format t " ~S" args))))
584
585     (when (sb!di:debug-fun-kind debug-fun)
586       (write-char #\[)
587       (prin1 (sb!di:debug-fun-kind debug-fun))
588       (write-char #\]))))
589
590 (defun ensure-printable-object (object)
591   (handler-case
592       (with-open-stream (out (make-broadcast-stream))
593         (prin1 object out)
594         object)
595     (error (cond)
596       (declare (ignore cond))
597       (make-unprintable-object "error printing object"))))
598
599 (defun frame-call-arg (var location frame)
600   (lambda-var-dispatch var location
601     (make-unprintable-object "unused argument")
602     (sb!di:debug-var-value var frame)
603     (make-unprintable-object "unavailable argument")))
604
605 ;;; Prints a representation of the function call causing FRAME to
606 ;;; exist. VERBOSITY indicates the level of information to output;
607 ;;; zero indicates just printing the DEBUG-FUN's name, and one
608 ;;; indicates displaying call-like, one-liner format with argument
609 ;;; values.
610 (defun print-frame-call (frame &key (verbosity 1) (number nil))
611   (cond
612    ((zerop verbosity)
613     (when number
614       (format t "~&~S: " (sb!di:frame-number frame)))
615     (format t "~S" frame))
616    (t
617     (when number
618       (format t "~&~S: " (sb!di:frame-number frame)))
619     (print-frame-call-1 frame)))
620   (when (>= verbosity 2)
621     (let ((loc (sb!di:frame-code-location frame)))
622       (handler-case
623           (progn
624             (sb!di:code-location-debug-block loc)
625             (format t "~%source: ")
626             (print-code-location-source-form loc 0))
627         (sb!di:debug-condition (ignore) ignore)
628         (error (c) (format t "error finding source: ~A" c))))))
629 \f
630 ;;;; INVOKE-DEBUGGER
631
632 (defvar *debugger-hook* nil
633   #!+sb-doc
634   "This is either NIL or a function of two arguments, a condition and the value
635    of *DEBUGGER-HOOK*. This function can either handle the condition or return
636    which causes the standard debugger to execute. The system passes the value
637    of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
638    around the invocation.")
639
640 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
641 (defvar *debug-restarts*)
642 (defvar *debug-condition*)
643 (defvar *nested-debug-condition*)
644
645 (defun invoke-debugger (condition)
646   #!+sb-doc
647   "Enter the debugger."
648   (let ((old-hook *debugger-hook*))
649     (when old-hook
650       (let ((*debugger-hook* nil))
651         (funcall old-hook condition old-hook))))
652
653   ;; Note: CMU CL had (SB-UNIX:UNIX-SIGSETMASK 0) here. I deleted it
654   ;; around sbcl-0.7.8.5 (by which time it had mutated to have a
655   ;; #!-SUNOS prefix and a FIXME note observing that it wasn't needed
656   ;; on SunOS and no one knew why it was needed anywhere else either).
657   ;; So if something mysteriously breaks that has worked since the CMU
658   ;; CL days, that might be why. -- WHN 2002-09-28
659
660   ;; We definitely want *PACKAGE* to be of valid type.
661   ;;
662   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
663   ;; this, but here causing an exception just as we're trying to handle
664   ;; an exception would be confusing, so instead we use a special hack.
665   (unless (and (packagep *package*)
666                (package-name *package*))
667     (setf *package* (find-package :cl-user))
668     (format *error-output*
669             "The value of ~S was not an undeleted PACKAGE. It has been
670 reset to ~S."
671             '*package* *package*))
672
673   ;; Try to force the other special variables into a useful state.
674   (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
675         ;; any default we might use is less useful than just reusing
676         ;; the global values.
677         (original-package *package*)
678         (original-print-pretty *print-pretty*))
679     (with-standard-io-syntax
680      (let ((*debug-condition* condition)
681            (*debug-restarts* (compute-restarts condition))
682            (*nested-debug-condition* nil)
683            ;; We want the printer and reader to be in a useful state,
684            ;; regardless of where the debugger was invoked in the
685            ;; program. WITH-STANDARD-IO-SYNTAX did much of what we
686            ;; want, but
687            ;;   * It doesn't affect our internal special variables 
688            ;;     like *CURRENT-LEVEL-IN-PRINT*.
689            ;;   * It isn't customizable.
690            ;;   * It doesn't set *PRINT-READABLY* to the same value
691            ;;     as the toplevel default.
692            ;;   * It sets *PACKAGE* to COMMON-LISP-USER, which is not
693            ;;     helpful behavior for a debugger.
694            ;;   * There's no particularly good debugger default for
695            ;;     *PRINT-PRETTY*, since T is usually what you want
696            ;;     -- except absolutely not what you want when you're
697            ;;     debugging failures in PRINT-OBJECT logic.
698            ;; We try to address all these issues with explicit
699            ;; rebindings here.
700            (sb!kernel:*current-level-in-print* 0)
701            (*print-length* *debug-print-length*)
702            (*print-level* *debug-print-level*)
703            (*readtable* *debug-readtable*)
704            (*print-readably* nil)
705            (*package* original-package)
706            (*print-pretty* original-print-pretty))
707
708        ;; Before we start our own output, finish any pending output.
709        ;; Otherwise, if the user tried to track the progress of his
710        ;; program using PRINT statements, he'd tend to lose the last
711        ;; line of output or so, which'd be confusing.
712        (flush-standard-output-streams)
713
714        ;; (The initial output here goes to *ERROR-OUTPUT*, because the
715        ;; initial output is not interactive, just an error message,
716        ;; and when people redirect *ERROR-OUTPUT*, they could
717        ;; reasonably expect to see error messages logged there,
718        ;; regardless of what the debugger does afterwards.)
719        (handler-case
720            (format *error-output*
721                    "~2&~@<debugger invoked on condition of type ~S: ~
722                     ~2I~_~A~:>~%"
723                    (type-of *debug-condition*)
724                    *debug-condition*)
725          (error (condition)
726            (setf *nested-debug-condition* condition)
727            (let ((ndc-type (type-of *nested-debug-condition*)))
728              (format *error-output*
729                      "~&~@<(A ~S was caught when trying to print ~S when ~
730                       entering the debugger. Printing was aborted and the ~
731                       ~S was stored in ~S.)~@:>~%"
732                      ndc-type
733                      '*debug-condition*
734                      ndc-type
735                      '*nested-debug-condition*))
736            (when (typep condition 'cell-error)
737              ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
738              (format *error-output*
739                      "~&(CELL-ERROR-NAME ~S) = ~S~%"
740                      '*debug-condition*
741                      (cell-error-name *debug-condition*)))))
742
743        ;; After the initial error/condition/whatever announcement to
744        ;; *ERROR-OUTPUT*, we become interactive, and should talk on
745        ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
746        ;; statement, not a description of reality.:-| There's a lot of
747        ;; older debugger code which was written to do i/o on whatever
748        ;; stream was in fashion at the time, and not all of it has
749        ;; been converted to behave this way. -- WHN 2000-11-16)
750        (let (;; FIXME: Rebinding *STANDARD-OUTPUT* here seems wrong,
751              ;; violating the principle of least surprise, and making
752              ;; it impossible for the user to do reasonable things
753              ;; like using PRINT at the debugger prompt to send output
754              ;; to the program's ordinary (possibly
755              ;; redirected-to-a-file) *STANDARD-OUTPUT*. (CMU CL
756              ;; used to rebind *STANDARD-INPUT* here too, but that's
757              ;; been fixed already.)
758              (*standard-output* *debug-io*)
759              ;; This seems reasonable: e.g. if the user has redirected
760              ;; *ERROR-OUTPUT* to some log file, it's probably wrong
761              ;; to send errors which occur in interactive debugging to
762              ;; that file, and right to send them to *DEBUG-IO*.
763              (*error-output* *debug-io*))
764          (unless (typep condition 'step-condition)
765            (when *debug-beginner-help-p*
766              (format *debug-io*
767                      "~%~@<Within the debugger, you can type HELP for help. ~
768                       At any command prompt (within the debugger or not) you ~
769                       can type (SB-EXT:QUIT) to terminate the SBCL ~
770                       executable. The condition which caused the debugger to ~
771                       be entered is bound to ~S. You can suppress this ~
772                       message by clearing ~S.~:@>~2%"
773                      '*debug-condition*
774                      '*debug-beginner-help-p*))
775            (show-restarts *debug-restarts* *debug-io*))
776          (internal-debug))))))
777
778 (defun show-restarts (restarts s)
779   (cond ((null restarts)
780          (format s
781                  "~&(no restarts: If you didn't do this on purpose, ~
782                   please report it as a bug.)~%"))
783         (t
784          (format s "~&restarts:~%")
785          (let ((count 0)
786                (names-used '(nil))
787                (max-name-len 0))
788            (dolist (restart restarts)
789              (let ((name (restart-name restart)))
790                (when name
791                  (let ((len (length (princ-to-string name))))
792                    (when (> len max-name-len)
793                      (setf max-name-len len))))))
794            (unless (zerop max-name-len)
795              (incf max-name-len 3))
796            (dolist (restart restarts)
797              (let ((name (restart-name restart)))
798                (cond ((member name names-used)
799                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
800                      (t
801                       (format s "~& ~2D: [~VA] ~A~%"
802                               count (- max-name-len 3) name restart)
803                       (push name names-used))))
804              (incf count))))))
805
806 ;;; This calls DEBUG-LOOP, performing some simple initializations
807 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
808 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
809 ;;; to get into a debug prompt as quickly as possible with as little
810 ;;; risk as possible for stepping on whatever is causing recursive
811 ;;; errors.
812 (defun internal-debug ()
813   (let ((*in-the-debugger* t)
814         (*read-suppress* nil))
815     (unless (typep *debug-condition* 'step-condition)
816       (clear-input *debug-io*))
817     (debug-loop)))
818 \f
819 ;;;; DEBUG-LOOP
820
821 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
822 ;;; was motivated by desire to play nicely with ILISP.
823 (defvar *flush-debug-errors* nil
824   #!+sb-doc
825   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
826    executing in the debugger.")
827
828 (defun debug-loop ()
829   (let* ((*debug-command-level* (1+ *debug-command-level*))
830          (*real-stack-top* (sb!di:top-frame))
831          (*stack-top* (or *stack-top-hint* *real-stack-top*))
832          (*stack-top-hint* nil)
833          (*current-frame* *stack-top*))
834     (handler-bind ((sb!di:debug-condition
835                     (lambda (condition)
836                       (princ condition *debug-io*)
837                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
838                       (throw 'debug-loop-catcher nil))))
839       (fresh-line)
840       (print-frame-call *current-frame* :verbosity 2)
841       (loop
842         (catch 'debug-loop-catcher
843           (handler-bind ((error (lambda (condition)
844                                   (when *flush-debug-errors*
845                                     (clear-input *debug-io*)
846                                     (princ condition)
847                                     ;; FIXME: Doing input on *DEBUG-IO*
848                                     ;; and output on T seems broken.
849                                     (format t
850                                             "~&error flushed (because ~
851                                              ~S is set)"
852                                             '*flush-debug-errors*)
853                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
854                                     (throw 'debug-loop-catcher nil)))))
855             ;; We have to bind LEVEL for the restart function created by
856             ;; WITH-SIMPLE-RESTART.
857             (let ((level *debug-command-level*)
858                   (restart-commands (make-restart-commands)))
859               (with-simple-restart (abort
860                                    "~@<Reduce debugger level (to debug level ~W).~@:>"
861                                     level)
862                 (debug-prompt *debug-io*)
863                 (force-output *debug-io*)
864                 (let ((input (sb!int:get-stream-command *debug-io*)))
865                   (cond (input
866                          (let ((cmd-fun (debug-command-p
867                                          (sb!int:stream-command-name input)
868                                          restart-commands)))
869                            (cond
870                             ((not cmd-fun)
871                              (error "unknown stream-command: ~S" input))
872                             ((consp cmd-fun)
873                              (error "ambiguous debugger command: ~S" cmd-fun))
874                             (t
875                              (apply cmd-fun
876                                     (sb!int:stream-command-args input))))))
877                         (t
878                          (let* ((exp (read *debug-io*))
879                                 (cmd-fun (debug-command-p exp
880                                                           restart-commands)))
881                            (cond ((not cmd-fun)
882                                   (debug-eval-print exp))
883                                  ((consp cmd-fun)
884                                   (format t
885                                           "~&Your command, ~S, is ambiguous:~%"
886                                           exp)
887                                   (dolist (ele cmd-fun)
888                                     (format t "   ~A~%" ele)))
889                                  (t
890                                   (funcall cmd-fun)))))))))))))))
891
892 ;;; FIXME: We could probably use INTERACTIVE-EVAL for much of this logic.
893 (defun debug-eval-print (expr)
894   (/noshow "entering DEBUG-EVAL-PRINT" expr)
895   (/noshow (fboundp 'compile))
896   (setq +++ ++ ++ + + - - expr)
897   (let* ((values (multiple-value-list (eval -)))
898          (*standard-output* *debug-io*))
899     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
900     (fresh-line)
901     (if values (prin1 (car values)))
902     (dolist (x (cdr values))
903       (fresh-line)
904       (prin1 x))
905     (setq /// // // / / values)
906     (setq *** ** ** * * (car values))
907     ;; Make sure that nobody passes back an unbound marker.
908     (unless (boundp '*)
909       (setq * nil)
910       (fresh-line)
911       ;; FIXME: The way INTERACTIVE-EVAL does this seems better.
912       (princ "Setting * to NIL (was unbound marker)."))))
913 \f
914 ;;;; debug loop functions
915
916 ;;; These commands are functions, not really commands, so that users
917 ;;; can get their hands on the values returned.
918
919 (eval-when (:execute :compile-toplevel)
920
921 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
922   `(let* ((temp (etypecase name
923                   (symbol (sb!di:debug-fun-symbol-vars
924                            (sb!di:frame-debug-fun *current-frame*)
925                            name))
926                   (simple-string (sb!di:ambiguous-debug-vars
927                                   (sb!di:frame-debug-fun *current-frame*)
928                                   name))))
929           (location (sb!di:frame-code-location *current-frame*))
930           ;; Let's only deal with valid variables.
931           (vars (remove-if-not (lambda (v)
932                                  (eq (sb!di:debug-var-validity v location)
933                                      :valid))
934                                temp)))
935      (declare (list vars))
936      (cond ((null vars)
937             (error "No known valid variables match ~S." name))
938            ((= (length vars) 1)
939             ,(ecase ref-or-set
940                (:ref
941                 '(sb!di:debug-var-value (car vars) *current-frame*))
942                (:set
943                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
944                        ,value-var))))
945            (t
946             ;; Since we have more than one, first see whether we have
947             ;; any variables that exactly match the specification.
948             (let* ((name (etypecase name
949                            (symbol (symbol-name name))
950                            (simple-string name)))
951                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
952                    ;; instead.
953                    (exact (remove-if-not (lambda (v)
954                                            (string= (sb!di:debug-var-symbol-name v)
955                                                     name))
956                                          vars))
957                    (vars (or exact vars)))
958               (declare (simple-string name)
959                        (list exact vars))
960               (cond
961                ;; Check now for only having one variable.
962                ((= (length vars) 1)
963                 ,(ecase ref-or-set
964                    (:ref
965                     '(sb!di:debug-var-value (car vars) *current-frame*))
966                    (:set
967                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
968                            ,value-var))))
969                ;; If there weren't any exact matches, flame about
970                ;; ambiguity unless all the variables have the same
971                ;; name.
972                ((and (not exact)
973                      (find-if-not
974                       (lambda (v)
975                         (string= (sb!di:debug-var-symbol-name v)
976                                  (sb!di:debug-var-symbol-name (car vars))))
977                       (cdr vars)))
978                 (error "specification ambiguous:~%~{   ~A~%~}"
979                        (mapcar #'sb!di:debug-var-symbol-name
980                                (delete-duplicates
981                                 vars :test #'string=
982                                 :key #'sb!di:debug-var-symbol-name))))
983                ;; All names are the same, so see whether the user
984                ;; ID'ed one of them.
985                (id-supplied
986                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
987                   (unless v
988                     (error
989                      "invalid variable ID, ~W: should have been one of ~S"
990                      id
991                      (mapcar #'sb!di:debug-var-id vars)))
992                   ,(ecase ref-or-set
993                      (:ref
994                       '(sb!di:debug-var-value v *current-frame*))
995                      (:set
996                       `(setf (sb!di:debug-var-value v *current-frame*)
997                              ,value-var)))))
998                (t
999                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
1000                        name
1001                        (mapcar #'sb!di:debug-var-id vars)))))))))
1002
1003 ) ; EVAL-WHEN
1004
1005 ;;; FIXME: This doesn't work. It would be real nice we could make it
1006 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
1007 (defun var (name &optional (id 0 id-supplied))
1008   #!+sb-doc
1009   "Return a variable's value if possible. NAME is a simple-string or symbol.
1010    If it is a simple-string, it is an initial substring of the variable's name.
1011    If name is a symbol, it has the same name and package as the variable whose
1012    value this function returns. If the symbol is uninterned, then the variable
1013    has the same name as the symbol, but it has no package.
1014
1015    If name is the initial substring of variables with different names, then
1016    this return no values after displaying the ambiguous names. If name
1017    determines multiple variables with the same name, then you must use the
1018    optional id argument to specify which one you want. If you left id
1019    unspecified, then this returns no values after displaying the distinguishing
1020    id values.
1021
1022    The result of this function is limited to the availability of variable
1023    information. This is SETF'able."
1024   (define-var-operation :ref))
1025 (defun (setf var) (value name &optional (id 0 id-supplied))
1026   (define-var-operation :set value))
1027
1028 ;;; This returns the COUNT'th arg as the user sees it from args, the
1029 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
1030 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
1031 ;;; T. If this returns a keyword symbol or a value from a rest arg,
1032 ;;; then the second value is NIL.
1033 ;;;
1034 ;;; FIXME: There's probably some way to merge the code here with
1035 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1036 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1037 (declaim (ftype (function (index list)) nth-arg))
1038 (defun nth-arg (count args)
1039   (let ((n count))
1040     (dolist (ele args (error "The argument specification ~S is out of range."
1041                              n))
1042       (lambda-list-element-dispatch ele
1043         :required ((if (zerop n) (return (values ele t))))
1044         :optional ((if (zerop n) (return (values (second ele) t))))
1045         :keyword ((cond ((zerop n)
1046                          (return (values (second ele) nil)))
1047                         ((zerop (decf n))
1048                          (return (values (third ele) t)))))
1049         :deleted ((if (zerop n) (return (values ele t))))
1050         :rest ((let ((var (second ele)))
1051                  (lambda-var-dispatch var (sb!di:frame-code-location
1052                                            *current-frame*)
1053                    (error "unused &REST argument before n'th argument")
1054                    (dolist (value
1055                             (sb!di:debug-var-value var *current-frame*)
1056                             (error
1057                              "The argument specification ~S is out of range."
1058                              n))
1059                      (if (zerop n)
1060                          (return-from nth-arg (values value nil))
1061                          (decf n)))
1062                    (error "invalid &REST argument before n'th argument")))))
1063       (decf n))))
1064
1065 (defun arg (n)
1066   #!+sb-doc
1067   "Return the N'th argument's value if possible. Argument zero is the first
1068    argument in a frame's default printed representation. Count keyword/value
1069    pairs as separate arguments."
1070   (multiple-value-bind (var lambda-var-p)
1071       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1072                                 (sb!di:frame-debug-fun *current-frame*))
1073                    (sb!di:lambda-list-unavailable ()
1074                      (error "No argument values are available."))))
1075     (if lambda-var-p
1076         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1077           (error "Unused arguments have no values.")
1078           (sb!di:debug-var-value var *current-frame*)
1079           (error "invalid argument value"))
1080         var)))
1081 \f
1082 ;;;; machinery for definition of debug loop commands
1083
1084 (defvar *debug-commands* nil)
1085
1086 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1087 ;;; permitted.
1088 (defmacro !def-debug-command (name args &rest body)
1089   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1090     `(progn
1091        (setf *debug-commands*
1092              (remove ,name *debug-commands* :key #'car :test #'string=))
1093        (defun ,fun-name ,args
1094          (unless *in-the-debugger*
1095            (error "invoking debugger command while outside the debugger"))
1096          ,@body)
1097        (push (cons ,name #',fun-name) *debug-commands*)
1098        ',fun-name)))
1099
1100 (defun !def-debug-command-alias (new-name existing-name)
1101   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1102     (unless pair (error "unknown debug command name: ~S" existing-name))
1103     (push (cons new-name (cdr pair)) *debug-commands*))
1104   new-name)
1105
1106 ;;; This takes a symbol and uses its name to find a debugger command,
1107 ;;; using initial substring matching. It returns the command function
1108 ;;; if form identifies only one command, but if form is ambiguous,
1109 ;;; this returns a list of the command names. If there are no matches,
1110 ;;; this returns nil. Whenever the loop that looks for a set of
1111 ;;; possibilities encounters an exact name match, we return that
1112 ;;; command function immediately.
1113 (defun debug-command-p (form &optional other-commands)
1114   (if (or (symbolp form) (integerp form))
1115       (let* ((name
1116               (if (symbolp form)
1117                   (symbol-name form)
1118                   (format nil "~W" form)))
1119              (len (length name))
1120              (res nil))
1121         (declare (simple-string name)
1122                  (fixnum len)
1123                  (list res))
1124
1125         ;; Find matching commands, punting if exact match.
1126         (flet ((match-command (ele)
1127                  (let* ((str (car ele))
1128                         (str-len (length str)))
1129                    (declare (simple-string str)
1130                             (fixnum str-len))
1131                    (cond ((< str-len len))
1132                          ((= str-len len)
1133                           (when (string= name str :end1 len :end2 len)
1134                             (return-from debug-command-p (cdr ele))))
1135                          ((string= name str :end1 len :end2 len)
1136                           (push ele res))))))
1137           (mapc #'match-command *debug-commands*)
1138           (mapc #'match-command other-commands))
1139
1140         ;; Return the right value.
1141         (cond ((not res) nil)
1142               ((= (length res) 1)
1143                (cdar res))
1144               (t ; Just return the names.
1145                (do ((cmds res (cdr cmds)))
1146                    ((not cmds) res)
1147                  (setf (car cmds) (caar cmds))))))))
1148
1149 ;;; Return a list of debug commands (in the same format as
1150 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1151 ;;;
1152 ;;; Two commands are made for each restart: one for the number, and
1153 ;;; one for the restart name (unless it's been shadowed by an earlier
1154 ;;; restart of the same name, or it is NIL).
1155 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1156   (let ((commands)
1157         (num 0))                        ; better be the same as show-restarts!
1158     (dolist (restart restarts)
1159       (let ((name (string (restart-name restart))))
1160         (let ((restart-fun
1161                 (lambda ()
1162                   (/show0 "in restart-command closure, about to i-r-i")
1163                   (invoke-restart-interactively restart))))
1164           (push (cons (prin1-to-string num) restart-fun) commands)
1165           (unless (or (null (restart-name restart)) 
1166                       (find name commands :key #'car :test #'string=))
1167             (push (cons name restart-fun) commands))))
1168     (incf num))
1169   commands))
1170 \f
1171 ;;;; frame-changing commands
1172
1173 (!def-debug-command "UP" ()
1174   (let ((next (sb!di:frame-up *current-frame*)))
1175     (cond (next
1176            (setf *current-frame* next)
1177            (print-frame-call next))
1178           (t
1179            (format t "~&Top of stack.")))))
1180
1181 (!def-debug-command "DOWN" ()
1182   (let ((next (sb!di:frame-down *current-frame*)))
1183     (cond (next
1184            (setf *current-frame* next)
1185            (print-frame-call next))
1186           (t
1187            (format t "~&Bottom of stack.")))))
1188
1189 (!def-debug-command-alias "D" "DOWN")
1190
1191 ;;; CMU CL had this command, but SBCL doesn't, since it's redundant
1192 ;;; with "FRAME 0", and it interferes with abbreviations for the
1193 ;;; TOPLEVEL restart.
1194 ;;;(!def-debug-command "TOP" ()
1195 ;;;  (do ((prev *current-frame* lead)
1196 ;;;       (lead (sb!di:frame-up *current-frame*) (sb!di:frame-up lead)))
1197 ;;;      ((null lead)
1198 ;;;       (setf *current-frame* prev)
1199 ;;;       (print-frame-call prev))))
1200
1201 (!def-debug-command "BOTTOM" ()
1202   (do ((prev *current-frame* lead)
1203        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1204       ((null lead)
1205        (setf *current-frame* prev)
1206        (print-frame-call prev))))
1207
1208 (!def-debug-command-alias "B" "BOTTOM")
1209
1210 (!def-debug-command "FRAME" (&optional
1211                              (n (read-prompting-maybe "frame number: ")))
1212   (setf *current-frame*
1213         (multiple-value-bind (next-frame-fun limit-string)
1214             (if (< n (sb!di:frame-number *current-frame*))
1215                 (values #'sb!di:frame-up "top")
1216               (values #'sb!di:frame-down "bottom"))
1217           (do ((frame *current-frame*))
1218               ((= n (sb!di:frame-number frame))
1219                frame)
1220             (let ((next-frame (funcall next-frame-fun frame)))
1221               (cond (next-frame
1222                      (setf frame next-frame))
1223                     (t
1224                      (format t
1225                              "The ~A of the stack was encountered.~%"
1226                              limit-string)
1227                      (return frame)))))))
1228   (print-frame-call *current-frame*))
1229
1230 (!def-debug-command-alias "F" "FRAME")
1231 \f
1232 ;;;; commands for entering and leaving the debugger
1233
1234 ;;; CMU CL supported this QUIT debug command, but SBCL provides this
1235 ;;; functionality with a restart instead. (The QUIT debug command was
1236 ;;; removed because it's confusing to have "quit" mean two different
1237 ;;; things in the system, "restart the top level REPL" in the debugger
1238 ;;; and "terminate the Lisp system" as the SB-EXT:QUIT function.)
1239 ;;;
1240 ;;;(!def-debug-command "QUIT" ()
1241 ;;;  (throw 'sb!impl::toplevel-catcher nil))
1242
1243 ;;; CMU CL supported this GO debug command, but SBCL doesn't -- in
1244 ;;; SBCL you just type the CONTINUE restart name instead (or "C" or
1245 ;;; "RESTART CONTINUE", that's OK too).
1246 ;;;(!def-debug-command "GO" ()
1247 ;;;  (continue *debug-condition*)
1248 ;;;  (error "There is no restart named CONTINUE."))
1249
1250 (!def-debug-command "RESTART" ()
1251   (/show0 "doing RESTART debug-command")
1252   (let ((num (read-if-available :prompt)))
1253     (when (eq num :prompt)
1254       (show-restarts *debug-restarts* *debug-io*)
1255       (write-string "restart: ")
1256       (force-output)
1257       (setf num (read *debug-io*)))
1258     (let ((restart (typecase num
1259                      (unsigned-byte
1260                       (nth num *debug-restarts*))
1261                      (symbol
1262                       (find num *debug-restarts* :key #'restart-name
1263                             :test (lambda (sym1 sym2)
1264                                     (string= (symbol-name sym1)
1265                                              (symbol-name sym2)))))
1266                      (t
1267                       (format t "~S is invalid as a restart name.~%" num)
1268                       (return-from restart-debug-command nil)))))
1269       (/show0 "got RESTART")
1270       (if restart
1271           (invoke-restart-interactively restart)
1272           ;; FIXME: Even if this isn't handled by WARN, it probably
1273           ;; shouldn't go to *STANDARD-OUTPUT*, but *ERROR-OUTPUT* or
1274           ;; *QUERY-IO* or something. Look through this file to
1275           ;; straighten out stream usage.
1276           (princ "There is no such restart.")))))
1277 \f
1278 ;;;; information commands
1279
1280 (!def-debug-command "HELP" ()
1281   ;; CMU CL had a little toy pager here, but "if you aren't running
1282   ;; ILISP (or a smart windowing system, or something) you deserve to
1283   ;; lose", so we've dropped it in SBCL. However, in case some
1284   ;; desperate holdout is running this on a dumb terminal somewhere,
1285   ;; we tell him where to find the message stored as a string.
1286   (format *debug-io*
1287           "~&~A~2%(The HELP string is stored in ~S.)~%"
1288           *debug-help-string*
1289           '*debug-help-string*))
1290
1291 (!def-debug-command-alias "?" "HELP")
1292
1293 (!def-debug-command "ERROR" ()
1294   (format *debug-io* "~A~%" *debug-condition*)
1295   (show-restarts *debug-restarts* *debug-io*))
1296
1297 (!def-debug-command "BACKTRACE" ()
1298   (backtrace (read-if-available most-positive-fixnum)))
1299
1300 (!def-debug-command "PRINT" ()
1301   (print-frame-call *current-frame*))
1302
1303 (!def-debug-command-alias "P" "PRINT")
1304
1305 (!def-debug-command "LIST-LOCALS" ()
1306   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1307     (if (sb!di:debug-var-info-available d-fun)
1308         (let ((*standard-output* *debug-io*)
1309               (location (sb!di:frame-code-location *current-frame*))
1310               (prefix (read-if-available nil))
1311               (any-p nil)
1312               (any-valid-p nil))
1313           (dolist (v (sb!di:ambiguous-debug-vars
1314                         d-fun
1315                         (if prefix (string prefix) "")))
1316             (setf any-p t)
1317             (when (eq (sb!di:debug-var-validity v location) :valid)
1318               (setf any-valid-p t)
1319               (format t "~S~:[#~W~;~*~]  =  ~S~%"
1320                       (sb!di:debug-var-symbol v)
1321                       (zerop (sb!di:debug-var-id v))
1322                       (sb!di:debug-var-id v)
1323                       (sb!di:debug-var-value v *current-frame*))))
1324
1325           (cond
1326            ((not any-p)
1327             (format t "There are no local variables ~@[starting with ~A ~]~
1328                        in the function."
1329                     prefix))
1330            ((not any-valid-p)
1331             (format t "All variables ~@[starting with ~A ~]currently ~
1332                        have invalid values."
1333                     prefix))))
1334         (write-line "There is no variable information available."))))
1335
1336 (!def-debug-command-alias "L" "LIST-LOCALS")
1337
1338 (!def-debug-command "SOURCE" ()
1339   (fresh-line)
1340   (print-code-location-source-form (sb!di:frame-code-location *current-frame*)
1341                                    (read-if-available 0)))
1342 \f
1343 ;;;; source location printing
1344
1345 ;;; We cache a stream to the last valid file debug source so that we
1346 ;;; won't have to repeatedly open the file.
1347 ;;;
1348 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1349 ;;; in the 1990s, so the benefit is negligible, less important than the
1350 ;;; potential of extra confusion if someone changes the source during
1351 ;;; a debug session and the change doesn't show up. And removing this
1352 ;;; would simplify the system, which I like. -- WHN 19990903
1353 (defvar *cached-debug-source* nil)
1354 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1355 (defvar *cached-source-stream* nil)
1356 (declaim (type (or stream null) *cached-source-stream*))
1357
1358 ;;; To suppress the read-time evaluation #. macro during source read,
1359 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1360 ;;; copying it each time, and invalidated when the
1361 ;;; *CACHED-DEBUG-SOURCE* has changed.
1362 (defvar *cached-readtable* nil)
1363 (declaim (type (or readtable null) *cached-readtable*))
1364
1365 (pushnew (lambda ()
1366            (setq *cached-debug-source* nil *cached-source-stream* nil
1367                  *cached-readtable* nil))
1368          *before-save-initializations*)
1369
1370 ;;; We also cache the last toplevel form that we printed a source for
1371 ;;; so that we don't have to do repeated reads and calls to
1372 ;;; FORM-NUMBER-TRANSLATIONS.
1373 (defvar *cached-toplevel-form-offset* nil)
1374 (declaim (type (or index null) *cached-toplevel-form-offset*))
1375 (defvar *cached-toplevel-form*)
1376 (defvar *cached-form-number-translations*)
1377
1378 ;;; Given a code location, return the associated form-number
1379 ;;; translations and the actual top level form. We check our cache ---
1380 ;;; if there is a miss, we dispatch on the kind of the debug source.
1381 (defun get-toplevel-form (location)
1382   (let ((d-source (sb!di:code-location-debug-source location)))
1383     (if (and (eq d-source *cached-debug-source*)
1384              (eql (sb!di:code-location-toplevel-form-offset location)
1385                   *cached-toplevel-form-offset*))
1386         (values *cached-form-number-translations* *cached-toplevel-form*)
1387         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1388                (res
1389                 (ecase (sb!di:debug-source-from d-source)
1390                   (:file (get-file-toplevel-form location))
1391                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1392           (setq *cached-toplevel-form-offset* offset)
1393           (values (setq *cached-form-number-translations*
1394                         (sb!di:form-number-translations res offset))
1395                   (setq *cached-toplevel-form* res))))))
1396
1397 ;;; Locate the source file (if it still exists) and grab the top level
1398 ;;; form. If the file is modified, we use the top level form offset
1399 ;;; instead of the recorded character offset.
1400 (defun get-file-toplevel-form (location)
1401   (let* ((d-source (sb!di:code-location-debug-source location))
1402          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1403          (local-tlf-offset (- tlf-offset
1404                               (sb!di:debug-source-root-number d-source)))
1405          (char-offset
1406           (aref (or (sb!di:debug-source-start-positions d-source)
1407                     (error "no start positions map"))
1408                 local-tlf-offset))
1409          (name (sb!di:debug-source-name d-source)))
1410     (unless (eq d-source *cached-debug-source*)
1411       (unless (and *cached-source-stream*
1412                    (equal (pathname *cached-source-stream*)
1413                           (pathname name)))
1414         (setq *cached-readtable* nil)
1415         (when *cached-source-stream* (close *cached-source-stream*))
1416         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1417         (unless *cached-source-stream*
1418           (error "The source file no longer exists:~%  ~A" (namestring name)))
1419         (format t "~%; file: ~A~%" (namestring name)))
1420
1421         (setq *cached-debug-source*
1422               (if (= (sb!di:debug-source-created d-source)
1423                      (file-write-date name))
1424                   d-source nil)))
1425
1426     (cond
1427      ((eq *cached-debug-source* d-source)
1428       (file-position *cached-source-stream* char-offset))
1429      (t
1430       (format t "~%; File has been modified since compilation:~%;   ~A~@
1431                  ; Using form offset instead of character position.~%"
1432               (namestring name))
1433       (file-position *cached-source-stream* 0)
1434       (let ((*read-suppress* t))
1435         (dotimes (i local-tlf-offset)
1436           (read *cached-source-stream*)))))
1437     (unless *cached-readtable*
1438       (setq *cached-readtable* (copy-readtable))
1439       (set-dispatch-macro-character
1440        #\# #\.
1441        (lambda (stream sub-char &rest rest)
1442          (declare (ignore rest sub-char))
1443          (let ((token (read stream t nil t)))
1444            (format nil "#.~S" token)))
1445        *cached-readtable*))
1446     (let ((*readtable* *cached-readtable*))
1447       (read *cached-source-stream*))))
1448
1449 (defun print-code-location-source-form (location context)
1450   (let* ((location (maybe-block-start-location location))
1451          (form-num (sb!di:code-location-form-number location)))
1452     (multiple-value-bind (translations form) (get-toplevel-form location)
1453       (unless (< form-num (length translations))
1454         (error "The source path no longer exists."))
1455       (prin1 (sb!di:source-path-context form
1456                                         (svref translations form-num)
1457                                         context)))))
1458 \f
1459 ;;; breakpoint and step commands
1460
1461 ;;; Step to the next code-location.
1462 (!def-debug-command "STEP" ()
1463   (setf *number-of-steps* (read-if-available 1))
1464   (set-step-breakpoint *current-frame*)
1465   (continue *debug-condition*)
1466   (error "couldn't continue"))
1467
1468 ;;; List possible breakpoint locations, which ones are active, and
1469 ;;; where the CONTINUE restart will transfer control. Set
1470 ;;; *POSSIBLE-BREAKPOINTS* to the code-locations which can then be
1471 ;;; used by sbreakpoint.
1472 (!def-debug-command "LIST-LOCATIONS" ()
1473   (let ((df (read-if-available *default-breakpoint-debug-fun*)))
1474     (cond ((consp df)
1475            (setf df (sb!di:fun-debug-fun (eval df)))
1476            (setf *default-breakpoint-debug-fun* df))
1477           ((or (eq ':c df)
1478                (not *default-breakpoint-debug-fun*))
1479            (setf df (sb!di:frame-debug-fun *current-frame*))
1480            (setf *default-breakpoint-debug-fun* df)))
1481     (setf *possible-breakpoints* (possible-breakpoints df)))
1482   (let ((continue-at (sb!di:frame-code-location *current-frame*)))
1483     (let ((active (location-in-list *default-breakpoint-debug-fun*
1484                                     *breakpoints* :fun-start))
1485           (here (sb!di:code-location=
1486                  (sb!di:debug-fun-start-location
1487                   *default-breakpoint-debug-fun*) continue-at)))
1488       (when (or active here)
1489         (format t "::FUN-START ")
1490         (when active (format t " *Active*"))
1491         (when here (format t " *Continue here*"))))
1492
1493     (let ((prev-location nil)
1494           (prev-num 0)
1495           (this-num 0))
1496       (flet ((flush ()
1497                (when prev-location
1498                  (let ((this-num (1- this-num)))
1499                    (if (= prev-num this-num)
1500                        (format t "~&~W: " prev-num)
1501                        (format t "~&~W-~W: " prev-num this-num)))
1502                  (print-code-location-source-form prev-location 0)
1503                  (when *print-location-kind*
1504                    (format t "~S " (sb!di:code-location-kind prev-location)))
1505                  (when (location-in-list prev-location *breakpoints*)
1506                    (format t " *Active*"))
1507                  (when (sb!di:code-location= prev-location continue-at)
1508                    (format t " *Continue here*")))))
1509         
1510         (dolist (code-location *possible-breakpoints*)
1511           (when (or *print-location-kind*
1512                     (location-in-list code-location *breakpoints*)
1513                     (sb!di:code-location= code-location continue-at)
1514                     (not prev-location)
1515                     (not (eq (sb!di:code-location-debug-source code-location)
1516                              (sb!di:code-location-debug-source prev-location)))
1517                     (not (eq (sb!di:code-location-toplevel-form-offset
1518                               code-location)
1519                              (sb!di:code-location-toplevel-form-offset
1520                               prev-location)))
1521                     (not (eq (sb!di:code-location-form-number code-location)
1522                              (sb!di:code-location-form-number prev-location))))
1523             (flush)
1524             (setq prev-location code-location  prev-num this-num))
1525
1526           (incf this-num))))
1527
1528     (when (location-in-list *default-breakpoint-debug-fun*
1529                             *breakpoints*
1530                             :fun-end)
1531       (format t "~&::FUN-END *Active* "))))
1532
1533 (!def-debug-command-alias "LL" "LIST-LOCATIONS")
1534
1535 ;;; Set breakpoint at the given number.
1536 (!def-debug-command "BREAKPOINT" ()
1537   (let ((index (read-prompting-maybe "location number, :START, or :END: "))
1538         (break t)
1539         (condition t)
1540         (print nil)
1541         (print-functions nil)
1542         (function nil)
1543         (bp)
1544         (place *default-breakpoint-debug-fun*))
1545     (flet ((get-command-line ()
1546              (let ((command-line nil)
1547                    (unique '(nil)))
1548                (loop
1549                  (let ((next-input (read-if-available unique)))
1550                    (when (eq next-input unique) (return))
1551                    (push next-input command-line)))
1552                (nreverse command-line)))
1553            (set-vars-from-command-line (command-line)
1554              (do ((arg (pop command-line) (pop command-line)))
1555                  ((not arg))
1556                (ecase arg
1557                  (:condition (setf condition (pop command-line)))
1558                  (:print (push (pop command-line) print))
1559                  (:break (setf break (pop command-line)))
1560                  (:function
1561                   (setf function (eval (pop command-line)))
1562                   (setf *default-breakpoint-debug-fun*
1563                         (sb!di:fun-debug-fun function))
1564                   (setf place *default-breakpoint-debug-fun*)
1565                   (setf *possible-breakpoints*
1566                         (possible-breakpoints
1567                          *default-breakpoint-debug-fun*))))))
1568            (setup-fun-start ()
1569              (let ((code-loc (sb!di:debug-fun-start-location place)))
1570                (setf bp (sb!di:make-breakpoint #'main-hook-fun
1571                                                place
1572                                                :kind :fun-start))
1573                (setf break (sb!di:preprocess-for-eval break code-loc))
1574                (setf condition (sb!di:preprocess-for-eval condition code-loc))
1575                (dolist (form print)
1576                  (push (cons (sb!di:preprocess-for-eval form code-loc) form)
1577                        print-functions))))
1578            (setup-fun-end ()
1579              (setf bp
1580                    (sb!di:make-breakpoint #'main-hook-fun
1581                                           place
1582                                           :kind :fun-end))
1583              (setf break
1584                    ;; FIXME: These and any other old (COERCE `(LAMBDA ..) ..)
1585                    ;; forms should be converted to shiny new (LAMBDA ..) forms.
1586                    ;; (Search the sources for "coerce.*\(lambda".)
1587                    (coerce `(lambda (dummy)
1588                               (declare (ignore dummy)) ,break)
1589                            'function))
1590              (setf condition (coerce `(lambda (dummy)
1591                                         (declare (ignore dummy)) ,condition)
1592                                      'function))
1593              (dolist (form print)
1594                (push (cons
1595                       (coerce `(lambda (dummy)
1596                                  (declare (ignore dummy)) ,form) 'function)
1597                       form)
1598                      print-functions)))
1599            (setup-code-location ()
1600              (setf place (nth index *possible-breakpoints*))
1601              (setf bp (sb!di:make-breakpoint #'main-hook-fun place
1602                                              :kind :code-location))
1603              (dolist (form print)
1604                (push (cons
1605                       (sb!di:preprocess-for-eval form place)
1606                       form)
1607                      print-functions))
1608              (setf break (sb!di:preprocess-for-eval break place))
1609              (setf condition (sb!di:preprocess-for-eval condition place))))
1610       (set-vars-from-command-line (get-command-line))
1611       (cond
1612        ((or (eq index :start) (eq index :s))
1613         (setup-fun-start))
1614        ((or (eq index :end) (eq index :e))
1615         (setup-fun-end))
1616        (t
1617         (setup-code-location)))
1618       (sb!di:activate-breakpoint bp)
1619       (let* ((new-bp-info (create-breakpoint-info place bp index
1620                                                   :break break
1621                                                   :print print-functions
1622                                                   :condition condition))
1623              (old-bp-info (location-in-list new-bp-info *breakpoints*)))
1624         (when old-bp-info
1625           (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
1626                                         old-bp-info))
1627           (setf *breakpoints* (remove old-bp-info *breakpoints*))
1628           (format t "previous breakpoint removed~%"))
1629         (push new-bp-info *breakpoints*))
1630       (print-breakpoint-info (first *breakpoints*))
1631       (format t "~&added"))))
1632
1633 (!def-debug-command-alias "BP" "BREAKPOINT")
1634
1635 ;;; List all breakpoints which are set.
1636 (!def-debug-command "LIST-BREAKPOINTS" ()
1637   (setf *breakpoints*
1638         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
1639   (dolist (info *breakpoints*)
1640     (print-breakpoint-info info)))
1641
1642 (!def-debug-command-alias "LB" "LIST-BREAKPOINTS")
1643 (!def-debug-command-alias "LBP" "LIST-BREAKPOINTS")
1644
1645 ;;; Remove breakpoint N, or remove all breakpoints if no N given.
1646 (!def-debug-command "DELETE-BREAKPOINT" ()
1647   (let* ((index (read-if-available nil))
1648          (bp-info
1649           (find index *breakpoints* :key #'breakpoint-info-breakpoint-number)))
1650     (cond (bp-info
1651            (sb!di:delete-breakpoint (breakpoint-info-breakpoint bp-info))
1652            (setf *breakpoints* (remove bp-info *breakpoints*))
1653            (format t "breakpoint ~S removed~%" index))
1654           (index (format t "The breakpoint doesn't exist."))
1655           (t
1656            (dolist (ele *breakpoints*)
1657              (sb!di:delete-breakpoint (breakpoint-info-breakpoint ele)))
1658            (setf *breakpoints* nil)
1659            (format t "all breakpoints deleted~%")))))
1660
1661 (!def-debug-command-alias "DBP" "DELETE-BREAKPOINT")
1662 \f
1663 ;;; miscellaneous commands
1664
1665 (!def-debug-command "DESCRIBE" ()
1666   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1667          (debug-fun (sb!di:code-location-debug-fun curloc))
1668          (function (sb!di:debug-fun-fun debug-fun)))
1669     (if function
1670         (describe function)
1671         (format t "can't figure out the function for this frame"))))
1672
1673 (!def-debug-command "SLURP" ()
1674   (loop while (read-char-no-hang *standard-input*)))
1675
1676 (!def-debug-command "RETURN" (&optional
1677                               (return (read-prompting-maybe
1678                                        "return: ")))
1679   (let ((tag (find-if (lambda (x)
1680                         (and (typep (car x) 'symbol)
1681                              (not (symbol-package (car x)))
1682                              (string= (car x) "SB-DEBUG-CATCH-TAG")))
1683                       (sb!di::frame-catches *current-frame*))))
1684     (if tag
1685         (throw (car tag)
1686           (funcall (sb!di:preprocess-for-eval
1687                     return
1688                     (sb!di:frame-code-location *current-frame*))
1689                    *current-frame*))
1690         (format t "~@<can't find a tag for this frame ~
1691                    ~2I~_(hint: try increasing the DEBUG optimization quality ~
1692                    and recompiling)~:@>"))))
1693 \f
1694 ;;;; debug loop command utilities
1695
1696 (defun read-prompting-maybe (prompt)
1697   (unless (sb!int:listen-skip-whitespace *debug-io*)
1698     (princ prompt)
1699     (force-output))
1700   (read *debug-io*))
1701
1702 (defun read-if-available (default)
1703   (if (sb!int:listen-skip-whitespace *debug-io*)
1704       (read *debug-io*)
1705       default))