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