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