0.7.1.1:
[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   ;; FIXME: No-one seems to know what this is for. Nothing is noticeably
621   ;; broken on sunos...
622   #!-sunos (sb!unix:unix-sigsetmask 0)
623
624   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
625   ;; this, but here causing an exception just as we're trying to handle
626   ;; an exception would be confusing, so instead we use a special hack.
627   (unless (and (packagep *package*)
628                (package-name *package*))
629     (setf *package* (find-package :cl-user))
630     (format *error-output*
631             "The value of ~S was not an undeleted PACKAGE. It has been
632 reset to ~S."
633             '*package* *package*))
634   (let (;; Save *PACKAGE* to protect it from WITH-STANDARD-IO-SYNTAX.
635         (original-package *package*))
636     (with-standard-io-syntax
637      (let* ((*debug-condition* condition)
638             (*debug-restarts* (compute-restarts condition))
639             ;; We want the i/o subsystem to be in a known, useful
640             ;; state, regardless of where the debugger was invoked in
641             ;; the program. WITH-STANDARD-IO-SYNTAX does some of that,
642             ;; but
643             ;;   1. It doesn't affect our internal special variables 
644             ;;      like *CURRENT-LEVEL-IN-PRINT*.
645             ;;   2. It isn't customizable.
646             ;;   3. It doesn't set *PRINT-READABLY* or *PRINT-PRETTY* 
647             ;;      to the same value as the toplevel default.
648             ;;   4. It sets *PACKAGE* to COMMON-LISP-USER, which is not
649             ;;      helpful behavior for a debugger.
650             ;; We try to remedy all these problems with explicit 
651             ;; rebindings here.
652             (sb!kernel:*current-level-in-print* 0)
653             (*print-length* *debug-print-length*)
654             (*print-level* *debug-print-level*)
655             (*readtable* *debug-readtable*)
656             (*print-readably* nil)
657             (*print-pretty* t)
658             (*package* original-package)
659             (*nested-debug-condition* nil))
660
661        ;; Before we start our own output, finish any pending output.
662        ;; Otherwise, if the user tried to track the progress of
663        ;; his program using PRINT statements, he'd tend to lose
664        ;; the last line of output or so, and get confused.
665        (flush-standard-output-streams)
666
667        ;; (The initial output here goes to *ERROR-OUTPUT*, because the
668        ;; initial output is not interactive, just an error message,
669        ;; and when people redirect *ERROR-OUTPUT*, they could
670        ;; reasonably expect to see error messages logged there,
671        ;; regardless of what the debugger does afterwards.)
672        (handler-case
673            (format *error-output*
674                    "~2&~@<debugger invoked on condition of type ~S: ~
675                     ~2I~_~A~:>~%"
676                    (type-of *debug-condition*)
677                    *debug-condition*)
678          (error (condition)
679            (setf *nested-debug-condition* condition)
680            (let ((ndc-type (type-of *nested-debug-condition*)))
681              (format *error-output*
682                      "~&~@<(A ~S was caught when trying to print ~S when ~
683                       entering the debugger. Printing was aborted and the ~
684                       ~S was stored in ~S.)~@:>~%"
685                      ndc-type
686                      '*debug-condition*
687                      ndc-type
688                      '*nested-debug-condition*))
689            (when (typep condition 'cell-error)
690              ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
691              (format *error-output*
692                      "~&(CELL-ERROR-NAME ~S) = ~S~%"
693                      '*debug-condition*
694                      (cell-error-name *debug-condition*)))))
695
696        ;; After the initial error/condition/whatever announcement to
697        ;; *ERROR-OUTPUT*, we become interactive, and should talk on
698        ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
699        ;; statement, not a description of reality.:-| There's a lot of
700        ;; older debugger code which was written to do i/o on whatever
701        ;; stream was in fashion at the time, and not all of it has
702        ;; been converted to behave this way. -- WHN 2000-11-16)
703        (let (;; FIXME: The first two bindings here seem wrong,
704              ;; violating the principle of least surprise, and making
705              ;; it impossible for the user to do reasonable things
706              ;; like using PRINT at the debugger prompt to send output
707              ;; to the program's ordinary (possibly
708              ;; redirected-to-a-file) *STANDARD-OUTPUT*, or using
709              ;; PEEK-CHAR or some such thing on the program's ordinary
710              ;; (possibly also redirected) *STANDARD-INPUT*.
711              (*standard-input* *debug-io*)
712              (*standard-output* *debug-io*)
713              ;; This seems reasonable: e.g. if the user has redirected
714              ;; *ERROR-OUTPUT* to some log file, it's probably wrong
715              ;; to send errors which occur in interactive debugging to
716              ;; that file, and right to send them to *DEBUG-IO*.
717              (*error-output* *debug-io*))
718          (unless (typep condition 'step-condition)
719            (when *debug-beginner-help-p*
720              (format *debug-io*
721                      "~%~@<Within the debugger, you can type HELP for help. ~
722                       At any command prompt (within the debugger or not) you ~
723                       can type (SB-EXT:QUIT) to terminate the SBCL ~
724                       executable. The condition which caused the debugger to ~
725                       be entered is bound to ~S. You can suppress this ~
726                       message by clearing ~S.~:@>~2%"
727                      '*debug-condition*
728                      '*debug-beginner-help-p*))
729            (show-restarts *debug-restarts* *debug-io*))
730          (internal-debug))))))
731
732 (defun show-restarts (restarts s)
733   (cond ((null restarts)
734          (format s
735                  "~&(no restarts: If you didn't do this on purpose, ~
736                   please report it as a bug.)~%"))
737         (t
738          (format s "~&restarts:~%")
739          (let ((count 0)
740                (names-used '(nil))
741                (max-name-len 0))
742            (dolist (restart restarts)
743              (let ((name (restart-name restart)))
744                (when name
745                  (let ((len (length (princ-to-string name))))
746                    (when (> len max-name-len)
747                      (setf max-name-len len))))))
748            (unless (zerop max-name-len)
749              (incf max-name-len 3))
750            (dolist (restart restarts)
751              (let ((name (restart-name restart)))
752                (cond ((member name names-used)
753                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
754                      (t
755                       (format s "~& ~2D: [~VA] ~A~%"
756                               count (- max-name-len 3) name restart)
757                       (push name names-used))))
758              (incf count))))))
759
760 ;;; This calls DEBUG-LOOP, performing some simple initializations
761 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
762 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
763 ;;; to get into a debug prompt as quickly as possible with as little
764 ;;; risk as possible for stepping on whatever is causing recursive
765 ;;; errors.
766 (defun internal-debug ()
767   (let ((*in-the-debugger* t)
768         (*read-suppress* nil))
769     (unless (typep *debug-condition* 'step-condition)
770       (clear-input *debug-io*))
771     #!-mp (debug-loop)
772     #!+mp (sb!mp:without-scheduling (debug-loop))))
773 \f
774 ;;;; DEBUG-LOOP
775
776 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
777 ;;; was motivated by desire to play nicely with ILISP.
778 (defvar *flush-debug-errors* nil
779   #!+sb-doc
780   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
781    executing in the debugger.")
782
783 (defun debug-loop ()
784   (let* ((*debug-command-level* (1+ *debug-command-level*))
785          (*real-stack-top* (sb!di:top-frame))
786          (*stack-top* (or *stack-top-hint* *real-stack-top*))
787          (*stack-top-hint* nil)
788          (*current-frame* *stack-top*))
789     (handler-bind ((sb!di:debug-condition
790                     (lambda (condition)
791                       (princ condition *debug-io*)
792                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
793                       (throw 'debug-loop-catcher nil))))
794       (fresh-line)
795       (print-frame-call *current-frame* :verbosity 2)
796       (loop
797         (catch 'debug-loop-catcher
798           (handler-bind ((error (lambda (condition)
799                                   (when *flush-debug-errors*
800                                     (clear-input *debug-io*)
801                                     (princ condition)
802                                     ;; FIXME: Doing input on *DEBUG-IO*
803                                     ;; and output on T seems broken.
804                                     (format t
805                                             "~&error flushed (because ~
806                                              ~S is set)"
807                                             '*flush-debug-errors*)
808                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
809                                     (throw 'debug-loop-catcher nil)))))
810             ;; We have to bind level for the restart function created by
811             ;; WITH-SIMPLE-RESTART.
812             (let ((level *debug-command-level*)
813                   (restart-commands (make-restart-commands)))
814               (with-simple-restart (abort
815                                    "Reduce debugger level (to debug level ~W)."
816                                     level)
817                 (debug-prompt *debug-io*)
818                 (force-output *debug-io*)
819                 (let ((input (sb!int:get-stream-command *debug-io*)))
820                   (cond (input
821                          (let ((cmd-fun (debug-command-p
822                                          (sb!int:stream-command-name input)
823                                          restart-commands)))
824                            (cond
825                             ((not cmd-fun)
826                              (error "unknown stream-command: ~S" input))
827                             ((consp cmd-fun)
828                              (error "ambiguous debugger command: ~S" cmd-fun))
829                             (t
830                              (apply cmd-fun
831                                     (sb!int:stream-command-args input))))))
832                         (t
833                          (let* ((exp (read))
834                                 (cmd-fun (debug-command-p exp
835                                                           restart-commands)))
836                            (cond ((not cmd-fun)
837                                   (debug-eval-print exp))
838                                  ((consp cmd-fun)
839                                   (format t
840                                           "~&Your command, ~S, is ambiguous:~%"
841                                           exp)
842                                   (dolist (ele cmd-fun)
843                                     (format t "   ~A~%" ele)))
844                                  (t
845                                   (funcall cmd-fun)))))))))))))))
846
847 ;;; FIXME: We could probably use INTERACTIVE-EVAL for much of this logic.
848 (defun debug-eval-print (expr)
849   (/noshow "entering DEBUG-EVAL-PRINT" expr)
850   (/noshow (fboundp 'compile))
851   (setq +++ ++ ++ + + - - expr)
852   (let* ((values (multiple-value-list (eval -)))
853          (*standard-output* *debug-io*))
854     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
855     (fresh-line)
856     (if values (prin1 (car values)))
857     (dolist (x (cdr values))
858       (fresh-line)
859       (prin1 x))
860     (setq /// // // / / values)
861     (setq *** ** ** * * (car values))
862     ;; Make sure that nobody passes back an unbound marker.
863     (unless (boundp '*)
864       (setq * nil)
865       (fresh-line)
866       ;; FIXME: The way INTERACTIVE-EVAL does this seems better.
867       (princ "Setting * to NIL (was unbound marker)."))))
868 \f
869 ;;;; debug loop functions
870
871 ;;; These commands are functions, not really commands, so that users
872 ;;; can get their hands on the values returned.
873
874 (eval-when (:execute :compile-toplevel)
875
876 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
877   `(let* ((temp (etypecase name
878                   (symbol (sb!di:debug-fun-symbol-vars
879                            (sb!di:frame-debug-fun *current-frame*)
880                            name))
881                   (simple-string (sb!di:ambiguous-debug-vars
882                                   (sb!di:frame-debug-fun *current-frame*)
883                                   name))))
884           (location (sb!di:frame-code-location *current-frame*))
885           ;; Let's only deal with valid variables.
886           (vars (remove-if-not (lambda (v)
887                                  (eq (sb!di:debug-var-validity v location)
888                                      :valid))
889                                temp)))
890      (declare (list vars))
891      (cond ((null vars)
892             (error "No known valid variables match ~S." name))
893            ((= (length vars) 1)
894             ,(ecase ref-or-set
895                (:ref
896                 '(sb!di:debug-var-value (car vars) *current-frame*))
897                (:set
898                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
899                        ,value-var))))
900            (t
901             ;; Since we have more than one, first see whether we have
902             ;; any variables that exactly match the specification.
903             (let* ((name (etypecase name
904                            (symbol (symbol-name name))
905                            (simple-string name)))
906                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
907                    ;; instead.
908                    (exact (remove-if-not (lambda (v)
909                                            (string= (sb!di:debug-var-symbol-name v)
910                                                     name))
911                                          vars))
912                    (vars (or exact vars)))
913               (declare (simple-string name)
914                        (list exact vars))
915               (cond
916                ;; Check now for only having one variable.
917                ((= (length vars) 1)
918                 ,(ecase ref-or-set
919                    (:ref
920                     '(sb!di:debug-var-value (car vars) *current-frame*))
921                    (:set
922                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
923                            ,value-var))))
924                ;; If there weren't any exact matches, flame about
925                ;; ambiguity unless all the variables have the same
926                ;; name.
927                ((and (not exact)
928                      (find-if-not
929                       (lambda (v)
930                         (string= (sb!di:debug-var-symbol-name v)
931                                  (sb!di:debug-var-symbol-name (car vars))))
932                       (cdr vars)))
933                 (error "specification ambiguous:~%~{   ~A~%~}"
934                        (mapcar #'sb!di:debug-var-symbol-name
935                                (delete-duplicates
936                                 vars :test #'string=
937                                 :key #'sb!di:debug-var-symbol-name))))
938                ;; All names are the same, so see whether the user
939                ;; ID'ed one of them.
940                (id-supplied
941                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
942                   (unless v
943                     (error
944                      "invalid variable ID, ~W: should have been one of ~S"
945                      id
946                      (mapcar #'sb!di:debug-var-id vars)))
947                   ,(ecase ref-or-set
948                      (:ref
949                       '(sb!di:debug-var-value v *current-frame*))
950                      (:set
951                       `(setf (sb!di:debug-var-value v *current-frame*)
952                              ,value-var)))))
953                (t
954                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
955                        name
956                        (mapcar #'sb!di:debug-var-id vars)))))))))
957
958 ) ; EVAL-WHEN
959
960 ;;; FIXME: This doesn't work. It would be real nice we could make it
961 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
962 (defun var (name &optional (id 0 id-supplied))
963   #!+sb-doc
964   "Return a variable's value if possible. NAME is a simple-string or symbol.
965    If it is a simple-string, it is an initial substring of the variable's name.
966    If name is a symbol, it has the same name and package as the variable whose
967    value this function returns. If the symbol is uninterned, then the variable
968    has the same name as the symbol, but it has no package.
969
970    If name is the initial substring of variables with different names, then
971    this return no values after displaying the ambiguous names. If name
972    determines multiple variables with the same name, then you must use the
973    optional id argument to specify which one you want. If you left id
974    unspecified, then this returns no values after displaying the distinguishing
975    id values.
976
977    The result of this function is limited to the availability of variable
978    information. This is SETF'able."
979   (define-var-operation :ref))
980 (defun (setf var) (value name &optional (id 0 id-supplied))
981   (define-var-operation :set value))
982
983 ;;; This returns the COUNT'th arg as the user sees it from args, the
984 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
985 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
986 ;;; T. If this returns a keyword symbol or a value from a rest arg,
987 ;;; then the second value is NIL.
988 (declaim (ftype (function (index list)) nth-arg))
989 (defun nth-arg (count args)
990   (let ((n count))
991     (dolist (ele args (error "The argument specification ~S is out of range."
992                              n))
993       (lambda-list-element-dispatch ele
994         :required ((if (zerop n) (return (values ele t))))
995         :optional ((if (zerop n) (return (values (second ele) t))))
996         :keyword ((cond ((zerop n)
997                          (return (values (second ele) nil)))
998                         ((zerop (decf n))
999                          (return (values (third ele) t)))))
1000         :deleted ((if (zerop n) (return (values ele t))))
1001         :rest ((let ((var (second ele)))
1002                  (lambda-var-dispatch var (sb!di:frame-code-location
1003                                            *current-frame*)
1004                    (error "unused &REST argument before n'th
1005 argument")
1006                    (dolist (value
1007                             (sb!di:debug-var-value var *current-frame*)
1008                             (error
1009                              "The argument specification ~S is out of range."
1010                              n))
1011                      (if (zerop n)
1012                          (return-from nth-arg (values value nil))
1013                          (decf n)))
1014                    (error "invalid &REST argument before n'th argument")))))
1015       (decf n))))
1016
1017 (defun arg (n)
1018   #!+sb-doc
1019   "Return the N'th argument's value if possible. Argument zero is the first
1020    argument in a frame's default printed representation. Count keyword/value
1021    pairs as separate arguments."
1022   (multiple-value-bind (var lambda-var-p)
1023       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1024                                 (sb!di:frame-debug-fun *current-frame*))
1025                    (sb!di:lambda-list-unavailable ()
1026                      (error "No argument values are available."))))
1027     (if lambda-var-p
1028         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1029           (error "Unused arguments have no values.")
1030           (sb!di:debug-var-value var *current-frame*)
1031           (error "invalid argument value"))
1032         var)))
1033 \f
1034 ;;;; machinery for definition of debug loop commands
1035
1036 (defvar *debug-commands* nil)
1037
1038 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1039 ;;; permitted.
1040 (defmacro !def-debug-command (name args &rest body)
1041   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1042     `(progn
1043        (setf *debug-commands*
1044              (remove ,name *debug-commands* :key #'car :test #'string=))
1045        (defun ,fun-name ,args
1046          (unless *in-the-debugger*
1047            (error "invoking debugger command while outside the debugger"))
1048          ,@body)
1049        (push (cons ,name #',fun-name) *debug-commands*)
1050        ',fun-name)))
1051
1052 (defun !def-debug-command-alias (new-name existing-name)
1053   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1054     (unless pair (error "unknown debug command name: ~S" existing-name))
1055     (push (cons new-name (cdr pair)) *debug-commands*))
1056   new-name)
1057
1058 ;;; This takes a symbol and uses its name to find a debugger command,
1059 ;;; using initial substring matching. It returns the command function
1060 ;;; if form identifies only one command, but if form is ambiguous,
1061 ;;; this returns a list of the command names. If there are no matches,
1062 ;;; this returns nil. Whenever the loop that looks for a set of
1063 ;;; possibilities encounters an exact name match, we return that
1064 ;;; command function immediately.
1065 (defun debug-command-p (form &optional other-commands)
1066   (if (or (symbolp form) (integerp form))
1067       (let* ((name
1068               (if (symbolp form)
1069                   (symbol-name form)
1070                   (format nil "~W" form)))
1071              (len (length name))
1072              (res nil))
1073         (declare (simple-string name)
1074                  (fixnum len)
1075                  (list res))
1076
1077         ;; Find matching commands, punting if exact match.
1078         (flet ((match-command (ele)
1079                  (let* ((str (car ele))
1080                         (str-len (length str)))
1081                    (declare (simple-string str)
1082                             (fixnum str-len))
1083                    (cond ((< str-len len))
1084                          ((= str-len len)
1085                           (when (string= name str :end1 len :end2 len)
1086                             (return-from debug-command-p (cdr ele))))
1087                          ((string= name str :end1 len :end2 len)
1088                           (push ele res))))))
1089           (mapc #'match-command *debug-commands*)
1090           (mapc #'match-command other-commands))
1091
1092         ;; Return the right value.
1093         (cond ((not res) nil)
1094               ((= (length res) 1)
1095                (cdar res))
1096               (t ; Just return the names.
1097                (do ((cmds res (cdr cmds)))
1098                    ((not cmds) res)
1099                  (setf (car cmds) (caar cmds))))))))
1100
1101 ;;; Return a list of debug commands (in the same format as
1102 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1103 ;;;
1104 ;;; Two commands are made for each restart: one for the number, and
1105 ;;; one for the restart name (unless it's been shadowed by an earlier
1106 ;;; restart of the same name, or it is NIL).
1107 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1108   (let ((commands)
1109         (num 0))                        ; better be the same as show-restarts!
1110     (dolist (restart restarts)
1111       (let ((name (string (restart-name restart))))
1112         (let ((restart-fun
1113                 (lambda ()
1114                   (/show0 "in restart-command closure, about to i-r-i")
1115                   (invoke-restart-interactively restart))))
1116           (push (cons (prin1-to-string num) restart-fun) commands)
1117           (unless (or (null (restart-name restart)) 
1118                       (find name commands :key #'car :test #'string=))
1119             (push (cons name restart-fun) commands))))
1120     (incf num))
1121   commands))
1122 \f
1123 ;;;; frame-changing commands
1124
1125 (!def-debug-command "UP" ()
1126   (let ((next (sb!di:frame-up *current-frame*)))
1127     (cond (next
1128            (setf *current-frame* next)
1129            (print-frame-call next))
1130           (t
1131            (format t "~&Top of stack.")))))
1132
1133 (!def-debug-command "DOWN" ()
1134   (let ((next (sb!di:frame-down *current-frame*)))
1135     (cond (next
1136            (setf *current-frame* next)
1137            (print-frame-call next))
1138           (t
1139            (format t "~&Bottom of stack.")))))
1140
1141 (!def-debug-command-alias "D" "DOWN")
1142
1143 ;;; CMU CL had this command, but SBCL doesn't, since it's redundant
1144 ;;; with "FRAME 0", and it interferes with abbreviations for the
1145 ;;; TOPLEVEL restart.
1146 ;;;(!def-debug-command "TOP" ()
1147 ;;;  (do ((prev *current-frame* lead)
1148 ;;;       (lead (sb!di:frame-up *current-frame*) (sb!di:frame-up lead)))
1149 ;;;      ((null lead)
1150 ;;;       (setf *current-frame* prev)
1151 ;;;       (print-frame-call prev))))
1152
1153 (!def-debug-command "BOTTOM" ()
1154   (do ((prev *current-frame* lead)
1155        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1156       ((null lead)
1157        (setf *current-frame* prev)
1158        (print-frame-call prev))))
1159
1160 (!def-debug-command-alias "B" "BOTTOM")
1161
1162 (!def-debug-command "FRAME" (&optional
1163                              (n (read-prompting-maybe "frame number: ")))
1164   (setf *current-frame*
1165         (multiple-value-bind (next-frame-fun limit-string)
1166             (if (< n (sb!di:frame-number *current-frame*))
1167                 (values #'sb!di:frame-up "top")
1168               (values #'sb!di:frame-down "bottom"))
1169           (do ((frame *current-frame*))
1170               ((= n (sb!di:frame-number frame))
1171                frame)
1172             (let ((next-frame (funcall next-frame-fun frame)))
1173               (cond (next-frame
1174                      (setf frame next-frame))
1175                     (t
1176                      (format t
1177                              "The ~A of the stack was encountered.~%"
1178                              limit-string)
1179                      (return frame)))))))
1180   (print-frame-call *current-frame*))
1181
1182 (!def-debug-command-alias "F" "FRAME")
1183 \f
1184 ;;;; commands for entering and leaving the debugger
1185
1186 ;;; CMU CL supported this QUIT debug command, but SBCL provides this
1187 ;;; functionality with a restart instead. (The QUIT debug command was
1188 ;;; removed because it's confusing to have "quit" mean two different
1189 ;;; things in the system, "restart the top level REPL" in the debugger
1190 ;;; and "terminate the Lisp system" as the SB-EXT:QUIT function.)
1191 ;;;
1192 ;;;(!def-debug-command "QUIT" ()
1193 ;;;  (throw 'sb!impl::toplevel-catcher nil))
1194
1195 ;;; CMU CL supported this GO debug command, but SBCL doesn't -- in
1196 ;;; SBCL you just type the CONTINUE restart name instead (or "RESTART
1197 ;;; CONTINUE", that's OK too).
1198
1199 ;;;(!def-debug-command "GO" ()
1200 ;;;  (continue *debug-condition*)
1201 ;;;  (error "There is no restart named CONTINUE."))
1202
1203 (!def-debug-command "RESTART" ()
1204   (/show0 "doing RESTART debug-command")
1205   (let ((num (read-if-available :prompt)))
1206     (when (eq num :prompt)
1207       (show-restarts *debug-restarts* *debug-io*)
1208       (write-string "restart: ")
1209       (force-output)
1210       (setf num (read *standard-input*)))
1211     (let ((restart (typecase num
1212                      (unsigned-byte
1213                       (nth num *debug-restarts*))
1214                      (symbol
1215                       (find num *debug-restarts* :key #'restart-name
1216                             :test (lambda (sym1 sym2)
1217                                     (string= (symbol-name sym1)
1218                                              (symbol-name sym2)))))
1219                      (t
1220                       (format t "~S is invalid as a restart name.~%" num)
1221                       (return-from restart-debug-command nil)))))
1222       (/show0 "got RESTART")
1223       (if restart
1224           (invoke-restart-interactively restart)
1225           ;; FIXME: Even if this isn't handled by WARN, it probably
1226           ;; shouldn't go to *STANDARD-OUTPUT*, but *ERROR-OUTPUT* or
1227           ;; *QUERY-IO* or something. Look through this file to
1228           ;; straighten out stream usage.
1229           (princ "There is no such restart.")))))
1230 \f
1231 ;;;; information commands
1232
1233 (!def-debug-command "HELP" ()
1234   ;; CMU CL had a little toy pager here, but "if you aren't running
1235   ;; ILISP (or a smart windowing system, or something) you deserve to
1236   ;; lose", so we've dropped it in SBCL. However, in case some
1237   ;; desperate holdout is running this on a dumb terminal somewhere,
1238   ;; we tell him where to find the message stored as a string.
1239   (format *debug-io*
1240           "~&~A~2%(The HELP string is stored in ~S.)~%"
1241           *debug-help-string*
1242           '*debug-help-string*))
1243
1244 (!def-debug-command-alias "?" "HELP")
1245
1246 (!def-debug-command "ERROR" ()
1247   (format *debug-io* "~A~%" *debug-condition*)
1248   (show-restarts *debug-restarts* *debug-io*))
1249
1250 (!def-debug-command "BACKTRACE" ()
1251   (backtrace (read-if-available most-positive-fixnum)))
1252
1253 (!def-debug-command "PRINT" ()
1254   (print-frame-call *current-frame*))
1255
1256 (!def-debug-command-alias "P" "PRINT")
1257
1258 (!def-debug-command "LIST-LOCALS" ()
1259   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1260     (if (sb!di:debug-var-info-available d-fun)
1261         (let ((*standard-output* *debug-io*)
1262               (location (sb!di:frame-code-location *current-frame*))
1263               (prefix (read-if-available nil))
1264               (any-p nil)
1265               (any-valid-p nil))
1266           (dolist (v (sb!di:ambiguous-debug-vars
1267                         d-fun
1268                         (if prefix (string prefix) "")))
1269             (setf any-p t)
1270             (when (eq (sb!di:debug-var-validity v location) :valid)
1271               (setf any-valid-p t)
1272               (format t "~S~:[#~W~;~*~]  =  ~S~%"
1273                       (sb!di:debug-var-symbol v)
1274                       (zerop (sb!di:debug-var-id v))
1275                       (sb!di:debug-var-id v)
1276                       (sb!di:debug-var-value v *current-frame*))))
1277
1278           (cond
1279            ((not any-p)
1280             (format t "There are no local variables ~@[starting with ~A ~]~
1281                        in the function."
1282                     prefix))
1283            ((not any-valid-p)
1284             (format t "All variables ~@[starting with ~A ~]currently ~
1285                        have invalid values."
1286                     prefix))))
1287         (write-line "There is no variable information available."))))
1288
1289 (!def-debug-command-alias "L" "LIST-LOCALS")
1290
1291 (!def-debug-command "SOURCE" ()
1292   (fresh-line)
1293   (print-code-location-source-form (sb!di:frame-code-location *current-frame*)
1294                                    (read-if-available 0)))
1295 \f
1296 ;;;; source location printing
1297
1298 ;;; We cache a stream to the last valid file debug source so that we
1299 ;;; won't have to repeatedly open the file.
1300 ;;;
1301 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1302 ;;; in the 1990s, so the benefit is negligible, less important than the
1303 ;;; potential of extra confusion if someone changes the source during
1304 ;;; a debug session and the change doesn't show up. And removing this
1305 ;;; would simplify the system, which I like. -- WHN 19990903
1306 (defvar *cached-debug-source* nil)
1307 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1308 (defvar *cached-source-stream* nil)
1309 (declaim (type (or stream null) *cached-source-stream*))
1310
1311 ;;; To suppress the read-time evaluation #. macro during source read,
1312 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1313 ;;; copying it each time, and invalidated when the
1314 ;;; *CACHED-DEBUG-SOURCE* has changed.
1315 (defvar *cached-readtable* nil)
1316 (declaim (type (or readtable null) *cached-readtable*))
1317
1318 (pushnew (lambda ()
1319            (setq *cached-debug-source* nil *cached-source-stream* nil
1320                  *cached-readtable* nil))
1321          *before-save-initializations*)
1322
1323 ;;; We also cache the last toplevel form that we printed a source for
1324 ;;; so that we don't have to do repeated reads and calls to
1325 ;;; FORM-NUMBER-TRANSLATIONS.
1326 (defvar *cached-toplevel-form-offset* nil)
1327 (declaim (type (or index null) *cached-toplevel-form-offset*))
1328 (defvar *cached-toplevel-form*)
1329 (defvar *cached-form-number-translations*)
1330
1331 ;;; Given a code location, return the associated form-number
1332 ;;; translations and the actual top level form. We check our cache ---
1333 ;;; if there is a miss, we dispatch on the kind of the debug source.
1334 (defun get-toplevel-form (location)
1335   (let ((d-source (sb!di:code-location-debug-source location)))
1336     (if (and (eq d-source *cached-debug-source*)
1337              (eql (sb!di:code-location-toplevel-form-offset location)
1338                   *cached-toplevel-form-offset*))
1339         (values *cached-form-number-translations* *cached-toplevel-form*)
1340         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1341                (res
1342                 (ecase (sb!di:debug-source-from d-source)
1343                   (:file (get-file-toplevel-form location))
1344                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1345           (setq *cached-toplevel-form-offset* offset)
1346           (values (setq *cached-form-number-translations*
1347                         (sb!di:form-number-translations res offset))
1348                   (setq *cached-toplevel-form* res))))))
1349
1350 ;;; Locate the source file (if it still exists) and grab the top level
1351 ;;; form. If the file is modified, we use the top level form offset
1352 ;;; instead of the recorded character offset.
1353 (defun get-file-toplevel-form (location)
1354   (let* ((d-source (sb!di:code-location-debug-source location))
1355          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1356          (local-tlf-offset (- tlf-offset
1357                               (sb!di:debug-source-root-number d-source)))
1358          (char-offset
1359           (aref (or (sb!di:debug-source-start-positions d-source)
1360                     (error "no start positions map"))
1361                 local-tlf-offset))
1362          (name (sb!di:debug-source-name d-source)))
1363     (unless (eq d-source *cached-debug-source*)
1364       (unless (and *cached-source-stream*
1365                    (equal (pathname *cached-source-stream*)
1366                           (pathname name)))
1367         (setq *cached-readtable* nil)
1368         (when *cached-source-stream* (close *cached-source-stream*))
1369         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1370         (unless *cached-source-stream*
1371           (error "The source file no longer exists:~%  ~A" (namestring name)))
1372         (format t "~%; file: ~A~%" (namestring name)))
1373
1374         (setq *cached-debug-source*
1375               (if (= (sb!di:debug-source-created d-source)
1376                      (file-write-date name))
1377                   d-source nil)))
1378
1379     (cond
1380      ((eq *cached-debug-source* d-source)
1381       (file-position *cached-source-stream* char-offset))
1382      (t
1383       (format t "~%; File has been modified since compilation:~%;   ~A~@
1384                  ; Using form offset instead of character position.~%"
1385               (namestring name))
1386       (file-position *cached-source-stream* 0)
1387       (let ((*read-suppress* t))
1388         (dotimes (i local-tlf-offset)
1389           (read *cached-source-stream*)))))
1390     (unless *cached-readtable*
1391       (setq *cached-readtable* (copy-readtable))
1392       (set-dispatch-macro-character
1393        #\# #\.
1394        (lambda (stream sub-char &rest rest)
1395          (declare (ignore rest sub-char))
1396          (let ((token (read stream t nil t)))
1397            (format nil "#.~S" token)))
1398        *cached-readtable*))
1399     (let ((*readtable* *cached-readtable*))
1400       (read *cached-source-stream*))))
1401
1402 (defun print-code-location-source-form (location context)
1403   (let* ((location (maybe-block-start-location location))
1404          (form-num (sb!di:code-location-form-number location)))
1405     (multiple-value-bind (translations form) (get-toplevel-form location)
1406       (unless (< form-num (length translations))
1407         (error "The source path no longer exists."))
1408       (prin1 (sb!di:source-path-context form
1409                                         (svref translations form-num)
1410                                         context)))))
1411 \f
1412 ;;; breakpoint and step commands
1413
1414 ;;; Step to the next code-location.
1415 (!def-debug-command "STEP" ()
1416   (setf *number-of-steps* (read-if-available 1))
1417   (set-step-breakpoint *current-frame*)
1418   (continue *debug-condition*)
1419   (error "couldn't continue"))
1420
1421 ;;; List possible breakpoint locations, which ones are active, and
1422 ;;; where the CONTINUE restart will transfer control. Set
1423 ;;; *POSSIBLE-BREAKPOINTS* to the code-locations which can then be
1424 ;;; used by sbreakpoint.
1425 (!def-debug-command "LIST-LOCATIONS" ()
1426   (let ((df (read-if-available *default-breakpoint-debug-fun*)))
1427     (cond ((consp df)
1428            (setf df (sb!di:fun-debug-fun (eval df)))
1429            (setf *default-breakpoint-debug-fun* df))
1430           ((or (eq ':c df)
1431                (not *default-breakpoint-debug-fun*))
1432            (setf df (sb!di:frame-debug-fun *current-frame*))
1433            (setf *default-breakpoint-debug-fun* df)))
1434     (setf *possible-breakpoints* (possible-breakpoints df)))
1435   (let ((continue-at (sb!di:frame-code-location *current-frame*)))
1436     (let ((active (location-in-list *default-breakpoint-debug-fun*
1437                                     *breakpoints* :fun-start))
1438           (here (sb!di:code-location=
1439                  (sb!di:debug-fun-start-location
1440                   *default-breakpoint-debug-fun*) continue-at)))
1441       (when (or active here)
1442         (format t "::FUN-START ")
1443         (when active (format t " *Active*"))
1444         (when here (format t " *Continue here*"))))
1445
1446     (let ((prev-location nil)
1447           (prev-num 0)
1448           (this-num 0))
1449       (flet ((flush ()
1450                (when prev-location
1451                  (let ((this-num (1- this-num)))
1452                    (if (= prev-num this-num)
1453                        (format t "~&~W: " prev-num)
1454                        (format t "~&~W-~W: " prev-num this-num)))
1455                  (print-code-location-source-form prev-location 0)
1456                  (when *print-location-kind*
1457                    (format t "~S " (sb!di:code-location-kind prev-location)))
1458                  (when (location-in-list prev-location *breakpoints*)
1459                    (format t " *Active*"))
1460                  (when (sb!di:code-location= prev-location continue-at)
1461                    (format t " *Continue here*")))))
1462         
1463         (dolist (code-location *possible-breakpoints*)
1464           (when (or *print-location-kind*
1465                     (location-in-list code-location *breakpoints*)
1466                     (sb!di:code-location= code-location continue-at)
1467                     (not prev-location)
1468                     (not (eq (sb!di:code-location-debug-source code-location)
1469                              (sb!di:code-location-debug-source prev-location)))
1470                     (not (eq (sb!di:code-location-toplevel-form-offset
1471                               code-location)
1472                              (sb!di:code-location-toplevel-form-offset
1473                               prev-location)))
1474                     (not (eq (sb!di:code-location-form-number code-location)
1475                              (sb!di:code-location-form-number prev-location))))
1476             (flush)
1477             (setq prev-location code-location  prev-num this-num))
1478
1479           (incf this-num))))
1480
1481     (when (location-in-list *default-breakpoint-debug-fun*
1482                             *breakpoints*
1483                             :fun-end)
1484       (format t "~&::FUN-END *Active* "))))
1485
1486 (!def-debug-command-alias "LL" "LIST-LOCATIONS")
1487
1488 ;;; Set breakpoint at the given number.
1489 (!def-debug-command "BREAKPOINT" ()
1490   (let ((index (read-prompting-maybe "location number, :START, or :END: "))
1491         (break t)
1492         (condition t)
1493         (print nil)
1494         (print-functions nil)
1495         (function nil)
1496         (bp)
1497         (place *default-breakpoint-debug-fun*))
1498     (flet ((get-command-line ()
1499              (let ((command-line nil)
1500                    (unique '(nil)))
1501                (loop
1502                  (let ((next-input (read-if-available unique)))
1503                    (when (eq next-input unique) (return))
1504                    (push next-input command-line)))
1505                (nreverse command-line)))
1506            (set-vars-from-command-line (command-line)
1507              (do ((arg (pop command-line) (pop command-line)))
1508                  ((not arg))
1509                (ecase arg
1510                  (:condition (setf condition (pop command-line)))
1511                  (:print (push (pop command-line) print))
1512                  (:break (setf break (pop command-line)))
1513                  (:function
1514                   (setf function (eval (pop command-line)))
1515                   (setf *default-breakpoint-debug-fun*
1516                         (sb!di:fun-debug-fun function))
1517                   (setf place *default-breakpoint-debug-fun*)
1518                   (setf *possible-breakpoints*
1519                         (possible-breakpoints
1520                          *default-breakpoint-debug-fun*))))))
1521            (setup-fun-start ()
1522              (let ((code-loc (sb!di:debug-fun-start-location place)))
1523                (setf bp (sb!di:make-breakpoint #'main-hook-fun
1524                                                place
1525                                                :kind :fun-start))
1526                (setf break (sb!di:preprocess-for-eval break code-loc))
1527                (setf condition (sb!di:preprocess-for-eval condition code-loc))
1528                (dolist (form print)
1529                  (push (cons (sb!di:preprocess-for-eval form code-loc) form)
1530                        print-functions))))
1531            (setup-fun-end ()
1532              (setf bp
1533                    (sb!di:make-breakpoint #'main-hook-fun
1534                                           place
1535                                           :kind :fun-end))
1536              (setf break
1537                    ;; FIXME: These and any other old (COERCE `(LAMBDA ..) ..)
1538                    ;; forms should be converted to shiny new (LAMBDA ..) forms.
1539                    ;; (Search the sources for "coerce.*\(lambda".)
1540                    (coerce `(lambda (dummy)
1541                               (declare (ignore dummy)) ,break)
1542                            'function))
1543              (setf condition (coerce `(lambda (dummy)
1544                                         (declare (ignore dummy)) ,condition)
1545                                      'function))
1546              (dolist (form print)
1547                (push (cons
1548                       (coerce `(lambda (dummy)
1549                                  (declare (ignore dummy)) ,form) 'function)
1550                       form)
1551                      print-functions)))
1552            (setup-code-location ()
1553              (setf place (nth index *possible-breakpoints*))
1554              (setf bp (sb!di:make-breakpoint #'main-hook-fun place
1555                                              :kind :code-location))
1556              (dolist (form print)
1557                (push (cons
1558                       (sb!di:preprocess-for-eval form place)
1559                       form)
1560                      print-functions))
1561              (setf break (sb!di:preprocess-for-eval break place))
1562              (setf condition (sb!di:preprocess-for-eval condition place))))
1563       (set-vars-from-command-line (get-command-line))
1564       (cond
1565        ((or (eq index :start) (eq index :s))
1566         (setup-fun-start))
1567        ((or (eq index :end) (eq index :e))
1568         (setup-fun-end))
1569        (t
1570         (setup-code-location)))
1571       (sb!di:activate-breakpoint bp)
1572       (let* ((new-bp-info (create-breakpoint-info place bp index
1573                                                   :break break
1574                                                   :print print-functions
1575                                                   :condition condition))
1576              (old-bp-info (location-in-list new-bp-info *breakpoints*)))
1577         (when old-bp-info
1578           (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
1579                                         old-bp-info))
1580           (setf *breakpoints* (remove old-bp-info *breakpoints*))
1581           (format t "previous breakpoint removed~%"))
1582         (push new-bp-info *breakpoints*))
1583       (print-breakpoint-info (first *breakpoints*))
1584       (format t "~&added"))))
1585
1586 (!def-debug-command-alias "BP" "BREAKPOINT")
1587
1588 ;;; List all breakpoints which are set.
1589 (!def-debug-command "LIST-BREAKPOINTS" ()
1590   (setf *breakpoints*
1591         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
1592   (dolist (info *breakpoints*)
1593     (print-breakpoint-info info)))
1594
1595 (!def-debug-command-alias "LB" "LIST-BREAKPOINTS")
1596 (!def-debug-command-alias "LBP" "LIST-BREAKPOINTS")
1597
1598 ;;; Remove breakpoint N, or remove all breakpoints if no N given.
1599 (!def-debug-command "DELETE-BREAKPOINT" ()
1600   (let* ((index (read-if-available nil))
1601          (bp-info
1602           (find index *breakpoints* :key #'breakpoint-info-breakpoint-number)))
1603     (cond (bp-info
1604            (sb!di:delete-breakpoint (breakpoint-info-breakpoint bp-info))
1605            (setf *breakpoints* (remove bp-info *breakpoints*))
1606            (format t "breakpoint ~S removed~%" index))
1607           (index (format t "The breakpoint doesn't exist."))
1608           (t
1609            (dolist (ele *breakpoints*)
1610              (sb!di:delete-breakpoint (breakpoint-info-breakpoint ele)))
1611            (setf *breakpoints* nil)
1612            (format t "all breakpoints deleted~%")))))
1613
1614 (!def-debug-command-alias "DBP" "DELETE-BREAKPOINT")
1615 \f
1616 ;;; miscellaneous commands
1617
1618 (!def-debug-command "DESCRIBE" ()
1619   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1620          (debug-fun (sb!di:code-location-debug-fun curloc))
1621          (function (sb!di:debug-fun-fun debug-fun)))
1622     (if function
1623         (describe function)
1624         (format t "can't figure out the function for this frame"))))
1625 \f
1626 ;;;; debug loop command utilities
1627
1628 (defun read-prompting-maybe (prompt &optional (in *standard-input*)
1629                                     (out *standard-output*))
1630   (unless (sb!int:listen-skip-whitespace in)
1631     (princ prompt out)
1632     (force-output out))
1633   (read in))
1634
1635 (defun read-if-available (default &optional (stream *standard-input*))
1636   (if (sb!int:listen-skip-whitespace stream)
1637       (read stream)
1638       default))