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