1.0.27.19: Restore variable access in debugger REPL.
[sbcl.git] / src / code / debug.lisp
1 ;;;; the debugger
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!DEBUG")
13 \f
14 ;;;; variables and constants
15
16 ;;; 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
30 ;;;           #
31 ;;;         to satisfy lambda list
32 ;;;           #:
33 ;;;         exactly 2 expected, but 5 found
34 (defvar *debug-print-variable-alist* nil
35   #!+sb-doc
36   "an association list describing new bindings for special variables
37 to be used within the debugger. Eg.
38
39  ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
40
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.
45
46 Initially empty, *DEBUG-PRINT-VARIABLE-ALIST* is typically used to
47 provide bindings for printer control variables.")
48
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
54   nil
55   #!+sb-doc
56   "*READTABLE* for the debugger")
57
58 (defvar *in-the-debugger* nil
59   #!+sb-doc
60   "This is T while in the debugger.")
61
62 ;;; nestedness inside debugger command loops
63 (defvar *debug-command-level* 0)
64
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)
68
69 (defvar *stack-top* nil)
70 (defvar *real-stack-top* nil)
71
72 (defvar *current-frame* nil)
73
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?")
80
81 (defun debug-prompt (stream)
82   (sb!thread::get-foreground)
83   (format stream
84           "~%~W~:[~;[~W~]] "
85           (sb!di:frame-number *current-frame*)
86           (> *debug-command-level* 1)
87           *debug-command-level*))
88
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
101   to debugger.
102
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.
107
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
110    that restart.
111
112 Changing frames:
113   UP     up frame         DOWN     down frame
114   BOTTOM bottom frame     FRAME n  frame n (n=0 for top frame)
115
116 Inspecting frames:
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.
121
122 Stepping:
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.
131
132 Function and macro commands:
133  (SB-DEBUG:ARG n)
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.
137
138 Other commands:
139   RETURN expr
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.
143
144   RESTART-FRAME
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.
148
149   SLURP
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.)")
153 \f
154
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)
162                       (return loc))))
163         (cond ((and (not (sb!di:debug-block-elsewhere-p block))
164                     start)
165                (format *debug-io* "~%unknown location: using block start~%")
166                start)
167               (t
168                loc)))
169       loc))
170 \f
171 ;;;; BACKTRACE
172
173 (defun map-backtrace (thunk &key (start 0) (count most-positive-fixnum))
174   (loop
175      with result = nil
176      for index upfrom 0
177      for frame = (if *in-the-debugger*
178                      *current-frame*
179                      (sb!di:top-frame))
180                then (sb!di:frame-down frame)
181      until (null frame)
182      when (<= start index) do
183        (if (minusp (decf count))
184            (return result)
185            (setf result (funcall thunk frame)))
186      finally (return result)))
187
188 (defun backtrace (&optional (count most-positive-fixnum) (stream *debug-io*))
189   #!+sb-doc
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."
193   (fresh-line stream)
194   (map-backtrace (lambda (frame)
195                    (print-frame-call frame stream :number t))
196                  :count count)
197   (fresh-line stream)
198   (values))
199
200 (defun backtrace-as-list (&optional (count most-positive-fixnum))
201   #!+sb-doc "Return a list representing the current BACKTRACE."
202   (let ((reversed-result (list)))
203     (map-backtrace (lambda (frame)
204                      (push (frame-call-as-list frame) reversed-result))
205                    :count count)
206     (nreverse reversed-result)))
207
208 (defun frame-call-as-list (frame)
209   (multiple-value-bind (name args) (frame-call frame)
210     (cons name args)))
211 \f
212 ;;;; frame printing
213
214 (eval-when (:compile-toplevel :execute)
215
216 ;;; This is a convenient way to express what to do for each type of
217 ;;; lambda-list element.
218 (sb!xc:defmacro lambda-list-element-dispatch (element
219                                               &key
220                                               required
221                                               optional
222                                               rest
223                                               keyword
224                                               deleted)
225   `(etypecase ,element
226      (sb!di:debug-var
227       ,@required)
228      (cons
229       (ecase (car ,element)
230         (:optional ,@optional)
231         (:rest ,@rest)
232         (:keyword ,@keyword)))
233      (symbol
234       (aver (eq ,element :deleted))
235       ,@deleted)))
236
237 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
238   (let ((var (gensym)))
239     `(let ((,var ,variable))
240        (cond ((eq ,var :deleted) ,deleted)
241              ((eq (sb!di:debug-var-validity ,var ,location) :valid)
242               ,valid)
243              (t ,other)))))
244
245 ) ; EVAL-WHEN
246
247 ;;; Extract the function argument values for a debug frame.
248 (defun map-frame-args (thunk frame)
249   (let ((debug-fun (sb!di:frame-debug-fun frame)))
250     (dolist (element (sb!di:debug-fun-lambda-list debug-fun))
251       (funcall thunk element))))
252
253 (defun frame-args-as-list (frame)
254   (handler-case
255       (let ((location (sb!di:frame-code-location frame))
256             (reversed-result nil))
257         (block enumerating
258           (map-frame-args
259            (lambda (element)
260              (lambda-list-element-dispatch element
261                :required ((push (frame-call-arg element location frame) reversed-result))
262                :optional ((push (frame-call-arg (second element) location frame)
263                                 reversed-result))
264                :keyword ((push (second element) reversed-result)
265                          (push (frame-call-arg (third element) location frame)
266                                reversed-result))
267                :deleted ((push (frame-call-arg element location frame) reversed-result))
268                :rest ((lambda-var-dispatch (second element) location
269                         nil
270                         (progn
271                           (setf reversed-result
272                                 (append (reverse (sb!di:debug-var-value
273                                                   (second element) frame))
274                                         reversed-result))
275                           (return-from enumerating))
276                         (push (make-unprintable-object
277                                "unavailable &REST argument")
278                               reversed-result)))))
279            frame))
280         (nreverse reversed-result))
281     (sb!di:lambda-list-unavailable ()
282       (make-unprintable-object "unavailable lambda list"))))
283
284 (defvar *show-entry-point-details* nil)
285
286 (defun clean-xep (name args)
287   (values (second name)
288           (if (consp args)
289               (let ((count (first args))
290                     (real-args (rest args)))
291                 (if (fixnump count)
292                     (subseq real-args 0
293                             (min count (length real-args)))
294                     real-args))
295               args)))
296
297 (defun clean-&more-processor (name args)
298   (values (second name)
299           (if (consp args)
300               (let* ((more (last args 2))
301                      (context (first more))
302                      (count (second more)))
303                 (append
304                  (butlast args 2)
305                  (if (fixnump count)
306                      (multiple-value-list
307                       (sb!c:%more-arg-values context 0 count))
308                      (list
309                       (make-unprintable-object "more unavailable arguments")))))
310               args)))
311
312 (defun frame-call (frame)
313   (labels ((clean-name-and-args (name args)
314              (if (and (consp name) (not *show-entry-point-details*))
315                  ;; FIXME: do we need to deal with
316                  ;; HAIRY-FUNCTION-ENTRY here? I can't make it or
317                  ;; &AUX-BINDINGS appear in backtraces, so they are
318                  ;; left alone for now. --NS 2005-02-28
319                  (case (first name)
320                    ((sb!c::xep sb!c::tl-xep)
321                     (clean-xep name args))
322                    ((sb!c::&more-processor)
323                     (clean-&more-processor name args))
324                    ((sb!c::hairy-arg-processor
325                      sb!c::varargs-entry sb!c::&optional-processor)
326                     (clean-name-and-args (second name) args))
327                    (t
328                     (values name args)))
329                  (values name args))))
330     (let ((debug-fun (sb!di:frame-debug-fun frame)))
331       (multiple-value-bind (name args)
332           (clean-name-and-args (sb!di:debug-fun-name debug-fun)
333                                 (frame-args-as-list frame))
334         (values name args (sb!di:debug-fun-kind debug-fun))))))
335
336 (defun ensure-printable-object (object)
337   (handler-case
338       (with-open-stream (out (make-broadcast-stream))
339         (prin1 object out)
340         object)
341     (error (cond)
342       (declare (ignore cond))
343       (make-unprintable-object "error printing object"))))
344
345 (defun frame-call-arg (var location frame)
346   (lambda-var-dispatch var location
347     (make-unprintable-object "unused argument")
348     (sb!di:debug-var-value var frame)
349     (make-unprintable-object "unavailable argument")))
350
351 ;;; Prints a representation of the function call causing FRAME to
352 ;;; exist. VERBOSITY indicates the level of information to output;
353 ;;; zero indicates just printing the DEBUG-FUN's name, and one
354 ;;; indicates displaying call-like, one-liner format with argument
355 ;;; values.
356 (defun print-frame-call (frame stream &key (verbosity 1) (number nil))
357   (when number
358     (format stream "~&~S: " (sb!di:frame-number frame)))
359   (if (zerop verbosity)
360       (let ((*print-readably* nil))
361         (prin1 frame stream))
362       (multiple-value-bind (name args kind) (frame-call frame)
363         (pprint-logical-block (stream nil :prefix "(" :suffix ")")
364           ;; Since we go to some trouble to make nice informative function
365           ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
366           ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
367           ;; For the function arguments, we can just print normally.
368           (let ((*print-length* nil)
369                 (*print-level* nil))
370             (prin1 (ensure-printable-object name) stream))
371           ;; If we hit a &REST arg, then print as many of the values as
372           ;; possible, punting the loop over lambda-list variables since any
373           ;; other arguments will be in the &REST arg's list of values.
374           (let ((args (ensure-printable-object args)))
375             (if (listp args)
376                 (format stream "~{ ~_~S~}" args)
377                 (format stream " ~S" args))))
378         (when kind
379           (format stream "[~S]" kind))))
380   (when (>= verbosity 2)
381     (let ((loc (sb!di:frame-code-location frame)))
382       (handler-case
383           (progn
384             ;; FIXME: Is this call really necessary here? If it is,
385             ;; then the reason for it should be unobscured.
386             (sb!di:code-location-debug-block loc)
387             (format stream "~%source: ")
388             (prin1 (code-location-source-form loc 0) stream))
389         (sb!di:debug-condition (ignore)
390           ignore)
391         (error (c)
392           (format stream "~&error finding source: ~A" c))))))
393 \f
394 ;;;; INVOKE-DEBUGGER
395
396 (defvar *debugger-hook* nil
397   #!+sb-doc
398   "This is either NIL or a function of two arguments, a condition and the value
399    of *DEBUGGER-HOOK*. This function can either handle the condition or return
400    which causes the standard debugger to execute. The system passes the value
401    of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
402    around the invocation.")
403
404 (defvar *invoke-debugger-hook* nil
405   #!+sb-doc
406   "This is either NIL or a designator for a function of two arguments,
407    to be run when the debugger is about to be entered.  The function is
408    run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
409    errors, and receives as arguments the condition that triggered
410    debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*
411
412    This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
413    In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
414    called by BREAK.")
415
416 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
417 (defvar *debug-restarts*)
418 (defvar *debug-condition*)
419 (defvar *nested-debug-condition*)
420
421 ;;; Oh, what a tangled web we weave when we preserve backwards
422 ;;; compatibility with 1968-style use of global variables to control
423 ;;; per-stream i/o properties; there's really no way to get this
424 ;;; quite right, but we do what we can.
425 (defun funcall-with-debug-io-syntax (fun &rest rest)
426   (declare (type function fun))
427   ;; Try to force the other special variables into a useful state.
428   (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
429         ;; any default we might use is less useful than just reusing
430         ;; the global values.
431         (original-package *package*)
432         (original-print-pretty *print-pretty*))
433     (with-standard-io-syntax
434       (with-sane-io-syntax
435           (let (;; We want the printer and reader to be in a useful
436                 ;; state, regardless of where the debugger was invoked
437                 ;; in the program. WITH-STANDARD-IO-SYNTAX and
438                 ;; WITH-SANE-IO-SYNTAX do much of what we want, but
439                 ;;   * It doesn't affect our internal special variables
440                 ;;     like *CURRENT-LEVEL-IN-PRINT*.
441                 ;;   * It isn't customizable.
442                 ;;   * It sets *PACKAGE* to COMMON-LISP-USER, which is not
443                 ;;     helpful behavior for a debugger.
444                 ;;   * There's no particularly good debugger default for
445                 ;;     *PRINT-PRETTY*, since T is usually what you want
446                 ;;     -- except absolutely not what you want when you're
447                 ;;     debugging failures in PRINT-OBJECT logic.
448                 ;; We try to address all these issues with explicit
449                 ;; rebindings here.
450                 (sb!kernel:*current-level-in-print* 0)
451                 (*package* original-package)
452                 (*print-pretty* original-print-pretty)
453                 ;; Clear the circularity machinery to try to to reduce the
454                 ;; pain from sharing the circularity table across all
455                 ;; streams; if these are not rebound here, then setting
456                 ;; *PRINT-CIRCLE* within the debugger when debugging in a
457                 ;; state where something circular was being printed (e.g.,
458                 ;; because the debugger was entered on an error in a
459                 ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
460                 ;; here does seem somewhat ugly because it makes it more
461                 ;; difficult to debug the printing-of-circularities code
462                 ;; itself; however, as far as I (WHN, 2004-05-29) can see,
463                 ;; that's almost entirely academic as long as there's one
464                 ;; shared *C-H-T* for all streams (i.e., it's already
465                 ;; unreasonably difficult to debug print-circle machinery
466                 ;; given the buggy crosstalk between the debugger streams
467                 ;; and the stream you're trying to watch), and any fix for
468                 ;; that buggy arrangement will likely let this hack go away
469                 ;; naturally.
470                 (sb!impl::*circularity-hash-table* . nil)
471                 (sb!impl::*circularity-counter* . nil)
472                 (*readtable* *debug-readtable*))
473             (progv
474                 ;; (Why NREVERSE? PROGV makes the later entries have
475                 ;; precedence over the earlier entries.
476                 ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
477                 ;; expected that its earlier entries have precedence. And
478                 ;; the earlier-has-precedence behavior is mostly more
479                 ;; convenient, so that programmers can use PUSH or LIST* to
480                 ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
481                 (nreverse (mapcar #'car *debug-print-variable-alist*))
482                 (nreverse (mapcar #'cdr *debug-print-variable-alist*))
483               (apply fun rest)))))))
484
485 (defun invoke-debugger (condition)
486   #!+sb-doc
487   "Enter the debugger."
488
489   ;; call *INVOKE-DEBUGGER-HOOK* first, so that *DEBUGGER-HOOK* is not
490   ;; called when the debugger is disabled
491   (let ((old-hook *invoke-debugger-hook*))
492     (when old-hook
493       (let ((*invoke-debugger-hook* nil))
494         (funcall old-hook condition old-hook))))
495   (let ((old-hook *debugger-hook*))
496     (when old-hook
497       (let ((*debugger-hook* nil))
498         (funcall old-hook condition old-hook))))
499
500   ;; We definitely want *PACKAGE* to be of valid type.
501   ;;
502   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
503   ;; this, but here causing an exception just as we're trying to handle
504   ;; an exception would be confusing, so instead we use a special hack.
505   (unless (and (packagep *package*)
506                (package-name *package*))
507     (setf *package* (find-package :cl-user))
508     (format *error-output*
509             "The value of ~S was not an undeleted PACKAGE. It has been
510 reset to ~S."
511             '*package* *package*))
512
513   ;; Before we start our own output, finish any pending output.
514   ;; Otherwise, if the user tried to track the progress of his program
515   ;; using PRINT statements, he'd tend to lose the last line of output
516   ;; or so, which'd be confusing.
517   (flush-standard-output-streams)
518
519   (funcall-with-debug-io-syntax #'%invoke-debugger condition))
520
521 (defun %print-debugger-invocation-reason (condition stream)
522   (format stream "~2&")
523   ;; Note: Ordinarily it's only a matter of taste whether to use
524   ;; FORMAT "~<...~:>" or to use PPRINT-LOGICAL-BLOCK directly, but
525   ;; until bug 403 is fixed, PPRINT-LOGICAL-BLOCK (STREAM NIL) is
526   ;; definitely preferred, because the FORMAT alternative was acting odd.
527   (pprint-logical-block (stream nil)
528     (format stream
529             "debugger invoked on a ~S~@[ in thread ~A~]: ~2I~_~A"
530             (type-of condition)
531             #!+sb-thread sb!thread:*current-thread*
532             #!-sb-thread nil
533             condition))
534   (terpri stream))
535
536 (defun %invoke-debugger (condition)
537   (let ((*debug-condition* condition)
538         (*debug-restarts* (compute-restarts condition))
539         (*nested-debug-condition* nil))
540     (handler-case
541         ;; (The initial output here goes to *ERROR-OUTPUT*, because the
542         ;; initial output is not interactive, just an error message, and
543         ;; when people redirect *ERROR-OUTPUT*, they could reasonably
544         ;; expect to see error messages logged there, regardless of what
545         ;; the debugger does afterwards.)
546         (unless (typep condition 'step-condition)
547           (%print-debugger-invocation-reason condition *error-output*))
548       (error (condition)
549         (setf *nested-debug-condition* condition)
550         (let ((ndc-type (type-of *nested-debug-condition*)))
551           (format *error-output*
552                   "~&~@<(A ~S was caught when trying to print ~S when ~
553                       entering the debugger. Printing was aborted and the ~
554                       ~S was stored in ~S.)~@:>~%"
555                   ndc-type
556                   '*debug-condition*
557                   ndc-type
558                   '*nested-debug-condition*))
559         (when (typep *nested-debug-condition* 'cell-error)
560           ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
561           (format *error-output*
562                   "~&(CELL-ERROR-NAME ~S) = ~S~%"
563                   '*nested-debug-condition*
564                   (cell-error-name *nested-debug-condition*)))))
565
566     (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
567                          *debug-io*)))
568
569       ;; After the initial error/condition/whatever announcement to
570       ;; *ERROR-OUTPUT*, we become interactive, and should talk on
571       ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
572       ;; statement, not a description of reality.:-| There's a lot of
573       ;; older debugger code which was written to do i/o on whatever
574       ;; stream was in fashion at the time, and not all of it has
575       ;; been converted to behave this way. -- WHN 2000-11-16)
576
577       (unwind-protect
578            (let (;; We used to bind *STANDARD-OUTPUT* to *DEBUG-IO*
579                  ;; here as well, but that is probably bogus since it
580                  ;; removes the users ability to do output to a redirected
581                  ;; *S-O*. Now we just rebind it so that users can temporarily
582                  ;; frob it. FIXME: This and other "what gets bound when"
583                  ;; behaviour should be documented in the manual.
584                  (*standard-output* *standard-output*)
585                  ;; This seems reasonable: e.g. if the user has redirected
586                  ;; *ERROR-OUTPUT* to some log file, it's probably wrong
587                  ;; to send errors which occur in interactive debugging to
588                  ;; that file, and right to send them to *DEBUG-IO*.
589                  (*error-output* *debug-io*))
590              (unless (typep condition 'step-condition)
591                (when *debug-beginner-help-p*
592                  (format *debug-io*
593                          "~%~@<Type HELP for debugger help, or ~
594                                (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
595                (show-restarts *debug-restarts* *debug-io*))
596              (internal-debug))
597         (when background-p
598           (sb!thread::release-foreground))))))
599
600 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
601 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
602 ;;; command-line option
603 (defun debugger-disabled-hook (condition me)
604   (declare (ignore me))
605   ;; There is no one there to interact with, so report the
606   ;; condition and terminate the program.
607   (flet ((failure-quit (&key recklessly-p)
608            (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
609            (quit :unix-status 1 :recklessly-p recklessly-p)))
610     ;; This HANDLER-CASE is here mostly to stop output immediately
611     ;; (and fall through to QUIT) when there's an I/O error. Thus,
612     ;; when we're run under a shell script or something, we can die
613     ;; cleanly when the script dies (and our pipes are cut), instead
614     ;; of falling into ldb or something messy like that. Similarly, we
615     ;; can terminate cleanly even if BACKTRACE dies because of bugs in
616     ;; user PRINT-OBJECT methods.
617     (handler-case
618         (progn
619           (format *error-output*
620                   "~&~@<unhandled ~S~@[ in thread ~S~]: ~2I~_~A~:>~2%"
621                   (type-of condition)
622                   #!+sb-thread sb!thread:*current-thread*
623                   #!-sb-thread nil
624                   condition)
625           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
626           ;; even if we hit an error within BACKTRACE (e.g. a bug in
627           ;; the debugger's own frame-walking code, or a bug in a user
628           ;; PRINT-OBJECT method) we'll at least have the CONDITION
629           ;; printed out before we die.
630           (finish-output *error-output*)
631           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
632           ;; it seems as though we should at least truncate it somewhere.)
633           (sb!debug:backtrace 128 *error-output*)
634           (format
635            *error-output*
636            "~%unhandled condition in --disable-debugger mode, quitting~%")
637           (finish-output *error-output*)
638           (failure-quit))
639       (condition ()
640         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
641         ;; fail when our output streams are blown away, as e.g. when
642         ;; we're running under a Unix shell script and it dies somehow
643         ;; (e.g. because of a SIGINT). In that case, we might as well
644         ;; just give it up for a bad job, and stop trying to notify
645         ;; the user of anything.
646         ;;
647         ;; Actually, the only way I've run across to exercise the
648         ;; problem is to have more than one layer of shell script.
649         ;; I have a shell script which does
650         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
651         ;; and the problem occurs when I interrupt this with Ctrl-C
652         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
653         ;; I haven't figured out whether it's bash, time, tee, Linux, or
654         ;; what that is responsible, but that it's possible at all
655         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
656         (ignore-errors
657          (%primitive print
658                      "Argh! error within --disable-debugger error handling"))
659         (failure-quit :recklessly-p t)))))
660
661 (defvar *old-debugger-hook* nil)
662
663 ;;; halt-on-failures and prompt-on-failures modes, suitable for
664 ;;; noninteractive and interactive use respectively
665 (defun disable-debugger ()
666   ;; *DEBUG-IO* used to be set here to *ERROR-OUTPUT* which is sort
667   ;; of unexpected but mostly harmless, but then ENABLE-DEBUGGER had
668   ;; to set it to a suitable value again and be very careful,
669   ;; especially if the user has also set it. -- MG 2005-07-15
670   (unless (eq *invoke-debugger-hook* 'debugger-disabled-hook)
671     (setf *old-debugger-hook* *invoke-debugger-hook*
672           *invoke-debugger-hook* 'debugger-disabled-hook))
673   ;; This is not inside the UNLESS to ensure that LDB is disabled
674   ;; regardless of what the old value of *INVOKE-DEBUGGER-HOOK* was.
675   ;; This might matter for example when restoring a core.
676   (sb!alien:alien-funcall (sb!alien:extern-alien "disable_lossage_handler"
677                                                  (function sb!alien:void))))
678
679 (defun enable-debugger ()
680   (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
681     (setf *invoke-debugger-hook* *old-debugger-hook*
682           *old-debugger-hook* nil))
683   (sb!alien:alien-funcall (sb!alien:extern-alien "enable_lossage_handler"
684                                                  (function sb!alien:void))))
685
686 (defun show-restarts (restarts s)
687   (cond ((null restarts)
688          (format s
689                  "~&(no restarts: If you didn't do this on purpose, ~
690                   please report it as a bug.)~%"))
691         (t
692          (format s "~&restarts (invokable by number or by ~
693                     possibly-abbreviated name):~%")
694          (let ((count 0)
695                (names-used '(nil))
696                (max-name-len 0))
697            (dolist (restart restarts)
698              (let ((name (restart-name restart)))
699                (when name
700                  (let ((len (length (princ-to-string name))))
701                    (when (> len max-name-len)
702                      (setf max-name-len len))))))
703            (unless (zerop max-name-len)
704              (incf max-name-len 3))
705            (dolist (restart restarts)
706              (let ((name (restart-name restart)))
707                ;; FIXME: maybe it would be better to display later names
708                ;; in parens instead of brakets, not just omit them fully.
709                ;; Call BREAK, call BREAK in the debugger, and tell me
710                ;; it's not confusing looking. --NS 20050310
711                (cond ((member name names-used)
712                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
713                      (t
714                       (format s "~& ~2D: [~VA] ~A~%"
715                               count (- max-name-len 3) name restart)
716                       (push name names-used))))
717              (incf count))))))
718
719 (defvar *debug-loop-fun* #'debug-loop-fun
720   "a function taking no parameters that starts the low-level debug loop")
721
722 ;;; When the debugger is invoked due to a stepper condition, we don't
723 ;;; want to print the current frame before the first prompt for aesthetic
724 ;;; reasons.
725 (defvar *suppress-frame-print* nil)
726
727 ;;; This calls DEBUG-LOOP, performing some simple initializations
728 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
729 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
730 ;;; to get into a debug prompt as quickly as possible with as little
731 ;;; risk as possible for stepping on whatever is causing recursive
732 ;;; errors.
733 (defun internal-debug ()
734   (let ((*in-the-debugger* t)
735         (*read-suppress* nil))
736     (unless (typep *debug-condition* 'step-condition)
737       (clear-input *debug-io*))
738     (let ((*suppress-frame-print* (typep *debug-condition* 'step-condition)))
739       (funcall *debug-loop-fun*))))
740 \f
741 ;;;; DEBUG-LOOP
742
743 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
744 ;;; was motivated by desire to play nicely with ILISP.
745 (defvar *flush-debug-errors* nil
746   #!+sb-doc
747   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
748    executing in the debugger.")
749
750 (defun debug-read (stream)
751   (declare (type stream stream))
752   (let* ((eof-marker (cons nil nil))
753          (form (read stream nil eof-marker)))
754     (if (eq form eof-marker)
755         (abort)
756         form)))
757
758 (defun debug-loop-fun ()
759   (let* ((*debug-command-level* (1+ *debug-command-level*))
760          (*real-stack-top* (sb!di:top-frame))
761          (*stack-top* (or *stack-top-hint* *real-stack-top*))
762          (*stack-top-hint* nil)
763          (*current-frame* *stack-top*))
764     (handler-bind ((sb!di:debug-condition
765                     (lambda (condition)
766                       (princ condition *debug-io*)
767                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
768                       (throw 'debug-loop-catcher nil))))
769       (cond (*suppress-frame-print*
770              (setf *suppress-frame-print* nil))
771             (t
772              (terpri *debug-io*)
773              (print-frame-call *current-frame* *debug-io* :verbosity 2)))
774       (loop
775        (catch 'debug-loop-catcher
776          (handler-bind ((error (lambda (condition)
777                                  (when *flush-debug-errors*
778                                    (clear-input *debug-io*)
779                                    (princ condition *debug-io*)
780                                    (format *debug-io*
781                                            "~&error flushed (because ~
782                                              ~S is set)"
783                                            '*flush-debug-errors*)
784                                    (/show0 "throwing DEBUG-LOOP-CATCHER")
785                                    (throw 'debug-loop-catcher nil)))))
786            ;; We have to bind LEVEL for the restart function created by
787            ;; WITH-SIMPLE-RESTART.
788            (let ((level *debug-command-level*)
789                  (restart-commands (make-restart-commands)))
790              (flush-standard-output-streams)
791              (debug-prompt *debug-io*)
792              (force-output *debug-io*)
793              (let* ((exp (debug-read *debug-io*))
794                     (cmd-fun (debug-command-p exp restart-commands)))
795                (with-simple-restart (abort
796                                      "~@<Reduce debugger level (to debug level ~W).~@:>"
797                                      level)
798                  (cond ((not cmd-fun)
799                         (debug-eval-print exp))
800                        ((consp cmd-fun)
801                         (format *debug-io*
802                                 "~&Your command, ~S, is ambiguous:~%"
803                                 exp)
804                         (dolist (ele cmd-fun)
805                           (format *debug-io* "   ~A~%" ele)))
806                        (t
807                         (funcall cmd-fun))))))))))))
808
809 (defvar *auto-eval-in-frame* t
810   #!+sb-doc
811   "When set (the default), evaluations in the debugger's command loop occur
812    relative to the current frame's environment without the need of debugger
813    forms that explicitly control this kind of evaluation.")
814
815 (defun debug-eval (expr)
816   (if (and (fboundp 'compile) *auto-eval-in-frame*)
817       (sb!di:eval-in-frame *current-frame* expr)
818       (eval expr)))
819
820 (defun debug-eval-print (expr)
821   (/noshow "entering DEBUG-EVAL-PRINT" expr)
822   (let ((values (multiple-value-list
823                  (interactive-eval expr :eval #'debug-eval))))
824     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
825     (dolist (value values)
826       (fresh-line *debug-io*)
827       (prin1 value *debug-io*)))
828   (force-output *debug-io*))
829 \f
830 ;;;; debug loop functions
831
832 ;;; These commands are functions, not really commands, so that users
833 ;;; can get their hands on the values returned.
834
835 (eval-when (:execute :compile-toplevel)
836
837 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
838   `(let* ((temp (etypecase name
839                   (symbol (sb!di:debug-fun-symbol-vars
840                            (sb!di:frame-debug-fun *current-frame*)
841                            name))
842                   (simple-string (sb!di:ambiguous-debug-vars
843                                   (sb!di:frame-debug-fun *current-frame*)
844                                   name))))
845           (location (sb!di:frame-code-location *current-frame*))
846           ;; Let's only deal with valid variables.
847           (vars (remove-if-not (lambda (v)
848                                  (eq (sb!di:debug-var-validity v location)
849                                      :valid))
850                                temp)))
851      (declare (list vars))
852      (cond ((null vars)
853             (error "No known valid variables match ~S." name))
854            ((= (length vars) 1)
855             ,(ecase ref-or-set
856                (:ref
857                 '(sb!di:debug-var-value (car vars) *current-frame*))
858                (:set
859                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
860                        ,value-var))))
861            (t
862             ;; Since we have more than one, first see whether we have
863             ;; any variables that exactly match the specification.
864             (let* ((name (etypecase name
865                            (symbol (symbol-name name))
866                            (simple-string name)))
867                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
868                    ;; instead.
869                    (exact (remove-if-not (lambda (v)
870                                            (string= (sb!di:debug-var-symbol-name v)
871                                                     name))
872                                          vars))
873                    (vars (or exact vars)))
874               (declare (simple-string name)
875                        (list exact vars))
876               (cond
877                ;; Check now for only having one variable.
878                ((= (length vars) 1)
879                 ,(ecase ref-or-set
880                    (:ref
881                     '(sb!di:debug-var-value (car vars) *current-frame*))
882                    (:set
883                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
884                            ,value-var))))
885                ;; If there weren't any exact matches, flame about
886                ;; ambiguity unless all the variables have the same
887                ;; name.
888                ((and (not exact)
889                      (find-if-not
890                       (lambda (v)
891                         (string= (sb!di:debug-var-symbol-name v)
892                                  (sb!di:debug-var-symbol-name (car vars))))
893                       (cdr vars)))
894                 (error "specification ambiguous:~%~{   ~A~%~}"
895                        (mapcar #'sb!di:debug-var-symbol-name
896                                (delete-duplicates
897                                 vars :test #'string=
898                                 :key #'sb!di:debug-var-symbol-name))))
899                ;; All names are the same, so see whether the user
900                ;; ID'ed one of them.
901                (id-supplied
902                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
903                   (unless v
904                     (error
905                      "invalid variable ID, ~W: should have been one of ~S"
906                      id
907                      (mapcar #'sb!di:debug-var-id vars)))
908                   ,(ecase ref-or-set
909                      (:ref
910                       '(sb!di:debug-var-value v *current-frame*))
911                      (:set
912                       `(setf (sb!di:debug-var-value v *current-frame*)
913                              ,value-var)))))
914                (t
915                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
916                        name
917                        (mapcar #'sb!di:debug-var-id vars)))))))))
918
919 ) ; EVAL-WHEN
920
921 ;;; FIXME: This doesn't work. It would be real nice we could make it
922 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
923 (defun var (name &optional (id 0 id-supplied))
924   #!+sb-doc
925   "Return a variable's value if possible. NAME is a simple-string or symbol.
926    If it is a simple-string, it is an initial substring of the variable's name.
927    If name is a symbol, it has the same name and package as the variable whose
928    value this function returns. If the symbol is uninterned, then the variable
929    has the same name as the symbol, but it has no package.
930
931    If name is the initial substring of variables with different names, then
932    this return no values after displaying the ambiguous names. If name
933    determines multiple variables with the same name, then you must use the
934    optional id argument to specify which one you want. If you left id
935    unspecified, then this returns no values after displaying the distinguishing
936    id values.
937
938    The result of this function is limited to the availability of variable
939    information. This is SETF'able."
940   (define-var-operation :ref))
941 (defun (setf var) (value name &optional (id 0 id-supplied))
942   (define-var-operation :set value))
943
944 ;;; This returns the COUNT'th arg as the user sees it from args, the
945 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
946 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
947 ;;; T. If this returns a keyword symbol or a value from a rest arg,
948 ;;; then the second value is NIL.
949 ;;;
950 ;;; FIXME: There's probably some way to merge the code here with
951 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
952 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
953 (declaim (ftype (function (index list)) nth-arg))
954 (defun nth-arg (count args)
955   (let ((n count))
956     (dolist (ele args (error "The argument specification ~S is out of range."
957                              n))
958       (lambda-list-element-dispatch ele
959         :required ((if (zerop n) (return (values ele t))))
960         :optional ((if (zerop n) (return (values (second ele) t))))
961         :keyword ((cond ((zerop n)
962                          (return (values (second ele) nil)))
963                         ((zerop (decf n))
964                          (return (values (third ele) t)))))
965         :deleted ((if (zerop n) (return (values ele t))))
966         :rest ((let ((var (second ele)))
967                  (lambda-var-dispatch var (sb!di:frame-code-location
968                                            *current-frame*)
969                    (error "unused &REST argument before n'th argument")
970                    (dolist (value
971                             (sb!di:debug-var-value var *current-frame*)
972                             (error
973                              "The argument specification ~S is out of range."
974                              n))
975                      (if (zerop n)
976                          (return-from nth-arg (values value nil))
977                          (decf n)))
978                    (error "invalid &REST argument before n'th argument")))))
979       (decf n))))
980
981 (defun arg (n)
982   #!+sb-doc
983   "Return the N'th argument's value if possible. Argument zero is the first
984    argument in a frame's default printed representation. Count keyword/value
985    pairs as separate arguments."
986   (multiple-value-bind (var lambda-var-p)
987       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
988                                 (sb!di:frame-debug-fun *current-frame*))
989                    (sb!di:lambda-list-unavailable ()
990                      (error "No argument values are available."))))
991     (if lambda-var-p
992         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
993           (error "Unused arguments have no values.")
994           (sb!di:debug-var-value var *current-frame*)
995           (error "invalid argument value"))
996         var)))
997 \f
998 ;;;; machinery for definition of debug loop commands
999
1000 (defvar *debug-commands* nil)
1001
1002 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1003 ;;; permitted.
1004 (defmacro !def-debug-command (name args &rest body)
1005   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1006     `(progn
1007        (setf *debug-commands*
1008              (remove ,name *debug-commands* :key #'car :test #'string=))
1009        (defun ,fun-name ,args
1010          (unless *in-the-debugger*
1011            (error "invoking debugger command while outside the debugger"))
1012          ,@body)
1013        (push (cons ,name #',fun-name) *debug-commands*)
1014        ',fun-name)))
1015
1016 (defun !def-debug-command-alias (new-name existing-name)
1017   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1018     (unless pair (error "unknown debug command name: ~S" existing-name))
1019     (push (cons new-name (cdr pair)) *debug-commands*))
1020   new-name)
1021
1022 ;;; This takes a symbol and uses its name to find a debugger command,
1023 ;;; using initial substring matching. It returns the command function
1024 ;;; if form identifies only one command, but if form is ambiguous,
1025 ;;; this returns a list of the command names. If there are no matches,
1026 ;;; this returns nil. Whenever the loop that looks for a set of
1027 ;;; possibilities encounters an exact name match, we return that
1028 ;;; command function immediately.
1029 (defun debug-command-p (form &optional other-commands)
1030   (if (or (symbolp form) (integerp form))
1031       (let* ((name
1032               (if (symbolp form)
1033                   (symbol-name form)
1034                   (format nil "~W" form)))
1035              (len (length name))
1036              (res nil))
1037         (declare (simple-string name)
1038                  (fixnum len)
1039                  (list res))
1040
1041         ;; Find matching commands, punting if exact match.
1042         (flet ((match-command (ele)
1043                  (let* ((str (car ele))
1044                         (str-len (length str)))
1045                    (declare (simple-string str)
1046                             (fixnum str-len))
1047                    (cond ((< str-len len))
1048                          ((= str-len len)
1049                           (when (string= name str :end1 len :end2 len)
1050                             (return-from debug-command-p (cdr ele))))
1051                          ((string= name str :end1 len :end2 len)
1052                           (push ele res))))))
1053           (mapc #'match-command *debug-commands*)
1054           (mapc #'match-command other-commands))
1055
1056         ;; Return the right value.
1057         (cond ((not res) nil)
1058               ((= (length res) 1)
1059                (cdar res))
1060               (t ; Just return the names.
1061                (do ((cmds res (cdr cmds)))
1062                    ((not cmds) res)
1063                  (setf (car cmds) (caar cmds))))))))
1064
1065 ;;; Return a list of debug commands (in the same format as
1066 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1067 ;;;
1068 ;;; Two commands are made for each restart: one for the number, and
1069 ;;; one for the restart name (unless it's been shadowed by an earlier
1070 ;;; restart of the same name, or it is NIL).
1071 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1072   (let ((commands)
1073         (num 0))                        ; better be the same as show-restarts!
1074     (dolist (restart restarts)
1075       (let ((name (string (restart-name restart))))
1076         (let ((restart-fun
1077                 (lambda ()
1078                   (/show0 "in restart-command closure, about to i-r-i")
1079                   (invoke-restart-interactively restart))))
1080           (push (cons (prin1-to-string num) restart-fun) commands)
1081           (unless (or (null (restart-name restart))
1082                       (find name commands :key #'car :test #'string=))
1083             (push (cons name restart-fun) commands))))
1084     (incf num))
1085   commands))
1086 \f
1087 ;;;; frame-changing commands
1088
1089 (!def-debug-command "UP" ()
1090   (let ((next (sb!di:frame-up *current-frame*)))
1091     (cond (next
1092            (setf *current-frame* next)
1093            (print-frame-call next *debug-io*))
1094           (t
1095            (format *debug-io* "~&Top of stack.")))))
1096
1097 (!def-debug-command "DOWN" ()
1098   (let ((next (sb!di:frame-down *current-frame*)))
1099     (cond (next
1100            (setf *current-frame* next)
1101            (print-frame-call next *debug-io*))
1102           (t
1103            (format *debug-io* "~&Bottom of stack.")))))
1104
1105 (!def-debug-command-alias "D" "DOWN")
1106
1107 (!def-debug-command "BOTTOM" ()
1108   (do ((prev *current-frame* lead)
1109        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1110       ((null lead)
1111        (setf *current-frame* prev)
1112        (print-frame-call prev *debug-io*))))
1113
1114 (!def-debug-command-alias "B" "BOTTOM")
1115
1116 (!def-debug-command "FRAME" (&optional
1117                              (n (read-prompting-maybe "frame number: ")))
1118   (setf *current-frame*
1119         (multiple-value-bind (next-frame-fun limit-string)
1120             (if (< n (sb!di:frame-number *current-frame*))
1121                 (values #'sb!di:frame-up "top")
1122               (values #'sb!di:frame-down "bottom"))
1123           (do ((frame *current-frame*))
1124               ((= n (sb!di:frame-number frame))
1125                frame)
1126             (let ((next-frame (funcall next-frame-fun frame)))
1127               (cond (next-frame
1128                      (setf frame next-frame))
1129                     (t
1130                      (format *debug-io*
1131                              "The ~A of the stack was encountered.~%"
1132                              limit-string)
1133                      (return frame)))))))
1134   (print-frame-call *current-frame* *debug-io*))
1135
1136 (!def-debug-command-alias "F" "FRAME")
1137 \f
1138 ;;;; commands for entering and leaving the debugger
1139
1140 (!def-debug-command "TOPLEVEL" ()
1141   (throw 'toplevel-catcher nil))
1142
1143 ;;; make T safe
1144 (!def-debug-command-alias "TOP" "TOPLEVEL")
1145
1146 (!def-debug-command "RESTART" ()
1147   (/show0 "doing RESTART debug-command")
1148   (let ((num (read-if-available :prompt)))
1149     (when (eq num :prompt)
1150       (show-restarts *debug-restarts* *debug-io*)
1151       (write-string "restart: " *debug-io*)
1152       (force-output *debug-io*)
1153       (setf num (read *debug-io*)))
1154     (let ((restart (typecase num
1155                      (unsigned-byte
1156                       (nth num *debug-restarts*))
1157                      (symbol
1158                       (find num *debug-restarts* :key #'restart-name
1159                             :test (lambda (sym1 sym2)
1160                                     (string= (symbol-name sym1)
1161                                              (symbol-name sym2)))))
1162                      (t
1163                       (format *debug-io* "~S is invalid as a restart name.~%"
1164                               num)
1165                       (return-from restart-debug-command nil)))))
1166       (/show0 "got RESTART")
1167       (if restart
1168           (invoke-restart-interactively restart)
1169           (princ "There is no such restart." *debug-io*)))))
1170 \f
1171 ;;;; information commands
1172
1173 (!def-debug-command "HELP" ()
1174   ;; CMU CL had a little toy pager here, but "if you aren't running
1175   ;; ILISP (or a smart windowing system, or something) you deserve to
1176   ;; lose", so we've dropped it in SBCL. However, in case some
1177   ;; desperate holdout is running this on a dumb terminal somewhere,
1178   ;; we tell him where to find the message stored as a string.
1179   (format *debug-io*
1180           "~&~A~2%(The HELP string is stored in ~S.)~%"
1181           *debug-help-string*
1182           '*debug-help-string*))
1183
1184 (!def-debug-command-alias "?" "HELP")
1185
1186 (!def-debug-command "ERROR" ()
1187   (format *debug-io* "~A~%" *debug-condition*)
1188   (show-restarts *debug-restarts* *debug-io*))
1189
1190 (!def-debug-command "BACKTRACE" ()
1191   (backtrace (read-if-available most-positive-fixnum)))
1192
1193 (!def-debug-command "PRINT" ()
1194   (print-frame-call *current-frame* *debug-io*))
1195
1196 (!def-debug-command-alias "P" "PRINT")
1197
1198 (!def-debug-command "LIST-LOCALS" ()
1199   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1200     (if (sb!di:debug-var-info-available d-fun)
1201         (let ((*standard-output* *debug-io*)
1202               (location (sb!di:frame-code-location *current-frame*))
1203               (prefix (read-if-available nil))
1204               (any-p nil)
1205               (any-valid-p nil))
1206           (dolist (v (sb!di:ambiguous-debug-vars
1207                         d-fun
1208                         (if prefix (string prefix) "")))
1209             (setf any-p t)
1210             (when (eq (sb!di:debug-var-validity v location) :valid)
1211               (setf any-valid-p t)
1212               (format *debug-io* "~S~:[#~W~;~*~]  =  ~S~%"
1213                       (sb!di:debug-var-symbol v)
1214                       (zerop (sb!di:debug-var-id v))
1215                       (sb!di:debug-var-id v)
1216                       (sb!di:debug-var-value v *current-frame*))))
1217
1218           (cond
1219            ((not any-p)
1220             (format *debug-io*
1221                     "There are no local variables ~@[starting with ~A ~]~
1222                     in the function."
1223                     prefix))
1224            ((not any-valid-p)
1225             (format *debug-io*
1226                     "All variables ~@[starting with ~A ~]currently ~
1227                     have invalid values."
1228                     prefix))))
1229         (write-line "There is no variable information available."
1230                     *debug-io*))))
1231
1232 (!def-debug-command-alias "L" "LIST-LOCALS")
1233
1234 (!def-debug-command "SOURCE" ()
1235   (print (code-location-source-form (sb!di:frame-code-location *current-frame*)
1236                                     (read-if-available 0))
1237          *debug-io*))
1238 \f
1239 ;;;; source location printing
1240
1241 ;;; We cache a stream to the last valid file debug source so that we
1242 ;;; won't have to repeatedly open the file.
1243 ;;;
1244 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1245 ;;; in the 1990s, so the benefit is negligible, less important than the
1246 ;;; potential of extra confusion if someone changes the source during
1247 ;;; a debug session and the change doesn't show up. And removing this
1248 ;;; would simplify the system, which I like. -- WHN 19990903
1249 (defvar *cached-debug-source* nil)
1250 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1251 (defvar *cached-source-stream* nil)
1252 (declaim (type (or stream null) *cached-source-stream*))
1253
1254 ;;; To suppress the read-time evaluation #. macro during source read,
1255 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1256 ;;; copying it each time, and invalidated when the
1257 ;;; *CACHED-DEBUG-SOURCE* has changed.
1258 (defvar *cached-readtable* nil)
1259 (declaim (type (or readtable null) *cached-readtable*))
1260
1261 ;;; Stuff to clean up before saving a core
1262 (defun debug-deinit ()
1263   (setf *cached-debug-source* nil
1264         *cached-source-stream* nil
1265         *cached-readtable* nil))
1266
1267 ;;; We also cache the last toplevel form that we printed a source for
1268 ;;; so that we don't have to do repeated reads and calls to
1269 ;;; FORM-NUMBER-TRANSLATIONS.
1270 (defvar *cached-toplevel-form-offset* nil)
1271 (declaim (type (or index null) *cached-toplevel-form-offset*))
1272 (defvar *cached-toplevel-form*)
1273 (defvar *cached-form-number-translations*)
1274
1275 ;;; Given a code location, return the associated form-number
1276 ;;; translations and the actual top level form. We check our cache ---
1277 ;;; if there is a miss, we dispatch on the kind of the debug source.
1278 (defun get-toplevel-form (location)
1279   (let ((d-source (sb!di:code-location-debug-source location)))
1280     (if (and (eq d-source *cached-debug-source*)
1281              (eql (sb!di:code-location-toplevel-form-offset location)
1282                   *cached-toplevel-form-offset*))
1283         (values *cached-form-number-translations* *cached-toplevel-form*)
1284         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1285                (res
1286                 (cond ((sb!di:debug-source-namestring d-source)
1287                        (get-file-toplevel-form location))
1288                       ((sb!di:debug-source-form d-source)
1289                        (sb!di:debug-source-form d-source))
1290                       (t (bug "Don't know how to use a DEBUG-SOURCE without ~
1291                                a namestring or a form.")))))
1292           (setq *cached-toplevel-form-offset* offset)
1293           (values (setq *cached-form-number-translations*
1294                         (sb!di:form-number-translations res offset))
1295                   (setq *cached-toplevel-form* res))))))
1296
1297 ;;; Locate the source file (if it still exists) and grab the top level
1298 ;;; form. If the file is modified, we use the top level form offset
1299 ;;; instead of the recorded character offset.
1300 (defun get-file-toplevel-form (location)
1301   (let* ((d-source (sb!di:code-location-debug-source location))
1302          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1303          (local-tlf-offset (- tlf-offset
1304                               (sb!di:debug-source-root-number d-source)))
1305          (char-offset
1306           (aref (or (sb!di:debug-source-start-positions d-source)
1307                     (error "no start positions map"))
1308                 local-tlf-offset))
1309          (name (sb!di:debug-source-namestring d-source)))
1310     (unless (eq d-source *cached-debug-source*)
1311       (unless (and *cached-source-stream*
1312                    (equal (pathname *cached-source-stream*)
1313                           (pathname name)))
1314         (setq *cached-readtable* nil)
1315         (when *cached-source-stream* (close *cached-source-stream*))
1316         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1317         (unless *cached-source-stream*
1318           (error "The source file no longer exists:~%  ~A" (namestring name)))
1319         (format *debug-io* "~%; file: ~A~%" (namestring name)))
1320
1321         (setq *cached-debug-source*
1322               (if (= (sb!di:debug-source-created d-source)
1323                      (file-write-date name))
1324                   d-source nil)))
1325
1326     (cond
1327      ((eq *cached-debug-source* d-source)
1328       (file-position *cached-source-stream* char-offset))
1329      (t
1330       (format *debug-io*
1331               "~%; File has been modified since compilation:~%;   ~A~@
1332                  ; Using form offset instead of character position.~%"
1333               (namestring name))
1334       (file-position *cached-source-stream* 0)
1335       (let ((*read-suppress* t))
1336         (dotimes (i local-tlf-offset)
1337           (read *cached-source-stream*)))))
1338     (unless *cached-readtable*
1339       (setq *cached-readtable* (copy-readtable))
1340       (set-dispatch-macro-character
1341        #\# #\.
1342        (lambda (stream sub-char &rest rest)
1343          (declare (ignore rest sub-char))
1344          (let ((token (read stream t nil t)))
1345            (format nil "#.~S" token)))
1346        *cached-readtable*))
1347     (let ((*readtable* *cached-readtable*))
1348       (read *cached-source-stream*))))
1349
1350 (defun code-location-source-form (location context)
1351   (let* ((location (maybe-block-start-location location))
1352          (form-num (sb!di:code-location-form-number location)))
1353     (multiple-value-bind (translations form) (get-toplevel-form location)
1354       (unless (< form-num (length translations))
1355         (error "The source path no longer exists."))
1356       (sb!di:source-path-context form
1357                                  (svref translations form-num)
1358                                  context))))
1359 \f
1360
1361 ;;; start single-stepping
1362 (!def-debug-command "START" ()
1363   (if (typep *debug-condition* 'step-condition)
1364       (format *debug-io* "~&Already single-stepping.~%")
1365       (let ((restart (find-restart 'continue *debug-condition*)))
1366         (cond (restart
1367                (sb!impl::enable-stepping)
1368                (invoke-restart restart))
1369               (t
1370                (format *debug-io* "~&Non-continuable error, cannot start stepping.~%"))))))
1371
1372 (defmacro def-step-command (command-name restart-name)
1373   `(!def-debug-command ,command-name ()
1374      (if (typep *debug-condition* 'step-condition)
1375          (let ((restart (find-restart ',restart-name *debug-condition*)))
1376            (aver restart)
1377            (invoke-restart restart))
1378          (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%"))))
1379
1380 (def-step-command "STEP" step-into)
1381 (def-step-command "NEXT" step-next)
1382 (def-step-command "STOP" step-continue)
1383
1384 (!def-debug-command-alias "S" "STEP")
1385 (!def-debug-command-alias "N" "NEXT")
1386
1387 (!def-debug-command "OUT" ()
1388   (if (typep *debug-condition* 'step-condition)
1389       (if sb!impl::*step-out*
1390           (let ((restart (find-restart 'step-out *debug-condition*)))
1391             (aver restart)
1392             (invoke-restart restart))
1393           (format *debug-io* "~&OUT can only be used step out of frames that were originally stepped into with STEP.~%"))
1394       (format *debug-io* "~&Not currently single-stepping. (Use START to activate the single-stepper)~%")))
1395
1396 ;;; miscellaneous commands
1397
1398 (!def-debug-command "DESCRIBE" ()
1399   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1400          (debug-fun (sb!di:code-location-debug-fun curloc))
1401          (function (sb!di:debug-fun-fun debug-fun)))
1402     (if function
1403         (describe function)
1404         (format *debug-io* "can't figure out the function for this frame"))))
1405
1406 (!def-debug-command "SLURP" ()
1407   (loop while (read-char-no-hang *standard-input*)))
1408
1409 ;;; RETURN-FROM-FRAME and RESTART-FRAME
1410
1411 (defun unwind-to-frame-and-call (frame thunk)
1412   #!+unwind-to-frame-and-call-vop
1413   (flet ((sap-int/fixnum (sap)
1414            ;; On unithreaded X86 *BINDING-STACK-POINTER* and
1415            ;; *CURRENT-CATCH-BLOCK* are negative, so we need to jump through
1416            ;; some hoops to make these calculated values negative too.
1417            (ash (truly-the (signed-byte #.sb!vm:n-word-bits)
1418                            (sap-int sap))
1419                 (- sb!vm::n-fixnum-tag-bits))))
1420     ;; To properly unwind the stack, we need three pieces of information:
1421     ;;   * The unwind block that should be active after the unwind
1422     ;;   * The catch block that should be active after the unwind
1423     ;;   * The values that the binding stack pointer should have after the
1424     ;;     unwind.
1425     (let* ((block (sap-int/fixnum (find-enclosing-catch-block frame)))
1426            (unbind-to (sap-int/fixnum (find-binding-stack-pointer frame))))
1427       ;; This VOP will run the neccessary cleanup forms, reset the fp, and
1428       ;; then call the supplied function.
1429       (sb!vm::%primitive sb!vm::unwind-to-frame-and-call
1430                          (sb!di::frame-pointer frame)
1431                          (find-enclosing-uwp frame)
1432                          (lambda ()
1433                            ;; Before calling the user-specified
1434                            ;; function, we need to restore the binding
1435                            ;; stack and the catch block. The unwind block
1436                            ;; is taken care of by the VOP.
1437                            (sb!vm::%primitive sb!vm::unbind-to-here
1438                                               unbind-to)
1439                            (setf sb!vm::*current-catch-block* block)
1440                            (funcall thunk)))))
1441   #!-unwind-to-frame-and-call-vop
1442   (let ((tag (gensym)))
1443     (sb!di:replace-frame-catch-tag frame
1444                                    'sb!c:debug-catch-tag
1445                                    tag)
1446     (throw tag thunk)))
1447
1448 (defun find-binding-stack-pointer (frame)
1449   #!-stack-grows-downward-not-upward
1450   (declare (ignore frame))
1451   #!-stack-grows-downward-not-upward
1452   (error "Not implemented on this architecture")
1453   #!+stack-grows-downward-not-upward
1454   (let ((bsp (sb!vm::binding-stack-pointer-sap))
1455         (unbind-to nil)
1456         (fp (sb!di::frame-pointer frame))
1457         (start (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1458                              (ash sb!vm:*binding-stack-start*
1459                                   sb!vm:n-fixnum-tag-bits)))))
1460     ;; Walk the binding stack looking for an entry where the symbol is
1461     ;; an unbound-symbol marker and the value is equal to the frame
1462     ;; pointer.  These entries are inserted into the stack by the
1463     ;; BIND-SENTINEL VOP and removed by UNBIND-SENTINEL (inserted into
1464     ;; the function during IR2). If an entry wasn't found, the
1465     ;; function that the frame corresponds to wasn't compiled with a
1466     ;; high enough debug setting, and can't be restarted / returned
1467     ;; from.
1468     (loop until (sap= bsp start)
1469           do (progn
1470                (setf bsp (sap+ bsp
1471                                (- (* sb!vm:binding-size sb!vm:n-word-bytes))))
1472                (let ((symbol (sap-ref-word bsp (* sb!vm:binding-symbol-slot
1473                                                   sb!vm:n-word-bytes)))
1474                      (value (sap-ref-sap bsp (* sb!vm:binding-value-slot
1475                                                 sb!vm:n-word-bytes))))
1476                  (when (eql symbol sb!vm:unbound-marker-widetag)
1477                    (when (sap= value fp)
1478                      (setf unbind-to bsp))))))
1479     unbind-to))
1480
1481 (defun find-enclosing-catch-block (frame)
1482   ;; Walk the catch block chain looking for the first entry with an address
1483   ;; higher than the pointer for FRAME or a null pointer.
1484   (let* ((frame-pointer (sb!di::frame-pointer frame))
1485          (current-block (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1486                                       (ash sb!vm::*current-catch-block*
1487                                            sb!vm:n-fixnum-tag-bits))))
1488          (enclosing-block (loop for block = current-block
1489                                 then (sap-ref-sap block
1490                                                   (* sb!vm:catch-block-previous-catch-slot
1491                                                      sb!vm::n-word-bytes))
1492                                 when (or (zerop (sap-int block))
1493                                          (sap> block frame-pointer))
1494                                 return block)))
1495     enclosing-block))
1496
1497 (defun find-enclosing-uwp (frame)
1498   ;; Walk the UWP chain looking for the first entry with an address
1499   ;; higher than the pointer for FRAME or a null pointer.
1500   (let* ((frame-pointer (sb!di::frame-pointer frame))
1501          (current-uwp (int-sap (ldb (byte #.sb!vm:n-word-bits 0)
1502                                     (ash sb!vm::*current-unwind-protect-block*
1503                                          sb!vm:n-fixnum-tag-bits))))
1504          (enclosing-uwp (loop for uwp-block = current-uwp
1505                               then (sap-ref-sap uwp-block
1506                                                 sb!vm:unwind-block-current-uwp-slot)
1507                               when (or (zerop (sap-int uwp-block))
1508                                        (sap> uwp-block frame-pointer))
1509                               return uwp-block)))
1510     enclosing-uwp))
1511
1512 (!def-debug-command "RETURN" (&optional
1513                               (return (read-prompting-maybe
1514                                        "return: ")))
1515    (if (frame-has-debug-tag-p *current-frame*)
1516        (let* ((code-location (sb!di:frame-code-location *current-frame*))
1517               (values (multiple-value-list
1518                        (funcall (sb!di:preprocess-for-eval return code-location)
1519                                 *current-frame*))))
1520          (unwind-to-frame-and-call *current-frame* (lambda ()
1521                                                      (values-list values))))
1522        (format *debug-io*
1523                "~@<can't find a tag for this frame ~
1524                  ~2I~_(hint: try increasing the DEBUG optimization quality ~
1525                  and recompiling)~:@>")))
1526
1527 (!def-debug-command "RESTART-FRAME" ()
1528   (if (frame-has-debug-tag-p *current-frame*)
1529       (let* ((call-list (frame-call-as-list *current-frame*))
1530              (fun (fdefinition (car call-list))))
1531         (unwind-to-frame-and-call *current-frame*
1532                                   (lambda ()
1533                                     (apply fun (cdr call-list)))))
1534       (format *debug-io*
1535               "~@<can't find a tag for this frame ~
1536                  ~2I~_(hint: try increasing the DEBUG optimization quality ~
1537                  and recompiling)~:@>")))
1538
1539 (defun frame-has-debug-tag-p (frame)
1540   #!+unwind-to-frame-and-call-vop
1541   (not (null (find-binding-stack-pointer frame)))
1542   #!-unwind-to-frame-and-call-vop
1543   (find 'sb!c:debug-catch-tag (sb!di::frame-catches frame) :key #'car))
1544
1545 ;; Hack: ensure that *U-T-F-F* has a tls index.
1546 #!+unwind-to-frame-and-call-vop
1547 (let ((sb!vm::*unwind-to-frame-function* (lambda ()))))
1548
1549 \f
1550 ;;;; debug loop command utilities
1551
1552 (defun read-prompting-maybe (prompt)
1553   (unless (sb!int:listen-skip-whitespace *debug-io*)
1554     (princ prompt *debug-io*)
1555     (force-output *debug-io*))
1556   (read *debug-io*))
1557
1558 (defun read-if-available (default)
1559   (if (sb!int:listen-skip-whitespace *debug-io*)
1560       (read *debug-io*)
1561       default))