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