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