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