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