0.8.14.5: Join the foreign legion!
[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            ;; Clear the circularity machinery to try to to reduce the
707            ;; pain from sharing the circularity table across all
708            ;; streams; if these are not rebound here, then setting
709            ;; *PRINT-CIRCLE* within the debugger when debugging in a
710            ;; state where something circular was being printed (e.g.,
711            ;; because the debugger was entered on an error in a
712            ;; PRINT-OBJECT method) makes a hopeless mess. Binding them
713            ;; here does seem somewhat ugly because it makes it more
714            ;; difficult to debug the printing-of-circularities code
715            ;; itself; however, as far as I (WHN, 2004-05-29) can see,
716            ;; that's almost entirely academic as long as there's one
717            ;; shared *C-H-T* for all streams (i.e., it's already
718            ;; unreasonably difficult to debug print-circle machinery
719            ;; given the buggy crosstalk between the debugger streams
720            ;; and the stream you're trying to watch), and any fix for
721            ;; that buggy arrangement will likely let this hack go away
722            ;; naturally.
723            (sb!impl::*circularity-hash-table* . nil)
724            (sb!impl::*circularity-counter* . nil)
725            ;; These rebindings are now (as of early 2004) deprecated,
726            ;; with the new *PRINT-VAR-ALIST* mechanism preferred.
727            (*print-length* *debug-print-length*)
728            (*print-level* *debug-print-level*)
729            (*readtable* *debug-readtable*))
730        (progv
731            ;; (Why NREVERSE? PROGV makes the later entries have
732            ;; precedence over the earlier entries.
733            ;; *DEBUG-PRINT-VARIABLE-ALIST* is called an alist, so it's
734            ;; expected that its earlier entries have precedence. And
735            ;; the earlier-has-precedence behavior is mostly more
736            ;; convenient, so that programmers can use PUSH or LIST* to
737            ;; customize *DEBUG-PRINT-VARIABLE-ALIST*.)
738            (nreverse (mapcar #'car *debug-print-variable-alist*))
739            (nreverse (mapcar #'cdr *debug-print-variable-alist*))
740          (apply fun rest))))))
741
742 ;;; the ordinary ANSI case of INVOKE-DEBUGGER, when not suppressed by
743 ;;; command-line --disable-debugger option
744 (defun invoke-debugger (condition)
745   #!+sb-doc
746   "Enter the debugger."
747
748   (let ((old-hook *debugger-hook*))
749     (when old-hook
750       (let ((*debugger-hook* nil))
751         (funcall old-hook condition old-hook))))
752   (let ((old-hook *invoke-debugger-hook*))
753     (when old-hook
754       (let ((*invoke-debugger-hook* nil))
755         (funcall old-hook condition old-hook))))
756
757   ;; Note: CMU CL had (SB-UNIX:UNIX-SIGSETMASK 0) here, to reset the
758   ;; signal state in the case that we wind up in the debugger as a
759   ;; result of something done by a signal handler.  It's not
760   ;; altogether obvious that this is necessary, and indeed SBCL has
761   ;; not been doing it since 0.7.8.5.  But nobody seems altogether
762   ;; convinced yet
763   ;; -- dan 2003.11.11, based on earlier comment of WHN 2002-09-28
764
765   ;; We definitely want *PACKAGE* to be of valid type.
766   ;;
767   ;; Elsewhere in the system, we use the SANE-PACKAGE function for
768   ;; this, but here causing an exception just as we're trying to handle
769   ;; an exception would be confusing, so instead we use a special hack.
770   (unless (and (packagep *package*)
771                (package-name *package*))
772     (setf *package* (find-package :cl-user))
773     (format *error-output*
774             "The value of ~S was not an undeleted PACKAGE. It has been
775 reset to ~S."
776             '*package* *package*))
777
778   ;; Before we start our own output, finish any pending output.
779   ;; Otherwise, if the user tried to track the progress of his program
780   ;; using PRINT statements, he'd tend to lose the last line of output
781   ;; or so, which'd be confusing.
782   (flush-standard-output-streams)
783
784   (funcall-with-debug-io-syntax #'%invoke-debugger condition))
785
786 (defun %invoke-debugger (condition)
787   
788   (let ((*debug-condition* condition)
789         (*debug-restarts* (compute-restarts condition))
790         (*nested-debug-condition* nil))
791     (handler-case
792         ;; (The initial output here goes to *ERROR-OUTPUT*, because the
793         ;; initial output is not interactive, just an error message, and
794         ;; when people redirect *ERROR-OUTPUT*, they could reasonably
795         ;; expect to see error messages logged there, regardless of what
796         ;; the debugger does afterwards.)
797         (format *error-output*
798                 "~2&~@<debugger invoked on a ~S in thread ~A: ~
799                     ~2I~_~A~:>~%"
800                 (type-of *debug-condition*)
801                 (sb!thread:current-thread-id)
802                 *debug-condition*)
803       (error (condition)
804         (setf *nested-debug-condition* condition)
805         (let ((ndc-type (type-of *nested-debug-condition*)))
806           (format *error-output*
807                   "~&~@<(A ~S was caught when trying to print ~S when ~
808                       entering the debugger. Printing was aborted and the ~
809                       ~S was stored in ~S.)~@:>~%"
810                   ndc-type
811                   '*debug-condition*
812                   ndc-type
813                   '*nested-debug-condition*))
814         (when (typep condition 'cell-error)
815           ;; what we really want to know when it's e.g. an UNBOUND-VARIABLE:
816           (format *error-output*
817                   "~&(CELL-ERROR-NAME ~S) = ~S~%"
818                   '*debug-condition*
819                   (cell-error-name *debug-condition*)))))
820
821     (let ((background-p (sb!thread::debugger-wait-until-foreground-thread
822                          *debug-io*)))
823
824       ;; After the initial error/condition/whatever announcement to
825       ;; *ERROR-OUTPUT*, we become interactive, and should talk on
826       ;; *DEBUG-IO* from now on. (KLUDGE: This is a normative
827       ;; statement, not a description of reality.:-| There's a lot of
828       ;; older debugger code which was written to do i/o on whatever
829       ;; stream was in fashion at the time, and not all of it has
830       ;; been converted to behave this way. -- WHN 2000-11-16)
831
832       (unwind-protect
833            (let (;; FIXME: Rebinding *STANDARD-OUTPUT* here seems wrong,
834                  ;; violating the principle of least surprise, and making
835                  ;; it impossible for the user to do reasonable things
836                  ;; like using PRINT at the debugger prompt to send output
837                  ;; to the program's ordinary (possibly
838                  ;; redirected-to-a-file) *STANDARD-OUTPUT*. (CMU CL
839                  ;; used to rebind *STANDARD-INPUT* here too, but that's
840                  ;; been fixed already.)
841                  (*standard-output* *debug-io*)
842                  ;; This seems reasonable: e.g. if the user has redirected
843                  ;; *ERROR-OUTPUT* to some log file, it's probably wrong
844                  ;; to send errors which occur in interactive debugging to
845                  ;; that file, and right to send them to *DEBUG-IO*.
846                  (*error-output* *debug-io*))
847              (unless (typep condition 'step-condition)
848                (when *debug-beginner-help-p*
849                  (format *debug-io*
850                          "~%~@<You can type HELP for debugger help, or ~
851                                (SB-EXT:QUIT) to exit from SBCL.~:@>~2%"))
852                (show-restarts *debug-restarts* *debug-io*))
853              (internal-debug))
854         (when background-p
855           (sb!thread::release-foreground))))))
856
857 ;;; this function is for use in *INVOKE-DEBUGGER-HOOK* when ordinary
858 ;;; ANSI behavior has been suppressed by the "--disable-debugger"
859 ;;; command-line option
860 (defun debugger-disabled-hook (condition me)
861   (declare (ignore me))
862   ;; There is no one there to interact with, so report the
863   ;; condition and terminate the program.
864   (flet ((failure-quit (&key recklessly-p)
865            (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
866            (quit :unix-status 1 :recklessly-p recklessly-p)))
867     ;; This HANDLER-CASE is here mostly to stop output immediately
868     ;; (and fall through to QUIT) when there's an I/O error. Thus,
869     ;; when we're run under a shell script or something, we can die
870     ;; cleanly when the script dies (and our pipes are cut), instead
871     ;; of falling into ldb or something messy like that. Similarly, we
872     ;; can terminate cleanly even if BACKTRACE dies because of bugs in
873     ;; user PRINT-OBJECT methods.
874     (handler-case
875         (progn
876           (format *error-output*
877                   "~&~@<unhandled ~S in thread ~S: ~2I~_~A~:>~2%"
878                   (type-of condition)
879                   (sb!thread:current-thread-id)
880                   condition)
881           ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
882           ;; even if we hit an error within BACKTRACE (e.g. a bug in
883           ;; the debugger's own frame-walking code, or a bug in a user
884           ;; PRINT-OBJECT method) we'll at least have the CONDITION
885           ;; printed out before we die.
886           (finish-output *error-output*)
887           ;; (Where to truncate the BACKTRACE is of course arbitrary, but
888           ;; it seems as though we should at least truncate it somewhere.)
889           (sb!debug:backtrace 128 *error-output*)
890           (format
891            *error-output*
892            "~%unhandled condition in --disable-debugger mode, quitting~%")
893           (finish-output *error-output*)
894           (failure-quit))
895       (condition ()
896         ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
897         ;; fail when our output streams are blown away, as e.g. when
898         ;; we're running under a Unix shell script and it dies somehow
899         ;; (e.g. because of a SIGINT). In that case, we might as well
900         ;; just give it up for a bad job, and stop trying to notify
901         ;; the user of anything.
902         ;;
903         ;; Actually, the only way I've run across to exercise the
904         ;; problem is to have more than one layer of shell script.
905         ;; I have a shell script which does
906         ;;   time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
907         ;; and the problem occurs when I interrupt this with Ctrl-C
908         ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
909         ;; I haven't figured out whether it's bash, time, tee, Linux, or
910         ;; what that is responsible, but that it's possible at all
911         ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
912         (ignore-errors
913          (%primitive print
914                      "Argh! error within --disable-debugger error handling"))
915         (failure-quit :recklessly-p t)))))
916
917 ;;; halt-on-failures and prompt-on-failures modes, suitable for
918 ;;; noninteractive and interactive use respectively
919 (defun disable-debugger ()
920   (when (eql *invoke-debugger-hook* nil)
921     (setf *debug-io* *error-output*
922           *invoke-debugger-hook* 'debugger-disabled-hook)))
923
924 (defun enable-debugger ()
925   (when (eql *invoke-debugger-hook* 'debugger-disabled-hook)
926     (setf *invoke-debugger-hook* nil)))
927
928 (setf *debug-io* *query-io*)
929
930 (defun show-restarts (restarts s)
931   (cond ((null restarts)
932          (format s
933                  "~&(no restarts: If you didn't do this on purpose, ~
934                   please report it as a bug.)~%"))
935         (t
936          (format s "~&restarts (invokable by number or by ~
937                     possibly-abbreviated name):~%")
938          (let ((count 0)
939                (names-used '(nil))
940                (max-name-len 0))
941            (dolist (restart restarts)
942              (let ((name (restart-name restart)))
943                (when name
944                  (let ((len (length (princ-to-string name))))
945                    (when (> len max-name-len)
946                      (setf max-name-len len))))))
947            (unless (zerop max-name-len)
948              (incf max-name-len 3))
949            (dolist (restart restarts)
950              (let ((name (restart-name restart)))
951                (cond ((member name names-used)
952                       (format s "~& ~2D: ~V@T~A~%" count max-name-len restart))
953                      (t
954                       (format s "~& ~2D: [~VA] ~A~%"
955                               count (- max-name-len 3) name restart)
956                       (push name names-used))))
957              (incf count))))))
958
959 (defvar *debug-loop-fun* #'debug-loop-fun
960   "a function taking no parameters that starts the low-level debug loop")
961
962 ;;; This calls DEBUG-LOOP, performing some simple initializations
963 ;;; before doing so. INVOKE-DEBUGGER calls this to actually get into
964 ;;; the debugger. SB!KERNEL::ERROR-ERROR calls this in emergencies
965 ;;; to get into a debug prompt as quickly as possible with as little
966 ;;; risk as possible for stepping on whatever is causing recursive
967 ;;; errors.
968 (defun internal-debug ()
969   (let ((*in-the-debugger* t)
970         (*read-suppress* nil))
971     (unless (typep *debug-condition* 'step-condition)
972       (clear-input *debug-io*))
973     (funcall *debug-loop-fun*)))
974 \f
975 ;;;; DEBUG-LOOP
976
977 ;;; Note: This defaulted to T in CMU CL. The changed default in SBCL
978 ;;; was motivated by desire to play nicely with ILISP.
979 (defvar *flush-debug-errors* nil
980   #!+sb-doc
981   "When set, avoid calling INVOKE-DEBUGGER recursively when errors occur while
982    executing in the debugger.")
983
984 (defun debug-loop-fun ()
985   (let* ((*debug-command-level* (1+ *debug-command-level*))
986          (*real-stack-top* (sb!di:top-frame))
987          (*stack-top* (or *stack-top-hint* *real-stack-top*))
988          (*stack-top-hint* nil)
989          (*current-frame* *stack-top*))
990     (handler-bind ((sb!di:debug-condition
991                     (lambda (condition)
992                       (princ condition *debug-io*)
993                       (/show0 "handling d-c by THROWing DEBUG-LOOP-CATCHER")
994                       (throw 'debug-loop-catcher nil))))
995       (fresh-line)
996       (print-frame-call *current-frame* :verbosity 2)
997       (loop
998         (catch 'debug-loop-catcher
999           (handler-bind ((error (lambda (condition)
1000                                   (when *flush-debug-errors*
1001                                     (clear-input *debug-io*)
1002                                     (princ condition)
1003                                     ;; FIXME: Doing input on *DEBUG-IO*
1004                                     ;; and output on T seems broken.
1005                                     (format t
1006                                             "~&error flushed (because ~
1007                                              ~S is set)"
1008                                             '*flush-debug-errors*)
1009                                     (/show0 "throwing DEBUG-LOOP-CATCHER")
1010                                     (throw 'debug-loop-catcher nil)))))
1011             ;; We have to bind LEVEL for the restart function created by
1012             ;; WITH-SIMPLE-RESTART.
1013             (let ((level *debug-command-level*)
1014                   (restart-commands (make-restart-commands)))
1015               (with-simple-restart (abort
1016                                    "~@<Reduce debugger level (to debug level ~W).~@:>"
1017                                     level)
1018                 (debug-prompt *debug-io*)
1019                 (force-output *debug-io*)
1020                 (let* ((exp (read *debug-io*))
1021                        (cmd-fun (debug-command-p exp restart-commands)))
1022                   (cond ((not cmd-fun)
1023                          (debug-eval-print exp))
1024                         ((consp cmd-fun)
1025                          (format t "~&Your command, ~S, is ambiguous:~%"
1026                                  exp)
1027                          (dolist (ele cmd-fun)
1028                            (format t "   ~A~%" ele)))
1029                         (t
1030                          (funcall cmd-fun))))))))))))
1031
1032 ;;; FIXME: We could probably use INTERACTIVE-EVAL for much of this logic.
1033 (defun debug-eval-print (expr)
1034   (/noshow "entering DEBUG-EVAL-PRINT" expr)
1035   (/noshow (fboundp 'compile))
1036   (setq +++ ++ ++ + + - - expr)
1037   (let* ((values (multiple-value-list (eval -)))
1038          (*standard-output* *debug-io*))
1039     (/noshow "done with EVAL in DEBUG-EVAL-PRINT")
1040     (fresh-line)
1041     (if values (prin1 (car values)))
1042     (dolist (x (cdr values))
1043       (fresh-line)
1044       (prin1 x))
1045     (setq /// // // / / values)
1046     (setq *** ** ** * * (car values))
1047     ;; Make sure that nobody passes back an unbound marker.
1048     (unless (boundp '*)
1049       (setq * nil)
1050       (fresh-line)
1051       ;; FIXME: The way INTERACTIVE-EVAL does this seems better.
1052       (princ "Setting * to NIL (was unbound marker)."))))
1053 \f
1054 ;;;; debug loop functions
1055
1056 ;;; These commands are functions, not really commands, so that users
1057 ;;; can get their hands on the values returned.
1058
1059 (eval-when (:execute :compile-toplevel)
1060
1061 (sb!xc:defmacro define-var-operation (ref-or-set &optional value-var)
1062   `(let* ((temp (etypecase name
1063                   (symbol (sb!di:debug-fun-symbol-vars
1064                            (sb!di:frame-debug-fun *current-frame*)
1065                            name))
1066                   (simple-string (sb!di:ambiguous-debug-vars
1067                                   (sb!di:frame-debug-fun *current-frame*)
1068                                   name))))
1069           (location (sb!di:frame-code-location *current-frame*))
1070           ;; Let's only deal with valid variables.
1071           (vars (remove-if-not (lambda (v)
1072                                  (eq (sb!di:debug-var-validity v location)
1073                                      :valid))
1074                                temp)))
1075      (declare (list vars))
1076      (cond ((null vars)
1077             (error "No known valid variables match ~S." name))
1078            ((= (length vars) 1)
1079             ,(ecase ref-or-set
1080                (:ref
1081                 '(sb!di:debug-var-value (car vars) *current-frame*))
1082                (:set
1083                 `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1084                        ,value-var))))
1085            (t
1086             ;; Since we have more than one, first see whether we have
1087             ;; any variables that exactly match the specification.
1088             (let* ((name (etypecase name
1089                            (symbol (symbol-name name))
1090                            (simple-string name)))
1091                    ;; FIXME: REMOVE-IF-NOT is deprecated, use STRING/=
1092                    ;; instead.
1093                    (exact (remove-if-not (lambda (v)
1094                                            (string= (sb!di:debug-var-symbol-name v)
1095                                                     name))
1096                                          vars))
1097                    (vars (or exact vars)))
1098               (declare (simple-string name)
1099                        (list exact vars))
1100               (cond
1101                ;; Check now for only having one variable.
1102                ((= (length vars) 1)
1103                 ,(ecase ref-or-set
1104                    (:ref
1105                     '(sb!di:debug-var-value (car vars) *current-frame*))
1106                    (:set
1107                     `(setf (sb!di:debug-var-value (car vars) *current-frame*)
1108                            ,value-var))))
1109                ;; If there weren't any exact matches, flame about
1110                ;; ambiguity unless all the variables have the same
1111                ;; name.
1112                ((and (not exact)
1113                      (find-if-not
1114                       (lambda (v)
1115                         (string= (sb!di:debug-var-symbol-name v)
1116                                  (sb!di:debug-var-symbol-name (car vars))))
1117                       (cdr vars)))
1118                 (error "specification ambiguous:~%~{   ~A~%~}"
1119                        (mapcar #'sb!di:debug-var-symbol-name
1120                                (delete-duplicates
1121                                 vars :test #'string=
1122                                 :key #'sb!di:debug-var-symbol-name))))
1123                ;; All names are the same, so see whether the user
1124                ;; ID'ed one of them.
1125                (id-supplied
1126                 (let ((v (find id vars :key #'sb!di:debug-var-id)))
1127                   (unless v
1128                     (error
1129                      "invalid variable ID, ~W: should have been one of ~S"
1130                      id
1131                      (mapcar #'sb!di:debug-var-id vars)))
1132                   ,(ecase ref-or-set
1133                      (:ref
1134                       '(sb!di:debug-var-value v *current-frame*))
1135                      (:set
1136                       `(setf (sb!di:debug-var-value v *current-frame*)
1137                              ,value-var)))))
1138                (t
1139                 (error "Specify variable ID to disambiguate ~S. Use one of ~S."
1140                        name
1141                        (mapcar #'sb!di:debug-var-id vars)))))))))
1142
1143 ) ; EVAL-WHEN
1144
1145 ;;; FIXME: This doesn't work. It would be real nice we could make it
1146 ;;; work! Alas, it doesn't seem to work in CMU CL X86 either..
1147 (defun var (name &optional (id 0 id-supplied))
1148   #!+sb-doc
1149   "Return a variable's value if possible. NAME is a simple-string or symbol.
1150    If it is a simple-string, it is an initial substring of the variable's name.
1151    If name is a symbol, it has the same name and package as the variable whose
1152    value this function returns. If the symbol is uninterned, then the variable
1153    has the same name as the symbol, but it has no package.
1154
1155    If name is the initial substring of variables with different names, then
1156    this return no values after displaying the ambiguous names. If name
1157    determines multiple variables with the same name, then you must use the
1158    optional id argument to specify which one you want. If you left id
1159    unspecified, then this returns no values after displaying the distinguishing
1160    id values.
1161
1162    The result of this function is limited to the availability of variable
1163    information. This is SETF'able."
1164   (define-var-operation :ref))
1165 (defun (setf var) (value name &optional (id 0 id-supplied))
1166   (define-var-operation :set value))
1167
1168 ;;; This returns the COUNT'th arg as the user sees it from args, the
1169 ;;; result of SB!DI:DEBUG-FUN-LAMBDA-LIST. If this returns a
1170 ;;; potential DEBUG-VAR from the lambda-list, then the second value is
1171 ;;; T. If this returns a keyword symbol or a value from a rest arg,
1172 ;;; then the second value is NIL.
1173 ;;;
1174 ;;; FIXME: There's probably some way to merge the code here with
1175 ;;; FRAME-ARGS-AS-LIST. (A fair amount of logic is already shared
1176 ;;; through LAMBDA-LIST-ELEMENT-DISPATCH, but I suspect more could be.)
1177 (declaim (ftype (function (index list)) nth-arg))
1178 (defun nth-arg (count args)
1179   (let ((n count))
1180     (dolist (ele args (error "The argument specification ~S is out of range."
1181                              n))
1182       (lambda-list-element-dispatch ele
1183         :required ((if (zerop n) (return (values ele t))))
1184         :optional ((if (zerop n) (return (values (second ele) t))))
1185         :keyword ((cond ((zerop n)
1186                          (return (values (second ele) nil)))
1187                         ((zerop (decf n))
1188                          (return (values (third ele) t)))))
1189         :deleted ((if (zerop n) (return (values ele t))))
1190         :rest ((let ((var (second ele)))
1191                  (lambda-var-dispatch var (sb!di:frame-code-location
1192                                            *current-frame*)
1193                    (error "unused &REST argument before n'th argument")
1194                    (dolist (value
1195                             (sb!di:debug-var-value var *current-frame*)
1196                             (error
1197                              "The argument specification ~S is out of range."
1198                              n))
1199                      (if (zerop n)
1200                          (return-from nth-arg (values value nil))
1201                          (decf n)))
1202                    (error "invalid &REST argument before n'th argument")))))
1203       (decf n))))
1204
1205 (defun arg (n)
1206   #!+sb-doc
1207   "Return the N'th argument's value if possible. Argument zero is the first
1208    argument in a frame's default printed representation. Count keyword/value
1209    pairs as separate arguments."
1210   (multiple-value-bind (var lambda-var-p)
1211       (nth-arg n (handler-case (sb!di:debug-fun-lambda-list
1212                                 (sb!di:frame-debug-fun *current-frame*))
1213                    (sb!di:lambda-list-unavailable ()
1214                      (error "No argument values are available."))))
1215     (if lambda-var-p
1216         (lambda-var-dispatch var (sb!di:frame-code-location *current-frame*)
1217           (error "Unused arguments have no values.")
1218           (sb!di:debug-var-value var *current-frame*)
1219           (error "invalid argument value"))
1220         var)))
1221 \f
1222 ;;;; machinery for definition of debug loop commands
1223
1224 (defvar *debug-commands* nil)
1225
1226 ;;; Interface to *DEBUG-COMMANDS*. No required arguments in args are
1227 ;;; permitted.
1228 (defmacro !def-debug-command (name args &rest body)
1229   (let ((fun-name (symbolicate name "-DEBUG-COMMAND")))
1230     `(progn
1231        (setf *debug-commands*
1232              (remove ,name *debug-commands* :key #'car :test #'string=))
1233        (defun ,fun-name ,args
1234          (unless *in-the-debugger*
1235            (error "invoking debugger command while outside the debugger"))
1236          ,@body)
1237        (push (cons ,name #',fun-name) *debug-commands*)
1238        ',fun-name)))
1239
1240 (defun !def-debug-command-alias (new-name existing-name)
1241   (let ((pair (assoc existing-name *debug-commands* :test #'string=)))
1242     (unless pair (error "unknown debug command name: ~S" existing-name))
1243     (push (cons new-name (cdr pair)) *debug-commands*))
1244   new-name)
1245
1246 ;;; This takes a symbol and uses its name to find a debugger command,
1247 ;;; using initial substring matching. It returns the command function
1248 ;;; if form identifies only one command, but if form is ambiguous,
1249 ;;; this returns a list of the command names. If there are no matches,
1250 ;;; this returns nil. Whenever the loop that looks for a set of
1251 ;;; possibilities encounters an exact name match, we return that
1252 ;;; command function immediately.
1253 (defun debug-command-p (form &optional other-commands)
1254   (if (or (symbolp form) (integerp form))
1255       (let* ((name
1256               (if (symbolp form)
1257                   (symbol-name form)
1258                   (format nil "~W" form)))
1259              (len (length name))
1260              (res nil))
1261         (declare (simple-string name)
1262                  (fixnum len)
1263                  (list res))
1264
1265         ;; Find matching commands, punting if exact match.
1266         (flet ((match-command (ele)
1267                  (let* ((str (car ele))
1268                         (str-len (length str)))
1269                    (declare (simple-string str)
1270                             (fixnum str-len))
1271                    (cond ((< str-len len))
1272                          ((= str-len len)
1273                           (when (string= name str :end1 len :end2 len)
1274                             (return-from debug-command-p (cdr ele))))
1275                          ((string= name str :end1 len :end2 len)
1276                           (push ele res))))))
1277           (mapc #'match-command *debug-commands*)
1278           (mapc #'match-command other-commands))
1279
1280         ;; Return the right value.
1281         (cond ((not res) nil)
1282               ((= (length res) 1)
1283                (cdar res))
1284               (t ; Just return the names.
1285                (do ((cmds res (cdr cmds)))
1286                    ((not cmds) res)
1287                  (setf (car cmds) (caar cmds))))))))
1288
1289 ;;; Return a list of debug commands (in the same format as
1290 ;;; *DEBUG-COMMANDS*) that invoke each active restart.
1291 ;;;
1292 ;;; Two commands are made for each restart: one for the number, and
1293 ;;; one for the restart name (unless it's been shadowed by an earlier
1294 ;;; restart of the same name, or it is NIL).
1295 (defun make-restart-commands (&optional (restarts *debug-restarts*))
1296   (let ((commands)
1297         (num 0))                        ; better be the same as show-restarts!
1298     (dolist (restart restarts)
1299       (let ((name (string (restart-name restart))))
1300         (let ((restart-fun
1301                 (lambda ()
1302                   (/show0 "in restart-command closure, about to i-r-i")
1303                   (invoke-restart-interactively restart))))
1304           (push (cons (prin1-to-string num) restart-fun) commands)
1305           (unless (or (null (restart-name restart)) 
1306                       (find name commands :key #'car :test #'string=))
1307             (push (cons name restart-fun) commands))))
1308     (incf num))
1309   commands))
1310 \f
1311 ;;;; frame-changing commands
1312
1313 (!def-debug-command "UP" ()
1314   (let ((next (sb!di:frame-up *current-frame*)))
1315     (cond (next
1316            (setf *current-frame* next)
1317            (print-frame-call next))
1318           (t
1319            (format t "~&Top of stack.")))))
1320
1321 (!def-debug-command "DOWN" ()
1322   (let ((next (sb!di:frame-down *current-frame*)))
1323     (cond (next
1324            (setf *current-frame* next)
1325            (print-frame-call next))
1326           (t
1327            (format t "~&Bottom of stack.")))))
1328
1329 (!def-debug-command-alias "D" "DOWN")
1330
1331 ;;; CMU CL had this command, but SBCL doesn't, since it's redundant
1332 ;;; with "FRAME 0", and it interferes with abbreviations for the
1333 ;;; TOPLEVEL restart.
1334 ;;;(!def-debug-command "TOP" ()
1335 ;;;  (do ((prev *current-frame* lead)
1336 ;;;       (lead (sb!di:frame-up *current-frame*) (sb!di:frame-up lead)))
1337 ;;;      ((null lead)
1338 ;;;       (setf *current-frame* prev)
1339 ;;;       (print-frame-call prev))))
1340
1341 (!def-debug-command "BOTTOM" ()
1342   (do ((prev *current-frame* lead)
1343        (lead (sb!di:frame-down *current-frame*) (sb!di:frame-down lead)))
1344       ((null lead)
1345        (setf *current-frame* prev)
1346        (print-frame-call prev))))
1347
1348 (!def-debug-command-alias "B" "BOTTOM")
1349
1350 (!def-debug-command "FRAME" (&optional
1351                              (n (read-prompting-maybe "frame number: ")))
1352   (setf *current-frame*
1353         (multiple-value-bind (next-frame-fun limit-string)
1354             (if (< n (sb!di:frame-number *current-frame*))
1355                 (values #'sb!di:frame-up "top")
1356               (values #'sb!di:frame-down "bottom"))
1357           (do ((frame *current-frame*))
1358               ((= n (sb!di:frame-number frame))
1359                frame)
1360             (let ((next-frame (funcall next-frame-fun frame)))
1361               (cond (next-frame
1362                      (setf frame next-frame))
1363                     (t
1364                      (format t
1365                              "The ~A of the stack was encountered.~%"
1366                              limit-string)
1367                      (return frame)))))))
1368   (print-frame-call *current-frame*))
1369
1370 (!def-debug-command-alias "F" "FRAME")
1371 \f
1372 ;;;; commands for entering and leaving the debugger
1373
1374 ;;; CMU CL supported this QUIT debug command, but SBCL provides this
1375 ;;; functionality with a restart instead. (The QUIT debug command was
1376 ;;; removed because it's confusing to have "quit" mean two different
1377 ;;; things in the system, "restart the top level REPL" in the debugger
1378 ;;; and "terminate the Lisp system" as the SB-EXT:QUIT function.)
1379 ;;;
1380 ;;;(!def-debug-command "QUIT" ()
1381 ;;;  (throw 'sb!impl::toplevel-catcher nil))
1382
1383 ;;; CMU CL supported this GO debug command, but SBCL doesn't -- in
1384 ;;; SBCL you just type the CONTINUE restart name instead (or "C" or
1385 ;;; "RESTART CONTINUE", that's OK too).
1386 ;;;(!def-debug-command "GO" ()
1387 ;;;  (continue *debug-condition*)
1388 ;;;  (error "There is no restart named CONTINUE."))
1389
1390 (!def-debug-command "RESTART" ()
1391   (/show0 "doing RESTART debug-command")
1392   (let ((num (read-if-available :prompt)))
1393     (when (eq num :prompt)
1394       (show-restarts *debug-restarts* *debug-io*)
1395       (write-string "restart: ")
1396       (force-output)
1397       (setf num (read *debug-io*)))
1398     (let ((restart (typecase num
1399                      (unsigned-byte
1400                       (nth num *debug-restarts*))
1401                      (symbol
1402                       (find num *debug-restarts* :key #'restart-name
1403                             :test (lambda (sym1 sym2)
1404                                     (string= (symbol-name sym1)
1405                                              (symbol-name sym2)))))
1406                      (t
1407                       (format t "~S is invalid as a restart name.~%" num)
1408                       (return-from restart-debug-command nil)))))
1409       (/show0 "got RESTART")
1410       (if restart
1411           (invoke-restart-interactively restart)
1412           ;; FIXME: Even if this isn't handled by WARN, it probably
1413           ;; shouldn't go to *STANDARD-OUTPUT*, but *ERROR-OUTPUT* or
1414           ;; *QUERY-IO* or something. Look through this file to
1415           ;; straighten out stream usage.
1416           (princ "There is no such restart.")))))
1417 \f
1418 ;;;; information commands
1419
1420 (!def-debug-command "HELP" ()
1421   ;; CMU CL had a little toy pager here, but "if you aren't running
1422   ;; ILISP (or a smart windowing system, or something) you deserve to
1423   ;; lose", so we've dropped it in SBCL. However, in case some
1424   ;; desperate holdout is running this on a dumb terminal somewhere,
1425   ;; we tell him where to find the message stored as a string.
1426   (format *debug-io*
1427           "~&~A~2%(The HELP string is stored in ~S.)~%"
1428           *debug-help-string*
1429           '*debug-help-string*))
1430
1431 (!def-debug-command-alias "?" "HELP")
1432
1433 (!def-debug-command "ERROR" ()
1434   (format *debug-io* "~A~%" *debug-condition*)
1435   (show-restarts *debug-restarts* *debug-io*))
1436
1437 (!def-debug-command "BACKTRACE" ()
1438   (backtrace (read-if-available most-positive-fixnum)))
1439
1440 (!def-debug-command "PRINT" ()
1441   (print-frame-call *current-frame*))
1442
1443 (!def-debug-command-alias "P" "PRINT")
1444
1445 (!def-debug-command "LIST-LOCALS" ()
1446   (let ((d-fun (sb!di:frame-debug-fun *current-frame*)))
1447     (if (sb!di:debug-var-info-available d-fun)
1448         (let ((*standard-output* *debug-io*)
1449               (location (sb!di:frame-code-location *current-frame*))
1450               (prefix (read-if-available nil))
1451               (any-p nil)
1452               (any-valid-p nil))
1453           (dolist (v (sb!di:ambiguous-debug-vars
1454                         d-fun
1455                         (if prefix (string prefix) "")))
1456             (setf any-p t)
1457             (when (eq (sb!di:debug-var-validity v location) :valid)
1458               (setf any-valid-p t)
1459               (format t "~S~:[#~W~;~*~]  =  ~S~%"
1460                       (sb!di:debug-var-symbol v)
1461                       (zerop (sb!di:debug-var-id v))
1462                       (sb!di:debug-var-id v)
1463                       (sb!di:debug-var-value v *current-frame*))))
1464
1465           (cond
1466            ((not any-p)
1467             (format t "There are no local variables ~@[starting with ~A ~]~
1468                        in the function."
1469                     prefix))
1470            ((not any-valid-p)
1471             (format t "All variables ~@[starting with ~A ~]currently ~
1472                        have invalid values."
1473                     prefix))))
1474         (write-line "There is no variable information available."))))
1475
1476 (!def-debug-command-alias "L" "LIST-LOCALS")
1477
1478 (!def-debug-command "SOURCE" ()
1479   (fresh-line)
1480   (print-code-location-source-form (sb!di:frame-code-location *current-frame*)
1481                                    (read-if-available 0)))
1482 \f
1483 ;;;; source location printing
1484
1485 ;;; We cache a stream to the last valid file debug source so that we
1486 ;;; won't have to repeatedly open the file.
1487 ;;;
1488 ;;; KLUDGE: This sounds like a bug, not a feature. Opening files is fast
1489 ;;; in the 1990s, so the benefit is negligible, less important than the
1490 ;;; potential of extra confusion if someone changes the source during
1491 ;;; a debug session and the change doesn't show up. And removing this
1492 ;;; would simplify the system, which I like. -- WHN 19990903
1493 (defvar *cached-debug-source* nil)
1494 (declaim (type (or sb!di:debug-source null) *cached-debug-source*))
1495 (defvar *cached-source-stream* nil)
1496 (declaim (type (or stream null) *cached-source-stream*))
1497
1498 ;;; To suppress the read-time evaluation #. macro during source read,
1499 ;;; *READTABLE* is modified. *READTABLE* is cached to avoid
1500 ;;; copying it each time, and invalidated when the
1501 ;;; *CACHED-DEBUG-SOURCE* has changed.
1502 (defvar *cached-readtable* nil)
1503 (declaim (type (or readtable null) *cached-readtable*))
1504
1505 ;;; Stuff to clean up before saving a core
1506 (defun debug-deinit ()
1507   (setf *cached-debug-source* nil
1508         *cached-source-stream* nil
1509         *cached-readtable* nil))
1510
1511 ;;; We also cache the last toplevel form that we printed a source for
1512 ;;; so that we don't have to do repeated reads and calls to
1513 ;;; FORM-NUMBER-TRANSLATIONS.
1514 (defvar *cached-toplevel-form-offset* nil)
1515 (declaim (type (or index null) *cached-toplevel-form-offset*))
1516 (defvar *cached-toplevel-form*)
1517 (defvar *cached-form-number-translations*)
1518
1519 ;;; Given a code location, return the associated form-number
1520 ;;; translations and the actual top level form. We check our cache ---
1521 ;;; if there is a miss, we dispatch on the kind of the debug source.
1522 (defun get-toplevel-form (location)
1523   (let ((d-source (sb!di:code-location-debug-source location)))
1524     (if (and (eq d-source *cached-debug-source*)
1525              (eql (sb!di:code-location-toplevel-form-offset location)
1526                   *cached-toplevel-form-offset*))
1527         (values *cached-form-number-translations* *cached-toplevel-form*)
1528         (let* ((offset (sb!di:code-location-toplevel-form-offset location))
1529                (res
1530                 (ecase (sb!di:debug-source-from d-source)
1531                   (:file (get-file-toplevel-form location))
1532                   (:lisp (svref (sb!di:debug-source-name d-source) offset)))))
1533           (setq *cached-toplevel-form-offset* offset)
1534           (values (setq *cached-form-number-translations*
1535                         (sb!di:form-number-translations res offset))
1536                   (setq *cached-toplevel-form* res))))))
1537
1538 ;;; Locate the source file (if it still exists) and grab the top level
1539 ;;; form. If the file is modified, we use the top level form offset
1540 ;;; instead of the recorded character offset.
1541 (defun get-file-toplevel-form (location)
1542   (let* ((d-source (sb!di:code-location-debug-source location))
1543          (tlf-offset (sb!di:code-location-toplevel-form-offset location))
1544          (local-tlf-offset (- tlf-offset
1545                               (sb!di:debug-source-root-number d-source)))
1546          (char-offset
1547           (aref (or (sb!di:debug-source-start-positions d-source)
1548                     (error "no start positions map"))
1549                 local-tlf-offset))
1550          (name (sb!di:debug-source-name d-source)))
1551     (unless (eq d-source *cached-debug-source*)
1552       (unless (and *cached-source-stream*
1553                    (equal (pathname *cached-source-stream*)
1554                           (pathname name)))
1555         (setq *cached-readtable* nil)
1556         (when *cached-source-stream* (close *cached-source-stream*))
1557         (setq *cached-source-stream* (open name :if-does-not-exist nil))
1558         (unless *cached-source-stream*
1559           (error "The source file no longer exists:~%  ~A" (namestring name)))
1560         (format t "~%; file: ~A~%" (namestring name)))
1561
1562         (setq *cached-debug-source*
1563               (if (= (sb!di:debug-source-created d-source)
1564                      (file-write-date name))
1565                   d-source nil)))
1566
1567     (cond
1568      ((eq *cached-debug-source* d-source)
1569       (file-position *cached-source-stream* char-offset))
1570      (t
1571       (format t "~%; File has been modified since compilation:~%;   ~A~@
1572                  ; Using form offset instead of character position.~%"
1573               (namestring name))
1574       (file-position *cached-source-stream* 0)
1575       (let ((*read-suppress* t))
1576         (dotimes (i local-tlf-offset)
1577           (read *cached-source-stream*)))))
1578     (unless *cached-readtable*
1579       (setq *cached-readtable* (copy-readtable))
1580       (set-dispatch-macro-character
1581        #\# #\.
1582        (lambda (stream sub-char &rest rest)
1583          (declare (ignore rest sub-char))
1584          (let ((token (read stream t nil t)))
1585            (format nil "#.~S" token)))
1586        *cached-readtable*))
1587     (let ((*readtable* *cached-readtable*))
1588       (read *cached-source-stream*))))
1589
1590 (defun print-code-location-source-form (location context)
1591   (let* ((location (maybe-block-start-location location))
1592          (form-num (sb!di:code-location-form-number location)))
1593     (multiple-value-bind (translations form) (get-toplevel-form location)
1594       (unless (< form-num (length translations))
1595         (error "The source path no longer exists."))
1596       (prin1 (sb!di:source-path-context form
1597                                         (svref translations form-num)
1598                                         context)))))
1599 \f
1600 ;;; breakpoint and step commands
1601
1602 ;;; Step to the next code-location.
1603 (!def-debug-command "STEP" ()
1604   (setf *number-of-steps* (read-if-available 1))
1605   (set-step-breakpoint *current-frame*)
1606   (continue *debug-condition*)
1607   (error "couldn't continue"))
1608
1609 ;;; List possible breakpoint locations, which ones are active, and
1610 ;;; where the CONTINUE restart will transfer control. Set
1611 ;;; *POSSIBLE-BREAKPOINTS* to the code-locations which can then be
1612 ;;; used by sbreakpoint.
1613 (!def-debug-command "LIST-LOCATIONS" ()
1614   (let ((df (read-if-available *default-breakpoint-debug-fun*)))
1615     (cond ((consp df)
1616            (setf df (sb!di:fun-debug-fun (eval df)))
1617            (setf *default-breakpoint-debug-fun* df))
1618           ((or (eq ':c df)
1619                (not *default-breakpoint-debug-fun*))
1620            (setf df (sb!di:frame-debug-fun *current-frame*))
1621            (setf *default-breakpoint-debug-fun* df)))
1622     (setf *possible-breakpoints* (possible-breakpoints df)))
1623   (let ((continue-at (sb!di:frame-code-location *current-frame*)))
1624     (let ((active (location-in-list *default-breakpoint-debug-fun*
1625                                     *breakpoints* :fun-start))
1626           (here (sb!di:code-location=
1627                  (sb!di:debug-fun-start-location
1628                   *default-breakpoint-debug-fun*) continue-at)))
1629       (when (or active here)
1630         (format t "::FUN-START ")
1631         (when active (format t " *Active*"))
1632         (when here (format t " *Continue here*"))))
1633
1634     (let ((prev-location nil)
1635           (prev-num 0)
1636           (this-num 0))
1637       (flet ((flush ()
1638                (when prev-location
1639                  (let ((this-num (1- this-num)))
1640                    (if (= prev-num this-num)
1641                        (format t "~&~W: " prev-num)
1642                        (format t "~&~W-~W: " prev-num this-num)))
1643                  (print-code-location-source-form prev-location 0)
1644                  (when *print-location-kind*
1645                    (format t "~S " (sb!di:code-location-kind prev-location)))
1646                  (when (location-in-list prev-location *breakpoints*)
1647                    (format t " *Active*"))
1648                  (when (sb!di:code-location= prev-location continue-at)
1649                    (format t " *Continue here*")))))
1650         
1651         (dolist (code-location *possible-breakpoints*)
1652           (when (or *print-location-kind*
1653                     (location-in-list code-location *breakpoints*)
1654                     (sb!di:code-location= code-location continue-at)
1655                     (not prev-location)
1656                     (not (eq (sb!di:code-location-debug-source code-location)
1657                              (sb!di:code-location-debug-source prev-location)))
1658                     (not (eq (sb!di:code-location-toplevel-form-offset
1659                               code-location)
1660                              (sb!di:code-location-toplevel-form-offset
1661                               prev-location)))
1662                     (not (eq (sb!di:code-location-form-number code-location)
1663                              (sb!di:code-location-form-number prev-location))))
1664             (flush)
1665             (setq prev-location code-location  prev-num this-num))
1666
1667           (incf this-num))))
1668
1669     (when (location-in-list *default-breakpoint-debug-fun*
1670                             *breakpoints*
1671                             :fun-end)
1672       (format t "~&::FUN-END *Active* "))))
1673
1674 (!def-debug-command-alias "LL" "LIST-LOCATIONS")
1675
1676 ;;; Set breakpoint at the given number.
1677 (!def-debug-command "BREAKPOINT" ()
1678   (let ((index (read-prompting-maybe "location number, :START, or :END: "))
1679         (break t)
1680         (condition t)
1681         (print nil)
1682         (print-functions nil)
1683         (function nil)
1684         (bp)
1685         (place *default-breakpoint-debug-fun*))
1686     (flet ((get-command-line ()
1687              (let ((command-line nil)
1688                    (unique '(nil)))
1689                (loop
1690                  (let ((next-input (read-if-available unique)))
1691                    (when (eq next-input unique) (return))
1692                    (push next-input command-line)))
1693                (nreverse command-line)))
1694            (set-vars-from-command-line (command-line)
1695              (do ((arg (pop command-line) (pop command-line)))
1696                  ((not arg))
1697                (ecase arg
1698                  (:condition (setf condition (pop command-line)))
1699                  (:print (push (pop command-line) print))
1700                  (:break (setf break (pop command-line)))
1701                  (:function
1702                   (setf function (eval (pop command-line)))
1703                   (setf *default-breakpoint-debug-fun*
1704                         (sb!di:fun-debug-fun function))
1705                   (setf place *default-breakpoint-debug-fun*)
1706                   (setf *possible-breakpoints*
1707                         (possible-breakpoints
1708                          *default-breakpoint-debug-fun*))))))
1709            (setup-fun-start ()
1710              (let ((code-loc (sb!di:debug-fun-start-location place)))
1711                (setf bp (sb!di:make-breakpoint #'main-hook-fun
1712                                                place
1713                                                :kind :fun-start))
1714                (setf break (sb!di:preprocess-for-eval break code-loc))
1715                (setf condition (sb!di:preprocess-for-eval condition code-loc))
1716                (dolist (form print)
1717                  (push (cons (sb!di:preprocess-for-eval form code-loc) form)
1718                        print-functions))))
1719            (setup-fun-end ()
1720              (setf bp
1721                    (sb!di:make-breakpoint #'main-hook-fun
1722                                           place
1723                                           :kind :fun-end))
1724              (setf break
1725                    ;; FIXME: These and any other old (COERCE `(LAMBDA ..) ..)
1726                    ;; forms should be converted to shiny new (LAMBDA ..) forms.
1727                    ;; (Search the sources for "coerce.*\(lambda".)
1728                    (coerce `(lambda (dummy)
1729                               (declare (ignore dummy)) ,break)
1730                            'function))
1731              (setf condition (coerce `(lambda (dummy)
1732                                         (declare (ignore dummy)) ,condition)
1733                                      'function))
1734              (dolist (form print)
1735                (push (cons
1736                       (coerce `(lambda (dummy)
1737                                  (declare (ignore dummy)) ,form) 'function)
1738                       form)
1739                      print-functions)))
1740            (setup-code-location ()
1741              (setf place (nth index *possible-breakpoints*))
1742              (setf bp (sb!di:make-breakpoint #'main-hook-fun place
1743                                              :kind :code-location))
1744              (dolist (form print)
1745                (push (cons
1746                       (sb!di:preprocess-for-eval form place)
1747                       form)
1748                      print-functions))
1749              (setf break (sb!di:preprocess-for-eval break place))
1750              (setf condition (sb!di:preprocess-for-eval condition place))))
1751       (set-vars-from-command-line (get-command-line))
1752       (cond
1753        ((or (eq index :start) (eq index :s))
1754         (setup-fun-start))
1755        ((or (eq index :end) (eq index :e))
1756         (setup-fun-end))
1757        (t
1758         (setup-code-location)))
1759       (sb!di:activate-breakpoint bp)
1760       (let* ((new-bp-info (create-breakpoint-info place bp index
1761                                                   :break break
1762                                                   :print print-functions
1763                                                   :condition condition))
1764              (old-bp-info (location-in-list new-bp-info *breakpoints*)))
1765         (when old-bp-info
1766           (sb!di:deactivate-breakpoint (breakpoint-info-breakpoint
1767                                         old-bp-info))
1768           (setf *breakpoints* (remove old-bp-info *breakpoints*))
1769           (format t "previous breakpoint removed~%"))
1770         (push new-bp-info *breakpoints*))
1771       (print-breakpoint-info (first *breakpoints*))
1772       (format t "~&added"))))
1773
1774 (!def-debug-command-alias "BP" "BREAKPOINT")
1775
1776 ;;; List all breakpoints which are set.
1777 (!def-debug-command "LIST-BREAKPOINTS" ()
1778   (setf *breakpoints*
1779         (sort *breakpoints* #'< :key #'breakpoint-info-breakpoint-number))
1780   (dolist (info *breakpoints*)
1781     (print-breakpoint-info info)))
1782
1783 (!def-debug-command-alias "LB" "LIST-BREAKPOINTS")
1784 (!def-debug-command-alias "LBP" "LIST-BREAKPOINTS")
1785
1786 ;;; Remove breakpoint N, or remove all breakpoints if no N given.
1787 (!def-debug-command "DELETE-BREAKPOINT" ()
1788   (let* ((index (read-if-available nil))
1789          (bp-info
1790           (find index *breakpoints* :key #'breakpoint-info-breakpoint-number)))
1791     (cond (bp-info
1792            (sb!di:delete-breakpoint (breakpoint-info-breakpoint bp-info))
1793            (setf *breakpoints* (remove bp-info *breakpoints*))
1794            (format t "breakpoint ~S removed~%" index))
1795           (index (format t "The breakpoint doesn't exist."))
1796           (t
1797            (dolist (ele *breakpoints*)
1798              (sb!di:delete-breakpoint (breakpoint-info-breakpoint ele)))
1799            (setf *breakpoints* nil)
1800            (format t "all breakpoints deleted~%")))))
1801
1802 (!def-debug-command-alias "DBP" "DELETE-BREAKPOINT")
1803 \f
1804 ;;; miscellaneous commands
1805
1806 (!def-debug-command "DESCRIBE" ()
1807   (let* ((curloc (sb!di:frame-code-location *current-frame*))
1808          (debug-fun (sb!di:code-location-debug-fun curloc))
1809          (function (sb!di:debug-fun-fun debug-fun)))
1810     (if function
1811         (describe function)
1812         (format t "can't figure out the function for this frame"))))
1813
1814 (!def-debug-command "SLURP" ()
1815   (loop while (read-char-no-hang *standard-input*)))
1816
1817 (!def-debug-command "RETURN" (&optional
1818                               (return (read-prompting-maybe
1819                                        "return: ")))
1820   (let ((tag (find-if (lambda (x)
1821                         (and (typep (car x) 'symbol)
1822                              (not (symbol-package (car x)))
1823                              (string= (car x) "SB-DEBUG-CATCH-TAG")))
1824                       (sb!di::frame-catches *current-frame*))))
1825     (if tag
1826         (throw (car tag)
1827           (funcall (sb!di:preprocess-for-eval
1828                     return
1829                     (sb!di:frame-code-location *current-frame*))
1830                    *current-frame*))
1831         (format t "~@<can't find a tag for this frame ~
1832                    ~2I~_(hint: try increasing the DEBUG optimization quality ~
1833                    and recompiling)~:@>"))))
1834 \f
1835 ;;;; debug loop command utilities
1836
1837 (defun read-prompting-maybe (prompt)
1838   (unless (sb!int:listen-skip-whitespace *debug-io*)
1839     (princ prompt)
1840     (force-output))
1841   (read *debug-io*))
1842
1843 (defun read-if-available (default)
1844   (if (sb!int:listen-skip-whitespace *debug-io*)
1845       (read *debug-io*)
1846       default))