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