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