3d375e86dd74b530c32ab7e8ee40f123c6dd83a8
[sbcl.git] / src / code / debug-int.lisp
1 ;;;; the implementation of the programmer's interface to writing
2 ;;;; debugging tools
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!DI")
14
15 ;;; FIXME: There are an awful lot of package prefixes in this code.
16 ;;; Couldn't we have SB-DI use the SB-C and SB-VM packages?
17 \f
18 ;;;; conditions
19
20 ;;;; The interface to building debugging tools signals conditions that
21 ;;;; prevent it from adhering to its contract. These are
22 ;;;; serious-conditions because the program using the interface must
23 ;;;; handle them before it can correctly continue execution. These
24 ;;;; debugging conditions are not errors since it is no fault of the
25 ;;;; programmers that the conditions occur. The interface does not
26 ;;;; provide for programs to detect these situations other than
27 ;;;; calling a routine that detects them and signals a condition. For
28 ;;;; example, programmers call A which may fail to return successfully
29 ;;;; due to a lack of debug information, and there is no B the they
30 ;;;; could have called to realize A would fail. It is not an error to
31 ;;;; have called A, but it is an error for the program to then ignore
32 ;;;; the signal generated by A since it cannot continue without A's
33 ;;;; correctly returning a value or performing some operation.
34 ;;;;
35 ;;;; Use DEBUG-SIGNAL to signal these conditions.
36
37 (define-condition debug-condition (serious-condition)
38   ()
39   #!+sb-doc
40   (:documentation
41    "All DEBUG-CONDITIONs inherit from this type. These are serious conditions
42     that must be handled, but they are not programmer errors."))
43
44 (define-condition no-debug-fun-returns (debug-condition)
45   ((debug-fun :reader no-debug-fun-returns-debug-fun
46               :initarg :debug-fun))
47   #!+sb-doc
48   (:documentation
49    "The system could not return values from a frame with DEBUG-FUN since
50     it lacked information about returning values.")
51   (:report (lambda (condition stream)
52              (let ((fun (debug-fun-fun
53                          (no-debug-fun-returns-debug-fun condition))))
54                (format stream
55                        "~&Cannot return values from ~:[frame~;~:*~S~] since ~
56                         the debug information lacks details about returning ~
57                         values here."
58                        fun)))))
59
60 (define-condition no-debug-blocks (debug-condition)
61   ((debug-fun :reader no-debug-blocks-debug-fun
62               :initarg :debug-fun))
63   #!+sb-doc
64   (:documentation "The debug-fun has no debug-block information.")
65   (:report (lambda (condition stream)
66              (format stream "~&~S has no debug-block information."
67                      (no-debug-blocks-debug-fun condition)))))
68
69 (define-condition no-debug-vars (debug-condition)
70   ((debug-fun :reader no-debug-vars-debug-fun
71               :initarg :debug-fun))
72   #!+sb-doc
73   (:documentation "The DEBUG-FUN has no DEBUG-VAR information.")
74   (:report (lambda (condition stream)
75              (format stream "~&~S has no debug variable information."
76                      (no-debug-vars-debug-fun condition)))))
77
78 (define-condition lambda-list-unavailable (debug-condition)
79   ((debug-fun :reader lambda-list-unavailable-debug-fun
80               :initarg :debug-fun))
81   #!+sb-doc
82   (:documentation
83    "The DEBUG-FUN has no lambda list since argument DEBUG-VARs are
84     unavailable.")
85   (:report (lambda (condition stream)
86              (format stream "~&~S has no lambda-list information available."
87                      (lambda-list-unavailable-debug-fun condition)))))
88
89 (define-condition invalid-value (debug-condition)
90   ((debug-var :reader invalid-value-debug-var :initarg :debug-var)
91    (frame :reader invalid-value-frame :initarg :frame))
92   (:report (lambda (condition stream)
93              (format stream "~&~S has :invalid or :unknown value in ~S."
94                      (invalid-value-debug-var condition)
95                      (invalid-value-frame condition)))))
96
97 (define-condition ambiguous-var-name (debug-condition)
98   ((name :reader ambiguous-var-name-name :initarg :name)
99    (frame :reader ambiguous-var-name-frame :initarg :frame))
100   (:report (lambda (condition stream)
101              (format stream "~&~S names more than one valid variable in ~S."
102                      (ambiguous-var-name-name condition)
103                      (ambiguous-var-name-frame condition)))))
104 \f
105 ;;;; errors and DEBUG-SIGNAL
106
107 ;;; The debug-internals code tries to signal all programmer errors as
108 ;;; subtypes of DEBUG-ERROR. There are calls to ERROR signalling
109 ;;; SIMPLE-ERRORs, but these dummy checks in the code and shouldn't
110 ;;; come up.
111 ;;;
112 ;;; While under development, this code also signals errors in code
113 ;;; branches that remain unimplemented.
114
115 (define-condition debug-error (error) ()
116   #!+sb-doc
117   (:documentation
118    "All programmer errors from using the interface for building debugging
119     tools inherit from this type."))
120
121 (define-condition unhandled-debug-condition (debug-error)
122   ((condition :reader unhandled-debug-condition-condition :initarg :condition))
123   (:report (lambda (condition stream)
124              (format stream "~&unhandled DEBUG-CONDITION:~%~A"
125                      (unhandled-debug-condition-condition condition)))))
126
127 (define-condition unknown-code-location (debug-error)
128   ((code-location :reader unknown-code-location-code-location
129                   :initarg :code-location))
130   (:report (lambda (condition stream)
131              (format stream "~&invalid use of an unknown code-location: ~S"
132                      (unknown-code-location-code-location condition)))))
133
134 (define-condition unknown-debug-var (debug-error)
135   ((debug-var :reader unknown-debug-var-debug-var :initarg :debug-var)
136    (debug-fun :reader unknown-debug-var-debug-fun
137               :initarg :debug-fun))
138   (:report (lambda (condition stream)
139              (format stream "~&~S is not in ~S."
140                      (unknown-debug-var-debug-var condition)
141                      (unknown-debug-var-debug-fun condition)))))
142
143 (define-condition invalid-control-stack-pointer (debug-error)
144   ()
145   (:report (lambda (condition stream)
146              (declare (ignore condition))
147              (fresh-line stream)
148              (write-string "invalid control stack pointer" stream))))
149
150 (define-condition frame-fun-mismatch (debug-error)
151   ((code-location :reader frame-fun-mismatch-code-location
152                   :initarg :code-location)
153    (frame :reader frame-fun-mismatch-frame :initarg :frame)
154    (form :reader frame-fun-mismatch-form :initarg :form))
155   (:report (lambda (condition stream)
156              (format
157               stream
158               "~&Form was preprocessed for ~S,~% but called on ~S:~%  ~S"
159               (frame-fun-mismatch-code-location condition)
160               (frame-fun-mismatch-frame condition)
161               (frame-fun-mismatch-form condition)))))
162
163 ;;; This signals debug-conditions. If they go unhandled, then signal
164 ;;; an UNHANDLED-DEBUG-CONDITION error.
165 ;;;
166 ;;; ??? Get SIGNAL in the right package!
167 (defmacro debug-signal (datum &rest arguments)
168   `(let ((condition (make-condition ,datum ,@arguments)))
169      (signal condition)
170      (error 'unhandled-debug-condition :condition condition)))
171 \f
172 ;;;; structures
173 ;;;;
174 ;;;; Most of these structures model information stored in internal
175 ;;;; data structures created by the compiler. Whenever comments
176 ;;;; preface an object or type with "compiler", they refer to the
177 ;;;; internal compiler thing, not to the object or type with the same
178 ;;;; name in the "SB-DI" package.
179
180 ;;;; DEBUG-VARs
181
182 ;;; These exist for caching data stored in packed binary form in
183 ;;; compiler DEBUG-FUNs.
184 (defstruct (debug-var (:constructor nil)
185                       (:copier nil))
186   ;; the name of the variable
187   (symbol (missing-arg) :type symbol)
188   ;; a unique integer identification relative to other variables with the same
189   ;; symbol
190   (id 0 :type index)
191   ;; Does the variable always have a valid value?
192   (alive-p nil :type boolean))
193 (def!method print-object ((debug-var debug-var) stream)
194   (print-unreadable-object (debug-var stream :type t :identity t)
195     (format stream
196             "~S ~W"
197             (debug-var-symbol debug-var)
198             (debug-var-id debug-var))))
199
200 #!+sb-doc
201 (setf (fdocumentation 'debug-var-id 'function)
202   "Return the integer that makes DEBUG-VAR's name and package unique
203    with respect to other DEBUG-VARs in the same function.")
204
205 (defstruct (compiled-debug-var
206             (:include debug-var)
207             (:constructor make-compiled-debug-var
208                           (symbol id alive-p sc-offset save-sc-offset))
209             (:copier nil))
210   ;; storage class and offset (unexported)
211   (sc-offset nil :type sb!c:sc-offset)
212   ;; storage class and offset when saved somewhere
213   (save-sc-offset nil :type (or sb!c:sc-offset null)))
214
215 ;;;; frames
216
217 ;;; These represent call frames on the stack.
218 (defstruct (frame (:constructor nil)
219                   (:copier nil))
220   ;; the next frame up, or NIL when top frame
221   (up nil :type (or frame null))
222   ;; the previous frame down, or NIL when the bottom frame. Before
223   ;; computing the next frame down, this slot holds the frame pointer
224   ;; to the control stack for the given frame. This lets us get the
225   ;; next frame down and the return-pc for that frame.
226   (%down :unparsed :type (or frame (member nil :unparsed)))
227   ;; the DEBUG-FUN for the function whose call this frame represents
228   (debug-fun nil :type debug-fun)
229   ;; the CODE-LOCATION where the frame's DEBUG-FUN will continue
230   ;; running when program execution returns to this frame. If someone
231   ;; interrupted this frame, the result could be an unknown
232   ;; CODE-LOCATION.
233   (code-location nil :type code-location)
234   ;; an a-list of catch-tags to code-locations
235   (%catches :unparsed :type (or list (member :unparsed)))
236   ;; pointer to frame on control stack (unexported)
237   pointer
238   ;; This is the frame's number for prompt printing. Top is zero.
239   (number 0 :type index))
240
241 (defstruct (compiled-frame
242             (:include frame)
243             (:constructor make-compiled-frame
244                           (pointer up debug-fun code-location number
245                                    &optional escaped))
246             (:copier nil))
247   ;; This indicates whether someone interrupted the frame.
248   ;; (unexported). If escaped, this is a pointer to the state that was
249   ;; saved when we were interrupted, an os_context_t, i.e. the third
250   ;; argument to an SA_SIGACTION-style signal handler.
251   escaped)
252 (def!method print-object ((obj compiled-frame) str)
253   (print-unreadable-object (obj str :type t)
254     (format str
255             "~S~:[~;, interrupted~]"
256             (debug-fun-name (frame-debug-fun obj))
257             (compiled-frame-escaped obj))))
258 \f
259 ;;;; DEBUG-FUNs
260
261 ;;; These exist for caching data stored in packed binary form in
262 ;;; compiler DEBUG-FUNs. *COMPILED-DEBUG-FUNS* maps a SB!C::DEBUG-FUN
263 ;;; to a DEBUG-FUN. There should only be one DEBUG-FUN in existence
264 ;;; for any function; that is, all CODE-LOCATIONs and other objects
265 ;;; that reference DEBUG-FUNs point to unique objects. This is
266 ;;; due to the overhead in cached information.
267 (defstruct (debug-fun (:constructor nil)
268                       (:copier nil))
269   ;; some representation of the function arguments. See
270   ;; DEBUG-FUN-LAMBDA-LIST.
271   ;; NOTE: must parse vars before parsing arg list stuff.
272   (%lambda-list :unparsed)
273   ;; cached DEBUG-VARS information (unexported).
274   ;; These are sorted by their name.
275   (%debug-vars :unparsed :type (or simple-vector null (member :unparsed)))
276   ;; cached debug-block information. This is NIL when we have tried to
277   ;; parse the packed binary info, but none is available.
278   (blocks :unparsed :type (or simple-vector null (member :unparsed)))
279   ;; the actual function if available
280   (%function :unparsed :type (or null function (member :unparsed))))
281 (def!method print-object ((obj debug-fun) stream)
282   (print-unreadable-object (obj stream :type t)
283     (prin1 (debug-fun-name obj) stream)))
284
285 (defstruct (compiled-debug-fun
286             (:include debug-fun)
287             (:constructor %make-compiled-debug-fun
288                           (compiler-debug-fun component))
289             (:copier nil))
290   ;; compiler's dumped DEBUG-FUN information (unexported)
291   (compiler-debug-fun nil :type sb!c::compiled-debug-fun)
292   ;; code object (unexported).
293   component
294   ;; the :FUN-START breakpoint (if any) used to facilitate
295   ;; function end breakpoints
296   (end-starter nil :type (or null breakpoint)))
297
298 ;;; This maps SB!C::COMPILED-DEBUG-FUNs to
299 ;;; COMPILED-DEBUG-FUNs, so we can get at cached stuff and not
300 ;;; duplicate COMPILED-DEBUG-FUN structures.
301 (defvar *compiled-debug-funs* (make-hash-table :test 'eq))
302
303 ;;; Make a COMPILED-DEBUG-FUN for a SB!C::COMPILER-DEBUG-FUN
304 ;;; and its component. This maps the latter to the former in
305 ;;; *COMPILED-DEBUG-FUNS*. If there already is a
306 ;;; COMPILED-DEBUG-FUN, then this returns it from
307 ;;; *COMPILED-DEBUG-FUNS*.
308 (defun make-compiled-debug-fun (compiler-debug-fun component)
309   (or (gethash compiler-debug-fun *compiled-debug-funs*)
310       (setf (gethash compiler-debug-fun *compiled-debug-funs*)
311             (%make-compiled-debug-fun compiler-debug-fun component))))
312
313 (defstruct (bogus-debug-fun
314             (:include debug-fun)
315             (:constructor make-bogus-debug-fun
316                           (%name &aux
317                                  (%lambda-list nil)
318                                  (%debug-vars nil)
319                                  (blocks nil)
320                                  (%function nil)))
321             (:copier nil))
322   %name)
323
324 (defvar *ir1-lambda-debug-fun* (make-hash-table :test 'eq))
325 \f
326 ;;;; DEBUG-BLOCKs
327
328 ;;; These exist for caching data stored in packed binary form in compiler
329 ;;; DEBUG-BLOCKs.
330 (defstruct (debug-block (:constructor nil)
331                         (:copier nil))
332   ;; Code-locations where execution continues after this block.
333   (successors nil :type list)
334   ;; This indicates whether the block is a special glob of code shared
335   ;; by various functions and tucked away elsewhere in a component.
336   ;; This kind of block has no start code-location. This slot is in
337   ;; all debug-blocks since it is an exported interface.
338   (elsewhere-p nil :type boolean))
339 (def!method print-object ((obj debug-block) str)
340   (print-unreadable-object (obj str :type t)
341     (prin1 (debug-block-fun-name obj) str)))
342
343 #!+sb-doc
344 (setf (fdocumentation 'debug-block-successors 'function)
345   "Return the list of possible code-locations where execution may continue
346    when the basic-block represented by debug-block completes its execution.")
347
348 #!+sb-doc
349 (setf (fdocumentation 'debug-block-elsewhere-p 'function)
350   "Return whether debug-block represents elsewhere code.")
351
352 (defstruct (compiled-debug-block (:include debug-block)
353                                  (:constructor
354                                   make-compiled-debug-block
355                                   (code-locations successors elsewhere-p))
356                                  (:copier nil))
357   ;; code-location information for the block
358   (code-locations nil :type simple-vector))
359
360 (defvar *ir1-block-debug-block* (make-hash-table :test 'eq))
361 \f
362 ;;;; breakpoints
363
364 ;;; This is an internal structure that manages information about a
365 ;;; breakpoint locations. See *COMPONENT-BREAKPOINT-OFFSETS*.
366 (defstruct (breakpoint-data (:constructor make-breakpoint-data
367                                           (component offset))
368                             (:copier nil))
369   ;; This is the component in which the breakpoint lies.
370   component
371   ;; This is the byte offset into the component.
372   (offset nil :type index)
373   ;; The original instruction replaced by the breakpoint.
374   (instruction nil :type (or null sb!vm::word))
375   ;; A list of user breakpoints at this location.
376   (breakpoints nil :type list))
377 (def!method print-object ((obj breakpoint-data) str)
378   (print-unreadable-object (obj str :type t)
379     (format str "~S at ~S"
380             (debug-fun-name
381              (debug-fun-from-pc (breakpoint-data-component obj)
382                                 (breakpoint-data-offset obj)))
383             (breakpoint-data-offset obj))))
384
385 (defstruct (breakpoint (:constructor %make-breakpoint
386                                      (hook-fun what kind %info))
387                        (:copier nil))
388   ;; This is the function invoked when execution encounters the
389   ;; breakpoint. It takes a frame, the breakpoint, and optionally a
390   ;; list of values. Values are supplied for :FUN-END breakpoints as
391   ;; values to return for the function containing the breakpoint.
392   ;; :FUN-END breakpoint hook functions also take a cookie argument.
393   ;; See the COOKIE-FUN slot.
394   (hook-fun (required-arg) :type function)
395   ;; CODE-LOCATION or DEBUG-FUN
396   (what nil :type (or code-location debug-fun))
397   ;; :CODE-LOCATION, :FUN-START, or :FUN-END for that kind
398   ;; of breakpoint. :UNKNOWN-RETURN-PARTNER if this is the partner of
399   ;; a :code-location breakpoint at an :UNKNOWN-RETURN code-location.
400   (kind nil :type (member :code-location :fun-start :fun-end
401                           :unknown-return-partner))
402   ;; Status helps the user and the implementation.
403   (status :inactive :type (member :active :inactive :deleted))
404   ;; This is a backpointer to a breakpoint-data.
405   (internal-data nil :type (or null breakpoint-data))
406   ;; With code-locations whose type is :UNKNOWN-RETURN, there are
407   ;; really two breakpoints: one at the multiple-value entry point,
408   ;; and one at the single-value entry point. This slot holds the
409   ;; breakpoint for the other one, or NIL if this isn't at an
410   ;; :UNKNOWN-RETURN code location.
411   (unknown-return-partner nil :type (or null breakpoint))
412   ;; :FUN-END breakpoints use a breakpoint at the :FUN-START
413   ;; to establish the end breakpoint upon function entry. We do this
414   ;; by frobbing the LRA to jump to a special piece of code that
415   ;; breaks and provides the return values for the returnee. This slot
416   ;; points to the start breakpoint, so we can activate, deactivate,
417   ;; and delete it.
418   (start-helper nil :type (or null breakpoint))
419   ;; This is a hook users supply to get a dynamically unique cookie
420   ;; for identifying :FUN-END breakpoint executions. That is, if
421   ;; there is one :FUN-END breakpoint, but there may be multiple
422   ;; pending calls of its function on the stack. This function takes
423   ;; the cookie, and the hook function takes the cookie too.
424   (cookie-fun nil :type (or null function))
425   ;; This slot users can set with whatever information they find useful.
426   %info)
427 (def!method print-object ((obj breakpoint) str)
428   (let ((what (breakpoint-what obj)))
429     (print-unreadable-object (obj str :type t)
430       (format str
431               "~S~:[~;~:*~S~]"
432               (etypecase what
433                 (code-location what)
434                 (debug-fun (debug-fun-name what)))
435               (etypecase what
436                 (code-location nil)
437                 (debug-fun (breakpoint-kind obj)))))))
438 \f
439 ;;;; CODE-LOCATIONs
440
441 (defstruct (code-location (:constructor nil)
442                           (:copier nil))
443   ;; the DEBUG-FUN containing this CODE-LOCATION
444   (debug-fun nil :type debug-fun)
445   ;; This is initially :UNSURE. Upon first trying to access an
446   ;; :UNPARSED slot, if the data is unavailable, then this becomes T,
447   ;; and the code-location is unknown. If the data is available, this
448   ;; becomes NIL, a known location. We can't use a separate type
449   ;; code-location for this since we must return code-locations before
450   ;; we can tell whether they're known or unknown. For example, when
451   ;; parsing the stack, we don't want to unpack all the variables and
452   ;; blocks just to make frames.
453   (%unknown-p :unsure :type (member t nil :unsure))
454   ;; the DEBUG-BLOCK containing CODE-LOCATION. XXX Possibly toss this
455   ;; out and just find it in the blocks cache in DEBUG-FUN.
456   (%debug-block :unparsed :type (or debug-block (member :unparsed)))
457   ;; This is the number of forms processed by the compiler or loader
458   ;; before the top level form containing this code-location.
459   (%tlf-offset :unparsed :type (or index (member :unparsed)))
460   ;; This is the depth-first number of the node that begins
461   ;; code-location within its top level form.
462   (%form-number :unparsed :type (or index (member :unparsed))))
463 (def!method print-object ((obj code-location) str)
464   (print-unreadable-object (obj str :type t)
465     (prin1 (debug-fun-name (code-location-debug-fun obj))
466            str)))
467
468 (defstruct (compiled-code-location
469              (:include code-location)
470              (:constructor make-known-code-location
471                            (pc debug-fun %tlf-offset %form-number
472                                %live-set kind step-info &aux (%unknown-p nil)))
473              (:constructor make-compiled-code-location (pc debug-fun))
474              (:copier nil))
475   ;; an index into DEBUG-FUN's component slot
476   (pc nil :type index)
477   ;; a bit-vector indexed by a variable's position in
478   ;; DEBUG-FUN-DEBUG-VARS indicating whether the variable has a
479   ;; valid value at this code-location. (unexported).
480   (%live-set :unparsed :type (or simple-bit-vector (member :unparsed)))
481   ;; (unexported) To see SB!C::LOCATION-KIND, do
482   ;; (SB!KERNEL:TYPE-EXPAND 'SB!C::LOCATION-KIND).
483   (kind :unparsed :type (or (member :unparsed) sb!c::location-kind))
484   (step-info :unparsed :type (or (member :unparsed :foo) simple-string)))
485 \f
486 ;;;; DEBUG-SOURCEs
487
488 ;;; Return the number of top level forms processed by the compiler
489 ;;; before compiling this source. If this source is uncompiled, this
490 ;;; is zero. This may be zero even if the source is compiled since the
491 ;;; first form in the first file compiled in one compilation, for
492 ;;; example, must have a root number of zero -- the compiler saw no
493 ;;; other top level forms before it.
494 (defun debug-source-root-number (debug-source)
495   (sb!c::debug-source-source-root debug-source))
496 \f
497 ;;;; frames
498
499 ;;; This is used in FIND-ESCAPED-FRAME and with the bogus components
500 ;;; and LRAs used for :FUN-END breakpoints. When a component's
501 ;;; debug-info slot is :BOGUS-LRA, then the REAL-LRA-SLOT contains the
502 ;;; real component to continue executing, as opposed to the bogus
503 ;;; component which appeared in some frame's LRA location.
504 (defconstant real-lra-slot sb!vm:code-constants-offset)
505
506 ;;; These are magically converted by the compiler.
507 (defun current-sp () (current-sp))
508 (defun current-fp () (current-fp))
509 (defun stack-ref (s n) (stack-ref s n))
510 (defun %set-stack-ref (s n value) (%set-stack-ref s n value))
511 (defun fun-code-header (fun) (fun-code-header fun))
512 (defun lra-code-header (lra) (lra-code-header lra))
513 (defun make-lisp-obj (value) (make-lisp-obj value))
514 (defun get-lisp-obj-address (thing) (get-lisp-obj-address thing))
515 (defun fun-word-offset (fun) (fun-word-offset fun))
516
517 #!-sb-fluid (declaim (inline control-stack-pointer-valid-p))
518 (defun control-stack-pointer-valid-p (x)
519   (declare (type system-area-pointer x))
520   (let* (#!-stack-grows-downward-not-upward
521          (control-stack-start
522           (descriptor-sap *control-stack-start*))
523          #!+stack-grows-downward-not-upward
524          (control-stack-end
525           (descriptor-sap *control-stack-end*)))
526     #!-stack-grows-downward-not-upward
527     (and (sap< x (current-sp))
528          (sap<= control-stack-start x)
529          (zerop (logand (sap-int x) sb!vm:fixnum-tag-mask)))
530     #!+stack-grows-downward-not-upward
531     (and (sap>= x (current-sp))
532          (sap> control-stack-end x)
533          (zerop (logand (sap-int x) sb!vm:fixnum-tag-mask)))))
534
535 (declaim (inline component-ptr-from-pc))
536 (sb!alien:define-alien-routine component-ptr-from-pc (system-area-pointer)
537   (pc system-area-pointer))
538
539 (declaim (inline component-from-component-ptr))
540 (defun component-from-component-ptr (component-ptr)
541   (declare (type system-area-pointer component-ptr))
542   (make-lisp-obj (logior (sap-int component-ptr)
543                          sb!vm:other-pointer-lowtag)))
544
545 ;;;; (OR X86 X86-64) support
546
547 (defun compute-lra-data-from-pc (pc)
548   (declare (type system-area-pointer pc))
549   (let ((component-ptr (component-ptr-from-pc pc)))
550     (unless (sap= component-ptr (int-sap #x0))
551        (let* ((code (component-from-component-ptr component-ptr))
552               (code-header-len (* (get-header-data code) sb!vm:n-word-bytes))
553               (pc-offset (- (sap-int pc)
554                             (- (get-lisp-obj-address code)
555                                sb!vm:other-pointer-lowtag)
556                             code-header-len)))
557 ;        (format t "c-lra-fpc ~A ~A ~A~%" pc code pc-offset)
558          (values pc-offset code)))))
559
560 #!+(or x86 x86-64)
561 (progn
562
563 (defconstant sb!vm::nargs-offset #.sb!vm::ecx-offset)
564
565 ;;; Check for a valid return address - it could be any valid C/Lisp
566 ;;; address.
567 ;;;
568 ;;; XXX Could be a little smarter.
569 #!-sb-fluid (declaim (inline ra-pointer-valid-p))
570 (defun ra-pointer-valid-p (ra)
571   (declare (type system-area-pointer ra))
572   (and
573    ;; not the first page (which is unmapped)
574    ;;
575    ;; FIXME: Where is this documented? Is it really true of every CPU
576    ;; architecture? Is it even necessarily true in current SBCL?
577    (>= (sap-int ra) 4096)
578    ;; not a Lisp stack pointer
579    (not (control-stack-pointer-valid-p ra))))
580
581 ;;; Try to find a valid previous stack. This is complex on the x86 as
582 ;;; it can jump between C and Lisp frames. To help find a valid frame
583 ;;; it searches backwards.
584 ;;;
585 ;;; XXX Should probably check whether it has reached the bottom of the
586 ;;; stack.
587 ;;;
588 ;;; XXX Should handle interrupted frames, both Lisp and C. At present
589 ;;; it manages to find a fp trail, see linux hack below.
590 (declaim (maybe-inline x86-call-context))
591 (defun x86-call-context (fp)
592   (declare (type system-area-pointer fp))
593   (labels ((fail ()
594              (values nil
595                      (int-sap 0)
596                      (int-sap 0)))
597            (handle (fp)
598              (cond
599                ((not (control-stack-pointer-valid-p fp))
600                 (fail))
601                (t
602                 ;; Check the two possible frame pointers.
603                 (let ((lisp-ocfp (sap-ref-sap fp (- (* (1+ ocfp-save-offset)
604                                                        sb!vm::n-word-bytes))))
605                       (lisp-ra (sap-ref-sap fp (- (* (1+ return-pc-save-offset)
606                                                      sb!vm::n-word-bytes))))
607                       (c-ocfp (sap-ref-sap fp (* 0 sb!vm:n-word-bytes)))
608                       (c-ra (sap-ref-sap fp (* 1 sb!vm:n-word-bytes))))
609                   (cond ((and (sap> lisp-ocfp fp)
610                               (control-stack-pointer-valid-p lisp-ocfp)
611                               (ra-pointer-valid-p lisp-ra)
612                               (sap> c-ocfp fp)
613                               (control-stack-pointer-valid-p c-ocfp)
614                               (ra-pointer-valid-p c-ra))
615                          ;; Look forward another step to check their validity.
616                          (let ((lisp-ok (handle lisp-ocfp))
617                                (c-ok (handle c-ocfp)))
618                            (cond ((and lisp-ok c-ok)
619                                   ;; Both still seem valid - choose the lisp frame.
620                                   #!+freebsd
621                                   (if (sap> lisp-ocfp c-ocfp)
622                                       (values t lisp-ra lisp-ocfp)
623                                       (values t c-ra c-ocfp))
624                                   #!-freebsd
625                                   (values t lisp-ra lisp-ocfp))
626                                  (lisp-ok
627                                   ;; The lisp convention is looking good.
628                                   (values t lisp-ra lisp-ocfp))
629                                  (c-ok
630                                   ;; The C convention is looking good.
631                                   (values t c-ra c-ocfp))
632                                  (t
633                                   ;; Neither seems right?
634                                   (fail)))))
635                         ((and (sap> lisp-ocfp fp)
636                               (control-stack-pointer-valid-p lisp-ocfp)
637                               (ra-pointer-valid-p lisp-ra))
638                          ;; The lisp convention is looking good.
639                          (values t lisp-ra lisp-ocfp))
640                         ((and (sap> c-ocfp fp)
641                               (control-stack-pointer-valid-p c-ocfp)
642                               #!-linux (ra-pointer-valid-p c-ra))
643                          ;; The C convention is looking good.
644                          (values t c-ra c-ocfp))
645                         (t
646                          (fail))))))))
647     (handle fp)))
648
649 ) ; #+x86 PROGN
650 \f
651 ;;; Convert the descriptor into a SAP. The bits all stay the same, we just
652 ;;; change our notion of what we think they are.
653 #!-sb-fluid (declaim (inline descriptor-sap))
654 (defun descriptor-sap (x)
655   (int-sap (get-lisp-obj-address x)))
656
657 (defun nth-interrupt-context (n)
658   (declare (type (unsigned-byte 32) n)
659            (optimize (speed 3) (safety 0)))
660   (sb!alien:sap-alien (sb!vm::current-thread-offset-sap
661                        (+ sb!vm::thread-interrupt-contexts-offset n))
662                       (* os-context-t)))
663
664 ;;; Return the top frame of the control stack as it was before calling
665 ;;; this function.
666 (defun top-frame ()
667   (/noshow0 "entering TOP-FRAME")
668   ;; check to see if we can get the context by calling
669   ;; nth-interrupt-context, otherwise use the (%caller-frame-and-pc
670   ;; vop).
671   (let ((context (nth-interrupt-context 0)))
672     (if context
673         (compute-calling-frame
674          (int-sap (sb!vm:context-register context
675                                           sb!vm::cfp-offset))
676          (context-pc context) nil)
677         (multiple-value-bind (fp pc) (%caller-frame-and-pc)
678           (compute-calling-frame (descriptor-sap fp) pc nil)))))
679
680 ;;; Flush all of the frames above FRAME, and renumber all the frames
681 ;;; below FRAME.
682 (defun flush-frames-above (frame)
683   (setf (frame-up frame) nil)
684   (do ((number 0 (1+ number))
685        (frame frame (frame-%down frame)))
686       ((not (frame-p frame)))
687     (setf (frame-number frame) number)))
688
689 ;;; Return the frame immediately below FRAME on the stack; or when
690 ;;; FRAME is the bottom of the stack, return NIL.
691 (defun frame-down (frame)
692   (/noshow0 "entering FRAME-DOWN")
693   ;; We have to access the old-fp and return-pc out of frame and pass
694   ;; them to COMPUTE-CALLING-FRAME.
695   (let ((down (frame-%down frame)))
696     (if (eq down :unparsed)
697         (let ((debug-fun (frame-debug-fun frame)))
698           (/noshow0 "in DOWN :UNPARSED case")
699           (setf (frame-%down frame)
700                 (etypecase debug-fun
701                   (compiled-debug-fun
702                    (let ((c-d-f (compiled-debug-fun-compiler-debug-fun
703                                  debug-fun)))
704                      (compute-calling-frame
705                       (descriptor-sap
706                        (get-context-value
707                         frame ocfp-save-offset
708                         (sb!c::compiled-debug-fun-old-fp c-d-f)))
709                       (get-context-value
710                        frame lra-save-offset
711                        (sb!c::compiled-debug-fun-return-pc c-d-f))
712                       frame)))
713                   (bogus-debug-fun
714                    (let ((fp (frame-pointer frame)))
715                      (when (control-stack-pointer-valid-p fp)
716                        #!+(or x86 x86-64)
717                        (multiple-value-bind (ok ra ofp) (x86-call-context fp)
718                          (and ok
719                               (compute-calling-frame ofp ra frame)))
720                        #!-(or x86 x86-64)
721                        (compute-calling-frame
722                         #!-alpha
723                         (sap-ref-sap fp (* ocfp-save-offset
724                                            sb!vm:n-word-bytes))
725                         #!+alpha
726                         (int-sap
727                          (sap-ref-32 fp (* ocfp-save-offset
728                                            sb!vm:n-word-bytes)))
729
730                         (stack-ref fp lra-save-offset)
731
732                         frame)))))))
733         down)))
734
735 ;;; Get the old FP or return PC out of FRAME. STACK-SLOT is the
736 ;;; standard save location offset on the stack. LOC is the saved
737 ;;; SC-OFFSET describing the main location.
738 (defun get-context-value (frame stack-slot loc)
739   (declare (type compiled-frame frame) (type unsigned-byte stack-slot)
740            (type sb!c:sc-offset loc))
741   (let ((pointer (frame-pointer frame))
742         (escaped (compiled-frame-escaped frame)))
743     (if escaped
744         (sub-access-debug-var-slot pointer loc escaped)
745         #!-(or x86 x86-64)
746         (stack-ref pointer stack-slot)
747         #!+(or x86 x86-64)
748         (ecase stack-slot
749           (#.ocfp-save-offset
750            (stack-ref pointer stack-slot))
751           (#.lra-save-offset
752            (sap-ref-sap pointer (- (* (1+ stack-slot)
753                                       sb!vm::n-word-bytes))))))))
754
755 (defun (setf get-context-value) (value frame stack-slot loc)
756   (declare (type compiled-frame frame) (type unsigned-byte stack-slot)
757            (type sb!c:sc-offset loc))
758   (let ((pointer (frame-pointer frame))
759         (escaped (compiled-frame-escaped frame)))
760     (if escaped
761         (sub-set-debug-var-slot pointer loc value escaped)
762         #!-(or x86 x86-64)
763         (setf (stack-ref pointer stack-slot) value)
764         #!+(or x86 x86-64)
765         (ecase stack-slot
766           (#.ocfp-save-offset
767            (setf (stack-ref pointer stack-slot) value))
768           (#.lra-save-offset
769            (setf (sap-ref-sap pointer (- (* (1+ stack-slot)
770                                             sb!vm::n-word-bytes))) value))))))
771
772 (defun foreign-function-backtrace-name (sap)
773   (let ((name (sap-foreign-symbol sap)))
774     (if name
775         (format nil "foreign function: ~A" name)
776         (format nil "foreign function: #x~X" (sap-int sap)))))
777
778 ;;; This returns a frame for the one existing in time immediately
779 ;;; prior to the frame referenced by current-fp. This is current-fp's
780 ;;; caller or the next frame down the control stack. If there is no
781 ;;; down frame, this returns NIL for the bottom of the stack. UP-FRAME
782 ;;; is the up link for the resulting frame object, and it is null when
783 ;;; we call this to get the top of the stack.
784 ;;;
785 ;;; The current frame contains the pointer to the temporally previous
786 ;;; frame we want, and the current frame contains the pc at which we
787 ;;; will continue executing upon returning to that previous frame.
788 ;;;
789 ;;; Note: Sometimes LRA is actually a fixnum. This happens when lisp
790 ;;; calls into C. In this case, the code object is stored on the stack
791 ;;; after the LRA, and the LRA is the word offset.
792 #!-(or x86 x86-64)
793 (defun compute-calling-frame (caller lra up-frame)
794   (declare (type system-area-pointer caller))
795   (when (control-stack-pointer-valid-p caller)
796     (multiple-value-bind (code pc-offset escaped)
797         (if lra
798             (multiple-value-bind (word-offset code)
799                 (if (fixnump lra)
800                     (let ((fp (frame-pointer up-frame)))
801                       (values lra
802                               (stack-ref fp (1+ lra-save-offset))))
803                     (values (get-header-data lra)
804                             (lra-code-header lra)))
805               (if code
806                   (values code
807                           (* (1+ (- word-offset (get-header-data code)))
808                              sb!vm:n-word-bytes)
809                           nil)
810                   (values :foreign-function
811                           0
812                           nil)))
813             (find-escaped-frame caller))
814       (if (and (code-component-p code)
815                (eq (%code-debug-info code) :bogus-lra))
816           (let ((real-lra (code-header-ref code real-lra-slot)))
817             (compute-calling-frame caller real-lra up-frame))
818           (let ((d-fun (case code
819                          (:undefined-function
820                           (make-bogus-debug-fun
821                            "undefined function"))
822                          (:foreign-function
823                           (make-bogus-debug-fun
824                            (foreign-function-backtrace-name
825                             (int-sap (get-lisp-obj-address lra)))))
826                          ((nil)
827                           (make-bogus-debug-fun
828                            "bogus stack frame"))
829                          (t
830                           (debug-fun-from-pc code pc-offset)))))
831             (make-compiled-frame caller up-frame d-fun
832                                  (code-location-from-pc d-fun pc-offset
833                                                         escaped)
834                                  (if up-frame (1+ (frame-number up-frame)) 0)
835                                  escaped))))))
836
837 #!+(or x86 x86-64)
838 (defun compute-calling-frame (caller ra up-frame)
839   (declare (type system-area-pointer caller ra))
840   (/noshow0 "entering COMPUTE-CALLING-FRAME")
841   (when (control-stack-pointer-valid-p caller)
842     (/noshow0 "in WHEN")
843     ;; First check for an escaped frame.
844     (multiple-value-bind (code pc-offset escaped) (find-escaped-frame caller)
845       (/noshow0 "at COND")
846       (cond (code
847              ;; If it's escaped it may be a function end breakpoint trap.
848              (when (and (code-component-p code)
849                         (eq (%code-debug-info code) :bogus-lra))
850                ;; If :bogus-lra grab the real lra.
851                (setq pc-offset (code-header-ref
852                                 code (1+ real-lra-slot)))
853                (setq code (code-header-ref code real-lra-slot))
854                (aver code)))
855             ((not escaped)
856              (multiple-value-setq (pc-offset code)
857                (compute-lra-data-from-pc ra))
858              (unless code
859                (setf code :foreign-function
860                      pc-offset 0))))
861       (let ((d-fun (case code
862                      (:undefined-function
863                       (make-bogus-debug-fun
864                        "undefined function"))
865                      (:foreign-function
866                       (make-bogus-debug-fun
867                        (foreign-function-backtrace-name ra)))
868                      ((nil)
869                       (make-bogus-debug-fun
870                        "bogus stack frame"))
871                      (t
872                       (debug-fun-from-pc code pc-offset)))))
873         (/noshow0 "returning MAKE-COMPILED-FRAME from COMPUTE-CALLING-FRAME")
874         (make-compiled-frame caller up-frame d-fun
875                              (code-location-from-pc d-fun pc-offset
876                                                     escaped)
877                              (if up-frame (1+ (frame-number up-frame)) 0)
878                              escaped)))))
879
880 #!+(or x86 x86-64)
881 (defun find-escaped-frame (frame-pointer)
882   (declare (type system-area-pointer frame-pointer))
883   (/noshow0 "entering FIND-ESCAPED-FRAME")
884   (dotimes (index *free-interrupt-context-index* (values nil 0 nil))
885       (/noshow0 "at head of WITH-ALIEN")
886     (let ((context (nth-interrupt-context index)))
887         (/noshow0 "got CONTEXT")
888         (when (= (sap-int frame-pointer)
889                  (sb!vm:context-register context sb!vm::cfp-offset))
890           (without-gcing
891            (/noshow0 "in WITHOUT-GCING")
892            (let* ((component-ptr (component-ptr-from-pc
893                                   (sb!vm:context-pc context)))
894                   (code (unless (sap= component-ptr (int-sap #x0))
895                           (component-from-component-ptr component-ptr))))
896              (/noshow0 "got CODE")
897              (when (null code)
898                (return (values code 0 context)))
899              (let* ((code-header-len (* (get-header-data code)
900                                         sb!vm:n-word-bytes))
901                     (pc-offset
902                      (- (sap-int (sb!vm:context-pc context))
903                         (- (get-lisp-obj-address code)
904                            sb!vm:other-pointer-lowtag)
905                         code-header-len)))
906                (/noshow "got PC-OFFSET")
907                (unless (<= 0 pc-offset
908                            (* (code-header-ref code sb!vm:code-code-size-slot)
909                               sb!vm:n-word-bytes))
910                  ;; We were in an assembly routine. Therefore, use the
911                  ;; LRA as the pc.
912                  ;;
913                  ;; FIXME: Should this be WARN or ERROR or what?
914                  (format t "** pc-offset ~S not in code obj ~S?~%"
915                          pc-offset code))
916                (/noshow0 "returning from FIND-ESCAPED-FRAME")
917                (return
918                (values code pc-offset context)))))))))
919
920 #!-(or x86 x86-64)
921 (defun find-escaped-frame (frame-pointer)
922   (declare (type system-area-pointer frame-pointer))
923   (dotimes (index *free-interrupt-context-index* (values nil 0 nil))
924     (let ((scp (nth-interrupt-context index)))
925       (when (= (sap-int frame-pointer)
926                (sb!vm:context-register scp sb!vm::cfp-offset))
927         (without-gcing
928          (let ((code (code-object-from-bits
929                       (sb!vm:context-register scp sb!vm::code-offset))))
930            (when (symbolp code)
931              (return (values code 0 scp)))
932            (let* ((code-header-len (* (get-header-data code)
933                                       sb!vm:n-word-bytes))
934                   (pc-offset
935                    (- (sap-int (sb!vm:context-pc scp))
936                       (- (get-lisp-obj-address code)
937                          sb!vm:other-pointer-lowtag)
938                       code-header-len)))
939              (let ((code-size (* (code-header-ref code
940                                                   sb!vm:code-code-size-slot)
941                                  sb!vm:n-word-bytes)))
942                (unless (<= 0 pc-offset code-size)
943                  ;; We were in an assembly routine.
944                  (multiple-value-bind (new-pc-offset computed-return)
945                      (find-pc-from-assembly-fun code scp)
946                    (setf pc-offset new-pc-offset)
947                    (unless (<= 0 pc-offset code-size)
948                      (cerror
949                       "Set PC-OFFSET to zero and continue backtrace."
950                       'bug
951                       :format-control
952                       "~@<PC-OFFSET (~D) not in code object. Frame details:~
953                        ~2I~:@_PC: #X~X~:@_CODE: ~S~:@_CODE FUN: ~S~:@_LRA: ~
954                        #X~X~:@_COMPUTED RETURN: #X~X.~:>"
955                       :format-arguments
956                       (list pc-offset
957                             (sap-int (sb!vm:context-pc scp))
958                             code
959                             (%code-entry-points code)
960                             (sb!vm:context-register scp sb!vm::lra-offset)
961                             computed-return))
962                      ;; We failed to pinpoint where PC is, but set
963                      ;; pc-offset to 0 to keep the backtrace from
964                      ;; exploding.
965                      (setf pc-offset 0)))))
966              (return
967                (if (eq (%code-debug-info code) :bogus-lra)
968                    (let ((real-lra (code-header-ref code
969                                                     real-lra-slot)))
970                      (values (lra-code-header real-lra)
971                              (get-header-data real-lra)
972                              nil))
973                    (values code pc-offset scp))))))))))
974
975 #!-(or x86 x86-64)
976 (defun find-pc-from-assembly-fun (code scp)
977   "Finds the PC for the return from an assembly routine properly.
978 For some architectures (such as PPC) this will not be the $LRA
979 register."
980   (let ((return-machine-address (sb!vm::return-machine-address scp))
981         (code-header-len (* (get-header-data code) sb!vm:n-word-bytes)))
982     (values (- return-machine-address
983                (- (get-lisp-obj-address code)
984                   sb!vm:other-pointer-lowtag)
985                code-header-len)
986             return-machine-address)))
987
988 ;;; Find the code object corresponding to the object represented by
989 ;;; bits and return it. We assume bogus functions correspond to the
990 ;;; undefined-function.
991 #!-(or x86 x86-64)
992 (defun code-object-from-bits (bits)
993   (declare (type (unsigned-byte 32) bits))
994   (let ((object (make-lisp-obj bits)))
995     (if (functionp object)
996         (or (fun-code-header object)
997             :undefined-function)
998         (let ((lowtag (lowtag-of object)))
999           (when (= lowtag sb!vm:other-pointer-lowtag)
1000             (let ((widetag (widetag-of object)))
1001               (cond ((= widetag sb!vm:code-header-widetag)
1002                      object)
1003                     ((= widetag sb!vm:return-pc-header-widetag)
1004                      (lra-code-header object))
1005                     (t
1006                      nil))))))))
1007 \f
1008 ;;;; frame utilities
1009
1010 ;;; This returns a COMPILED-DEBUG-FUN for COMPONENT and PC. We fetch the
1011 ;;; SB!C::DEBUG-INFO and run down its FUN-MAP to get a
1012 ;;; SB!C::COMPILED-DEBUG-FUN from the PC. The result only needs to
1013 ;;; reference the COMPONENT, for function constants, and the
1014 ;;; SB!C::COMPILED-DEBUG-FUN.
1015 (defun debug-fun-from-pc (component pc)
1016   (let ((info (%code-debug-info component)))
1017     (cond
1018       ((not info)
1019        ;; FIXME: It seems that most of these (at least on x86) are
1020        ;; actually assembler routines, and could be named by looking
1021        ;; at the sb-fasl:*assembler-routines*.
1022        (make-bogus-debug-fun "no debug information for frame"))
1023      ((eq info :bogus-lra)
1024       (make-bogus-debug-fun "function end breakpoint"))
1025      (t
1026       (let* ((fun-map (sb!c::compiled-debug-info-fun-map info))
1027              (len (length fun-map)))
1028         (declare (type simple-vector fun-map))
1029         (if (= len 1)
1030             (make-compiled-debug-fun (svref fun-map 0) component)
1031             (let ((i 1)
1032                   (elsewhere-p
1033                    (>= pc (sb!c::compiled-debug-fun-elsewhere-pc
1034                            (svref fun-map 0)))))
1035               (declare (type sb!int:index i))
1036               (loop
1037                 (when (or (= i len)
1038                           (< pc (if elsewhere-p
1039                                     (sb!c::compiled-debug-fun-elsewhere-pc
1040                                      (svref fun-map (1+ i)))
1041                                     (svref fun-map i))))
1042                   (return (make-compiled-debug-fun
1043                            (svref fun-map (1- i))
1044                            component)))
1045                 (incf i 2)))))))))
1046
1047 ;;; This returns a code-location for the COMPILED-DEBUG-FUN,
1048 ;;; DEBUG-FUN, and the pc into its code vector. If we stopped at a
1049 ;;; breakpoint, find the CODE-LOCATION for that breakpoint. Otherwise,
1050 ;;; make an :UNSURE code location, so it can be filled in when we
1051 ;;; figure out what is going on.
1052 (defun code-location-from-pc (debug-fun pc escaped)
1053   (or (and (compiled-debug-fun-p debug-fun)
1054            escaped
1055            (let ((data (breakpoint-data
1056                         (compiled-debug-fun-component debug-fun)
1057                         pc nil)))
1058              (when (and data (breakpoint-data-breakpoints data))
1059                (let ((what (breakpoint-what
1060                             (first (breakpoint-data-breakpoints data)))))
1061                  (when (compiled-code-location-p what)
1062                    what)))))
1063       (make-compiled-code-location pc debug-fun)))
1064
1065 ;;; Return an alist mapping catch tags to CODE-LOCATIONs. These are
1066 ;;; CODE-LOCATIONs at which execution would continue with frame as the
1067 ;;; top frame if someone threw to the corresponding tag.
1068 (defun frame-catches (frame)
1069   (let ((catch (descriptor-sap sb!vm:*current-catch-block*))
1070         (reversed-result nil)
1071         (fp (frame-pointer frame)))
1072     (loop until (zerop (sap-int catch))
1073           finally (return (nreverse reversed-result))
1074           do
1075           (when (sap= fp
1076                       #!-alpha
1077                       (sap-ref-sap catch
1078                                    (* sb!vm:catch-block-current-cont-slot
1079                                       sb!vm:n-word-bytes))
1080                       #!+alpha
1081                       (int-sap
1082                        (sap-ref-32 catch
1083                                    (* sb!vm:catch-block-current-cont-slot
1084                                       sb!vm:n-word-bytes))))
1085             (let* (#!-(or x86 x86-64)
1086                    (lra (stack-ref catch sb!vm:catch-block-entry-pc-slot))
1087                    #!+(or x86 x86-64)
1088                    (ra (sap-ref-sap
1089                         catch (* sb!vm:catch-block-entry-pc-slot
1090                                  sb!vm:n-word-bytes)))
1091                    #!-(or x86 x86-64)
1092                    (component
1093                     (stack-ref catch sb!vm:catch-block-current-code-slot))
1094                    #!+(or x86 x86-64)
1095                    (component (component-from-component-ptr
1096                                (component-ptr-from-pc ra)))
1097                    (offset
1098                     #!-(or x86 x86-64)
1099                     (* (- (1+ (get-header-data lra))
1100                           (get-header-data component))
1101                        sb!vm:n-word-bytes)
1102                     #!+(or x86 x86-64)
1103                     (- (sap-int ra)
1104                        (- (get-lisp-obj-address component)
1105                           sb!vm:other-pointer-lowtag)
1106                        (* (get-header-data component) sb!vm:n-word-bytes))))
1107               (push (cons #!-(or x86 x86-64)
1108                           (stack-ref catch sb!vm:catch-block-tag-slot)
1109                           #!+(or x86 x86-64)
1110                           (make-lisp-obj
1111                            (sap-ref-word catch (* sb!vm:catch-block-tag-slot
1112                                                   sb!vm:n-word-bytes)))
1113                           (make-compiled-code-location
1114                            offset (frame-debug-fun frame)))
1115                     reversed-result)))
1116           (setf catch
1117                 #!-alpha
1118                 (sap-ref-sap catch
1119                              (* sb!vm:catch-block-previous-catch-slot
1120                                 sb!vm:n-word-bytes))
1121                 #!+alpha
1122                 (int-sap
1123                  (sap-ref-32 catch
1124                              (* sb!vm:catch-block-previous-catch-slot
1125                                 sb!vm:n-word-bytes)))))))
1126
1127 ;;; Modify the value of the OLD-TAG catches in FRAME to NEW-TAG
1128 (defun replace-frame-catch-tag (frame old-tag new-tag)
1129   (let ((catch (descriptor-sap sb!vm:*current-catch-block*))
1130         (fp (frame-pointer frame)))
1131     (loop until (zerop (sap-int catch))
1132           do (when (sap= fp
1133                          #!-alpha
1134                          (sap-ref-sap catch
1135                                       (* sb!vm:catch-block-current-cont-slot
1136                                          sb!vm:n-word-bytes))
1137                          #!+alpha
1138                          (int-sap
1139                           (sap-ref-32 catch
1140                                       (* sb!vm:catch-block-current-cont-slot
1141                                          sb!vm:n-word-bytes))))
1142                (let ((current-tag
1143                       #!-(or x86 x86-64)
1144                       (stack-ref catch sb!vm:catch-block-tag-slot)
1145                       #!+(or x86 x86-64)
1146                       (make-lisp-obj
1147                        (sap-ref-word catch (* sb!vm:catch-block-tag-slot
1148                                               sb!vm:n-word-bytes)))))
1149                  (when (eq current-tag old-tag)
1150                    #!-(or x86 x86-64)
1151                    (setf (stack-ref catch sb!vm:catch-block-tag-slot) new-tag)
1152                    #!+(or x86 x86-64)
1153                    (setf (sap-ref-word catch (* sb!vm:catch-block-tag-slot
1154                                                 sb!vm:n-word-bytes))
1155                          (get-lisp-obj-address new-tag)))))
1156           do (setf catch
1157                    #!-alpha
1158                    (sap-ref-sap catch
1159                                 (* sb!vm:catch-block-previous-catch-slot
1160                                    sb!vm:n-word-bytes))
1161                    #!+alpha
1162                    (int-sap
1163                     (sap-ref-32 catch
1164                                 (* sb!vm:catch-block-previous-catch-slot
1165                                    sb!vm:n-word-bytes)))))))
1166
1167
1168 \f
1169 ;;;; operations on DEBUG-FUNs
1170
1171 ;;; Execute the forms in a context with BLOCK-VAR bound to each
1172 ;;; DEBUG-BLOCK in DEBUG-FUN successively. Result is an optional
1173 ;;; form to execute for return values, and DO-DEBUG-FUN-BLOCKS
1174 ;;; returns nil if there is no result form. This signals a
1175 ;;; NO-DEBUG-BLOCKS condition when the DEBUG-FUN lacks
1176 ;;; DEBUG-BLOCK information.
1177 (defmacro do-debug-fun-blocks ((block-var debug-fun &optional result)
1178                                &body body)
1179   (let ((blocks (gensym))
1180         (i (gensym)))
1181     `(let ((,blocks (debug-fun-debug-blocks ,debug-fun)))
1182        (declare (simple-vector ,blocks))
1183        (dotimes (,i (length ,blocks) ,result)
1184          (let ((,block-var (svref ,blocks ,i)))
1185            ,@body)))))
1186
1187 ;;; Execute body in a context with VAR bound to each DEBUG-VAR in
1188 ;;; DEBUG-FUN. This returns the value of executing result (defaults to
1189 ;;; nil). This may iterate over only some of DEBUG-FUN's variables or
1190 ;;; none depending on debug policy; for example, possibly the
1191 ;;; compilation only preserved argument information.
1192 (defmacro do-debug-fun-vars ((var debug-fun &optional result) &body body)
1193   (let ((vars (gensym))
1194         (i (gensym)))
1195     `(let ((,vars (debug-fun-debug-vars ,debug-fun)))
1196        (declare (type (or null simple-vector) ,vars))
1197        (if ,vars
1198            (dotimes (,i (length ,vars) ,result)
1199              (let ((,var (svref ,vars ,i)))
1200                ,@body))
1201            ,result))))
1202
1203 ;;; Return the object of type FUNCTION associated with the DEBUG-FUN,
1204 ;;; or NIL if the function is unavailable or is non-existent as a user
1205 ;;; callable function object.
1206 (defun debug-fun-fun (debug-fun)
1207   (let ((cached-value (debug-fun-%function debug-fun)))
1208     (if (eq cached-value :unparsed)
1209         (setf (debug-fun-%function debug-fun)
1210               (etypecase debug-fun
1211                 (compiled-debug-fun
1212                  (let ((component
1213                         (compiled-debug-fun-component debug-fun))
1214                        (start-pc
1215                         (sb!c::compiled-debug-fun-start-pc
1216                          (compiled-debug-fun-compiler-debug-fun debug-fun))))
1217                    (do ((entry (%code-entry-points component)
1218                                (%simple-fun-next entry)))
1219                        ((null entry) nil)
1220                      (when (= start-pc
1221                               (sb!c::compiled-debug-fun-start-pc
1222                                (compiled-debug-fun-compiler-debug-fun
1223                                 (fun-debug-fun entry))))
1224                        (return entry)))))
1225                 (bogus-debug-fun nil)))
1226         cached-value)))
1227
1228 ;;; Return the name of the function represented by DEBUG-FUN. This may
1229 ;;; be a string or a cons; do not assume it is a symbol.
1230 (defun debug-fun-name (debug-fun)
1231   (declare (type debug-fun debug-fun))
1232   (etypecase debug-fun
1233     (compiled-debug-fun
1234      (sb!c::compiled-debug-fun-name
1235       (compiled-debug-fun-compiler-debug-fun debug-fun)))
1236     (bogus-debug-fun
1237      (bogus-debug-fun-%name debug-fun))))
1238
1239 ;;; Return a DEBUG-FUN that represents debug information for FUN.
1240 (defun fun-debug-fun (fun)
1241   (declare (type function fun))
1242   (ecase (widetag-of fun)
1243     (#.sb!vm:closure-header-widetag
1244      (fun-debug-fun (%closure-fun fun)))
1245     (#.sb!vm:funcallable-instance-header-widetag
1246      (fun-debug-fun (funcallable-instance-fun fun)))
1247     (#.sb!vm:simple-fun-header-widetag
1248       (let* ((name (%simple-fun-name fun))
1249              (component (fun-code-header fun))
1250              (res (find-if
1251                    (lambda (x)
1252                      (and (sb!c::compiled-debug-fun-p x)
1253                           (eq (sb!c::compiled-debug-fun-name x) name)
1254                           (eq (sb!c::compiled-debug-fun-kind x) nil)))
1255                    (sb!c::compiled-debug-info-fun-map
1256                     (%code-debug-info component)))))
1257         (if res
1258             (make-compiled-debug-fun res component)
1259             ;; KLUDGE: comment from CMU CL:
1260             ;;   This used to be the non-interpreted branch, but
1261             ;;   William wrote it to return the debug-fun of fun's XEP
1262             ;;   instead of fun's debug-fun. The above code does this
1263             ;;   more correctly, but it doesn't get or eliminate all
1264             ;;   appropriate cases. It mostly works, and probably
1265             ;;   works for all named functions anyway.
1266             ;; -- WHN 20000120
1267             (debug-fun-from-pc component
1268                                (* (- (fun-word-offset fun)
1269                                      (get-header-data component))
1270                                   sb!vm:n-word-bytes)))))))
1271
1272 ;;; Return the kind of the function, which is one of :OPTIONAL,
1273 ;;; :EXTERNAL, :TOPLEVEL, :CLEANUP, or NIL.
1274 (defun debug-fun-kind (debug-fun)
1275   ;; FIXME: This "is one of" information should become part of the function
1276   ;; declamation, not just a doc string
1277   (etypecase debug-fun
1278     (compiled-debug-fun
1279      (sb!c::compiled-debug-fun-kind
1280       (compiled-debug-fun-compiler-debug-fun debug-fun)))
1281     (bogus-debug-fun
1282      nil)))
1283
1284 ;;; Is there any variable information for DEBUG-FUN?
1285 (defun debug-var-info-available (debug-fun)
1286   (not (not (debug-fun-debug-vars debug-fun))))
1287
1288 ;;; Return a list of DEBUG-VARs in DEBUG-FUN having the same name
1289 ;;; and package as SYMBOL. If SYMBOL is uninterned, then this returns
1290 ;;; a list of DEBUG-VARs without package names and with the same name
1291 ;;; as symbol. The result of this function is limited to the
1292 ;;; availability of variable information in DEBUG-FUN; for
1293 ;;; example, possibly DEBUG-FUN only knows about its arguments.
1294 (defun debug-fun-symbol-vars (debug-fun symbol)
1295   (let ((vars (ambiguous-debug-vars debug-fun (symbol-name symbol)))
1296         (package (and (symbol-package symbol)
1297                       (package-name (symbol-package symbol)))))
1298     (delete-if (if (stringp package)
1299                    (lambda (var)
1300                      (let ((p (debug-var-package-name var)))
1301                        (or (not (stringp p))
1302                            (string/= p package))))
1303                    (lambda (var)
1304                      (stringp (debug-var-package-name var))))
1305                vars)))
1306
1307 ;;; Return a list of DEBUG-VARs in DEBUG-FUN whose names contain
1308 ;;; NAME-PREFIX-STRING as an initial substring. The result of this
1309 ;;; function is limited to the availability of variable information in
1310 ;;; debug-fun; for example, possibly debug-fun only knows
1311 ;;; about its arguments.
1312 (defun ambiguous-debug-vars (debug-fun name-prefix-string)
1313   (declare (simple-string name-prefix-string))
1314   (let ((variables (debug-fun-debug-vars debug-fun)))
1315     (declare (type (or null simple-vector) variables))
1316     (if variables
1317         (let* ((len (length variables))
1318                (prefix-len (length name-prefix-string))
1319                (pos (find-var name-prefix-string variables len))
1320                (res nil))
1321           (when pos
1322             ;; Find names from pos to variable's len that contain prefix.
1323             (do ((i pos (1+ i)))
1324                 ((= i len))
1325               (let* ((var (svref variables i))
1326                      (name (debug-var-symbol-name var))
1327                      (name-len (length name)))
1328                 (declare (simple-string name))
1329                 (when (/= (or (string/= name-prefix-string name
1330                                         :end1 prefix-len :end2 name-len)
1331                               prefix-len)
1332                           prefix-len)
1333                   (return))
1334                 (push var res)))
1335             (setq res (nreverse res)))
1336           res))))
1337
1338 ;;; This returns a position in VARIABLES for one containing NAME as an
1339 ;;; initial substring. END is the length of VARIABLES if supplied.
1340 (defun find-var (name variables &optional end)
1341   (declare (simple-vector variables)
1342            (simple-string name))
1343   (let ((name-len (length name)))
1344     (position name variables
1345               :test (lambda (x y)
1346                       (let* ((y (debug-var-symbol-name y))
1347                              (y-len (length y)))
1348                         (declare (simple-string y))
1349                         (and (>= y-len name-len)
1350                              (string= x y :end1 name-len :end2 name-len))))
1351               :end (or end (length variables)))))
1352
1353 ;;; Return a list representing the lambda-list for DEBUG-FUN. The
1354 ;;; list has the following structure:
1355 ;;;   (required-var1 required-var2
1356 ;;;    ...
1357 ;;;    (:optional var3 suppliedp-var4)
1358 ;;;    (:optional var5)
1359 ;;;    ...
1360 ;;;    (:rest var6) (:rest var7)
1361 ;;;    ...
1362 ;;;    (:keyword keyword-symbol var8 suppliedp-var9)
1363 ;;;    (:keyword keyword-symbol var10)
1364 ;;;    ...
1365 ;;;   )
1366 ;;; Each VARi is a DEBUG-VAR; however it may be the symbol :DELETED if
1367 ;;; it is unreferenced in DEBUG-FUN. This signals a
1368 ;;; LAMBDA-LIST-UNAVAILABLE condition when there is no argument list
1369 ;;; information.
1370 (defun debug-fun-lambda-list (debug-fun)
1371   (etypecase debug-fun
1372     (compiled-debug-fun (compiled-debug-fun-lambda-list debug-fun))
1373     (bogus-debug-fun nil)))
1374
1375 ;;; Note: If this has to compute the lambda list, it caches it in DEBUG-FUN.
1376 (defun compiled-debug-fun-lambda-list (debug-fun)
1377   (let ((lambda-list (debug-fun-%lambda-list debug-fun)))
1378     (cond ((eq lambda-list :unparsed)
1379            (multiple-value-bind (args argsp)
1380                (parse-compiled-debug-fun-lambda-list debug-fun)
1381              (setf (debug-fun-%lambda-list debug-fun) args)
1382              (if argsp
1383                  args
1384                  (debug-signal 'lambda-list-unavailable
1385                                :debug-fun debug-fun))))
1386           (lambda-list)
1387           ((bogus-debug-fun-p debug-fun)
1388            nil)
1389           ((sb!c::compiled-debug-fun-arguments
1390             (compiled-debug-fun-compiler-debug-fun debug-fun))
1391            ;; If the packed information is there (whether empty or not) as
1392            ;; opposed to being nil, then returned our cached value (nil).
1393            nil)
1394           (t
1395            ;; Our cached value is nil, and the packed lambda-list information
1396            ;; is nil, so we don't have anything available.
1397            (debug-signal 'lambda-list-unavailable
1398                          :debug-fun debug-fun)))))
1399
1400 ;;; COMPILED-DEBUG-FUN-LAMBDA-LIST calls this when a
1401 ;;; COMPILED-DEBUG-FUN has no lambda list information cached. It
1402 ;;; returns the lambda list as the first value and whether there was
1403 ;;; any argument information as the second value. Therefore,
1404 ;;; (VALUES NIL T) means there were no arguments, but (VALUES NIL NIL)
1405 ;;; means there was no argument information.
1406 (defun parse-compiled-debug-fun-lambda-list (debug-fun)
1407   (let ((args (sb!c::compiled-debug-fun-arguments
1408                (compiled-debug-fun-compiler-debug-fun debug-fun))))
1409     (cond
1410      ((not args)
1411       (values nil nil))
1412      ((eq args :minimal)
1413       (values (coerce (debug-fun-debug-vars debug-fun) 'list)
1414               t))
1415      (t
1416       (let ((vars (debug-fun-debug-vars debug-fun))
1417             (i 0)
1418             (len (length args))
1419             (res nil)
1420             (optionalp nil))
1421         (declare (type (or null simple-vector) vars))
1422         (loop
1423           (when (>= i len) (return))
1424           (let ((ele (aref args i)))
1425             (cond
1426              ((symbolp ele)
1427               (case ele
1428                 (sb!c::deleted
1429                  ;; Deleted required arg at beginning of args array.
1430                  (push :deleted res))
1431                 (sb!c::optional-args
1432                  (setf optionalp t))
1433                 (sb!c::supplied-p
1434                  ;; SUPPLIED-P var immediately following keyword or
1435                  ;; optional. Stick the extra var in the result
1436                  ;; element representing the keyword or optional,
1437                  ;; which is the previous one.
1438                  ;;
1439                  ;; FIXME: NCONC used for side-effect: the effect is defined,
1440                  ;; but this is bad style no matter what.
1441                  (nconc (car res)
1442                         (list (compiled-debug-fun-lambda-list-var
1443                                args (incf i) vars))))
1444                 (sb!c::rest-arg
1445                  (push (list :rest
1446                              (compiled-debug-fun-lambda-list-var
1447                               args (incf i) vars))
1448                        res))
1449                 (sb!c::more-arg
1450                  ;; Just ignore the fact that the next two args are
1451                  ;; the &MORE arg context and count, and act like they
1452                  ;; are regular arguments.
1453                  nil)
1454                 (t
1455                  ;; &KEY arg
1456                  (push (list :keyword
1457                              ele
1458                              (compiled-debug-fun-lambda-list-var
1459                               args (incf i) vars))
1460                        res))))
1461              (optionalp
1462               ;; We saw an optional marker, so the following
1463               ;; non-symbols are indexes indicating optional
1464               ;; variables.
1465               (push (list :optional (svref vars ele)) res))
1466              (t
1467               ;; Required arg at beginning of args array.
1468               (push (svref vars ele) res))))
1469           (incf i))
1470         (values (nreverse res) t))))))
1471
1472 ;;; This is used in COMPILED-DEBUG-FUN-LAMBDA-LIST.
1473 (defun compiled-debug-fun-lambda-list-var (args i vars)
1474   (declare (type (simple-array * (*)) args)
1475            (simple-vector vars))
1476   (let ((ele (aref args i)))
1477     (cond ((not (symbolp ele)) (svref vars ele))
1478           ((eq ele 'sb!c::deleted) :deleted)
1479           (t (error "malformed arguments description")))))
1480
1481 (defun compiled-debug-fun-debug-info (debug-fun)
1482   (%code-debug-info (compiled-debug-fun-component debug-fun)))
1483 \f
1484 ;;;; unpacking variable and basic block data
1485
1486 (defvar *parsing-buffer*
1487   (make-array 20 :adjustable t :fill-pointer t))
1488 (defvar *other-parsing-buffer*
1489   (make-array 20 :adjustable t :fill-pointer t))
1490 ;;; PARSE-DEBUG-BLOCKS and PARSE-DEBUG-VARS
1491 ;;; use this to unpack binary encoded information. It returns the
1492 ;;; values returned by the last form in body.
1493 ;;;
1494 ;;; This binds buffer-var to *parsing-buffer*, makes sure it starts at
1495 ;;; element zero, and makes sure if we unwind, we nil out any set
1496 ;;; elements for GC purposes.
1497 ;;;
1498 ;;; This also binds other-var to *other-parsing-buffer* when it is
1499 ;;; supplied, making sure it starts at element zero and that we nil
1500 ;;; out any elements if we unwind.
1501 ;;;
1502 ;;; This defines the local macro RESULT that takes a buffer, copies
1503 ;;; its elements to a resulting simple-vector, nil's out elements, and
1504 ;;; restarts the buffer at element zero. RESULT returns the
1505 ;;; simple-vector.
1506 (eval-when (:compile-toplevel :execute)
1507 (sb!xc:defmacro with-parsing-buffer ((buffer-var &optional other-var)
1508                                      &body body)
1509   (let ((len (gensym))
1510         (res (gensym)))
1511     `(unwind-protect
1512          (let ((,buffer-var *parsing-buffer*)
1513                ,@(if other-var `((,other-var *other-parsing-buffer*))))
1514            (setf (fill-pointer ,buffer-var) 0)
1515            ,@(if other-var `((setf (fill-pointer ,other-var) 0)))
1516            (macrolet ((result (buf)
1517                         `(let* ((,',len (length ,buf))
1518                                 (,',res (make-array ,',len)))
1519                            (replace ,',res ,buf :end1 ,',len :end2 ,',len)
1520                            (fill ,buf nil :end ,',len)
1521                            (setf (fill-pointer ,buf) 0)
1522                            ,',res)))
1523              ,@body))
1524      (fill *parsing-buffer* nil)
1525      ,@(if other-var `((fill *other-parsing-buffer* nil))))))
1526 ) ; EVAL-WHEN
1527
1528 ;;; The argument is a debug internals structure. This returns the
1529 ;;; DEBUG-BLOCKs for DEBUG-FUN, regardless of whether we have unpacked
1530 ;;; them yet. It signals a NO-DEBUG-BLOCKS condition if it can't
1531 ;;; return the blocks.
1532 (defun debug-fun-debug-blocks (debug-fun)
1533   (let ((blocks (debug-fun-blocks debug-fun)))
1534     (cond ((eq blocks :unparsed)
1535            (setf (debug-fun-blocks debug-fun)
1536                  (parse-debug-blocks debug-fun))
1537            (unless (debug-fun-blocks debug-fun)
1538              (debug-signal 'no-debug-blocks
1539                            :debug-fun debug-fun))
1540            (debug-fun-blocks debug-fun))
1541           (blocks)
1542           (t
1543            (debug-signal 'no-debug-blocks
1544                          :debug-fun debug-fun)))))
1545
1546 ;;; Return a SIMPLE-VECTOR of DEBUG-BLOCKs or NIL. NIL indicates there
1547 ;;; was no basic block information.
1548 (defun parse-debug-blocks (debug-fun)
1549   (etypecase debug-fun
1550     (compiled-debug-fun
1551      (parse-compiled-debug-blocks debug-fun))
1552     (bogus-debug-fun
1553      (debug-signal 'no-debug-blocks :debug-fun debug-fun))))
1554
1555 ;;; This does some of the work of PARSE-DEBUG-BLOCKS.
1556 (defun parse-compiled-debug-blocks (debug-fun)
1557   (let* ((var-count (length (debug-fun-debug-vars debug-fun)))
1558          (compiler-debug-fun (compiled-debug-fun-compiler-debug-fun
1559                               debug-fun))
1560          (blocks (sb!c::compiled-debug-fun-blocks compiler-debug-fun))
1561          ;; KLUDGE: 8 is a hard-wired constant in the compiler for the
1562          ;; element size of the packed binary representation of the
1563          ;; blocks data.
1564          (live-set-len (ceiling var-count 8))
1565          (tlf-number (sb!c::compiled-debug-fun-tlf-number compiler-debug-fun)))
1566     (unless blocks
1567       (return-from parse-compiled-debug-blocks nil))
1568     (macrolet ((aref+ (a i) `(prog1 (aref ,a ,i) (incf ,i))))
1569       (with-parsing-buffer (blocks-buffer locations-buffer)
1570         (let ((i 0)
1571               (len (length blocks))
1572               (last-pc 0))
1573           (loop
1574             (when (>= i len) (return))
1575             (let ((succ-and-flags (aref+ blocks i))
1576                   (successors nil))
1577               (declare (type (unsigned-byte 8) succ-and-flags)
1578                        (list successors))
1579               (dotimes (k (ldb sb!c::compiled-debug-block-nsucc-byte
1580                                succ-and-flags))
1581                 (push (sb!c:read-var-integer blocks i) successors))
1582               (let* ((locations
1583                       (dotimes (k (sb!c:read-var-integer blocks i)
1584                                   (result locations-buffer))
1585                         (let ((kind (svref sb!c::*compiled-code-location-kinds*
1586                                            (aref+ blocks i)))
1587                               (pc (+ last-pc
1588                                      (sb!c:read-var-integer blocks i)))
1589                               (tlf-offset (or tlf-number
1590                                               (sb!c:read-var-integer blocks i)))
1591                               (form-number (sb!c:read-var-integer blocks i))
1592                               (live-set (sb!c:read-packed-bit-vector
1593                                          live-set-len blocks i))
1594                               (step-info (sb!c:read-var-string blocks i)))
1595                           (vector-push-extend (make-known-code-location
1596                                                pc debug-fun tlf-offset
1597                                                form-number live-set kind
1598                                                step-info)
1599                                               locations-buffer)
1600                           (setf last-pc pc))))
1601                      (block (make-compiled-debug-block
1602                              locations successors
1603                              (not (zerop (logand
1604                                           sb!c::compiled-debug-block-elsewhere-p
1605                                           succ-and-flags))))))
1606                 (vector-push-extend block blocks-buffer)
1607                 (dotimes (k (length locations))
1608                   (setf (code-location-%debug-block (svref locations k))
1609                         block))))))
1610         (let ((res (result blocks-buffer)))
1611           (declare (simple-vector res))
1612           (dotimes (i (length res))
1613             (let* ((block (svref res i))
1614                    (succs nil))
1615               (dolist (ele (debug-block-successors block))
1616                 (push (svref res ele) succs))
1617               (setf (debug-block-successors block) succs)))
1618           res)))))
1619
1620 ;;; The argument is a debug internals structure. This returns NIL if
1621 ;;; there is no variable information. It returns an empty
1622 ;;; simple-vector if there were no locals in the function. Otherwise
1623 ;;; it returns a SIMPLE-VECTOR of DEBUG-VARs.
1624 (defun debug-fun-debug-vars (debug-fun)
1625   (let ((vars (debug-fun-%debug-vars debug-fun)))
1626     (if (eq vars :unparsed)
1627         (setf (debug-fun-%debug-vars debug-fun)
1628               (etypecase debug-fun
1629                 (compiled-debug-fun
1630                  (parse-compiled-debug-vars debug-fun))
1631                 (bogus-debug-fun nil)))
1632         vars)))
1633
1634 ;;; VARS is the parsed variables for a minimal debug function. We need
1635 ;;; to assign names of the form ARG-NNN. We must pad with leading
1636 ;;; zeros, since the arguments must be in alphabetical order.
1637 (defun assign-minimal-var-names (vars)
1638   (declare (simple-vector vars))
1639   (let* ((len (length vars))
1640          (width (length (format nil "~W" (1- len)))))
1641     (dotimes (i len)
1642       (without-package-locks
1643         (setf (compiled-debug-var-symbol (svref vars i))
1644               (intern (format nil "ARG-~V,'0D" width i)
1645                       ;; KLUDGE: It's somewhat nasty to have a bare
1646                       ;; package name string here. It would be
1647                       ;; nicer to have #.(FIND-PACKAGE "SB!DEBUG")
1648                       ;; instead, since then at least it would transform
1649                       ;; correctly under package renaming and stuff.
1650                       ;; However, genesis can't handle dumped packages..
1651                       ;; -- WHN 20000129
1652                       ;;
1653                       ;; FIXME: Maybe this could be fixed by moving the
1654                       ;; whole debug-int.lisp file to warm init? (after
1655                       ;; which dumping a #.(FIND-PACKAGE ..) expression
1656                       ;; would work fine) If this is possible, it would
1657                       ;; probably be a good thing, since minimizing the
1658                       ;; amount of stuff in cold init is basically good.
1659                       (or (find-package "SB-DEBUG")
1660                           (find-package "SB!DEBUG"))))))))
1661
1662 ;;; Parse the packed representation of DEBUG-VARs from
1663 ;;; DEBUG-FUN's SB!C::COMPILED-DEBUG-FUN, returning a vector
1664 ;;; of DEBUG-VARs, or NIL if there was no information to parse.
1665 (defun parse-compiled-debug-vars (debug-fun)
1666   (let* ((cdebug-fun (compiled-debug-fun-compiler-debug-fun
1667                       debug-fun))
1668          (packed-vars (sb!c::compiled-debug-fun-vars cdebug-fun))
1669          (args-minimal (eq (sb!c::compiled-debug-fun-arguments cdebug-fun)
1670                            :minimal)))
1671     (when packed-vars
1672       (do ((i 0)
1673            (buffer (make-array 0 :fill-pointer 0 :adjustable t)))
1674           ((>= i (length packed-vars))
1675            (let ((result (coerce buffer 'simple-vector)))
1676              (when args-minimal
1677                (assign-minimal-var-names result))
1678              result))
1679         (flet ((geti () (prog1 (aref packed-vars i) (incf i))))
1680           (let* ((flags (geti))
1681                  (minimal (logtest sb!c::compiled-debug-var-minimal-p flags))
1682                  (deleted (logtest sb!c::compiled-debug-var-deleted-p flags))
1683                  (live (logtest sb!c::compiled-debug-var-environment-live
1684                                 flags))
1685                  (save (logtest sb!c::compiled-debug-var-save-loc-p flags))
1686                  (symbol (if minimal nil (geti)))
1687                  (id (if (logtest sb!c::compiled-debug-var-id-p flags)
1688                          (geti)
1689                          0))
1690                  (sc-offset (if deleted 0 (geti)))
1691                  (save-sc-offset (if save (geti) nil)))
1692             (aver (not (and args-minimal (not minimal))))
1693             (vector-push-extend (make-compiled-debug-var symbol
1694                                                          id
1695                                                          live
1696                                                          sc-offset
1697                                                          save-sc-offset)
1698                                 buffer)))))))
1699 \f
1700 ;;;; CODE-LOCATIONs
1701
1702 ;;; If we're sure of whether code-location is known, return T or NIL.
1703 ;;; If we're :UNSURE, then try to fill in the code-location's slots.
1704 ;;; This determines whether there is any debug-block information, and
1705 ;;; if code-location is known.
1706 ;;;
1707 ;;; ??? IF this conses closures every time it's called, then break off the
1708 ;;; :UNSURE part to get the HANDLER-CASE into another function.
1709 (defun code-location-unknown-p (basic-code-location)
1710   (ecase (code-location-%unknown-p basic-code-location)
1711     ((t) t)
1712     ((nil) nil)
1713     (:unsure
1714      (setf (code-location-%unknown-p basic-code-location)
1715            (handler-case (not (fill-in-code-location basic-code-location))
1716              (no-debug-blocks () t))))))
1717
1718 ;;; Return the DEBUG-BLOCK containing code-location if it is available.
1719 ;;; Some debug policies inhibit debug-block information, and if none
1720 ;;; is available, then this signals a NO-DEBUG-BLOCKS condition.
1721 (defun code-location-debug-block (basic-code-location)
1722   (let ((block (code-location-%debug-block basic-code-location)))
1723     (if (eq block :unparsed)
1724         (etypecase basic-code-location
1725           (compiled-code-location
1726            (compute-compiled-code-location-debug-block basic-code-location))
1727           ;; (There used to be more cases back before sbcl-0.7.0, when
1728           ;; we did special tricks to debug the IR1 interpreter.)
1729           )
1730         block)))
1731
1732 ;;; Store and return BASIC-CODE-LOCATION's debug-block. We determines
1733 ;;; the correct one using the code-location's pc. We use
1734 ;;; DEBUG-FUN-DEBUG-BLOCKS to return the cached block information
1735 ;;; or signal a NO-DEBUG-BLOCKS condition. The blocks are sorted by
1736 ;;; their first code-location's pc, in ascending order. Therefore, as
1737 ;;; soon as we find a block that starts with a pc greater than
1738 ;;; basic-code-location's pc, we know the previous block contains the
1739 ;;; pc. If we get to the last block, then the code-location is either
1740 ;;; in the second to last block or the last block, and we have to be
1741 ;;; careful in determining this since the last block could be code at
1742 ;;; the end of the function. We have to check for the last block being
1743 ;;; code first in order to see how to compare the code-location's pc.
1744 (defun compute-compiled-code-location-debug-block (basic-code-location)
1745   (let* ((pc (compiled-code-location-pc basic-code-location))
1746          (debug-fun (code-location-debug-fun
1747                           basic-code-location))
1748          (blocks (debug-fun-debug-blocks debug-fun))
1749          (len (length blocks)))
1750     (declare (simple-vector blocks))
1751     (setf (code-location-%debug-block basic-code-location)
1752           (if (= len 1)
1753               (svref blocks 0)
1754               (do ((i 1 (1+ i))
1755                    (end (1- len)))
1756                   ((= i end)
1757                    (let ((last (svref blocks end)))
1758                      (cond
1759                       ((debug-block-elsewhere-p last)
1760                        (if (< pc
1761                               (sb!c::compiled-debug-fun-elsewhere-pc
1762                                (compiled-debug-fun-compiler-debug-fun
1763                                 debug-fun)))
1764                            (svref blocks (1- end))
1765                            last))
1766                       ((< pc
1767                           (compiled-code-location-pc
1768                            (svref (compiled-debug-block-code-locations last)
1769                                   0)))
1770                        (svref blocks (1- end)))
1771                       (t last))))
1772                 (declare (type index i end))
1773                 (when (< pc
1774                          (compiled-code-location-pc
1775                           (svref (compiled-debug-block-code-locations
1776                                   (svref blocks i))
1777                                  0)))
1778                   (return (svref blocks (1- i)))))))))
1779
1780 ;;; Return the CODE-LOCATION's DEBUG-SOURCE.
1781 (defun code-location-debug-source (code-location)
1782   (let ((info (compiled-debug-fun-debug-info
1783                (code-location-debug-fun code-location))))
1784     (or (sb!c::debug-info-source info)
1785         (debug-signal 'no-debug-blocks :debug-fun
1786                       (code-location-debug-fun code-location)))))
1787
1788 ;;; Returns the number of top level forms before the one containing
1789 ;;; CODE-LOCATION as seen by the compiler in some compilation unit. (A
1790 ;;; compilation unit is not necessarily a single file, see the section
1791 ;;; on debug-sources.)
1792 (defun code-location-toplevel-form-offset (code-location)
1793   (when (code-location-unknown-p code-location)
1794     (error 'unknown-code-location :code-location code-location))
1795   (let ((tlf-offset (code-location-%tlf-offset code-location)))
1796     (cond ((eq tlf-offset :unparsed)
1797            (etypecase code-location
1798              (compiled-code-location
1799               (unless (fill-in-code-location code-location)
1800                 ;; This check should be unnecessary. We're missing
1801                 ;; debug info the compiler should have dumped.
1802                 (bug "unknown code location"))
1803               (code-location-%tlf-offset code-location))
1804              ;; (There used to be more cases back before sbcl-0.7.0,,
1805              ;; when we did special tricks to debug the IR1
1806              ;; interpreter.)
1807              ))
1808           (t tlf-offset))))
1809
1810 ;;; Return the number of the form corresponding to CODE-LOCATION. The
1811 ;;; form number is derived by a walking the subforms of a top level
1812 ;;; form in depth-first order.
1813 (defun code-location-form-number (code-location)
1814   (when (code-location-unknown-p code-location)
1815     (error 'unknown-code-location :code-location code-location))
1816   (let ((form-num (code-location-%form-number code-location)))
1817     (cond ((eq form-num :unparsed)
1818            (etypecase code-location
1819              (compiled-code-location
1820               (unless (fill-in-code-location code-location)
1821                 ;; This check should be unnecessary. We're missing
1822                 ;; debug info the compiler should have dumped.
1823                 (bug "unknown code location"))
1824               (code-location-%form-number code-location))
1825              ;; (There used to be more cases back before sbcl-0.7.0,,
1826              ;; when we did special tricks to debug the IR1
1827              ;; interpreter.)
1828              ))
1829           (t form-num))))
1830
1831 ;;; Return the kind of CODE-LOCATION, one of:
1832 ;;;  :INTERPRETED, :UNKNOWN-RETURN, :KNOWN-RETURN, :INTERNAL-ERROR,
1833 ;;;  :NON-LOCAL-EXIT, :BLOCK-START, :CALL-SITE, :SINGLE-VALUE-RETURN,
1834 ;;;  :NON-LOCAL-ENTRY
1835 (defun code-location-kind (code-location)
1836   (when (code-location-unknown-p code-location)
1837     (error 'unknown-code-location :code-location code-location))
1838   (etypecase code-location
1839     (compiled-code-location
1840      (let ((kind (compiled-code-location-kind code-location)))
1841        (cond ((not (eq kind :unparsed)) kind)
1842              ((not (fill-in-code-location code-location))
1843               ;; This check should be unnecessary. We're missing
1844               ;; debug info the compiler should have dumped.
1845               (bug "unknown code location"))
1846              (t
1847               (compiled-code-location-kind code-location)))))
1848     ;; (There used to be more cases back before sbcl-0.7.0,,
1849     ;; when we did special tricks to debug the IR1
1850     ;; interpreter.)
1851     ))
1852
1853 ;;; This returns CODE-LOCATION's live-set if it is available. If
1854 ;;; there is no debug-block information, this returns NIL.
1855 (defun compiled-code-location-live-set (code-location)
1856   (if (code-location-unknown-p code-location)
1857       nil
1858       (let ((live-set (compiled-code-location-%live-set code-location)))
1859         (cond ((eq live-set :unparsed)
1860                (unless (fill-in-code-location code-location)
1861                  ;; This check should be unnecessary. We're missing
1862                  ;; debug info the compiler should have dumped.
1863                  ;;
1864                  ;; FIXME: This error and comment happen over and over again.
1865                  ;; Make them a shared function.
1866                  (bug "unknown code location"))
1867                (compiled-code-location-%live-set code-location))
1868               (t live-set)))))
1869
1870 ;;; true if OBJ1 and OBJ2 are the same place in the code
1871 (defun code-location= (obj1 obj2)
1872   (etypecase obj1
1873     (compiled-code-location
1874      (etypecase obj2
1875        (compiled-code-location
1876         (and (eq (code-location-debug-fun obj1)
1877                  (code-location-debug-fun obj2))
1878              (sub-compiled-code-location= obj1 obj2)))
1879        ;; (There used to be more cases back before sbcl-0.7.0,,
1880        ;; when we did special tricks to debug the IR1
1881        ;; interpreter.)
1882        ))
1883     ;; (There used to be more cases back before sbcl-0.7.0,,
1884     ;; when we did special tricks to debug IR1-interpreted code.)
1885     ))
1886 (defun sub-compiled-code-location= (obj1 obj2)
1887   (= (compiled-code-location-pc obj1)
1888      (compiled-code-location-pc obj2)))
1889
1890 ;;; Fill in CODE-LOCATION's :UNPARSED slots, returning T or NIL
1891 ;;; depending on whether the code-location was known in its
1892 ;;; DEBUG-FUN's debug-block information. This may signal a
1893 ;;; NO-DEBUG-BLOCKS condition due to DEBUG-FUN-DEBUG-BLOCKS, and
1894 ;;; it assumes the %UNKNOWN-P slot is already set or going to be set.
1895 (defun fill-in-code-location (code-location)
1896   (declare (type compiled-code-location code-location))
1897   (let* ((debug-fun (code-location-debug-fun code-location))
1898          (blocks (debug-fun-debug-blocks debug-fun)))
1899     (declare (simple-vector blocks))
1900     (dotimes (i (length blocks) nil)
1901       (let* ((block (svref blocks i))
1902              (locations (compiled-debug-block-code-locations block)))
1903         (declare (simple-vector locations))
1904         (dotimes (j (length locations))
1905           (let ((loc (svref locations j)))
1906             (when (sub-compiled-code-location= code-location loc)
1907               (setf (code-location-%debug-block code-location) block)
1908               (setf (code-location-%tlf-offset code-location)
1909                     (code-location-%tlf-offset loc))
1910               (setf (code-location-%form-number code-location)
1911                     (code-location-%form-number loc))
1912               (setf (compiled-code-location-%live-set code-location)
1913                     (compiled-code-location-%live-set loc))
1914               (setf (compiled-code-location-kind code-location)
1915                     (compiled-code-location-kind loc))
1916               (setf (compiled-code-location-step-info code-location)
1917                     (compiled-code-location-step-info loc))
1918               (return-from fill-in-code-location t))))))))
1919 \f
1920 ;;;; operations on DEBUG-BLOCKs
1921
1922 ;;; Execute FORMS in a context with CODE-VAR bound to each
1923 ;;; CODE-LOCATION in DEBUG-BLOCK, and return the value of RESULT.
1924 (defmacro do-debug-block-locations ((code-var debug-block &optional result)
1925                                     &body body)
1926   (let ((code-locations (gensym))
1927         (i (gensym)))
1928     `(let ((,code-locations (debug-block-code-locations ,debug-block)))
1929        (declare (simple-vector ,code-locations))
1930        (dotimes (,i (length ,code-locations) ,result)
1931          (let ((,code-var (svref ,code-locations ,i)))
1932            ,@body)))))
1933
1934 ;;; Return the name of the function represented by DEBUG-FUN.
1935 ;;; This may be a string or a cons; do not assume it is a symbol.
1936 (defun debug-block-fun-name (debug-block)
1937   (etypecase debug-block
1938     (compiled-debug-block
1939      (let ((code-locs (compiled-debug-block-code-locations debug-block)))
1940        (declare (simple-vector code-locs))
1941        (if (zerop (length code-locs))
1942            "??? Can't get name of debug-block's function."
1943            (debug-fun-name
1944             (code-location-debug-fun (svref code-locs 0))))))
1945     ;; (There used to be more cases back before sbcl-0.7.0, when we
1946     ;; did special tricks to debug the IR1 interpreter.)
1947     ))
1948
1949 (defun debug-block-code-locations (debug-block)
1950   (etypecase debug-block
1951     (compiled-debug-block
1952      (compiled-debug-block-code-locations debug-block))
1953     ;; (There used to be more cases back before sbcl-0.7.0, when we
1954     ;; did special tricks to debug the IR1 interpreter.)
1955     ))
1956 \f
1957 ;;;; operations on debug variables
1958
1959 (defun debug-var-symbol-name (debug-var)
1960   (symbol-name (debug-var-symbol debug-var)))
1961
1962 ;;; FIXME: Make sure that this isn't called anywhere that it wouldn't
1963 ;;; be acceptable to have NIL returned, or that it's only called on
1964 ;;; DEBUG-VARs whose symbols have non-NIL packages.
1965 (defun debug-var-package-name (debug-var)
1966   (package-name (symbol-package (debug-var-symbol debug-var))))
1967
1968 ;;; Return the value stored for DEBUG-VAR in frame, or if the value is
1969 ;;; not :VALID, then signal an INVALID-VALUE error.
1970 (defun debug-var-valid-value (debug-var frame)
1971   (unless (eq (debug-var-validity debug-var (frame-code-location frame))
1972               :valid)
1973     (error 'invalid-value :debug-var debug-var :frame frame))
1974   (debug-var-value debug-var frame))
1975
1976 ;;; Returns the value stored for DEBUG-VAR in frame. The value may be
1977 ;;; invalid. This is SETFable.
1978 (defun debug-var-value (debug-var frame)
1979   (aver (typep frame 'compiled-frame))
1980   (let ((res (access-compiled-debug-var-slot debug-var frame)))
1981     (if (indirect-value-cell-p res)
1982         (value-cell-ref res)
1983         res)))
1984
1985 ;;; This returns what is stored for the variable represented by
1986 ;;; DEBUG-VAR relative to the FRAME. This may be an indirect value
1987 ;;; cell if the variable is both closed over and set.
1988 (defun access-compiled-debug-var-slot (debug-var frame)
1989   (declare (optimize (speed 1)))
1990   (let ((escaped (compiled-frame-escaped frame)))
1991     (if escaped
1992         (sub-access-debug-var-slot
1993          (frame-pointer frame)
1994          (compiled-debug-var-sc-offset debug-var)
1995          escaped)
1996       (sub-access-debug-var-slot
1997        (frame-pointer frame)
1998        (or (compiled-debug-var-save-sc-offset debug-var)
1999            (compiled-debug-var-sc-offset debug-var))))))
2000
2001 ;;; a helper function for working with possibly-invalid values:
2002 ;;; Do (MAKE-LISP-OBJ VAL) only if the value looks valid.
2003 ;;;
2004 ;;; (Such values can arise in registers on machines with conservative
2005 ;;; GC, and might also arise in debug variable locations when
2006 ;;; those variables are invalid.)
2007 (defun make-valid-lisp-obj (val)
2008   (if (or
2009        ;; fixnum
2010        (zerop (logand val sb!vm:fixnum-tag-mask))
2011        ;; immediate single float, 64-bit only
2012        #!+#.(cl:if (cl:= sb!vm::n-machine-word-bits 64) '(and) '(or))
2013        (= (logand val #xff) sb!vm:single-float-widetag)
2014        ;; character
2015        (and (zerop (logandc2 val #x1fffffff)) ; Top bits zero
2016             (= (logand val #xff) sb!vm:character-widetag)) ; char tag
2017        ;; unbound marker
2018        (= val sb!vm:unbound-marker-widetag)
2019        ;; pointer
2020        (and (logbitp 0 val)
2021             ;; Check that the pointer is valid. XXX Could do a better
2022             ;; job. FIXME: e.g. by calling out to an is_valid_pointer
2023             ;; routine in the C runtime support code
2024             (or (< sb!vm:read-only-space-start val
2025                    (* sb!vm:*read-only-space-free-pointer*
2026                       sb!vm:n-word-bytes))
2027                 (< sb!vm:static-space-start val
2028                    (* sb!vm:*static-space-free-pointer*
2029                       sb!vm:n-word-bytes))
2030                 (< (current-dynamic-space-start) val
2031                    (sap-int (dynamic-space-free-pointer))))))
2032       (make-lisp-obj val)
2033       :invalid-object))
2034
2035 #!-(or x86 x86-64)
2036 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2037   (macrolet ((with-escaped-value ((var) &body forms)
2038                `(if escaped
2039                     (let ((,var (sb!vm:context-register
2040                                  escaped
2041                                  (sb!c:sc-offset-offset sc-offset))))
2042                       ,@forms)
2043                     :invalid-value-for-unescaped-register-storage))
2044              (escaped-float-value (format)
2045                `(if escaped
2046                     (sb!vm:context-float-register
2047                      escaped
2048                      (sb!c:sc-offset-offset sc-offset)
2049                      ',format)
2050                     :invalid-value-for-unescaped-register-storage))
2051              (with-nfp ((var) &body body)
2052                `(let ((,var (if escaped
2053                                 (sb!sys:int-sap
2054                                  (sb!vm:context-register escaped
2055                                                          sb!vm::nfp-offset))
2056                                 #!-alpha
2057                                 (sb!sys:sap-ref-sap fp (* nfp-save-offset
2058                                                           sb!vm:n-word-bytes))
2059                                 #!+alpha
2060                                 (sb!vm::make-number-stack-pointer
2061                                  (sb!sys:sap-ref-32 fp (* nfp-save-offset
2062                                                           sb!vm:n-word-bytes))))))
2063                   ,@body)))
2064     (ecase (sb!c:sc-offset-scn sc-offset)
2065       ((#.sb!vm:any-reg-sc-number
2066         #.sb!vm:descriptor-reg-sc-number
2067         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2068        (sb!sys:without-gcing
2069         (with-escaped-value (val) (sb!kernel:make-lisp-obj val))))
2070
2071       (#.sb!vm:character-reg-sc-number
2072        (with-escaped-value (val)
2073          (code-char val)))
2074       (#.sb!vm:sap-reg-sc-number
2075        (with-escaped-value (val)
2076          (sb!sys:int-sap val)))
2077       (#.sb!vm:signed-reg-sc-number
2078        (with-escaped-value (val)
2079          (if (logbitp (1- sb!vm:n-word-bits) val)
2080              (logior val (ash -1 sb!vm:n-word-bits))
2081              val)))
2082       (#.sb!vm:unsigned-reg-sc-number
2083        (with-escaped-value (val)
2084          val))
2085       (#.sb!vm:non-descriptor-reg-sc-number
2086        (error "Local non-descriptor register access?"))
2087       (#.sb!vm:interior-reg-sc-number
2088        (error "Local interior register access?"))
2089       (#.sb!vm:single-reg-sc-number
2090        (escaped-float-value single-float))
2091       (#.sb!vm:double-reg-sc-number
2092        (escaped-float-value double-float))
2093       #!+long-float
2094       (#.sb!vm:long-reg-sc-number
2095        (escaped-float-value long-float))
2096       (#.sb!vm:complex-single-reg-sc-number
2097        (if escaped
2098            (complex
2099             (sb!vm:context-float-register
2100              escaped (sb!c:sc-offset-offset sc-offset) 'single-float)
2101             (sb!vm:context-float-register
2102              escaped (1+ (sb!c:sc-offset-offset sc-offset)) 'single-float))
2103            :invalid-value-for-unescaped-register-storage))
2104       (#.sb!vm:complex-double-reg-sc-number
2105        (if escaped
2106            (complex
2107             (sb!vm:context-float-register
2108              escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2109             (sb!vm:context-float-register
2110              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #!-sparc 1)
2111              'double-float))
2112            :invalid-value-for-unescaped-register-storage))
2113       #!+long-float
2114       (#.sb!vm:complex-long-reg-sc-number
2115        (if escaped
2116            (complex
2117             (sb!vm:context-float-register
2118              escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2119             (sb!vm:context-float-register
2120              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2121              'long-float))
2122            :invalid-value-for-unescaped-register-storage))
2123       (#.sb!vm:single-stack-sc-number
2124        (with-nfp (nfp)
2125          (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2126                                        sb!vm:n-word-bytes))))
2127       (#.sb!vm:double-stack-sc-number
2128        (with-nfp (nfp)
2129          (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2130                                        sb!vm:n-word-bytes))))
2131       #!+long-float
2132       (#.sb!vm:long-stack-sc-number
2133        (with-nfp (nfp)
2134          (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2135                                      sb!vm:n-word-bytes))))
2136       (#.sb!vm:complex-single-stack-sc-number
2137        (with-nfp (nfp)
2138          (complex
2139           (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2140                                         sb!vm:n-word-bytes))
2141           (sb!sys:sap-ref-single nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2142                                         sb!vm:n-word-bytes)))))
2143       (#.sb!vm:complex-double-stack-sc-number
2144        (with-nfp (nfp)
2145          (complex
2146           (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2147                                         sb!vm:n-word-bytes))
2148           (sb!sys:sap-ref-double nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2149                                         sb!vm:n-word-bytes)))))
2150       #!+long-float
2151       (#.sb!vm:complex-long-stack-sc-number
2152        (with-nfp (nfp)
2153          (complex
2154           (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2155                                       sb!vm:n-word-bytes))
2156           (sb!sys:sap-ref-long nfp (* (+ (sb!c:sc-offset-offset sc-offset)
2157                                          #!+sparc 4)
2158                                       sb!vm:n-word-bytes)))))
2159       (#.sb!vm:control-stack-sc-number
2160        (sb!kernel:stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2161       (#.sb!vm:character-stack-sc-number
2162        (with-nfp (nfp)
2163          (code-char (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2164                                               sb!vm:n-word-bytes)))))
2165       (#.sb!vm:unsigned-stack-sc-number
2166        (with-nfp (nfp)
2167          (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2168                                    sb!vm:n-word-bytes))))
2169       (#.sb!vm:signed-stack-sc-number
2170        (with-nfp (nfp)
2171          (sb!sys:signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2172                                           sb!vm:n-word-bytes))))
2173       (#.sb!vm:sap-stack-sc-number
2174        (with-nfp (nfp)
2175          (sb!sys:sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2176                                     sb!vm:n-word-bytes)))))))
2177
2178 #!+(or x86 x86-64)
2179 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2180   (declare (type system-area-pointer fp))
2181   (macrolet ((with-escaped-value ((var) &body forms)
2182                `(if escaped
2183                     (let ((,var (sb!vm:context-register
2184                                  escaped
2185                                  (sb!c:sc-offset-offset sc-offset))))
2186                       ,@forms)
2187                     :invalid-value-for-unescaped-register-storage))
2188              (escaped-float-value (format)
2189                `(if escaped
2190                     (sb!vm:context-float-register
2191                      escaped (sb!c:sc-offset-offset sc-offset) ',format)
2192                     :invalid-value-for-unescaped-register-storage))
2193              (escaped-complex-float-value (format)
2194                `(if escaped
2195                     (complex
2196                      (sb!vm:context-float-register
2197                       escaped (sb!c:sc-offset-offset sc-offset) ',format)
2198                      (sb!vm:context-float-register
2199                       escaped (1+ (sb!c:sc-offset-offset sc-offset)) ',format))
2200                     :invalid-value-for-unescaped-register-storage)))
2201     (ecase (sb!c:sc-offset-scn sc-offset)
2202       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2203        (without-gcing
2204         (with-escaped-value (val)
2205           (make-valid-lisp-obj val))))
2206       (#.sb!vm:character-reg-sc-number
2207        (with-escaped-value (val)
2208          (code-char val)))
2209       (#.sb!vm:sap-reg-sc-number
2210        (with-escaped-value (val)
2211          (int-sap val)))
2212       (#.sb!vm:signed-reg-sc-number
2213        (with-escaped-value (val)
2214          (if (logbitp (1- sb!vm:n-word-bits) val)
2215              (logior val (ash -1 sb!vm:n-word-bits))
2216              val)))
2217       (#.sb!vm:unsigned-reg-sc-number
2218        (with-escaped-value (val)
2219          val))
2220       (#.sb!vm:single-reg-sc-number
2221        (escaped-float-value single-float))
2222       (#.sb!vm:double-reg-sc-number
2223        (escaped-float-value double-float))
2224       #!+long-float
2225       (#.sb!vm:long-reg-sc-number
2226        (escaped-float-value long-float))
2227       (#.sb!vm:complex-single-reg-sc-number
2228        (escaped-complex-float-value single-float))
2229       (#.sb!vm:complex-double-reg-sc-number
2230        (escaped-complex-float-value double-float))
2231       #!+long-float
2232       (#.sb!vm:complex-long-reg-sc-number
2233        (escaped-complex-float-value long-float))
2234       (#.sb!vm:single-stack-sc-number
2235        (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2236                                 sb!vm:n-word-bytes))))
2237       (#.sb!vm:double-stack-sc-number
2238        (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2239                                 sb!vm:n-word-bytes))))
2240       #!+long-float
2241       (#.sb!vm:long-stack-sc-number
2242        (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2243                               sb!vm:n-word-bytes))))
2244       (#.sb!vm:complex-single-stack-sc-number
2245        (complex
2246         (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2247                                  sb!vm:n-word-bytes)))
2248         (sap-ref-single fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2249                                  sb!vm:n-word-bytes)))))
2250       (#.sb!vm:complex-double-stack-sc-number
2251        (complex
2252         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2253                                  sb!vm:n-word-bytes)))
2254         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2255                                  sb!vm:n-word-bytes)))))
2256       #!+long-float
2257       (#.sb!vm:complex-long-stack-sc-number
2258        (complex
2259         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2260                                sb!vm:n-word-bytes)))
2261         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2262                                sb!vm:n-word-bytes)))))
2263       (#.sb!vm:control-stack-sc-number
2264        (stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2265       (#.sb!vm:character-stack-sc-number
2266        (code-char
2267         (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2268                                sb!vm:n-word-bytes)))))
2269       (#.sb!vm:unsigned-stack-sc-number
2270        (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2271                               sb!vm:n-word-bytes))))
2272       (#.sb!vm:signed-stack-sc-number
2273        (signed-sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2274                                      sb!vm:n-word-bytes))))
2275       (#.sb!vm:sap-stack-sc-number
2276        (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2277                              sb!vm:n-word-bytes)))))))
2278
2279 ;;; This stores value as the value of DEBUG-VAR in FRAME. In the
2280 ;;; COMPILED-DEBUG-VAR case, access the current value to determine if
2281 ;;; it is an indirect value cell. This occurs when the variable is
2282 ;;; both closed over and set.
2283 (defun %set-debug-var-value (debug-var frame new-value)
2284   (aver (typep frame 'compiled-frame))
2285   (let ((old-value (access-compiled-debug-var-slot debug-var frame)))
2286     (if (indirect-value-cell-p old-value)
2287         (value-cell-set old-value new-value)
2288         (set-compiled-debug-var-slot debug-var frame new-value)))
2289   new-value)
2290
2291 ;;; This stores VALUE for the variable represented by debug-var
2292 ;;; relative to the frame. This assumes the location directly contains
2293 ;;; the variable's value; that is, there is no indirect value cell
2294 ;;; currently there in case the variable is both closed over and set.
2295 (defun set-compiled-debug-var-slot (debug-var frame value)
2296   (let ((escaped (compiled-frame-escaped frame)))
2297     (if escaped
2298         (sub-set-debug-var-slot (frame-pointer frame)
2299                                 (compiled-debug-var-sc-offset debug-var)
2300                                 value escaped)
2301         (sub-set-debug-var-slot
2302          (frame-pointer frame)
2303          (or (compiled-debug-var-save-sc-offset debug-var)
2304              (compiled-debug-var-sc-offset debug-var))
2305          value))))
2306
2307 #!-(or x86 x86-64)
2308 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2309   (macrolet ((set-escaped-value (val)
2310                `(if escaped
2311                     (setf (sb!vm:context-register
2312                            escaped
2313                            (sb!c:sc-offset-offset sc-offset))
2314                           ,val)
2315                     value))
2316              (set-escaped-float-value (format val)
2317                `(if escaped
2318                     (setf (sb!vm:context-float-register
2319                            escaped
2320                            (sb!c:sc-offset-offset sc-offset)
2321                            ',format)
2322                           ,val)
2323                     value))
2324              (with-nfp ((var) &body body)
2325                `(let ((,var (if escaped
2326                                 (int-sap
2327                                  (sb!vm:context-register escaped
2328                                                          sb!vm::nfp-offset))
2329                                 #!-alpha
2330                                 (sap-ref-sap fp
2331                                              (* nfp-save-offset
2332                                                 sb!vm:n-word-bytes))
2333                                 #!+alpha
2334                                 (sb!vm::make-number-stack-pointer
2335                                  (sap-ref-32 fp
2336                                              (* nfp-save-offset
2337                                                 sb!vm:n-word-bytes))))))
2338                   ,@body)))
2339     (ecase (sb!c:sc-offset-scn sc-offset)
2340       ((#.sb!vm:any-reg-sc-number
2341         #.sb!vm:descriptor-reg-sc-number
2342         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2343        (without-gcing
2344         (set-escaped-value
2345           (get-lisp-obj-address value))))
2346       (#.sb!vm:character-reg-sc-number
2347        (set-escaped-value (char-code value)))
2348       (#.sb!vm:sap-reg-sc-number
2349        (set-escaped-value (sap-int value)))
2350       (#.sb!vm:signed-reg-sc-number
2351        (set-escaped-value (logand value (1- (ash 1 sb!vm:n-word-bits)))))
2352       (#.sb!vm:unsigned-reg-sc-number
2353        (set-escaped-value value))
2354       (#.sb!vm:non-descriptor-reg-sc-number
2355        (error "Local non-descriptor register access?"))
2356       (#.sb!vm:interior-reg-sc-number
2357        (error "Local interior register access?"))
2358       (#.sb!vm:single-reg-sc-number
2359        (set-escaped-float-value single-float value))
2360       (#.sb!vm:double-reg-sc-number
2361        (set-escaped-float-value double-float value))
2362       #!+long-float
2363       (#.sb!vm:long-reg-sc-number
2364        (set-escaped-float-value long-float value))
2365       (#.sb!vm:complex-single-reg-sc-number
2366        (when escaped
2367          (setf (sb!vm:context-float-register escaped
2368                                              (sb!c:sc-offset-offset sc-offset)
2369                                              'single-float)
2370                (realpart value))
2371          (setf (sb!vm:context-float-register
2372                 escaped (1+ (sb!c:sc-offset-offset sc-offset))
2373                 'single-float)
2374                (imagpart value)))
2375        value)
2376       (#.sb!vm:complex-double-reg-sc-number
2377        (when escaped
2378          (setf (sb!vm:context-float-register
2379                 escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2380                (realpart value))
2381          (setf (sb!vm:context-float-register
2382                 escaped
2383                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #!-sparc 1)
2384                 'double-float)
2385                (imagpart value)))
2386        value)
2387       #!+long-float
2388       (#.sb!vm:complex-long-reg-sc-number
2389        (when escaped
2390          (setf (sb!vm:context-float-register
2391                 escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2392                (realpart value))
2393          (setf (sb!vm:context-float-register
2394                 escaped
2395                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2396                 'long-float)
2397                (imagpart value)))
2398        value)
2399       (#.sb!vm:single-stack-sc-number
2400        (with-nfp (nfp)
2401          (setf (sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2402                                       sb!vm:n-word-bytes))
2403                (the single-float value))))
2404       (#.sb!vm:double-stack-sc-number
2405        (with-nfp (nfp)
2406          (setf (sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2407                                       sb!vm:n-word-bytes))
2408                (the double-float value))))
2409       #!+long-float
2410       (#.sb!vm:long-stack-sc-number
2411        (with-nfp (nfp)
2412          (setf (sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2413                                     sb!vm:n-word-bytes))
2414                (the long-float value))))
2415       (#.sb!vm:complex-single-stack-sc-number
2416        (with-nfp (nfp)
2417          (setf (sap-ref-single
2418                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2419                (the single-float (realpart value)))
2420          (setf (sap-ref-single
2421                 nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2422                        sb!vm:n-word-bytes))
2423                (the single-float (realpart value)))))
2424       (#.sb!vm:complex-double-stack-sc-number
2425        (with-nfp (nfp)
2426          (setf (sap-ref-double
2427                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2428                (the double-float (realpart value)))
2429          (setf (sap-ref-double
2430                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2431                        sb!vm:n-word-bytes))
2432                (the double-float (realpart value)))))
2433       #!+long-float
2434       (#.sb!vm:complex-long-stack-sc-number
2435        (with-nfp (nfp)
2436          (setf (sap-ref-long
2437                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2438                (the long-float (realpart value)))
2439          (setf (sap-ref-long
2440                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2441                        sb!vm:n-word-bytes))
2442                (the long-float (realpart value)))))
2443       (#.sb!vm:control-stack-sc-number
2444        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2445       (#.sb!vm:character-stack-sc-number
2446        (with-nfp (nfp)
2447          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2448                                          sb!vm:n-word-bytes))
2449                (char-code (the character value)))))
2450       (#.sb!vm:unsigned-stack-sc-number
2451        (with-nfp (nfp)
2452          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2453                                   sb!vm:n-word-bytes))
2454                (the (unsigned-byte 32) value))))
2455       (#.sb!vm:signed-stack-sc-number
2456        (with-nfp (nfp)
2457          (setf (signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2458                                          sb!vm:n-word-bytes))
2459                (the (signed-byte 32) value))))
2460       (#.sb!vm:sap-stack-sc-number
2461        (with-nfp (nfp)
2462          (setf (sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2463                                    sb!vm:n-word-bytes))
2464                (the system-area-pointer value)))))))
2465
2466 #!+(or x86 x86-64)
2467 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2468   (macrolet ((set-escaped-value (val)
2469                `(if escaped
2470                     (setf (sb!vm:context-register
2471                            escaped
2472                            (sb!c:sc-offset-offset sc-offset))
2473                           ,val)
2474                     value)))
2475     (ecase (sb!c:sc-offset-scn sc-offset)
2476       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2477        (without-gcing
2478         (set-escaped-value
2479           (get-lisp-obj-address value))))
2480       (#.sb!vm:character-reg-sc-number
2481        (set-escaped-value (char-code value)))
2482       (#.sb!vm:sap-reg-sc-number
2483        (set-escaped-value (sap-int value)))
2484       (#.sb!vm:signed-reg-sc-number
2485        (set-escaped-value (logand value (1- (ash 1 sb!vm:n-word-bits)))))
2486       (#.sb!vm:unsigned-reg-sc-number
2487        (set-escaped-value value))
2488       (#.sb!vm:single-reg-sc-number
2489         #+nil ;; don't have escaped floats.
2490        (set-escaped-float-value single-float value))
2491       (#.sb!vm:double-reg-sc-number
2492         #+nil ;;  don't have escaped floats -- still in npx?
2493        (set-escaped-float-value double-float value))
2494       #!+long-float
2495       (#.sb!vm:long-reg-sc-number
2496         #+nil ;;  don't have escaped floats -- still in npx?
2497        (set-escaped-float-value long-float value))
2498       (#.sb!vm:single-stack-sc-number
2499        (setf (sap-ref-single
2500               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2501                        sb!vm:n-word-bytes)))
2502              (the single-float value)))
2503       (#.sb!vm:double-stack-sc-number
2504        (setf (sap-ref-double
2505               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2506                        sb!vm:n-word-bytes)))
2507              (the double-float value)))
2508       #!+long-float
2509       (#.sb!vm:long-stack-sc-number
2510        (setf (sap-ref-long
2511               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2512                        sb!vm:n-word-bytes)))
2513              (the long-float value)))
2514       (#.sb!vm:complex-single-stack-sc-number
2515        (setf (sap-ref-single
2516               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2517                        sb!vm:n-word-bytes)))
2518              (realpart (the (complex single-float) value)))
2519        (setf (sap-ref-single
2520               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2521                        sb!vm:n-word-bytes)))
2522              (imagpart (the (complex single-float) value))))
2523       (#.sb!vm:complex-double-stack-sc-number
2524        (setf (sap-ref-double
2525               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2526                        sb!vm:n-word-bytes)))
2527              (realpart (the (complex double-float) value)))
2528        (setf (sap-ref-double
2529               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2530                        sb!vm:n-word-bytes)))
2531              (imagpart (the (complex double-float) value))))
2532       #!+long-float
2533       (#.sb!vm:complex-long-stack-sc-number
2534        (setf (sap-ref-long
2535               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2536                        sb!vm:n-word-bytes)))
2537              (realpart (the (complex long-float) value)))
2538        (setf (sap-ref-long
2539               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2540                        sb!vm:n-word-bytes)))
2541              (imagpart (the (complex long-float) value))))
2542       (#.sb!vm:control-stack-sc-number
2543        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2544       (#.sb!vm:character-stack-sc-number
2545        (setf (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2546                                     sb!vm:n-word-bytes)))
2547              (char-code (the character value))))
2548       (#.sb!vm:unsigned-stack-sc-number
2549        (setf (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2550                                     sb!vm:n-word-bytes)))
2551              (the sb!vm:word value)))
2552       (#.sb!vm:signed-stack-sc-number
2553        (setf (signed-sap-ref-word
2554               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2555                        sb!vm:n-word-bytes)))
2556              (the (signed-byte #.sb!vm:n-word-bits) value)))
2557       (#.sb!vm:sap-stack-sc-number
2558        (setf (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2559                                           sb!vm:n-word-bytes)))
2560              (the system-area-pointer value))))))
2561
2562 ;;; The method for setting and accessing COMPILED-DEBUG-VAR values use
2563 ;;; this to determine if the value stored is the actual value or an
2564 ;;; indirection cell.
2565 (defun indirect-value-cell-p (x)
2566   (and (= (lowtag-of x) sb!vm:other-pointer-lowtag)
2567        (= (widetag-of x) sb!vm:value-cell-header-widetag)))
2568
2569 ;;; Return three values reflecting the validity of DEBUG-VAR's value
2570 ;;; at BASIC-CODE-LOCATION:
2571 ;;;   :VALID    The value is known to be available.
2572 ;;;   :INVALID  The value is known to be unavailable.
2573 ;;;   :UNKNOWN  The value's availability is unknown.
2574 ;;;
2575 ;;; If the variable is always alive, then it is valid. If the
2576 ;;; code-location is unknown, then the variable's validity is
2577 ;;; :unknown. Once we've called CODE-LOCATION-UNKNOWN-P, we know the
2578 ;;; live-set information has been cached in the code-location.
2579 (defun debug-var-validity (debug-var basic-code-location)
2580   (etypecase debug-var
2581     (compiled-debug-var
2582      (compiled-debug-var-validity debug-var basic-code-location))
2583     ;; (There used to be more cases back before sbcl-0.7.0, when
2584     ;; we did special tricks to debug the IR1 interpreter.)
2585     ))
2586
2587 ;;; This is the method for DEBUG-VAR-VALIDITY for COMPILED-DEBUG-VARs.
2588 ;;; For safety, make sure basic-code-location is what we think.
2589 (defun compiled-debug-var-validity (debug-var basic-code-location)
2590   (declare (type compiled-code-location basic-code-location))
2591   (cond ((debug-var-alive-p debug-var)
2592          (let ((debug-fun (code-location-debug-fun basic-code-location)))
2593            (if (>= (compiled-code-location-pc basic-code-location)
2594                    (sb!c::compiled-debug-fun-start-pc
2595                     (compiled-debug-fun-compiler-debug-fun debug-fun)))
2596                :valid
2597                :invalid)))
2598         ((code-location-unknown-p basic-code-location) :unknown)
2599         (t
2600          (let ((pos (position debug-var
2601                               (debug-fun-debug-vars
2602                                (code-location-debug-fun
2603                                 basic-code-location)))))
2604            (unless pos
2605              (error 'unknown-debug-var
2606                     :debug-var debug-var
2607                     :debug-fun
2608                     (code-location-debug-fun basic-code-location)))
2609            ;; There must be live-set info since basic-code-location is known.
2610            (if (zerop (sbit (compiled-code-location-live-set
2611                              basic-code-location)
2612                             pos))
2613                :invalid
2614                :valid)))))
2615 \f
2616 ;;;; sources
2617
2618 ;;; This code produces and uses what we call source-paths. A
2619 ;;; source-path is a list whose first element is a form number as
2620 ;;; returned by CODE-LOCATION-FORM-NUMBER and whose last element is a
2621 ;;; top level form number as returned by
2622 ;;; CODE-LOCATION-TOPLEVEL-FORM-NUMBER. The elements from the last to
2623 ;;; the first, exclusively, are the numbered subforms into which to
2624 ;;; descend. For example:
2625 ;;;    (defun foo (x)
2626 ;;;      (let ((a (aref x 3)))
2627 ;;;     (cons a 3)))
2628 ;;; The call to AREF in this example is form number 5. Assuming this
2629 ;;; DEFUN is the 11'th top level form, the source-path for the AREF
2630 ;;; call is as follows:
2631 ;;;    (5 1 0 1 3 11)
2632 ;;; Given the DEFUN, 3 gets you the LET, 1 gets you the bindings, 0
2633 ;;; gets the first binding, and 1 gets the AREF form.
2634
2635 ;;; temporary buffer used to build form-number => source-path translation in
2636 ;;; FORM-NUMBER-TRANSLATIONS
2637 (defvar *form-number-temp* (make-array 10 :fill-pointer 0 :adjustable t))
2638
2639 ;;; table used to detect CAR circularities in FORM-NUMBER-TRANSLATIONS
2640 (defvar *form-number-circularity-table* (make-hash-table :test 'eq))
2641
2642 ;;; This returns a table mapping form numbers to source-paths. A
2643 ;;; source-path indicates a descent into the TOPLEVEL-FORM form,
2644 ;;; going directly to the subform corressponding to the form number.
2645 ;;;
2646 ;;; The vector elements are in the same format as the compiler's
2647 ;;; NODE-SOURCE-PATH; that is, the first element is the form number and
2648 ;;; the last is the TOPLEVEL-FORM number.
2649 (defun form-number-translations (form tlf-number)
2650   (clrhash *form-number-circularity-table*)
2651   (setf (fill-pointer *form-number-temp*) 0)
2652   (sub-translate-form-numbers form (list tlf-number))
2653   (coerce *form-number-temp* 'simple-vector))
2654 (defun sub-translate-form-numbers (form path)
2655   (unless (gethash form *form-number-circularity-table*)
2656     (setf (gethash form *form-number-circularity-table*) t)
2657     (vector-push-extend (cons (fill-pointer *form-number-temp*) path)
2658                         *form-number-temp*)
2659     (let ((pos 0)
2660           (subform form)
2661           (trail form))
2662       (declare (fixnum pos))
2663       (macrolet ((frob ()
2664                    '(progn
2665                       (when (atom subform) (return))
2666                       (let ((fm (car subform)))
2667                         (when (consp fm)
2668                           (sub-translate-form-numbers fm (cons pos path)))
2669                         (incf pos))
2670                       (setq subform (cdr subform))
2671                       (when (eq subform trail) (return)))))
2672         (loop
2673           (frob)
2674           (frob)
2675           (setq trail (cdr trail)))))))
2676
2677 ;;; FORM is a top level form, and path is a source-path into it. This
2678 ;;; returns the form indicated by the source-path. Context is the
2679 ;;; number of enclosing forms to return instead of directly returning
2680 ;;; the source-path form. When context is non-zero, the form returned
2681 ;;; contains a marker, #:****HERE****, immediately before the form
2682 ;;; indicated by path.
2683 (defun source-path-context (form path context)
2684   (declare (type unsigned-byte context))
2685   ;; Get to the form indicated by path or the enclosing form indicated
2686   ;; by context and path.
2687   (let ((path (reverse (butlast (cdr path)))))
2688     (dotimes (i (- (length path) context))
2689       (let ((index (first path)))
2690         (unless (and (listp form) (< index (length form)))
2691           (error "Source path no longer exists."))
2692         (setq form (elt form index))
2693         (setq path (rest path))))
2694     ;; Recursively rebuild the source form resulting from the above
2695     ;; descent, copying the beginning of each subform up to the next
2696     ;; subform we descend into according to path. At the bottom of the
2697     ;; recursion, we return the form indicated by path preceded by our
2698     ;; marker, and this gets spliced into the resulting list structure
2699     ;; on the way back up.
2700     (labels ((frob (form path level)
2701                (if (or (zerop level) (null path))
2702                    (if (zerop context)
2703                        form
2704                        `(#:***here*** ,form))
2705                    (let ((n (first path)))
2706                      (unless (and (listp form) (< n (length form)))
2707                        (error "Source path no longer exists."))
2708                      (let ((res (frob (elt form n) (rest path) (1- level))))
2709                        (nconc (subseq form 0 n)
2710                               (cons res (nthcdr (1+ n) form))))))))
2711       (frob form path context))))
2712 \f
2713 ;;;; PREPROCESS-FOR-EVAL
2714
2715 ;;; Return a function of one argument that evaluates form in the
2716 ;;; lexical context of the BASIC-CODE-LOCATION LOC, or signal a
2717 ;;; NO-DEBUG-VARS condition when the LOC's DEBUG-FUN has no
2718 ;;; DEBUG-VAR information available.
2719 ;;;
2720 ;;; The returned function takes the frame to get values from as its
2721 ;;; argument, and it returns the values of FORM. The returned function
2722 ;;; can signal the following conditions: INVALID-VALUE,
2723 ;;; AMBIGUOUS-VAR-NAME, and FRAME-FUN-MISMATCH.
2724 (defun preprocess-for-eval (form loc)
2725   (declare (type code-location loc))
2726   (let ((n-frame (gensym))
2727         (fun (code-location-debug-fun loc)))
2728     (unless (debug-var-info-available fun)
2729       (debug-signal 'no-debug-vars :debug-fun fun))
2730     (sb!int:collect ((binds)
2731                      (specs))
2732       (do-debug-fun-vars (var fun)
2733         (let ((validity (debug-var-validity var loc)))
2734           (unless (eq validity :invalid)
2735             (let* ((sym (debug-var-symbol var))
2736                    (found (assoc sym (binds))))
2737               (if found
2738                   (setf (second found) :ambiguous)
2739                   (binds (list sym validity var)))))))
2740       (dolist (bind (binds))
2741         (let ((name (first bind))
2742               (var (third bind)))
2743           (ecase (second bind)
2744             (:valid
2745              (specs `(,name (debug-var-value ',var ,n-frame))))
2746             (:unknown
2747              (specs `(,name (debug-signal 'invalid-value
2748                                           :debug-var ',var
2749                                           :frame ,n-frame))))
2750             (:ambiguous
2751              (specs `(,name (debug-signal 'ambiguous-var-name
2752                                           :name ',name
2753                                           :frame ,n-frame)))))))
2754       (let ((res (coerce `(lambda (,n-frame)
2755                             (declare (ignorable ,n-frame))
2756                             (symbol-macrolet ,(specs) ,form))
2757                          'function)))
2758         (lambda (frame)
2759           ;; This prevents these functions from being used in any
2760           ;; location other than a function return location, so maybe
2761           ;; this should only check whether FRAME's DEBUG-FUN is the
2762           ;; same as LOC's.
2763           (unless (code-location= (frame-code-location frame) loc)
2764             (debug-signal 'frame-fun-mismatch
2765                           :code-location loc :form form :frame frame))
2766           (funcall res frame))))))
2767 \f
2768 ;;;; breakpoints
2769
2770 ;;;; user-visible interface
2771
2772 ;;; Create and return a breakpoint. When program execution encounters
2773 ;;; the breakpoint, the system calls HOOK-FUN. HOOK-FUN takes the
2774 ;;; current frame for the function in which the program is running and
2775 ;;; the breakpoint object.
2776 ;;;
2777 ;;; WHAT and KIND determine where in a function the system invokes
2778 ;;; HOOK-FUN. WHAT is either a code-location or a DEBUG-FUN. KIND is
2779 ;;; one of :CODE-LOCATION, :FUN-START, or :FUN-END. Since the starts
2780 ;;; and ends of functions may not have code-locations representing
2781 ;;; them, designate these places by supplying WHAT as a DEBUG-FUN and
2782 ;;; KIND indicating the :FUN-START or :FUN-END. When WHAT is a
2783 ;;; DEBUG-FUN and kind is :FUN-END, then HOOK-FUN must take two
2784 ;;; additional arguments, a list of values returned by the function
2785 ;;; and a FUN-END-COOKIE.
2786 ;;;
2787 ;;; INFO is information supplied by and used by the user.
2788 ;;;
2789 ;;; FUN-END-COOKIE is a function. To implement :FUN-END
2790 ;;; breakpoints, the system uses starter breakpoints to establish the
2791 ;;; :FUN-END breakpoint for each invocation of the function. Upon
2792 ;;; each entry, the system creates a unique cookie to identify the
2793 ;;; invocation, and when the user supplies a function for this
2794 ;;; argument, the system invokes it on the frame and the cookie. The
2795 ;;; system later invokes the :FUN-END breakpoint hook on the same
2796 ;;; cookie. The user may save the cookie for comparison in the hook
2797 ;;; function.
2798 ;;;
2799 ;;; Signal an error if WHAT is an unknown code-location.
2800 (defun make-breakpoint (hook-fun what
2801                         &key (kind :code-location) info fun-end-cookie)
2802   (etypecase what
2803     (code-location
2804      (when (code-location-unknown-p what)
2805        (error "cannot make a breakpoint at an unknown code location: ~S"
2806               what))
2807      (aver (eq kind :code-location))
2808      (let ((bpt (%make-breakpoint hook-fun what kind info)))
2809        (etypecase what
2810          (compiled-code-location
2811           ;; This slot is filled in due to calling CODE-LOCATION-UNKNOWN-P.
2812           (when (eq (compiled-code-location-kind what) :unknown-return)
2813             (let ((other-bpt (%make-breakpoint hook-fun what
2814                                                :unknown-return-partner
2815                                                info)))
2816               (setf (breakpoint-unknown-return-partner bpt) other-bpt)
2817               (setf (breakpoint-unknown-return-partner other-bpt) bpt))))
2818          ;; (There used to be more cases back before sbcl-0.7.0,,
2819          ;; when we did special tricks to debug the IR1
2820          ;; interpreter.)
2821          )
2822        bpt))
2823     (compiled-debug-fun
2824      (ecase kind
2825        (:fun-start
2826         (%make-breakpoint hook-fun what kind info))
2827        (:fun-end
2828         (unless (eq (sb!c::compiled-debug-fun-returns
2829                      (compiled-debug-fun-compiler-debug-fun what))
2830                     :standard)
2831           (error ":FUN-END breakpoints are currently unsupported ~
2832                   for the known return convention."))
2833
2834         (let* ((bpt (%make-breakpoint hook-fun what kind info))
2835                (starter (compiled-debug-fun-end-starter what)))
2836           (unless starter
2837             (setf starter (%make-breakpoint #'list what :fun-start nil))
2838             (setf (breakpoint-hook-fun starter)
2839                   (fun-end-starter-hook starter what))
2840             (setf (compiled-debug-fun-end-starter what) starter))
2841           (setf (breakpoint-start-helper bpt) starter)
2842           (push bpt (breakpoint-%info starter))
2843           (setf (breakpoint-cookie-fun bpt) fun-end-cookie)
2844           bpt))))))
2845
2846 ;;; These are unique objects created upon entry into a function by a
2847 ;;; :FUN-END breakpoint's starter hook. These are only created
2848 ;;; when users supply :FUN-END-COOKIE to MAKE-BREAKPOINT. Also,
2849 ;;; the :FUN-END breakpoint's hook is called on the same cookie
2850 ;;; when it is created.
2851 (defstruct (fun-end-cookie
2852             (:print-object (lambda (obj str)
2853                              (print-unreadable-object (obj str :type t))))
2854             (:constructor make-fun-end-cookie (bogus-lra debug-fun))
2855             (:copier nil))
2856   ;; a pointer to the bogus-lra created for :FUN-END breakpoints
2857   bogus-lra
2858   ;; the DEBUG-FUN associated with this cookie
2859   debug-fun)
2860
2861 ;;; This maps bogus-lra-components to cookies, so that
2862 ;;; HANDLE-FUN-END-BREAKPOINT can find the appropriate cookie for the
2863 ;;; breakpoint hook.
2864 (defvar *fun-end-cookies* (make-hash-table :test 'eq))
2865
2866 ;;; This returns a hook function for the start helper breakpoint
2867 ;;; associated with a :FUN-END breakpoint. The returned function
2868 ;;; makes a fake LRA that all returns go through, and this piece of
2869 ;;; fake code actually breaks. Upon return from the break, the code
2870 ;;; provides the returnee with any values. Since the returned function
2871 ;;; effectively activates FUN-END-BPT on each entry to DEBUG-FUN's
2872 ;;; function, we must establish breakpoint-data about FUN-END-BPT.
2873 (defun fun-end-starter-hook (starter-bpt debug-fun)
2874   (declare (type breakpoint starter-bpt)
2875            (type compiled-debug-fun debug-fun))
2876   (lambda (frame breakpoint)
2877     (declare (ignore breakpoint)
2878              (type frame frame))
2879     (let ((lra-sc-offset
2880            (sb!c::compiled-debug-fun-return-pc
2881             (compiled-debug-fun-compiler-debug-fun debug-fun))))
2882       (multiple-value-bind (lra component offset)
2883           (make-bogus-lra
2884            (get-context-value frame
2885                               lra-save-offset
2886                               lra-sc-offset))
2887         (setf (get-context-value frame
2888                                  lra-save-offset
2889                                  lra-sc-offset)
2890               lra)
2891         (let ((end-bpts (breakpoint-%info starter-bpt)))
2892           (let ((data (breakpoint-data component offset)))
2893             (setf (breakpoint-data-breakpoints data) end-bpts)
2894             (dolist (bpt end-bpts)
2895               (setf (breakpoint-internal-data bpt) data)))
2896           (let ((cookie (make-fun-end-cookie lra debug-fun)))
2897             (setf (gethash component *fun-end-cookies*) cookie)
2898             (dolist (bpt end-bpts)
2899               (let ((fun (breakpoint-cookie-fun bpt)))
2900                 (when fun (funcall fun frame cookie))))))))))
2901
2902 ;;; This takes a FUN-END-COOKIE and a frame, and it returns
2903 ;;; whether the cookie is still valid. A cookie becomes invalid when
2904 ;;; the frame that established the cookie has exited. Sometimes cookie
2905 ;;; holders are unaware of cookie invalidation because their
2906 ;;; :FUN-END breakpoint hooks didn't run due to THROW'ing.
2907 ;;;
2908 ;;; This takes a frame as an efficiency hack since the user probably
2909 ;;; has a frame object in hand when using this routine, and it saves
2910 ;;; repeated parsing of the stack and consing when asking whether a
2911 ;;; series of cookies is valid.
2912 (defun fun-end-cookie-valid-p (frame cookie)
2913   (let ((lra (fun-end-cookie-bogus-lra cookie))
2914         (lra-sc-offset (sb!c::compiled-debug-fun-return-pc
2915                         (compiled-debug-fun-compiler-debug-fun
2916                          (fun-end-cookie-debug-fun cookie)))))
2917     (do ((frame frame (frame-down frame)))
2918         ((not frame) nil)
2919       (when (and (compiled-frame-p frame)
2920                  (#!-(or x86 x86-64) eq #!+(or x86 x86-64) sap=
2921                   lra
2922                   (get-context-value frame lra-save-offset lra-sc-offset)))
2923         (return t)))))
2924 \f
2925 ;;;; ACTIVATE-BREAKPOINT
2926
2927 ;;; Cause the system to invoke the breakpoint's hook function until
2928 ;;; the next call to DEACTIVATE-BREAKPOINT or DELETE-BREAKPOINT. The
2929 ;;; system invokes breakpoint hook functions in the opposite order
2930 ;;; that you activate them.
2931 (defun activate-breakpoint (breakpoint)
2932   (when (eq (breakpoint-status breakpoint) :deleted)
2933     (error "cannot activate a deleted breakpoint: ~S" breakpoint))
2934   (unless (eq (breakpoint-status breakpoint) :active)
2935     (ecase (breakpoint-kind breakpoint)
2936       (:code-location
2937        (let ((loc (breakpoint-what breakpoint)))
2938          (etypecase loc
2939            (compiled-code-location
2940             (activate-compiled-code-location-breakpoint breakpoint)
2941             (let ((other (breakpoint-unknown-return-partner breakpoint)))
2942               (when other
2943                 (activate-compiled-code-location-breakpoint other))))
2944            ;; (There used to be more cases back before sbcl-0.7.0, when
2945            ;; we did special tricks to debug the IR1 interpreter.)
2946            )))
2947       (:fun-start
2948        (etypecase (breakpoint-what breakpoint)
2949          (compiled-debug-fun
2950           (activate-compiled-fun-start-breakpoint breakpoint))
2951          ;; (There used to be more cases back before sbcl-0.7.0, when
2952          ;; we did special tricks to debug the IR1 interpreter.)
2953          ))
2954       (:fun-end
2955        (etypecase (breakpoint-what breakpoint)
2956          (compiled-debug-fun
2957           (let ((starter (breakpoint-start-helper breakpoint)))
2958             (unless (eq (breakpoint-status starter) :active)
2959               ;; may already be active by some other :FUN-END breakpoint
2960               (activate-compiled-fun-start-breakpoint starter)))
2961           (setf (breakpoint-status breakpoint) :active))
2962          ;; (There used to be more cases back before sbcl-0.7.0, when
2963          ;; we did special tricks to debug the IR1 interpreter.)
2964          ))))
2965   breakpoint)
2966
2967 (defun activate-compiled-code-location-breakpoint (breakpoint)
2968   (declare (type breakpoint breakpoint))
2969   (let ((loc (breakpoint-what breakpoint)))
2970     (declare (type compiled-code-location loc))
2971     (sub-activate-breakpoint
2972      breakpoint
2973      (breakpoint-data (compiled-debug-fun-component
2974                        (code-location-debug-fun loc))
2975                       (+ (compiled-code-location-pc loc)
2976                          (if (or (eq (breakpoint-kind breakpoint)
2977                                      :unknown-return-partner)
2978                                  (eq (compiled-code-location-kind loc)
2979                                      :single-value-return))
2980                              sb!vm:single-value-return-byte-offset
2981                              0))))))
2982
2983 (defun activate-compiled-fun-start-breakpoint (breakpoint)
2984   (declare (type breakpoint breakpoint))
2985   (let ((debug-fun (breakpoint-what breakpoint)))
2986     (sub-activate-breakpoint
2987      breakpoint
2988      (breakpoint-data (compiled-debug-fun-component debug-fun)
2989                       (sb!c::compiled-debug-fun-start-pc
2990                        (compiled-debug-fun-compiler-debug-fun
2991                         debug-fun))))))
2992
2993 (defun sub-activate-breakpoint (breakpoint data)
2994   (declare (type breakpoint breakpoint)
2995            (type breakpoint-data data))
2996   (setf (breakpoint-status breakpoint) :active)
2997   (without-interrupts
2998    (unless (breakpoint-data-breakpoints data)
2999      (setf (breakpoint-data-instruction data)
3000            (without-gcing
3001             (breakpoint-install (get-lisp-obj-address
3002                                  (breakpoint-data-component data))
3003                                 (breakpoint-data-offset data)))))
3004    (setf (breakpoint-data-breakpoints data)
3005          (append (breakpoint-data-breakpoints data) (list breakpoint)))
3006    (setf (breakpoint-internal-data breakpoint) data)))
3007 \f
3008 ;;;; DEACTIVATE-BREAKPOINT
3009
3010 ;;; Stop the system from invoking the breakpoint's hook function.
3011 (defun deactivate-breakpoint (breakpoint)
3012   (when (eq (breakpoint-status breakpoint) :active)
3013     (without-interrupts
3014      (let ((loc (breakpoint-what breakpoint)))
3015        (etypecase loc
3016          ((or compiled-code-location compiled-debug-fun)
3017           (deactivate-compiled-breakpoint breakpoint)
3018           (let ((other (breakpoint-unknown-return-partner breakpoint)))
3019             (when other
3020               (deactivate-compiled-breakpoint other))))
3021          ;; (There used to be more cases back before sbcl-0.7.0, when
3022          ;; we did special tricks to debug the IR1 interpreter.)
3023          ))))
3024   breakpoint)
3025
3026 (defun deactivate-compiled-breakpoint (breakpoint)
3027   (if (eq (breakpoint-kind breakpoint) :fun-end)
3028       (let ((starter (breakpoint-start-helper breakpoint)))
3029         (unless (find-if (lambda (bpt)
3030                            (and (not (eq bpt breakpoint))
3031                                 (eq (breakpoint-status bpt) :active)))
3032                          (breakpoint-%info starter))
3033           (deactivate-compiled-breakpoint starter)))
3034       (let* ((data (breakpoint-internal-data breakpoint))
3035              (bpts (delete breakpoint (breakpoint-data-breakpoints data))))
3036         (setf (breakpoint-internal-data breakpoint) nil)
3037         (setf (breakpoint-data-breakpoints data) bpts)
3038         (unless bpts
3039           (without-gcing
3040            (breakpoint-remove (get-lisp-obj-address
3041                                (breakpoint-data-component data))
3042                               (breakpoint-data-offset data)
3043                               (breakpoint-data-instruction data)))
3044           (delete-breakpoint-data data))))
3045   (setf (breakpoint-status breakpoint) :inactive)
3046   breakpoint)
3047 \f
3048 ;;;; BREAKPOINT-INFO
3049
3050 ;;; Return the user-maintained info associated with breakpoint. This
3051 ;;; is SETF'able.
3052 (defun breakpoint-info (breakpoint)
3053   (breakpoint-%info breakpoint))
3054 (defun %set-breakpoint-info (breakpoint value)
3055   (setf (breakpoint-%info breakpoint) value)
3056   (let ((other (breakpoint-unknown-return-partner breakpoint)))
3057     (when other
3058       (setf (breakpoint-%info other) value))))
3059 \f
3060 ;;;; BREAKPOINT-ACTIVE-P and DELETE-BREAKPOINT
3061
3062 (defun breakpoint-active-p (breakpoint)
3063   (ecase (breakpoint-status breakpoint)
3064     (:active t)
3065     ((:inactive :deleted) nil)))
3066
3067 ;;; Free system storage and remove computational overhead associated
3068 ;;; with breakpoint. After calling this, breakpoint is completely
3069 ;;; impotent and can never become active again.
3070 (defun delete-breakpoint (breakpoint)
3071   (let ((status (breakpoint-status breakpoint)))
3072     (unless (eq status :deleted)
3073       (when (eq status :active)
3074         (deactivate-breakpoint breakpoint))
3075       (setf (breakpoint-status breakpoint) :deleted)
3076       (let ((other (breakpoint-unknown-return-partner breakpoint)))
3077         (when other
3078           (setf (breakpoint-status other) :deleted)))
3079       (when (eq (breakpoint-kind breakpoint) :fun-end)
3080         (let* ((starter (breakpoint-start-helper breakpoint))
3081                (breakpoints (delete breakpoint
3082                                     (the list (breakpoint-info starter)))))
3083           (setf (breakpoint-info starter) breakpoints)
3084           (unless breakpoints
3085             (delete-breakpoint starter)
3086             (setf (compiled-debug-fun-end-starter
3087                    (breakpoint-what breakpoint))
3088                   nil))))))
3089   breakpoint)
3090 \f
3091 ;;;; C call out stubs
3092
3093 ;;; This actually installs the break instruction in the component. It
3094 ;;; returns the overwritten bits. You must call this in a context in
3095 ;;; which GC is disabled, so that Lisp doesn't move objects around
3096 ;;; that C is pointing to.
3097 (sb!alien:define-alien-routine "breakpoint_install" sb!alien:unsigned-int
3098   (code-obj sb!alien:unsigned-long)
3099   (pc-offset sb!alien:int))
3100
3101 ;;; This removes the break instruction and replaces the original
3102 ;;; instruction. You must call this in a context in which GC is disabled
3103 ;;; so Lisp doesn't move objects around that C is pointing to.
3104 (sb!alien:define-alien-routine "breakpoint_remove" sb!alien:void
3105   (code-obj sb!alien:unsigned-long)
3106   (pc-offset sb!alien:int)
3107   (old-inst sb!alien:unsigned-int))
3108
3109 (sb!alien:define-alien-routine "breakpoint_do_displaced_inst" sb!alien:void
3110   (scp (* os-context-t))
3111   (orig-inst sb!alien:unsigned-int))
3112
3113 ;;;; breakpoint handlers (layer between C and exported interface)
3114
3115 ;;; This maps components to a mapping of offsets to BREAKPOINT-DATAs.
3116 (defvar *component-breakpoint-offsets* (make-hash-table :test 'eq))
3117
3118 ;;; This returns the BREAKPOINT-DATA object associated with component cross
3119 ;;; offset. If none exists, this makes one, installs it, and returns it.
3120 (defun breakpoint-data (component offset &optional (create t))
3121   (flet ((install-breakpoint-data ()
3122            (when create
3123              (let ((data (make-breakpoint-data component offset)))
3124                (push (cons offset data)
3125                      (gethash component *component-breakpoint-offsets*))
3126                data))))
3127     (let ((offsets (gethash component *component-breakpoint-offsets*)))
3128       (if offsets
3129           (let ((data (assoc offset offsets)))
3130             (if data
3131                 (cdr data)
3132                 (install-breakpoint-data)))
3133           (install-breakpoint-data)))))
3134
3135 ;;; We use this when there are no longer any active breakpoints
3136 ;;; corresponding to DATA.
3137 (defun delete-breakpoint-data (data)
3138   (let* ((component (breakpoint-data-component data))
3139          (offsets (delete (breakpoint-data-offset data)
3140                           (gethash component *component-breakpoint-offsets*)
3141                           :key #'car)))
3142     (if offsets
3143         (setf (gethash component *component-breakpoint-offsets*) offsets)
3144         (remhash component *component-breakpoint-offsets*)))
3145   (values))
3146
3147 ;;; The C handler for interrupts calls this when it has a
3148 ;;; debugging-tool break instruction. This does *not* handle all
3149 ;;; breaks; for example, it does not handle breaks for internal
3150 ;;; errors.
3151 (defun handle-breakpoint (offset component signal-context)
3152   (let ((data (breakpoint-data component offset nil)))
3153     (unless data
3154       (error "unknown breakpoint in ~S at offset ~S"
3155               (debug-fun-name (debug-fun-from-pc component offset))
3156               offset))
3157     (let ((breakpoints (breakpoint-data-breakpoints data)))
3158       (if (or (null breakpoints)
3159               (eq (breakpoint-kind (car breakpoints)) :fun-end))
3160           (handle-fun-end-breakpoint-aux breakpoints data signal-context)
3161           (handle-breakpoint-aux breakpoints data
3162                                  offset component signal-context)))))
3163
3164 ;;; This holds breakpoint-datas while invoking the breakpoint hooks
3165 ;;; associated with that particular component and location. While they
3166 ;;; are executing, if we hit the location again, we ignore the
3167 ;;; breakpoint to avoid infinite recursion. fun-end breakpoints
3168 ;;; must work differently since the breakpoint-data is unique for each
3169 ;;; invocation.
3170 (defvar *executing-breakpoint-hooks* nil)
3171
3172 ;;; This handles code-location and DEBUG-FUN :FUN-START
3173 ;;; breakpoints.
3174 (defun handle-breakpoint-aux (breakpoints data offset component signal-context)
3175   (unless breakpoints
3176     (bug "breakpoint that nobody wants"))
3177   (unless (member data *executing-breakpoint-hooks*)
3178     (let ((*executing-breakpoint-hooks* (cons data
3179                                               *executing-breakpoint-hooks*)))
3180       (invoke-breakpoint-hooks breakpoints signal-context)))
3181   ;; At this point breakpoints may not hold the same list as
3182   ;; BREAKPOINT-DATA-BREAKPOINTS since invoking hooks may have allowed
3183   ;; a breakpoint deactivation. In fact, if all breakpoints were
3184   ;; deactivated then data is invalid since it was deleted and so the
3185   ;; correct one must be looked up if it is to be used. If there are
3186   ;; no more breakpoints active at this location, then the normal
3187   ;; instruction has been put back, and we do not need to
3188   ;; DO-DISPLACED-INST.
3189   (setf data (breakpoint-data component offset nil))
3190   (when (and data (breakpoint-data-breakpoints data))
3191     ;; The breakpoint is still active, so we need to execute the
3192     ;; displaced instruction and leave the breakpoint instruction
3193     ;; behind. The best way to do this is different on each machine,
3194     ;; so we just leave it up to the C code.
3195     (breakpoint-do-displaced-inst signal-context
3196                                   (breakpoint-data-instruction data))
3197     ;; Some platforms have no usable sigreturn() call.  If your
3198     ;; implementation of arch_do_displaced_inst() _does_ sigreturn(),
3199     ;; it's polite to warn here
3200     #!+(and sparc solaris)
3201     (error "BREAKPOINT-DO-DISPLACED-INST returned?")))
3202
3203 (defun invoke-breakpoint-hooks (breakpoints signal-context)
3204   (let* ((frame (signal-context-frame signal-context)))
3205     (dolist (bpt breakpoints)
3206       (funcall (breakpoint-hook-fun bpt)
3207                frame
3208                ;; If this is an :UNKNOWN-RETURN-PARTNER, then pass the
3209                ;; hook function the original breakpoint, so that users
3210                ;; aren't forced to confront the fact that some
3211                ;; breakpoints really are two.
3212                (if (eq (breakpoint-kind bpt) :unknown-return-partner)
3213                    (breakpoint-unknown-return-partner bpt)
3214                    bpt)))))
3215
3216 (defun signal-context-frame (signal-context)
3217   (let* ((scp
3218           (locally
3219             (declare (optimize (inhibit-warnings 3)))
3220             (sb!alien:sap-alien signal-context (* os-context-t))))
3221          (cfp (int-sap (sb!vm:context-register scp sb!vm::cfp-offset))))
3222     (compute-calling-frame cfp
3223                            (sb!vm:context-pc scp)
3224                            nil)))
3225
3226 (defun handle-fun-end-breakpoint (offset component context)
3227   (let ((data (breakpoint-data component offset nil)))
3228     (unless data
3229       (error "unknown breakpoint in ~S at offset ~S"
3230               (debug-fun-name (debug-fun-from-pc component offset))
3231               offset))
3232     (let ((breakpoints (breakpoint-data-breakpoints data)))
3233       (when breakpoints
3234         (aver (eq (breakpoint-kind (car breakpoints)) :fun-end))
3235         (handle-fun-end-breakpoint-aux breakpoints data context)))))
3236
3237 ;;; Either HANDLE-BREAKPOINT calls this for :FUN-END breakpoints
3238 ;;; [old C code] or HANDLE-FUN-END-BREAKPOINT calls this directly
3239 ;;; [new C code].
3240 (defun handle-fun-end-breakpoint-aux (breakpoints data signal-context)
3241   (delete-breakpoint-data data)
3242   (let* ((scp
3243           (locally
3244             (declare (optimize (inhibit-warnings 3)))
3245             (sb!alien:sap-alien signal-context (* os-context-t))))
3246          (frame (signal-context-frame signal-context))
3247          (component (breakpoint-data-component data))
3248          (cookie (gethash component *fun-end-cookies*)))
3249     (remhash component *fun-end-cookies*)
3250     (dolist (bpt breakpoints)
3251       (funcall (breakpoint-hook-fun bpt)
3252                frame bpt
3253                (get-fun-end-breakpoint-values scp)
3254                cookie))))
3255
3256 (defun get-fun-end-breakpoint-values (scp)
3257   (let ((ocfp (int-sap (sb!vm:context-register
3258                         scp
3259                         #!-(or x86 x86-64) sb!vm::ocfp-offset
3260                         #!+(or x86 x86-64) sb!vm::ebx-offset)))
3261         (nargs (make-lisp-obj
3262                 (sb!vm:context-register scp sb!vm::nargs-offset)))
3263         (reg-arg-offsets '#.sb!vm::*register-arg-offsets*)
3264         (results nil))
3265     (without-gcing
3266      (dotimes (arg-num nargs)
3267        (push (if reg-arg-offsets
3268                  (make-lisp-obj
3269                   (sb!vm:context-register scp (pop reg-arg-offsets)))
3270                (stack-ref ocfp arg-num))
3271              results)))
3272     (nreverse results)))
3273 \f
3274 ;;;; MAKE-BOGUS-LRA (used for :FUN-END breakpoints)
3275
3276 (defconstant bogus-lra-constants
3277   #!-(or x86 x86-64) 2 #!+(or x86 x86-64) 3)
3278 (defconstant known-return-p-slot
3279   (+ sb!vm:code-constants-offset #!-(or x86 x86-64) 1 #!+(or x86 x86-64) 2))
3280
3281 ;;; Make a bogus LRA object that signals a breakpoint trap when
3282 ;;; returned to. If the breakpoint trap handler returns, REAL-LRA is
3283 ;;; returned to. Three values are returned: the bogus LRA object, the
3284 ;;; code component it is part of, and the PC offset for the trap
3285 ;;; instruction.
3286 (defun make-bogus-lra (real-lra &optional known-return-p)
3287   (without-gcing
3288    ;; These are really code labels, not variables: but this way we get
3289    ;; their addresses.
3290    (let* ((src-start (foreign-symbol-sap "fun_end_breakpoint_guts"))
3291           (src-end (foreign-symbol-sap "fun_end_breakpoint_end"))
3292           (trap-loc (foreign-symbol-sap "fun_end_breakpoint_trap"))
3293           (length (sap- src-end src-start))
3294           (code-object
3295            (%primitive sb!c:allocate-code-object (1+ bogus-lra-constants)
3296                        length))
3297           (dst-start (code-instructions code-object)))
3298      (declare (type system-area-pointer
3299                     src-start src-end dst-start trap-loc)
3300               (type index length))
3301      (setf (%code-debug-info code-object) :bogus-lra)
3302      (setf (code-header-ref code-object sb!vm:code-trace-table-offset-slot)
3303            length)
3304      #!-(or x86 x86-64)
3305      (setf (code-header-ref code-object real-lra-slot) real-lra)
3306      #!+(or x86 x86-64)
3307      (multiple-value-bind (offset code) (compute-lra-data-from-pc real-lra)
3308        (setf (code-header-ref code-object real-lra-slot) code)
3309        (setf (code-header-ref code-object (1+ real-lra-slot)) offset))
3310      (setf (code-header-ref code-object known-return-p-slot)
3311            known-return-p)
3312      (system-area-ub8-copy src-start 0 dst-start 0 length)
3313      (sb!vm:sanctify-for-execution code-object)
3314      #!+(or x86 x86-64)
3315      (values dst-start code-object (sap- trap-loc src-start))
3316      #!-(or x86 x86-64)
3317      (let ((new-lra (make-lisp-obj (+ (sap-int dst-start)
3318                                       sb!vm:other-pointer-lowtag))))
3319        (set-header-data
3320         new-lra
3321         (logandc2 (+ sb!vm:code-constants-offset bogus-lra-constants 1)
3322                   1))
3323        (sb!vm:sanctify-for-execution code-object)
3324        (values new-lra code-object (sap- trap-loc src-start))))))
3325 \f
3326 ;;;; miscellaneous
3327
3328 ;;; This appears here because it cannot go with the DEBUG-FUN
3329 ;;; interface since DO-DEBUG-BLOCK-LOCATIONS isn't defined until after
3330 ;;; the DEBUG-FUN routines.
3331
3332 ;;; Return a code-location before the body of a function and after all
3333 ;;; the arguments are in place; or if that location can't be
3334 ;;; determined due to a lack of debug information, return NIL.
3335 (defun debug-fun-start-location (debug-fun)
3336   (etypecase debug-fun
3337     (compiled-debug-fun
3338      (code-location-from-pc debug-fun
3339                             (sb!c::compiled-debug-fun-start-pc
3340                              (compiled-debug-fun-compiler-debug-fun
3341                               debug-fun))
3342                             nil))
3343     ;; (There used to be more cases back before sbcl-0.7.0, when
3344     ;; we did special tricks to debug the IR1 interpreter.)
3345     ))
3346
3347 \f
3348 ;;;; Single-stepping
3349
3350 ;;; The single-stepper works by inserting conditional trap instructions
3351 ;;; into the generated code (see src/compiler/*/call.lisp), currently:
3352 ;;;
3353 ;;;   1) Before the code generated for a function call that was
3354 ;;;      translated to a VOP
3355 ;;;   2) Just before the call instruction for a full call
3356 ;;;
3357 ;;; In both cases, the trap will only be executed if stepping has been
3358 ;;; enabled, in which case it'll ultimately be handled by
3359 ;;; HANDLE-SINGLE-STEP-TRAP, which will either signal a stepping condition,
3360 ;;; or replace the function that's about to be called with a wrapper
3361 ;;; which will signal the condition.
3362
3363 (defun handle-single-step-trap (context-sap kind callee-register-offset)
3364   (let ((context (sb!alien:sap-alien context-sap (* os-context-t))))
3365     ;; The following calls must get tail-call eliminated for
3366     ;; *STEP-FRAME* to get set correctly on non-x86.
3367     (if (= kind single-step-before-trap)
3368         (handle-single-step-before-trap context)
3369         (handle-single-step-around-trap context callee-register-offset))))
3370
3371 (defvar *step-frame* nil)
3372
3373 (defun handle-single-step-before-trap (context)
3374   (let ((step-info (single-step-info-from-context context)))
3375     ;; If there was not enough debug information available, there's no
3376     ;; sense in signaling the condition.
3377     (when step-info
3378       (let ((*step-frame*
3379              #+(or x86 x86-64)
3380              (signal-context-frame (sb!alien::alien-sap context))
3381              #-(or x86 x86-64)
3382              ;; KLUDGE: Use the first non-foreign frame as the
3383              ;; *STACK-TOP-HINT*. Getting the frame from the signal
3384              ;; context as on x86 would be cleaner, but
3385              ;; SIGNAL-CONTEXT-FRAME doesn't seem seem to work at all
3386              ;; on non-x86.
3387              (loop with frame = (frame-down (top-frame))
3388                    while frame
3389                    for dfun = (frame-debug-fun frame)
3390                    do (when (typep dfun 'compiled-debug-fun)
3391                         (return frame))
3392                    do (setf frame (frame-down frame)))))
3393         (sb!impl::step-form step-info
3394                             ;; We could theoretically store information in
3395                             ;; the debug-info about to determine the
3396                             ;; arguments here, but for now let's just pass
3397                             ;; on it.
3398                             :unknown)))))
3399
3400 ;;; This function will replace the fdefn / function that was in the
3401 ;;; register at CALLEE-REGISTER-OFFSET with a wrapper function. To
3402 ;;; ensure that the full call will use the wrapper instead of the
3403 ;;; original, conditional trap must be emitted before the fdefn /
3404 ;;; function is converted into a raw address.
3405 (defun handle-single-step-around-trap (context callee-register-offset)
3406   ;; Fetch the function / fdefn we're about to call from the
3407   ;; appropriate register.
3408   (let* ((callee (sb!kernel::make-lisp-obj
3409                   (context-register context callee-register-offset)))
3410          (step-info (single-step-info-from-context context)))
3411     ;; If there was not enough debug information available, there's no
3412     ;; sense in signaling the condition.
3413     (unless step-info
3414       (return-from handle-single-step-around-trap))
3415     (let* ((fun (lambda (&rest args)
3416                   (flet ((call ()
3417                            (apply (typecase callee
3418                                     (fdefn (fdefn-fun callee))
3419                                     (function callee))
3420                                   args)))
3421                     ;; Signal a step condition
3422                     (let* ((step-in
3423                             (let ((*step-frame* (frame-down (top-frame))))
3424                               (sb!impl::step-form step-info args))))
3425                       ;; And proceed based on its return value.
3426                       (if step-in
3427                           ;; STEP-INTO was selected. Use *STEP-OUT* to
3428                           ;; let the stepper know that selecting the
3429                           ;; STEP-OUT restart is valid inside this
3430                           (let ((sb!impl::*step-out* :maybe))
3431                             ;; Pass the return values of the call to
3432                             ;; STEP-VALUES, which will signal a
3433                             ;; condition with them in the VALUES slot.
3434                             (unwind-protect
3435                                  (multiple-value-call #'sb!impl::step-values
3436                                    step-info
3437                                    (call))
3438                               ;; If the user selected the STEP-OUT
3439                               ;; restart during the call, resume
3440                               ;; stepping
3441                               (when (eq sb!impl::*step-out* t)
3442                                 (sb!impl::enable-stepping))))
3443                           ;; STEP-NEXT / CONTINUE / OUT selected:
3444                           ;; Disable the stepper for the duration of
3445                           ;; the call.
3446                           (sb!impl::with-stepping-disabled
3447                             (call)))))))
3448            (new-callee (etypecase callee
3449                          (fdefn
3450                           (let ((fdefn (make-fdefn (gensym))))
3451                             (setf (fdefn-fun fdefn) fun)
3452                             fdefn))
3453                          (function fun))))
3454       ;; And then store the wrapper in the same place.
3455       (setf (context-register context callee-register-offset)
3456             (get-lisp-obj-address new-callee)))))
3457
3458 ;;; Given a signal context, fetch the step-info that's been stored in
3459 ;;; the debug info at the trap point.
3460 (defun single-step-info-from-context (context)
3461   (multiple-value-bind (pc-offset code)
3462       (compute-lra-data-from-pc (context-pc context))
3463     (let* ((debug-fun (debug-fun-from-pc code pc-offset))
3464            (location (code-location-from-pc debug-fun
3465                                             pc-offset
3466                                             nil)))
3467       (handler-case
3468           (progn
3469             (fill-in-code-location location)
3470             (code-location-debug-source location)
3471             (compiled-code-location-step-info location))
3472         (debug-condition ()
3473           nil)))))
3474
3475 ;;; Return the frame that triggered a single-step condition. Used to
3476 ;;; provide a *STACK-TOP-HINT*.
3477 (defun find-stepped-frame ()
3478   (or *step-frame*
3479       (top-frame)))