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