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