1.0.11.14: thread-safe FORM-NUMBER-TRANSLATIONS
[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 \f
324 ;;;; DEBUG-BLOCKs
325
326 ;;; These exist for caching data stored in packed binary form in compiler
327 ;;; DEBUG-BLOCKs.
328 (defstruct (debug-block (:constructor nil)
329                         (:copier nil))
330   ;; Code-locations where execution continues after this block.
331   (successors nil :type list)
332   ;; This indicates whether the block is a special glob of code shared
333   ;; by various functions and tucked away elsewhere in a component.
334   ;; This kind of block has no start code-location. This slot is in
335   ;; all debug-blocks since it is an exported interface.
336   (elsewhere-p nil :type boolean))
337 (def!method print-object ((obj debug-block) str)
338   (print-unreadable-object (obj str :type t)
339     (prin1 (debug-block-fun-name obj) str)))
340
341 #!+sb-doc
342 (setf (fdocumentation 'debug-block-successors 'function)
343   "Return the list of possible code-locations where execution may continue
344    when the basic-block represented by debug-block completes its execution.")
345
346 #!+sb-doc
347 (setf (fdocumentation 'debug-block-elsewhere-p 'function)
348   "Return whether debug-block represents elsewhere code.")
349
350 (defstruct (compiled-debug-block (:include debug-block)
351                                  (:constructor
352                                   make-compiled-debug-block
353                                   (code-locations successors elsewhere-p))
354                                  (:copier nil))
355   ;; code-location information for the block
356   (code-locations nil :type simple-vector))
357 \f
358 ;;;; breakpoints
359
360 ;;; This is an internal structure that manages information about a
361 ;;; breakpoint locations. See *COMPONENT-BREAKPOINT-OFFSETS*.
362 (defstruct (breakpoint-data (:constructor make-breakpoint-data
363                                           (component offset))
364                             (:copier nil))
365   ;; This is the component in which the breakpoint lies.
366   component
367   ;; This is the byte offset into the component.
368   (offset nil :type index)
369   ;; The original instruction replaced by the breakpoint.
370   (instruction nil :type (or null sb!vm::word))
371   ;; A list of user breakpoints at this location.
372   (breakpoints nil :type list))
373 (def!method print-object ((obj breakpoint-data) str)
374   (print-unreadable-object (obj str :type t)
375     (format str "~S at ~S"
376             (debug-fun-name
377              (debug-fun-from-pc (breakpoint-data-component obj)
378                                 (breakpoint-data-offset obj)))
379             (breakpoint-data-offset obj))))
380
381 (defstruct (breakpoint (:constructor %make-breakpoint
382                                      (hook-fun what kind %info))
383                        (:copier nil))
384   ;; This is the function invoked when execution encounters the
385   ;; breakpoint. It takes a frame, the breakpoint, and optionally a
386   ;; list of values. Values are supplied for :FUN-END breakpoints as
387   ;; values to return for the function containing the breakpoint.
388   ;; :FUN-END breakpoint hook functions also take a cookie argument.
389   ;; See the COOKIE-FUN slot.
390   (hook-fun (required-arg) :type function)
391   ;; CODE-LOCATION or DEBUG-FUN
392   (what nil :type (or code-location debug-fun))
393   ;; :CODE-LOCATION, :FUN-START, or :FUN-END for that kind
394   ;; of breakpoint. :UNKNOWN-RETURN-PARTNER if this is the partner of
395   ;; a :code-location breakpoint at an :UNKNOWN-RETURN code-location.
396   (kind nil :type (member :code-location :fun-start :fun-end
397                           :unknown-return-partner))
398   ;; Status helps the user and the implementation.
399   (status :inactive :type (member :active :inactive :deleted))
400   ;; This is a backpointer to a breakpoint-data.
401   (internal-data nil :type (or null breakpoint-data))
402   ;; With code-locations whose type is :UNKNOWN-RETURN, there are
403   ;; really two breakpoints: one at the multiple-value entry point,
404   ;; and one at the single-value entry point. This slot holds the
405   ;; breakpoint for the other one, or NIL if this isn't at an
406   ;; :UNKNOWN-RETURN code location.
407   (unknown-return-partner nil :type (or null breakpoint))
408   ;; :FUN-END breakpoints use a breakpoint at the :FUN-START
409   ;; to establish the end breakpoint upon function entry. We do this
410   ;; by frobbing the LRA to jump to a special piece of code that
411   ;; breaks and provides the return values for the returnee. This slot
412   ;; points to the start breakpoint, so we can activate, deactivate,
413   ;; and delete it.
414   (start-helper nil :type (or null breakpoint))
415   ;; This is a hook users supply to get a dynamically unique cookie
416   ;; for identifying :FUN-END breakpoint executions. That is, if
417   ;; there is one :FUN-END breakpoint, but there may be multiple
418   ;; pending calls of its function on the stack. This function takes
419   ;; the cookie, and the hook function takes the cookie too.
420   (cookie-fun nil :type (or null function))
421   ;; This slot users can set with whatever information they find useful.
422   %info)
423 (def!method print-object ((obj breakpoint) str)
424   (let ((what (breakpoint-what obj)))
425     (print-unreadable-object (obj str :type t)
426       (format str
427               "~S~:[~;~:*~S~]"
428               (etypecase what
429                 (code-location what)
430                 (debug-fun (debug-fun-name what)))
431               (etypecase what
432                 (code-location nil)
433                 (debug-fun (breakpoint-kind obj)))))))
434 \f
435 ;;;; CODE-LOCATIONs
436
437 (defstruct (code-location (:constructor nil)
438                           (:copier nil))
439   ;; the DEBUG-FUN containing this CODE-LOCATION
440   (debug-fun nil :type debug-fun)
441   ;; This is initially :UNSURE. Upon first trying to access an
442   ;; :UNPARSED slot, if the data is unavailable, then this becomes T,
443   ;; and the code-location is unknown. If the data is available, this
444   ;; becomes NIL, a known location. We can't use a separate type
445   ;; code-location for this since we must return code-locations before
446   ;; we can tell whether they're known or unknown. For example, when
447   ;; parsing the stack, we don't want to unpack all the variables and
448   ;; blocks just to make frames.
449   (%unknown-p :unsure :type (member t nil :unsure))
450   ;; the DEBUG-BLOCK containing CODE-LOCATION. XXX Possibly toss this
451   ;; out and just find it in the blocks cache in DEBUG-FUN.
452   (%debug-block :unparsed :type (or debug-block (member :unparsed)))
453   ;; This is the number of forms processed by the compiler or loader
454   ;; before the top level form containing this code-location.
455   (%tlf-offset :unparsed :type (or index (member :unparsed)))
456   ;; This is the depth-first number of the node that begins
457   ;; code-location within its top level form.
458   (%form-number :unparsed :type (or index (member :unparsed))))
459 (def!method print-object ((obj code-location) str)
460   (print-unreadable-object (obj str :type t)
461     (prin1 (debug-fun-name (code-location-debug-fun obj))
462            str)))
463
464 (defstruct (compiled-code-location
465              (:include code-location)
466              (:constructor make-known-code-location
467                            (pc debug-fun %tlf-offset %form-number
468                                %live-set kind step-info &aux (%unknown-p nil)))
469              (:constructor make-compiled-code-location (pc debug-fun))
470              (:copier nil))
471   ;; an index into DEBUG-FUN's component slot
472   (pc nil :type index)
473   ;; a bit-vector indexed by a variable's position in
474   ;; DEBUG-FUN-DEBUG-VARS indicating whether the variable has a
475   ;; valid value at this code-location. (unexported).
476   (%live-set :unparsed :type (or simple-bit-vector (member :unparsed)))
477   ;; (unexported) To see SB!C::LOCATION-KIND, do
478   ;; (SB!KERNEL:TYPE-EXPAND 'SB!C::LOCATION-KIND).
479   (kind :unparsed :type (or (member :unparsed) sb!c::location-kind))
480   (step-info :unparsed :type (or (member :unparsed :foo) simple-string)))
481 \f
482 ;;;; DEBUG-SOURCEs
483
484 ;;; Return the number of top level forms processed by the compiler
485 ;;; before compiling this source. If this source is uncompiled, this
486 ;;; is zero. This may be zero even if the source is compiled since the
487 ;;; first form in the first file compiled in one compilation, for
488 ;;; example, must have a root number of zero -- the compiler saw no
489 ;;; other top level forms before it.
490 (defun debug-source-root-number (debug-source)
491   (sb!c::debug-source-source-root debug-source))
492 \f
493 ;;;; frames
494
495 ;;; This is used in FIND-ESCAPED-FRAME and with the bogus components
496 ;;; and LRAs used for :FUN-END breakpoints. When a component's
497 ;;; debug-info slot is :BOGUS-LRA, then the REAL-LRA-SLOT contains the
498 ;;; real component to continue executing, as opposed to the bogus
499 ;;; component which appeared in some frame's LRA location.
500 (defconstant real-lra-slot sb!vm:code-constants-offset)
501
502 ;;; These are magically converted by the compiler.
503 (defun current-sp () (current-sp))
504 (defun current-fp () (current-fp))
505 (defun stack-ref (s n) (stack-ref s n))
506 (defun %set-stack-ref (s n value) (%set-stack-ref s n value))
507 (defun fun-code-header (fun) (fun-code-header fun))
508 (defun lra-code-header (lra) (lra-code-header lra))
509 (defun %make-lisp-obj (value) (%make-lisp-obj value))
510 (defun get-lisp-obj-address (thing) (get-lisp-obj-address thing))
511 (defun fun-word-offset (fun) (fun-word-offset fun))
512
513 #!-sb-fluid (declaim (inline control-stack-pointer-valid-p))
514 (defun control-stack-pointer-valid-p (x)
515   (declare (type system-area-pointer x))
516   (let* (#!-stack-grows-downward-not-upward
517          (control-stack-start
518           (descriptor-sap *control-stack-start*))
519          #!+stack-grows-downward-not-upward
520          (control-stack-end
521           (descriptor-sap *control-stack-end*)))
522     #!-stack-grows-downward-not-upward
523     (and (sap< x (current-sp))
524          (sap<= control-stack-start x)
525          (zerop (logand (sap-int x) sb!vm:fixnum-tag-mask)))
526     #!+stack-grows-downward-not-upward
527     (and (sap>= x (current-sp))
528          (sap> control-stack-end x)
529          (zerop (logand (sap-int x) sb!vm:fixnum-tag-mask)))))
530
531 (declaim (inline component-ptr-from-pc))
532 (sb!alien:define-alien-routine component-ptr-from-pc (system-area-pointer)
533   (pc system-area-pointer))
534
535 #!+(or x86 x86-64)
536 (sb!alien:define-alien-routine valid-lisp-pointer-p sb!alien:int
537   (pointer 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 ;;; Return the top frame of the control stack as it was before calling
658 ;;; this function.
659 (defun top-frame ()
660   (/noshow0 "entering TOP-FRAME")
661   (multiple-value-bind (fp pc) (%caller-frame-and-pc)
662     (compute-calling-frame (descriptor-sap fp) pc nil)))
663
664 ;;; Flush all of the frames above FRAME, and renumber all the frames
665 ;;; below FRAME.
666 (defun flush-frames-above (frame)
667   (setf (frame-up frame) nil)
668   (do ((number 0 (1+ number))
669        (frame frame (frame-%down frame)))
670       ((not (frame-p frame)))
671     (setf (frame-number frame) number)))
672
673 ;;; Return the frame immediately below FRAME on the stack; or when
674 ;;; FRAME is the bottom of the stack, return NIL.
675 (defun frame-down (frame)
676   (/noshow0 "entering FRAME-DOWN")
677   ;; We have to access the old-fp and return-pc out of frame and pass
678   ;; them to COMPUTE-CALLING-FRAME.
679   (let ((down (frame-%down frame)))
680     (if (eq down :unparsed)
681         (let ((debug-fun (frame-debug-fun frame)))
682           (/noshow0 "in DOWN :UNPARSED case")
683           (setf (frame-%down frame)
684                 (etypecase debug-fun
685                   (compiled-debug-fun
686                    (let ((c-d-f (compiled-debug-fun-compiler-debug-fun
687                                  debug-fun)))
688                      (compute-calling-frame
689                       (descriptor-sap
690                        (get-context-value
691                         frame ocfp-save-offset
692                         (sb!c::compiled-debug-fun-old-fp c-d-f)))
693                       (get-context-value
694                        frame lra-save-offset
695                        (sb!c::compiled-debug-fun-return-pc c-d-f))
696                       frame)))
697                   (bogus-debug-fun
698                    (let ((fp (frame-pointer frame)))
699                      (when (control-stack-pointer-valid-p fp)
700                        #!+(or x86 x86-64)
701                        (multiple-value-bind (ok ra ofp) (x86-call-context fp)
702                          (and ok
703                               (compute-calling-frame ofp ra frame)))
704                        #!-(or x86 x86-64)
705                        (compute-calling-frame
706                         #!-alpha
707                         (sap-ref-sap fp (* ocfp-save-offset
708                                            sb!vm:n-word-bytes))
709                         #!+alpha
710                         (int-sap
711                          (sap-ref-32 fp (* ocfp-save-offset
712                                            sb!vm:n-word-bytes)))
713
714                         (stack-ref fp lra-save-offset)
715
716                         frame)))))))
717         down)))
718
719 ;;; Get the old FP or return PC out of FRAME. STACK-SLOT is the
720 ;;; standard save location offset on the stack. LOC is the saved
721 ;;; SC-OFFSET describing the main location.
722 (defun get-context-value (frame stack-slot loc)
723   (declare (type compiled-frame frame) (type unsigned-byte stack-slot)
724            (type sb!c:sc-offset loc))
725   (let ((pointer (frame-pointer frame))
726         (escaped (compiled-frame-escaped frame)))
727     (if escaped
728         (sub-access-debug-var-slot pointer loc escaped)
729         #!-(or x86 x86-64)
730         (stack-ref pointer stack-slot)
731         #!+(or x86 x86-64)
732         (ecase stack-slot
733           (#.ocfp-save-offset
734            (stack-ref pointer stack-slot))
735           (#.lra-save-offset
736            (sap-ref-sap pointer (- (* (1+ stack-slot)
737                                       sb!vm::n-word-bytes))))))))
738
739 (defun (setf get-context-value) (value frame stack-slot loc)
740   (declare (type compiled-frame frame) (type unsigned-byte stack-slot)
741            (type sb!c:sc-offset loc))
742   (let ((pointer (frame-pointer frame))
743         (escaped (compiled-frame-escaped frame)))
744     (if escaped
745         (sub-set-debug-var-slot pointer loc value escaped)
746         #!-(or x86 x86-64)
747         (setf (stack-ref pointer stack-slot) value)
748         #!+(or x86 x86-64)
749         (ecase stack-slot
750           (#.ocfp-save-offset
751            (setf (stack-ref pointer stack-slot) value))
752           (#.lra-save-offset
753            (setf (sap-ref-sap pointer (- (* (1+ stack-slot)
754                                             sb!vm::n-word-bytes))) value))))))
755
756 (defun foreign-function-backtrace-name (sap)
757   (let ((name (sap-foreign-symbol sap)))
758     (if name
759         (format nil "foreign function: ~A" name)
760         (format nil "foreign function: #x~X" (sap-int sap)))))
761
762 ;;; This returns a frame for the one existing in time immediately
763 ;;; prior to the frame referenced by current-fp. This is current-fp's
764 ;;; caller or the next frame down the control stack. If there is no
765 ;;; down frame, this returns NIL for the bottom of the stack. UP-FRAME
766 ;;; is the up link for the resulting frame object, and it is null when
767 ;;; we call this to get the top of the stack.
768 ;;;
769 ;;; The current frame contains the pointer to the temporally previous
770 ;;; frame we want, and the current frame contains the pc at which we
771 ;;; will continue executing upon returning to that previous frame.
772 ;;;
773 ;;; Note: Sometimes LRA is actually a fixnum. This happens when lisp
774 ;;; calls into C. In this case, the code object is stored on the stack
775 ;;; after the LRA, and the LRA is the word offset.
776 #!-(or x86 x86-64)
777 (defun compute-calling-frame (caller lra up-frame)
778   (declare (type system-area-pointer caller))
779   (/noshow0 "entering COMPUTE-CALLING-FRAME")
780   (when (control-stack-pointer-valid-p caller)
781     (/noshow0 "in WHEN")
782     (multiple-value-bind (code pc-offset escaped)
783         (if lra
784             (multiple-value-bind (word-offset code)
785                 (if (fixnump lra)
786                     (let ((fp (frame-pointer up-frame)))
787                       (values lra
788                               (stack-ref fp (1+ lra-save-offset))))
789                     (values (get-header-data lra)
790                             (lra-code-header lra)))
791               (if code
792                   (values code
793                           (* (1+ (- word-offset (get-header-data code)))
794                              sb!vm:n-word-bytes)
795                           nil)
796                   (values :foreign-function
797                           0
798                           nil)))
799             (find-escaped-frame caller))
800       (if (and (code-component-p code)
801                (eq (%code-debug-info code) :bogus-lra))
802           (let ((real-lra (code-header-ref code real-lra-slot)))
803             (compute-calling-frame caller real-lra up-frame))
804           (let ((d-fun (case code
805                          (:undefined-function
806                           (make-bogus-debug-fun
807                            "undefined function"))
808                          (:foreign-function
809                           (make-bogus-debug-fun
810                            (foreign-function-backtrace-name
811                             (int-sap (get-lisp-obj-address lra)))))
812                          ((nil)
813                           (make-bogus-debug-fun
814                            "bogus stack frame"))
815                          (t
816                           (debug-fun-from-pc code pc-offset)))))
817             (/noshow0 "returning MAKE-COMPILED-FRAME from COMPUTE-CALLING-FRAME")
818             (make-compiled-frame caller up-frame d-fun
819                                  (code-location-from-pc d-fun pc-offset
820                                                         escaped)
821                                  (if up-frame (1+ (frame-number up-frame)) 0)
822                                  escaped))))))
823
824 #!+(or x86 x86-64)
825 (defun compute-calling-frame (caller ra up-frame)
826   (declare (type system-area-pointer caller ra))
827   (/noshow0 "entering COMPUTE-CALLING-FRAME")
828   (when (control-stack-pointer-valid-p caller)
829     (/noshow0 "in WHEN")
830     ;; First check for an escaped frame.
831     (multiple-value-bind (code pc-offset escaped) (find-escaped-frame caller)
832       (/noshow0 "at COND")
833       (cond (code
834              ;; If it's escaped it may be a function end breakpoint trap.
835              (when (and (code-component-p code)
836                         (eq (%code-debug-info code) :bogus-lra))
837                ;; If :bogus-lra grab the real lra.
838                (setq pc-offset (code-header-ref
839                                 code (1+ real-lra-slot)))
840                (setq code (code-header-ref code real-lra-slot))
841                (aver code)))
842             ((not escaped)
843              (multiple-value-setq (pc-offset code)
844                (compute-lra-data-from-pc ra))
845              (unless code
846                (setf code :foreign-function
847                      pc-offset 0))))
848       (let ((d-fun (case code
849                      (:undefined-function
850                       (make-bogus-debug-fun
851                        "undefined function"))
852                      (:foreign-function
853                       (make-bogus-debug-fun
854                        (foreign-function-backtrace-name ra)))
855                      ((nil)
856                       (make-bogus-debug-fun
857                        "bogus stack frame"))
858                      (t
859                       (debug-fun-from-pc code pc-offset)))))
860         (/noshow0 "returning MAKE-COMPILED-FRAME from COMPUTE-CALLING-FRAME")
861         (make-compiled-frame caller up-frame d-fun
862                              (code-location-from-pc d-fun pc-offset
863                                                     escaped)
864                              (if up-frame (1+ (frame-number up-frame)) 0)
865                              escaped)))))
866
867 (defun nth-interrupt-context (n)
868   (declare (type (unsigned-byte 32) n)
869            (optimize (speed 3) (safety 0)))
870   (sb!alien:sap-alien (sb!vm::current-thread-offset-sap
871                        (+ sb!vm::thread-interrupt-contexts-offset n))
872                       (* os-context-t)))
873
874 #!+(or x86 x86-64)
875 (defun find-escaped-frame (frame-pointer)
876   (declare (type system-area-pointer frame-pointer))
877   (/noshow0 "entering FIND-ESCAPED-FRAME")
878   (dotimes (index *free-interrupt-context-index* (values nil 0 nil))
879       (/noshow0 "at head of WITH-ALIEN")
880     (let ((context (nth-interrupt-context index)))
881         (/noshow0 "got CONTEXT")
882         (when (= (sap-int frame-pointer)
883                  (sb!vm:context-register context sb!vm::cfp-offset))
884           (without-gcing
885            (/noshow0 "in WITHOUT-GCING")
886            (let* ((component-ptr (component-ptr-from-pc
887                                   (sb!vm:context-pc context)))
888                   (code (unless (sap= component-ptr (int-sap #x0))
889                           (component-from-component-ptr component-ptr))))
890              (/noshow0 "got CODE")
891              (when (null code)
892                (return (values code 0 context)))
893              (let* ((code-header-len (* (get-header-data code)
894                                         sb!vm:n-word-bytes))
895                     (pc-offset
896                      (- (sap-int (sb!vm:context-pc context))
897                         (- (get-lisp-obj-address code)
898                            sb!vm:other-pointer-lowtag)
899                         code-header-len)))
900                (/noshow "got PC-OFFSET")
901                (unless (<= 0 pc-offset
902                            (* (code-header-ref code sb!vm:code-code-size-slot)
903                               sb!vm:n-word-bytes))
904                  ;; We were in an assembly routine. Therefore, use the
905                  ;; LRA as the pc.
906                  ;;
907                  ;; FIXME: Should this be WARN or ERROR or what?
908                  (format t "** pc-offset ~S not in code obj ~S?~%"
909                          pc-offset code))
910                (/noshow0 "returning from FIND-ESCAPED-FRAME")
911                (return
912                (values code pc-offset context)))))))))
913
914 #!-(or x86 x86-64)
915 (defun find-escaped-frame (frame-pointer)
916   (declare (type system-area-pointer frame-pointer))
917   (/noshow0 "entering FIND-ESCAPED-FRAME")
918   (dotimes (index *free-interrupt-context-index* (values nil 0 nil))
919       (/noshow0 "at head of WITH-ALIEN")
920     (let ((scp (nth-interrupt-context index)))
921         (/noshow0 "got SCP")
922       (when (= (sap-int frame-pointer)
923                (sb!vm:context-register scp sb!vm::cfp-offset))
924         (without-gcing
925          (/noshow0 "in WITHOUT-GCING")
926          (let ((code (code-object-from-bits
927                       (sb!vm:context-register scp sb!vm::code-offset))))
928            (/noshow0 "got CODE")
929            (when (symbolp code)
930              (return (values code 0 scp)))
931            (let* ((code-header-len (* (get-header-data code)
932                                       sb!vm:n-word-bytes))
933                   (pc-offset
934                    (- (sap-int (sb!vm:context-pc scp))
935                       (- (get-lisp-obj-address code)
936                          sb!vm:other-pointer-lowtag)
937                       code-header-len)))
938              (let ((code-size (* (code-header-ref code
939                                                   sb!vm:code-code-size-slot)
940                                  sb!vm:n-word-bytes)))
941                (unless (<= 0 pc-offset code-size)
942                  ;; We were in an assembly routine.
943                  (multiple-value-bind (new-pc-offset computed-return)
944                      (find-pc-from-assembly-fun code scp)
945                    (setf pc-offset new-pc-offset)
946                    (unless (<= 0 pc-offset code-size)
947                      (cerror
948                       "Set PC-OFFSET to zero and continue backtrace."
949                       'bug
950                       :format-control
951                       "~@<PC-OFFSET (~D) not in code object. Frame details:~
952                        ~2I~:@_PC: #X~X~:@_CODE: ~S~:@_CODE FUN: ~S~:@_LRA: ~
953                        #X~X~:@_COMPUTED RETURN: #X~X.~:>"
954                       :format-arguments
955                       (list pc-offset
956                             (sap-int (sb!vm:context-pc scp))
957                             code
958                             (%code-entry-points code)
959                             (sb!vm:context-register scp sb!vm::lra-offset)
960                             computed-return))
961                      ;; We failed to pinpoint where PC is, but set
962                      ;; pc-offset to 0 to keep the backtrace from
963                      ;; exploding.
964                      (setf pc-offset 0)))))
965              (/noshow0 "returning from FIND-ESCAPED-FRAME")
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 nil)))
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-lisp-obj (val &optional (errorp t))
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        #!+(or x86 x86-64)
2021        (not (zerop (valid-lisp-pointer-p (int-sap val))))
2022       ;; FIXME: There is no fundamental reason not to use the above
2023       ;; function on other platforms as well, but I didn't have
2024       ;; others available while doing this. --NS 2007-06-21
2025       #!-(or x86 x86-64)
2026       (and (logbitp 0 val)
2027            (or (< sb!vm:read-only-space-start val
2028                   (* sb!vm:*read-only-space-free-pointer*
2029                      sb!vm:n-word-bytes))
2030                (< sb!vm:static-space-start val
2031                   (* sb!vm:*static-space-free-pointer*
2032                      sb!vm:n-word-bytes))
2033                (< (current-dynamic-space-start) val
2034                   (sap-int (dynamic-space-free-pointer))))))
2035       (values (%make-lisp-obj val) t)
2036       (if errorp
2037           (error "~S is not a valid argument to ~S"
2038                  val 'make-lisp-obj)
2039           (values (make-unprintable-object (format nil "invalid object #x~X" val))
2040                   nil))))
2041
2042 #!-(or x86 x86-64)
2043 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2044   (macrolet ((with-escaped-value ((var) &body forms)
2045                `(if escaped
2046                     (let ((,var (sb!vm:context-register
2047                                  escaped
2048                                  (sb!c:sc-offset-offset sc-offset))))
2049                       ,@forms)
2050                     :invalid-value-for-unescaped-register-storage))
2051              (escaped-float-value (format)
2052                `(if escaped
2053                     (sb!vm:context-float-register
2054                      escaped
2055                      (sb!c:sc-offset-offset sc-offset)
2056                      ',format)
2057                     :invalid-value-for-unescaped-register-storage))
2058              (with-nfp ((var) &body body)
2059                `(let ((,var (if escaped
2060                                 (sb!sys:int-sap
2061                                  (sb!vm:context-register escaped
2062                                                          sb!vm::nfp-offset))
2063                                 #!-alpha
2064                                 (sb!sys:sap-ref-sap fp (* nfp-save-offset
2065                                                           sb!vm:n-word-bytes))
2066                                 #!+alpha
2067                                 (sb!vm::make-number-stack-pointer
2068                                  (sb!sys:sap-ref-32 fp (* nfp-save-offset
2069                                                           sb!vm:n-word-bytes))))))
2070                   ,@body)))
2071     (ecase (sb!c:sc-offset-scn sc-offset)
2072       ((#.sb!vm:any-reg-sc-number
2073         #.sb!vm:descriptor-reg-sc-number
2074         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2075        (sb!sys:without-gcing
2076         (with-escaped-value (val)
2077           (make-lisp-obj val nil))))
2078       (#.sb!vm:character-reg-sc-number
2079        (with-escaped-value (val)
2080          (code-char val)))
2081       (#.sb!vm:sap-reg-sc-number
2082        (with-escaped-value (val)
2083          (sb!sys:int-sap val)))
2084       (#.sb!vm:signed-reg-sc-number
2085        (with-escaped-value (val)
2086          (if (logbitp (1- sb!vm:n-word-bits) val)
2087              (logior val (ash -1 sb!vm:n-word-bits))
2088              val)))
2089       (#.sb!vm:unsigned-reg-sc-number
2090        (with-escaped-value (val)
2091          val))
2092       (#.sb!vm:non-descriptor-reg-sc-number
2093        (error "Local non-descriptor register access?"))
2094       (#.sb!vm:interior-reg-sc-number
2095        (error "Local interior register access?"))
2096       (#.sb!vm:single-reg-sc-number
2097        (escaped-float-value single-float))
2098       (#.sb!vm:double-reg-sc-number
2099        (escaped-float-value double-float))
2100       #!+long-float
2101       (#.sb!vm:long-reg-sc-number
2102        (escaped-float-value long-float))
2103       (#.sb!vm:complex-single-reg-sc-number
2104        (if escaped
2105            (complex
2106             (sb!vm:context-float-register
2107              escaped (sb!c:sc-offset-offset sc-offset) 'single-float)
2108             (sb!vm:context-float-register
2109              escaped (1+ (sb!c:sc-offset-offset sc-offset)) 'single-float))
2110            :invalid-value-for-unescaped-register-storage))
2111       (#.sb!vm:complex-double-reg-sc-number
2112        (if escaped
2113            (complex
2114             (sb!vm:context-float-register
2115              escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2116             (sb!vm:context-float-register
2117              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #!-sparc 1)
2118              'double-float))
2119            :invalid-value-for-unescaped-register-storage))
2120       #!+long-float
2121       (#.sb!vm:complex-long-reg-sc-number
2122        (if escaped
2123            (complex
2124             (sb!vm:context-float-register
2125              escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2126             (sb!vm:context-float-register
2127              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2128              'long-float))
2129            :invalid-value-for-unescaped-register-storage))
2130       (#.sb!vm:single-stack-sc-number
2131        (with-nfp (nfp)
2132          (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2133                                        sb!vm:n-word-bytes))))
2134       (#.sb!vm:double-stack-sc-number
2135        (with-nfp (nfp)
2136          (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2137                                        sb!vm:n-word-bytes))))
2138       #!+long-float
2139       (#.sb!vm:long-stack-sc-number
2140        (with-nfp (nfp)
2141          (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2142                                      sb!vm:n-word-bytes))))
2143       (#.sb!vm:complex-single-stack-sc-number
2144        (with-nfp (nfp)
2145          (complex
2146           (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2147                                         sb!vm:n-word-bytes))
2148           (sb!sys:sap-ref-single nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2149                                         sb!vm:n-word-bytes)))))
2150       (#.sb!vm:complex-double-stack-sc-number
2151        (with-nfp (nfp)
2152          (complex
2153           (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2154                                         sb!vm:n-word-bytes))
2155           (sb!sys:sap-ref-double nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2156                                         sb!vm:n-word-bytes)))))
2157       #!+long-float
2158       (#.sb!vm:complex-long-stack-sc-number
2159        (with-nfp (nfp)
2160          (complex
2161           (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2162                                       sb!vm:n-word-bytes))
2163           (sb!sys:sap-ref-long nfp (* (+ (sb!c:sc-offset-offset sc-offset)
2164                                          #!+sparc 4)
2165                                       sb!vm:n-word-bytes)))))
2166       (#.sb!vm:control-stack-sc-number
2167        (sb!kernel:stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2168       (#.sb!vm:character-stack-sc-number
2169        (with-nfp (nfp)
2170          (code-char (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2171                                               sb!vm:n-word-bytes)))))
2172       (#.sb!vm:unsigned-stack-sc-number
2173        (with-nfp (nfp)
2174          (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2175                                    sb!vm:n-word-bytes))))
2176       (#.sb!vm:signed-stack-sc-number
2177        (with-nfp (nfp)
2178          (sb!sys:signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2179                                           sb!vm:n-word-bytes))))
2180       (#.sb!vm:sap-stack-sc-number
2181        (with-nfp (nfp)
2182          (sb!sys:sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2183                                     sb!vm:n-word-bytes)))))))
2184
2185 #!+(or x86 x86-64)
2186 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2187   (declare (type system-area-pointer fp))
2188   (macrolet ((with-escaped-value ((var) &body forms)
2189                `(if escaped
2190                     (let ((,var (sb!vm:context-register
2191                                  escaped
2192                                  (sb!c:sc-offset-offset sc-offset))))
2193                       ,@forms)
2194                     :invalid-value-for-unescaped-register-storage))
2195              (escaped-float-value (format)
2196                `(if escaped
2197                     (sb!vm:context-float-register
2198                      escaped (sb!c:sc-offset-offset sc-offset) ',format)
2199                     :invalid-value-for-unescaped-register-storage))
2200              (escaped-complex-float-value (format)
2201                `(if escaped
2202                     (complex
2203                      (sb!vm:context-float-register
2204                       escaped (sb!c:sc-offset-offset sc-offset) ',format)
2205                      (sb!vm:context-float-register
2206                       escaped (1+ (sb!c:sc-offset-offset sc-offset)) ',format))
2207                     :invalid-value-for-unescaped-register-storage)))
2208     (ecase (sb!c:sc-offset-scn sc-offset)
2209       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2210        (without-gcing
2211         (with-escaped-value (val)
2212           (make-lisp-obj val nil))))
2213       (#.sb!vm:character-reg-sc-number
2214        (with-escaped-value (val)
2215          (code-char val)))
2216       (#.sb!vm:sap-reg-sc-number
2217        (with-escaped-value (val)
2218          (int-sap val)))
2219       (#.sb!vm:signed-reg-sc-number
2220        (with-escaped-value (val)
2221          (if (logbitp (1- sb!vm:n-word-bits) val)
2222              (logior val (ash -1 sb!vm:n-word-bits))
2223              val)))
2224       (#.sb!vm:unsigned-reg-sc-number
2225        (with-escaped-value (val)
2226          val))
2227       (#.sb!vm:single-reg-sc-number
2228        (escaped-float-value single-float))
2229       (#.sb!vm:double-reg-sc-number
2230        (escaped-float-value double-float))
2231       #!+long-float
2232       (#.sb!vm:long-reg-sc-number
2233        (escaped-float-value long-float))
2234       (#.sb!vm:complex-single-reg-sc-number
2235        (escaped-complex-float-value single-float))
2236       (#.sb!vm:complex-double-reg-sc-number
2237        (escaped-complex-float-value double-float))
2238       #!+long-float
2239       (#.sb!vm:complex-long-reg-sc-number
2240        (escaped-complex-float-value long-float))
2241       (#.sb!vm:single-stack-sc-number
2242        (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2243                                 sb!vm:n-word-bytes))))
2244       (#.sb!vm:double-stack-sc-number
2245        (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2246                                 sb!vm:n-word-bytes))))
2247       #!+long-float
2248       (#.sb!vm:long-stack-sc-number
2249        (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2250                               sb!vm:n-word-bytes))))
2251       (#.sb!vm:complex-single-stack-sc-number
2252        (complex
2253         (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2254                                  sb!vm:n-word-bytes)))
2255         (sap-ref-single fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2256                                  sb!vm:n-word-bytes)))))
2257       (#.sb!vm:complex-double-stack-sc-number
2258        (complex
2259         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2260                                  sb!vm:n-word-bytes)))
2261         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2262                                  sb!vm:n-word-bytes)))))
2263       #!+long-float
2264       (#.sb!vm:complex-long-stack-sc-number
2265        (complex
2266         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2267                                sb!vm:n-word-bytes)))
2268         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2269                                sb!vm:n-word-bytes)))))
2270       (#.sb!vm:control-stack-sc-number
2271        (stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2272       (#.sb!vm:character-stack-sc-number
2273        (code-char
2274         (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2275                                sb!vm:n-word-bytes)))))
2276       (#.sb!vm:unsigned-stack-sc-number
2277        (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2278                               sb!vm:n-word-bytes))))
2279       (#.sb!vm:signed-stack-sc-number
2280        (signed-sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2281                                      sb!vm:n-word-bytes))))
2282       (#.sb!vm:sap-stack-sc-number
2283        (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2284                              sb!vm:n-word-bytes)))))))
2285
2286 ;;; This stores value as the value of DEBUG-VAR in FRAME. In the
2287 ;;; COMPILED-DEBUG-VAR case, access the current value to determine if
2288 ;;; it is an indirect value cell. This occurs when the variable is
2289 ;;; both closed over and set.
2290 (defun %set-debug-var-value (debug-var frame new-value)
2291   (aver (typep frame 'compiled-frame))
2292   (let ((old-value (access-compiled-debug-var-slot debug-var frame)))
2293     (if (indirect-value-cell-p old-value)
2294         (value-cell-set old-value new-value)
2295         (set-compiled-debug-var-slot debug-var frame new-value)))
2296   new-value)
2297
2298 ;;; This stores VALUE for the variable represented by debug-var
2299 ;;; relative to the frame. This assumes the location directly contains
2300 ;;; the variable's value; that is, there is no indirect value cell
2301 ;;; currently there in case the variable is both closed over and set.
2302 (defun set-compiled-debug-var-slot (debug-var frame value)
2303   (let ((escaped (compiled-frame-escaped frame)))
2304     (if escaped
2305         (sub-set-debug-var-slot (frame-pointer frame)
2306                                 (compiled-debug-var-sc-offset debug-var)
2307                                 value escaped)
2308         (sub-set-debug-var-slot
2309          (frame-pointer frame)
2310          (or (compiled-debug-var-save-sc-offset debug-var)
2311              (compiled-debug-var-sc-offset debug-var))
2312          value))))
2313
2314 #!-(or x86 x86-64)
2315 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2316   (macrolet ((set-escaped-value (val)
2317                `(if escaped
2318                     (setf (sb!vm:context-register
2319                            escaped
2320                            (sb!c:sc-offset-offset sc-offset))
2321                           ,val)
2322                     value))
2323              (set-escaped-float-value (format val)
2324                `(if escaped
2325                     (setf (sb!vm:context-float-register
2326                            escaped
2327                            (sb!c:sc-offset-offset sc-offset)
2328                            ',format)
2329                           ,val)
2330                     value))
2331              (with-nfp ((var) &body body)
2332                `(let ((,var (if escaped
2333                                 (int-sap
2334                                  (sb!vm:context-register escaped
2335                                                          sb!vm::nfp-offset))
2336                                 #!-alpha
2337                                 (sap-ref-sap fp
2338                                              (* nfp-save-offset
2339                                                 sb!vm:n-word-bytes))
2340                                 #!+alpha
2341                                 (sb!vm::make-number-stack-pointer
2342                                  (sap-ref-32 fp
2343                                              (* nfp-save-offset
2344                                                 sb!vm:n-word-bytes))))))
2345                   ,@body)))
2346     (ecase (sb!c:sc-offset-scn sc-offset)
2347       ((#.sb!vm:any-reg-sc-number
2348         #.sb!vm:descriptor-reg-sc-number
2349         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2350        (without-gcing
2351         (set-escaped-value
2352           (get-lisp-obj-address value))))
2353       (#.sb!vm:character-reg-sc-number
2354        (set-escaped-value (char-code value)))
2355       (#.sb!vm:sap-reg-sc-number
2356        (set-escaped-value (sap-int value)))
2357       (#.sb!vm:signed-reg-sc-number
2358        (set-escaped-value (logand value (1- (ash 1 sb!vm:n-word-bits)))))
2359       (#.sb!vm:unsigned-reg-sc-number
2360        (set-escaped-value value))
2361       (#.sb!vm:non-descriptor-reg-sc-number
2362        (error "Local non-descriptor register access?"))
2363       (#.sb!vm:interior-reg-sc-number
2364        (error "Local interior register access?"))
2365       (#.sb!vm:single-reg-sc-number
2366        (set-escaped-float-value single-float value))
2367       (#.sb!vm:double-reg-sc-number
2368        (set-escaped-float-value double-float value))
2369       #!+long-float
2370       (#.sb!vm:long-reg-sc-number
2371        (set-escaped-float-value long-float value))
2372       (#.sb!vm:complex-single-reg-sc-number
2373        (when escaped
2374          (setf (sb!vm:context-float-register escaped
2375                                              (sb!c:sc-offset-offset sc-offset)
2376                                              'single-float)
2377                (realpart value))
2378          (setf (sb!vm:context-float-register
2379                 escaped (1+ (sb!c:sc-offset-offset sc-offset))
2380                 'single-float)
2381                (imagpart value)))
2382        value)
2383       (#.sb!vm:complex-double-reg-sc-number
2384        (when escaped
2385          (setf (sb!vm:context-float-register
2386                 escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2387                (realpart value))
2388          (setf (sb!vm:context-float-register
2389                 escaped
2390                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #!-sparc 1)
2391                 'double-float)
2392                (imagpart value)))
2393        value)
2394       #!+long-float
2395       (#.sb!vm:complex-long-reg-sc-number
2396        (when escaped
2397          (setf (sb!vm:context-float-register
2398                 escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2399                (realpart value))
2400          (setf (sb!vm:context-float-register
2401                 escaped
2402                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2403                 'long-float)
2404                (imagpart value)))
2405        value)
2406       (#.sb!vm:single-stack-sc-number
2407        (with-nfp (nfp)
2408          (setf (sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2409                                       sb!vm:n-word-bytes))
2410                (the single-float value))))
2411       (#.sb!vm:double-stack-sc-number
2412        (with-nfp (nfp)
2413          (setf (sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2414                                       sb!vm:n-word-bytes))
2415                (the double-float value))))
2416       #!+long-float
2417       (#.sb!vm:long-stack-sc-number
2418        (with-nfp (nfp)
2419          (setf (sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2420                                     sb!vm:n-word-bytes))
2421                (the long-float value))))
2422       (#.sb!vm:complex-single-stack-sc-number
2423        (with-nfp (nfp)
2424          (setf (sap-ref-single
2425                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2426                (the single-float (realpart value)))
2427          (setf (sap-ref-single
2428                 nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2429                        sb!vm:n-word-bytes))
2430                (the single-float (realpart value)))))
2431       (#.sb!vm:complex-double-stack-sc-number
2432        (with-nfp (nfp)
2433          (setf (sap-ref-double
2434                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2435                (the double-float (realpart value)))
2436          (setf (sap-ref-double
2437                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2438                        sb!vm:n-word-bytes))
2439                (the double-float (realpart value)))))
2440       #!+long-float
2441       (#.sb!vm:complex-long-stack-sc-number
2442        (with-nfp (nfp)
2443          (setf (sap-ref-long
2444                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:n-word-bytes))
2445                (the long-float (realpart value)))
2446          (setf (sap-ref-long
2447                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2448                        sb!vm:n-word-bytes))
2449                (the long-float (realpart value)))))
2450       (#.sb!vm:control-stack-sc-number
2451        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2452       (#.sb!vm:character-stack-sc-number
2453        (with-nfp (nfp)
2454          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2455                                          sb!vm:n-word-bytes))
2456                (char-code (the character value)))))
2457       (#.sb!vm:unsigned-stack-sc-number
2458        (with-nfp (nfp)
2459          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2460                                   sb!vm:n-word-bytes))
2461                (the (unsigned-byte 32) value))))
2462       (#.sb!vm:signed-stack-sc-number
2463        (with-nfp (nfp)
2464          (setf (signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2465                                          sb!vm:n-word-bytes))
2466                (the (signed-byte 32) value))))
2467       (#.sb!vm:sap-stack-sc-number
2468        (with-nfp (nfp)
2469          (setf (sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2470                                    sb!vm:n-word-bytes))
2471                (the system-area-pointer value)))))))
2472
2473 #!+(or x86 x86-64)
2474 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2475   (macrolet ((set-escaped-value (val)
2476                `(if escaped
2477                     (setf (sb!vm:context-register
2478                            escaped
2479                            (sb!c:sc-offset-offset sc-offset))
2480                           ,val)
2481                     value)))
2482     (ecase (sb!c:sc-offset-scn sc-offset)
2483       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2484        (without-gcing
2485         (set-escaped-value
2486           (get-lisp-obj-address value))))
2487       (#.sb!vm:character-reg-sc-number
2488        (set-escaped-value (char-code value)))
2489       (#.sb!vm:sap-reg-sc-number
2490        (set-escaped-value (sap-int value)))
2491       (#.sb!vm:signed-reg-sc-number
2492        (set-escaped-value (logand value (1- (ash 1 sb!vm:n-word-bits)))))
2493       (#.sb!vm:unsigned-reg-sc-number
2494        (set-escaped-value value))
2495       (#.sb!vm:single-reg-sc-number
2496         #+nil ;; don't have escaped floats.
2497        (set-escaped-float-value single-float value))
2498       (#.sb!vm:double-reg-sc-number
2499         #+nil ;;  don't have escaped floats -- still in npx?
2500        (set-escaped-float-value double-float value))
2501       #!+long-float
2502       (#.sb!vm:long-reg-sc-number
2503         #+nil ;;  don't have escaped floats -- still in npx?
2504        (set-escaped-float-value long-float value))
2505       (#.sb!vm:single-stack-sc-number
2506        (setf (sap-ref-single
2507               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2508                        sb!vm:n-word-bytes)))
2509              (the single-float value)))
2510       (#.sb!vm:double-stack-sc-number
2511        (setf (sap-ref-double
2512               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2513                        sb!vm:n-word-bytes)))
2514              (the double-float value)))
2515       #!+long-float
2516       (#.sb!vm:long-stack-sc-number
2517        (setf (sap-ref-long
2518               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2519                        sb!vm:n-word-bytes)))
2520              (the long-float value)))
2521       (#.sb!vm:complex-single-stack-sc-number
2522        (setf (sap-ref-single
2523               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2524                        sb!vm:n-word-bytes)))
2525              (realpart (the (complex single-float) value)))
2526        (setf (sap-ref-single
2527               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2528                        sb!vm:n-word-bytes)))
2529              (imagpart (the (complex single-float) value))))
2530       (#.sb!vm:complex-double-stack-sc-number
2531        (setf (sap-ref-double
2532               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2533                        sb!vm:n-word-bytes)))
2534              (realpart (the (complex double-float) value)))
2535        (setf (sap-ref-double
2536               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2537                        sb!vm:n-word-bytes)))
2538              (imagpart (the (complex double-float) value))))
2539       #!+long-float
2540       (#.sb!vm:complex-long-stack-sc-number
2541        (setf (sap-ref-long
2542               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2543                        sb!vm:n-word-bytes)))
2544              (realpart (the (complex long-float) value)))
2545        (setf (sap-ref-long
2546               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2547                        sb!vm:n-word-bytes)))
2548              (imagpart (the (complex long-float) value))))
2549       (#.sb!vm:control-stack-sc-number
2550        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2551       (#.sb!vm:character-stack-sc-number
2552        (setf (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2553                                     sb!vm:n-word-bytes)))
2554              (char-code (the character value))))
2555       (#.sb!vm:unsigned-stack-sc-number
2556        (setf (sap-ref-word fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2557                                     sb!vm:n-word-bytes)))
2558              (the sb!vm:word value)))
2559       (#.sb!vm:signed-stack-sc-number
2560        (setf (signed-sap-ref-word
2561               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2562                        sb!vm:n-word-bytes)))
2563              (the (signed-byte #.sb!vm:n-word-bits) value)))
2564       (#.sb!vm:sap-stack-sc-number
2565        (setf (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2566                                           sb!vm:n-word-bytes)))
2567              (the system-area-pointer value))))))
2568
2569 ;;; The method for setting and accessing COMPILED-DEBUG-VAR values use
2570 ;;; this to determine if the value stored is the actual value or an
2571 ;;; indirection cell.
2572 (defun indirect-value-cell-p (x)
2573   (and (= (lowtag-of x) sb!vm:other-pointer-lowtag)
2574        (= (widetag-of x) sb!vm:value-cell-header-widetag)))
2575
2576 ;;; Return three values reflecting the validity of DEBUG-VAR's value
2577 ;;; at BASIC-CODE-LOCATION:
2578 ;;;   :VALID    The value is known to be available.
2579 ;;;   :INVALID  The value is known to be unavailable.
2580 ;;;   :UNKNOWN  The value's availability is unknown.
2581 ;;;
2582 ;;; If the variable is always alive, then it is valid. If the
2583 ;;; code-location is unknown, then the variable's validity is
2584 ;;; :unknown. Once we've called CODE-LOCATION-UNKNOWN-P, we know the
2585 ;;; live-set information has been cached in the code-location.
2586 (defun debug-var-validity (debug-var basic-code-location)
2587   (etypecase debug-var
2588     (compiled-debug-var
2589      (compiled-debug-var-validity debug-var basic-code-location))
2590     ;; (There used to be more cases back before sbcl-0.7.0, when
2591     ;; we did special tricks to debug the IR1 interpreter.)
2592     ))
2593
2594 ;;; This is the method for DEBUG-VAR-VALIDITY for COMPILED-DEBUG-VARs.
2595 ;;; For safety, make sure basic-code-location is what we think.
2596 (defun compiled-debug-var-validity (debug-var basic-code-location)
2597   (declare (type compiled-code-location basic-code-location))
2598   (cond ((debug-var-alive-p debug-var)
2599          (let ((debug-fun (code-location-debug-fun basic-code-location)))
2600            (if (>= (compiled-code-location-pc basic-code-location)
2601                    (sb!c::compiled-debug-fun-start-pc
2602                     (compiled-debug-fun-compiler-debug-fun debug-fun)))
2603                :valid
2604                :invalid)))
2605         ((code-location-unknown-p basic-code-location) :unknown)
2606         (t
2607          (let ((pos (position debug-var
2608                               (debug-fun-debug-vars
2609                                (code-location-debug-fun
2610                                 basic-code-location)))))
2611            (unless pos
2612              (error 'unknown-debug-var
2613                     :debug-var debug-var
2614                     :debug-fun
2615                     (code-location-debug-fun basic-code-location)))
2616            ;; There must be live-set info since basic-code-location is known.
2617            (if (zerop (sbit (compiled-code-location-live-set
2618                              basic-code-location)
2619                             pos))
2620                :invalid
2621                :valid)))))
2622 \f
2623 ;;;; sources
2624
2625 ;;; This code produces and uses what we call source-paths. A
2626 ;;; source-path is a list whose first element is a form number as
2627 ;;; returned by CODE-LOCATION-FORM-NUMBER and whose last element is a
2628 ;;; top level form number as returned by
2629 ;;; CODE-LOCATION-TOPLEVEL-FORM-NUMBER. The elements from the last to
2630 ;;; the first, exclusively, are the numbered subforms into which to
2631 ;;; descend. For example:
2632 ;;;    (defun foo (x)
2633 ;;;      (let ((a (aref x 3)))
2634 ;;;     (cons a 3)))
2635 ;;; The call to AREF in this example is form number 5. Assuming this
2636 ;;; DEFUN is the 11'th top level form, the source-path for the AREF
2637 ;;; call is as follows:
2638 ;;;    (5 1 0 1 3 11)
2639 ;;; Given the DEFUN, 3 gets you the LET, 1 gets you the bindings, 0
2640 ;;; gets the first binding, and 1 gets the AREF form.
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   (let ((seen nil)
2651         (translations (make-array 12 :fill-pointer 0 :adjustable t)))
2652     (labels ((translate1 (form path)
2653                (unless (member form seen)
2654                  (push form seen)
2655                  (vector-push-extend (cons (fill-pointer translations) path)
2656                                      translations)
2657                  (let ((pos 0)
2658                        (subform form)
2659                        (trail form))
2660                    (declare (fixnum pos))
2661                    (macrolet ((frob ()
2662                                 '(progn
2663                                   (when (atom subform) (return))
2664                                   (let ((fm (car subform)))
2665                                     (when (consp fm)
2666                                       (translate1 fm (cons pos path)))
2667                                     (incf pos))
2668                                   (setq subform (cdr subform))
2669                                   (when (eq subform trail) (return)))))
2670                      (loop
2671                        (frob)
2672                        (frob)
2673                        (setq trail (cdr trail))))))))
2674       (translate1 form (list tlf-number)))
2675     (coerce translations 'simple-vector)))
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 (kind callee-register-offset)
3364   (let ((context (nth-interrupt-context (1- *free-interrupt-context-index*))))
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 (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)))