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