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