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