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