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