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