0.7.11.5:
[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     #!-mp (debug-loop)
818     #!+mp (sb!mp:without-scheduling (debug-loop))))
819 \f
820 ;;;; DEBUG-LOOP
821
822 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
823 ;;; was motivated by desire to play nicely with ILISP.
824 (defvar *flush-debug-errors* nil
825   #!+sb-doc
826   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
827    executing in the debugger.")
828
829 (defun debug-loop ()
830   (let* ((*debug-command-level* (1+ *debug-command-level*))
831          (*real-stack-top* (sb!di:top-frame))
832          (*stack-top* (or *stack-top-hint* *real-stack-top*))
833          (*stack-top-hint* nil)
834          (*current-frame* *stack-top*))
835     (handler-bind ((sb!di:debug-condition
836                     (lambda (condition)
837                       (princ condition *debug-io*)
838                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
839                       (throw 'debug-loop-catcher nil))))
840       (fresh-line)
841       (print-frame-call *current-frame* :verbosity 2)
842       (loop
843         (catch 'debug-loop-catcher
844           (handler-bind ((error (lambda (condition)
845                                   (when *flush-debug-errors*
846                                     (clear-input *debug-io*)
847                                     (princ condition)
848                                     ;; FIXME: Doing input on *DEBUG-IO*
849                                     ;; and output on T seems broken.
850                                     (format t
851                                             "~&error flushed (because ~
852                                              ~S is set)"
853                                             '*flush-debug-errors*)
854                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
855                                     (throw 'debug-loop-catcher nil)))))
856             ;; We have to bind LEVEL for the restart function created by
857             ;; WITH-SIMPLE-RESTART.
858             (let ((level *debug-command-level*)
859                   (restart-commands (make-restart-commands)))
860               (with-simple-restart (abort
861                                    "~@<Reduce debugger level (to debug level ~W).~@:>"
862                                     level)
863                 (debug-prompt *debug-io*)
864                 (force-output *debug-io*)
865                 (let ((input (sb!int:get-stream-command *debug-io*)))
866                   (cond (input
867                          (let ((cmd-fun (debug-command-p
868                                          (sb!int:stream-command-name input)
869                                          restart-commands)))
870                            (cond
871                             ((not cmd-fun)
872                              (error "unknown stream-command: ~S" input))
873                             ((consp cmd-fun)
874                              (error "ambiguous debugger command: ~S" cmd-fun))
875                             (t
876                              (apply cmd-fun
877                                     (sb!int:stream-command-args input))))))
878                         (t
879                          (let* ((exp (read *debug-io*))
880                                 (cmd-fun (debug-command-p exp
881                                                           restart-commands)))
882                            (cond ((not cmd-fun)
883                                   (debug-eval-print exp))
884                                  ((consp cmd-fun)
885                                   (format t
886                                           "~&Your command, ~S, is ambiguous:~%"
887                                           exp)
888                                   (dolist (ele cmd-fun)
889                                     (format t "   ~A~%" ele)))
890                                  (t
891                                   (funcall cmd-fun)))))))))))))))
892
893 ;;; FIXME: We could probably use INTERACTIVE-EVAL for much of this logic.
894 (defun debug-eval-print (expr)
895   (/noshow "entering DEBUG-EVAL-PRINT" expr)
896   (/noshow (fboundp 'compile))
897   (setq +++ ++ ++ + + - - expr)
898   (let* ((values (multiple-value-list (eval -)))
899          (*standard-output* *debug-io*))
900     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
901     (fresh-line)
902     (if values (prin1 (car values)))
903     (dolist (x (cdr values))
904       (fresh-line)
905       (prin1 x))
906     (setq /// // // / / values)
907     (setq *** ** ** * * (car values))
908     ;; Make sure that nobody passes back an unbound marker.
909     (unless (boundp '*)
910       (setq * nil)
911       (fresh-line)
912       ;; FIXME: The way INTERACTIVE-EVAL does this seems better.
913       (princ "Setting * to NIL (was unbound marker)."))))
914 \f
915 ;;;; debug loop functions
916
917 ;;; These commands are functions, not really commands, so that users
918 ;;; can get their hands on the values returned.
919
920 (eval-when (:execute :compile-toplevel)
921
922 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
923   `(let* ((temp (etypecase name
924                   (symbol (sb!di:debug-fun-symbol-vars
925                            (sb!di:frame-debug-fun *current-frame*)
926                            name))
927                   (simple-string (sb!di:ambiguous-debug-vars
928                                   (sb!di:frame-debug-fun *current-frame*)
929                                   name))))
930           (location (sb!di:frame-code-location *current-frame*))
931           ;; Let's only deal with valid variables.
932           (vars (remove-if-not (lambda (v)
933                                  (eq (sb!di:debug-var-validity v location)
934                                      :valid))
935                                temp)))
936      (declare (list vars))
937      (cond ((null vars)
938             (error "No known valid variables match ~S." name))
939            ((= (length vars) 1)
940             ,(ecase ref-or-set
941                (:ref
942                 '(sb!di:debug-var-value (car vars) *current-frame*))
943                (:set
944                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
945                        ,value-var))))
946            (t
947             ;; Since we have more than one, first see whether we have
948             ;; any variables that exactly match the specification.
949             (let* ((name (etypecase name
950                            (symbol (symbol-name name))
951                            (simple-string name)))
952                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
953                    ;; instead.
954                    (exact (remove-if-not (lambda (v)
955                                            (string= (sb!di:debug-var-symbol-name v)
956                                                     name))
957                                          vars))
958                    (vars (or exact vars)))
959               (declare (simple-string name)
960                        (list exact vars))
961               (cond
962                ;; Check now for only having one variable.
963                ((= (length vars) 1)
964                 ,(ecase ref-or-set
965                    (:ref
966                     '(sb!di:debug-var-value (car vars) *current-frame*))
967                    (:set
968                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
969                            ,value-var))))
970                ;; If there weren't any exact matches, flame about
971                ;; ambiguity unless all the variables have the same
972                ;; name.
973                ((and (not exact)
974                      (find-if-not
975                       (lambda (v)
976                         (string= (sb!di:debug-var-symbol-name v)
977                                  (sb!di:debug-var-symbol-name (car vars))))
978                       (cdr vars)))
979                 (error "specification ambiguous:~%~{   ~A~%~}"
980                        (mapcar #'sb!di:debug-var-symbol-name
981                                (delete-duplicates
982                                 vars :test #'string=
983                                 :key #'sb!di:debug-var-symbol-name))))
984                ;; All names are the same, so see whether the user
985                ;; ID'ed one of them.
986                (id-supplied
987                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
988                   (unless v
989                     (error
990                      "invalid variable ID, ~W: should have been one of ~S"
991                      id
992                      (mapcar #'sb!di:debug-var-id vars)))
993                   ,(ecase ref-or-set
994                      (:ref
995                       '(sb!di:debug-var-value v *current-frame*))
996                      (:set
997                       `(setf (sb!di:debug-var-value v *current-frame*)
998                              ,value-var)))))
999                (t
1000                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
1001                        name
1002                        (mapcar #'sb!di:debug-var-id vars)))))))))
1003
1004 ) ; EVAL-WHEN
1005
1006 ;;; FIXME: This doesn't work. It would be real nice we could make it
1007 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
1008 (defun var (name &optional (id 0 id-supplied))
1009   #!+sb-doc
1010   "Return a variable's value if possible. NAME is a simple-string or symbol.
1011    If it is a simple-string, it is an initial substring of the variable's name.
1012    If name is a symbol, it has the same name and package as the variable whose
1013    value this function returns. If the symbol is uninterned, then the variable
1014    has the same name as the symbol, but it has no package.
1015
1016    If name is the initial substring of variables with different names, then
1017    this return no values after displaying the ambiguous names. If name
1018    determines multiple variables with the same name, then you must use the
1019    optional id argument to specify which one you want. If you left id
1020    unspecified, then this returns no values after displaying the distinguishing
1021    id values.
1022
1023    The result of this function is limited to the availability of variable
1024    information. This is SETF'able."
1025   (define-var-operation :ref))
1026 (defun (setf var) (value name &optional (id 0 id-supplied))
1027   (define-var-operation :set value))
1028
1029 ;;; This returns the COUNT'th arg as the user sees it from args, the
1030 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
1031 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
1032 ;;; T. If this returns a keyword symbol or a value from a rest arg,
1033 ;;; then the second value is NIL.
1034 ;;;
1035 ;;; FIXME: There's probably some way to merge the code here with
1036 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1037 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1038 (declaim (ftype (function (index list)) nth-arg))
1039 (defun nth-arg (count args)
1040   (let ((n count))
1041     (dolist (ele args (error "The argument specification ~S is out of range."
1042                              n))
1043       (lambda-list-element-dispatch ele
1044         :required ((if (zerop n) (return (values ele t))))
1045         :optional ((if (zerop n) (return (values (second ele) t))))
1046         :keyword ((cond ((zerop n)
1047                          (return (values (second ele) nil)))
1048                         ((zerop (decf n))
1049                          (return (values (third ele) t)))))
1050         :deleted ((if (zerop n) (return (values ele t))))
1051         :rest ((let ((var (second ele)))
1052                  (lambda-var-dispatch var (sb!di:frame-code-location
1053                                            *current-frame*)
1054                    (error "unused &REST argument before n'th argument")
1055                    (dolist (value
1056                             (sb!di:debug-var-value var *current-frame*)
1057                             (error
1058                              "The argument specification ~S is out of range."
1059                              n))
1060                      (if (zerop n)
1061                          (return-from nth-arg (values value nil))
1062                          (decf n)))
1063                    (error "invalid &REST argument before n'th argument")))))
1064       (decf n))))
1065
1066 (defun arg (n)
1067   #!+sb-doc
1068   "Return the N'th argument's value if possible. Argument zero is the first
1069    argument in a frame's default printed representation. Count keyword/value
1070    pairs as separate arguments."
1071   (multiple-value-bind (var lambda-var-p)
1072       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1073                                 (sb!di:frame-debug-fun *current-frame*))
1074                    (sb!di:lambda-list-unavailable ()
1075                      (error "No argument values are available."))))
1076     (if lambda-var-p
1077         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1078           (error "Unused arguments have no values.")
1079           (sb!di:debug-var-value var *current-frame*)
1080           (error "invalid argument value"))
1081         var)))
1082 \f
1083 ;;;; machinery for definition of debug loop commands
1084
1085 (defvar *debug-commands* nil)
1086
1087 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1088 ;;; permitted.
1089 (defmacro !def-debug-command (name args &rest body)
1090   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1091     `(progn
1092        (setf *debug-commands*
1093              (remove ,name *debug-commands* :key #'car :test #'string=))
1094        (defun ,fun-name ,args
1095          (unless *in-the-debugger*
1096            (error "invoking debugger command while outside the debugger"))
1097          ,@body)
1098        (push (cons ,name #',fun-name) *debug-commands*)
1099        ',fun-name)))
1100
1101 (defun !def-debug-command-alias (new-name existing-name)
1102   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1103     (unless pair (error "unknown debug command name: ~S" existing-name))
1104     (push (cons new-name (cdr pair)) *debug-commands*))
1105   new-name)
1106
1107 ;;; This takes a symbol and uses its name to find a debugger command,
1108 ;;; using initial substring matching. It returns the command function
1109 ;;; if form identifies only one command, but if form is ambiguous,
1110 ;;; this returns a list of the command names. If there are no matches,
1111 ;;; this returns nil. Whenever the loop that looks for a set of
1112 ;;; possibilities encounters an exact name match, we return that
1113 ;;; command function immediately.
1114 (defun debug-command-p (form &optional other-commands)
1115   (if (or (symbolp form) (integerp form))
1116       (let* ((name
1117               (if (symbolp form)
1118                   (symbol-name form)
1119                   (format nil "~W" form)))
1120              (len (length name))
1121              (res nil))
1122         (declare (simple-string name)
1123                  (fixnum len)
1124                  (list res))
1125
1126         ;; Find matching commands, punting if exact match.
1127         (flet ((match-command (ele)
1128                  (let* ((str (car ele))
1129                         (str-len (length str)))
1130                    (declare (simple-string str)
1131                             (fixnum str-len))
1132                    (cond ((< str-len len))
1133                          ((= str-len len)
1134                           (when (string= name str :end1 len :end2 len)
1135                             (return-from debug-command-p (cdr ele))))
1136                          ((string= name str :end1 len :end2 len)
1137                           (push ele res))))))
1138           (mapc #'match-command *debug-commands*)
1139           (mapc #'match-command other-commands))
1140
1141         ;; Return the right value.
1142         (cond ((not res) nil)
1143               ((= (length res) 1)
1144                (cdar res))
1145               (t ; Just return the names.
1146                (do ((cmds res (cdr cmds)))
1147                    ((not cmds) res)
1148                  (setf (car cmds) (caar cmds))))))))
1149
1150 ;;; Return a list of debug commands (in the same format as
1151 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1152 ;;;
1153 ;;; Two commands are made for each restart: one for the number, and
1154 ;;; one for the restart name (unless it's been shadowed by an earlier
1155 ;;; restart of the same name, or it is NIL).
1156 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1157   (let ((commands)
1158         (num 0))                        ; better be the same as show-restarts!
1159     (dolist (restart restarts)
1160       (let ((name (string (restart-name restart))))
1161         (let ((restart-fun
1162                 (lambda ()
1163                   (/show0 "in restart-command closure, about to i-r-i")
1164                   (invoke-restart-interactively restart))))
1165           (push (cons (prin1-to-string num) restart-fun) commands)
1166           (unless (or (null (restart-name restart)) 
1167                       (find name commands :key #'car :test #'string=))
1168             (push (cons name restart-fun) commands))))
1169     (incf num))
1170   commands))
1171 \f
1172 ;;;; frame-changing commands
1173
1174 (!def-debug-command "UP" ()
1175   (let ((next (sb!di:frame-up *current-frame*)))
1176     (cond (next
1177            (setf *current-frame* next)
1178            (print-frame-call next))
1179           (t
1180            (format t "~&Top of stack.")))))
1181
1182 (!def-debug-command "DOWN" ()
1183   (let ((next (sb!di:frame-down *current-frame*)))
1184     (cond (next
1185            (setf *current-frame* next)
1186            (print-frame-call next))
1187           (t
1188            (format t "~&Bottom of stack.")))))
1189
1190 (!def-debug-command-alias "D" "DOWN")
1191
1192 ;;; CMU CL had this command, but SBCL doesn't, since it's redundant
1193 ;;; with "FRAME 0", and it interferes with abbreviations for the
1194 ;;; TOPLEVEL restart.
1195 ;;;(!def-debug-command "TOP" ()
1196 ;;;  (do ((prev *current-frame* lead)
1197 ;;;       (lead (sb!di:frame-up *current-frame*) (sb!di:frame-up lead)))
1198 ;;;      ((null lead)
1199 ;;;       (setf *current-frame* prev)
1200 ;;;       (print-frame-call prev))))
1201
1202 (!def-debug-command "BOTTOM" ()
1203   (do ((prev *current-frame* lead)
1204        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1205       ((null lead)
1206        (setf *current-frame* prev)
1207        (print-frame-call prev))))
1208
1209 (!def-debug-command-alias "B" "BOTTOM")
1210
1211 (!def-debug-command "FRAME" (&optional
1212                              (n (read-prompting-maybe "frame number: ")))
1213   (setf *current-frame*
1214         (multiple-value-bind (next-frame-fun limit-string)
1215             (if (< n (sb!di:frame-number *current-frame*))
1216                 (values #'sb!di:frame-up "top")
1217               (values #'sb!di:frame-down "bottom"))
1218           (do ((frame *current-frame*))
1219               ((= n (sb!di:frame-number frame))
1220                frame)
1221             (let ((next-frame (funcall next-frame-fun frame)))
1222               (cond (next-frame
1223                      (setf frame next-frame))
1224                     (t
1225                      (format t
1226                              "The ~A of the stack was encountered.~%"
1227                              limit-string)
1228                      (return frame)))))))
1229   (print-frame-call *current-frame*))
1230
1231 (!def-debug-command-alias "F" "FRAME")
1232 \f
1233 ;;;; commands for entering and leaving the debugger
1234
1235 ;;; CMU CL supported this QUIT debug command, but SBCL provides this
1236 ;;; functionality with a restart instead. (The QUIT debug command was
1237 ;;; removed because it's confusing to have "quit" mean two different
1238 ;;; things in the system, "restart the top level REPL" in the debugger
1239 ;;; and "terminate the Lisp system" as the SB-EXT:QUIT function.)
1240 ;;;
1241 ;;;(!def-debug-command "QUIT" ()
1242 ;;;  (throw 'sb!impl::toplevel-catcher nil))
1243
1244 ;;; CMU CL supported this GO debug command, but SBCL doesn't -- in
1245 ;;; SBCL you just type the CONTINUE restart name instead (or "C" or
1246 ;;; "RESTART CONTINUE", that's OK too).
1247 ;;;(!def-debug-command "GO" ()
1248 ;;;  (continue *debug-condition*)
1249 ;;;  (error "There is no restart named CONTINUE."))
1250
1251 (!def-debug-command "RESTART" ()
1252   (/show0 "doing RESTART debug-command")
1253   (let ((num (read-if-available :prompt)))
1254     (when (eq num :prompt)
1255       (show-restarts *debug-restarts* *debug-io*)
1256       (write-string "restart: ")
1257       (force-output)
1258       (setf num (read *debug-io*)))
1259     (let ((restart (typecase num
1260                      (unsigned-byte
1261                       (nth num *debug-restarts*))
1262                      (symbol
1263                       (find num *debug-restarts* :key #'restart-name
1264                             :test (lambda (sym1 sym2)
1265                                     (string= (symbol-name sym1)
1266                                              (symbol-name sym2)))))
1267                      (t
1268                       (format t "~S is invalid as a restart name.~%" num)
1269                       (return-from restart-debug-command nil)))))
1270       (/show0 "got RESTART")
1271       (if restart
1272           (invoke-restart-interactively restart)
1273           ;; FIXME: Even if this isn't handled by WARN, it probably
1274           ;; shouldn't go to *STANDARD-OUTPUT*, but *ERROR-OUTPUT* or
1275           ;; *QUERY-IO* or something. Look through this file to
1276           ;; straighten out stream usage.
1277           (princ "There is no such restart.")))))
1278 \f
1279 ;;;; information commands
1280
1281 (!def-debug-command "HELP" ()
1282   ;; CMU CL had a little toy pager here, but "if you aren't running
1283   ;; ILISP (or a smart windowing system, or something) you deserve to
1284   ;; lose", so we've dropped it in SBCL. However, in case some
1285   ;; desperate holdout is running this on a dumb terminal somewhere,
1286   ;; we tell him where to find the message stored as a string.
1287   (format *debug-io*
1288           "~&~A~2%(The HELP string is stored in ~S.)~%"
1289           *debug-help-string*
1290           '*debug-help-string*))
1291
1292 (!def-debug-command-alias "?" "HELP")
1293
1294 (!def-debug-command "ERROR" ()
1295   (format *debug-io* "~A~%" *debug-condition*)
1296   (show-restarts *debug-restarts* *debug-io*))
1297
1298 (!def-debug-command "BACKTRACE" ()
1299   (backtrace (read-if-available most-positive-fixnum)))
1300
1301 (!def-debug-command "PRINT" ()
1302   (print-frame-call *current-frame*))
1303
1304 (!def-debug-command-alias "P" "PRINT")
1305
1306 (!def-debug-command "LIST-LOCALS" ()
1307   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1308     (if (sb!di:debug-var-info-available d-fun)
1309         (let ((*standard-output* *debug-io*)
1310               (location (sb!di:frame-code-location *current-frame*))
1311               (prefix (read-if-available nil))
1312               (any-p nil)
1313               (any-valid-p nil))
1314           (dolist (v (sb!di:ambiguous-debug-vars
1315                         d-fun
1316                         (if prefix (string prefix) "")))
1317             (setf any-p t)
1318             (when (eq (sb!di:debug-var-validity v location) :valid)
1319               (setf any-valid-p t)
1320               (format t "~S~:[#~W~;~*~]  =  ~S~%"
1321                       (sb!di:debug-var-symbol v)
1322                       (zerop (sb!di:debug-var-id v))
1323                       (sb!di:debug-var-id v)
1324                       (sb!di:debug-var-value v *current-frame*))))
1325
1326           (cond
1327            ((not any-p)
1328             (format t "There are no local variables ~@[starting with ~A ~]~
1329                        in the function."
1330                     prefix))
1331            ((not any-valid-p)
1332             (format t "All variables ~@[starting with ~A ~]currently ~
1333                        have invalid values."
1334                     prefix))))
1335         (write-line "There is no variable information available."))))
1336
1337 (!def-debug-command-alias "L" "LIST-LOCALS")
1338
1339 (!def-debug-command "SOURCE" ()
1340   (fresh-line)
1341   (print-code-location-source-form (sb!di:frame-code-location *current-frame*)
1342                                    (read-if-available 0)))
1343 \f
1344 ;;;; source location printing
1345
1346 ;;; We cache a stream to the last valid file debug source so that we
1347 ;;; won't have to repeatedly open the file.
1348 ;;;
1349 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1350 ;;; in the 1990s, so the benefit is negligible, less important than the
1351 ;;; potential of extra confusion if someone changes the source during
1352 ;;; a debug session and the change doesn't show up. And removing this
1353 ;;; would simplify the system, which I like. -- WHN 19990903
1354 (defvar *cached-debug-source* nil)
1355 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1356 (defvar *cached-source-stream* nil)
1357 (declaim (type (or stream null) *cached-source-stream*))
1358
1359 ;;; To suppress the read-time evaluation #. macro during source read,
1360 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1361 ;;; copying it each time, and invalidated when the
1362 ;;; *CACHED-DEBUG-SOURCE* has changed.
1363 (defvar *cached-readtable* nil)
1364 (declaim (type (or readtable null) *cached-readtable*))
1365
1366 (pushnew (lambda ()
1367            (setq *cached-debug-source* nil *cached-source-stream* nil
1368                  *cached-readtable* nil))
1369          *before-save-initializations*)
1370
1371 ;;; We also cache the last toplevel form that we printed a source for
1372 ;;; so that we don't have to do repeated reads and calls to
1373 ;;; FORM-NUMBER-TRANSLATIONS.
1374 (defvar *cached-toplevel-form-offset* nil)
1375 (declaim (type (or index null) *cached-toplevel-form-offset*))
1376 (defvar *cached-toplevel-form*)
1377 (defvar *cached-form-number-translations*)
1378
1379 ;;; Given a code location, return the associated form-number
1380 ;;; translations and the actual top level form. We check our cache ---
1381 ;;; if there is a miss, we dispatch on the kind of the debug source.
1382 (defun get-toplevel-form (location)
1383   (let ((d-source (sb!di:code-location-debug-source location)))
1384     (if (and (eq d-source *cached-debug-source*)
1385              (eql (sb!di:code-location-toplevel-form-offset location)
1386                   *cached-toplevel-form-offset*))
1387         (values *cached-form-number-translations* *cached-toplevel-form*)
1388         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1389                (res
1390                 (ecase (sb!di:debug-source-from d-source)
1391                   (:file (get-file-toplevel-form location))
1392                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1393           (setq *cached-toplevel-form-offset* offset)
1394           (values (setq *cached-form-number-translations*
1395                         (sb!di:form-number-translations res offset))
1396                   (setq *cached-toplevel-form* res))))))
1397
1398 ;;; Locate the source file (if it still exists) and grab the top level
1399 ;;; form. If the file is modified, we use the top level form offset
1400 ;;; instead of the recorded character offset.
1401 (defun get-file-toplevel-form (location)
1402   (let* ((d-source (sb!di:code-location-debug-source location))
1403          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1404          (local-tlf-offset (- tlf-offset
1405                               (sb!di:debug-source-root-number d-source)))
1406          (char-offset
1407           (aref (or (sb!di:debug-source-start-positions d-source)
1408                     (error "no start positions map"))
1409                 local-tlf-offset))
1410          (name (sb!di:debug-source-name d-source)))
1411     (unless (eq d-source *cached-debug-source*)
1412       (unless (and *cached-source-stream*
1413                    (equal (pathname *cached-source-stream*)
1414                           (pathname name)))
1415         (setq *cached-readtable* nil)
1416         (when *cached-source-stream* (close *cached-source-stream*))
1417         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1418         (unless *cached-source-stream*
1419           (error "The source file no longer exists:~%  ~A" (namestring name)))
1420         (format t "~%; file: ~A~%" (namestring name)))
1421
1422         (setq *cached-debug-source*
1423               (if (= (sb!di:debug-source-created d-source)
1424                      (file-write-date name))
1425                   d-source nil)))
1426
1427     (cond
1428      ((eq *cached-debug-source* d-source)
1429       (file-position *cached-source-stream* char-offset))
1430      (t
1431       (format t "~%; File has been modified since compilation:~%;   ~A~@
1432                  ; Using form offset instead of character position.~%"
1433               (namestring name))
1434       (file-position *cached-source-stream* 0)
1435       (let ((*read-suppress* t))
1436         (dotimes (i local-tlf-offset)
1437           (read *cached-source-stream*)))))
1438     (unless *cached-readtable*
1439       (setq *cached-readtable* (copy-readtable))
1440       (set-dispatch-macro-character
1441        #\# #\.
1442        (lambda (stream sub-char &rest rest)
1443          (declare (ignore rest sub-char))
1444          (let ((token (read stream t nil t)))
1445            (format nil "#.~S" token)))
1446        *cached-readtable*))
1447     (let ((*readtable* *cached-readtable*))
1448       (read *cached-source-stream*))))
1449
1450 (defun print-code-location-source-form (location context)
1451   (let* ((location (maybe-block-start-location location))
1452          (form-num (sb!di:code-location-form-number location)))
1453     (multiple-value-bind (translations form) (get-toplevel-form location)
1454       (unless (< form-num (length translations))
1455         (error "The source path no longer exists."))
1456       (prin1 (sb!di:source-path-context form
1457                                         (svref translations form-num)
1458                                         context)))))
1459 \f
1460 ;;; breakpoint and step commands
1461
1462 ;;; Step to the next code-location.
1463 (!def-debug-command "STEP" ()
1464   (setf *number-of-steps* (read-if-available 1))
1465   (set-step-breakpoint *current-frame*)
1466   (continue *debug-condition*)
1467   (error "couldn't continue"))
1468
1469 ;;; List possible breakpoint locations, which ones are active, and
1470 ;;; where the CONTINUE restart will transfer control. Set
1471 ;;; *POSSIBLE-BREAKPOINTS* to the code-locations which can then be
1472 ;;; used by sbreakpoint.
1473 (!def-debug-command "LIST-LOCATIONS" ()
1474   (let ((df (read-if-available *default-breakpoint-debug-fun*)))
1475     (cond ((consp df)
1476            (setf df (sb!di:fun-debug-fun (eval df)))
1477            (setf *default-breakpoint-debug-fun* df))
1478           ((or (eq ':c df)
1479                (not *default-breakpoint-debug-fun*))
1480            (setf df (sb!di:frame-debug-fun *current-frame*))
1481            (setf *default-breakpoint-debug-fun* df)))
1482     (setf *possible-breakpoints* (possible-breakpoints df)))
1483   (let ((continue-at (sb!di:frame-code-location *current-frame*)))
1484     (let ((active (location-in-list *default-breakpoint-debug-fun*
1485                                     *breakpoints* :fun-start))
1486           (here (sb!di:code-location=
1487                  (sb!di:debug-fun-start-location
1488                   *default-breakpoint-debug-fun*) continue-at)))
1489       (when (or active here)
1490         (format t "::FUN-START ")
1491         (when active (format t " *Active*"))
1492         (when here (format t " *Continue here*"))))
1493
1494     (let ((prev-location nil)
1495           (prev-num 0)
1496           (this-num 0))
1497       (flet ((flush ()
1498                (when prev-location
1499                  (let ((this-num (1- this-num)))
1500                    (if (= prev-num this-num)
1501                        (format t "~&~W: " prev-num)
1502                        (format t "~&~W-~W: " prev-num this-num)))
1503                  (print-code-location-source-form prev-location 0)
1504                  (when *print-location-kind*
1505                    (format t "~S " (sb!di:code-location-kind prev-location)))
1506                  (when (location-in-list prev-location *breakpoints*)
1507                    (format t " *Active*"))
1508                  (when (sb!di:code-location= prev-location continue-at)
1509                    (format t " *Continue here*")))))
1510         
1511         (dolist (code-location *possible-breakpoints*)
1512           (when (or *print-location-kind*
1513                     (location-in-list code-location *breakpoints*)
1514                     (sb!di:code-location= code-location continue-at)
1515                     (not prev-location)
1516                     (not (eq (sb!di:code-location-debug-source code-location)
1517                              (sb!di:code-location-debug-source prev-location)))
1518                     (not (eq (sb!di:code-location-toplevel-form-offset
1519                               code-location)
1520                              (sb!di:code-location-toplevel-form-offset
1521                               prev-location)))
1522                     (not (eq (sb!di:code-location-form-number code-location)
1523                              (sb!di:code-location-form-number prev-location))))
1524             (flush)
1525             (setq prev-location code-location  prev-num this-num))
1526
1527           (incf this-num))))
1528
1529     (when (location-in-list *default-breakpoint-debug-fun*
1530                             *breakpoints*
1531                             :fun-end)
1532       (format t "~&::FUN-END *Active* "))))
1533
1534 (!def-debug-command-alias "LL" "LIST-LOCATIONS")
1535
1536 ;;; Set breakpoint at the given number.
1537 (!def-debug-command "BREAKPOINT" ()
1538   (let ((index (read-prompting-maybe "location number, :START, or :END: "))
1539         (break t)
1540         (condition t)
1541         (print nil)
1542         (print-functions nil)
1543         (function nil)
1544         (bp)
1545         (place *default-breakpoint-debug-fun*))
1546     (flet ((get-command-line ()
1547              (let ((command-line nil)
1548                    (unique '(nil)))
1549                (loop
1550                  (let ((next-input (read-if-available unique)))
1551                    (when (eq next-input unique) (return))
1552                    (push next-input command-line)))
1553                (nreverse command-line)))
1554            (set-vars-from-command-line (command-line)
1555              (do ((arg (pop command-line) (pop command-line)))
1556                  ((not arg))
1557                (ecase arg
1558                  (:condition (setf condition (pop command-line)))
1559                  (:print (push (pop command-line) print))
1560                  (:break (setf break (pop command-line)))
1561                  (:function
1562                   (setf function (eval (pop command-line)))
1563                   (setf *default-breakpoint-debug-fun*
1564                         (sb!di:fun-debug-fun function))
1565                   (setf place *default-breakpoint-debug-fun*)
1566                   (setf *possible-breakpoints*
1567                         (possible-breakpoints
1568                          *default-breakpoint-debug-fun*))))))
1569            (setup-fun-start ()
1570              (let ((code-loc (sb!di:debug-fun-start-location place)))
1571                (setf bp (sb!di:make-breakpoint #'main-hook-fun
1572                                                place
1573                                                :kind :fun-start))
1574                (setf break (sb!di:preprocess-for-eval break code-loc))
1575                (setf condition (sb!di:preprocess-for-eval condition code-loc))
1576                (dolist (form print)
1577                  (push (cons (sb!di:preprocess-for-eval form code-loc) form)
1578                        print-functions))))
1579            (setup-fun-end ()
1580              (setf bp
1581                    (sb!di:make-breakpoint #'main-hook-fun
1582                                           place
1583                                           :kind :fun-end))
1584              (setf break
1585                    ;; FIXME: These and any other old (COERCE `(LAMBDA ..) ..)
1586                    ;; forms should be converted to shiny new (LAMBDA ..) forms.
1587                    ;; (Search the sources for "coerce.*\(lambda".)
1588                    (coerce `(lambda (dummy)
1589                               (declare (ignore dummy)) ,break)
1590                            'function))
1591              (setf condition (coerce `(lambda (dummy)
1592                                         (declare (ignore dummy)) ,condition)
1593                                      'function))
1594              (dolist (form print)
1595                (push (cons
1596                       (coerce `(lambda (dummy)
1597                                  (declare (ignore dummy)) ,form) 'function)
1598                       form)
1599                      print-functions)))
1600            (setup-code-location ()
1601              (setf place (nth index *possible-breakpoints*))
1602              (setf bp (sb!di:make-breakpoint #'main-hook-fun place
1603                                              :kind :code-location))
1604              (dolist (form print)
1605                (push (cons
1606                       (sb!di:preprocess-for-eval form place)
1607                       form)
1608                      print-functions))
1609              (setf break (sb!di:preprocess-for-eval break place))
1610              (setf condition (sb!di:preprocess-for-eval condition place))))
1611       (set-vars-from-command-line (get-command-line))
1612       (cond
1613        ((or (eq index :start) (eq index :s))
1614         (setup-fun-start))
1615        ((or (eq index :end) (eq index :e))
1616         (setup-fun-end))
1617        (t
1618         (setup-code-location)))
1619       (sb!di:activate-breakpoint bp)
1620       (let* ((new-bp-info (create-breakpoint-info place bp index
1621                                                   :break break
1622                                                   :print print-functions
1623                                                   :condition condition))
1624              (old-bp-info (location-in-list new-bp-info *breakpoints*)))
1625         (when old-bp-info
1626           (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
1627                                         old-bp-info))
1628           (setf *breakpoints* (remove old-bp-info *breakpoints*))
1629           (format t "previous breakpoint removed~%"))
1630         (push new-bp-info *breakpoints*))
1631       (print-breakpoint-info (first *breakpoints*))
1632       (format t "~&added"))))
1633
1634 (!def-debug-command-alias "BP" "BREAKPOINT")
1635
1636 ;;; List all breakpoints which are set.
1637 (!def-debug-command "LIST-BREAKPOINTS" ()
1638   (setf *breakpoints*
1639         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
1640   (dolist (info *breakpoints*)
1641     (print-breakpoint-info info)))
1642
1643 (!def-debug-command-alias "LB" "LIST-BREAKPOINTS")
1644 (!def-debug-command-alias "LBP" "LIST-BREAKPOINTS")
1645
1646 ;;; Remove breakpoint N, or remove all breakpoints if no N given.
1647 (!def-debug-command "DELETE-BREAKPOINT" ()
1648   (let* ((index (read-if-available nil))
1649          (bp-info
1650           (find index *breakpoints* :key #'breakpoint-info-breakpoint-number)))
1651     (cond (bp-info
1652            (sb!di:delete-breakpoint (breakpoint-info-breakpoint bp-info))
1653            (setf *breakpoints* (remove bp-info *breakpoints*))
1654            (format t "breakpoint ~S removed~%" index))
1655           (index (format t "The breakpoint doesn't exist."))
1656           (t
1657            (dolist (ele *breakpoints*)
1658              (sb!di:delete-breakpoint (breakpoint-info-breakpoint ele)))
1659            (setf *breakpoints* nil)
1660            (format t "all breakpoints deleted~%")))))
1661
1662 (!def-debug-command-alias "DBP" "DELETE-BREAKPOINT")
1663 \f
1664 ;;; miscellaneous commands
1665
1666 (!def-debug-command "DESCRIBE" ()
1667   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1668          (debug-fun (sb!di:code-location-debug-fun curloc))
1669          (function (sb!di:debug-fun-fun debug-fun)))
1670     (if function
1671         (describe function)
1672         (format t "can't figure out the function for this frame"))))
1673
1674 (!def-debug-command "SLURP" ()
1675   (loop while (read-char-no-hang *standard-input*)))
1676
1677 (!def-debug-command "RETURN" (&optional
1678                               (return (read-prompting-maybe
1679                                        "return: ")))
1680   (let ((tag (find-if (lambda (x)
1681                         (and (typep (car x) 'symbol)
1682                              (not (symbol-package (car x)))
1683                              (string= (car x) "SB-DEBUG-CATCH-TAG")))
1684                       (sb!di::frame-catches *current-frame*))))
1685     (if tag
1686         (throw (car tag)
1687           (funcall (sb!di:preprocess-for-eval
1688                     return
1689                     (sb!di:frame-code-location *current-frame*))
1690                    *current-frame*))
1691         (format t "~@<can't find a tag for this frame ~
1692                    ~2I~_(hint: try increasing the DEBUG optimization quality ~
1693                    and recompiling)~:@>"))))
1694 \f
1695 ;;;; debug loop command utilities
1696
1697 (defun read-prompting-maybe (prompt)
1698   (unless (sb!int:listen-skip-whitespace *debug-io*)
1699     (princ prompt)
1700     (force-output))
1701   (read *debug-io*))
1702
1703 (defun read-if-available (default)
1704   (if (sb!int:listen-skip-whitespace *debug-io*)
1705       (read *debug-io*)
1706       default))