632ddc4e0a73afb3f55a1db9ad829db49aabfdad
[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 ;;;
35 ;;; FIXME: These variables were deprecated in late February 2004, and
36 ;;; can probably be removed in about a year.
37 (defvar *debug-print-level* 5
38   #!+sb-doc
39   "(This is deprecated in favor of *DEBUG-PRINT-VARIABLE-ALIST*.)
40
41 *PRINT-LEVEL* for the debugger")
42 (defvar *debug-print-length* 7
43   #!+sb-doc
44   "(This is deprecated in favor of *DEBUG-PRINT-VARIABLE-ALIST*.)
45
46 *PRINT-LENGTH* for the debugger")
47
48 (defvar *debug-print-variable-alist* nil
49   #!+sb-doc
50   "an association list describing new bindings for special variables
51 (typically *PRINT-FOO* variables) to be used within the debugger, e.g.
52 ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))")
53
54 (defvar *debug-readtable*
55   ;; KLUDGE: This can't be initialized in a cold toplevel form,
56   ;; because the *STANDARD-READTABLE* isn't initialized until after
57   ;; cold toplevel forms have run. So instead we initialize it
58   ;; immediately after *STANDARD-READTABLE*. -- WHN 20000205
59   nil
60   #!+sb-doc
61   "*READTABLE* for the debugger")
62
63 (defvar *in-the-debugger* nil
64   #!+sb-doc
65   "This is T while in the debugger.")
66
67 ;;; nestedness inside debugger command loops
68 (defvar *debug-command-level* 0)
69
70 ;;; If this is bound before the debugger is invoked, it is used as the
71 ;;; stack top by the debugger.
72 (defvar *stack-top-hint* nil)
73
74 (defvar *stack-top* nil)
75 (defvar *real-stack-top* nil)
76
77 (defvar *current-frame* nil)
78
79 ;;; Beginner-oriented help messages are important because you end up
80 ;;; in the debugger whenever something bad happens, or if you try to
81 ;;; get out of the system with Ctrl-C or (EXIT) or EXIT or whatever.
82 ;;; But after memorizing them the wasted screen space gets annoying..
83 (defvar *debug-beginner-help-p* t
84   "Should the debugger display beginner-oriented help messages?")
85
86 (defun debug-prompt (stream)
87   (sb!thread::get-foreground)
88   (format stream
89           "~%~W~:[~;[~W~]] "
90           (sb!di:frame-number *current-frame*)
91           (> *debug-command-level* 1)
92           *debug-command-level*))
93   
94 (defparameter *debug-help-string*
95 "The debug prompt is square brackets, with number(s) indicating the current
96   control stack level and, if you've entered the debugger recursively, how
97   deeply recursed you are.
98 Any command -- including the name of a restart -- may be uniquely abbreviated.
99 The debugger rebinds various special variables for controlling i/o, sometimes
100   to defaults (much like WITH-STANDARD-IO-SYNTAX does) and sometimes to 
101   its own special values, e.g. SB-DEBUG:*DEBUG-PRINT-LEVEL*.
102 Debug commands do not affect *, //, and similar variables, but evaluation in
103   the debug loop does affect these variables.
104 SB-DEBUG:*FLUSH-DEBUG-ERRORS* controls whether errors at the debug prompt
105   drop you deeper into the debugger.
106
107 Getting in and out of the debugger:
108   RESTART  invokes restart numbered as shown (prompt if not given).
109   ERROR    prints the error condition and restart cases.
110   The number of any restart, or its name, or a unique abbreviation for its
111     name, is a valid command, and is the same as using RESTART to invoke
112     that restart.
113
114 Changing frames:
115   U      up frame     D    down frame
116   B  bottom frame     F n  frame n (n=0 for top frame)
117
118 Inspecting frames:
119   BACKTRACE [n]  shows n frames going down the stack.
120   LIST-LOCALS, L lists locals in current function.
121   PRINT, P       displays current function call.
122   SOURCE [n]     displays frame's source form with n levels of enclosing forms.
123
124 Breakpoints and steps:
125   LIST-LOCATIONS [{function | :C}]   List the locations for breakpoints.
126                                      Specify :C for the current frame.
127     Abbreviation: LL
128   LIST-BREAKPOINTS                   List the active breakpoints.
129     Abbreviations: LB, LBP
130   DELETE-BREAKPOINT [n]              Remove breakpoint n or all breakpoints.
131     Abbreviations: DEL, DBP
132   BREAKPOINT {n | :end | :start} [:break form] [:function function]
133              [{:print form}*] [:condition form]
134                                      Set a breakpoint.
135     Abbreviations: BR, BP
136   STEP [n]                           Step to the next location or step n times.
137
138 Function and macro commands:
139  (SB-DEBUG:ARG n)
140     Return the n'th argument in the current frame.
141  (SB-DEBUG:VAR string-or-symbol [id])
142     Returns the value of the specified variable in the current frame.
143
144 Other commands:
145   RETURN expr
146     [EXPERIMENTAL] Return the values resulting from evaluation of expr
147     from the current frame, if this frame was compiled with a sufficiently
148     high DEBUG optimization quality.
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 ;;; This is used to communicate to DEBUG-LOOP that we are at a step breakpoint.
155 (define-condition step-condition (simple-condition) ())
156 \f
157 ;;;; breakpoint state
158
159 (defvar *only-block-start-locations* nil
160   #!+sb-doc
161   "When true, the LIST-LOCATIONS command only displays block start locations.
162    Otherwise, all locations are displayed.")
163
164 (defvar *print-location-kind* nil
165   #!+sb-doc
166   "When true, list the code location type in the LIST-LOCATIONS command.")
167
168 ;;; a list of the types of code-locations that should not be stepped
169 ;;; to and should not be listed when listing breakpoints
170 (defvar *bad-code-location-types* '(:call-site :internal-error))
171 (declaim (type list *bad-code-location-types*))
172
173 ;;; code locations of the possible breakpoints
174 (defvar *possible-breakpoints*)
175 (declaim (type list *possible-breakpoints*))
176
177 ;;; a list of the made and active breakpoints, each is a
178 ;;; BREAKPOINT-INFO structure
179 (defvar *breakpoints* nil)
180 (declaim (type list *breakpoints*))
181
182 ;;; a list of BREAKPOINT-INFO structures of the made and active step
183 ;;; breakpoints
184 (defvar *step-breakpoints* nil)
185 (declaim (type list *step-breakpoints*))
186
187 ;;; the number of times left to step
188 (defvar *number-of-steps* 1)
189 (declaim (type integer *number-of-steps*))
190
191 ;;; This is used when listing and setting breakpoints.
192 (defvar *default-breakpoint-debug-fun* nil)
193 (declaim (type (or list sb!di:debug-fun) *default-breakpoint-debug-fun*))
194 \f
195 ;;;; code location utilities
196
197 ;;; Return the first code-location in the passed debug block.
198 (defun first-code-location (debug-block)
199   (let ((found nil)
200         (first-code-location nil))
201     (sb!di:do-debug-block-locations (code-location debug-block)
202       (unless found
203         (setf first-code-location code-location)
204         (setf found t)))
205     first-code-location))
206
207 ;;; Return a list of the next code-locations following the one passed.
208 ;;; One of the *BAD-CODE-LOCATION-TYPES* will not be returned.
209 (defun next-code-locations (code-location)
210   (let ((debug-block (sb!di:code-location-debug-block code-location))
211         (block-code-locations nil))
212     (sb!di:do-debug-block-locations (block-code-location debug-block)
213       (unless (member (sb!di:code-location-kind block-code-location)
214                       *bad-code-location-types*)
215         (push block-code-location block-code-locations)))
216     (setf block-code-locations (nreverse block-code-locations))
217     (let* ((code-loc-list (rest (member code-location block-code-locations
218                                         :test #'sb!di:code-location=)))
219            (next-list (cond (code-loc-list
220                              (list (first code-loc-list)))
221                             ((map 'list #'first-code-location
222                                   (sb!di:debug-block-successors debug-block)))
223                             (t nil))))
224       (when (and (= (length next-list) 1)
225                  (sb!di:code-location= (first next-list) code-location))
226         (setf next-list (next-code-locations (first next-list))))
227       next-list)))
228
229 ;;; Return a list of code-locations of the possible breakpoints of DEBUG-FUN.
230 (defun possible-breakpoints (debug-fun)
231   (let ((possible-breakpoints nil))
232     (sb!di:do-debug-fun-blocks (debug-block debug-fun)
233       (unless (sb!di:debug-block-elsewhere-p debug-block)
234         (if *only-block-start-locations*
235             (push (first-code-location debug-block) possible-breakpoints)
236             (sb!di:do-debug-block-locations (code-location debug-block)
237               (when (not (member (sb!di:code-location-kind code-location)
238                                  *bad-code-location-types*))
239                 (push code-location possible-breakpoints))))))
240     (nreverse possible-breakpoints)))
241
242 ;;; Search the info-list for the item passed (CODE-LOCATION,
243 ;;; DEBUG-FUN, or BREAKPOINT-INFO). If the item passed is a debug
244 ;;; function then kind will be compared if it was specified. The kind
245 ;;; if also compared if a breakpoint-info is passed since it's in the
246 ;;; breakpoint. The info structure is returned if found.
247 (defun location-in-list (place info-list &optional (kind nil))
248   (when (breakpoint-info-p place)
249     (setf kind (sb!di:breakpoint-kind (breakpoint-info-breakpoint place)))
250     (setf place (breakpoint-info-place place)))
251   (cond ((sb!di:code-location-p place)
252          (find place info-list
253                :key #'breakpoint-info-place
254                :test (lambda (x y) (and (sb!di:code-location-p y)
255                                         (sb!di:code-location= x y)))))
256         (t
257          (find place info-list
258                :test (lambda (x-debug-fun y-info)
259                        (let ((y-place (breakpoint-info-place y-info))
260                              (y-breakpoint (breakpoint-info-breakpoint
261                                             y-info)))
262                          (and (sb!di:debug-fun-p y-place)
263                               (eq x-debug-fun y-place)
264                               (or (not kind)
265                                   (eq kind (sb!di:breakpoint-kind
266                                             y-breakpoint))))))))))
267
268 ;;; If LOC is an unknown location, then try to find the block start
269 ;;; location. Used by source printing to some information instead of
270 ;;; none for the user.
271 (defun maybe-block-start-location (loc)
272   (if (sb!di:code-location-unknown-p loc)
273       (let* ((block (sb!di:code-location-debug-block loc))
274              (start (sb!di:do-debug-block-locations (loc block)
275                       (return loc))))
276         (cond ((and (not (sb!di:debug-block-elsewhere-p block))
277                     start)
278                ;; FIXME: Why output on T instead of *DEBUG-FOO* or something?
279                (format t "~%unknown location: using block start~%")
280                start)
281               (t
282                loc)))
283       loc))
284 \f
285 ;;;; the BREAKPOINT-INFO structure
286
287 ;;; info about a made breakpoint
288 (defstruct (breakpoint-info (:copier nil)
289                             (:constructor %make-breakpoint-info))
290   ;; where we are going to stop
291   (place (missing-arg)
292          :type (or sb!di:code-location sb!di:debug-fun)
293          :read-only t)
294   ;; the breakpoint returned by SB!DI:MAKE-BREAKPOINT
295   (breakpoint (missing-arg) :type sb!di:breakpoint :read-only t)
296   ;; the function returned from SB!DI:PREPROCESS-FOR-EVAL. If result is
297   ;; non-NIL, drop into the debugger.
298   (break #'identity :type function :read-only t)
299   ;; the function returned from SB!DI:PREPROCESS-FOR-EVAL. If result is
300   ;; non-NIL, eval (each) print and print results.
301   (condition #'identity :type function :read-only t)
302   ;; the list of functions from SB!DI:PREPROCESS-FOR-EVAL to evaluate.
303   ;; Results are conditionally printed. CAR of each element is the
304   ;; function, CDR is the form it goes with.
305   (print nil :type list :read-only t)
306   ;; the number used when listing the possible breakpoints within a
307   ;; function; or could also be a symbol such as START or END
308   (code-location-selector (missing-arg) :type (or symbol integer) :read-only t)
309   ;; the number used when listing the active breakpoints, and when
310   ;; deleting breakpoints
311   (breakpoint-number (missing-arg) :type integer :read-only t))
312
313 (defun create-breakpoint-info (place breakpoint code-location-selector
314                                      &key (break #'identity)
315                                      (condition #'identity) (print nil))
316   (setf *breakpoints*
317         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
318   (let ((breakpoint-number
319          (do ((i 1 (incf i)) (breakpoints *breakpoints* (rest breakpoints)))
320              ((or (> i (length *breakpoints*))
321                   (not (= i (breakpoint-info-breakpoint-number
322                              (first breakpoints)))))
323
324               i))))
325     (%make-breakpoint-info :place place
326                            :breakpoint breakpoint
327                            :code-location-selector code-location-selector
328                            :breakpoint-number breakpoint-number
329                            :break break
330                            :condition condition
331                            :print print)))
332
333 (defun print-breakpoint-info (breakpoint-info)
334   (let ((place (breakpoint-info-place breakpoint-info))
335         (bp-number (breakpoint-info-breakpoint-number breakpoint-info)))
336     (case (sb!di:breakpoint-kind (breakpoint-info-breakpoint breakpoint-info))
337       (:code-location
338        (print-code-location-source-form place 0)
339        (format t
340                "~&~S: ~S in ~S"
341                bp-number
342                (breakpoint-info-code-location-selector breakpoint-info)
343                (sb!di:debug-fun-name (sb!di:code-location-debug-fun place))))
344       (:fun-start
345        (format t "~&~S: FUN-START in ~S" bp-number
346                (sb!di:debug-fun-name place)))
347       (:fun-end
348        (format t "~&~S: FUN-END in ~S" bp-number
349                (sb!di:debug-fun-name place))))))
350 \f
351 ;;;; MAIN-HOOK-FUN for steps and breakpoints
352
353 ;;; This must be passed as the hook function. It keeps track of where
354 ;;; STEP breakpoints are.
355 (defun main-hook-fun (current-frame breakpoint &optional return-vals
356                                     fun-end-cookie)
357   (setf *default-breakpoint-debug-fun*
358         (sb!di:frame-debug-fun current-frame))
359   (dolist (step-info *step-breakpoints*)
360     (sb!di:delete-breakpoint (breakpoint-info-breakpoint step-info))
361     (let ((bp-info (location-in-list step-info *breakpoints*)))
362       (when bp-info
363         (sb!di:activate-breakpoint (breakpoint-info-breakpoint bp-info)))))
364   (let ((*stack-top-hint* current-frame)
365         (step-hit-info
366          (location-in-list (sb!di:breakpoint-what breakpoint)
367                            *step-breakpoints*
368                            (sb!di:breakpoint-kind breakpoint)))
369         (bp-hit-info
370          (location-in-list (sb!di:breakpoint-what breakpoint)
371                            *breakpoints*
372                            (sb!di:breakpoint-kind breakpoint)))
373         (break)
374         (condition)
375         (string ""))
376     (setf *step-breakpoints* nil)
377     (labels ((build-string (str)
378                (setf string (concatenate 'string string str)))
379              (print-common-info ()
380                (build-string
381                 (with-output-to-string (*standard-output*)
382                   (when fun-end-cookie
383                     (format t "~%Return values: ~S" return-vals))
384                   (when condition
385                     (when (breakpoint-info-print bp-hit-info)
386                       (format t "~%")
387                       (print-frame-call current-frame))
388                     (dolist (print (breakpoint-info-print bp-hit-info))
389                       (format t "~& ~S = ~S" (rest print)
390                               (funcall (first print) current-frame))))))))
391       (when bp-hit-info
392         (setf break (funcall (breakpoint-info-break bp-hit-info)
393                              current-frame))
394         (setf condition (funcall (breakpoint-info-condition bp-hit-info)
395                                  current-frame)))
396       (cond ((and bp-hit-info step-hit-info (= 1 *number-of-steps*))
397              (build-string (format nil "~&*Step (to a breakpoint)*"))
398              (print-common-info)
399              (break string))
400             ((and bp-hit-info step-hit-info break)
401              (build-string (format nil "~&*Step (to a breakpoint)*"))
402              (print-common-info)
403              (break string))
404             ((and bp-hit-info step-hit-info)
405              (print-common-info)
406              (format t "~A" string)
407              (decf *number-of-steps*)
408              (set-step-breakpoint current-frame))
409             ((and step-hit-info (= 1 *number-of-steps*))
410              (build-string "*Step*")
411              (break (make-condition 'step-condition :format-control string)))
412             (step-hit-info
413              (decf *number-of-steps*)
414              (set-step-breakpoint current-frame))
415             (bp-hit-info
416              (when break
417                (build-string (format nil "~&*Breakpoint hit*")))
418              (print-common-info)
419              (if break
420                  (break string)
421                  (format t "~A" string)))
422             (t
423              (break "unknown breakpoint"))))))
424 \f
425 ;;; Set breakpoints at the next possible code-locations. After calling
426 ;;; this, either (CONTINUE) if in the debugger or just let program flow
427 ;;; return if in a hook function.
428 (defun set-step-breakpoint (frame)
429   (cond
430    ((sb!di:debug-block-elsewhere-p (sb!di:code-location-debug-block
431                                     (sb!di:frame-code-location frame)))
432     ;; FIXME: FORMAT T is used for error output here and elsewhere in
433     ;; the debug code.
434     (format t "cannot step, in elsewhere code~%"))
435    (t
436     (let* ((code-location (sb!di:frame-code-location frame))
437            (next-code-locations (next-code-locations code-location)))
438       (cond
439        (next-code-locations
440         (dolist (code-location next-code-locations)
441           (let ((bp-info (location-in-list code-location *breakpoints*)))
442             (when bp-info
443               (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
444                                             bp-info))))
445           (let ((bp (sb!di:make-breakpoint #'main-hook-fun code-location
446                                            :kind :code-location)))
447             (sb!di:activate-breakpoint bp)
448             (push (create-breakpoint-info code-location bp 0)
449                   *step-breakpoints*))))
450        (t
451         (let* ((debug-fun (sb!di:frame-debug-fun *current-frame*))
452                (bp (sb!di:make-breakpoint #'main-hook-fun debug-fun
453                                           :kind :fun-end)))
454           (sb!di:activate-breakpoint bp)
455           (push (create-breakpoint-info debug-fun bp 0)
456                 *step-breakpoints*))))))))
457 \f
458 ;;;; STEP
459
460 ;;; ANSI specifies that this macro shall exist, even if only as a
461 ;;; trivial placeholder like this.
462 (defmacro step (form)
463   "This is a trivial placeholder implementation of the CL:STEP macro required
464    by the ANSI spec, simply expanding to `(LET () ,FORM). A more featureful
465    version would be welcome, we just haven't written it."
466   `(let ()
467      ,form))
468 \f
469 ;;;; BACKTRACE
470
471 (defun backtrace (&optional (count most-positive-fixnum)
472                             (*standard-output* *debug-io*))
473   #!+sb-doc
474   "Show a listing of the call stack going down from the current frame. In the
475    debugger, the current frame is indicated by the prompt. COUNT is how many
476    frames to show."
477   (fresh-line *standard-output*)
478   (do ((frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
479               (sb!di:frame-down frame))
480        (count count (1- count)))
481       ((or (null frame) (zerop count)))
482     (print-frame-call frame :number t))
483   (fresh-line *standard-output*)
484   (values))
485
486 (defun backtrace-as-list (&optional (count most-positive-fixnum))
487   #!+sb-doc "Return a list representing the current BACKTRACE."
488   (do ((reversed-result nil)
489        (frame (if *in-the-debugger* *current-frame* (sb!di:top-frame))
490               (sb!di:frame-down frame))
491        (count count (1- count)))
492       ((or (null frame) (zerop count))
493        (nreverse reversed-result))
494     (push (frame-call-as-list frame) reversed-result)))
495
496 (defun frame-call-as-list (frame)
497   (cons (sb!di:debug-fun-name (sb!di:frame-debug-fun frame))
498         (frame-args-as-list frame)))
499 \f
500 ;;;; frame printing
501
502 (eval-when (:compile-toplevel :execute)
503
504 ;;; This is a convenient way to express what to do for each type of
505 ;;; lambda-list element.
506 (sb!xc:defmacro lambda-list-element-dispatch (element
507                                               &key
508                                               required
509                                               optional
510                                               rest
511                                               keyword
512                                               deleted)
513   `(etypecase ,element
514      (sb!di:debug-var
515       ,@required)
516      (cons
517       (ecase (car ,element)
518         (:optional ,@optional)
519         (:rest ,@rest)
520         (:keyword ,@keyword)))
521      (symbol
522       (aver (eq ,element :deleted))
523       ,@deleted)))
524
525 (sb!xc:defmacro lambda-var-dispatch (variable location deleted valid other)
526   (let ((var (gensym)))
527     `(let ((,var ,variable))
528        (cond ((eq ,var :deleted) ,deleted)
529              ((eq (sb!di:debug-var-validity ,var ,location) :valid)
530               ,valid)
531              (t ,other)))))
532
533 ) ; EVAL-WHEN
534
535 ;;; This is used in constructing arg lists for debugger printing when
536 ;;; the arg list is unavailable, some arg is unavailable or unused, etc.
537 (defstruct (unprintable-object
538             (:constructor make-unprintable-object (string))
539             (:print-object (lambda (x s)
540                              (print-unreadable-object (x s)
541                                (write-string (unprintable-object-string x)
542                                              s))))
543             (:copier nil))
544   string)
545
546 ;;; Extract the function argument values for a debug frame.
547 (defun frame-args-as-list (frame)
548   (let ((debug-fun (sb!di:frame-debug-fun frame))
549         (loc (sb!di:frame-code-location frame))
550         (reversed-result nil))
551     (handler-case
552         (progn
553           (dolist (ele (sb!di:debug-fun-lambda-list debug-fun))
554             (lambda-list-element-dispatch ele
555              :required ((push (frame-call-arg ele loc frame) reversed-result))
556              :optional ((push (frame-call-arg (second ele) loc frame)
557                               reversed-result))
558              :keyword ((push (second ele) reversed-result)
559                        (push (frame-call-arg (third ele) loc frame)
560                              reversed-result))
561              :deleted ((push (frame-call-arg ele loc frame) reversed-result))
562              :rest ((lambda-var-dispatch (second ele) loc
563                      nil
564                      (progn
565                        (setf reversed-result
566                              (append (reverse (sb!di:debug-var-value
567                                                (second ele) frame))
568                                      reversed-result))
569                        (return))
570                      (push (make-unprintable-object
571                             "unavailable &REST argument")
572                      reversed-result)))))
573           ;; As long as we do an ordinary return (as opposed to SIGNALing
574           ;; a CONDITION) from the DOLIST above:
575           (nreverse reversed-result))
576       (sb!di:lambda-list-unavailable
577        ()
578        (make-unprintable-object "unavailable lambda list")))))
579
580 ;;; Print FRAME with verbosity level 1. If we hit a &REST arg, then
581 ;;; print as many of the values as possible, punting the loop over
582 ;;; lambda-list variables since any other arguments will be in the
583 ;;; &REST arg's list of values.
584 (defun print-frame-call-1 (frame)
585   (let ((debug-fun (sb!di:frame-debug-fun frame)))
586
587     (pprint-logical-block (*standard-output* nil :prefix "(" :suffix ")")
588       (let ((args (ensure-printable-object (frame-args-as-list frame))))
589         ;; Since we go to some trouble to make nice informative function
590         ;; names like (PRINT-OBJECT :AROUND (CLOWN T)), let's make sure
591         ;; that they aren't truncated by *PRINT-LENGTH* and *PRINT-LEVEL*.
592         (let ((*print-length* nil)
593               (*print-level* nil))
594           (prin1 (ensure-printable-object (sb!di:debug-fun-name debug-fun))))
595         ;; For the function arguments, we can just print normally.
596         (if (listp args)
597             (format t "~{ ~_~S~}" args)
598             (format t " ~S" args))))
599
600     (when (sb!di:debug-fun-kind debug-fun)
601       (write-char #\[)
602       (prin1 (sb!di:debug-fun-kind debug-fun))
603       (write-char #\]))))
604
605 (defun ensure-printable-object (object)
606   (handler-case
607       (with-open-stream (out (make-broadcast-stream))
608         (prin1 object out)
609         object)
610     (error (cond)
611       (declare (ignore cond))
612       (make-unprintable-object "error printing object"))))
613
614 (defun frame-call-arg (var location frame)
615   (lambda-var-dispatch var location
616     (make-unprintable-object "unused argument")
617     (sb!di:debug-var-value var frame)
618     (make-unprintable-object "unavailable argument")))
619
620 ;;; Prints a representation of the function call causing FRAME to
621 ;;; exist. VERBOSITY indicates the level of information to output;
622 ;;; zero indicates just printing the DEBUG-FUN's name, and one
623 ;;; indicates displaying call-like, one-liner format with argument
624 ;;; values.
625 (defun print-frame-call (frame &key (verbosity 1) (number nil))
626   (cond
627    ((zerop verbosity)
628     (when number
629       (format t "~&~S: " (sb!di:frame-number frame)))
630     (format t "~S" frame))
631    (t
632     (when number
633       (format t "~&~S: " (sb!di:frame-number frame)))
634     (print-frame-call-1 frame)))
635   (when (>= verbosity 2)
636     (let ((loc (sb!di:frame-code-location frame)))
637       (handler-case
638           (progn
639             (sb!di:code-location-debug-block loc)
640             (format t "~%source: ")
641             (print-code-location-source-form loc 0))
642         (sb!di:debug-condition (ignore) ignore)
643         (error (c) (format t "error finding source: ~A" c))))))
644 \f
645 ;;;; INVOKE-DEBUGGER
646
647 (defvar *debugger-hook* nil
648   #!+sb-doc
649   "This is either NIL or a function of two arguments, a condition and the value
650    of *DEBUGGER-HOOK*. This function can either handle the condition or return
651    which causes the standard debugger to execute. The system passes the value
652    of this variable to the function because it binds *DEBUGGER-HOOK* to NIL
653    around the invocation.")
654
655 (defvar *invoke-debugger-hook* nil
656   #!+sb-doc
657   "This is either NIL or a designator for a function of two arguments,
658    to be run when the debugger is about to be entered.  The function is
659    run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
660    errors, and receives as arguments the condition that triggered 
661    debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*   
662
663    This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
664    In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
665    called by BREAK.")
666
667 ;;; These are bound on each invocation of INVOKE-DEBUGGER.
668 (defvar *debug-restarts*)
669 (defvar *debug-condition*)
670 (defvar *nested-debug-condition*)
671
672 ;;; Oh, what a tangled web we weave when we preserve backwards
673 ;;; compatibility with 1968-style use of global variables to control
674 ;;; per-stream i/o properties; there's really no way to get this
675 ;;; quite right, but we do what we can.
676 (defun funcall-with-debug-io-syntax (fun &rest rest)
677   (declare (type function fun))
678   ;; Try to force the other special variables into a useful state.
679   (let (;; Protect from WITH-STANDARD-IO-SYNTAX some variables where
680         ;; any default we might use is less useful than just reusing
681         ;; the global values.
682         (original-package *package*)
683         (original-print-pretty *print-pretty*))
684     (with-standard-io-syntax
685      (let (;; We want the printer and reader to be in a useful state,
686            ;; regardless of where the debugger was invoked in the
687            ;; program. WITH-STANDARD-IO-SYNTAX did much of what we
688            ;; want, but
689            ;;   * It doesn't affect our internal special variables 
690            ;;     like *CURRENT-LEVEL-IN-PRINT*.
691            ;;   * It isn't customizable.
692            ;;   * It doesn't set *PRINT-READABLY* to the same value
693            ;;     as the toplevel default.
694            ;;   * It sets *PACKAGE* to COMMON-LISP-USER, which is not
695            ;;     helpful behavior for a debugger.
696            ;;   * There's no particularly good debugger default for
697            ;;     *PRINT-PRETTY*, since T is usually what you want
698            ;;     -- except absolutely not what you want when you're
699            ;;     debugging failures in PRINT-OBJECT logic.
700            ;; We try to address all these issues with explicit
701            ;; rebindings here.
702            (sb!kernel:*current-level-in-print* 0)
703            (*package* original-package)
704            (*print-pretty* original-print-pretty)
705            (*print-readably* nil)
706            ;; These rebindings are now (as of early 2004) deprecated,
707            ;; with the new *PRINT-VAR-ALIST* mechanism preferred.
708            (*print-length* *debug-print-length*)
709            (*print-level* *debug-print-level*)
710            (*readtable* *debug-readtable*))
711        (progv
712            ;; (Why NREVERSE? PROGV makes the later entries have
713            ;; precedence over the earlier entries. *PRINT-VAR-ALIST*
714            ;; is called an alist, so it's expected that its earlier
715            ;; entries have precedence. And the earlier-has-precedence
716            ;; behavior is mostly more convenient, so that programmers
717            ;; can use PUSH or LIST* to customize *PRINT-VAR-ALIST*.)
718            (nreverse (mapcar #'car *debug-print-variable-alist*))
719            (nreverse (mapcar #'cdr *debug-print-variable-alist*))
720          (apply fun rest))))))
721
722 ;;; the ordinary ANSI case of INVOKE-DEBUGGER, when not suppressed by
723 ;;; command-line --disable-debugger option
724 (defun invoke-debugger (condition)
725   #!+sb-doc
726   "Enter the debugger."
727
728   (let ((old-hook *debugger-hook*))
729     (when old-hook
730       (let ((*debugger-hook* nil))
731         (funcall old-hook condition old-hook))))
732   (let ((old-hook *invoke-debugger-hook*))
733     (when old-hook
734       (let ((*invoke-debugger-hook* nil))
735         (funcall old-hook condition old-hook))))
736
737   ;; Note: CMU CL had (SB-UNIX:UNIX-SIGSETMASK 0) here, to reset the
738   ;; signal state in the case that we wind up in the debugger as a
739   ;; result of something done by a signal handler.  It's not
740   ;; altogether obvious that this is necessary, and indeed SBCL has
741   ;; not been doing it since 0.7.8.5.  But nobody seems altogether
742   ;; convinced yet
743   ;; -- dan 2003.11.11, based on earlier comment of WHN 2002-09-28
744
745   ;; We definitely want *PACKAGE* to be of valid type.
746   ;;
747   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
748   ;; this, but here causing an exception just as we're trying to handle
749   ;; an exception would be confusing, so instead we use a special hack.
750   (unless (and (packagep *package*)
751                (package-name *package*))
752     (setf *package* (find-package :cl-user))
753     (format *error-output*
754             "The value of ~S was not an undeleted PACKAGE. It has been
755 reset to ~S."
756             '*package* *package*))
757
758   ;; Before we start our own output, finish any pending output.
759   ;; Otherwise, if the user tried to track the progress of his program
760   ;; using PRINT statements, he'd tend to lose the last line of output
761   ;; or so, which'd be confusing.
762   (flush-standard-output-streams)
763
764   (funcall-with-debug-io-syntax #'%invoke-debugger condition))
765
766 (defun %invoke-debugger (condition)
767   
768   (let ((*debug-condition* condition)
769         (*debug-restarts* (compute-restarts condition))
770         (*nested-debug-condition* nil))
771     (handler-case
772         ;; (The initial output here goes to *ERROR-OUTPUT*, because the
773         ;; initial output is not interactive, just an error message, and
774         ;; when people redirect *ERROR-OUTPUT*, they could reasonably
775         ;; expect to see error messages logged there, regardless of what
776         ;; the debugger does afterwards.)
777         (format *error-output*
778                 "~2&~@<debugger invoked on a ~S in thread ~A: ~
779                     ~2I~_~A~:>~%"
780                 (type-of *debug-condition*)
781                 (sb!thread:current-thread-id)
782                 *debug-condition*)
783       (error (condition)
784         (setf *nested-debug-condition* condition)
785         (let ((ndc-type (type-of *nested-debug-condition*)))
786           (format *error-output*
787                   "~&~@<(A ~S was caught when trying to print ~S when ~
788                       entering the debugger. Printing was aborted and the ~
789                       ~S was stored in ~S.)~@:>~%"
790                   ndc-type
791                   '*debug-condition*
792                   ndc-type
793                   '*nested-debug-condition*))
794         (when (typep condition 'cell-error)
795           ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
796           (format *error-output*
797                   "~&(CELL-ERROR-NAME ~S) = ~S~%"
798                   '*debug-condition*
799                   (cell-error-name *debug-condition*)))))
800
801     (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
802                          *debug-io*)))
803
804       ;; After the initial error/condition/whatever announcement to
805       ;; *ERROR-OUTPUT*, we become interactive, and should talk on
806       ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
807       ;; statement, not a description of reality.:-| There's a lot of
808       ;; older debugger code which was written to do i/o on whatever
809       ;; stream was in fashion at the time, and not all of it has
810       ;; been converted to behave this way. -- WHN 2000-11-16)
811
812       (unwind-protect
813            (let (;; FIXME: Rebinding *STANDARD-OUTPUT* here seems wrong,
814                  ;; violating the principle of least surprise, and making
815                  ;; it impossible for the user to do reasonable things
816                  ;; like using PRINT at the debugger prompt to send output
817                  ;; to the program's ordinary (possibly
818                  ;; redirected-to-a-file) *STANDARD-OUTPUT*. (CMU CL
819                  ;; used to rebind *STANDARD-INPUT* here too, but that's
820                  ;; been fixed already.)
821                  (*standard-output* *debug-io*)
822                  ;; This seems reasonable: e.g. if the user has redirected
823                  ;; *ERROR-OUTPUT* to some log file, it's probably wrong
824                  ;; to send errors which occur in interactive debugging to
825                  ;; that file, and right to send them to *DEBUG-IO*.
826                  (*error-output* *debug-io*))
827              (unless (typep condition 'step-condition)
828                (when *debug-beginner-help-p*
829                  (format *debug-io*
830                          "~%~@<You can type HELP for debugger help, or ~
831                                (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
832                (show-restarts *debug-restarts* *debug-io*))
833              (internal-debug))
834         (when background-p
835           (sb!thread::release-foreground))))))
836
837 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
838 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
839 ;;; command-line option
840 (defun debugger-disabled-hook (condition me)
841   (declare (ignore me))
842   ;; There is no one there to interact with, so report the
843   ;; condition and terminate the program.
844   (flet ((failure-quit (&key recklessly-p)
845            (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
846            (quit :unix-status 1 :recklessly-p recklessly-p)))
847     ;; This HANDLER-CASE is here mostly to stop output immediately
848     ;; (and fall through to QUIT) when there's an I/O error. Thus,
849     ;; when we're run under a shell script or something, we can die
850     ;; cleanly when the script dies (and our pipes are cut), instead
851     ;; of falling into ldb or something messy like that. Similarly, we
852     ;; can terminate cleanly even if BACKTRACE dies because of bugs in
853     ;; user PRINT-OBJECT methods.
854     (handler-case
855         (progn
856           (format *error-output*
857                   "~&~@<unhandled condition (of type ~S): ~2I~_~A~:>~2%"
858                   (type-of condition)
859                   condition)
860           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
861           ;; even if we hit an error within BACKTRACE (e.g. a bug in
862           ;; the debugger's own frame-walking code, or a bug in a user
863           ;; PRINT-OBJECT method) we'll at least have the CONDITION
864           ;; printed out before we die.
865           (finish-output *error-output*)
866           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
867           ;; it seems as though we should at least truncate it somewhere.)
868           (sb!debug:backtrace 128 *error-output*)
869           (format
870            *error-output*
871            "~%unhandled condition in --disable-debugger mode, quitting~%")
872           (finish-output *error-output*)
873           (failure-quit))
874       (condition ()
875         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
876         ;; fail when our output streams are blown away, as e.g. when
877         ;; we're running under a Unix shell script and it dies somehow
878         ;; (e.g. because of a SIGINT). In that case, we might as well
879         ;; just give it up for a bad job, and stop trying to notify
880         ;; the user of anything.
881         ;;
882         ;; Actually, the only way I've run across to exercise the
883         ;; problem is to have more than one layer of shell script.
884         ;; I have a shell script which does
885         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
886         ;; and the problem occurs when I interrupt this with Ctrl-C
887         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
888         ;; I haven't figured out whether it's bash, time, tee, Linux, or
889         ;; what that is responsible, but that it's possible at all
890         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
891         (ignore-errors
892          (%primitive print
893                      "Argh! error within --disable-debugger error handling"))
894         (failure-quit :recklessly-p t)))))
895
896 ;;; halt-on-failures and prompt-on-failures modes, suitable for
897 ;;; noninteractive and interactive use respectively
898 (defun disable-debugger ()
899   (when (eql *invoke-debugger-hook* nil)
900     (setf *debug-io* *error-output*
901           *invoke-debugger-hook* 'debugger-disabled-hook)))
902
903 (defun enable-debugger ()
904   (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
905     (setf *invoke-debugger-hook* nil)))
906
907 (setf *debug-io* *query-io*)
908
909 (defun show-restarts (restarts s)
910   (cond ((null restarts)
911          (format s
912                  "~&(no restarts: If you didn't do this on purpose, ~
913                   please report it as a bug.)~%"))
914         (t
915          (format s "~&restarts (invokable by number or by ~
916                     possibly-abbreviated name):~%")
917          (let ((count 0)
918                (names-used '(nil))
919                (max-name-len 0))
920            (dolist (restart restarts)
921              (let ((name (restart-name restart)))
922                (when name
923                  (let ((len (length (princ-to-string name))))
924                    (when (> len max-name-len)
925                      (setf max-name-len len))))))
926            (unless (zerop max-name-len)
927              (incf max-name-len 3))
928            (dolist (restart restarts)
929              (let ((name (restart-name restart)))
930                (cond ((member name names-used)
931                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
932                      (t
933                       (format s "~& ~2D: [~VA] ~A~%"
934                               count (- max-name-len 3) name restart)
935                       (push name names-used))))
936              (incf count))))))
937
938 (defvar *debug-loop-fun* #'debug-loop-fun
939   "a function taking no parameters that starts the low-level debug loop")
940
941 ;;; This calls DEBUG-LOOP, performing some simple initializations
942 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
943 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
944 ;;; to get into a debug prompt as quickly as possible with as little
945 ;;; risk as possible for stepping on whatever is causing recursive
946 ;;; errors.
947 (defun internal-debug ()
948   (let ((*in-the-debugger* t)
949         (*read-suppress* nil))
950     (unless (typep *debug-condition* 'step-condition)
951       (clear-input *debug-io*))
952     (funcall *debug-loop-fun*)))
953 \f
954 ;;;; DEBUG-LOOP
955
956 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
957 ;;; was motivated by desire to play nicely with ILISP.
958 (defvar *flush-debug-errors* nil
959   #!+sb-doc
960   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
961    executing in the debugger.")
962
963 (defun debug-loop-fun ()
964   (let* ((*debug-command-level* (1+ *debug-command-level*))
965          (*real-stack-top* (sb!di:top-frame))
966          (*stack-top* (or *stack-top-hint* *real-stack-top*))
967          (*stack-top-hint* nil)
968          (*current-frame* *stack-top*))
969     (handler-bind ((sb!di:debug-condition
970                     (lambda (condition)
971                       (princ condition *debug-io*)
972                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
973                       (throw 'debug-loop-catcher nil))))
974       (fresh-line)
975       (print-frame-call *current-frame* :verbosity 2)
976       (loop
977         (catch 'debug-loop-catcher
978           (handler-bind ((error (lambda (condition)
979                                   (when *flush-debug-errors*
980                                     (clear-input *debug-io*)
981                                     (princ condition)
982                                     ;; FIXME: Doing input on *DEBUG-IO*
983                                     ;; and output on T seems broken.
984                                     (format t
985                                             "~&error flushed (because ~
986                                              ~S is set)"
987                                             '*flush-debug-errors*)
988                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
989                                     (throw 'debug-loop-catcher nil)))))
990             ;; We have to bind LEVEL for the restart function created by
991             ;; WITH-SIMPLE-RESTART.
992             (let ((level *debug-command-level*)
993                   (restart-commands (make-restart-commands)))
994               (with-simple-restart (abort
995                                    "~@<Reduce debugger level (to debug level ~W).~@:>"
996                                     level)
997                 (debug-prompt *debug-io*)
998                 (force-output *debug-io*)
999                 (let* ((exp (read *debug-io*))
1000                        (cmd-fun (debug-command-p exp restart-commands)))
1001                   (cond ((not cmd-fun)
1002                          (debug-eval-print exp))
1003                         ((consp cmd-fun)
1004                          (format t "~&Your command, ~S, is ambiguous:~%"
1005                                  exp)
1006                          (dolist (ele cmd-fun)
1007                            (format t "   ~A~%" ele)))
1008                         (t
1009                          (funcall cmd-fun))))))))))))
1010
1011 ;;; FIXME: We could probably use INTERACTIVE-EVAL for much of this logic.
1012 (defun debug-eval-print (expr)
1013   (/noshow "entering DEBUG-EVAL-PRINT" expr)
1014   (/noshow (fboundp 'compile))
1015   (setq +++ ++ ++ + + - - expr)
1016   (let* ((values (multiple-value-list (eval -)))
1017          (*standard-output* *debug-io*))
1018     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
1019     (fresh-line)
1020     (if values (prin1 (car values)))
1021     (dolist (x (cdr values))
1022       (fresh-line)
1023       (prin1 x))
1024     (setq /// // // / / values)
1025     (setq *** ** ** * * (car values))
1026     ;; Make sure that nobody passes back an unbound marker.
1027     (unless (boundp '*)
1028       (setq * nil)
1029       (fresh-line)
1030       ;; FIXME: The way INTERACTIVE-EVAL does this seems better.
1031       (princ "Setting * to NIL (was unbound marker)."))))
1032 \f
1033 ;;;; debug loop functions
1034
1035 ;;; These commands are functions, not really commands, so that users
1036 ;;; can get their hands on the values returned.
1037
1038 (eval-when (:execute :compile-toplevel)
1039
1040 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
1041   `(let* ((temp (etypecase name
1042                   (symbol (sb!di:debug-fun-symbol-vars
1043                            (sb!di:frame-debug-fun *current-frame*)
1044                            name))
1045                   (simple-string (sb!di:ambiguous-debug-vars
1046                                   (sb!di:frame-debug-fun *current-frame*)
1047                                   name))))
1048           (location (sb!di:frame-code-location *current-frame*))
1049           ;; Let's only deal with valid variables.
1050           (vars (remove-if-not (lambda (v)
1051                                  (eq (sb!di:debug-var-validity v location)
1052                                      :valid))
1053                                temp)))
1054      (declare (list vars))
1055      (cond ((null vars)
1056             (error "No known valid variables match ~S." name))
1057            ((= (length vars) 1)
1058             ,(ecase ref-or-set
1059                (:ref
1060                 '(sb!di:debug-var-value (car vars) *current-frame*))
1061                (:set
1062                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1063                        ,value-var))))
1064            (t
1065             ;; Since we have more than one, first see whether we have
1066             ;; any variables that exactly match the specification.
1067             (let* ((name (etypecase name
1068                            (symbol (symbol-name name))
1069                            (simple-string name)))
1070                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
1071                    ;; instead.
1072                    (exact (remove-if-not (lambda (v)
1073                                            (string= (sb!di:debug-var-symbol-name v)
1074                                                     name))
1075                                          vars))
1076                    (vars (or exact vars)))
1077               (declare (simple-string name)
1078                        (list exact vars))
1079               (cond
1080                ;; Check now for only having one variable.
1081                ((= (length vars) 1)
1082                 ,(ecase ref-or-set
1083                    (:ref
1084                     '(sb!di:debug-var-value (car vars) *current-frame*))
1085                    (:set
1086                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1087                            ,value-var))))
1088                ;; If there weren't any exact matches, flame about
1089                ;; ambiguity unless all the variables have the same
1090                ;; name.
1091                ((and (not exact)
1092                      (find-if-not
1093                       (lambda (v)
1094                         (string= (sb!di:debug-var-symbol-name v)
1095                                  (sb!di:debug-var-symbol-name (car vars))))
1096                       (cdr vars)))
1097                 (error "specification ambiguous:~%~{   ~A~%~}"
1098                        (mapcar #'sb!di:debug-var-symbol-name
1099                                (delete-duplicates
1100                                 vars :test #'string=
1101                                 :key #'sb!di:debug-var-symbol-name))))
1102                ;; All names are the same, so see whether the user
1103                ;; ID'ed one of them.
1104                (id-supplied
1105                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
1106                   (unless v
1107                     (error
1108                      "invalid variable ID, ~W: should have been one of ~S"
1109                      id
1110                      (mapcar #'sb!di:debug-var-id vars)))
1111                   ,(ecase ref-or-set
1112                      (:ref
1113                       '(sb!di:debug-var-value v *current-frame*))
1114                      (:set
1115                       `(setf (sb!di:debug-var-value v *current-frame*)
1116                              ,value-var)))))
1117                (t
1118                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
1119                        name
1120                        (mapcar #'sb!di:debug-var-id vars)))))))))
1121
1122 ) ; EVAL-WHEN
1123
1124 ;;; FIXME: This doesn't work. It would be real nice we could make it
1125 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
1126 (defun var (name &optional (id 0 id-supplied))
1127   #!+sb-doc
1128   "Return a variable's value if possible. NAME is a simple-string or symbol.
1129    If it is a simple-string, it is an initial substring of the variable's name.
1130    If name is a symbol, it has the same name and package as the variable whose
1131    value this function returns. If the symbol is uninterned, then the variable
1132    has the same name as the symbol, but it has no package.
1133
1134    If name is the initial substring of variables with different names, then
1135    this return no values after displaying the ambiguous names. If name
1136    determines multiple variables with the same name, then you must use the
1137    optional id argument to specify which one you want. If you left id
1138    unspecified, then this returns no values after displaying the distinguishing
1139    id values.
1140
1141    The result of this function is limited to the availability of variable
1142    information. This is SETF'able."
1143   (define-var-operation :ref))
1144 (defun (setf var) (value name &optional (id 0 id-supplied))
1145   (define-var-operation :set value))
1146
1147 ;;; This returns the COUNT'th arg as the user sees it from args, the
1148 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
1149 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
1150 ;;; T. If this returns a keyword symbol or a value from a rest arg,
1151 ;;; then the second value is NIL.
1152 ;;;
1153 ;;; FIXME: There's probably some way to merge the code here with
1154 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1155 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1156 (declaim (ftype (function (index list)) nth-arg))
1157 (defun nth-arg (count args)
1158   (let ((n count))
1159     (dolist (ele args (error "The argument specification ~S is out of range."
1160                              n))
1161       (lambda-list-element-dispatch ele
1162         :required ((if (zerop n) (return (values ele t))))
1163         :optional ((if (zerop n) (return (values (second ele) t))))
1164         :keyword ((cond ((zerop n)
1165                          (return (values (second ele) nil)))
1166                         ((zerop (decf n))
1167                          (return (values (third ele) t)))))
1168         :deleted ((if (zerop n) (return (values ele t))))
1169         :rest ((let ((var (second ele)))
1170                  (lambda-var-dispatch var (sb!di:frame-code-location
1171                                            *current-frame*)
1172                    (error "unused &REST argument before n'th argument")
1173                    (dolist (value
1174                             (sb!di:debug-var-value var *current-frame*)
1175                             (error
1176                              "The argument specification ~S is out of range."
1177                              n))
1178                      (if (zerop n)
1179                          (return-from nth-arg (values value nil))
1180                          (decf n)))
1181                    (error "invalid &REST argument before n'th argument")))))
1182       (decf n))))
1183
1184 (defun arg (n)
1185   #!+sb-doc
1186   "Return the N'th argument's value if possible. Argument zero is the first
1187    argument in a frame's default printed representation. Count keyword/value
1188    pairs as separate arguments."
1189   (multiple-value-bind (var lambda-var-p)
1190       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1191                                 (sb!di:frame-debug-fun *current-frame*))
1192                    (sb!di:lambda-list-unavailable ()
1193                      (error "No argument values are available."))))
1194     (if lambda-var-p
1195         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1196           (error "Unused arguments have no values.")
1197           (sb!di:debug-var-value var *current-frame*)
1198           (error "invalid argument value"))
1199         var)))
1200 \f
1201 ;;;; machinery for definition of debug loop commands
1202
1203 (defvar *debug-commands* nil)
1204
1205 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1206 ;;; permitted.
1207 (defmacro !def-debug-command (name args &rest body)
1208   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1209     `(progn
1210        (setf *debug-commands*
1211              (remove ,name *debug-commands* :key #'car :test #'string=))
1212        (defun ,fun-name ,args
1213          (unless *in-the-debugger*
1214            (error "invoking debugger command while outside the debugger"))
1215          ,@body)
1216        (push (cons ,name #',fun-name) *debug-commands*)
1217        ',fun-name)))
1218
1219 (defun !def-debug-command-alias (new-name existing-name)
1220   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1221     (unless pair (error "unknown debug command name: ~S" existing-name))
1222     (push (cons new-name (cdr pair)) *debug-commands*))
1223   new-name)
1224
1225 ;;; This takes a symbol and uses its name to find a debugger command,
1226 ;;; using initial substring matching. It returns the command function
1227 ;;; if form identifies only one command, but if form is ambiguous,
1228 ;;; this returns a list of the command names. If there are no matches,
1229 ;;; this returns nil. Whenever the loop that looks for a set of
1230 ;;; possibilities encounters an exact name match, we return that
1231 ;;; command function immediately.
1232 (defun debug-command-p (form &optional other-commands)
1233   (if (or (symbolp form) (integerp form))
1234       (let* ((name
1235               (if (symbolp form)
1236                   (symbol-name form)
1237                   (format nil "~W" form)))
1238              (len (length name))
1239              (res nil))
1240         (declare (simple-string name)
1241                  (fixnum len)
1242                  (list res))
1243
1244         ;; Find matching commands, punting if exact match.
1245         (flet ((match-command (ele)
1246                  (let* ((str (car ele))
1247                         (str-len (length str)))
1248                    (declare (simple-string str)
1249                             (fixnum str-len))
1250                    (cond ((< str-len len))
1251                          ((= str-len len)
1252                           (when (string= name str :end1 len :end2 len)
1253                             (return-from debug-command-p (cdr ele))))
1254                          ((string= name str :end1 len :end2 len)
1255                           (push ele res))))))
1256           (mapc #'match-command *debug-commands*)
1257           (mapc #'match-command other-commands))
1258
1259         ;; Return the right value.
1260         (cond ((not res) nil)
1261               ((= (length res) 1)
1262                (cdar res))
1263               (t ; Just return the names.
1264                (do ((cmds res (cdr cmds)))
1265                    ((not cmds) res)
1266                  (setf (car cmds) (caar cmds))))))))
1267
1268 ;;; Return a list of debug commands (in the same format as
1269 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1270 ;;;
1271 ;;; Two commands are made for each restart: one for the number, and
1272 ;;; one for the restart name (unless it's been shadowed by an earlier
1273 ;;; restart of the same name, or it is NIL).
1274 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1275   (let ((commands)
1276         (num 0))                        ; better be the same as show-restarts!
1277     (dolist (restart restarts)
1278       (let ((name (string (restart-name restart))))
1279         (let ((restart-fun
1280                 (lambda ()
1281                   (/show0 "in restart-command closure, about to i-r-i")
1282                   (invoke-restart-interactively restart))))
1283           (push (cons (prin1-to-string num) restart-fun) commands)
1284           (unless (or (null (restart-name restart)) 
1285                       (find name commands :key #'car :test #'string=))
1286             (push (cons name restart-fun) commands))))
1287     (incf num))
1288   commands))
1289 \f
1290 ;;;; frame-changing commands
1291
1292 (!def-debug-command "UP" ()
1293   (let ((next (sb!di:frame-up *current-frame*)))
1294     (cond (next
1295            (setf *current-frame* next)
1296            (print-frame-call next))
1297           (t
1298            (format t "~&Top of stack.")))))
1299
1300 (!def-debug-command "DOWN" ()
1301   (let ((next (sb!di:frame-down *current-frame*)))
1302     (cond (next
1303            (setf *current-frame* next)
1304            (print-frame-call next))
1305           (t
1306            (format t "~&Bottom of stack.")))))
1307
1308 (!def-debug-command-alias "D" "DOWN")
1309
1310 ;;; CMU CL had this command, but SBCL doesn't, since it's redundant
1311 ;;; with "FRAME 0", and it interferes with abbreviations for the
1312 ;;; TOPLEVEL restart.
1313 ;;;(!def-debug-command "TOP" ()
1314 ;;;  (do ((prev *current-frame* lead)
1315 ;;;       (lead (sb!di:frame-up *current-frame*) (sb!di:frame-up lead)))
1316 ;;;      ((null lead)
1317 ;;;       (setf *current-frame* prev)
1318 ;;;       (print-frame-call prev))))
1319
1320 (!def-debug-command "BOTTOM" ()
1321   (do ((prev *current-frame* lead)
1322        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1323       ((null lead)
1324        (setf *current-frame* prev)
1325        (print-frame-call prev))))
1326
1327 (!def-debug-command-alias "B" "BOTTOM")
1328
1329 (!def-debug-command "FRAME" (&optional
1330                              (n (read-prompting-maybe "frame number: ")))
1331   (setf *current-frame*
1332         (multiple-value-bind (next-frame-fun limit-string)
1333             (if (< n (sb!di:frame-number *current-frame*))
1334                 (values #'sb!di:frame-up "top")
1335               (values #'sb!di:frame-down "bottom"))
1336           (do ((frame *current-frame*))
1337               ((= n (sb!di:frame-number frame))
1338                frame)
1339             (let ((next-frame (funcall next-frame-fun frame)))
1340               (cond (next-frame
1341                      (setf frame next-frame))
1342                     (t
1343                      (format t
1344                              "The ~A of the stack was encountered.~%"
1345                              limit-string)
1346                      (return frame)))))))
1347   (print-frame-call *current-frame*))
1348
1349 (!def-debug-command-alias "F" "FRAME")
1350 \f
1351 ;;;; commands for entering and leaving the debugger
1352
1353 ;;; CMU CL supported this QUIT debug command, but SBCL provides this
1354 ;;; functionality with a restart instead. (The QUIT debug command was
1355 ;;; removed because it's confusing to have "quit" mean two different
1356 ;;; things in the system, "restart the top level REPL" in the debugger
1357 ;;; and "terminate the Lisp system" as the SB-EXT:QUIT function.)
1358 ;;;
1359 ;;;(!def-debug-command "QUIT" ()
1360 ;;;  (throw 'sb!impl::toplevel-catcher nil))
1361
1362 ;;; CMU CL supported this GO debug command, but SBCL doesn't -- in
1363 ;;; SBCL you just type the CONTINUE restart name instead (or "C" or
1364 ;;; "RESTART CONTINUE", that's OK too).
1365 ;;;(!def-debug-command "GO" ()
1366 ;;;  (continue *debug-condition*)
1367 ;;;  (error "There is no restart named CONTINUE."))
1368
1369 (!def-debug-command "RESTART" ()
1370   (/show0 "doing RESTART debug-command")
1371   (let ((num (read-if-available :prompt)))
1372     (when (eq num :prompt)
1373       (show-restarts *debug-restarts* *debug-io*)
1374       (write-string "restart: ")
1375       (force-output)
1376       (setf num (read *debug-io*)))
1377     (let ((restart (typecase num
1378                      (unsigned-byte
1379                       (nth num *debug-restarts*))
1380                      (symbol
1381                       (find num *debug-restarts* :key #'restart-name
1382                             :test (lambda (sym1 sym2)
1383                                     (string= (symbol-name sym1)
1384                                              (symbol-name sym2)))))
1385                      (t
1386                       (format t "~S is invalid as a restart name.~%" num)
1387                       (return-from restart-debug-command nil)))))
1388       (/show0 "got RESTART")
1389       (if restart
1390           (invoke-restart-interactively restart)
1391           ;; FIXME: Even if this isn't handled by WARN, it probably
1392           ;; shouldn't go to *STANDARD-OUTPUT*, but *ERROR-OUTPUT* or
1393           ;; *QUERY-IO* or something. Look through this file to
1394           ;; straighten out stream usage.
1395           (princ "There is no such restart.")))))
1396 \f
1397 ;;;; information commands
1398
1399 (!def-debug-command "HELP" ()
1400   ;; CMU CL had a little toy pager here, but "if you aren't running
1401   ;; ILISP (or a smart windowing system, or something) you deserve to
1402   ;; lose", so we've dropped it in SBCL. However, in case some
1403   ;; desperate holdout is running this on a dumb terminal somewhere,
1404   ;; we tell him where to find the message stored as a string.
1405   (format *debug-io*
1406           "~&~A~2%(The HELP string is stored in ~S.)~%"
1407           *debug-help-string*
1408           '*debug-help-string*))
1409
1410 (!def-debug-command-alias "?" "HELP")
1411
1412 (!def-debug-command "ERROR" ()
1413   (format *debug-io* "~A~%" *debug-condition*)
1414   (show-restarts *debug-restarts* *debug-io*))
1415
1416 (!def-debug-command "BACKTRACE" ()
1417   (backtrace (read-if-available most-positive-fixnum)))
1418
1419 (!def-debug-command "PRINT" ()
1420   (print-frame-call *current-frame*))
1421
1422 (!def-debug-command-alias "P" "PRINT")
1423
1424 (!def-debug-command "LIST-LOCALS" ()
1425   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1426     (if (sb!di:debug-var-info-available d-fun)
1427         (let ((*standard-output* *debug-io*)
1428               (location (sb!di:frame-code-location *current-frame*))
1429               (prefix (read-if-available nil))
1430               (any-p nil)
1431               (any-valid-p nil))
1432           (dolist (v (sb!di:ambiguous-debug-vars
1433                         d-fun
1434                         (if prefix (string prefix) "")))
1435             (setf any-p t)
1436             (when (eq (sb!di:debug-var-validity v location) :valid)
1437               (setf any-valid-p t)
1438               (format t "~S~:[#~W~;~*~]  =  ~S~%"
1439                       (sb!di:debug-var-symbol v)
1440                       (zerop (sb!di:debug-var-id v))
1441                       (sb!di:debug-var-id v)
1442                       (sb!di:debug-var-value v *current-frame*))))
1443
1444           (cond
1445            ((not any-p)
1446             (format t "There are no local variables ~@[starting with ~A ~]~
1447                        in the function."
1448                     prefix))
1449            ((not any-valid-p)
1450             (format t "All variables ~@[starting with ~A ~]currently ~
1451                        have invalid values."
1452                     prefix))))
1453         (write-line "There is no variable information available."))))
1454
1455 (!def-debug-command-alias "L" "LIST-LOCALS")
1456
1457 (!def-debug-command "SOURCE" ()
1458   (fresh-line)
1459   (print-code-location-source-form (sb!di:frame-code-location *current-frame*)
1460                                    (read-if-available 0)))
1461 \f
1462 ;;;; source location printing
1463
1464 ;;; We cache a stream to the last valid file debug source so that we
1465 ;;; won't have to repeatedly open the file.
1466 ;;;
1467 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1468 ;;; in the 1990s, so the benefit is negligible, less important than the
1469 ;;; potential of extra confusion if someone changes the source during
1470 ;;; a debug session and the change doesn't show up. And removing this
1471 ;;; would simplify the system, which I like. -- WHN 19990903
1472 (defvar *cached-debug-source* nil)
1473 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1474 (defvar *cached-source-stream* nil)
1475 (declaim (type (or stream null) *cached-source-stream*))
1476
1477 ;;; To suppress the read-time evaluation #. macro during source read,
1478 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1479 ;;; copying it each time, and invalidated when the
1480 ;;; *CACHED-DEBUG-SOURCE* has changed.
1481 (defvar *cached-readtable* nil)
1482 (declaim (type (or readtable null) *cached-readtable*))
1483
1484 (pushnew (lambda ()
1485            (setq *cached-debug-source* nil *cached-source-stream* nil
1486                  *cached-readtable* nil))
1487          *before-save-initializations*)
1488
1489 ;;; We also cache the last toplevel form that we printed a source for
1490 ;;; so that we don't have to do repeated reads and calls to
1491 ;;; FORM-NUMBER-TRANSLATIONS.
1492 (defvar *cached-toplevel-form-offset* nil)
1493 (declaim (type (or index null) *cached-toplevel-form-offset*))
1494 (defvar *cached-toplevel-form*)
1495 (defvar *cached-form-number-translations*)
1496
1497 ;;; Given a code location, return the associated form-number
1498 ;;; translations and the actual top level form. We check our cache ---
1499 ;;; if there is a miss, we dispatch on the kind of the debug source.
1500 (defun get-toplevel-form (location)
1501   (let ((d-source (sb!di:code-location-debug-source location)))
1502     (if (and (eq d-source *cached-debug-source*)
1503              (eql (sb!di:code-location-toplevel-form-offset location)
1504                   *cached-toplevel-form-offset*))
1505         (values *cached-form-number-translations* *cached-toplevel-form*)
1506         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1507                (res
1508                 (ecase (sb!di:debug-source-from d-source)
1509                   (:file (get-file-toplevel-form location))
1510                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1511           (setq *cached-toplevel-form-offset* offset)
1512           (values (setq *cached-form-number-translations*
1513                         (sb!di:form-number-translations res offset))
1514                   (setq *cached-toplevel-form* res))))))
1515
1516 ;;; Locate the source file (if it still exists) and grab the top level
1517 ;;; form. If the file is modified, we use the top level form offset
1518 ;;; instead of the recorded character offset.
1519 (defun get-file-toplevel-form (location)
1520   (let* ((d-source (sb!di:code-location-debug-source location))
1521          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1522          (local-tlf-offset (- tlf-offset
1523                               (sb!di:debug-source-root-number d-source)))
1524          (char-offset
1525           (aref (or (sb!di:debug-source-start-positions d-source)
1526                     (error "no start positions map"))
1527                 local-tlf-offset))
1528          (name (sb!di:debug-source-name d-source)))
1529     (unless (eq d-source *cached-debug-source*)
1530       (unless (and *cached-source-stream*
1531                    (equal (pathname *cached-source-stream*)
1532                           (pathname name)))
1533         (setq *cached-readtable* nil)
1534         (when *cached-source-stream* (close *cached-source-stream*))
1535         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1536         (unless *cached-source-stream*
1537           (error "The source file no longer exists:~%  ~A" (namestring name)))
1538         (format t "~%; file: ~A~%" (namestring name)))
1539
1540         (setq *cached-debug-source*
1541               (if (= (sb!di:debug-source-created d-source)
1542                      (file-write-date name))
1543                   d-source nil)))
1544
1545     (cond
1546      ((eq *cached-debug-source* d-source)
1547       (file-position *cached-source-stream* char-offset))
1548      (t
1549       (format t "~%; File has been modified since compilation:~%;   ~A~@
1550                  ; Using form offset instead of character position.~%"
1551               (namestring name))
1552       (file-position *cached-source-stream* 0)
1553       (let ((*read-suppress* t))
1554         (dotimes (i local-tlf-offset)
1555           (read *cached-source-stream*)))))
1556     (unless *cached-readtable*
1557       (setq *cached-readtable* (copy-readtable))
1558       (set-dispatch-macro-character
1559        #\# #\.
1560        (lambda (stream sub-char &rest rest)
1561          (declare (ignore rest sub-char))
1562          (let ((token (read stream t nil t)))
1563            (format nil "#.~S" token)))
1564        *cached-readtable*))
1565     (let ((*readtable* *cached-readtable*))
1566       (read *cached-source-stream*))))
1567
1568 (defun print-code-location-source-form (location context)
1569   (let* ((location (maybe-block-start-location location))
1570          (form-num (sb!di:code-location-form-number location)))
1571     (multiple-value-bind (translations form) (get-toplevel-form location)
1572       (unless (< form-num (length translations))
1573         (error "The source path no longer exists."))
1574       (prin1 (sb!di:source-path-context form
1575                                         (svref translations form-num)
1576                                         context)))))
1577 \f
1578 ;;; breakpoint and step commands
1579
1580 ;;; Step to the next code-location.
1581 (!def-debug-command "STEP" ()
1582   (setf *number-of-steps* (read-if-available 1))
1583   (set-step-breakpoint *current-frame*)
1584   (continue *debug-condition*)
1585   (error "couldn't continue"))
1586
1587 ;;; List possible breakpoint locations, which ones are active, and
1588 ;;; where the CONTINUE restart will transfer control. Set
1589 ;;; *POSSIBLE-BREAKPOINTS* to the code-locations which can then be
1590 ;;; used by sbreakpoint.
1591 (!def-debug-command "LIST-LOCATIONS" ()
1592   (let ((df (read-if-available *default-breakpoint-debug-fun*)))
1593     (cond ((consp df)
1594            (setf df (sb!di:fun-debug-fun (eval df)))
1595            (setf *default-breakpoint-debug-fun* df))
1596           ((or (eq ':c df)
1597                (not *default-breakpoint-debug-fun*))
1598            (setf df (sb!di:frame-debug-fun *current-frame*))
1599            (setf *default-breakpoint-debug-fun* df)))
1600     (setf *possible-breakpoints* (possible-breakpoints df)))
1601   (let ((continue-at (sb!di:frame-code-location *current-frame*)))
1602     (let ((active (location-in-list *default-breakpoint-debug-fun*
1603                                     *breakpoints* :fun-start))
1604           (here (sb!di:code-location=
1605                  (sb!di:debug-fun-start-location
1606                   *default-breakpoint-debug-fun*) continue-at)))
1607       (when (or active here)
1608         (format t "::FUN-START ")
1609         (when active (format t " *Active*"))
1610         (when here (format t " *Continue here*"))))
1611
1612     (let ((prev-location nil)
1613           (prev-num 0)
1614           (this-num 0))
1615       (flet ((flush ()
1616                (when prev-location
1617                  (let ((this-num (1- this-num)))
1618                    (if (= prev-num this-num)
1619                        (format t "~&~W: " prev-num)
1620                        (format t "~&~W-~W: " prev-num this-num)))
1621                  (print-code-location-source-form prev-location 0)
1622                  (when *print-location-kind*
1623                    (format t "~S " (sb!di:code-location-kind prev-location)))
1624                  (when (location-in-list prev-location *breakpoints*)
1625                    (format t " *Active*"))
1626                  (when (sb!di:code-location= prev-location continue-at)
1627                    (format t " *Continue here*")))))
1628         
1629         (dolist (code-location *possible-breakpoints*)
1630           (when (or *print-location-kind*
1631                     (location-in-list code-location *breakpoints*)
1632                     (sb!di:code-location= code-location continue-at)
1633                     (not prev-location)
1634                     (not (eq (sb!di:code-location-debug-source code-location)
1635                              (sb!di:code-location-debug-source prev-location)))
1636                     (not (eq (sb!di:code-location-toplevel-form-offset
1637                               code-location)
1638                              (sb!di:code-location-toplevel-form-offset
1639                               prev-location)))
1640                     (not (eq (sb!di:code-location-form-number code-location)
1641                              (sb!di:code-location-form-number prev-location))))
1642             (flush)
1643             (setq prev-location code-location  prev-num this-num))
1644
1645           (incf this-num))))
1646
1647     (when (location-in-list *default-breakpoint-debug-fun*
1648                             *breakpoints*
1649                             :fun-end)
1650       (format t "~&::FUN-END *Active* "))))
1651
1652 (!def-debug-command-alias "LL" "LIST-LOCATIONS")
1653
1654 ;;; Set breakpoint at the given number.
1655 (!def-debug-command "BREAKPOINT" ()
1656   (let ((index (read-prompting-maybe "location number, :START, or :END: "))
1657         (break t)
1658         (condition t)
1659         (print nil)
1660         (print-functions nil)
1661         (function nil)
1662         (bp)
1663         (place *default-breakpoint-debug-fun*))
1664     (flet ((get-command-line ()
1665              (let ((command-line nil)
1666                    (unique '(nil)))
1667                (loop
1668                  (let ((next-input (read-if-available unique)))
1669                    (when (eq next-input unique) (return))
1670                    (push next-input command-line)))
1671                (nreverse command-line)))
1672            (set-vars-from-command-line (command-line)
1673              (do ((arg (pop command-line) (pop command-line)))
1674                  ((not arg))
1675                (ecase arg
1676                  (:condition (setf condition (pop command-line)))
1677                  (:print (push (pop command-line) print))
1678                  (:break (setf break (pop command-line)))
1679                  (:function
1680                   (setf function (eval (pop command-line)))
1681                   (setf *default-breakpoint-debug-fun*
1682                         (sb!di:fun-debug-fun function))
1683                   (setf place *default-breakpoint-debug-fun*)
1684                   (setf *possible-breakpoints*
1685                         (possible-breakpoints
1686                          *default-breakpoint-debug-fun*))))))
1687            (setup-fun-start ()
1688              (let ((code-loc (sb!di:debug-fun-start-location place)))
1689                (setf bp (sb!di:make-breakpoint #'main-hook-fun
1690                                                place
1691                                                :kind :fun-start))
1692                (setf break (sb!di:preprocess-for-eval break code-loc))
1693                (setf condition (sb!di:preprocess-for-eval condition code-loc))
1694                (dolist (form print)
1695                  (push (cons (sb!di:preprocess-for-eval form code-loc) form)
1696                        print-functions))))
1697            (setup-fun-end ()
1698              (setf bp
1699                    (sb!di:make-breakpoint #'main-hook-fun
1700                                           place
1701                                           :kind :fun-end))
1702              (setf break
1703                    ;; FIXME: These and any other old (COERCE `(LAMBDA ..) ..)
1704                    ;; forms should be converted to shiny new (LAMBDA ..) forms.
1705                    ;; (Search the sources for "coerce.*\(lambda".)
1706                    (coerce `(lambda (dummy)
1707                               (declare (ignore dummy)) ,break)
1708                            'function))
1709              (setf condition (coerce `(lambda (dummy)
1710                                         (declare (ignore dummy)) ,condition)
1711                                      'function))
1712              (dolist (form print)
1713                (push (cons
1714                       (coerce `(lambda (dummy)
1715                                  (declare (ignore dummy)) ,form) 'function)
1716                       form)
1717                      print-functions)))
1718            (setup-code-location ()
1719              (setf place (nth index *possible-breakpoints*))
1720              (setf bp (sb!di:make-breakpoint #'main-hook-fun place
1721                                              :kind :code-location))
1722              (dolist (form print)
1723                (push (cons
1724                       (sb!di:preprocess-for-eval form place)
1725                       form)
1726                      print-functions))
1727              (setf break (sb!di:preprocess-for-eval break place))
1728              (setf condition (sb!di:preprocess-for-eval condition place))))
1729       (set-vars-from-command-line (get-command-line))
1730       (cond
1731        ((or (eq index :start) (eq index :s))
1732         (setup-fun-start))
1733        ((or (eq index :end) (eq index :e))
1734         (setup-fun-end))
1735        (t
1736         (setup-code-location)))
1737       (sb!di:activate-breakpoint bp)
1738       (let* ((new-bp-info (create-breakpoint-info place bp index
1739                                                   :break break
1740                                                   :print print-functions
1741                                                   :condition condition))
1742              (old-bp-info (location-in-list new-bp-info *breakpoints*)))
1743         (when old-bp-info
1744           (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
1745                                         old-bp-info))
1746           (setf *breakpoints* (remove old-bp-info *breakpoints*))
1747           (format t "previous breakpoint removed~%"))
1748         (push new-bp-info *breakpoints*))
1749       (print-breakpoint-info (first *breakpoints*))
1750       (format t "~&added"))))
1751
1752 (!def-debug-command-alias "BP" "BREAKPOINT")
1753
1754 ;;; List all breakpoints which are set.
1755 (!def-debug-command "LIST-BREAKPOINTS" ()
1756   (setf *breakpoints*
1757         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
1758   (dolist (info *breakpoints*)
1759     (print-breakpoint-info info)))
1760
1761 (!def-debug-command-alias "LB" "LIST-BREAKPOINTS")
1762 (!def-debug-command-alias "LBP" "LIST-BREAKPOINTS")
1763
1764 ;;; Remove breakpoint N, or remove all breakpoints if no N given.
1765 (!def-debug-command "DELETE-BREAKPOINT" ()
1766   (let* ((index (read-if-available nil))
1767          (bp-info
1768           (find index *breakpoints* :key #'breakpoint-info-breakpoint-number)))
1769     (cond (bp-info
1770            (sb!di:delete-breakpoint (breakpoint-info-breakpoint bp-info))
1771            (setf *breakpoints* (remove bp-info *breakpoints*))
1772            (format t "breakpoint ~S removed~%" index))
1773           (index (format t "The breakpoint doesn't exist."))
1774           (t
1775            (dolist (ele *breakpoints*)
1776              (sb!di:delete-breakpoint (breakpoint-info-breakpoint ele)))
1777            (setf *breakpoints* nil)
1778            (format t "all breakpoints deleted~%")))))
1779
1780 (!def-debug-command-alias "DBP" "DELETE-BREAKPOINT")
1781 \f
1782 ;;; miscellaneous commands
1783
1784 (!def-debug-command "DESCRIBE" ()
1785   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1786          (debug-fun (sb!di:code-location-debug-fun curloc))
1787          (function (sb!di:debug-fun-fun debug-fun)))
1788     (if function
1789         (describe function)
1790         (format t "can't figure out the function for this frame"))))
1791
1792 (!def-debug-command "SLURP" ()
1793   (loop while (read-char-no-hang *standard-input*)))
1794
1795 (!def-debug-command "RETURN" (&optional
1796                               (return (read-prompting-maybe
1797                                        "return: ")))
1798   (let ((tag (find-if (lambda (x)
1799                         (and (typep (car x) 'symbol)
1800                              (not (symbol-package (car x)))
1801                              (string= (car x) "SB-DEBUG-CATCH-TAG")))
1802                       (sb!di::frame-catches *current-frame*))))
1803     (if tag
1804         (throw (car tag)
1805           (funcall (sb!di:preprocess-for-eval
1806                     return
1807                     (sb!di:frame-code-location *current-frame*))
1808                    *current-frame*))
1809         (format t "~@<can't find a tag for this frame ~
1810                    ~2I~_(hint: try increasing the DEBUG optimization quality ~
1811                    and recompiling)~:@>"))))
1812 \f
1813 ;;;; debug loop command utilities
1814
1815 (defun read-prompting-maybe (prompt)
1816   (unless (sb!int:listen-skip-whitespace *debug-io*)
1817     (princ prompt)
1818     (force-output))
1819   (read *debug-io*))
1820
1821 (defun read-if-available (default)
1822   (if (sb!int:listen-skip-whitespace *debug-io*)
1823       (read *debug-io*)
1824       default))