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