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