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