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