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