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