3 ;;;; This software is part of the SBCL system. See the README file for
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.
12 (in-package "SB!DEBUG")
14 ;;;; variables and constants
16 ;;; things to consider when tweaking these values:
17 ;;; * We're afraid to just default them to NIL and NIL, in case the
18 ;;; user inadvertently causes a hairy data structure to be printed
19 ;;; when he inadvertently enters the debugger.
20 ;;; * We don't want to truncate output too much. These days anyone
21 ;;; can easily run their Lisp in a windowing system or under Emacs,
22 ;;; so it's not the end of the world even if the worst case is a
23 ;;; few thousand lines of output.
24 ;;; * As condition :REPORT methods are converted to use the pretty
25 ;;; printer, they acquire *PRINT-LEVEL* constraints, so e.g. under
26 ;;; sbcl-0.7.1.28's old value of *DEBUG-PRINT-LEVEL*=3, an
27 ;;; ARG-COUNT-ERROR printed as
28 ;;; error while parsing arguments to DESTRUCTURING-BIND:
29 ;;; invalid number of elements in
31 ;;; to satisfy lambda list
33 ;;; exactly 2 expected, but 5 found
34 (defvar *debug-print-variable-alist* nil
36 "an association list describing new bindings for special variables
37 to be used within the debugger. Eg.
39 ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
41 The variables in the CAR positions are bound to the values in the CDR
42 during the execution of some debug commands. When evaluating arbitrary
43 expressions in the debugger, the normal values of the printer control
44 variables are in effect.
46 Initially empty, *DEBUG-PRINT-VARIABLE-ALIST* is typically used to
47 provide bindings for printer control variables.")
49 (defvar *debug-readtable*
50 ;; KLUDGE: This can't be initialized in a cold toplevel form,
51 ;; because the *STANDARD-READTABLE* isn't initialized until after
52 ;; cold toplevel forms have run. So instead we initialize it
53 ;; immediately after *STANDARD-READTABLE*. -- WHN 20000205
56 "*READTABLE* for the debugger")
58 (defvar *in-the-debugger* nil
60 "This is T while in the debugger.")
62 ;;; nestedness inside debugger command loops
63 (defvar *debug-command-level* 0)
65 ;;; If this is bound before the debugger is invoked, it is used as the stack
66 ;;; top by the debugger. It can either be the first interesting frame, or the
67 ;;; name of the last uninteresting frame.
68 (defvar *stack-top-hint* nil)
70 (defvar *real-stack-top* nil)
71 (defvar *stack-top* nil)
73 (defvar *current-frame* nil)
75 ;;; Beginner-oriented help messages are important because you end up
76 ;;; in the debugger whenever something bad happens, or if you try to
77 ;;; get out of the system with Ctrl-C or (EXIT) or EXIT or whatever.
78 ;;; But after memorizing them the wasted screen space gets annoying..
79 (defvar *debug-beginner-help-p* t
80 "Should the debugger display beginner-oriented help messages?")
82 (defun debug-prompt (stream)
83 (sb!thread::get-foreground)
86 (sb!di:frame-number *current-frame*)
87 (> *debug-command-level* 1)
88 *debug-command-level*))
90 (defparameter *debug-help-string*
91 "The debug prompt is square brackets, with number(s) indicating the current
92 control stack level and, if you've entered the debugger recursively, how
93 deeply recursed you are.
94 Any command -- including the name of a restart -- may be uniquely abbreviated.
95 The debugger rebinds various special variables for controlling i/o, sometimes
96 to defaults (much like WITH-STANDARD-IO-SYNTAX does) and sometimes to
97 its own special values, based on SB-EXT:*DEBUG-PRINT-VARIABLE-ALIST*.
98 Debug commands do not affect *, //, and similar variables, but evaluation in
99 the debug loop does affect these variables.
100 SB-DEBUG:*FLUSH-DEBUG-ERRORS* controls whether errors at the debug prompt
101 drop you deeper into the debugger. The default NIL allows recursive entry
104 Getting in and out of the debugger:
105 TOPLEVEL, TOP exits debugger and returns to top level REPL
106 RESTART invokes restart numbered as shown (prompt if not given).
107 ERROR prints the error condition and restart cases.
109 The number of any restart, or its name, or a unique abbreviation for its
110 name, is a valid command, and is the same as using RESTART to invoke
114 UP up frame DOWN down frame
115 BOTTOM bottom frame FRAME n frame n (n=0 for top frame)
118 BACKTRACE [n] shows n frames going down the stack.
119 LIST-LOCALS, L lists locals in current frame.
120 PRINT, P displays function call for current frame.
121 SOURCE [n] displays frame's source form with n levels of enclosing forms.
124 START Selects the CONTINUE restart if one exists and starts
125 single-stepping. Single stepping affects only code compiled with
126 under high DEBUG optimization quality. See User Manual for details.
127 STEP Steps into the current form.
128 NEXT Steps over the current form.
129 OUT Stops stepping temporarily, but resumes it when the topmost frame that
130 was stepped into returns.
131 STOP Stops single-stepping.
133 Function and macro commands:
135 Return the n'th argument in the current frame.
136 (SB-DEBUG:VAR string-or-symbol [id])
137 Returns the value of the specified variable in the current frame.
141 Return the values resulting from evaluation of expr from the
142 current frame, if this frame was compiled with a sufficiently high
143 DEBUG optimization quality.
146 Restart execution of the current frame, if this frame is for a
147 global function which was compiled with a sufficiently high
148 DEBUG optimization quality.
151 Discard all pending input on *STANDARD-INPUT*. (This can be
152 useful when the debugger was invoked to handle an error in
153 deeply nested input syntax, and now the reader is confused.)")
156 ;;; If LOC is an unknown location, then try to find the block start
157 ;;; location. Used by source printing to some information instead of
158 ;;; none for the user.
159 (defun maybe-block-start-location (loc)
160 (if (sb!di:code-location-unknown-p loc)
161 (let* ((block (sb!di:code-location-debug-block loc))
162 (start (sb!di:do-debug-block-locations (loc block)
164 (cond ((and (not (sb!di:debug-block-elsewhere-p block))
166 (format *debug-io* "~%unknown location: using block start~%")
174 (declaim (unsigned-byte *backtrace-frame-count*))
175 (defvar *backtrace-frame-count* 1000
176 "Default number of frames to backtrace. Defaults to 1000.")
178 (declaim (type (member :minimal :normal :full) *method-frame-style*))
179 (defvar *method-frame-style* :normal
180 "Determines how frames corresponding to method functions are represented in
181 backtraces. Possible values are :MINIMAL, :NORMAL, and :FULL.
183 :MINIMAL represents them as
185 (<gf-name> ...args...)
187 if all arguments are available, and only a single method is applicable to
188 the arguments -- otherwise behaves as :NORMAL.
190 :NORMAL represents them as
192 ((:method <gf-name> [<qualifier>*] (<specializer>*)) ...args...)
194 The frame is then followed by either [fast-method] or [slow-method],
195 designating the kind of method function. (See below.)
197 :FULL represents them using the actual funcallable method function name:
199 ((sb-pcl:fast-method <gf-name> [<qualifier>*] (<specializer>*)) ...args...)
203 ((sb-pcl:slow-method <gf-name> [<qualifier>*] (<specializer>*)) ...args...)
205 In the this case arguments may include values internal to SBCL's method
206 dispatch machinery.")
208 (define-deprecated-variable :early "1.1.4.9" *show-entry-point-details*
211 (defun backtrace (&optional (count *backtrace-frame-count*) (stream *debug-io*))
212 "Replaced by PRINT-BACKTRACE, will eventually be deprecated."
213 (print-backtrace :count count :stream stream))
215 (defun backtrace-as-list (&optional (count *backtrace-frame-count*))
216 "Replaced by LIST-BACKTRACE, will eventually be deprecated."
217 (list-backtrace :count count))
219 (defun backtrace-start-frame (frame-designator)
220 (let ((here (sb!di:top-frame)))
221 (labels ((current-frame ()
223 ;; Our caller's caller.
225 do (setf frame (or (sb!di:frame-down frame) frame)))
227 (interrupted-frame ()
228 (or (nth-value 1 (find-interrupted-name-and-frame))
230 (cond ((eq :current-frame frame-designator)
232 ((eq :interrupted-frame frame-designator)
234 ((eq :debugger-frame frame-designator)
235 (if (and *in-the-debugger* *current-frame*)
237 (interrupted-frame)))
238 ((sb!di:frame-p frame-designator)
241 (error "Invalid designator for initial backtrace frame: ~S"
242 frame-designator))))))
244 (defun map-backtrace (function &key
246 (from :debugger-frame)
247 (count *backtrace-frame-count*))
249 "Calls the designated FUNCTION with each frame on the call stack.
250 Returns the last value returned by FUNCTION.
252 COUNT is the number of frames to backtrace, defaulting to
253 *BACKTRACE-FRAME-COUNT*.
255 START is the number of the frame the backtrace should start from.
257 FROM specifies the frame relative to which the frames are numbered. Possible
258 values are an explicit SB-DI:FRAME object, and the
259 keywords :CURRENT-FRAME, :INTERRUPTED-FRAME, and :DEBUGGER-FRAME. Default
263 specifies the caller of MAP-BACKTRACE.
266 specifies the first interrupted frame on the stack \(typically the frame
267 where the error occured, as opposed to error handling frames) if any,
268 otherwise behaving as :CURRENT-FRAME.
271 specifies the currently debugged frame when inside the debugger, and
272 behaves as :INTERRUPTED-FRAME outside the debugger.
274 (loop with result = nil
276 for frame = (backtrace-start-frame from)
277 then (sb!di:frame-down frame)
279 when (<= start index) do
280 (if (minusp (decf count))
282 (setf result (funcall function frame)))
283 finally (return result)))
285 (defun print-backtrace (&key
288 (from :debugger-frame)
289 (count *backtrace-frame-count*)
291 (print-frame-source nil)
292 (method-frame-style *method-frame-style*))
294 "Print a listing of the call stack to STREAM, defaulting to *DEBUG-IO*.
296 COUNT is the number of frames to backtrace, defaulting to
297 *BACKTRACE-FRAME-COUNT*.
299 START is the number of the frame the backtrace should start from.
301 FROM specifies the frame relative to which the frames are numbered. Possible
302 values are an explicit SB-DI:FRAME object, and the
303 keywords :CURRENT-FRAME, :INTERRUPTED-FRAME, and :DEBUGGER-FRAME. Default
307 specifies the caller of PRINT-BACKTRACE.
310 specifies the first interrupted frame on the stack \(typically the frame
311 where the error occured, as opposed to error handling frames) if any,
312 otherwise behaving as :CURRENT-FRAME.
315 specifies the currently debugged frame when inside the debugger, and
316 behaves as :INTERRUPTED-FRAME outside the debugger.
318 If PRINT-THREAD is true (default), backtrace is preceded by printing the
319 thread object the backtrace is from.
321 If PRINT-FRAME-SOURCE is true (default is false), each frame is followed by
322 printing the currently executing source form in the function responsible for
323 that frame, when available. Requires the function to have been compiled at
324 DEBUG 2 or higher. If PRINT-FRAME-SOURCE is :ALWAYS, it also reports \"no
325 source available\" for frames for which were compiled at lower debug settings.
327 METHOD-FRAME-STYLE (defaulting to *METHOD-FRAME-STYLE*), determines how frames
328 corresponding to method functions are printed. Possible values
329 are :MINIMAL, :NORMAL, and :FULL. See *METHOD-FRAME-STYLE* for more
333 (format stream "Backtrace for: ~S~%" sb!thread:*current-thread*))
334 (let ((*suppress-print-errors* (if (subtypep 'serious-condition *suppress-print-errors*)
335 *suppress-print-errors*
339 (handler-bind ((print-not-readable #'print-unreadably))
340 (map-backtrace (lambda (frame)
341 (print-frame-call frame stream
343 :method-frame-style method-frame-style
344 :print-frame-source print-frame-source)
346 :from (backtrace-start-frame from)
352 (defun list-backtrace (&key
353 (count *backtrace-frame-count*)
355 (from :debugger-frame)
356 (method-frame-style *method-frame-style*))
358 "Returns a list describing the call stack. Each frame is represented
363 where the name describes the function responsible for the frame. The name
364 might not be bound to the actual function object. Unavailable arguments are
365 represented by dummy objects that print as #<unavailable argument>. Objects
366 with dynamic-extent allocation by the current thread are represented by
367 substitutes to avoid references to them from leaking outside their legal
370 COUNT is the number of frames to backtrace, defaulting to
371 *BACKTRACE-FRAME-COUNT*.
373 START is the number of the frame the backtrace should start from.
375 FROM specifies the frame relative to which the frames are numbered. Possible
376 values are an explicit SB-DI:FRAME object, and the
377 keywords :CURRENT-FRAME, :INTERRUPTED-FRAME, and :DEBUGGER-FRAME. Default
381 specifies the caller of LIST-BACKTRACE.
384 specifies the first interrupted frame on the stack \(typically the frame
385 where the error occured, as opposed to error handling frames) if any,
386 otherwise behaving as :CURRENT-FRAME.
389 specifies the currently debugged frame when inside the debugger, and
390 behaves as :INTERRUPTED-FRAME outside the debugger.
392 METHOD-FRAME-STYLE (defaulting to *METHOD-FRAME-STYLE*), determines how frames
393 corresponding to method functions are printed. Possible values
394 are :MINIMAL, :NORMAL, and :FULL. See *METHOD-FRAME-STYLE* for more
399 (push (frame-call-as-list frame :method-frame-style method-frame-style)
403 :from (backtrace-start-frame from))
404 (nreverse rbacktrace)))
406 (defun frame-call-as-list (frame &key (method-frame-style *method-frame-style*))
407 (multiple-value-bind (name args info)
408 (frame-call frame :method-frame-style method-frame-style
409 :replace-dynamic-extent-objects t)
410 (values (cons name args) info)))
412 (defun replace-dynamic-extent-object (obj)
413 (if (stack-allocated-p obj)
414 (make-unprintable-object
416 (format nil "dynamic-extent: ~S" obj)
418 "error printing dynamic-extent object")))
421 (defun stack-allocated-p (obj)
422 "Returns T if OBJ is allocated on the stack of the current
423 thread, NIL otherwise."
424 (with-pinned-objects (obj)
425 (let ((sap (int-sap (get-lisp-obj-address obj))))
426 (when (sb!vm:control-stack-pointer-valid-p sap nil)
431 (eval-when (:compile-toplevel :execute)
433 ;;; This is a convenient way to express what to do for each type of
434 ;;; lambda-list element.
435 (sb!xc:defmacro lambda-list-element-dispatch (element
447 (ecase (car ,element)
448 (:optional ,@optional)
453 (aver (eq ,element :deleted))
456 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
457 (let ((var (gensym)))
458 `(let ((,var ,variable))
459 (cond ((eq ,var :deleted) ,deleted)
460 ((eq (sb!di:debug-var-validity ,var ,location) :valid)
466 ;;; Extract the function argument values for a debug frame.
467 (defun map-frame-args (thunk frame)
468 (let ((debug-fun (sb!di:frame-debug-fun frame)))
469 (dolist (element (sb!di:debug-fun-lambda-list debug-fun))
470 (funcall thunk element))))
472 (defun frame-args-as-list (frame)
474 (let ((location (sb!di:frame-code-location frame))
475 (reversed-result nil))
479 (lambda-list-element-dispatch element
480 :required ((push (frame-call-arg element location frame) reversed-result))
481 :optional ((push (frame-call-arg (second element) location frame)
483 :keyword ((push (second element) reversed-result)
484 (push (frame-call-arg (third element) location frame)
486 :deleted ((push (frame-call-arg element location frame) reversed-result))
487 :rest ((lambda-var-dispatch (second element) location
489 (let ((rest (sb!di:debug-var-value (second element) frame)))
491 (setf reversed-result (append (reverse rest) reversed-result))
492 (push (make-unprintable-object "unavailable &REST argument")
494 (return-from enumerating))
495 (push (make-unprintable-object
496 "unavailable &REST argument")
498 :more ((lambda-var-dispatch (second element) location
500 (let ((context (sb!di:debug-var-value (second element) frame))
501 (count (sb!di:debug-var-value (third element) frame)))
502 (setf reversed-result
505 (sb!c::%more-arg-values context 0 count)))
507 (return-from enumerating))
508 (push (make-unprintable-object "unavailable &MORE argument")
511 (nreverse reversed-result))
512 (sb!di:lambda-list-unavailable ()
513 (make-unprintable-object "unavailable lambda list"))))
515 (defun interrupted-frame-error (frame)
516 (when (and (sb!di::compiled-frame-p frame)
517 (sb!di::compiled-frame-escaped frame))
518 (let ((error-number (sb!vm:internal-error-args
519 (sb!di::compiled-frame-escaped frame))))
520 (when (array-in-bounds-p sb!c:*backend-internal-errors* error-number)
521 (car (svref sb!c:*backend-internal-errors* error-number))))))
523 (defun clean-xep (frame name args info)
524 (values (second name)
526 (let* ((count (first args))
527 (real-args (rest args)))
528 (if (and (integerp count)
529 (eq (interrupted-frame-error frame)
530 'invalid-arg-count-error))
531 ;; So, this is a cheap trick -- but makes backtraces for
532 ;; too-many-arguments-errors much, much easier to to
533 ;; understand. FIXME: For :EXTERNAL frames at least we
534 ;; should be able to get the actual arguments, really.
536 for arg = (if real-args
538 (make-unprintable-object "unknown"))
542 (if (eq (car name) 'sb!c::tl-xep)
546 (defun clean-&more-processor (name args info)
547 (values (second name)
549 (let* ((more (last args 2))
550 (context (first more))
551 (count (second more)))
556 (sb!c:%more-arg-values context 0 count))
558 (make-unprintable-object "more unavailable arguments")))))
562 (defun clean-fast-method (name args style info)
563 (multiple-value-bind (cname cargs)
566 (let ((gf-name (second name))
567 (real-args (cddr args)))
568 (if (and (fboundp gf-name)
569 (notany #'sb!impl::unprintable-object-p real-args)
570 (let ((methods (compute-applicable-methods
571 (fdefinition gf-name) real-args)))
572 (and methods (not (cdr methods)))))
573 (values gf-name real-args)
574 (values (cons :method (cdr name)) real-args))))
576 (values (cons :method (cdr name)) (cddr args)))
579 (values cname cargs (cons :fast-method info))))
581 (defun clean-frame-call (frame name method-frame-style info)
582 (let ((args (frame-args-as-list frame)))
585 ((sb!c::xep sb!c::tl-xep)
586 (clean-xep frame name args info))
587 ((sb!c::&more-processor)
588 (clean-&more-processor name args info))
589 ((sb!c::&optional-processor)
590 (clean-frame-call frame (second name) method-frame-style
592 ((sb!pcl::fast-method)
593 (clean-fast-method name args method-frame-style info))
595 (values name args info)))
596 (values name args info))))
598 (defun frame-call (frame &key (method-frame-style *method-frame-style*)
599 replace-dynamic-extent-objects)
600 "Returns as multiple values a descriptive name for the function responsible
601 for FRAME, arguments that that function, and a list providing additional
602 information about the frame.
604 Unavailable arguments are represented using dummy-objects printing as
605 #<unavailable argument>.
607 METHOD-FRAME-STYLE (defaulting to *METHOD-FRAME-STYLE*), determines how frames
608 corresponding to method functions are printed. Possible values
609 are :MINIMAL, :NORMAL, and :FULL. See *METHOD-FRAME-STYLE* for more
612 If REPLACE-DYNAMIC-EXTENT-OBJECTS is true, objects allocated on the stack of
613 the current thread are replaced with dummy objects which can safely escape."
614 (let* ((debug-fun (sb!di:frame-debug-fun frame))
615 (kind (sb!di:debug-fun-kind debug-fun)))
616 (multiple-value-bind (name args info)
617 (clean-frame-call frame
618 (sb!di:debug-fun-name debug-fun)
620 (when kind (list kind)))
621 (let ((args (if (and (consp args) replace-dynamic-extent-objects)
622 (mapcar #'replace-dynamic-extent-object args)
624 (values name args info)))))
626 (defun ensure-printable-object (object)
628 (with-open-stream (out (make-broadcast-stream))
632 (declare (ignore cond))
633 (make-unprintable-object "error printing object"))))
635 (defun frame-call-arg (var location frame)
636 (lambda-var-dispatch var location
637 (make-unprintable-object "unused argument")
638 (sb!di:debug-var-value var frame)
639 (make-unprintable-object "unavailable argument")))
641 ;;; Prints a representation of the function call causing FRAME to
642 ;;; exist. VERBOSITY indicates the level of information to output;
643 ;;; zero indicates just printing the DEBUG-FUN's name, and one
644 ;;; indicates displaying call-like, one-liner format with argument
646 (defun print-frame-call (frame stream
647 &key print-frame-source
649 (method-frame-style *method-frame-style*))
651 (format stream "~&~S: " (if (integerp number)
653 (sb!di:frame-number frame))))
654 (multiple-value-bind (name args info)
655 (frame-call frame :method-frame-style method-frame-style)
656 (pprint-logical-block (stream nil :prefix "(" :suffix ")")
657 ;; Since we go to some trouble to make nice informative function
658 ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
659 ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
660 ;; For the function arguments, we can just print normally.
661 (let ((*print-length* nil)
665 (name (ensure-printable-object name)))
666 (write name :stream stream :escape t :pretty (equal '(lambda ()) name))
667 ;; If we hit a &REST arg, then print as many of the values as
668 ;; possible, punting the loop over lambda-list variables since any
669 ;; other arguments will be in the &REST arg's list of values.
670 (let ((args (ensure-printable-object args)))
672 (format stream "~{ ~_~S~}" args)
673 (format stream " ~S" args)))))
675 (format stream " [~{~(~A~)~^,~}]" info)))
676 (when print-frame-source
677 (let ((loc (sb!di:frame-code-location frame)))
679 (let ((source (handler-case
680 (code-location-source-form loc 0)
682 (format stream "~& error finding frame source: ~A" c)))))
683 (format stream "~% source: ~S" source))
684 (sb!di:debug-condition ()
685 ;; This is mostly noise.
686 (when (eq :always print-frame-source)
687 (format stream "~& no source available for frame")))
689 (format stream "~& error printing frame source: ~A" c))))))
693 (defvar *debugger-hook* nil
695 "This is either NIL or a function of two arguments, a condition and the value
696 of *DEBUGGER-HOOK*. This function can either handle the condition or return
697 which causes the standard debugger to execute. The system passes the value
698 of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
699 around the invocation.")
701 (defvar *invoke-debugger-hook* nil
703 "This is either NIL or a designator for a function of two arguments,
704 to be run when the debugger is about to be entered. The function is
705 run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
706 errors, and receives as arguments the condition that triggered
707 debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*
709 This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
710 In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
713 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
714 (defvar *debug-restarts*)
715 (defvar *debug-condition*)
716 (defvar *nested-debug-condition*)
718 ;;; Oh, what a tangled web we weave when we preserve backwards
719 ;;; compatibility with 1968-style use of global variables to control
720 ;;; per-stream i/o properties; there's really no way to get this
721 ;;; quite right, but we do what we can.
722 (defun funcall-with-debug-io-syntax (fun &rest rest)
723 (declare (type function fun))
724 ;; Try to force the other special variables into a useful state.
725 (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
726 ;; any default we might use is less useful than just reusing
727 ;; the global values.
728 (original-package *package*)
729 (original-print-pretty *print-pretty*))
730 (with-standard-io-syntax
732 (let (;; We want the printer and reader to be in a useful
733 ;; state, regardless of where the debugger was invoked
734 ;; in the program. WITH-STANDARD-IO-SYNTAX and
735 ;; WITH-SANE-IO-SYNTAX do much of what we want, but
736 ;; * It doesn't affect our internal special variables
737 ;; like *CURRENT-LEVEL-IN-PRINT*.
738 ;; * It isn't customizable.
739 ;; * It sets *PACKAGE* to COMMON-LISP-USER, which is not
740 ;; helpful behavior for a debugger.
741 ;; * There's no particularly good debugger default for
742 ;; *PRINT-PRETTY*, since T is usually what you want
743 ;; -- except absolutely not what you want when you're
744 ;; debugging failures in PRINT-OBJECT logic.
745 ;; We try to address all these issues with explicit
747 (sb!kernel:*current-level-in-print* 0)
748 (*package* original-package)
749 (*print-pretty* original-print-pretty)
750 ;; Clear the circularity machinery to try to to reduce the
751 ;; pain from sharing the circularity table across all
752 ;; streams; if these are not rebound here, then setting
753 ;; *PRINT-CIRCLE* within the debugger when debugging in a
754 ;; state where something circular was being printed (e.g.,
755 ;; because the debugger was entered on an error in a
756 ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
757 ;; here does seem somewhat ugly because it makes it more
758 ;; difficult to debug the printing-of-circularities code
759 ;; itself; however, as far as I (WHN, 2004-05-29) can see,
760 ;; that's almost entirely academic as long as there's one
761 ;; shared *C-H-T* for all streams (i.e., it's already
762 ;; unreasonably difficult to debug print-circle machinery
763 ;; given the buggy crosstalk between the debugger streams
764 ;; and the stream you're trying to watch), and any fix for
765 ;; that buggy arrangement will likely let this hack go away
767 (sb!impl::*circularity-hash-table* . nil)
768 (sb!impl::*circularity-counter* . nil)
769 (*readtable* *debug-readtable*))
771 ;; (Why NREVERSE? PROGV makes the later entries have
772 ;; precedence over the earlier entries.
773 ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
774 ;; expected that its earlier entries have precedence. And
775 ;; the earlier-has-precedence behavior is mostly more
776 ;; convenient, so that programmers can use PUSH or LIST* to
777 ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
778 (nreverse (mapcar #'car *debug-print-variable-alist*))
779 (nreverse (mapcar #'cdr *debug-print-variable-alist*))
780 (apply fun rest)))))))
782 ;;; This function is not inlined so it shows up in the backtrace; that
783 ;;; can be rather handy when one has to debug the interplay between
784 ;;; *INVOKE-DEBUGGER-HOOK* and *DEBUGGER-HOOK*.
785 (declaim (notinline run-hook))
786 (defun run-hook (variable condition)
787 (let ((old-hook (symbol-value variable)))
789 (progv (list variable) (list nil)
790 (funcall old-hook condition old-hook)))))
792 ;;; We can bind *stack-top-hint* to a symbol, in which case this function will
793 ;;; resolve that hint lazily before we enter the debugger.
794 (defun resolve-stack-top-hint ()
795 (let ((hint *stack-top-hint*)
796 (*stack-top-hint* nil))
798 ;; No hint, just keep the debugger guts out.
800 (find-caller-name-and-frame))
801 ;; Interrupted. Look for the interrupted frame -- if we don't find one
802 ;; this falls back to the next case.
803 ((and (eq hint 'invoke-interruption)
804 (nth-value 1 (find-interrupted-name-and-frame))))
805 ;; Name of the first uninteresting frame.
807 (find-caller-of-named-frame hint))
808 ;; We already have a resolved hint.
812 (defun invoke-debugger (condition)
814 "Enter the debugger."
816 (let ((*stack-top-hint* (resolve-stack-top-hint)))
818 ;; call *INVOKE-DEBUGGER-HOOK* first, so that *DEBUGGER-HOOK* is not
819 ;; called when the debugger is disabled
820 (run-hook '*invoke-debugger-hook* condition)
821 (run-hook '*debugger-hook* condition)
823 ;; We definitely want *PACKAGE* to be of valid type.
825 ;; Elsewhere in the system, we use the SANE-PACKAGE function for
826 ;; this, but here causing an exception just as we're trying to handle
827 ;; an exception would be confusing, so instead we use a special hack.
828 (unless (and (packagep *package*)
829 (package-name *package*))
830 (setf *package* (find-package :cl-user))
831 (format *error-output*
832 "The value of ~S was not an undeleted PACKAGE. It has been
834 '*package* *package*))
836 ;; Before we start our own output, finish any pending output.
837 ;; Otherwise, if the user tried to track the progress of his program
838 ;; using PRINT statements, he'd tend to lose the last line of output
839 ;; or so, which'd be confusing.
840 (flush-standard-output-streams)
842 (funcall-with-debug-io-syntax #'%invoke-debugger condition)))
844 (defun %print-debugger-invocation-reason (condition stream)
845 (format stream "~2&")
846 ;; Note: Ordinarily it's only a matter of taste whether to use
847 ;; FORMAT "~<...~:>" or to use PPRINT-LOGICAL-BLOCK directly, but
848 ;; until bug 403 is fixed, PPRINT-LOGICAL-BLOCK (STREAM NIL) is
849 ;; definitely preferred, because the FORMAT alternative was acting odd.
850 (pprint-logical-block (stream nil)
852 "debugger invoked on a ~S~@[ in thread ~_~A~]: ~2I~_~A"
854 #!+sb-thread sb!thread:*current-thread*
859 (defun %invoke-debugger (condition)
860 (let ((*debug-condition* condition)
861 (*debug-restarts* (compute-restarts condition))
862 (*nested-debug-condition* nil))
864 ;; (The initial output here goes to *ERROR-OUTPUT*, because the
865 ;; initial output is not interactive, just an error message, and
866 ;; when people redirect *ERROR-OUTPUT*, they could reasonably
867 ;; expect to see error messages logged there, regardless of what
868 ;; the debugger does afterwards.)
869 (unless (typep condition 'step-condition)
870 (%print-debugger-invocation-reason condition *error-output*))
872 (setf *nested-debug-condition* condition)
873 (let ((ndc-type (type-of *nested-debug-condition*)))
874 (format *error-output*
875 "~&~@<(A ~S was caught when trying to print ~S when ~
876 entering the debugger. Printing was aborted and the ~
877 ~S was stored in ~S.)~@:>~%"
881 '*nested-debug-condition*))
882 (when (typep *nested-debug-condition* 'cell-error)
883 ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
884 (format *error-output*
885 "~&(CELL-ERROR-NAME ~S) = ~S~%"
886 '*nested-debug-condition*
887 (cell-error-name *nested-debug-condition*)))))
889 (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
892 ;; After the initial error/condition/whatever announcement to
893 ;; *ERROR-OUTPUT*, we become interactive, and should talk on
894 ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
895 ;; statement, not a description of reality.:-| There's a lot of
896 ;; older debugger code which was written to do i/o on whatever
897 ;; stream was in fashion at the time, and not all of it has
898 ;; been converted to behave this way. -- WHN 2000-11-16)
901 (let (;; We used to bind *STANDARD-OUTPUT* to *DEBUG-IO*
902 ;; here as well, but that is probably bogus since it
903 ;; removes the users ability to do output to a redirected
904 ;; *S-O*. Now we just rebind it so that users can temporarily
905 ;; frob it. FIXME: This and other "what gets bound when"
906 ;; behaviour should be documented in the manual.
907 (*standard-output* *standard-output*)
908 ;; This seems reasonable: e.g. if the user has redirected
909 ;; *ERROR-OUTPUT* to some log file, it's probably wrong
910 ;; to send errors which occur in interactive debugging to
911 ;; that file, and right to send them to *DEBUG-IO*.
912 (*error-output* *debug-io*))
913 (unless (typep condition 'step-condition)
914 (when *debug-beginner-help-p*
916 "~%~@<Type HELP for debugger help, or ~
917 (SB-EXT:EXIT) to exit from SBCL.~:@>~2%"))
918 (show-restarts *debug-restarts* *debug-io*))
921 (sb!thread::release-foreground))))))
923 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
924 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
925 ;;; command-line option
926 (defun debugger-disabled-hook (condition previous-hook)
927 (declare (ignore previous-hook))
928 ;; There is no one there to interact with, so report the
929 ;; condition and terminate the program.
930 (let ((*suppress-print-errors* t)
931 (condition-error-message
932 #.(format nil "A nested error within --disable-debugger error ~
933 handling prevents displaying the original error. Attempting ~
934 to print a backtrace."))
935 (backtrace-error-message
936 #.(format nil "A nested error within --disable-debugger error ~
937 handling prevents printing the backtrace. Sorry, exiting.")))
939 ((failure-quit (&key abort)
940 (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
941 (exit :code 1 :abort abort))
942 (display-condition ()
947 ;; printing failed, try to describe it
948 (describe-condition)))
950 ;; ok, give up trying to display the error and inform the user about it
951 (finish-output *error-output*)
952 (%primitive print condition-error-message))))
954 (format *error-output*
955 "~&~@<Unhandled ~S~@[ in thread ~S~]: ~2I~_~A~:>~2%"
957 #!+sb-thread sb!thread:*current-thread*
960 (finish-output *error-output*))
961 (describe-condition ()
962 (format *error-output*
963 "~&Unhandled ~S~@[ in thread ~S~]:~%"
965 #!+sb-thread sb!thread:*current-thread*
967 (describe condition *error-output*)
968 (finish-output *error-output*))
969 (display-backtrace ()
971 (print-backtrace :stream *error-output*
972 :from :interrupted-frame
976 (finish-output *error-output*)))
977 ;; This HANDLER-CASE is here mostly to stop output immediately
978 ;; (and fall through to QUIT) when there's an I/O error. Thus,
979 ;; when we're run under a shell script or something, we can die
980 ;; cleanly when the script dies (and our pipes are cut), instead
981 ;; of falling into ldb or something messy like that. Similarly, we
982 ;; can terminate cleanly even if BACKTRACE dies because of bugs in
983 ;; user PRINT-OBJECT methods. Separate the error handling of the
984 ;; two phases to maximize the chance of emitting some useful
990 (format *error-output*
991 "~%unhandled condition in --disable-debugger mode, quitting~%")
992 (finish-output *error-output*)
995 ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
996 ;; fail when our output streams are blown away, as e.g. when
997 ;; we're running under a Unix shell script and it dies somehow
998 ;; (e.g. because of a SIGINT). In that case, we might as well
999 ;; just give it up for a bad job, and stop trying to notify
1000 ;; the user of anything.
1002 ;; Actually, the only way I've run across to exercise the
1003 ;; problem is to have more than one layer of shell script.
1004 ;; I have a shell script which does
1005 ;; time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
1006 ;; and the problem occurs when I interrupt this with Ctrl-C
1007 ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
1008 ;; I haven't figured out whether it's bash, time, tee, Linux, or
1009 ;; what that is responsible, but that it's possible at all
1010 ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
1012 (%primitive print backtrace-error-message))
1013 (failure-quit :abort t))))))
1015 (defvar *old-debugger-hook* nil)
1017 ;;; halt-on-failures and prompt-on-failures modes, suitable for
1018 ;;; noninteractive and interactive use respectively
1019 (defun disable-debugger ()
1020 "When invoked, this function will turn off both the SBCL debugger
1021 and LDB (the low-level debugger). See also ENABLE-DEBUGGER."
1022 ;; *DEBUG-IO* used to be set here to *ERROR-OUTPUT* which is sort
1023 ;; of unexpected but mostly harmless, but then ENABLE-DEBUGGER had
1024 ;; to set it to a suitable value again and be very careful,
1025 ;; especially if the user has also set it. -- MG 2005-07-15
1026 (unless (eq *invoke-debugger-hook* 'debugger-disabled-hook)
1027 (setf *old-debugger-hook* *invoke-debugger-hook*
1028 *invoke-debugger-hook* 'debugger-disabled-hook))
1029 ;; This is not inside the UNLESS to ensure that LDB is disabled
1030 ;; regardless of what the old value of *INVOKE-DEBUGGER-HOOK* was.
1031 ;; This might matter for example when restoring a core.
1032 (sb!alien:alien-funcall (sb!alien:extern-alien "disable_lossage_handler"
1033 (function sb!alien:void))))
1035 (defun enable-debugger ()
1036 "Restore the debugger if it has been turned off by DISABLE-DEBUGGER."
1037 (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
1038 (setf *invoke-debugger-hook* *old-debugger-hook*
1039 *old-debugger-hook* nil))
1040 (sb!alien:alien-funcall (sb!alien:extern-alien "enable_lossage_handler"
1041 (function sb!alien:void))))
1043 (defun show-restarts (restarts s)
1044 (cond ((null restarts)
1046 "~&(no restarts: If you didn't do this on purpose, ~
1047 please report it as a bug.)~%"))
1049 (format s "~&restarts (invokable by number or by ~
1050 possibly-abbreviated name):~%")
1054 (dolist (restart restarts)
1055 (let ((name (restart-name restart)))
1057 (let ((len (length (princ-to-string name))))
1058 (when (> len max-name-len)
1059 (setf max-name-len len))))))
1060 (unless (zerop max-name-len)
1061 (incf max-name-len 3))
1062 (dolist (restart restarts)
1063 (let ((name (restart-name restart)))
1064 ;; FIXME: maybe it would be better to display later names
1065 ;; in parens instead of brakets, not just omit them fully.
1066 ;; Call BREAK, call BREAK in the debugger, and tell me
1067 ;; it's not confusing looking. --NS 20050310
1068 (cond ((member name names-used)
1069 (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
1071 (format s "~& ~2D: [~VA] ~A~%"
1072 count (- max-name-len 3) name restart)
1073 (push name names-used))))
1076 (defvar *debug-loop-fun* #'debug-loop-fun
1077 "a function taking no parameters that starts the low-level debug loop")
1079 ;;; When the debugger is invoked due to a stepper condition, we don't
1080 ;;; want to print the current frame before the first prompt for aesthetic
1082 (defvar *suppress-frame-print* nil)
1084 ;;; This calls DEBUG-LOOP, performing some simple initializations
1085 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
1086 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
1087 ;;; to get into a debug prompt as quickly as possible with as little
1088 ;;; risk as possible for stepping on whatever is causing recursive
1090 (defun internal-debug ()
1091 (let ((*in-the-debugger* t)
1092 (*read-suppress* nil))
1093 (unless (typep *debug-condition* 'step-condition)
1094 (clear-input *debug-io*))
1095 (let ((*suppress-frame-print* (typep *debug-condition* 'step-condition)))
1096 (funcall *debug-loop-fun*))))
1100 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
1101 ;;; was motivated by desire to play nicely with ILISP.
1102 (defvar *flush-debug-errors* nil
1104 "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
1105 executing in the debugger.")
1107 (defun debug-read (stream eof-restart)
1108 (declare (type stream stream))
1109 (let* ((eof-marker (cons nil nil))
1110 (form (read stream nil eof-marker)))
1111 (if (eq form eof-marker)
1112 (invoke-restart eof-restart)
1115 (defun debug-loop-fun ()
1116 (let* ((*debug-command-level* (1+ *debug-command-level*))
1117 (*real-stack-top* (sb!di:top-frame))
1118 (*stack-top* (or *stack-top-hint* *real-stack-top*))
1119 (*stack-top-hint* nil)
1120 (*current-frame* *stack-top*))
1121 (handler-bind ((sb!di:debug-condition
1123 (princ condition *debug-io*)
1124 (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
1125 (throw 'debug-loop-catcher nil))))
1126 (cond (*suppress-frame-print*
1127 (setf *suppress-frame-print* nil))
1130 (print-frame-call *current-frame* *debug-io* :print-frame-source t)))
1132 (catch 'debug-loop-catcher
1133 (handler-bind ((error (lambda (condition)
1134 (when *flush-debug-errors*
1135 (clear-input *debug-io*)
1136 (princ condition *debug-io*)
1138 "~&error flushed (because ~
1140 '*flush-debug-errors*)
1141 (/show0 "throwing DEBUG-LOOP-CATCHER")
1142 (throw 'debug-loop-catcher nil)))))
1143 ;; We have to bind LEVEL for the restart function created
1144 ;; by WITH-SIMPLE-RESTART, and we need the explicit ABORT
1145 ;; restart that exists now so that EOF from read can drop
1146 ;; one debugger level.
1147 (let ((level *debug-command-level*)
1148 (restart-commands (make-restart-commands))
1149 (abort-restart-for-eof (find-restart 'abort)))
1150 (flush-standard-output-streams)
1151 (debug-prompt *debug-io*)
1152 (force-output *debug-io*)
1153 (with-simple-restart (abort
1154 "~@<Reduce debugger level (to debug level ~W).~@:>"
1156 (let* ((exp (debug-read *debug-io* abort-restart-for-eof))
1157 (cmd-fun (debug-command-p exp restart-commands)))
1158 (cond ((not cmd-fun)
1159 (debug-eval-print exp))
1162 "~&Your command, ~S, is ambiguous:~%"
1164 (dolist (ele cmd-fun)
1165 (format *debug-io* " ~A~%" ele)))
1167 (funcall cmd-fun))))))))))))
1169 (defvar *auto-eval-in-frame* t
1171 "When set (the default), evaluations in the debugger's command loop occur
1172 relative to the current frame's environment without the need of debugger
1173 forms that explicitly control this kind of evaluation.")
1175 (defun debug-eval (expr)
1176 (cond ((not (and (fboundp 'compile) *auto-eval-in-frame*))
1178 ((frame-has-debug-vars-p *current-frame*)
1179 (sb!di:eval-in-frame *current-frame* expr))
1181 (format *debug-io* "; No debug variables for current frame: ~
1182 using EVAL instead of EVAL-IN-FRAME.~%")
1185 (defun debug-eval-print (expr)
1186 (/noshow "entering DEBUG-EVAL-PRINT" expr)
1187 (let ((values (multiple-value-list
1188 (interactive-eval expr :eval #'debug-eval))))
1189 (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
1190 (dolist (value values)
1191 (fresh-line *debug-io*)
1192 (prin1 value *debug-io*)))
1193 (force-output *debug-io*))
1195 ;;;; debug loop functions
1197 ;;; These commands are functions, not really commands, so that users
1198 ;;; can get their hands on the values returned.
1200 (eval-when (:execute :compile-toplevel)
1202 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
1203 `(let* ((temp (etypecase name
1204 (symbol (sb!di:debug-fun-symbol-vars
1205 (sb!di:frame-debug-fun *current-frame*)
1207 (simple-string (sb!di:ambiguous-debug-vars
1208 (sb!di:frame-debug-fun *current-frame*)
1210 (location (sb!di:frame-code-location *current-frame*))
1211 ;; Let's only deal with valid variables.
1212 (vars (remove-if-not (lambda (v)
1213 (eq (sb!di:debug-var-validity v location)
1216 (declare (list vars))
1218 (error "No known valid variables match ~S." name))
1219 ((= (length vars) 1)
1222 '(sb!di:debug-var-value (car vars) *current-frame*))
1224 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1227 ;; Since we have more than one, first see whether we have
1228 ;; any variables that exactly match the specification.
1229 (let* ((name (etypecase name
1230 (symbol (symbol-name name))
1231 (simple-string name)))
1232 ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
1234 (exact (remove-if-not (lambda (v)
1235 (string= (sb!di:debug-var-symbol-name v)
1238 (vars (or exact vars)))
1239 (declare (simple-string name)
1242 ;; Check now for only having one variable.
1243 ((= (length vars) 1)
1246 '(sb!di:debug-var-value (car vars) *current-frame*))
1248 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1250 ;; If there weren't any exact matches, flame about
1251 ;; ambiguity unless all the variables have the same
1256 (string= (sb!di:debug-var-symbol-name v)
1257 (sb!di:debug-var-symbol-name (car vars))))
1259 (error "specification ambiguous:~%~{ ~A~%~}"
1260 (mapcar #'sb!di:debug-var-symbol-name
1262 vars :test #'string=
1263 :key #'sb!di:debug-var-symbol-name))))
1264 ;; All names are the same, so see whether the user
1265 ;; ID'ed one of them.
1267 (let ((v (find id vars :key #'sb!di:debug-var-id)))
1270 "invalid variable ID, ~W: should have been one of ~S"
1272 (mapcar #'sb!di:debug-var-id vars)))
1275 '(sb!di:debug-var-value v *current-frame*))
1277 `(setf (sb!di:debug-var-value v *current-frame*)
1280 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
1282 (mapcar #'sb!di:debug-var-id vars)))))))))
1286 ;;; FIXME: This doesn't work. It would be real nice we could make it
1287 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
1288 (defun var (name &optional (id 0 id-supplied))
1290 "Return a variable's value if possible. NAME is a simple-string or symbol.
1291 If it is a simple-string, it is an initial substring of the variable's name.
1292 If name is a symbol, it has the same name and package as the variable whose
1293 value this function returns. If the symbol is uninterned, then the variable
1294 has the same name as the symbol, but it has no package.
1296 If name is the initial substring of variables with different names, then
1297 this return no values after displaying the ambiguous names. If name
1298 determines multiple variables with the same name, then you must use the
1299 optional id argument to specify which one you want. If you left id
1300 unspecified, then this returns no values after displaying the distinguishing
1303 The result of this function is limited to the availability of variable
1304 information. This is SETF'able."
1305 (define-var-operation :ref))
1306 (defun (setf var) (value name &optional (id 0 id-supplied))
1307 (define-var-operation :set value))
1309 ;;; This returns the COUNT'th arg as the user sees it from args, the
1310 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
1311 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
1312 ;;; T. If this returns a keyword symbol or a value from a rest arg,
1313 ;;; then the second value is NIL.
1315 ;;; FIXME: There's probably some way to merge the code here with
1316 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1317 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1318 (declaim (ftype (function (index list)) nth-arg))
1319 (defun nth-arg (count args)
1321 (dolist (ele args (error "The argument specification ~S is out of range."
1323 (lambda-list-element-dispatch ele
1324 :required ((if (zerop n) (return (values ele t))))
1325 :optional ((if (zerop n) (return (values (second ele) t))))
1326 :keyword ((cond ((zerop n)
1327 (return (values (second ele) nil)))
1329 (return (values (third ele) t)))))
1330 :deleted ((if (zerop n) (return (values ele t))))
1331 :rest ((let ((var (second ele)))
1332 (lambda-var-dispatch var (sb!di:frame-code-location
1334 (error "unused &REST argument before n'th argument")
1336 (sb!di:debug-var-value var *current-frame*)
1338 "The argument specification ~S is out of range."
1341 (return-from nth-arg (values value nil))
1343 (error "invalid &REST argument before n'th argument")))))
1348 "Return the N'th argument's value if possible. Argument zero is the first
1349 argument in a frame's default printed representation. Count keyword/value
1350 pairs as separate arguments."
1351 (multiple-value-bind (var lambda-var-p)
1352 (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1353 (sb!di:frame-debug-fun *current-frame*))
1354 (sb!di:lambda-list-unavailable ()
1355 (error "No argument values are available."))))
1357 (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1358 (error "Unused arguments have no values.")
1359 (sb!di:debug-var-value var *current-frame*)
1360 (error "invalid argument value"))
1363 ;;;; machinery for definition of debug loop commands
1365 (defvar *debug-commands* nil)
1367 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1369 (defmacro !def-debug-command (name args &rest body)
1370 (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1372 (setf *debug-commands*
1373 (remove ,name *debug-commands* :key #'car :test #'string=))
1374 (defun ,fun-name ,args
1375 (unless *in-the-debugger*
1376 (error "invoking debugger command while outside the debugger"))
1378 (push (cons ,name #',fun-name) *debug-commands*)
1381 (defun !def-debug-command-alias (new-name existing-name)
1382 (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1383 (unless pair (error "unknown debug command name: ~S" existing-name))
1384 (push (cons new-name (cdr pair)) *debug-commands*))
1387 ;;; This takes a symbol and uses its name to find a debugger command,
1388 ;;; using initial substring matching. It returns the command function
1389 ;;; if form identifies only one command, but if form is ambiguous,
1390 ;;; this returns a list of the command names. If there are no matches,
1391 ;;; this returns nil. Whenever the loop that looks for a set of
1392 ;;; possibilities encounters an exact name match, we return that
1393 ;;; command function immediately.
1394 (defun debug-command-p (form &optional other-commands)
1395 (if (or (symbolp form) (integerp form))
1399 (format nil "~W" form)))
1402 (declare (simple-string name)
1406 ;; Find matching commands, punting if exact match.
1407 (flet ((match-command (ele)
1408 (let* ((str (car ele))
1409 (str-len (length str)))
1410 (declare (simple-string str)
1412 (cond ((< str-len len))
1414 (when (string= name str :end1 len :end2 len)
1415 (return-from debug-command-p (cdr ele))))
1416 ((string= name str :end1 len :end2 len)
1418 (mapc #'match-command *debug-commands*)
1419 (mapc #'match-command other-commands))
1421 ;; Return the right value.
1422 (cond ((not res) nil)
1425 (t ; Just return the names.
1426 (do ((cmds res (cdr cmds)))
1428 (setf (car cmds) (caar cmds))))))))
1430 ;;; Return a list of debug commands (in the same format as
1431 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1433 ;;; Two commands are made for each restart: one for the number, and
1434 ;;; one for the restart name (unless it's been shadowed by an earlier
1435 ;;; restart of the same name, or it is NIL).
1436 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1438 (num 0)) ; better be the same as show-restarts!
1439 (dolist (restart restarts)
1440 (let ((name (string (restart-name restart))))
1443 (/show0 "in restart-command closure, about to i-r-i")
1444 (invoke-restart-interactively restart))))
1445 (push (cons (prin1-to-string num) restart-fun) commands)
1446 (unless (or (null (restart-name restart))
1447 (find name commands :key #'car :test #'string=))
1448 (push (cons name restart-fun) commands))))
1452 ;;;; frame-changing commands
1454 (!def-debug-command "UP" ()
1455 (let ((next (sb!di:frame-up *current-frame*)))
1457 (setf *current-frame* next)
1458 (print-frame-call next *debug-io*))
1460 (format *debug-io* "~&Top of stack.")))))
1462 (!def-debug-command "DOWN" ()
1463 (let ((next (sb!di:frame-down *current-frame*)))
1465 (setf *current-frame* next)
1466 (print-frame-call next *debug-io*))
1468 (format *debug-io* "~&Bottom of stack.")))))
1470 (!def-debug-command-alias "D" "DOWN")
1472 (!def-debug-command "BOTTOM" ()
1473 (do ((prev *current-frame* lead)
1474 (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1476 (setf *current-frame* prev)
1477 (print-frame-call prev *debug-io*))))
1479 (!def-debug-command-alias "B" "BOTTOM")
1481 (!def-debug-command "FRAME" (&optional
1482 (n (read-prompting-maybe "frame number: ")))
1483 (setf *current-frame*
1484 (multiple-value-bind (next-frame-fun limit-string)
1485 (if (< n (sb!di:frame-number *current-frame*))
1486 (values #'sb!di:frame-up "top")
1487 (values #'sb!di:frame-down "bottom"))
1488 (do ((frame *current-frame*))
1489 ((= n (sb!di:frame-number frame))
1491 (let ((next-frame (funcall next-frame-fun frame)))
1493 (setf frame next-frame))
1496 "The ~A of the stack was encountered.~%"
1498 (return frame)))))))
1499 (print-frame-call *current-frame* *debug-io*))
1501 (!def-debug-command-alias "F" "FRAME")
1503 ;;;; commands for entering and leaving the debugger
1505 (!def-debug-command "TOPLEVEL" ()
1506 (throw 'toplevel-catcher nil))
1509 (!def-debug-command-alias "TOP" "TOPLEVEL")
1511 (!def-debug-command "RESTART" ()
1512 (/show0 "doing RESTART debug-command")
1513 (let ((num (read-if-available :prompt)))
1514 (when (eq num :prompt)
1515 (show-restarts *debug-restarts* *debug-io*)
1516 (write-string "restart: " *debug-io*)
1517 (force-output *debug-io*)
1518 (setf num (read *debug-io*)))
1519 (let ((restart (typecase num
1521 (nth num *debug-restarts*))
1523 (find num *debug-restarts* :key #'restart-name
1524 :test (lambda (sym1 sym2)
1525 (string= (symbol-name sym1)
1526 (symbol-name sym2)))))
1528 (format *debug-io* "~S is invalid as a restart name.~%"
1530 (return-from restart-debug-command nil)))))
1531 (/show0 "got RESTART")
1533 (invoke-restart-interactively restart)
1534 (princ "There is no such restart." *debug-io*)))))
1536 ;;;; information commands
1538 (!def-debug-command "HELP" ()
1539 ;; CMU CL had a little toy pager here, but "if you aren't running
1540 ;; ILISP (or a smart windowing system, or something) you deserve to
1541 ;; lose", so we've dropped it in SBCL. However, in case some
1542 ;; desperate holdout is running this on a dumb terminal somewhere,
1543 ;; we tell him where to find the message stored as a string.
1545 "~&~A~2%(The HELP string is stored in ~S.)~%"
1547 '*debug-help-string*))
1549 (!def-debug-command-alias "?" "HELP")
1551 (!def-debug-command "ERROR" ()
1552 (format *debug-io* "~A~%" *debug-condition*)
1553 (show-restarts *debug-restarts* *debug-io*))
1555 (!def-debug-command "BACKTRACE" ()
1556 (print-backtrace :count (read-if-available most-positive-fixnum)))
1558 (!def-debug-command "PRINT" ()
1559 (print-frame-call *current-frame* *debug-io*))
1561 (!def-debug-command-alias "P" "PRINT")
1563 (!def-debug-command "LIST-LOCALS" ()
1564 (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1565 (if (sb!di:debug-var-info-available d-fun)
1566 (let ((*standard-output* *debug-io*)
1567 (location (sb!di:frame-code-location *current-frame*))
1568 (prefix (read-if-available nil))
1573 (dolist (v (sb!di:ambiguous-debug-vars
1575 (if prefix (string prefix) "")))
1577 (when (eq (sb!di:debug-var-validity v location) :valid)
1578 (setf any-valid-p t)
1579 (case (sb!di::debug-var-info v)
1581 (setf more-context (sb!di:debug-var-value v *current-frame*)))
1583 (setf more-count (sb!di:debug-var-value v *current-frame*))))
1584 (format *debug-io* "~S~:[#~W~;~*~] = ~S~%"
1585 (sb!di:debug-var-symbol v)
1586 (zerop (sb!di:debug-var-id v))
1587 (sb!di:debug-var-id v)
1588 (sb!di:debug-var-value v *current-frame*))))
1589 (when (and more-context more-count)
1590 (format *debug-io* "~S = ~S~%"
1592 (multiple-value-list (sb!c:%more-arg-values more-context 0 more-count))))
1596 "There are no local variables ~@[starting with ~A ~]~
1601 "All variables ~@[starting with ~A ~]currently ~
1602 have invalid values."
1604 (write-line "There is no variable information available."
1607 (!def-debug-command-alias "L" "LIST-LOCALS")
1609 (!def-debug-command "SOURCE" ()
1610 (print (code-location-source-form (sb!di:frame-code-location *current-frame*)
1611 (read-if-available 0))
1614 ;;;; source location printing
1616 ;;; Stuff to clean up before saving a core
1617 (defun debug-deinit ()
1618 ;; Nothing to do right now. Once there was, maybe once there
1622 (defun code-location-source-form (location context &optional (errorp t))
1623 (let* ((start-location (maybe-block-start-location location))
1624 (form-num (sb!di:code-location-form-number start-location)))
1625 (multiple-value-bind (translations form)
1626 (sb!di:get-toplevel-form start-location)
1627 (cond ((< form-num (length translations))
1628 (sb!di:source-path-context form
1629 (svref translations form-num)
1632 (funcall (if errorp #'error #'warn)
1633 "~@<Bogus form-number: the source file has ~
1634 probably changed too much to cope with.~:@>"))))))
1637 ;;; start single-stepping
1638 (!def-debug-command "START" ()
1639 (if (typep *debug-condition* 'step-condition)
1640 (format *debug-io* "~&Already single-stepping.~%")
1641 (let ((restart (find-restart 'continue *debug-condition*)))
1643 (sb!impl::enable-stepping)
1644 (invoke-restart restart))
1646 (format *debug-io* "~&Non-continuable error, cannot start stepping.~%"))))))
1648 (defmacro def-step-command (command-name restart-name)
1649 `(!def-debug-command ,command-name ()
1650 (if (typep *debug-condition* 'step-condition)
1651 (let ((restart (find-restart ',restart-name *debug-condition*)))
1653 (invoke-restart restart))
1654 (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%"))))
1656 (def-step-command "STEP" step-into)
1657 (def-step-command "NEXT" step-next)
1658 (def-step-command "STOP" step-continue)
1660 (!def-debug-command-alias "S" "STEP")
1661 (!def-debug-command-alias "N" "NEXT")
1663 (!def-debug-command "OUT" ()
1664 (if (typep *debug-condition* 'step-condition)
1665 (if sb!impl::*step-out*
1666 (let ((restart (find-restart 'step-out *debug-condition*)))
1668 (invoke-restart restart))
1669 (format *debug-io* "~&OUT can only be used step out of frames that were originally stepped into with STEP.~%"))
1670 (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%")))
1672 ;;; miscellaneous commands
1674 (!def-debug-command "DESCRIBE" ()
1675 (let* ((curloc (sb!di:frame-code-location *current-frame*))
1676 (debug-fun (sb!di:code-location-debug-fun curloc))
1677 (function (sb!di:debug-fun-fun debug-fun)))
1680 (format *debug-io* "can't figure out the function for this frame"))))
1682 (!def-debug-command "SLURP" ()
1683 (loop while (read-char-no-hang *standard-input*)))
1685 ;;; RETURN-FROM-FRAME and RESTART-FRAME
1687 (defun unwind-to-frame-and-call (frame thunk)
1688 #!+unwind-to-frame-and-call-vop
1689 (flet ((sap-int/fixnum (sap)
1690 ;; On unithreaded X86 *BINDING-STACK-POINTER* and
1691 ;; *CURRENT-CATCH-BLOCK* are negative, so we need to jump through
1692 ;; some hoops to make these calculated values negative too.
1693 (ash (truly-the (signed-byte #.sb!vm:n-word-bits)
1695 (- sb!vm::n-fixnum-tag-bits))))
1696 ;; To properly unwind the stack, we need three pieces of information:
1697 ;; * The unwind block that should be active after the unwind
1698 ;; * The catch block that should be active after the unwind
1699 ;; * The values that the binding stack pointer should have after the
1701 (let* ((block (sap-int/fixnum (find-enclosing-catch-block frame)))
1702 (unbind-to (sap-int/fixnum (find-binding-stack-pointer frame))))
1703 ;; This VOP will run the neccessary cleanup forms, reset the fp, and
1704 ;; then call the supplied function.
1705 (sb!vm::%primitive sb!vm::unwind-to-frame-and-call
1706 (sb!di::frame-pointer frame)
1707 (find-enclosing-uwp frame)
1709 ;; Before calling the user-specified
1710 ;; function, we need to restore the binding
1711 ;; stack and the catch block. The unwind block
1712 ;; is taken care of by the VOP.
1713 (sb!vm::%primitive sb!vm::unbind-to-here
1715 (setf sb!vm::*current-catch-block* block)
1717 #!-unwind-to-frame-and-call-vop
1718 (let ((tag (gensym)))
1719 (sb!di:replace-frame-catch-tag frame
1720 'sb!c:debug-catch-tag
1724 (defun find-binding-stack-pointer (frame)
1725 #!-stack-grows-downward-not-upward
1726 (declare (ignore frame))
1727 #!-stack-grows-downward-not-upward
1728 (error "Not implemented on this architecture")
1729 #!+stack-grows-downward-not-upward
1730 (let ((bsp (sb!vm::binding-stack-pointer-sap))
1732 (fp (sb!di::frame-pointer frame))
1733 (start (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1734 (ash sb!vm:*binding-stack-start*
1735 sb!vm:n-fixnum-tag-bits)))))
1736 ;; Walk the binding stack looking for an entry where the symbol is
1737 ;; an unbound-symbol marker and the value is equal to the frame
1738 ;; pointer. These entries are inserted into the stack by the
1739 ;; BIND-SENTINEL VOP and removed by UNBIND-SENTINEL (inserted into
1740 ;; the function during IR2). If an entry wasn't found, the
1741 ;; function that the frame corresponds to wasn't compiled with a
1742 ;; high enough debug setting, and can't be restarted / returned
1744 (loop until (sap= bsp start)
1747 (- (* sb!vm:binding-size sb!vm:n-word-bytes))))
1748 (let ((symbol (sap-ref-word bsp (* sb!vm:binding-symbol-slot
1749 sb!vm:n-word-bytes)))
1750 (value (sap-ref-sap bsp (* sb!vm:binding-value-slot
1751 sb!vm:n-word-bytes))))
1752 (when (eql symbol sb!vm:unbound-marker-widetag)
1753 (when (sap= value fp)
1754 (setf unbind-to bsp))))))
1757 (defun find-enclosing-catch-block (frame)
1758 ;; Walk the catch block chain looking for the first entry with an address
1759 ;; higher than the pointer for FRAME or a null pointer.
1760 (let* ((frame-pointer (sb!di::frame-pointer frame))
1761 (current-block (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1762 (ash sb!vm::*current-catch-block*
1763 sb!vm:n-fixnum-tag-bits))))
1764 (enclosing-block (loop for block = current-block
1765 then (sap-ref-sap block
1766 (* sb!vm:catch-block-previous-catch-slot
1767 sb!vm::n-word-bytes))
1768 when (or (zerop (sap-int block))
1769 (sap> block frame-pointer))
1773 (defun find-enclosing-uwp (frame)
1774 ;; Walk the UWP chain looking for the first entry with an address
1775 ;; higher than the pointer for FRAME or a null pointer.
1776 (let* ((frame-pointer (sb!di::frame-pointer frame))
1777 (current-uwp (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1778 (ash sb!vm::*current-unwind-protect-block*
1779 sb!vm:n-fixnum-tag-bits))))
1780 (enclosing-uwp (loop for uwp-block = current-uwp
1781 then (sap-ref-sap uwp-block
1782 sb!vm:unwind-block-current-uwp-slot)
1783 when (or (zerop (sap-int uwp-block))
1784 (sap> uwp-block frame-pointer))
1788 (!def-debug-command "RETURN" (&optional
1789 (return (read-prompting-maybe
1791 (if (frame-has-debug-tag-p *current-frame*)
1792 (let* ((code-location (sb!di:frame-code-location *current-frame*))
1793 (values (multiple-value-list
1794 (funcall (sb!di:preprocess-for-eval return code-location)
1796 (unwind-to-frame-and-call *current-frame* (lambda ()
1797 (values-list values))))
1799 "~@<can't find a tag for this frame ~
1800 ~2I~_(hint: try increasing the DEBUG optimization quality ~
1801 and recompiling)~:@>")))
1803 (!def-debug-command "RESTART-FRAME" ()
1804 (if (frame-has-debug-tag-p *current-frame*)
1805 (multiple-value-bind (fname args) (frame-call *current-frame*)
1806 (multiple-value-bind (fun arglist ok)
1807 (if (and (legal-fun-name-p fname) (fboundp fname))
1808 (values (fdefinition fname) args t)
1809 (values (sb!di:debug-fun-fun (sb!di:frame-debug-fun *current-frame*))
1810 (frame-args-as-list *current-frame*)
1814 (y-or-n-p "~@<No global function for the frame, but we ~
1815 do have access to a function object that we ~
1816 can try to call -- but if it is normally part ~
1817 of a closure, then this is NOT going to end well.~_~_~
1818 Try it anyways?~:@>")))
1819 (unwind-to-frame-and-call *current-frame*
1822 (declare (optimize (debug 0)))
1823 (apply fun arglist))))
1825 "Can't restart ~S: no function for frame."
1828 "~@<Can't restart ~S: tag not found. ~
1829 ~2I~_(hint: try increasing the DEBUG optimization quality ~
1830 and recompiling)~:@>"
1833 (defun frame-has-debug-tag-p (frame)
1834 #!+unwind-to-frame-and-call-vop
1835 (not (null (find-binding-stack-pointer frame)))
1836 #!-unwind-to-frame-and-call-vop
1837 (find 'sb!c:debug-catch-tag (sb!di::frame-catches frame) :key #'car))
1839 (defun frame-has-debug-vars-p (frame)
1840 (sb!di:debug-var-info-available
1841 (sb!di:code-location-debug-fun
1842 (sb!di:frame-code-location frame))))
1844 ;; Hack: ensure that *U-T-F-F* has a tls index.
1845 #!+unwind-to-frame-and-call-vop
1846 (let ((sb!vm::*unwind-to-frame-function* (lambda ()))))
1849 ;;;; debug loop command utilities
1851 (defun read-prompting-maybe (prompt)
1852 (unless (sb!int:listen-skip-whitespace *debug-io*)
1853 (princ prompt *debug-io*)
1854 (force-output *debug-io*))
1857 (defun read-if-available (default)
1858 (if (sb!int:listen-skip-whitespace *debug-io*)