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