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