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
66 ;;; stack top by the debugger.
67 (defvar *stack-top-hint* nil)
69 (defvar *stack-top* nil)
70 (defvar *real-stack-top* nil)
72 (defvar *current-frame* nil)
74 ;;; Beginner-oriented help messages are important because you end up
75 ;;; in the debugger whenever something bad happens, or if you try to
76 ;;; get out of the system with Ctrl-C or (EXIT) or EXIT or whatever.
77 ;;; But after memorizing them the wasted screen space gets annoying..
78 (defvar *debug-beginner-help-p* t
79 "Should the debugger display beginner-oriented help messages?")
81 (defun debug-prompt (stream)
82 (sb!thread::get-foreground)
85 (sb!di:frame-number *current-frame*)
86 (> *debug-command-level* 1)
87 *debug-command-level*))
89 (defparameter *debug-help-string*
90 "The debug prompt is square brackets, with number(s) indicating the current
91 control stack level and, if you've entered the debugger recursively, how
92 deeply recursed you are.
93 Any command -- including the name of a restart -- may be uniquely abbreviated.
94 The debugger rebinds various special variables for controlling i/o, sometimes
95 to defaults (much like WITH-STANDARD-IO-SYNTAX does) and sometimes to
96 its own special values, based on SB-EXT:*DEBUG-PRINT-VARIABLE-ALIST*.
97 Debug commands do not affect *, //, and similar variables, but evaluation in
98 the debug loop does affect these variables.
99 SB-DEBUG:*FLUSH-DEBUG-ERRORS* controls whether errors at the debug prompt
100 drop you deeper into the debugger. The default NIL allows recursive entry
103 Getting in and out of the debugger:
104 TOPLEVEL, TOP exits debugger and returns to top level REPL
105 RESTART invokes restart numbered as shown (prompt if not given).
106 ERROR prints the error condition and restart cases.
108 The number of any restart, or its name, or a unique abbreviation for its
109 name, is a valid command, and is the same as using RESTART to invoke
113 UP up frame DOWN down frame
114 BOTTOM bottom frame FRAME n frame n (n=0 for top frame)
117 BACKTRACE [n] shows n frames going down the stack.
118 LIST-LOCALS, L lists locals in current frame.
119 PRINT, P displays function call for current frame.
120 SOURCE [n] displays frame's source form with n levels of enclosing forms.
123 START Selects the CONTINUE restart if one exists and starts
124 single-stepping. Single stepping affects only code compiled with
125 under high DEBUG optimization quality. See User Manual for details.
126 STEP Steps into the current form.
127 NEXT Steps over the current form.
128 OUT Stops stepping temporarily, but resumes it when the topmost frame that
129 was stepped into returns.
130 STOP Stops single-stepping.
132 Function and macro commands:
134 Return the n'th argument in the current frame.
135 (SB-DEBUG:VAR string-or-symbol [id])
136 Returns the value of the specified variable in the current frame.
140 Return the values resulting from evaluation of expr from the
141 current frame, if this frame was compiled with a sufficiently high
142 DEBUG optimization quality.
145 Restart execution of the current frame, if this frame is for a
146 global function which was compiled with a sufficiently high
147 DEBUG optimization quality.
150 Discard all pending input on *STANDARD-INPUT*. (This can be
151 useful when the debugger was invoked to handle an error in
152 deeply nested input syntax, and now the reader is confused.)")
155 ;;; If LOC is an unknown location, then try to find the block start
156 ;;; location. Used by source printing to some information instead of
157 ;;; none for the user.
158 (defun maybe-block-start-location (loc)
159 (if (sb!di:code-location-unknown-p loc)
160 (let* ((block (sb!di:code-location-debug-block loc))
161 (start (sb!di:do-debug-block-locations (loc block)
163 (cond ((and (not (sb!di:debug-block-elsewhere-p block))
165 (format *debug-io* "~%unknown location: using block start~%")
173 (defun map-backtrace (thunk &key (start 0) (count most-positive-fixnum))
177 for frame = (if *in-the-debugger*
180 then (sb!di:frame-down frame)
182 when (<= start index) do
183 (if (minusp (decf count))
185 (setf result (funcall thunk frame)))
186 finally (return result)))
188 (defun backtrace (&optional (count most-positive-fixnum) (stream *debug-io*))
190 "Show a listing of the call stack going down from the current frame.
191 In the debugger, the current frame is indicated by the prompt. COUNT
192 is how many frames to show."
194 (map-backtrace (lambda (frame)
195 (print-frame-call frame stream :number t))
200 (defun backtrace-as-list (&optional (count most-positive-fixnum))
202 "Return a list representing the current BACKTRACE.
204 Objects in the backtrace with dynamic-extent allocation by the current
205 thread are represented by substitutes to avoid references to them from
206 leaking outside their legal extent."
207 (let ((reversed-result (list)))
208 (map-backtrace (lambda (frame)
209 (let ((frame-list (frame-call-as-list frame)))
210 (if (listp (cdr frame-list))
211 (push (mapcar #'replace-dynamic-extent-object frame-list)
213 (push frame-list reversed-result))))
215 (nreverse reversed-result)))
217 (defun frame-call-as-list (frame)
218 (multiple-value-bind (name args) (frame-call frame)
221 (defun replace-dynamic-extent-object (obj)
222 (if (stack-allocated-p obj)
223 (make-unprintable-object
225 (format nil "dynamic-extent: ~S" obj)
227 "error printing dynamic-extent object")))
230 (defun stack-allocated-p (obj)
231 "Returns T if OBJ is allocated on the stack of the current
232 thread, NIL otherwise."
233 (with-pinned-objects (obj)
234 (let ((sap (int-sap (get-lisp-obj-address obj))))
235 (when (sb!vm:control-stack-pointer-valid-p sap nil)
240 (eval-when (:compile-toplevel :execute)
242 ;;; This is a convenient way to express what to do for each type of
243 ;;; lambda-list element.
244 (sb!xc:defmacro lambda-list-element-dispatch (element
255 (ecase (car ,element)
256 (:optional ,@optional)
258 (:keyword ,@keyword)))
260 (aver (eq ,element :deleted))
263 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
264 (let ((var (gensym)))
265 `(let ((,var ,variable))
266 (cond ((eq ,var :deleted) ,deleted)
267 ((eq (sb!di:debug-var-validity ,var ,location) :valid)
273 ;;; Extract the function argument values for a debug frame.
274 (defun map-frame-args (thunk frame)
275 (let ((debug-fun (sb!di:frame-debug-fun frame)))
276 (dolist (element (sb!di:debug-fun-lambda-list debug-fun))
277 (funcall thunk element))))
279 (defun frame-args-as-list (frame)
281 (let ((location (sb!di:frame-code-location frame))
282 (reversed-result nil))
286 (lambda-list-element-dispatch element
287 :required ((push (frame-call-arg element location frame) reversed-result))
288 :optional ((push (frame-call-arg (second element) location frame)
290 :keyword ((push (second element) reversed-result)
291 (push (frame-call-arg (third element) location frame)
293 :deleted ((push (frame-call-arg element location frame) reversed-result))
294 :rest ((lambda-var-dispatch (second element) location
297 (setf reversed-result
298 (append (reverse (sb!di:debug-var-value
299 (second element) frame))
301 (return-from enumerating))
302 (push (make-unprintable-object
303 "unavailable &REST argument")
306 (nreverse reversed-result))
307 (sb!di:lambda-list-unavailable ()
308 (make-unprintable-object "unavailable lambda list"))))
310 (defvar *show-entry-point-details* nil)
312 (defun clean-xep (name args)
313 (values (second name)
315 (let ((count (first args))
316 (real-args (rest args)))
319 (min count (length real-args)))
323 (defun clean-&more-processor (name args)
324 (values (second name)
326 (let* ((more (last args 2))
327 (context (first more))
328 (count (second more)))
333 (sb!c:%more-arg-values context 0 count))
335 (make-unprintable-object "more unavailable arguments")))))
338 (defun frame-call (frame)
339 (labels ((clean-name-and-args (name args)
340 (if (and (consp name) (not *show-entry-point-details*))
341 ;; FIXME: do we need to deal with
342 ;; HAIRY-FUNCTION-ENTRY here? I can't make it or
343 ;; &AUX-BINDINGS appear in backtraces, so they are
344 ;; left alone for now. --NS 2005-02-28
347 ;; The name of an evaluator thunk contains
348 ;; the source context -- but that makes for a
349 ;; confusing frame name, since it can look like an
350 ;; EVAL call with a bogus argument.
351 (values '#:eval-thunk nil))
352 ((sb!c::xep sb!c::tl-xep)
353 (clean-xep name args))
354 ((sb!c::&more-processor)
355 (clean-&more-processor name args))
356 ((sb!c::hairy-arg-processor
357 sb!c::varargs-entry sb!c::&optional-processor)
358 (clean-name-and-args (second name) args))
361 (values name args))))
362 (let ((debug-fun (sb!di:frame-debug-fun frame)))
363 (multiple-value-bind (name args)
364 (clean-name-and-args (sb!di:debug-fun-name debug-fun)
365 (frame-args-as-list frame))
366 (values name args (sb!di:debug-fun-kind debug-fun))))))
368 (defun ensure-printable-object (object)
370 (with-open-stream (out (make-broadcast-stream))
374 (declare (ignore cond))
375 (make-unprintable-object "error printing object"))))
377 (defun frame-call-arg (var location frame)
378 (lambda-var-dispatch var location
379 (make-unprintable-object "unused argument")
380 (sb!di:debug-var-value var frame)
381 (make-unprintable-object "unavailable argument")))
383 ;;; Prints a representation of the function call causing FRAME to
384 ;;; exist. VERBOSITY indicates the level of information to output;
385 ;;; zero indicates just printing the DEBUG-FUN's name, and one
386 ;;; indicates displaying call-like, one-liner format with argument
388 (defun print-frame-call (frame stream &key (verbosity 1) (number nil))
390 (format stream "~&~S: " (sb!di:frame-number frame)))
391 (if (zerop verbosity)
392 (let ((*print-readably* nil))
393 (prin1 frame stream))
394 (multiple-value-bind (name args kind) (frame-call frame)
395 (pprint-logical-block (stream nil :prefix "(" :suffix ")")
396 ;; Since we go to some trouble to make nice informative function
397 ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
398 ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
399 ;; For the function arguments, we can just print normally.
400 (let ((*print-length* nil)
402 (prin1 (ensure-printable-object name) stream))
403 ;; If we hit a &REST arg, then print as many of the values as
404 ;; possible, punting the loop over lambda-list variables since any
405 ;; other arguments will be in the &REST arg's list of values.
406 (let ((print-args (ensure-printable-object args))
407 ;; Special case *PRINT-PRETTY* for eval frames: if
408 ;; *PRINT-LINES* is 1, turn off pretty-printing.
410 (if (and (eql 1 *print-lines*)
411 (member name '(eval simple-eval-in-lexenv)))
414 (if (listp print-args)
415 (format stream "~{ ~_~S~}" print-args)
416 (format stream " ~S" print-args))))
418 (format stream "[~S]" kind))))
419 (when (>= verbosity 2)
420 (let ((loc (sb!di:frame-code-location frame)))
423 ;; FIXME: Is this call really necessary here? If it is,
424 ;; then the reason for it should be unobscured.
425 (sb!di:code-location-debug-block loc)
426 (format stream "~%source: ")
427 (prin1 (code-location-source-form loc 0) stream))
428 (sb!di:debug-condition (ignore)
431 (format stream "~&error finding source: ~A" c))))))
435 (defvar *debugger-hook* nil
437 "This is either NIL or a function of two arguments, a condition and the value
438 of *DEBUGGER-HOOK*. This function can either handle the condition or return
439 which causes the standard debugger to execute. The system passes the value
440 of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
441 around the invocation.")
443 (defvar *invoke-debugger-hook* nil
445 "This is either NIL or a designator for a function of two arguments,
446 to be run when the debugger is about to be entered. The function is
447 run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
448 errors, and receives as arguments the condition that triggered
449 debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*
451 This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
452 In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
455 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
456 (defvar *debug-restarts*)
457 (defvar *debug-condition*)
458 (defvar *nested-debug-condition*)
460 ;;; Oh, what a tangled web we weave when we preserve backwards
461 ;;; compatibility with 1968-style use of global variables to control
462 ;;; per-stream i/o properties; there's really no way to get this
463 ;;; quite right, but we do what we can.
464 (defun funcall-with-debug-io-syntax (fun &rest rest)
465 (declare (type function fun))
466 ;; Try to force the other special variables into a useful state.
467 (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
468 ;; any default we might use is less useful than just reusing
469 ;; the global values.
470 (original-package *package*)
471 (original-print-pretty *print-pretty*))
472 (with-standard-io-syntax
474 (let (;; We want the printer and reader to be in a useful
475 ;; state, regardless of where the debugger was invoked
476 ;; in the program. WITH-STANDARD-IO-SYNTAX and
477 ;; WITH-SANE-IO-SYNTAX do much of what we want, but
478 ;; * It doesn't affect our internal special variables
479 ;; like *CURRENT-LEVEL-IN-PRINT*.
480 ;; * It isn't customizable.
481 ;; * It sets *PACKAGE* to COMMON-LISP-USER, which is not
482 ;; helpful behavior for a debugger.
483 ;; * There's no particularly good debugger default for
484 ;; *PRINT-PRETTY*, since T is usually what you want
485 ;; -- except absolutely not what you want when you're
486 ;; debugging failures in PRINT-OBJECT logic.
487 ;; We try to address all these issues with explicit
489 (sb!kernel:*current-level-in-print* 0)
490 (*package* original-package)
491 (*print-pretty* original-print-pretty)
492 ;; Clear the circularity machinery to try to to reduce the
493 ;; pain from sharing the circularity table across all
494 ;; streams; if these are not rebound here, then setting
495 ;; *PRINT-CIRCLE* within the debugger when debugging in a
496 ;; state where something circular was being printed (e.g.,
497 ;; because the debugger was entered on an error in a
498 ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
499 ;; here does seem somewhat ugly because it makes it more
500 ;; difficult to debug the printing-of-circularities code
501 ;; itself; however, as far as I (WHN, 2004-05-29) can see,
502 ;; that's almost entirely academic as long as there's one
503 ;; shared *C-H-T* for all streams (i.e., it's already
504 ;; unreasonably difficult to debug print-circle machinery
505 ;; given the buggy crosstalk between the debugger streams
506 ;; and the stream you're trying to watch), and any fix for
507 ;; that buggy arrangement will likely let this hack go away
509 (sb!impl::*circularity-hash-table* . nil)
510 (sb!impl::*circularity-counter* . nil)
511 (*readtable* *debug-readtable*))
513 ;; (Why NREVERSE? PROGV makes the later entries have
514 ;; precedence over the earlier entries.
515 ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
516 ;; expected that its earlier entries have precedence. And
517 ;; the earlier-has-precedence behavior is mostly more
518 ;; convenient, so that programmers can use PUSH or LIST* to
519 ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
520 (nreverse (mapcar #'car *debug-print-variable-alist*))
521 (nreverse (mapcar #'cdr *debug-print-variable-alist*))
522 (apply fun rest)))))))
524 ;;; This function is not inlined so it shows up in the backtrace; that
525 ;;; can be rather handy when one has to debug the interplay between
526 ;;; *INVOKE-DEBUGGER-HOOK* and *DEBUGGER-HOOK*.
527 (declaim (notinline run-hook))
528 (defun run-hook (variable condition)
529 (let ((old-hook (symbol-value variable)))
531 (progv (list variable) (list nil)
532 (funcall old-hook condition old-hook)))))
534 (defun invoke-debugger (condition)
536 "Enter the debugger."
538 ;; call *INVOKE-DEBUGGER-HOOK* first, so that *DEBUGGER-HOOK* is not
539 ;; called when the debugger is disabled
540 (run-hook '*invoke-debugger-hook* condition)
541 (run-hook '*debugger-hook* condition)
543 ;; We definitely want *PACKAGE* to be of valid type.
545 ;; Elsewhere in the system, we use the SANE-PACKAGE function for
546 ;; this, but here causing an exception just as we're trying to handle
547 ;; an exception would be confusing, so instead we use a special hack.
548 (unless (and (packagep *package*)
549 (package-name *package*))
550 (setf *package* (find-package :cl-user))
551 (format *error-output*
552 "The value of ~S was not an undeleted PACKAGE. It has been
554 '*package* *package*))
556 ;; Before we start our own output, finish any pending output.
557 ;; Otherwise, if the user tried to track the progress of his program
558 ;; using PRINT statements, he'd tend to lose the last line of output
559 ;; or so, which'd be confusing.
560 (flush-standard-output-streams)
562 (funcall-with-debug-io-syntax #'%invoke-debugger condition))
564 (defun %print-debugger-invocation-reason (condition stream)
565 (format stream "~2&")
566 ;; Note: Ordinarily it's only a matter of taste whether to use
567 ;; FORMAT "~<...~:>" or to use PPRINT-LOGICAL-BLOCK directly, but
568 ;; until bug 403 is fixed, PPRINT-LOGICAL-BLOCK (STREAM NIL) is
569 ;; definitely preferred, because the FORMAT alternative was acting odd.
570 (pprint-logical-block (stream nil)
572 "debugger invoked on a ~S~@[ in thread ~A~]: ~2I~_~A"
574 #!+sb-thread sb!thread:*current-thread*
579 (defun %invoke-debugger (condition)
580 (let ((*debug-condition* condition)
581 (*debug-restarts* (compute-restarts condition))
582 (*nested-debug-condition* nil))
584 ;; (The initial output here goes to *ERROR-OUTPUT*, because the
585 ;; initial output is not interactive, just an error message, and
586 ;; when people redirect *ERROR-OUTPUT*, they could reasonably
587 ;; expect to see error messages logged there, regardless of what
588 ;; the debugger does afterwards.)
589 (unless (typep condition 'step-condition)
590 (%print-debugger-invocation-reason condition *error-output*))
592 (setf *nested-debug-condition* condition)
593 (let ((ndc-type (type-of *nested-debug-condition*)))
594 (format *error-output*
595 "~&~@<(A ~S was caught when trying to print ~S when ~
596 entering the debugger. Printing was aborted and the ~
597 ~S was stored in ~S.)~@:>~%"
601 '*nested-debug-condition*))
602 (when (typep *nested-debug-condition* 'cell-error)
603 ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
604 (format *error-output*
605 "~&(CELL-ERROR-NAME ~S) = ~S~%"
606 '*nested-debug-condition*
607 (cell-error-name *nested-debug-condition*)))))
609 (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
612 ;; After the initial error/condition/whatever announcement to
613 ;; *ERROR-OUTPUT*, we become interactive, and should talk on
614 ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
615 ;; statement, not a description of reality.:-| There's a lot of
616 ;; older debugger code which was written to do i/o on whatever
617 ;; stream was in fashion at the time, and not all of it has
618 ;; been converted to behave this way. -- WHN 2000-11-16)
621 (let (;; We used to bind *STANDARD-OUTPUT* to *DEBUG-IO*
622 ;; here as well, but that is probably bogus since it
623 ;; removes the users ability to do output to a redirected
624 ;; *S-O*. Now we just rebind it so that users can temporarily
625 ;; frob it. FIXME: This and other "what gets bound when"
626 ;; behaviour should be documented in the manual.
627 (*standard-output* *standard-output*)
628 ;; This seems reasonable: e.g. if the user has redirected
629 ;; *ERROR-OUTPUT* to some log file, it's probably wrong
630 ;; to send errors which occur in interactive debugging to
631 ;; that file, and right to send them to *DEBUG-IO*.
632 (*error-output* *debug-io*))
633 (unless (typep condition 'step-condition)
634 (when *debug-beginner-help-p*
636 "~%~@<Type HELP for debugger help, or ~
637 (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
638 (show-restarts *debug-restarts* *debug-io*))
641 (sb!thread::release-foreground))))))
643 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
644 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
645 ;;; command-line option
646 (defun debugger-disabled-hook (condition me)
647 (declare (ignore me))
648 ;; There is no one there to interact with, so report the
649 ;; condition and terminate the program.
650 (flet ((failure-quit (&key recklessly-p)
651 (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
652 (quit :unix-status 1 :recklessly-p recklessly-p)))
653 ;; This HANDLER-CASE is here mostly to stop output immediately
654 ;; (and fall through to QUIT) when there's an I/O error. Thus,
655 ;; when we're run under a shell script or something, we can die
656 ;; cleanly when the script dies (and our pipes are cut), instead
657 ;; of falling into ldb or something messy like that. Similarly, we
658 ;; can terminate cleanly even if BACKTRACE dies because of bugs in
659 ;; user PRINT-OBJECT methods.
662 (format *error-output*
663 "~&~@<unhandled ~S~@[ in thread ~S~]: ~2I~_~A~:>~2%"
665 #!+sb-thread sb!thread:*current-thread*
668 ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
669 ;; even if we hit an error within BACKTRACE (e.g. a bug in
670 ;; the debugger's own frame-walking code, or a bug in a user
671 ;; PRINT-OBJECT method) we'll at least have the CONDITION
672 ;; printed out before we die.
673 (finish-output *error-output*)
674 ;; (Where to truncate the BACKTRACE is of course arbitrary, but
675 ;; it seems as though we should at least truncate it somewhere.)
676 (sb!debug:backtrace 128 *error-output*)
679 "~%unhandled condition in --disable-debugger mode, quitting~%")
680 (finish-output *error-output*)
683 ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
684 ;; fail when our output streams are blown away, as e.g. when
685 ;; we're running under a Unix shell script and it dies somehow
686 ;; (e.g. because of a SIGINT). In that case, we might as well
687 ;; just give it up for a bad job, and stop trying to notify
688 ;; the user of anything.
690 ;; Actually, the only way I've run across to exercise the
691 ;; problem is to have more than one layer of shell script.
692 ;; I have a shell script which does
693 ;; time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
694 ;; and the problem occurs when I interrupt this with Ctrl-C
695 ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
696 ;; I haven't figured out whether it's bash, time, tee, Linux, or
697 ;; what that is responsible, but that it's possible at all
698 ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
701 "Argh! error within --disable-debugger error handling"))
702 (failure-quit :recklessly-p t)))))
704 (defvar *old-debugger-hook* nil)
706 ;;; halt-on-failures and prompt-on-failures modes, suitable for
707 ;;; noninteractive and interactive use respectively
708 (defun disable-debugger ()
709 "When invoked, this function will turn off both the SBCL debugger
710 and LDB (the low-level debugger). See also ENABLE-DEBUGGER."
711 ;; *DEBUG-IO* used to be set here to *ERROR-OUTPUT* which is sort
712 ;; of unexpected but mostly harmless, but then ENABLE-DEBUGGER had
713 ;; to set it to a suitable value again and be very careful,
714 ;; especially if the user has also set it. -- MG 2005-07-15
715 (unless (eq *invoke-debugger-hook* 'debugger-disabled-hook)
716 (setf *old-debugger-hook* *invoke-debugger-hook*
717 *invoke-debugger-hook* 'debugger-disabled-hook))
718 ;; This is not inside the UNLESS to ensure that LDB is disabled
719 ;; regardless of what the old value of *INVOKE-DEBUGGER-HOOK* was.
720 ;; This might matter for example when restoring a core.
721 (sb!alien:alien-funcall (sb!alien:extern-alien "disable_lossage_handler"
722 (function sb!alien:void))))
724 (defun enable-debugger ()
725 "Restore the debugger if it has been turned off by DISABLE-DEBUGGER."
726 (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
727 (setf *invoke-debugger-hook* *old-debugger-hook*
728 *old-debugger-hook* nil))
729 (sb!alien:alien-funcall (sb!alien:extern-alien "enable_lossage_handler"
730 (function sb!alien:void))))
732 (defun show-restarts (restarts s)
733 (cond ((null restarts)
735 "~&(no restarts: If you didn't do this on purpose, ~
736 please report it as a bug.)~%"))
738 (format s "~&restarts (invokable by number or by ~
739 possibly-abbreviated name):~%")
743 (dolist (restart restarts)
744 (let ((name (restart-name restart)))
746 (let ((len (length (princ-to-string name))))
747 (when (> len max-name-len)
748 (setf max-name-len len))))))
749 (unless (zerop max-name-len)
750 (incf max-name-len 3))
751 (dolist (restart restarts)
752 (let ((name (restart-name restart)))
753 ;; FIXME: maybe it would be better to display later names
754 ;; in parens instead of brakets, not just omit them fully.
755 ;; Call BREAK, call BREAK in the debugger, and tell me
756 ;; it's not confusing looking. --NS 20050310
757 (cond ((member name names-used)
758 (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
760 (format s "~& ~2D: [~VA] ~A~%"
761 count (- max-name-len 3) name restart)
762 (push name names-used))))
765 (defvar *debug-loop-fun* #'debug-loop-fun
766 "a function taking no parameters that starts the low-level debug loop")
768 ;;; When the debugger is invoked due to a stepper condition, we don't
769 ;;; want to print the current frame before the first prompt for aesthetic
771 (defvar *suppress-frame-print* nil)
773 ;;; This calls DEBUG-LOOP, performing some simple initializations
774 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
775 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
776 ;;; to get into a debug prompt as quickly as possible with as little
777 ;;; risk as possible for stepping on whatever is causing recursive
779 (defun internal-debug ()
780 (let ((*in-the-debugger* t)
781 (*read-suppress* nil))
782 (unless (typep *debug-condition* 'step-condition)
783 (clear-input *debug-io*))
784 (let ((*suppress-frame-print* (typep *debug-condition* 'step-condition)))
785 (funcall *debug-loop-fun*))))
789 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
790 ;;; was motivated by desire to play nicely with ILISP.
791 (defvar *flush-debug-errors* nil
793 "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
794 executing in the debugger.")
796 (defun debug-read (stream)
797 (declare (type stream stream))
798 (let* ((eof-marker (cons nil nil))
799 (form (read stream nil eof-marker)))
800 (if (eq form eof-marker)
804 (defun debug-loop-fun ()
805 (let* ((*debug-command-level* (1+ *debug-command-level*))
806 (*real-stack-top* (sb!di:top-frame))
807 (*stack-top* (or *stack-top-hint* *real-stack-top*))
808 (*stack-top-hint* nil)
809 (*current-frame* *stack-top*))
810 (handler-bind ((sb!di:debug-condition
812 (princ condition *debug-io*)
813 (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
814 (throw 'debug-loop-catcher nil))))
815 (cond (*suppress-frame-print*
816 (setf *suppress-frame-print* nil))
819 (print-frame-call *current-frame* *debug-io* :verbosity 2)))
821 (catch 'debug-loop-catcher
822 (handler-bind ((error (lambda (condition)
823 (when *flush-debug-errors*
824 (clear-input *debug-io*)
825 (princ condition *debug-io*)
827 "~&error flushed (because ~
829 '*flush-debug-errors*)
830 (/show0 "throwing DEBUG-LOOP-CATCHER")
831 (throw 'debug-loop-catcher nil)))))
832 ;; We have to bind LEVEL for the restart function created by
833 ;; WITH-SIMPLE-RESTART.
834 (let ((level *debug-command-level*)
835 (restart-commands (make-restart-commands)))
836 (flush-standard-output-streams)
837 (debug-prompt *debug-io*)
838 (force-output *debug-io*)
839 (let* ((exp (debug-read *debug-io*))
840 (cmd-fun (debug-command-p exp restart-commands)))
841 (with-simple-restart (abort
842 "~@<Reduce debugger level (to debug level ~W).~@:>"
845 (debug-eval-print exp))
848 "~&Your command, ~S, is ambiguous:~%"
850 (dolist (ele cmd-fun)
851 (format *debug-io* " ~A~%" ele)))
853 (funcall cmd-fun))))))))))))
855 (defvar *auto-eval-in-frame* t
857 "When set (the default), evaluations in the debugger's command loop occur
858 relative to the current frame's environment without the need of debugger
859 forms that explicitly control this kind of evaluation.")
861 (defun debug-eval (expr)
862 (cond ((not (and (fboundp 'compile) *auto-eval-in-frame*))
864 ((frame-has-debug-vars-p *current-frame*)
865 (sb!di:eval-in-frame *current-frame* expr))
867 (format *debug-io* "; No debug variables for current frame: ~
868 using EVAL instead of EVAL-IN-FRAME.~%")
871 (defun debug-eval-print (expr)
872 (/noshow "entering DEBUG-EVAL-PRINT" expr)
873 (let ((values (multiple-value-list
874 (interactive-eval expr :eval #'debug-eval))))
875 (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
876 (dolist (value values)
877 (fresh-line *debug-io*)
878 (prin1 value *debug-io*)))
879 (force-output *debug-io*))
881 ;;;; debug loop functions
883 ;;; These commands are functions, not really commands, so that users
884 ;;; can get their hands on the values returned.
886 (eval-when (:execute :compile-toplevel)
888 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
889 `(let* ((temp (etypecase name
890 (symbol (sb!di:debug-fun-symbol-vars
891 (sb!di:frame-debug-fun *current-frame*)
893 (simple-string (sb!di:ambiguous-debug-vars
894 (sb!di:frame-debug-fun *current-frame*)
896 (location (sb!di:frame-code-location *current-frame*))
897 ;; Let's only deal with valid variables.
898 (vars (remove-if-not (lambda (v)
899 (eq (sb!di:debug-var-validity v location)
902 (declare (list vars))
904 (error "No known valid variables match ~S." name))
908 '(sb!di:debug-var-value (car vars) *current-frame*))
910 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
913 ;; Since we have more than one, first see whether we have
914 ;; any variables that exactly match the specification.
915 (let* ((name (etypecase name
916 (symbol (symbol-name name))
917 (simple-string name)))
918 ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
920 (exact (remove-if-not (lambda (v)
921 (string= (sb!di:debug-var-symbol-name v)
924 (vars (or exact vars)))
925 (declare (simple-string name)
928 ;; Check now for only having one variable.
932 '(sb!di:debug-var-value (car vars) *current-frame*))
934 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
936 ;; If there weren't any exact matches, flame about
937 ;; ambiguity unless all the variables have the same
942 (string= (sb!di:debug-var-symbol-name v)
943 (sb!di:debug-var-symbol-name (car vars))))
945 (error "specification ambiguous:~%~{ ~A~%~}"
946 (mapcar #'sb!di:debug-var-symbol-name
949 :key #'sb!di:debug-var-symbol-name))))
950 ;; All names are the same, so see whether the user
951 ;; ID'ed one of them.
953 (let ((v (find id vars :key #'sb!di:debug-var-id)))
956 "invalid variable ID, ~W: should have been one of ~S"
958 (mapcar #'sb!di:debug-var-id vars)))
961 '(sb!di:debug-var-value v *current-frame*))
963 `(setf (sb!di:debug-var-value v *current-frame*)
966 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
968 (mapcar #'sb!di:debug-var-id vars)))))))))
972 ;;; FIXME: This doesn't work. It would be real nice we could make it
973 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
974 (defun var (name &optional (id 0 id-supplied))
976 "Return a variable's value if possible. NAME is a simple-string or symbol.
977 If it is a simple-string, it is an initial substring of the variable's name.
978 If name is a symbol, it has the same name and package as the variable whose
979 value this function returns. If the symbol is uninterned, then the variable
980 has the same name as the symbol, but it has no package.
982 If name is the initial substring of variables with different names, then
983 this return no values after displaying the ambiguous names. If name
984 determines multiple variables with the same name, then you must use the
985 optional id argument to specify which one you want. If you left id
986 unspecified, then this returns no values after displaying the distinguishing
989 The result of this function is limited to the availability of variable
990 information. This is SETF'able."
991 (define-var-operation :ref))
992 (defun (setf var) (value name &optional (id 0 id-supplied))
993 (define-var-operation :set value))
995 ;;; This returns the COUNT'th arg as the user sees it from args, the
996 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
997 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
998 ;;; T. If this returns a keyword symbol or a value from a rest arg,
999 ;;; then the second value is NIL.
1001 ;;; FIXME: There's probably some way to merge the code here with
1002 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1003 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1004 (declaim (ftype (function (index list)) nth-arg))
1005 (defun nth-arg (count args)
1007 (dolist (ele args (error "The argument specification ~S is out of range."
1009 (lambda-list-element-dispatch ele
1010 :required ((if (zerop n) (return (values ele t))))
1011 :optional ((if (zerop n) (return (values (second ele) t))))
1012 :keyword ((cond ((zerop n)
1013 (return (values (second ele) nil)))
1015 (return (values (third ele) t)))))
1016 :deleted ((if (zerop n) (return (values ele t))))
1017 :rest ((let ((var (second ele)))
1018 (lambda-var-dispatch var (sb!di:frame-code-location
1020 (error "unused &REST argument before n'th argument")
1022 (sb!di:debug-var-value var *current-frame*)
1024 "The argument specification ~S is out of range."
1027 (return-from nth-arg (values value nil))
1029 (error "invalid &REST argument before n'th argument")))))
1034 "Return the N'th argument's value if possible. Argument zero is the first
1035 argument in a frame's default printed representation. Count keyword/value
1036 pairs as separate arguments."
1037 (multiple-value-bind (var lambda-var-p)
1038 (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1039 (sb!di:frame-debug-fun *current-frame*))
1040 (sb!di:lambda-list-unavailable ()
1041 (error "No argument values are available."))))
1043 (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1044 (error "Unused arguments have no values.")
1045 (sb!di:debug-var-value var *current-frame*)
1046 (error "invalid argument value"))
1049 ;;;; machinery for definition of debug loop commands
1051 (defvar *debug-commands* nil)
1053 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1055 (defmacro !def-debug-command (name args &rest body)
1056 (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1058 (setf *debug-commands*
1059 (remove ,name *debug-commands* :key #'car :test #'string=))
1060 (defun ,fun-name ,args
1061 (unless *in-the-debugger*
1062 (error "invoking debugger command while outside the debugger"))
1064 (push (cons ,name #',fun-name) *debug-commands*)
1067 (defun !def-debug-command-alias (new-name existing-name)
1068 (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1069 (unless pair (error "unknown debug command name: ~S" existing-name))
1070 (push (cons new-name (cdr pair)) *debug-commands*))
1073 ;;; This takes a symbol and uses its name to find a debugger command,
1074 ;;; using initial substring matching. It returns the command function
1075 ;;; if form identifies only one command, but if form is ambiguous,
1076 ;;; this returns a list of the command names. If there are no matches,
1077 ;;; this returns nil. Whenever the loop that looks for a set of
1078 ;;; possibilities encounters an exact name match, we return that
1079 ;;; command function immediately.
1080 (defun debug-command-p (form &optional other-commands)
1081 (if (or (symbolp form) (integerp form))
1085 (format nil "~W" form)))
1088 (declare (simple-string name)
1092 ;; Find matching commands, punting if exact match.
1093 (flet ((match-command (ele)
1094 (let* ((str (car ele))
1095 (str-len (length str)))
1096 (declare (simple-string str)
1098 (cond ((< str-len len))
1100 (when (string= name str :end1 len :end2 len)
1101 (return-from debug-command-p (cdr ele))))
1102 ((string= name str :end1 len :end2 len)
1104 (mapc #'match-command *debug-commands*)
1105 (mapc #'match-command other-commands))
1107 ;; Return the right value.
1108 (cond ((not res) nil)
1111 (t ; Just return the names.
1112 (do ((cmds res (cdr cmds)))
1114 (setf (car cmds) (caar cmds))))))))
1116 ;;; Return a list of debug commands (in the same format as
1117 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1119 ;;; Two commands are made for each restart: one for the number, and
1120 ;;; one for the restart name (unless it's been shadowed by an earlier
1121 ;;; restart of the same name, or it is NIL).
1122 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1124 (num 0)) ; better be the same as show-restarts!
1125 (dolist (restart restarts)
1126 (let ((name (string (restart-name restart))))
1129 (/show0 "in restart-command closure, about to i-r-i")
1130 (invoke-restart-interactively restart))))
1131 (push (cons (prin1-to-string num) restart-fun) commands)
1132 (unless (or (null (restart-name restart))
1133 (find name commands :key #'car :test #'string=))
1134 (push (cons name restart-fun) commands))))
1138 ;;;; frame-changing commands
1140 (!def-debug-command "UP" ()
1141 (let ((next (sb!di:frame-up *current-frame*)))
1143 (setf *current-frame* next)
1144 (print-frame-call next *debug-io*))
1146 (format *debug-io* "~&Top of stack.")))))
1148 (!def-debug-command "DOWN" ()
1149 (let ((next (sb!di:frame-down *current-frame*)))
1151 (setf *current-frame* next)
1152 (print-frame-call next *debug-io*))
1154 (format *debug-io* "~&Bottom of stack.")))))
1156 (!def-debug-command-alias "D" "DOWN")
1158 (!def-debug-command "BOTTOM" ()
1159 (do ((prev *current-frame* lead)
1160 (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1162 (setf *current-frame* prev)
1163 (print-frame-call prev *debug-io*))))
1165 (!def-debug-command-alias "B" "BOTTOM")
1167 (!def-debug-command "FRAME" (&optional
1168 (n (read-prompting-maybe "frame number: ")))
1169 (setf *current-frame*
1170 (multiple-value-bind (next-frame-fun limit-string)
1171 (if (< n (sb!di:frame-number *current-frame*))
1172 (values #'sb!di:frame-up "top")
1173 (values #'sb!di:frame-down "bottom"))
1174 (do ((frame *current-frame*))
1175 ((= n (sb!di:frame-number frame))
1177 (let ((next-frame (funcall next-frame-fun frame)))
1179 (setf frame next-frame))
1182 "The ~A of the stack was encountered.~%"
1184 (return frame)))))))
1185 (print-frame-call *current-frame* *debug-io*))
1187 (!def-debug-command-alias "F" "FRAME")
1189 ;;;; commands for entering and leaving the debugger
1191 (!def-debug-command "TOPLEVEL" ()
1192 (throw 'toplevel-catcher nil))
1195 (!def-debug-command-alias "TOP" "TOPLEVEL")
1197 (!def-debug-command "RESTART" ()
1198 (/show0 "doing RESTART debug-command")
1199 (let ((num (read-if-available :prompt)))
1200 (when (eq num :prompt)
1201 (show-restarts *debug-restarts* *debug-io*)
1202 (write-string "restart: " *debug-io*)
1203 (force-output *debug-io*)
1204 (setf num (read *debug-io*)))
1205 (let ((restart (typecase num
1207 (nth num *debug-restarts*))
1209 (find num *debug-restarts* :key #'restart-name
1210 :test (lambda (sym1 sym2)
1211 (string= (symbol-name sym1)
1212 (symbol-name sym2)))))
1214 (format *debug-io* "~S is invalid as a restart name.~%"
1216 (return-from restart-debug-command nil)))))
1217 (/show0 "got RESTART")
1219 (invoke-restart-interactively restart)
1220 (princ "There is no such restart." *debug-io*)))))
1222 ;;;; information commands
1224 (!def-debug-command "HELP" ()
1225 ;; CMU CL had a little toy pager here, but "if you aren't running
1226 ;; ILISP (or a smart windowing system, or something) you deserve to
1227 ;; lose", so we've dropped it in SBCL. However, in case some
1228 ;; desperate holdout is running this on a dumb terminal somewhere,
1229 ;; we tell him where to find the message stored as a string.
1231 "~&~A~2%(The HELP string is stored in ~S.)~%"
1233 '*debug-help-string*))
1235 (!def-debug-command-alias "?" "HELP")
1237 (!def-debug-command "ERROR" ()
1238 (format *debug-io* "~A~%" *debug-condition*)
1239 (show-restarts *debug-restarts* *debug-io*))
1241 (!def-debug-command "BACKTRACE" ()
1242 (backtrace (read-if-available most-positive-fixnum)))
1244 (!def-debug-command "PRINT" ()
1245 (print-frame-call *current-frame* *debug-io*))
1247 (!def-debug-command-alias "P" "PRINT")
1249 (!def-debug-command "LIST-LOCALS" ()
1250 (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1251 (if (sb!di:debug-var-info-available d-fun)
1252 (let ((*standard-output* *debug-io*)
1253 (location (sb!di:frame-code-location *current-frame*))
1254 (prefix (read-if-available nil))
1257 (dolist (v (sb!di:ambiguous-debug-vars
1259 (if prefix (string prefix) "")))
1261 (when (eq (sb!di:debug-var-validity v location) :valid)
1262 (setf any-valid-p t)
1263 (format *debug-io* "~S~:[#~W~;~*~] = ~S~%"
1264 (sb!di:debug-var-symbol v)
1265 (zerop (sb!di:debug-var-id v))
1266 (sb!di:debug-var-id v)
1267 (sb!di:debug-var-value v *current-frame*))))
1272 "There are no local variables ~@[starting with ~A ~]~
1277 "All variables ~@[starting with ~A ~]currently ~
1278 have invalid values."
1280 (write-line "There is no variable information available."
1283 (!def-debug-command-alias "L" "LIST-LOCALS")
1285 (!def-debug-command "SOURCE" ()
1286 (print (code-location-source-form (sb!di:frame-code-location *current-frame*)
1287 (read-if-available 0))
1290 ;;;; source location printing
1292 ;;; We cache a stream to the last valid file debug source so that we
1293 ;;; won't have to repeatedly open the file.
1295 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1296 ;;; in the 1990s, so the benefit is negligible, less important than the
1297 ;;; potential of extra confusion if someone changes the source during
1298 ;;; a debug session and the change doesn't show up. And removing this
1299 ;;; would simplify the system, which I like. -- WHN 19990903
1300 (defvar *cached-debug-source* nil)
1301 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1302 (defvar *cached-source-stream* nil)
1303 (declaim (type (or stream null) *cached-source-stream*))
1305 ;;; To suppress the read-time evaluation #. macro during source read,
1306 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1307 ;;; copying it each time, and invalidated when the
1308 ;;; *CACHED-DEBUG-SOURCE* has changed.
1309 (defvar *cached-readtable* nil)
1310 (declaim (type (or readtable null) *cached-readtable*))
1312 ;;; Stuff to clean up before saving a core
1313 (defun debug-deinit ()
1314 (setf *cached-debug-source* nil
1315 *cached-source-stream* nil
1316 *cached-readtable* nil))
1318 ;;; We also cache the last toplevel form that we printed a source for
1319 ;;; so that we don't have to do repeated reads and calls to
1320 ;;; FORM-NUMBER-TRANSLATIONS.
1321 (defvar *cached-toplevel-form-offset* nil)
1322 (declaim (type (or index null) *cached-toplevel-form-offset*))
1323 (defvar *cached-toplevel-form*)
1324 (defvar *cached-form-number-translations*)
1326 ;;; Given a code location, return the associated form-number
1327 ;;; translations and the actual top level form. We check our cache ---
1328 ;;; if there is a miss, we dispatch on the kind of the debug source.
1329 (defun get-toplevel-form (location)
1330 (let ((d-source (sb!di:code-location-debug-source location)))
1331 (if (and (eq d-source *cached-debug-source*)
1332 (eql (sb!di:code-location-toplevel-form-offset location)
1333 *cached-toplevel-form-offset*))
1334 (values *cached-form-number-translations* *cached-toplevel-form*)
1335 (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1337 (cond ((sb!di:debug-source-namestring d-source)
1338 (get-file-toplevel-form location))
1339 ((sb!di:debug-source-form d-source)
1340 (sb!di:debug-source-form d-source))
1341 (t (bug "Don't know how to use a DEBUG-SOURCE without ~
1342 a namestring or a form.")))))
1343 (setq *cached-toplevel-form-offset* offset)
1344 (values (setq *cached-form-number-translations*
1345 (sb!di:form-number-translations res offset))
1346 (setq *cached-toplevel-form* res))))))
1348 ;;; Locate the source file (if it still exists) and grab the top level
1349 ;;; form. If the file is modified, we use the top level form offset
1350 ;;; instead of the recorded character offset.
1351 (defun get-file-toplevel-form (location)
1352 (let* ((d-source (sb!di:code-location-debug-source location))
1353 (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1354 (local-tlf-offset (- tlf-offset
1355 (sb!di:debug-source-root-number d-source)))
1357 (aref (or (sb!di:debug-source-start-positions d-source)
1358 (error "no start positions map"))
1360 (name (sb!di:debug-source-namestring d-source)))
1361 (unless (eq d-source *cached-debug-source*)
1362 (unless (and *cached-source-stream*
1363 (equal (pathname *cached-source-stream*)
1365 (setq *cached-readtable* nil)
1366 (when *cached-source-stream* (close *cached-source-stream*))
1367 (setq *cached-source-stream* (open name :if-does-not-exist nil))
1368 (unless *cached-source-stream*
1369 (error "The source file no longer exists:~% ~A" (namestring name)))
1370 (format *debug-io* "~%; file: ~A~%" (namestring name)))
1372 (setq *cached-debug-source*
1373 (if (= (sb!di:debug-source-created d-source)
1374 (file-write-date name))
1378 ((eq *cached-debug-source* d-source)
1379 (file-position *cached-source-stream* char-offset))
1382 "~%; File has been modified since compilation:~%; ~A~@
1383 ; Using form offset instead of character position.~%"
1385 (file-position *cached-source-stream* 0)
1386 (let ((*read-suppress* t))
1387 (dotimes (i local-tlf-offset)
1388 (read *cached-source-stream*)))))
1389 (unless *cached-readtable*
1390 (setq *cached-readtable* (copy-readtable))
1391 (set-dispatch-macro-character
1393 (lambda (stream sub-char &rest rest)
1394 (declare (ignore rest sub-char))
1395 (let ((token (read stream t nil t)))
1396 (format nil "#.~S" token)))
1397 *cached-readtable*))
1398 (let ((*readtable* *cached-readtable*))
1399 (read *cached-source-stream*))))
1401 (defun code-location-source-form (location context)
1402 (let* ((location (maybe-block-start-location location))
1403 (form-num (sb!di:code-location-form-number location)))
1404 (multiple-value-bind (translations form) (get-toplevel-form location)
1405 (unless (< form-num (length translations))
1406 (error "The source path no longer exists."))
1407 (sb!di:source-path-context form
1408 (svref translations form-num)
1412 ;;; start single-stepping
1413 (!def-debug-command "START" ()
1414 (if (typep *debug-condition* 'step-condition)
1415 (format *debug-io* "~&Already single-stepping.~%")
1416 (let ((restart (find-restart 'continue *debug-condition*)))
1418 (sb!impl::enable-stepping)
1419 (invoke-restart restart))
1421 (format *debug-io* "~&Non-continuable error, cannot start stepping.~%"))))))
1423 (defmacro def-step-command (command-name restart-name)
1424 `(!def-debug-command ,command-name ()
1425 (if (typep *debug-condition* 'step-condition)
1426 (let ((restart (find-restart ',restart-name *debug-condition*)))
1428 (invoke-restart restart))
1429 (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%"))))
1431 (def-step-command "STEP" step-into)
1432 (def-step-command "NEXT" step-next)
1433 (def-step-command "STOP" step-continue)
1435 (!def-debug-command-alias "S" "STEP")
1436 (!def-debug-command-alias "N" "NEXT")
1438 (!def-debug-command "OUT" ()
1439 (if (typep *debug-condition* 'step-condition)
1440 (if sb!impl::*step-out*
1441 (let ((restart (find-restart 'step-out *debug-condition*)))
1443 (invoke-restart restart))
1444 (format *debug-io* "~&OUT can only be used step out of frames that were originally stepped into with STEP.~%"))
1445 (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%")))
1447 ;;; miscellaneous commands
1449 (!def-debug-command "DESCRIBE" ()
1450 (let* ((curloc (sb!di:frame-code-location *current-frame*))
1451 (debug-fun (sb!di:code-location-debug-fun curloc))
1452 (function (sb!di:debug-fun-fun debug-fun)))
1455 (format *debug-io* "can't figure out the function for this frame"))))
1457 (!def-debug-command "SLURP" ()
1458 (loop while (read-char-no-hang *standard-input*)))
1460 ;;; RETURN-FROM-FRAME and RESTART-FRAME
1462 (defun unwind-to-frame-and-call (frame thunk)
1463 #!+unwind-to-frame-and-call-vop
1464 (flet ((sap-int/fixnum (sap)
1465 ;; On unithreaded X86 *BINDING-STACK-POINTER* and
1466 ;; *CURRENT-CATCH-BLOCK* are negative, so we need to jump through
1467 ;; some hoops to make these calculated values negative too.
1468 (ash (truly-the (signed-byte #.sb!vm:n-word-bits)
1470 (- sb!vm::n-fixnum-tag-bits))))
1471 ;; To properly unwind the stack, we need three pieces of information:
1472 ;; * The unwind block that should be active after the unwind
1473 ;; * The catch block that should be active after the unwind
1474 ;; * The values that the binding stack pointer should have after the
1476 (let* ((block (sap-int/fixnum (find-enclosing-catch-block frame)))
1477 (unbind-to (sap-int/fixnum (find-binding-stack-pointer frame))))
1478 ;; This VOP will run the neccessary cleanup forms, reset the fp, and
1479 ;; then call the supplied function.
1480 (sb!vm::%primitive sb!vm::unwind-to-frame-and-call
1481 (sb!di::frame-pointer frame)
1482 (find-enclosing-uwp frame)
1484 ;; Before calling the user-specified
1485 ;; function, we need to restore the binding
1486 ;; stack and the catch block. The unwind block
1487 ;; is taken care of by the VOP.
1488 (sb!vm::%primitive sb!vm::unbind-to-here
1490 (setf sb!vm::*current-catch-block* block)
1492 #!-unwind-to-frame-and-call-vop
1493 (let ((tag (gensym)))
1494 (sb!di:replace-frame-catch-tag frame
1495 'sb!c:debug-catch-tag
1499 (defun find-binding-stack-pointer (frame)
1500 #!-stack-grows-downward-not-upward
1501 (declare (ignore frame))
1502 #!-stack-grows-downward-not-upward
1503 (error "Not implemented on this architecture")
1504 #!+stack-grows-downward-not-upward
1505 (let ((bsp (sb!vm::binding-stack-pointer-sap))
1507 (fp (sb!di::frame-pointer frame))
1508 (start (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1509 (ash sb!vm:*binding-stack-start*
1510 sb!vm:n-fixnum-tag-bits)))))
1511 ;; Walk the binding stack looking for an entry where the symbol is
1512 ;; an unbound-symbol marker and the value is equal to the frame
1513 ;; pointer. These entries are inserted into the stack by the
1514 ;; BIND-SENTINEL VOP and removed by UNBIND-SENTINEL (inserted into
1515 ;; the function during IR2). If an entry wasn't found, the
1516 ;; function that the frame corresponds to wasn't compiled with a
1517 ;; high enough debug setting, and can't be restarted / returned
1519 (loop until (sap= bsp start)
1522 (- (* sb!vm:binding-size sb!vm:n-word-bytes))))
1523 (let ((symbol (sap-ref-word bsp (* sb!vm:binding-symbol-slot
1524 sb!vm:n-word-bytes)))
1525 (value (sap-ref-sap bsp (* sb!vm:binding-value-slot
1526 sb!vm:n-word-bytes))))
1527 (when (eql symbol sb!vm:unbound-marker-widetag)
1528 (when (sap= value fp)
1529 (setf unbind-to bsp))))))
1532 (defun find-enclosing-catch-block (frame)
1533 ;; Walk the catch block chain looking for the first entry with an address
1534 ;; higher than the pointer for FRAME or a null pointer.
1535 (let* ((frame-pointer (sb!di::frame-pointer frame))
1536 (current-block (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1537 (ash sb!vm::*current-catch-block*
1538 sb!vm:n-fixnum-tag-bits))))
1539 (enclosing-block (loop for block = current-block
1540 then (sap-ref-sap block
1541 (* sb!vm:catch-block-previous-catch-slot
1542 sb!vm::n-word-bytes))
1543 when (or (zerop (sap-int block))
1544 (sap> block frame-pointer))
1548 (defun find-enclosing-uwp (frame)
1549 ;; Walk the UWP chain looking for the first entry with an address
1550 ;; higher than the pointer for FRAME or a null pointer.
1551 (let* ((frame-pointer (sb!di::frame-pointer frame))
1552 (current-uwp (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1553 (ash sb!vm::*current-unwind-protect-block*
1554 sb!vm:n-fixnum-tag-bits))))
1555 (enclosing-uwp (loop for uwp-block = current-uwp
1556 then (sap-ref-sap uwp-block
1557 sb!vm:unwind-block-current-uwp-slot)
1558 when (or (zerop (sap-int uwp-block))
1559 (sap> uwp-block frame-pointer))
1563 (!def-debug-command "RETURN" (&optional
1564 (return (read-prompting-maybe
1566 (if (frame-has-debug-tag-p *current-frame*)
1567 (let* ((code-location (sb!di:frame-code-location *current-frame*))
1568 (values (multiple-value-list
1569 (funcall (sb!di:preprocess-for-eval return code-location)
1571 (unwind-to-frame-and-call *current-frame* (lambda ()
1572 (values-list values))))
1574 "~@<can't find a tag for this frame ~
1575 ~2I~_(hint: try increasing the DEBUG optimization quality ~
1576 and recompiling)~:@>")))
1578 (!def-debug-command "RESTART-FRAME" ()
1579 (if (frame-has-debug-tag-p *current-frame*)
1580 (let* ((call-list (frame-call-as-list *current-frame*))
1581 (fun (fdefinition (car call-list))))
1582 (unwind-to-frame-and-call *current-frame*
1584 (apply fun (cdr call-list)))))
1586 "~@<can't find a tag for this frame ~
1587 ~2I~_(hint: try increasing the DEBUG optimization quality ~
1588 and recompiling)~:@>")))
1590 (defun frame-has-debug-tag-p (frame)
1591 #!+unwind-to-frame-and-call-vop
1592 (not (null (find-binding-stack-pointer frame)))
1593 #!-unwind-to-frame-and-call-vop
1594 (find 'sb!c:debug-catch-tag (sb!di::frame-catches frame) :key #'car))
1596 (defun frame-has-debug-vars-p (frame)
1597 (sb!di:debug-var-info-available
1598 (sb!di:code-location-debug-fun
1599 (sb!di:frame-code-location frame))))
1601 ;; Hack: ensure that *U-T-F-F* has a tls index.
1602 #!+unwind-to-frame-and-call-vop
1603 (let ((sb!vm::*unwind-to-frame-function* (lambda ()))))
1606 ;;;; debug loop command utilities
1608 (defun read-prompting-maybe (prompt)
1609 (unless (sb!int:listen-skip-whitespace *debug-io*)
1610 (princ prompt *debug-io*)
1611 (force-output *debug-io*))
1614 (defun read-if-available (default)
1615 (if (sb!int:listen-skip-whitespace *debug-io*)