0.pre7.48:
[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 (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 #!+x86
586 (sb!alien:def-alien-routine component-ptr-from-pc (system-area-pointer)
587   (pc system-area-pointer))
588
589 #!+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 #!-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 (defun code-object-from-bits (bits)
1097   (declare (type (unsigned-byte 32) bits))
1098   (let ((object (make-lisp-obj bits)))
1099     (if (functionp object)
1100         (or (function-code-header object)
1101             :undefined-function)
1102         (let ((lowtag (get-lowtag object)))
1103           (if (= lowtag sb!vm:other-pointer-type)
1104               (let ((type (get-type object)))
1105                 (cond ((= type sb!vm:code-header-type)
1106                        object)
1107                       ((= type sb!vm:return-pc-header-type)
1108                        (lra-code-header object))
1109                       (t
1110                        nil))))))))
1111 \f
1112 ;;;; frame utilities
1113
1114 ;;; This returns a COMPILED-DEBUG-FUNCTION for code and pc. We fetch
1115 ;;; the SB!C::DEBUG-INFO and run down its function-map to get a
1116 ;;; SB!C::COMPILED-DEBUG-FUNCTION from the pc. The result only needs
1117 ;;; to reference the component, for function constants, and the
1118 ;;; SB!C::COMPILED-DEBUG-FUNCTION.
1119 (defun debug-function-from-pc (component pc)
1120   (let ((info (%code-debug-info component)))
1121     (cond
1122      ((not info)
1123       (debug-signal 'no-debug-info :code-component component))
1124      ((eq info :bogus-lra)
1125       (make-bogus-debug-function "function end breakpoint"))
1126      (t
1127       (let* ((function-map (get-debug-info-function-map info))
1128              (len (length function-map)))
1129         (declare (simple-vector function-map))
1130         (if (= len 1)
1131             (make-compiled-debug-function (svref function-map 0) component)
1132             (let ((i 1)
1133                   (elsewhere-p
1134                    (>= pc (sb!c::compiled-debug-function-elsewhere-pc
1135                            (svref function-map 0)))))
1136               (declare (type sb!int:index i))
1137               (loop
1138                 (when (or (= i len)
1139                           (< pc (if elsewhere-p
1140                                     (sb!c::compiled-debug-function-elsewhere-pc
1141                                      (svref function-map (1+ i)))
1142                                     (svref function-map i))))
1143                   (return (make-compiled-debug-function
1144                            (svref function-map (1- i))
1145                            component)))
1146                 (incf i 2)))))))))
1147
1148 ;;; This returns a code-location for the COMPILED-DEBUG-FUNCTION,
1149 ;;; DEBUG-FUN, and the pc into its code vector. If we stopped at a
1150 ;;; breakpoint, find the CODE-LOCATION for that breakpoint. Otherwise,
1151 ;;; make an :UNSURE code location, so it can be filled in when we
1152 ;;; figure out what is going on.
1153 (defun code-location-from-pc (debug-fun pc escaped)
1154   (or (and (compiled-debug-function-p debug-fun)
1155            escaped
1156            (let ((data (breakpoint-data
1157                         (compiled-debug-function-component debug-fun)
1158                         pc nil)))
1159              (when (and data (breakpoint-data-breakpoints data))
1160                (let ((what (breakpoint-what
1161                             (first (breakpoint-data-breakpoints data)))))
1162                  (when (compiled-code-location-p what)
1163                    what)))))
1164       (make-compiled-code-location pc debug-fun)))
1165
1166 ;;; Return an alist mapping catch tags to CODE-LOCATIONs. These are
1167 ;;; CODE-LOCATIONs at which execution would continue with frame as the
1168 ;;; top frame if someone threw to the corresponding tag.
1169 (defun frame-catches (frame)
1170   (let ((catch (descriptor-sap *current-catch-block*))
1171         (res nil)
1172         (fp (frame-pointer (frame-real-frame frame))))
1173     (loop
1174       (when (zerop (sap-int catch)) (return (nreverse res)))
1175       (when (sap= fp
1176                   #!-alpha
1177                   (sap-ref-sap catch
1178                                       (* sb!vm:catch-block-current-cont-slot
1179                                          sb!vm:word-bytes))
1180                   #!+alpha
1181                   (:int-sap
1182                    (sap-ref-32 catch
1183                                       (* sb!vm:catch-block-current-cont-slot
1184                                          sb!vm:word-bytes))))
1185         (let* (#!-x86
1186                (lra (stack-ref catch sb!vm:catch-block-entry-pc-slot))
1187                #!+x86
1188                (ra (sap-ref-sap
1189                     catch (* sb!vm:catch-block-entry-pc-slot
1190                              sb!vm:word-bytes)))
1191                #!-x86
1192                (component
1193                 (stack-ref catch sb!vm:catch-block-current-code-slot))
1194                #!+x86
1195                (component (component-from-component-ptr
1196                            (component-ptr-from-pc ra)))
1197                (offset
1198                 #!-x86
1199                 (* (- (1+ (get-header-data lra))
1200                       (get-header-data component))
1201                    sb!vm:word-bytes)
1202                 #!+x86
1203                 (- (sap-int ra)
1204                    (- (get-lisp-obj-address component)
1205                       sb!vm:other-pointer-type)
1206                    (* (get-header-data component) sb!vm:word-bytes))))
1207           (push (cons #!-x86
1208                       (stack-ref catch sb!vm:catch-block-tag-slot)
1209                       #!+x86
1210                       (make-lisp-obj
1211                        (sap-ref-32 catch (* sb!vm:catch-block-tag-slot
1212                                                    sb!vm:word-bytes)))
1213                       (make-compiled-code-location
1214                        offset (frame-debug-function frame)))
1215                 res)))
1216       (setf catch
1217             #!-alpha
1218             (sap-ref-sap catch
1219                                 (* sb!vm:catch-block-previous-catch-slot
1220                                    sb!vm:word-bytes))
1221             #!+alpha
1222             (:int-sap
1223              (sap-ref-32 catch
1224                                 (* sb!vm:catch-block-previous-catch-slot
1225                                    sb!vm:word-bytes)))))))
1226
1227 ;;; If an interpreted frame, return the real frame, otherwise frame.
1228 (defun frame-real-frame (frame)
1229   (etypecase frame
1230     (compiled-frame frame)
1231     (interpreted-frame (interpreted-frame-real-frame frame))))
1232 \f
1233 ;;;; operations on DEBUG-FUNCTIONs
1234
1235 ;;; Execute the forms in a context with block-var bound to each
1236 ;;; debug-block in debug-function successively. Result is an optional
1237 ;;; form to execute for return values, and DO-DEBUG-FUNCTION-BLOCKS
1238 ;;; returns nil if there is no result form. This signals a
1239 ;;; no-debug-blocks condition when the debug-function lacks
1240 ;;; debug-block information.
1241 (defmacro do-debug-function-blocks ((block-var debug-function &optional result)
1242                                     &body body)
1243   (let ((blocks (gensym))
1244         (i (gensym)))
1245     `(let ((,blocks (debug-function-debug-blocks ,debug-function)))
1246        (declare (simple-vector ,blocks))
1247        (dotimes (,i (length ,blocks) ,result)
1248          (let ((,block-var (svref ,blocks ,i)))
1249            ,@body)))))
1250
1251 ;;; Execute body in a context with var bound to each debug-var in
1252 ;;; debug-function. This returns the value of executing result (defaults to
1253 ;;; nil). This may iterate over only some of debug-function's variables or none
1254 ;;; depending on debug policy; for example, possibly the compilation only
1255 ;;; preserved argument information.
1256 (defmacro do-debug-function-variables ((var debug-function &optional result)
1257                                        &body body)
1258   (let ((vars (gensym))
1259         (i (gensym)))
1260     `(let ((,vars (debug-function-debug-vars ,debug-function)))
1261        (declare (type (or null simple-vector) ,vars))
1262        (if ,vars
1263            (dotimes (,i (length ,vars) ,result)
1264              (let ((,var (svref ,vars ,i)))
1265                ,@body))
1266            ,result))))
1267
1268 ;;; Return the Common Lisp function associated with the debug-function. This
1269 ;;; returns nil if the function is unavailable or is non-existent as a user
1270 ;;; callable function object.
1271 (defun debug-function-function (debug-function)
1272   (let ((cached-value (debug-function-%function debug-function)))
1273     (if (eq cached-value :unparsed)
1274         (setf (debug-function-%function debug-function)
1275               (etypecase debug-function
1276                 (compiled-debug-function
1277                  (let ((component
1278                         (compiled-debug-function-component debug-function))
1279                        (start-pc
1280                         (sb!c::compiled-debug-function-start-pc
1281                          (compiled-debug-function-compiler-debug-fun
1282                           debug-function))))
1283                    (do ((entry (%code-entry-points component)
1284                                (%function-next entry)))
1285                        ((null entry) nil)
1286                      (when (= start-pc
1287                               (sb!c::compiled-debug-function-start-pc
1288                                (compiled-debug-function-compiler-debug-fun
1289                                 (function-debug-function entry))))
1290                        (return entry)))))
1291                 (bogus-debug-function nil)))
1292         cached-value)))
1293
1294 ;;; Return the name of the function represented by debug-function. This may
1295 ;;; be a string or a cons; do not assume it is a symbol.
1296 (defun debug-function-name (debug-function)
1297   (etypecase debug-function
1298     (compiled-debug-function
1299      (sb!c::compiled-debug-function-name
1300       (compiled-debug-function-compiler-debug-fun debug-function)))
1301     (bogus-debug-function
1302      (bogus-debug-function-%name debug-function))))
1303
1304 ;;; Return a debug-function that represents debug information for function.
1305 (defun function-debug-function (fun)
1306   (ecase (get-type fun)
1307     (#.sb!vm:closure-header-type
1308      (function-debug-function (%closure-function fun)))
1309     (#.sb!vm:funcallable-instance-header-type
1310      (function-debug-function (funcallable-instance-function fun)))
1311     ((#.sb!vm:function-header-type #.sb!vm:closure-function-header-type)
1312       (let* ((name (%function-name fun))
1313              (component (function-code-header fun))
1314              (res (find-if
1315                    (lambda (x)
1316                      (and (sb!c::compiled-debug-function-p x)
1317                           (eq (sb!c::compiled-debug-function-name x) name)
1318                           (eq (sb!c::compiled-debug-function-kind x) nil)))
1319                    (get-debug-info-function-map
1320                     (%code-debug-info component)))))
1321         (if res
1322             (make-compiled-debug-function res component)
1323             ;; KLUDGE: comment from CMU CL:
1324             ;;   This used to be the non-interpreted branch, but
1325             ;;   William wrote it to return the debug-fun of fun's XEP
1326             ;;   instead of fun's debug-fun. The above code does this
1327             ;;   more correctly, but it doesn't get or eliminate all
1328             ;;   appropriate cases. It mostly works, and probably
1329             ;;   works for all named functions anyway.
1330             ;; -- WHN 20000120
1331             (debug-function-from-pc component
1332                                     (* (- (function-word-offset fun)
1333                                           (get-header-data component))
1334                                        sb!vm:word-bytes)))))))
1335
1336 ;;; Return the kind of the function, which is one of :OPTIONAL,
1337 ;;; :EXTERNAL, TOP-level, :CLEANUP, or NIL.
1338 (defun debug-function-kind (debug-function)
1339   ;; FIXME: This "is one of" information should become part of the function
1340   ;; declamation, not just a doc string
1341   (etypecase debug-function
1342     (compiled-debug-function
1343      (sb!c::compiled-debug-function-kind
1344       (compiled-debug-function-compiler-debug-fun debug-function)))
1345     (bogus-debug-function
1346      nil)))
1347
1348 ;;; Is there any variable information for DEBUG-FUNCTION?
1349 (defun debug-var-info-available (debug-function)
1350   (not (not (debug-function-debug-vars debug-function))))
1351
1352 ;;; Return a list of debug-vars in debug-function having the same name
1353 ;;; and package as symbol. If symbol is uninterned, then this returns
1354 ;;; a list of debug-vars without package names and with the same name
1355 ;;; as symbol. The result of this function is limited to the
1356 ;;; availability of variable information in debug-function; for
1357 ;;; example, possibly DEBUG-FUNCTION only knows about its arguments.
1358 (defun debug-function-symbol-variables (debug-function symbol)
1359   (let ((vars (ambiguous-debug-vars debug-function (symbol-name symbol)))
1360         (package (and (symbol-package symbol)
1361                       (package-name (symbol-package symbol)))))
1362     (delete-if (if (stringp package)
1363                    (lambda (var)
1364                      (let ((p (debug-var-package-name var)))
1365                        (or (not (stringp p))
1366                            (string/= p package))))
1367                    (lambda (var)
1368                      (stringp (debug-var-package-name var))))
1369                vars)))
1370
1371 ;;; Return a list of debug-vars in debug-function whose names contain
1372 ;;; name-prefix-string as an intial substring. The result of this
1373 ;;; function is limited to the availability of variable information in
1374 ;;; debug-function; for example, possibly debug-function only knows
1375 ;;; about its arguments.
1376 (defun ambiguous-debug-vars (debug-function name-prefix-string)
1377   (declare (simple-string name-prefix-string))
1378   (let ((variables (debug-function-debug-vars debug-function)))
1379     (declare (type (or null simple-vector) variables))
1380     (if variables
1381         (let* ((len (length variables))
1382                (prefix-len (length name-prefix-string))
1383                (pos (find-variable name-prefix-string variables len))
1384                (res nil))
1385           (when pos
1386             ;; Find names from pos to variable's len that contain prefix.
1387             (do ((i pos (1+ i)))
1388                 ((= i len))
1389               (let* ((var (svref variables i))
1390                      (name (debug-var-symbol-name var))
1391                      (name-len (length name)))
1392                 (declare (simple-string name))
1393                 (when (/= (or (string/= name-prefix-string name
1394                                         :end1 prefix-len :end2 name-len)
1395                               prefix-len)
1396                           prefix-len)
1397                   (return))
1398                 (push var res)))
1399             (setq res (nreverse res)))
1400           res))))
1401
1402 ;;; This returns a position in variables for one containing name as an
1403 ;;; initial substring. End is the length of variables if supplied.
1404 (defun find-variable (name variables &optional end)
1405   (declare (simple-vector variables)
1406            (simple-string name))
1407   (let ((name-len (length name)))
1408     (position name variables
1409               :test #'(lambda (x y)
1410                         (let* ((y (debug-var-symbol-name y))
1411                                (y-len (length y)))
1412                           (declare (simple-string y))
1413                           (and (>= y-len name-len)
1414                                (string= x y :end1 name-len :end2 name-len))))
1415               :end (or end (length variables)))))
1416
1417 ;;; Return a list representing the lambda-list for DEBUG-FUNCTION. The
1418 ;;; list has the following structure:
1419 ;;;   (required-var1 required-var2
1420 ;;;    ...
1421 ;;;    (:optional var3 suppliedp-var4)
1422 ;;;    (:optional var5)
1423 ;;;    ...
1424 ;;;    (:rest var6) (:rest var7)
1425 ;;;    ...
1426 ;;;    (:keyword keyword-symbol var8 suppliedp-var9)
1427 ;;;    (:keyword keyword-symbol var10)
1428 ;;;    ...
1429 ;;;   )
1430 ;;; Each VARi is a DEBUG-VAR; however it may be the symbol :DELETED if
1431 ;;; it is unreferenced in DEBUG-FUNCTION. This signals a
1432 ;;; LAMBDA-LIST-UNAVAILABLE condition when there is no argument list
1433 ;;; information.
1434 (defun debug-function-lambda-list (debug-function)
1435   (etypecase debug-function
1436     (compiled-debug-function
1437      (compiled-debug-function-lambda-list debug-function))
1438     (bogus-debug-function
1439      nil)))
1440
1441 ;;; Note: If this has to compute the lambda list, it caches it in
1442 ;;; DEBUG-FUNCTION.
1443 (defun compiled-debug-function-lambda-list (debug-function)
1444   (let ((lambda-list (debug-function-%lambda-list debug-function)))
1445     (cond ((eq lambda-list :unparsed)
1446            (multiple-value-bind (args argsp)
1447                (parse-compiled-debug-function-lambda-list debug-function)
1448              (setf (debug-function-%lambda-list debug-function) args)
1449              (if argsp
1450                  args
1451                  (debug-signal 'lambda-list-unavailable
1452                                :debug-function debug-function))))
1453           (lambda-list)
1454           ((bogus-debug-function-p debug-function)
1455            nil)
1456           ((sb!c::compiled-debug-function-arguments
1457             (compiled-debug-function-compiler-debug-fun
1458              debug-function))
1459            ;; If the packed information is there (whether empty or not) as
1460            ;; opposed to being nil, then returned our cached value (nil).
1461            nil)
1462           (t
1463            ;; Our cached value is nil, and the packed lambda-list information
1464            ;; is nil, so we don't have anything available.
1465            (debug-signal 'lambda-list-unavailable
1466                          :debug-function debug-function)))))
1467
1468 ;;; COMPILED-DEBUG-FUNCTION-LAMBDA-LIST calls this when a
1469 ;;; compiled-debug-function has no lambda-list information cached. It
1470 ;;; returns the lambda-list as the first value and whether there was
1471 ;;; any argument information as the second value. Therefore, nil and t
1472 ;;; means there were no arguments, but nil and nil means there was no
1473 ;;; argument information.
1474 (defun parse-compiled-debug-function-lambda-list (debug-function)
1475   (let ((args (sb!c::compiled-debug-function-arguments
1476                (compiled-debug-function-compiler-debug-fun
1477                 debug-function))))
1478     (cond
1479      ((not args)
1480       (values nil nil))
1481      ((eq args :minimal)
1482       (values (coerce (debug-function-debug-vars debug-function) 'list)
1483               t))
1484      (t
1485       (let ((vars (debug-function-debug-vars debug-function))
1486             (i 0)
1487             (len (length args))
1488             (res nil)
1489             (optionalp nil))
1490         (declare (type (or null simple-vector) vars))
1491         (loop
1492           (when (>= i len) (return))
1493           (let ((ele (aref args i)))
1494             (cond
1495              ((symbolp ele)
1496               (case ele
1497                 (sb!c::deleted
1498                  ;; Deleted required arg at beginning of args array.
1499                  (push :deleted res))
1500                 (sb!c::optional-args
1501                  (setf optionalp t))
1502                 (sb!c::supplied-p
1503                  ;; SUPPLIED-P var immediately following keyword or
1504                  ;; optional. Stick the extra var in the result
1505                  ;; element representing the keyword or optional,
1506                  ;; which is the previous one.
1507                  (nconc (car res)
1508                         (list (compiled-debug-function-lambda-list-var
1509                                args (incf i) vars))))
1510                 (sb!c::rest-arg
1511                  (push (list :rest
1512                              (compiled-debug-function-lambda-list-var
1513                               args (incf i) vars))
1514                        res))
1515                 (sb!c::more-arg
1516                  ;; Just ignore the fact that the next two args are
1517                  ;; the &MORE arg context and count, and act like they
1518                  ;; are regular arguments.
1519                  nil)
1520                 (t
1521                  ;; &KEY arg
1522                  (push (list :keyword
1523                              ele
1524                              (compiled-debug-function-lambda-list-var
1525                               args (incf i) vars))
1526                        res))))
1527              (optionalp
1528               ;; We saw an optional marker, so the following
1529               ;; non-symbols are indexes indicating optional
1530               ;; variables.
1531               (push (list :optional (svref vars ele)) res))
1532              (t
1533               ;; Required arg at beginning of args array.
1534               (push (svref vars ele) res))))
1535           (incf i))
1536         (values (nreverse res) t))))))
1537
1538 ;;; This is used in COMPILED-DEBUG-FUNCTION-LAMBDA-LIST.
1539 (defun compiled-debug-function-lambda-list-var (args i vars)
1540   (declare (type (simple-array * (*)) args)
1541            (simple-vector vars))
1542   (let ((ele (aref args i)))
1543     (cond ((not (symbolp ele)) (svref vars ele))
1544           ((eq ele 'sb!c::deleted) :deleted)
1545           (t (error "malformed arguments description")))))
1546
1547 (defun compiled-debug-function-debug-info (debug-fun)
1548   (%code-debug-info (compiled-debug-function-component debug-fun)))
1549 \f
1550 ;;;; unpacking variable and basic block data
1551
1552 (defvar *parsing-buffer*
1553   (make-array 20 :adjustable t :fill-pointer t))
1554 (defvar *other-parsing-buffer*
1555   (make-array 20 :adjustable t :fill-pointer t))
1556 ;;; PARSE-DEBUG-BLOCKS, PARSE-DEBUG-VARS and UNCOMPACT-FUNCTION-MAP
1557 ;;; use this to unpack binary encoded information. It returns the
1558 ;;; values returned by the last form in body.
1559 ;;;
1560 ;;; This binds buffer-var to *parsing-buffer*, makes sure it starts at
1561 ;;; element zero, and makes sure if we unwind, we nil out any set
1562 ;;; elements for GC purposes.
1563 ;;;
1564 ;;; This also binds other-var to *other-parsing-buffer* when it is
1565 ;;; supplied, making sure it starts at element zero and that we nil
1566 ;;; out any elements if we unwind.
1567 ;;;
1568 ;;; This defines the local macro RESULT that takes a buffer, copies
1569 ;;; its elements to a resulting simple-vector, nil's out elements, and
1570 ;;; restarts the buffer at element zero. RESULT returns the
1571 ;;; simple-vector.
1572 (eval-when (:compile-toplevel :execute)
1573 (sb!xc:defmacro with-parsing-buffer ((buffer-var &optional other-var)
1574                                      &body body)
1575   (let ((len (gensym))
1576         (res (gensym)))
1577     `(unwind-protect
1578          (let ((,buffer-var *parsing-buffer*)
1579                ,@(if other-var `((,other-var *other-parsing-buffer*))))
1580            (setf (fill-pointer ,buffer-var) 0)
1581            ,@(if other-var `((setf (fill-pointer ,other-var) 0)))
1582            (macrolet ((result (buf)
1583                         `(let* ((,',len (length ,buf))
1584                                 (,',res (make-array ,',len)))
1585                            (replace ,',res ,buf :end1 ,',len :end2 ,',len)
1586                            (fill ,buf nil :end ,',len)
1587                            (setf (fill-pointer ,buf) 0)
1588                            ,',res)))
1589              ,@body))
1590      (fill *parsing-buffer* nil)
1591      ,@(if other-var `((fill *other-parsing-buffer* nil))))))
1592 ) ; EVAL-WHEN
1593
1594 ;;; The argument is a debug internals structure. This returns the
1595 ;;; debug-blocks for debug-function, regardless of whether we have
1596 ;;; unpacked them yet. It signals a no-debug-blocks condition if it
1597 ;;; can't return the blocks.
1598 (defun debug-function-debug-blocks (debug-function)
1599   (let ((blocks (debug-function-blocks debug-function)))
1600     (cond ((eq blocks :unparsed)
1601            (setf (debug-function-blocks debug-function)
1602                  (parse-debug-blocks debug-function))
1603            (unless (debug-function-blocks debug-function)
1604              (debug-signal 'no-debug-blocks
1605                            :debug-function debug-function))
1606            (debug-function-blocks debug-function))
1607           (blocks)
1608           (t
1609            (debug-signal 'no-debug-blocks
1610                          :debug-function debug-function)))))
1611
1612 ;;; This returns a SIMPLE-VECTOR of DEBUG-BLOCKs or NIL. NIL indicates
1613 ;;; there was no basic block information.
1614 (defun parse-debug-blocks (debug-function)
1615   (etypecase debug-function
1616     (compiled-debug-function
1617      (parse-compiled-debug-blocks debug-function))
1618     (bogus-debug-function
1619      (debug-signal 'no-debug-blocks :debug-function debug-function))))
1620
1621 ;;; This does some of the work of PARSE-DEBUG-BLOCKS.
1622 (defun parse-compiled-debug-blocks (debug-function)
1623   (let* ((debug-fun (compiled-debug-function-compiler-debug-fun
1624                      debug-function))
1625          (var-count (length (debug-function-debug-vars debug-function)))
1626          (blocks (sb!c::compiled-debug-function-blocks debug-fun))
1627          ;; KLUDGE: 8 is a hard-wired constant in the compiler for the
1628          ;; element size of the packed binary representation of the
1629          ;; blocks data.
1630          (live-set-len (ceiling var-count 8))
1631          (tlf-number (sb!c::compiled-debug-function-tlf-number debug-fun)))
1632     (unless blocks (return-from parse-compiled-debug-blocks nil))
1633     (macrolet ((aref+ (a i) `(prog1 (aref ,a ,i) (incf ,i))))
1634       (with-parsing-buffer (blocks-buffer locations-buffer)
1635         (let ((i 0)
1636               (len (length blocks))
1637               (last-pc 0))
1638           (loop
1639             (when (>= i len) (return))
1640             (let ((succ-and-flags (aref+ blocks i))
1641                   (successors nil))
1642               (declare (type (unsigned-byte 8) succ-and-flags)
1643                        (list successors))
1644               (dotimes (k (ldb sb!c::compiled-debug-block-nsucc-byte
1645                                succ-and-flags))
1646                 (push (sb!c::read-var-integer blocks i) successors))
1647               (let* ((locations
1648                       (dotimes (k (sb!c::read-var-integer blocks i)
1649                                   (result locations-buffer))
1650                         (let ((kind (svref sb!c::*compiled-code-location-kinds*
1651                                            (aref+ blocks i)))
1652                               (pc (+ last-pc
1653                                      (sb!c::read-var-integer blocks i)))
1654                               (tlf-offset (or tlf-number
1655                                               (sb!c::read-var-integer blocks
1656                                                                       i)))
1657                               (form-number (sb!c::read-var-integer blocks i))
1658                               (live-set (sb!c::read-packed-bit-vector
1659                                          live-set-len blocks i)))
1660                           (vector-push-extend (make-known-code-location
1661                                                pc debug-function tlf-offset
1662                                                form-number live-set kind)
1663                                               locations-buffer)
1664                           (setf last-pc pc))))
1665                      (block (make-compiled-debug-block
1666                              locations successors
1667                              (not (zerop (logand
1668                                           sb!c::compiled-debug-block-elsewhere-p
1669                                           succ-and-flags))))))
1670                 (vector-push-extend block blocks-buffer)
1671                 (dotimes (k (length locations))
1672                   (setf (code-location-%debug-block (svref locations k))
1673                         block))))))
1674         (let ((res (result blocks-buffer)))
1675           (declare (simple-vector res))
1676           (dotimes (i (length res))
1677             (let* ((block (svref res i))
1678                    (succs nil))
1679               (dolist (ele (debug-block-successors block))
1680                 (push (svref res ele) succs))
1681               (setf (debug-block-successors block) succs)))
1682           res)))))
1683
1684 ;;; The argument is a debug internals structure. This returns NIL if
1685 ;;; there is no variable information. It returns an empty
1686 ;;; simple-vector if there were no locals in the function. Otherwise
1687 ;;; it returns a SIMPLE-VECTOR of DEBUG-VARs.
1688 (defun debug-function-debug-vars (debug-function)
1689   (let ((vars (debug-function-%debug-vars debug-function)))
1690     (if (eq vars :unparsed)
1691         (setf (debug-function-%debug-vars debug-function)
1692               (etypecase debug-function
1693                 (compiled-debug-function
1694                  (parse-compiled-debug-vars debug-function))
1695                 (bogus-debug-function nil)))
1696         vars)))
1697
1698 ;;; VARS is the parsed variables for a minimal debug function. We need
1699 ;;; to assign names of the form ARG-NNN. We must pad with leading
1700 ;;; zeros, since the arguments must be in alphabetical order.
1701 (defun assign-minimal-var-names (vars)
1702   (declare (simple-vector vars))
1703   (let* ((len (length vars))
1704          (width (length (format nil "~D" (1- len)))))
1705     (dotimes (i len)
1706       (setf (compiled-debug-var-symbol (svref vars i))
1707             (intern (format nil "ARG-~V,'0D" width i)
1708                     ;; KLUDGE: It's somewhat nasty to have a bare
1709                     ;; package name string here. It would be
1710                     ;; nicer to have #.(FIND-PACKAGE "SB!DEBUG")
1711                     ;; instead, since then at least it would transform
1712                     ;; correctly under package renaming and stuff.
1713                     ;; However, genesis can't handle dumped packages..
1714                     ;; -- WHN 20000129
1715                     ;;
1716                     ;; FIXME: Maybe this could be fixed by moving the
1717                     ;; whole debug-int.lisp file to warm init? (after
1718                     ;; which dumping a #.(FIND-PACKAGE ..) expression
1719                     ;; would work fine) If this is possible, it would
1720                     ;; probably be a good thing, since minimizing the
1721                     ;; amount of stuff in cold init is basically good.
1722                     (or (find-package "SB-DEBUG")
1723                         (find-package "SB!DEBUG")))))))
1724
1725 ;;; Parse the packed representation of DEBUG-VARs from
1726 ;;; DEBUG-FUNCTION's SB!C::COMPILED-DEBUG-FUNCTION, returning a vector
1727 ;;; of DEBUG-VARs, or NIL if there was no information to parse.
1728 (defun parse-compiled-debug-vars (debug-function)
1729   (let* ((cdebug-fun (compiled-debug-function-compiler-debug-fun
1730                       debug-function))
1731          (packed-vars (sb!c::compiled-debug-function-variables cdebug-fun))
1732          (args-minimal (eq (sb!c::compiled-debug-function-arguments cdebug-fun)
1733                            :minimal)))
1734     (when packed-vars
1735       (do ((i 0)
1736            (buffer (make-array 0 :fill-pointer 0 :adjustable t)))
1737           ((>= i (length packed-vars))
1738            (let ((result (coerce buffer 'simple-vector)))
1739              (when args-minimal
1740                (assign-minimal-var-names result))
1741              result))
1742         (flet ((geti () (prog1 (aref packed-vars i) (incf i))))
1743           (let* ((flags (geti))
1744                  (minimal (logtest sb!c::compiled-debug-var-minimal-p flags))
1745                  (deleted (logtest sb!c::compiled-debug-var-deleted-p flags))
1746                  (live (logtest sb!c::compiled-debug-var-environment-live
1747                                 flags))
1748                  (save (logtest sb!c::compiled-debug-var-save-loc-p flags))
1749                  (symbol (if minimal nil (geti)))
1750                  (id (if (logtest sb!c::compiled-debug-var-id-p flags)
1751                          (geti)
1752                          0))
1753                  (sc-offset (if deleted 0 (geti)))
1754                  (save-sc-offset (if save (geti) nil)))
1755             (aver (not (and args-minimal (not minimal))))
1756             (vector-push-extend (make-compiled-debug-var symbol
1757                                                          id
1758                                                          live
1759                                                          sc-offset
1760                                                          save-sc-offset)
1761                                 buffer)))))))
1762 \f
1763 ;;;; unpacking minimal debug functions
1764
1765 (eval-when (:compile-toplevel :execute)
1766
1767 ;;; sleazoid "macro" to keep our indentation sane in UNCOMPACT-FUNCTION-MAP
1768 (sb!xc:defmacro make-uncompacted-debug-fun ()
1769   '(sb!c::make-compiled-debug-function
1770     :name
1771     (let ((base (ecase (ldb sb!c::minimal-debug-function-name-style-byte
1772                             options)
1773                   (#.sb!c::minimal-debug-function-name-symbol
1774                    (intern (sb!c::read-var-string map i)
1775                            (sb!c::compiled-debug-info-package info)))
1776                   (#.sb!c::minimal-debug-function-name-packaged
1777                    (let ((pkg (sb!c::read-var-string map i)))
1778                      (intern (sb!c::read-var-string map i) pkg)))
1779                   (#.sb!c::minimal-debug-function-name-uninterned
1780                    (make-symbol (sb!c::read-var-string map i)))
1781                   (#.sb!c::minimal-debug-function-name-component
1782                    (sb!c::compiled-debug-info-name info)))))
1783       (if (logtest flags sb!c::minimal-debug-function-setf-bit)
1784           `(setf ,base)
1785           base))
1786     :kind (svref sb!c::*minimal-debug-function-kinds*
1787                  (ldb sb!c::minimal-debug-function-kind-byte options))
1788     :variables
1789     (when vars-p
1790       (let ((len (sb!c::read-var-integer map i)))
1791         (prog1 (subseq map i (+ i len))
1792           (incf i len))))
1793     :arguments (when vars-p :minimal)
1794     :returns
1795     (ecase (ldb sb!c::minimal-debug-function-returns-byte options)
1796       (#.sb!c::minimal-debug-function-returns-standard
1797        :standard)
1798       (#.sb!c::minimal-debug-function-returns-fixed
1799        :fixed)
1800       (#.sb!c::minimal-debug-function-returns-specified
1801        (with-parsing-buffer (buf)
1802          (dotimes (idx (sb!c::read-var-integer map i))
1803            (vector-push-extend (sb!c::read-var-integer map i) buf))
1804          (result buf))))
1805     :return-pc (sb!c::read-var-integer map i)
1806     :old-fp (sb!c::read-var-integer map i)
1807     :nfp (when (logtest flags sb!c::minimal-debug-function-nfp-bit)
1808            (sb!c::read-var-integer map i))
1809     :start-pc
1810     (progn
1811       (setq code-start-pc (+ code-start-pc (sb!c::read-var-integer map i)))
1812       (+ code-start-pc (sb!c::read-var-integer map i)))
1813     :elsewhere-pc
1814     (setq elsewhere-pc (+ elsewhere-pc (sb!c::read-var-integer map i)))))
1815
1816 ) ; EVAL-WHEN
1817
1818 ;;; Return a normal function map derived from a minimal debug info
1819 ;;; function map. This involves looping parsing
1820 ;;; minimal-debug-functions and then building a vector out of them.
1821 ;;;
1822 ;;; FIXME: This and its helper macro just above become dead code now
1823 ;;; that we no longer use compacted function maps.
1824 (defun uncompact-function-map (info)
1825   (declare (type sb!c::compiled-debug-info info))
1826
1827   ;; (This is stubified until we solve the problem of representing
1828   ;; debug information in a way which plays nicely with package renaming.)
1829   (error "FIXME: dead code UNCOMPACT-FUNCTION-MAP (was stub)")
1830
1831   (let* ((map (sb!c::compiled-debug-info-function-map info))
1832          (i 0)
1833          (len (length map))
1834          (code-start-pc 0)
1835          (elsewhere-pc 0))
1836     (declare (type (simple-array (unsigned-byte 8) (*)) map))
1837     (sb!int:collect ((res))
1838       (loop
1839         (when (= i len) (return))
1840         (let* ((options (prog1 (aref map i) (incf i)))
1841                (flags (prog1 (aref map i) (incf i)))
1842                (vars-p (logtest flags
1843                                 sb!c::minimal-debug-function-variables-bit))
1844                (dfun (make-uncompacted-debug-fun)))
1845           (res code-start-pc)
1846           (res dfun)))
1847
1848       (coerce (cdr (res)) 'simple-vector))))
1849
1850 ;;; a map from minimal DEBUG-INFO function maps to unpacked
1851 ;;; versions thereof
1852 (defvar *uncompacted-function-maps* (make-hash-table :test 'eq))
1853
1854 ;;; Return a FUNCTION-MAP for a given COMPILED-DEBUG-info object. If
1855 ;;; the info is minimal, and has not been parsed, then parse it.
1856 ;;;
1857 ;;; FIXME: Now that we no longer use the MINIMAL-DEBUG-FUNCTION
1858 ;;; representation, calls to this function can be replaced by calls to
1859 ;;; the bare COMPILED-DEBUG-INFO-FUNCTION-MAP slot accessor function,
1860 ;;; and this function and everything it calls become dead code which
1861 ;;; can be deleted.
1862 (defun get-debug-info-function-map (info)
1863   (declare (type sb!c::compiled-debug-info info))
1864   (let ((map (sb!c::compiled-debug-info-function-map info)))
1865     (if (simple-vector-p map)
1866         map
1867         (or (gethash map *uncompacted-function-maps*)
1868             (setf (gethash map *uncompacted-function-maps*)
1869                   (uncompact-function-map info))))))
1870 \f
1871 ;;;; CODE-LOCATIONs
1872
1873 ;;; If we're sure of whether code-location is known, return T or NIL.
1874 ;;; If we're :UNSURE, then try to fill in the code-location's slots.
1875 ;;; This determines whether there is any debug-block information, and
1876 ;;; if code-location is known.
1877 ;;;
1878 ;;; ??? IF this conses closures every time it's called, then break off the
1879 ;;; :UNSURE part to get the HANDLER-CASE into another function.
1880 (defun code-location-unknown-p (basic-code-location)
1881   (ecase (code-location-%unknown-p basic-code-location)
1882     ((t) t)
1883     ((nil) nil)
1884     (:unsure
1885      (setf (code-location-%unknown-p basic-code-location)
1886            (handler-case (not (fill-in-code-location basic-code-location))
1887              (no-debug-blocks () t))))))
1888
1889 ;;; Return the DEBUG-BLOCK containing code-location if it is available.
1890 ;;; Some debug policies inhibit debug-block information, and if none
1891 ;;; is available, then this signals a NO-DEBUG-BLOCKS condition.
1892 (defun code-location-debug-block (basic-code-location)
1893   (let ((block (code-location-%debug-block basic-code-location)))
1894     (if (eq block :unparsed)
1895         (etypecase basic-code-location
1896           (compiled-code-location
1897            (compute-compiled-code-location-debug-block basic-code-location))
1898           ;; (There used to be more cases back before sbcl-0.7.0, when
1899           ;; we did special tricks to debug the IR1 interpreter.)
1900           )
1901         block)))
1902
1903 ;;; Store and return BASIC-CODE-LOCATION's debug-block. We determines
1904 ;;; the correct one using the code-location's pc. We use
1905 ;;; DEBUG-FUNCTION-DEBUG-BLOCKS to return the cached block information
1906 ;;; or signal a NO-DEBUG-BLOCKS condition. The blocks are sorted by
1907 ;;; their first code-location's pc, in ascending order. Therefore, as
1908 ;;; soon as we find a block that starts with a pc greater than
1909 ;;; basic-code-location's pc, we know the previous block contains the
1910 ;;; pc. If we get to the last block, then the code-location is either
1911 ;;; in the second to last block or the last block, and we have to be
1912 ;;; careful in determining this since the last block could be code at
1913 ;;; the end of the function. We have to check for the last block being
1914 ;;; code first in order to see how to compare the code-location's pc.
1915 (defun compute-compiled-code-location-debug-block (basic-code-location)
1916   (let* ((pc (compiled-code-location-pc basic-code-location))
1917          (debug-function (code-location-debug-function
1918                           basic-code-location))
1919          (blocks (debug-function-debug-blocks debug-function))
1920          (len (length blocks)))
1921     (declare (simple-vector blocks))
1922     (setf (code-location-%debug-block basic-code-location)
1923           (if (= len 1)
1924               (svref blocks 0)
1925               (do ((i 1 (1+ i))
1926                    (end (1- len)))
1927                   ((= i end)
1928                    (let ((last (svref blocks end)))
1929                      (cond
1930                       ((debug-block-elsewhere-p last)
1931                        (if (< pc
1932                               (sb!c::compiled-debug-function-elsewhere-pc
1933                                (compiled-debug-function-compiler-debug-fun
1934                                 debug-function)))
1935                            (svref blocks (1- end))
1936                            last))
1937                       ((< pc
1938                           (compiled-code-location-pc
1939                            (svref (compiled-debug-block-code-locations last)
1940                                   0)))
1941                        (svref blocks (1- end)))
1942                       (t last))))
1943                 (declare (type sb!c::index i end))
1944                 (when (< pc
1945                          (compiled-code-location-pc
1946                           (svref (compiled-debug-block-code-locations
1947                                   (svref blocks i))
1948                                  0)))
1949                   (return (svref blocks (1- i)))))))))
1950
1951 ;;; Return the CODE-LOCATION's DEBUG-SOURCE.
1952 (defun code-location-debug-source (code-location)
1953   (etypecase code-location
1954     (compiled-code-location
1955      (let* ((info (compiled-debug-function-debug-info
1956                    (code-location-debug-function code-location)))
1957             (sources (sb!c::compiled-debug-info-source info))
1958             (len (length sources)))
1959        (declare (list sources))
1960        (when (zerop len)
1961          (debug-signal 'no-debug-blocks :debug-function
1962                        (code-location-debug-function code-location)))
1963        (if (= len 1)
1964            (car sources)
1965            (do ((prev sources src)
1966                 (src (cdr sources) (cdr src))
1967                 (offset (code-location-top-level-form-offset code-location)))
1968                ((null src) (car prev))
1969              (when (< offset (sb!c::debug-source-source-root (car src)))
1970                (return (car prev)))))))
1971     ;; (There used to be more cases back before sbcl-0.7.0, when we
1972     ;; did special tricks to debug the IR1 interpreter.)
1973     ))
1974
1975 ;;; Returns the number of top-level forms before the one containing
1976 ;;; CODE-LOCATION as seen by the compiler in some compilation unit. (A
1977 ;;; compilation unit is not necessarily a single file, see the section
1978 ;;; on debug-sources.)
1979 (defun code-location-top-level-form-offset (code-location)
1980   (when (code-location-unknown-p code-location)
1981     (error 'unknown-code-location :code-location code-location))
1982   (let ((tlf-offset (code-location-%tlf-offset code-location)))
1983     (cond ((eq tlf-offset :unparsed)
1984            (etypecase code-location
1985              (compiled-code-location
1986               (unless (fill-in-code-location code-location)
1987                 ;; This check should be unnecessary. We're missing
1988                 ;; debug info the compiler should have dumped.
1989                 (error "internal error: unknown code location"))
1990               (code-location-%tlf-offset code-location))
1991              ;; (There used to be more cases back before sbcl-0.7.0,,
1992              ;; when we did special tricks to debug the IR1
1993              ;; interpreter.)
1994              ))
1995           (t tlf-offset))))
1996
1997 ;;; Return the number of the form corresponding to CODE-LOCATION. The
1998 ;;; form number is derived by a walking the subforms of a top-level
1999 ;;; form in depth-first order.
2000 (defun code-location-form-number (code-location)
2001   (when (code-location-unknown-p code-location)
2002     (error 'unknown-code-location :code-location code-location))
2003   (let ((form-num (code-location-%form-number code-location)))
2004     (cond ((eq form-num :unparsed)
2005            (etypecase code-location
2006              (compiled-code-location
2007               (unless (fill-in-code-location code-location)
2008                 ;; This check should be unnecessary. We're missing
2009                 ;; debug info the compiler should have dumped.
2010                 (error "internal error: unknown code location"))
2011               (code-location-%form-number code-location))
2012              ;; (There used to be more cases back before sbcl-0.7.0,,
2013              ;; when we did special tricks to debug the IR1
2014              ;; interpreter.)
2015              ))
2016           (t form-num))))
2017
2018 ;;; Return the kind of CODE-LOCATION, one of:
2019 ;;;  :INTERPRETED, :UNKNOWN-RETURN, :KNOWN-RETURN, :INTERNAL-ERROR,
2020 ;;;  :NON-LOCAL-EXIT, :BLOCK-START, :CALL-SITE, :SINGLE-VALUE-RETURN,
2021 ;;;  :NON-LOCAL-ENTRY
2022 (defun code-location-kind (code-location)
2023   (when (code-location-unknown-p code-location)
2024     (error 'unknown-code-location :code-location code-location))
2025   (etypecase code-location
2026     (compiled-code-location
2027      (let ((kind (compiled-code-location-kind code-location)))
2028        (cond ((not (eq kind :unparsed)) kind)
2029              ((not (fill-in-code-location code-location))
2030               ;; This check should be unnecessary. We're missing
2031               ;; debug info the compiler should have dumped.
2032               (error "internal error: unknown code location"))
2033              (t
2034               (compiled-code-location-kind code-location)))))
2035     ;; (There used to be more cases back before sbcl-0.7.0,,
2036     ;; when we did special tricks to debug the IR1
2037     ;; interpreter.)
2038     ))
2039
2040 ;;; This returns CODE-LOCATION's live-set if it is available. If
2041 ;;; there is no debug-block information, this returns NIL.
2042 (defun compiled-code-location-live-set (code-location)
2043   (if (code-location-unknown-p code-location)
2044       nil
2045       (let ((live-set (compiled-code-location-%live-set code-location)))
2046         (cond ((eq live-set :unparsed)
2047                (unless (fill-in-code-location code-location)
2048                  ;; This check should be unnecessary. We're missing
2049                  ;; debug info the compiler should have dumped.
2050                  ;;
2051                  ;; FIXME: This error and comment happen over and over again.
2052                  ;; Make them a shared function.
2053                  (error "internal error: unknown code location"))
2054                (compiled-code-location-%live-set code-location))
2055               (t live-set)))))
2056
2057 ;;; true if OBJ1 and OBJ2 are the same place in the code
2058 (defun code-location= (obj1 obj2)
2059   (etypecase obj1
2060     (compiled-code-location
2061      (etypecase obj2
2062        (compiled-code-location
2063         (and (eq (code-location-debug-function obj1)
2064                  (code-location-debug-function obj2))
2065              (sub-compiled-code-location= obj1 obj2)))
2066        ;; (There used to be more cases back before sbcl-0.7.0,,
2067        ;; when we did special tricks to debug the IR1
2068        ;; interpreter.)
2069        ))
2070     ;; (There used to be more cases back before sbcl-0.7.0,,
2071     ;; when we did special tricks to debug the IR1
2072     ;; interpreter.)
2073     ))
2074 (defun sub-compiled-code-location= (obj1 obj2)
2075   (= (compiled-code-location-pc obj1)
2076      (compiled-code-location-pc obj2)))
2077
2078 ;;; Fill in CODE-LOCATION's :UNPARSED slots, returning T or NIL
2079 ;;; depending on whether the code-location was known in its
2080 ;;; debug-function's debug-block information. This may signal a
2081 ;;; NO-DEBUG-BLOCKS condition due to DEBUG-FUNCTION-DEBUG-BLOCKS, and
2082 ;;; it assumes the %UNKNOWN-P slot is already set or going to be set.
2083 (defun fill-in-code-location (code-location)
2084   (declare (type compiled-code-location code-location))
2085   (let* ((debug-function (code-location-debug-function code-location))
2086          (blocks (debug-function-debug-blocks debug-function)))
2087     (declare (simple-vector blocks))
2088     (dotimes (i (length blocks) nil)
2089       (let* ((block (svref blocks i))
2090              (locations (compiled-debug-block-code-locations block)))
2091         (declare (simple-vector locations))
2092         (dotimes (j (length locations))
2093           (let ((loc (svref locations j)))
2094             (when (sub-compiled-code-location= code-location loc)
2095               (setf (code-location-%debug-block code-location) block)
2096               (setf (code-location-%tlf-offset code-location)
2097                     (code-location-%tlf-offset loc))
2098               (setf (code-location-%form-number code-location)
2099                     (code-location-%form-number loc))
2100               (setf (compiled-code-location-%live-set code-location)
2101                     (compiled-code-location-%live-set loc))
2102               (setf (compiled-code-location-kind code-location)
2103                     (compiled-code-location-kind loc))
2104               (return-from fill-in-code-location t))))))))
2105 \f
2106 ;;;; operations on DEBUG-BLOCKs
2107
2108 ;;; Execute FORMS in a context with CODE-VAR bound to each
2109 ;;; CODE-LOCATION in DEBUG-BLOCK, and return the value of RESULT.
2110 (defmacro do-debug-block-locations ((code-var debug-block &optional result)
2111                                     &body body)
2112   (let ((code-locations (gensym))
2113         (i (gensym)))
2114     `(let ((,code-locations (debug-block-code-locations ,debug-block)))
2115        (declare (simple-vector ,code-locations))
2116        (dotimes (,i (length ,code-locations) ,result)
2117          (let ((,code-var (svref ,code-locations ,i)))
2118            ,@body)))))
2119
2120 ;;; Return the name of the function represented by DEBUG-FUNCTION.
2121 ;;; This may be a string or a cons; do not assume it is a symbol.
2122 (defun debug-block-function-name (debug-block)
2123   (etypecase debug-block
2124     (compiled-debug-block
2125      (let ((code-locs (compiled-debug-block-code-locations debug-block)))
2126        (declare (simple-vector code-locs))
2127        (if (zerop (length code-locs))
2128            "??? Can't get name of debug-block's function."
2129            (debug-function-name
2130             (code-location-debug-function (svref code-locs 0))))))
2131     ;; (There used to be more cases back before sbcl-0.7.0, when we
2132     ;; did special tricks to debug the IR1 interpreter.)
2133     ))
2134
2135 (defun debug-block-code-locations (debug-block)
2136   (etypecase debug-block
2137     (compiled-debug-block
2138      (compiled-debug-block-code-locations debug-block))
2139     ;; (There used to be more cases back before sbcl-0.7.0, when we
2140     ;; did special tricks to debug the IR1 interpreter.)
2141     ))
2142 \f
2143 ;;;; operations on debug variables
2144
2145 (defun debug-var-symbol-name (debug-var)
2146   (symbol-name (debug-var-symbol debug-var)))
2147
2148 ;;; FIXME: Make sure that this isn't called anywhere that it wouldn't
2149 ;;; be acceptable to have NIL returned, or that it's only called on
2150 ;;; DEBUG-VARs whose symbols have non-NIL packages.
2151 (defun debug-var-package-name (debug-var)
2152   (package-name (symbol-package (debug-var-symbol debug-var))))
2153
2154 ;;; Return the value stored for DEBUG-VAR in frame, or if the value is
2155 ;;; not :VALID, then signal an INVALID-VALUE error.
2156 (defun debug-var-valid-value (debug-var frame)
2157   (unless (eq (debug-var-validity debug-var (frame-code-location frame))
2158               :valid)
2159     (error 'invalid-value :debug-var debug-var :frame frame))
2160   (debug-var-value debug-var frame))
2161
2162 ;;; Returns the value stored for DEBUG-VAR in frame. The value may be
2163 ;;; invalid. This is SETFable.
2164 (defun debug-var-value (debug-var frame)
2165   (etypecase debug-var
2166     (compiled-debug-var
2167      (aver (typep frame 'compiled-frame))
2168      (let ((res (access-compiled-debug-var-slot debug-var frame)))
2169        (if (indirect-value-cell-p res)
2170            (value-cell-ref res)
2171            res)))
2172     ;; (This function used to be more interesting, with more type
2173     ;; cases here, before the IR1 interpreter went away. It might
2174     ;; become more interesting again if we ever try to generalize the
2175     ;; CMU CL POSSIBLY-AN-INTERPRETED-FRAME thing to elide
2176     ;; internal-to-the-byte-interpreter debug frames the way that CMU
2177     ;; CL elided internal-to-the-IR1-interpreter debug frames.)
2178     ))
2179
2180 ;;; This returns what is stored for the variable represented by
2181 ;;; DEBUG-VAR relative to the FRAME. This may be an indirect value
2182 ;;; cell if the variable is both closed over and set.
2183 (defun access-compiled-debug-var-slot (debug-var frame)
2184   (declare (optimize (speed 1)))
2185   (let ((escaped (compiled-frame-escaped frame)))
2186     (if escaped
2187         (sub-access-debug-var-slot
2188          (frame-pointer frame)
2189          (compiled-debug-var-sc-offset debug-var)
2190          escaped)
2191       (sub-access-debug-var-slot
2192        (frame-pointer frame)
2193        (or (compiled-debug-var-save-sc-offset debug-var)
2194            (compiled-debug-var-sc-offset debug-var))))))
2195
2196 ;;; a helper function for working with possibly-invalid values:
2197 ;;; Do (MAKE-LISP-OBJ VAL) only if the value looks valid.
2198 ;;;
2199 ;;; (Such values can arise in registers on machines with conservative
2200 ;;; GC, and might also arise in debug variable locations when
2201 ;;; those variables are invalid.)
2202 (defun make-valid-lisp-obj (val)
2203   (/show0 "entering MAKE-VALID-LISP-OBJ, VAL=..")
2204   #!+sb-show (/hexstr val)
2205   (if (or
2206        ;; fixnum
2207        (zerop (logand val 3))
2208        ;; character
2209        (and (zerop (logand val #xffff0000)) ; Top bits zero
2210             (= (logand val #xff) sb!vm:base-char-type)) ; Char tag
2211        ;; unbound marker
2212        (= val sb!vm:unbound-marker-type)
2213        ;; pointer
2214        (and (logand val 1)
2215             ;; Check that the pointer is valid. XXX Could do a better
2216             ;; job. FIXME: e.g. by calling out to an is_valid_pointer
2217             ;; routine in the C runtime support code
2218             (or (< sb!vm:read-only-space-start val
2219                    (* sb!vm:*read-only-space-free-pointer*
2220                       sb!vm:word-bytes))
2221                 (< sb!vm:static-space-start val
2222                    (* sb!vm:*static-space-free-pointer*
2223                       sb!vm:word-bytes))
2224                 (< sb!vm:dynamic-space-start val
2225                    (sap-int (dynamic-space-free-pointer))))))
2226       (make-lisp-obj val)
2227       :invalid-object))
2228
2229 #!-x86
2230 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2231   (macrolet ((with-escaped-value ((var) &body forms)
2232                `(if escaped
2233                     (let ((,var (sb!vm:context-register
2234                                  escaped
2235                                  (sb!c:sc-offset-offset sc-offset))))
2236                       ,@forms)
2237                     :invalid-value-for-unescaped-register-storage))
2238              (escaped-float-value (format)
2239                `(if escaped
2240                     (sb!vm:context-float-register
2241                      escaped
2242                      (sb!c:sc-offset-offset sc-offset)
2243                      ',format)
2244                     :invalid-value-for-unescaped-register-storage))
2245              (with-nfp ((var) &body body)
2246                `(let ((,var (if escaped
2247                                 (sb!sys:int-sap
2248                                  (sb!vm:context-register escaped
2249                                                          sb!vm::nfp-offset))
2250                                 #!-alpha
2251                                 (sb!sys:sap-ref-sap fp (* sb!vm::nfp-save-offset
2252                                                           sb!vm:word-bytes))
2253                                 #!+alpha
2254                                 (sb!vm::make-number-stack-pointer
2255                                  (sb!sys:sap-ref-32 fp (* sb!vm::nfp-save-offset
2256                                                           sb!vm:word-bytes))))))
2257                   ,@body)))
2258     (ecase (sb!c:sc-offset-scn sc-offset)
2259       ((#.sb!vm:any-reg-sc-number
2260         #.sb!vm:descriptor-reg-sc-number
2261         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2262        (sb!sys:without-gcing
2263         (with-escaped-value (val) (sb!kernel:make-lisp-obj val))))
2264                             
2265       (#.sb!vm:base-char-reg-sc-number
2266        (with-escaped-value (val)
2267          (code-char val)))
2268       (#.sb!vm:sap-reg-sc-number
2269        (with-escaped-value (val)
2270          (sb!sys:int-sap val)))
2271       (#.sb!vm:signed-reg-sc-number
2272        (with-escaped-value (val)
2273          (if (logbitp (1- sb!vm:word-bits) val)
2274              (logior val (ash -1 sb!vm:word-bits))
2275              val)))
2276       (#.sb!vm:unsigned-reg-sc-number
2277        (with-escaped-value (val)
2278          val))
2279       (#.sb!vm:non-descriptor-reg-sc-number
2280        (error "Local non-descriptor register access?"))
2281       (#.sb!vm:interior-reg-sc-number
2282        (error "Local interior register access?"))
2283       (#.sb!vm:single-reg-sc-number
2284        (escaped-float-value single-float))
2285       (#.sb!vm:double-reg-sc-number
2286        (escaped-float-value double-float))
2287       #!+long-float
2288       (#.sb!vm:long-reg-sc-number
2289        (escaped-float-value long-float))
2290       (#.sb!vm:complex-single-reg-sc-number
2291        (if escaped
2292            (complex
2293             (sb!vm:context-float-register
2294              escaped (sb!c:sc-offset-offset sc-offset) 'single-float)
2295             (sb!vm:context-float-register
2296              escaped (1+ (sb!c:sc-offset-offset sc-offset)) 'single-float))
2297            :invalid-value-for-unescaped-register-storage))
2298       (#.sb!vm:complex-double-reg-sc-number
2299        (if escaped
2300            (complex
2301             (sb!vm:context-float-register
2302              escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2303             (sb!vm:context-float-register
2304              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #-sparc 1)
2305              'double-float))
2306            :invalid-value-for-unescaped-register-storage))
2307       #!+long-float
2308       (#.sb!vm:complex-long-reg-sc-number
2309        (if escaped
2310            (complex
2311             (sb!vm:context-float-register
2312              escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2313             (sb!vm:context-float-register
2314              escaped (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2315              'long-float))
2316            :invalid-value-for-unescaped-register-storage))
2317       (#.sb!vm:single-stack-sc-number
2318        (with-nfp (nfp)
2319          (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2320                                        sb!vm:word-bytes))))
2321       (#.sb!vm:double-stack-sc-number
2322        (with-nfp (nfp)
2323          (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2324                                        sb!vm:word-bytes))))
2325       #!+long-float
2326       (#.sb!vm:long-stack-sc-number
2327        (with-nfp (nfp)
2328          (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2329                                      sb!vm:word-bytes))))
2330       (#.sb!vm:complex-single-stack-sc-number
2331        (with-nfp (nfp)
2332          (complex
2333           (sb!sys:sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2334                                         sb!vm:word-bytes))
2335           (sb!sys:sap-ref-single nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2336                                         sb!vm:word-bytes)))))
2337       (#.sb!vm:complex-double-stack-sc-number
2338        (with-nfp (nfp)
2339          (complex
2340           (sb!sys:sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2341                                         sb!vm:word-bytes))
2342           (sb!sys:sap-ref-double nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2343                                         sb!vm:word-bytes)))))
2344       #!+long-float
2345       (#.sb!vm:complex-long-stack-sc-number
2346        (with-nfp (nfp)
2347          (complex
2348           (sb!sys:sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2349                                       sb!vm:word-bytes))
2350           (sb!sys:sap-ref-long nfp (* (+ (sb!c:sc-offset-offset sc-offset)
2351                                          #!+sparc 4)
2352                                       sb!vm:word-bytes)))))
2353       (#.sb!vm:control-stack-sc-number
2354        (sb!kernel:stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2355       (#.sb!vm:base-char-stack-sc-number
2356        (with-nfp (nfp)
2357          (code-char (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2358                                               sb!vm:word-bytes)))))
2359       (#.sb!vm:unsigned-stack-sc-number
2360        (with-nfp (nfp)
2361          (sb!sys:sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2362                                    sb!vm:word-bytes))))
2363       (#.sb!vm:signed-stack-sc-number
2364        (with-nfp (nfp)
2365          (sb!sys:signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2366                                           sb!vm:word-bytes))))
2367       (#.sb!vm:sap-stack-sc-number
2368        (with-nfp (nfp)
2369          (sb!sys:sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2370                                     sb!vm:word-bytes)))))))
2371
2372 #!+x86
2373 (defun sub-access-debug-var-slot (fp sc-offset &optional escaped)
2374   (declare (type system-area-pointer fp))
2375   (/show0 "entering SUB-ACCESS-DEBUG-VAR-SLOT, FP,SC-OFFSET,ESCAPED=..")
2376   (/hexstr fp) (/hexstr sc-offset) (/hexstr escaped)
2377   (macrolet ((with-escaped-value ((var) &body forms)
2378                `(if escaped
2379                     (let ((,var (sb!vm:context-register
2380                                  escaped
2381                                  (sb!c:sc-offset-offset sc-offset))))
2382                       (/show0 "in escaped case, ,VAR value=..")
2383                       (/hexstr ,var)
2384                       ,@forms)
2385                     :invalid-value-for-unescaped-register-storage))
2386              (escaped-float-value (format)
2387                `(if escaped
2388                     (sb!vm:context-float-register
2389                      escaped (sb!c:sc-offset-offset sc-offset) ',format)
2390                     :invalid-value-for-unescaped-register-storage))
2391              (escaped-complex-float-value (format)
2392                `(if escaped
2393                     (complex
2394                      (sb!vm:context-float-register
2395                       escaped (sb!c:sc-offset-offset sc-offset) ',format)
2396                      (sb!vm:context-float-register
2397                       escaped (1+ (sb!c:sc-offset-offset sc-offset)) ',format))
2398                     :invalid-value-for-unescaped-register-storage)))
2399     (ecase (sb!c:sc-offset-scn sc-offset)
2400       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2401        (/show0 "case of ANY-REG-SC-NUMBER or DESCRIPTOR-REG-SC-NUMBER")
2402        (without-gcing
2403         (with-escaped-value (val)
2404           (/show0 "VAL=..")
2405           (/hexstr val)
2406           (make-valid-lisp-obj val))))
2407       (#.sb!vm:base-char-reg-sc-number
2408        (/show0 "case of BASE-CHAR-REG-SC-NUMBER")
2409        (with-escaped-value (val)
2410          (code-char val)))
2411       (#.sb!vm:sap-reg-sc-number
2412        (/show0 "case of SAP-REG-SC-NUMBER")
2413        (with-escaped-value (val)
2414          (int-sap val)))
2415       (#.sb!vm:signed-reg-sc-number
2416        (/show0 "case of SIGNED-REG-SC-NUMBER")
2417        (with-escaped-value (val)
2418          (if (logbitp (1- sb!vm:word-bits) val)
2419              (logior val (ash -1 sb!vm:word-bits))
2420              val)))
2421       (#.sb!vm:unsigned-reg-sc-number
2422        (/show0 "case of UNSIGNED-REG-SC-NUMBER")
2423        (with-escaped-value (val)
2424          val))
2425       (#.sb!vm:single-reg-sc-number
2426        (/show0 "case of SINGLE-REG-SC-NUMBER")
2427        (escaped-float-value single-float))
2428       (#.sb!vm:double-reg-sc-number
2429        (/show0 "case of DOUBLE-REG-SC-NUMBER")
2430        (escaped-float-value double-float))
2431       #!+long-float
2432       (#.sb!vm:long-reg-sc-number
2433        (/show0 "case of LONG-REG-SC-NUMBER")
2434        (escaped-float-value long-float))
2435       (#.sb!vm:complex-single-reg-sc-number
2436        (/show0 "case of COMPLEX-SINGLE-REG-SC-NUMBER")
2437        (escaped-complex-float-value single-float))
2438       (#.sb!vm:complex-double-reg-sc-number
2439        (/show0 "case of COMPLEX-DOUBLE-REG-SC-NUMBER")
2440        (escaped-complex-float-value double-float))
2441       #!+long-float
2442       (#.sb!vm:complex-long-reg-sc-number
2443        (/show0 "case of COMPLEX-LONG-REG-SC-NUMBER")
2444        (escaped-complex-float-value long-float))
2445       (#.sb!vm:single-stack-sc-number
2446        (/show0 "case of SINGLE-STACK-SC-NUMBER")
2447        (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2448                                 sb!vm:word-bytes))))
2449       (#.sb!vm:double-stack-sc-number
2450        (/show0 "case of DOUBLE-STACK-SC-NUMBER")
2451        (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2452                                 sb!vm:word-bytes))))
2453       #!+long-float
2454       (#.sb!vm:long-stack-sc-number
2455        (/show0 "case of LONG-STACK-SC-NUMBER")
2456        (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2457                               sb!vm:word-bytes))))
2458       (#.sb!vm:complex-single-stack-sc-number
2459        (/show0 "case of COMPLEX-STACK-SC-NUMBER")
2460        (complex
2461         (sap-ref-single fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2462                                  sb!vm:word-bytes)))
2463         (sap-ref-single fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2464                                  sb!vm:word-bytes)))))
2465       (#.sb!vm:complex-double-stack-sc-number
2466        (/show0 "case of COMPLEX-DOUBLE-STACK-SC-NUMBER")
2467        (complex
2468         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2469                                  sb!vm:word-bytes)))
2470         (sap-ref-double fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2471                                  sb!vm:word-bytes)))))
2472       #!+long-float
2473       (#.sb!vm:complex-long-stack-sc-number
2474        (/show0 "case of COMPLEX-LONG-STACK-SC-NUMBER")
2475        (complex
2476         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2477                                sb!vm:word-bytes)))
2478         (sap-ref-long fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2479                                sb!vm:word-bytes)))))
2480       (#.sb!vm:control-stack-sc-number
2481        (/show0 "case of CONTROL-STACK-SC-NUMBER")
2482        (stack-ref fp (sb!c:sc-offset-offset sc-offset)))
2483       (#.sb!vm:base-char-stack-sc-number
2484        (/show0 "case of BASE-CHAR-STACK-SC-NUMBER")
2485        (code-char
2486         (sap-ref-32 fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2487                              sb!vm:word-bytes)))))
2488       (#.sb!vm:unsigned-stack-sc-number
2489        (/show0 "case of UNSIGNED-STACK-SC-NUMBER")
2490        (sap-ref-32 fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2491                             sb!vm:word-bytes))))
2492       (#.sb!vm:signed-stack-sc-number
2493        (/show0 "case of SIGNED-STACK-SC-NUMBER")
2494        (signed-sap-ref-32 fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2495                                    sb!vm:word-bytes))))
2496       (#.sb!vm:sap-stack-sc-number
2497        (/show0 "case of SAP-STACK-SC-NUMBER")
2498        (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2499                              sb!vm:word-bytes)))))))
2500
2501 ;;; This stores value as the value of DEBUG-VAR in FRAME. In the
2502 ;;; COMPILED-DEBUG-VAR case, access the current value to determine if
2503 ;;; it is an indirect value cell. This occurs when the variable is
2504 ;;; both closed over and set.
2505 (defun %set-debug-var-value (debug-var frame value)
2506   (etypecase debug-var
2507     (compiled-debug-var
2508      (aver (typep frame 'compiled-frame))
2509      (let ((current-value (access-compiled-debug-var-slot debug-var frame)))
2510        (if (indirect-value-cell-p current-value)
2511            (value-cell-set current-value value)
2512            (set-compiled-debug-var-slot debug-var frame value))))
2513     ;; (This function used to be more interesting, with more type
2514     ;; cases here, before the IR1 interpreter went away. It might
2515     ;; become more interesting again if we ever try to generalize the
2516     ;; CMU CL POSSIBLY-AN-INTERPRETED-FRAME thing to elide
2517     ;; internal-to-the-byte-interpreter debug frames the way that CMU
2518     ;; CL elided internal-to-the-IR1-interpreter debug frames.)
2519     )
2520   value)
2521
2522 ;;; This stores value for the variable represented by debug-var
2523 ;;; relative to the frame. This assumes the location directly contains
2524 ;;; the variable's value; that is, there is no indirect value cell
2525 ;;; currently there in case the variable is both closed over and set.
2526 (defun set-compiled-debug-var-slot (debug-var frame value)
2527   (let ((escaped (compiled-frame-escaped frame)))
2528     (if escaped
2529         (sub-set-debug-var-slot (frame-pointer frame)
2530                                 (compiled-debug-var-sc-offset debug-var)
2531                                 value escaped)
2532         (sub-set-debug-var-slot
2533          (frame-pointer frame)
2534          (or (compiled-debug-var-save-sc-offset debug-var)
2535              (compiled-debug-var-sc-offset debug-var))
2536          value))))
2537
2538 #!-x86
2539 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2540   (macrolet ((set-escaped-value (val)
2541                `(if escaped
2542                     (setf (sb!vm:context-register
2543                            escaped
2544                            (sb!c:sc-offset-offset sc-offset))
2545                           ,val)
2546                     value))
2547              (set-escaped-float-value (format val)
2548                `(if escaped
2549                     (setf (sb!vm:context-float-register
2550                            escaped
2551                            (sb!c:sc-offset-offset sc-offset)
2552                            ',format)
2553                           ,val)
2554                     value))
2555              (with-nfp ((var) &body body)
2556                `(let ((,var (if escaped
2557                                 (int-sap
2558                                  (sb!vm:context-register escaped
2559                                                          sb!vm::nfp-offset))
2560                                 #!-alpha
2561                                 (sap-ref-sap fp
2562                                              (* sb!vm::nfp-save-offset
2563                                                 sb!vm:word-bytes))
2564                                 #!+alpha
2565                                 (sb!vm::make-number-stack-pointer
2566                                  (sap-ref-32 fp
2567                                              (* sb!vm::nfp-save-offset
2568                                                 sb!vm:word-bytes))))))
2569                   ,@body)))
2570     (ecase (sb!c:sc-offset-scn sc-offset)
2571       ((#.sb!vm:any-reg-sc-number
2572         #.sb!vm:descriptor-reg-sc-number
2573         #!+rt #.sb!vm:word-pointer-reg-sc-number)
2574        (without-gcing
2575         (set-escaped-value
2576           (get-lisp-obj-address value))))
2577       (#.sb!vm:base-char-reg-sc-number
2578        (set-escaped-value (char-code value)))
2579       (#.sb!vm:sap-reg-sc-number
2580        (set-escaped-value (sap-int value)))
2581       (#.sb!vm:signed-reg-sc-number
2582        (set-escaped-value (logand value (1- (ash 1 sb!vm:word-bits)))))
2583       (#.sb!vm:unsigned-reg-sc-number
2584        (set-escaped-value value))
2585       (#.sb!vm:non-descriptor-reg-sc-number
2586        (error "Local non-descriptor register access?"))
2587       (#.sb!vm:interior-reg-sc-number
2588        (error "Local interior register access?"))
2589       (#.sb!vm:single-reg-sc-number
2590        (set-escaped-float-value single-float value))
2591       (#.sb!vm:double-reg-sc-number
2592        (set-escaped-float-value double-float value))
2593       #!+long-float
2594       (#.sb!vm:long-reg-sc-number
2595        (set-escaped-float-value long-float value))
2596       (#.sb!vm:complex-single-reg-sc-number
2597        (when escaped
2598          (setf (sb!vm:context-float-register escaped
2599                                              (sb!c:sc-offset-offset sc-offset)
2600                                              'single-float)
2601                (realpart value))
2602          (setf (sb!vm:context-float-register
2603                 escaped (1+ (sb!c:sc-offset-offset sc-offset))
2604                 'single-float)
2605                (imagpart value)))
2606        value)
2607       (#.sb!vm:complex-double-reg-sc-number
2608        (when escaped
2609          (setf (sb!vm:context-float-register
2610                 escaped (sb!c:sc-offset-offset sc-offset) 'double-float)
2611                (realpart value))
2612          (setf (sb!vm:context-float-register
2613                 escaped
2614                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 2 #!-sparc 1)
2615                 'double-float)
2616                (imagpart value)))
2617        value)
2618       #!+long-float
2619       (#.sb!vm:complex-long-reg-sc-number
2620        (when escaped
2621          (setf (sb!vm:context-float-register
2622                 escaped (sb!c:sc-offset-offset sc-offset) 'long-float)
2623                (realpart value))
2624          (setf (sb!vm:context-float-register
2625                 escaped
2626                 (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2627                 'long-float)
2628                (imagpart value)))
2629        value)
2630       (#.sb!vm:single-stack-sc-number
2631        (with-nfp (nfp)
2632          (setf (sap-ref-single nfp (* (sb!c:sc-offset-offset sc-offset)
2633                                       sb!vm:word-bytes))
2634                (the single-float value))))
2635       (#.sb!vm:double-stack-sc-number
2636        (with-nfp (nfp)
2637          (setf (sap-ref-double nfp (* (sb!c:sc-offset-offset sc-offset)
2638                                       sb!vm:word-bytes))
2639                (the double-float value))))
2640       #!+long-float
2641       (#.sb!vm:long-stack-sc-number
2642        (with-nfp (nfp)
2643          (setf (sap-ref-long nfp (* (sb!c:sc-offset-offset sc-offset)
2644                                     sb!vm:word-bytes))
2645                (the long-float value))))
2646       (#.sb!vm:complex-single-stack-sc-number
2647        (with-nfp (nfp)
2648          (setf (sap-ref-single
2649                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:word-bytes))
2650                (the single-float (realpart value)))
2651          (setf (sap-ref-single
2652                 nfp (* (1+ (sb!c:sc-offset-offset sc-offset))
2653                        sb!vm:word-bytes))
2654                (the single-float (realpart value)))))
2655       (#.sb!vm:complex-double-stack-sc-number
2656        (with-nfp (nfp)
2657          (setf (sap-ref-double
2658                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:word-bytes))
2659                (the double-float (realpart value)))
2660          (setf (sap-ref-double
2661                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2662                        sb!vm:word-bytes))
2663                (the double-float (realpart value)))))
2664       #!+long-float
2665       (#.sb!vm:complex-long-stack-sc-number
2666        (with-nfp (nfp)
2667          (setf (sap-ref-long
2668                 nfp (* (sb!c:sc-offset-offset sc-offset) sb!vm:word-bytes))
2669                (the long-float (realpart value)))
2670          (setf (sap-ref-long
2671                 nfp (* (+ (sb!c:sc-offset-offset sc-offset) #!+sparc 4)
2672                        sb!vm:word-bytes))
2673                (the long-float (realpart value)))))
2674       (#.sb!vm:control-stack-sc-number
2675        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2676       (#.sb!vm:base-char-stack-sc-number
2677        (with-nfp (nfp)
2678          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2679                                          sb!vm:word-bytes))
2680                (char-code (the character value)))))
2681       (#.sb!vm:unsigned-stack-sc-number
2682        (with-nfp (nfp)
2683          (setf (sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2684                                   sb!vm:word-bytes))
2685                (the (unsigned-byte 32) value))))
2686       (#.sb!vm:signed-stack-sc-number
2687        (with-nfp (nfp)
2688          (setf (signed-sap-ref-32 nfp (* (sb!c:sc-offset-offset sc-offset)
2689                                          sb!vm:word-bytes))
2690                (the (signed-byte 32) value))))
2691       (#.sb!vm:sap-stack-sc-number
2692        (with-nfp (nfp)
2693          (setf (sap-ref-sap nfp (* (sb!c:sc-offset-offset sc-offset)
2694                                    sb!vm:word-bytes))
2695                (the system-area-pointer value)))))))
2696
2697 #!+x86
2698 (defun sub-set-debug-var-slot (fp sc-offset value &optional escaped)
2699   (macrolet ((set-escaped-value (val)
2700                `(if escaped
2701                     (setf (sb!vm:context-register
2702                            escaped
2703                            (sb!c:sc-offset-offset sc-offset))
2704                           ,val)
2705                     value)))
2706     (ecase (sb!c:sc-offset-scn sc-offset)
2707       ((#.sb!vm:any-reg-sc-number #.sb!vm:descriptor-reg-sc-number)
2708        (without-gcing
2709         (set-escaped-value
2710           (get-lisp-obj-address value))))
2711       (#.sb!vm:base-char-reg-sc-number
2712        (set-escaped-value (char-code value)))
2713       (#.sb!vm:sap-reg-sc-number
2714        (set-escaped-value (sap-int value)))
2715       (#.sb!vm:signed-reg-sc-number
2716        (set-escaped-value (logand value (1- (ash 1 sb!vm:word-bits)))))
2717       (#.sb!vm:unsigned-reg-sc-number
2718        (set-escaped-value value))
2719       (#.sb!vm:single-reg-sc-number
2720         #+nil ;; don't have escaped floats.
2721        (set-escaped-float-value single-float value))
2722       (#.sb!vm:double-reg-sc-number
2723         #+nil ;;  don't have escaped floats -- still in npx?
2724        (set-escaped-float-value double-float value))
2725       #!+long-float
2726       (#.sb!vm:long-reg-sc-number
2727         #+nil ;;  don't have escaped floats -- still in npx?
2728        (set-escaped-float-value long-float value))
2729       (#.sb!vm:single-stack-sc-number
2730        (setf (sap-ref-single
2731               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2732                        sb!vm:word-bytes)))
2733              (the single-float value)))
2734       (#.sb!vm:double-stack-sc-number
2735        (setf (sap-ref-double
2736               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2737                        sb!vm:word-bytes)))
2738              (the double-float value)))
2739       #!+long-float
2740       (#.sb!vm:long-stack-sc-number
2741        (setf (sap-ref-long
2742               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2743                        sb!vm:word-bytes)))
2744              (the long-float value)))
2745       (#.sb!vm:complex-single-stack-sc-number
2746        (setf (sap-ref-single
2747               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2748                        sb!vm:word-bytes)))
2749              (realpart (the (complex single-float) value)))
2750        (setf (sap-ref-single
2751               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2752                        sb!vm:word-bytes)))
2753              (imagpart (the (complex single-float) value))))
2754       (#.sb!vm:complex-double-stack-sc-number
2755        (setf (sap-ref-double
2756               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 2)
2757                        sb!vm:word-bytes)))
2758              (realpart (the (complex double-float) value)))
2759        (setf (sap-ref-double
2760               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 4)
2761                        sb!vm:word-bytes)))
2762              (imagpart (the (complex double-float) value))))
2763       #!+long-float
2764       (#.sb!vm:complex-long-stack-sc-number
2765        (setf (sap-ref-long
2766               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 3)
2767                        sb!vm:word-bytes)))
2768              (realpart (the (complex long-float) value)))
2769        (setf (sap-ref-long
2770               fp (- (* (+ (sb!c:sc-offset-offset sc-offset) 6)
2771                        sb!vm:word-bytes)))
2772              (imagpart (the (complex long-float) value))))
2773       (#.sb!vm:control-stack-sc-number
2774        (setf (stack-ref fp (sb!c:sc-offset-offset sc-offset)) value))
2775       (#.sb!vm:base-char-stack-sc-number
2776        (setf (sap-ref-32 fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2777                                          sb!vm:word-bytes)))
2778              (char-code (the character value))))
2779       (#.sb!vm:unsigned-stack-sc-number
2780        (setf (sap-ref-32 fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2781                                          sb!vm:word-bytes)))
2782              (the (unsigned-byte 32) value)))
2783       (#.sb!vm:signed-stack-sc-number
2784        (setf (signed-sap-ref-32
2785               fp (- (* (1+ (sb!c:sc-offset-offset sc-offset)) sb!vm:word-bytes)))
2786              (the (signed-byte 32) value)))
2787       (#.sb!vm:sap-stack-sc-number
2788        (setf (sap-ref-sap fp (- (* (1+ (sb!c:sc-offset-offset sc-offset))
2789                                           sb!vm:word-bytes)))
2790              (the system-area-pointer value))))))
2791
2792 ;;; The method for setting and accessing COMPILED-DEBUG-VAR values use
2793 ;;; this to determine if the value stored is the actual value or an
2794 ;;; indirection cell.
2795 (defun indirect-value-cell-p (x)
2796   (and (= (get-lowtag x) sb!vm:other-pointer-type)
2797        (= (get-type x) sb!vm:value-cell-header-type)))
2798
2799 ;;; Return three values reflecting the validity of DEBUG-VAR's value
2800 ;;; at BASIC-CODE-LOCATION:
2801 ;;;   :VALID    The value is known to be available.
2802 ;;;   :INVALID  The value is known to be unavailable.
2803 ;;;   :UNKNOWN  The value's availability is unknown.
2804 ;;;
2805 ;;; If the variable is always alive, then it is valid. If the
2806 ;;; code-location is unknown, then the variable's validity is
2807 ;;; :unknown. Once we've called CODE-LOCATION-UNKNOWN-P, we know the
2808 ;;; live-set information has been cached in the code-location.
2809 (defun debug-var-validity (debug-var basic-code-location)
2810   (etypecase debug-var
2811     (compiled-debug-var
2812      (compiled-debug-var-validity debug-var basic-code-location))
2813     ;; (There used to be more cases back before sbcl-0.7.0, when
2814     ;; we did special tricks to debug the IR1 interpreter.)
2815     ))
2816
2817 ;;; This is the method for DEBUG-VAR-VALIDITY for COMPILED-DEBUG-VARs.
2818 ;;; For safety, make sure basic-code-location is what we think.
2819 (defun compiled-debug-var-validity (debug-var basic-code-location)
2820   (declare (type compiled-code-location basic-code-location))
2821   (cond ((debug-var-alive-p debug-var)
2822          (let ((debug-fun (code-location-debug-function basic-code-location)))
2823            (if (>= (compiled-code-location-pc basic-code-location)
2824                    (sb!c::compiled-debug-function-start-pc
2825                     (compiled-debug-function-compiler-debug-fun debug-fun)))
2826                :valid
2827                :invalid)))
2828         ((code-location-unknown-p basic-code-location) :unknown)
2829         (t
2830          (let ((pos (position debug-var
2831                               (debug-function-debug-vars
2832                                (code-location-debug-function
2833                                 basic-code-location)))))
2834            (unless pos
2835              (error 'unknown-debug-var
2836                     :debug-var debug-var
2837                     :debug-function
2838                     (code-location-debug-function basic-code-location)))
2839            ;; There must be live-set info since basic-code-location is known.
2840            (if (zerop (sbit (compiled-code-location-live-set
2841                              basic-code-location)
2842                             pos))
2843                :invalid
2844                :valid)))))
2845 \f
2846 ;;;; sources
2847
2848 ;;; This code produces and uses what we call source-paths. A
2849 ;;; source-path is a list whose first element is a form number as
2850 ;;; returned by CODE-LOCATION-FORM-NUMBER and whose last element is a
2851 ;;; top-level-form number as returned by
2852 ;;; CODE-LOCATION-TOP-LEVEL-FORM-NUMBER. The elements from the last to
2853 ;;; the first, exclusively, are the numbered subforms into which to
2854 ;;; descend. For example:
2855 ;;;    (defun foo (x)
2856 ;;;      (let ((a (aref x 3)))
2857 ;;;     (cons a 3)))
2858 ;;; The call to AREF in this example is form number 5. Assuming this
2859 ;;; DEFUN is the 11'th top-level-form, the source-path for the AREF
2860 ;;; call is as follows:
2861 ;;;    (5 1 0 1 3 11)
2862 ;;; Given the DEFUN, 3 gets you the LET, 1 gets you the bindings, 0
2863 ;;; gets the first binding, and 1 gets the AREF form.
2864
2865 ;;; temporary buffer used to build form-number => source-path translation in
2866 ;;; FORM-NUMBER-TRANSLATIONS
2867 (defvar *form-number-temp* (make-array 10 :fill-pointer 0 :adjustable t))
2868
2869 ;;; table used to detect CAR circularities in FORM-NUMBER-TRANSLATIONS
2870 (defvar *form-number-circularity-table* (make-hash-table :test 'eq))
2871
2872 ;;; This returns a table mapping form numbers to source-paths. A source-path
2873 ;;; indicates a descent into the top-level-form form, going directly to the
2874 ;;; subform corressponding to the form number.
2875 ;;;
2876 ;;; The vector elements are in the same format as the compiler's
2877 ;;; NODE-SOURCE-PATH; that is, the first element is the form number and
2878 ;;; the last is the top-level-form number.
2879 (defun form-number-translations (form tlf-number)
2880   (clrhash *form-number-circularity-table*)
2881   (setf (fill-pointer *form-number-temp*) 0)
2882   (sub-translate-form-numbers form (list tlf-number))
2883   (coerce *form-number-temp* 'simple-vector))
2884 (defun sub-translate-form-numbers (form path)
2885   (unless (gethash form *form-number-circularity-table*)
2886     (setf (gethash form *form-number-circularity-table*) t)
2887     (vector-push-extend (cons (fill-pointer *form-number-temp*) path)
2888                         *form-number-temp*)
2889     (let ((pos 0)
2890           (subform form)
2891           (trail form))
2892       (declare (fixnum pos))
2893       (macrolet ((frob ()
2894                    '(progn
2895                       (when (atom subform) (return))
2896                       (let ((fm (car subform)))
2897                         (when (consp fm)
2898                           (sub-translate-form-numbers fm (cons pos path)))
2899                         (incf pos))
2900                       (setq subform (cdr subform))
2901                       (when (eq subform trail) (return)))))
2902         (loop
2903           (frob)
2904           (frob)
2905           (setq trail (cdr trail)))))))
2906
2907 ;;; FORM is a top-level form, and path is a source-path into it. This
2908 ;;; returns the form indicated by the source-path. Context is the
2909 ;;; number of enclosing forms to return instead of directly returning
2910 ;;; the source-path form. When context is non-zero, the form returned
2911 ;;; contains a marker, #:****HERE****, immediately before the form
2912 ;;; indicated by path.
2913 (defun source-path-context (form path context)
2914   (declare (type unsigned-byte context))
2915   ;; Get to the form indicated by path or the enclosing form indicated
2916   ;; by context and path.
2917   (let ((path (reverse (butlast (cdr path)))))
2918     (dotimes (i (- (length path) context))
2919       (let ((index (first path)))
2920         (unless (and (listp form) (< index (length form)))
2921           (error "Source path no longer exists."))
2922         (setq form (elt form index))
2923         (setq path (rest path))))
2924     ;; Recursively rebuild the source form resulting from the above
2925     ;; descent, copying the beginning of each subform up to the next
2926     ;; subform we descend into according to path. At the bottom of the
2927     ;; recursion, we return the form indicated by path preceded by our
2928     ;; marker, and this gets spliced into the resulting list structure
2929     ;; on the way back up.
2930     (labels ((frob (form path level)
2931                (if (or (zerop level) (null path))
2932                    (if (zerop context)
2933                        form
2934                        `(#:***here*** ,form))
2935                    (let ((n (first path)))
2936                      (unless (and (listp form) (< n (length form)))
2937                        (error "Source path no longer exists."))
2938                      (let ((res (frob (elt form n) (rest path) (1- level))))
2939                        (nconc (subseq form 0 n)
2940                               (cons res (nthcdr (1+ n) form))))))))
2941       (frob form path context))))
2942 \f
2943 ;;;; PREPROCESS-FOR-EVAL
2944
2945 ;;; Return a function of one argument that evaluates form in the
2946 ;;; lexical context of the BASIC-CODE-LOCATION LOC, or signal a
2947 ;;; NO-DEBUG-VARS condition when the LOC's DEBUG-FUNCTION has no
2948 ;;; DEBUG-VAR information available.
2949 ;;;
2950 ;;; The returned function takes the frame to get values from as its
2951 ;;; argument, and it returns the values of FORM. The returned function
2952 ;;; can signal the following conditions: INVALID-VALUE,
2953 ;;; AMBIGUOUS-VARIABLE-NAME, and FRAME-FUNCTION-MISMATCH.
2954 (defun preprocess-for-eval (form loc)
2955   (declare (type code-location loc))
2956   (let ((n-frame (gensym))
2957         (fun (code-location-debug-function loc)))
2958     (unless (debug-var-info-available fun)
2959       (debug-signal 'no-debug-vars :debug-function fun))
2960     (sb!int:collect ((binds)
2961                      (specs))
2962       (do-debug-function-variables (var fun)
2963         (let ((validity (debug-var-validity var loc)))
2964           (unless (eq validity :invalid)
2965             (let* ((sym (debug-var-symbol var))
2966                    (found (assoc sym (binds))))
2967               (if found
2968                   (setf (second found) :ambiguous)
2969                   (binds (list sym validity var)))))))
2970       (dolist (bind (binds))
2971         (let ((name (first bind))
2972               (var (third bind)))
2973           (ecase (second bind)
2974             (:valid
2975              (specs `(,name (debug-var-value ',var ,n-frame))))
2976             (:unknown
2977              (specs `(,name (debug-signal 'invalid-value :debug-var ',var
2978                                           :frame ,n-frame))))
2979             (:ambiguous
2980              (specs `(,name (debug-signal 'ambiguous-variable-name :name ',name
2981                                           :frame ,n-frame)))))))
2982       (let ((res (coerce `(lambda (,n-frame)
2983                             (declare (ignorable ,n-frame))
2984                             (symbol-macrolet ,(specs) ,form))
2985                          'function)))
2986         #'(lambda (frame)
2987             ;; This prevents these functions from being used in any
2988             ;; location other than a function return location, so
2989             ;; maybe this should only check whether frame's
2990             ;; debug-function is the same as loc's.
2991             (unless (code-location= (frame-code-location frame) loc)
2992               (debug-signal 'frame-function-mismatch
2993                             :code-location loc :form form :frame frame))
2994             (funcall res frame))))))
2995 \f
2996 ;;;; breakpoints
2997
2998 ;;;; user-visible interface
2999
3000 ;;; Create and return a breakpoint. When program execution encounters
3001 ;;; the breakpoint, the system calls HOOK-FUNCTION. HOOK-FUNCTION takes the
3002 ;;; current frame for the function in which the program is running and the
3003 ;;; breakpoint object.
3004 ;;;
3005 ;;; WHAT and KIND determine where in a function the system invokes
3006 ;;; HOOK-FUNCTION. WHAT is either a code-location or a debug-function.
3007 ;;; KIND is one of :CODE-LOCATION, :FUNCTION-START, or :FUNCTION-END.
3008 ;;; Since the starts and ends of functions may not have code-locations
3009 ;;; representing them, designate these places by supplying WHAT as a
3010 ;;; debug-function and KIND indicating the :FUNCTION-START or
3011 ;;; :FUNCTION-END. When WHAT is a debug-function and kind is
3012 ;;; :FUNCTION-END, then hook-function must take two additional
3013 ;;; arguments, a list of values returned by the function and a
3014 ;;; FUNCTION-END-COOKIE.
3015 ;;;
3016 ;;; INFO is information supplied by and used by the user.
3017 ;;;
3018 ;;; FUNCTION-END-COOKIE is a function. To implement :FUNCTION-END
3019 ;;; breakpoints, the system uses starter breakpoints to establish the
3020 ;;; :FUNCTION-END breakpoint for each invocation of the function. Upon
3021 ;;; each entry, the system creates a unique cookie to identify the
3022 ;;; invocation, and when the user supplies a function for this
3023 ;;; argument, the system invokes it on the frame and the cookie. The
3024 ;;; system later invokes the :FUNCTION-END breakpoint hook on the same
3025 ;;; cookie. The user may save the cookie for comparison in the hook
3026 ;;; function.
3027 ;;;
3028 ;;; Signal an error if WHAT is an unknown code-location.
3029 (defun make-breakpoint (hook-function what
3030                         &key (kind :code-location) info function-end-cookie)
3031   (etypecase what
3032     (code-location
3033      (when (code-location-unknown-p what)
3034        (error "cannot make a breakpoint at an unknown code location: ~S"
3035               what))
3036      (aver (eq kind :code-location))
3037      (let ((bpt (%make-breakpoint hook-function what kind info)))
3038        (etypecase what
3039          (compiled-code-location
3040           ;; This slot is filled in due to calling CODE-LOCATION-UNKNOWN-P.
3041           (when (eq (compiled-code-location-kind what) :unknown-return)
3042             (let ((other-bpt (%make-breakpoint hook-function what
3043                                                :unknown-return-partner
3044                                                info)))
3045               (setf (breakpoint-unknown-return-partner bpt) other-bpt)
3046               (setf (breakpoint-unknown-return-partner other-bpt) bpt))))
3047          ;; (There used to be more cases back before sbcl-0.7.0,,
3048          ;; when we did special tricks to debug the IR1
3049          ;; interpreter.)
3050          )
3051        bpt))
3052     (compiled-debug-function
3053      (ecase kind
3054        (:function-start
3055         (%make-breakpoint hook-function what kind info))
3056        (:function-end
3057         (unless (eq (sb!c::compiled-debug-function-returns
3058                      (compiled-debug-function-compiler-debug-fun what))
3059                     :standard)
3060           (error ":FUNCTION-END breakpoints are currently unsupported ~
3061                   for the known return convention."))
3062
3063         (let* ((bpt (%make-breakpoint hook-function what kind info))
3064                (starter (compiled-debug-function-end-starter what)))
3065           (unless starter
3066             (setf starter (%make-breakpoint #'list what :function-start nil))
3067             (setf (breakpoint-hook-function starter)
3068                   (function-end-starter-hook starter what))
3069             (setf (compiled-debug-function-end-starter what) starter))
3070           (setf (breakpoint-start-helper bpt) starter)
3071           (push bpt (breakpoint-%info starter))
3072           (setf (breakpoint-cookie-fun bpt) function-end-cookie)
3073           bpt))))))
3074
3075 ;;; These are unique objects created upon entry into a function by a
3076 ;;; :FUNCTION-END breakpoint's starter hook. These are only created
3077 ;;; when users supply :FUNCTION-END-COOKIE to MAKE-BREAKPOINT. Also,
3078 ;;; the :FUNCTION-END breakpoint's hook is called on the same cookie
3079 ;;; when it is created.
3080 (defstruct (function-end-cookie
3081             (:print-object (lambda (obj str)
3082                              (print-unreadable-object (obj str :type t))))
3083             (:constructor make-function-end-cookie (bogus-lra debug-fun))
3084             (:copier nil))
3085   ;; a pointer to the bogus-lra created for :FUNCTION-END breakpoints
3086   bogus-lra
3087   ;; the debug-function associated with the cookie
3088   debug-fun)
3089
3090 ;;; This maps bogus-lra-components to cookies, so that
3091 ;;; HANDLE-FUNCTION-END-BREAKPOINT can find the appropriate cookie for the
3092 ;;; breakpoint hook.
3093 (defvar *function-end-cookies* (make-hash-table :test 'eq))
3094
3095 ;;; This returns a hook function for the start helper breakpoint
3096 ;;; associated with a :FUNCTION-END breakpoint. The returned function
3097 ;;; makes a fake LRA that all returns go through, and this piece of
3098 ;;; fake code actually breaks. Upon return from the break, the code
3099 ;;; provides the returnee with any values. Since the returned function
3100 ;;; effectively activates FUN-END-BPT on each entry to DEBUG-FUN's
3101 ;;; function, we must establish breakpoint-data about FUN-END-BPT.
3102 (defun function-end-starter-hook (starter-bpt debug-fun)
3103   (declare (type breakpoint starter-bpt)
3104            (type compiled-debug-function debug-fun))
3105   #'(lambda (frame breakpoint)
3106       (declare (ignore breakpoint)
3107                (type frame frame))
3108       (let ((lra-sc-offset
3109              (sb!c::compiled-debug-function-return-pc
3110               (compiled-debug-function-compiler-debug-fun debug-fun))))
3111         (multiple-value-bind (lra component offset)
3112             (make-bogus-lra
3113              (get-context-value frame
3114                                 sb!vm::lra-save-offset
3115                                 lra-sc-offset))
3116           (setf (get-context-value frame
3117                                    sb!vm::lra-save-offset
3118                                    lra-sc-offset)
3119                 lra)
3120           (let ((end-bpts (breakpoint-%info starter-bpt)))
3121             (let ((data (breakpoint-data component offset)))
3122               (setf (breakpoint-data-breakpoints data) end-bpts)
3123               (dolist (bpt end-bpts)
3124                 (setf (breakpoint-internal-data bpt) data)))
3125             (let ((cookie (make-function-end-cookie lra debug-fun)))
3126               (setf (gethash component *function-end-cookies*) cookie)
3127               (dolist (bpt end-bpts)
3128                 (let ((fun (breakpoint-cookie-fun bpt)))
3129                   (when fun (funcall fun frame cookie))))))))))
3130
3131 ;;; This takes a FUNCTION-END-COOKIE and a frame, and it returns
3132 ;;; whether the cookie is still valid. A cookie becomes invalid when
3133 ;;; the frame that established the cookie has exited. Sometimes cookie
3134 ;;; holders are unaware of cookie invalidation because their
3135 ;;; :FUNCTION-END breakpoint hooks didn't run due to THROW'ing.
3136 ;;;
3137 ;;; This takes a frame as an efficiency hack since the user probably
3138 ;;; has a frame object in hand when using this routine, and it saves
3139 ;;; repeated parsing of the stack and consing when asking whether a
3140 ;;; series of cookies is valid.
3141 (defun function-end-cookie-valid-p (frame cookie)
3142   (let ((lra (function-end-cookie-bogus-lra cookie))
3143         (lra-sc-offset (sb!c::compiled-debug-function-return-pc
3144                         (compiled-debug-function-compiler-debug-fun
3145                          (function-end-cookie-debug-fun cookie)))))
3146     (do ((frame frame (frame-down frame)))
3147         ((not frame) nil)
3148       (when (and (compiled-frame-p frame)
3149                  (eq lra
3150                      (get-context-value frame
3151                                         sb!vm::lra-save-offset
3152                                         lra-sc-offset)))
3153         (return t)))))
3154 \f
3155 ;;;; ACTIVATE-BREAKPOINT
3156
3157 ;;; Cause the system to invoke the breakpoint's hook-function until
3158 ;;; the next call to DEACTIVATE-BREAKPOINT or DELETE-BREAKPOINT. The
3159 ;;; system invokes breakpoint hook functions in the opposite order
3160 ;;; that you activate them.
3161 (defun activate-breakpoint (breakpoint)
3162   (when (eq (breakpoint-status breakpoint) :deleted)
3163     (error "cannot activate a deleted breakpoint: ~S" breakpoint))
3164   (unless (eq (breakpoint-status breakpoint) :active)
3165     (ecase (breakpoint-kind breakpoint)
3166       (:code-location
3167        (let ((loc (breakpoint-what breakpoint)))
3168          (etypecase loc
3169            (compiled-code-location
3170             (activate-compiled-code-location-breakpoint breakpoint)
3171             (let ((other (breakpoint-unknown-return-partner breakpoint)))
3172               (when other
3173                 (activate-compiled-code-location-breakpoint other))))
3174            ;; (There used to be more cases back before sbcl-0.7.0, when
3175            ;; we did special tricks to debug the IR1 interpreter.)
3176            )))
3177       (:function-start
3178        (etypecase (breakpoint-what breakpoint)
3179          (compiled-debug-function
3180           (activate-compiled-function-start-breakpoint breakpoint))
3181          ;; (There used to be more cases back before sbcl-0.7.0, when
3182          ;; we did special tricks to debug the IR1 interpreter.)
3183          ))
3184       (:function-end
3185        (etypecase (breakpoint-what breakpoint)
3186          (compiled-debug-function
3187           (let ((starter (breakpoint-start-helper breakpoint)))
3188             (unless (eq (breakpoint-status starter) :active)
3189               ;; may already be active by some other :FUNCTION-END breakpoint
3190               (activate-compiled-function-start-breakpoint starter)))
3191           (setf (breakpoint-status breakpoint) :active))
3192          ;; (There used to be more cases back before sbcl-0.7.0, when
3193          ;; we did special tricks to debug the IR1 interpreter.)
3194          ))))
3195   breakpoint)
3196
3197 (defun activate-compiled-code-location-breakpoint (breakpoint)
3198   (declare (type breakpoint breakpoint))
3199   (let ((loc (breakpoint-what breakpoint)))
3200     (declare (type compiled-code-location loc))
3201     (sub-activate-breakpoint
3202      breakpoint
3203      (breakpoint-data (compiled-debug-function-component
3204                        (code-location-debug-function loc))
3205                       (+ (compiled-code-location-pc loc)
3206                          (if (or (eq (breakpoint-kind breakpoint)
3207                                      :unknown-return-partner)
3208                                  (eq (compiled-code-location-kind loc)
3209                                      :single-value-return))
3210                              sb!vm:single-value-return-byte-offset
3211                              0))))))
3212
3213 (defun activate-compiled-function-start-breakpoint (breakpoint)
3214   (declare (type breakpoint breakpoint))
3215   (let ((debug-fun (breakpoint-what breakpoint)))
3216     (sub-activate-breakpoint
3217      breakpoint
3218      (breakpoint-data (compiled-debug-function-component debug-fun)
3219                       (sb!c::compiled-debug-function-start-pc
3220                        (compiled-debug-function-compiler-debug-fun
3221                         debug-fun))))))
3222
3223 (defun sub-activate-breakpoint (breakpoint data)
3224   (declare (type breakpoint breakpoint)
3225            (type breakpoint-data data))
3226   (setf (breakpoint-status breakpoint) :active)
3227   (without-interrupts
3228    (unless (breakpoint-data-breakpoints data)
3229      (setf (breakpoint-data-instruction data)
3230            (without-gcing
3231             (breakpoint-install (get-lisp-obj-address
3232                                  (breakpoint-data-component data))
3233                                 (breakpoint-data-offset data)))))
3234    (setf (breakpoint-data-breakpoints data)
3235          (append (breakpoint-data-breakpoints data) (list breakpoint)))
3236    (setf (breakpoint-internal-data breakpoint) data)))
3237 \f
3238 ;;;; DEACTIVATE-BREAKPOINT
3239
3240 ;;; Stop the system from invoking the breakpoint's hook-function.
3241 (defun deactivate-breakpoint (breakpoint)
3242   (when (eq (breakpoint-status breakpoint) :active)
3243     (without-interrupts
3244      (let ((loc (breakpoint-what breakpoint)))
3245        (etypecase loc
3246          ((or compiled-code-location compiled-debug-function)
3247           (deactivate-compiled-breakpoint breakpoint)
3248           (let ((other (breakpoint-unknown-return-partner breakpoint)))
3249             (when other
3250               (deactivate-compiled-breakpoint other))))
3251          ;; (There used to be more cases back before sbcl-0.7.0, when
3252          ;; we did special tricks to debug the IR1 interpreter.)
3253          ))))
3254   breakpoint)
3255
3256 (defun deactivate-compiled-breakpoint (breakpoint)
3257   (if (eq (breakpoint-kind breakpoint) :function-end)
3258       (let ((starter (breakpoint-start-helper breakpoint)))
3259         (unless (find-if #'(lambda (bpt)
3260                              (and (not (eq bpt breakpoint))
3261                                   (eq (breakpoint-status bpt) :active)))
3262                          (breakpoint-%info starter))
3263           (deactivate-compiled-breakpoint starter)))
3264       (let* ((data (breakpoint-internal-data breakpoint))
3265              (bpts (delete breakpoint (breakpoint-data-breakpoints data))))
3266         (setf (breakpoint-internal-data breakpoint) nil)
3267         (setf (breakpoint-data-breakpoints data) bpts)
3268         (unless bpts
3269           (without-gcing
3270            (breakpoint-remove (get-lisp-obj-address
3271                                (breakpoint-data-component data))
3272                               (breakpoint-data-offset data)
3273                               (breakpoint-data-instruction data)))
3274           (delete-breakpoint-data data))))
3275   (setf (breakpoint-status breakpoint) :inactive)
3276   breakpoint)
3277 \f
3278 ;;;; BREAKPOINT-INFO
3279
3280 ;;; Return the user-maintained info associated with breakpoint. This
3281 ;;; is SETF'able.
3282 (defun breakpoint-info (breakpoint)
3283   (breakpoint-%info breakpoint))
3284 (defun %set-breakpoint-info (breakpoint value)
3285   (setf (breakpoint-%info breakpoint) value)
3286   (let ((other (breakpoint-unknown-return-partner breakpoint)))
3287     (when other
3288       (setf (breakpoint-%info other) value))))
3289 \f
3290 ;;;; BREAKPOINT-ACTIVE-P and DELETE-BREAKPOINT
3291
3292 (defun breakpoint-active-p (breakpoint)
3293   (ecase (breakpoint-status breakpoint)
3294     (:active t)
3295     ((:inactive :deleted) nil)))
3296
3297 ;;; Free system storage and remove computational overhead associated
3298 ;;; with breakpoint. After calling this, breakpoint is completely
3299 ;;; impotent and can never become active again.
3300 (defun delete-breakpoint (breakpoint)
3301   (let ((status (breakpoint-status breakpoint)))
3302     (unless (eq status :deleted)
3303       (when (eq status :active)
3304         (deactivate-breakpoint breakpoint))
3305       (setf (breakpoint-status breakpoint) :deleted)
3306       (let ((other (breakpoint-unknown-return-partner breakpoint)))
3307         (when other
3308           (setf (breakpoint-status other) :deleted)))
3309       (when (eq (breakpoint-kind breakpoint) :function-end)
3310         (let* ((starter (breakpoint-start-helper breakpoint))
3311                (breakpoints (delete breakpoint
3312                                     (the list (breakpoint-info starter)))))
3313           (setf (breakpoint-info starter) breakpoints)
3314           (unless breakpoints
3315             (delete-breakpoint starter)
3316             (setf (compiled-debug-function-end-starter
3317                    (breakpoint-what breakpoint))
3318                   nil))))))
3319   breakpoint)
3320 \f
3321 ;;;; C call out stubs
3322
3323 ;;; This actually installs the break instruction in the component. It
3324 ;;; returns the overwritten bits. You must call this in a context in
3325 ;;; which GC is disabled, so that Lisp doesn't move objects around
3326 ;;; that C is pointing to.
3327 (sb!alien:def-alien-routine "breakpoint_install" sb!c-call:unsigned-long
3328   (code-obj sb!c-call:unsigned-long)
3329   (pc-offset sb!c-call:int))
3330
3331 ;;; This removes the break instruction and replaces the original
3332 ;;; instruction. You must call this in a context in which GC is disabled
3333 ;;; so Lisp doesn't move objects around that C is pointing to.
3334 (sb!alien:def-alien-routine "breakpoint_remove" sb!c-call:void
3335   (code-obj sb!c-call:unsigned-long)
3336   (pc-offset sb!c-call:int)
3337   (old-inst sb!c-call:unsigned-long))
3338
3339 (sb!alien:def-alien-routine "breakpoint_do_displaced_inst" sb!c-call:void
3340   (scp (* os-context-t))
3341   (orig-inst sb!c-call:unsigned-long))
3342
3343 ;;;; breakpoint handlers (layer between C and exported interface)
3344
3345 ;;; This maps components to a mapping of offsets to breakpoint-datas.
3346 (defvar *component-breakpoint-offsets* (make-hash-table :test 'eq))
3347
3348 ;;; This returns the breakpoint-data associated with component cross
3349 ;;; offset. If none exists, this makes one, installs it, and returns it.
3350 (defun breakpoint-data (component offset &optional (create t))
3351   (flet ((install-breakpoint-data ()
3352            (when create
3353              (let ((data (make-breakpoint-data component offset)))
3354                (push (cons offset data)
3355                      (gethash component *component-breakpoint-offsets*))
3356                data))))
3357     (let ((offsets (gethash component *component-breakpoint-offsets*)))
3358       (if offsets
3359           (let ((data (assoc offset offsets)))
3360             (if data
3361                 (cdr data)
3362                 (install-breakpoint-data)))
3363           (install-breakpoint-data)))))
3364
3365 ;;; We use this when there are no longer any active breakpoints
3366 ;;; corresponding to data.
3367 (defun delete-breakpoint-data (data)
3368   (let* ((component (breakpoint-data-component data))
3369          (offsets (delete (breakpoint-data-offset data)
3370                           (gethash component *component-breakpoint-offsets*)
3371                           :key #'car)))
3372     (if offsets
3373         (setf (gethash component *component-breakpoint-offsets*) offsets)
3374         (remhash component *component-breakpoint-offsets*)))
3375   (values))
3376
3377 ;;; The C handler for interrupts calls this when it has a
3378 ;;; debugging-tool break instruction. This does NOT handle all breaks;
3379 ;;; for example, it does not handle breaks for internal errors.
3380 (defun handle-breakpoint (offset component signal-context)
3381   (/show0 "entering HANDLE-BREAKPOINT")
3382   (let ((data (breakpoint-data component offset nil)))
3383     (unless data
3384       (error "unknown breakpoint in ~S at offset ~S"
3385               (debug-function-name (debug-function-from-pc component offset))
3386               offset))
3387     (let ((breakpoints (breakpoint-data-breakpoints data)))
3388       (if (or (null breakpoints)
3389               (eq (breakpoint-kind (car breakpoints)) :function-end))
3390           (handle-function-end-breakpoint-aux breakpoints data signal-context)
3391           (handle-breakpoint-aux breakpoints data
3392                                  offset component signal-context)))))
3393
3394 ;;; This holds breakpoint-datas while invoking the breakpoint hooks
3395 ;;; associated with that particular component and location. While they
3396 ;;; are executing, if we hit the location again, we ignore the
3397 ;;; breakpoint to avoid infinite recursion. Function-end breakpoints
3398 ;;; must work differently since the breakpoint-data is unique for each
3399 ;;; invocation.
3400 (defvar *executing-breakpoint-hooks* nil)
3401
3402 ;;; This handles code-location and debug-function :FUNCTION-START
3403 ;;; breakpoints.
3404 (defun handle-breakpoint-aux (breakpoints data offset component signal-context)
3405   (/show0 "entering HANDLE-BREAKPOINT-AUX")
3406   (unless breakpoints
3407     (error "internal error: breakpoint that nobody wants"))
3408   (unless (member data *executing-breakpoint-hooks*)
3409     (let ((*executing-breakpoint-hooks* (cons data
3410                                               *executing-breakpoint-hooks*)))
3411       (invoke-breakpoint-hooks breakpoints component offset)))
3412   ;; At this point breakpoints may not hold the same list as
3413   ;; BREAKPOINT-DATA-BREAKPOINTS since invoking hooks may have allowed
3414   ;; a breakpoint deactivation. In fact, if all breakpoints were
3415   ;; deactivated then data is invalid since it was deleted and so the
3416   ;; correct one must be looked up if it is to be used. If there are
3417   ;; no more breakpoints active at this location, then the normal
3418   ;; instruction has been put back, and we do not need to
3419   ;; DO-DISPLACED-INST.
3420   (let ((data (breakpoint-data component offset nil)))
3421     (when (and data (breakpoint-data-breakpoints data))
3422       ;; The breakpoint is still active, so we need to execute the
3423       ;; displaced instruction and leave the breakpoint instruction
3424       ;; behind. The best way to do this is different on each machine,
3425       ;; so we just leave it up to the C code.
3426       (breakpoint-do-displaced-inst signal-context
3427                                     (breakpoint-data-instruction data))
3428       ;; Some platforms have no usable sigreturn() call.  If your
3429       ;; implementation of arch_do_displaced_inst() doesn't sigreturn(),
3430       ;; add it to this list.
3431       #!-(or hpux irix x86 alpha)
3432       (error "BREAKPOINT-DO-DISPLACED-INST returned?"))))
3433
3434 (defun invoke-breakpoint-hooks (breakpoints component offset)
3435   (let* ((debug-fun (debug-function-from-pc component offset))
3436          (frame (do ((f (top-frame) (frame-down f)))
3437                     ((eq debug-fun (frame-debug-function f)) f))))
3438     (dolist (bpt breakpoints)
3439       (funcall (breakpoint-hook-function bpt)
3440                frame
3441                ;; If this is an :UNKNOWN-RETURN-PARTNER, then pass the
3442                ;; hook function the original breakpoint, so that users
3443                ;; aren't forced to confront the fact that some
3444                ;; breakpoints really are two.
3445                (if (eq (breakpoint-kind bpt) :unknown-return-partner)
3446                    (breakpoint-unknown-return-partner bpt)
3447                    bpt)))))
3448
3449 (defun handle-function-end-breakpoint (offset component context)
3450   (/show0 "entering HANDLE-FUNCTION-END-BREAKPOINT")
3451   (let ((data (breakpoint-data component offset nil)))
3452     (unless data
3453       (error "unknown breakpoint in ~S at offset ~S"
3454               (debug-function-name (debug-function-from-pc component offset))
3455               offset))
3456     (let ((breakpoints (breakpoint-data-breakpoints data)))
3457       (when breakpoints
3458         (aver (eq (breakpoint-kind (car breakpoints)) :function-end))
3459         (handle-function-end-breakpoint-aux breakpoints data context)))))
3460
3461 ;;; Either HANDLE-BREAKPOINT calls this for :FUNCTION-END breakpoints
3462 ;;; [old C code] or HANDLE-FUNCTION-END-BREAKPOINT calls this directly
3463 ;;; [new C code].
3464 (defun handle-function-end-breakpoint-aux (breakpoints data signal-context)
3465   (/show0 "entering HANDLE-FUNCTION-END-BREAKPOINT-AUX")
3466   (delete-breakpoint-data data)
3467   (let* ((scp
3468           (locally
3469             (declare (optimize (inhibit-warnings 3)))
3470             (sb!alien:sap-alien signal-context (* os-context-t))))
3471          (frame (do ((cfp (sb!vm:context-register scp sb!vm::cfp-offset))
3472                      (f (top-frame) (frame-down f)))
3473                     ((= cfp (sap-int (frame-pointer f))) f)
3474                   (declare (type (unsigned-byte #.sb!vm:word-bits) cfp))))
3475          (component (breakpoint-data-component data))
3476          (cookie (gethash component *function-end-cookies*)))
3477     (remhash component *function-end-cookies*)
3478     (dolist (bpt breakpoints)
3479       (funcall (breakpoint-hook-function bpt)
3480                frame bpt
3481                (get-function-end-breakpoint-values scp)
3482                cookie))))
3483
3484 (defun get-function-end-breakpoint-values (scp)
3485   (let ((ocfp (int-sap (sb!vm:context-register
3486                         scp
3487                         #!-x86 sb!vm::ocfp-offset
3488                         #!+x86 sb!vm::ebx-offset)))
3489         (nargs (make-lisp-obj
3490                 (sb!vm:context-register scp sb!vm::nargs-offset)))
3491         (reg-arg-offsets '#.sb!vm::*register-arg-offsets*)
3492         (results nil))
3493     (without-gcing
3494      (dotimes (arg-num nargs)
3495        (push (if reg-arg-offsets
3496                  (make-lisp-obj
3497                   (sb!vm:context-register scp (pop reg-arg-offsets)))
3498                (stack-ref ocfp arg-num))
3499              results)))
3500     (nreverse results)))
3501 \f
3502 ;;;; MAKE-BOGUS-LRA (used for :FUNCTION-END breakpoints)
3503
3504 (defconstant bogus-lra-constants
3505   #!-x86 2 #!+x86 3)
3506 (defconstant known-return-p-slot
3507   (+ sb!vm:code-constants-offset #!-x86 1 #!+x86 2))
3508
3509 ;;; Make a bogus LRA object that signals a breakpoint trap when
3510 ;;; returned to. If the breakpoint trap handler returns, REAL-LRA is
3511 ;;; returned to. Three values are returned: the bogus LRA object, the
3512 ;;; code component it is part of, and the PC offset for the trap
3513 ;;; instruction.
3514 (defun make-bogus-lra (real-lra &optional known-return-p)
3515   (without-gcing
3516    (let* ((src-start (foreign-symbol-address "function_end_breakpoint_guts"))
3517           (src-end (foreign-symbol-address "function_end_breakpoint_end"))
3518           (trap-loc (foreign-symbol-address "function_end_breakpoint_trap"))
3519           (length (sap- src-end src-start))
3520           (code-object
3521            (%primitive
3522             #!-(and x86 gencgc) sb!c:allocate-code-object
3523             #!+(and x86 gencgc) sb!c::allocate-dynamic-code-object
3524             (1+ bogus-lra-constants)
3525             length))
3526           (dst-start (code-instructions code-object)))
3527      (declare (type system-area-pointer
3528                     src-start src-end dst-start trap-loc)
3529               (type index length))
3530      (setf (%code-debug-info code-object) :bogus-lra)
3531      (setf (code-header-ref code-object sb!vm:code-trace-table-offset-slot)
3532            length)
3533      #!-x86
3534      (setf (code-header-ref code-object real-lra-slot) real-lra)
3535      #!+x86
3536      (multiple-value-bind (offset code) (compute-lra-data-from-pc real-lra)
3537        (setf (code-header-ref code-object real-lra-slot) code)
3538        (setf (code-header-ref code-object (1+ real-lra-slot)) offset))
3539      (setf (code-header-ref code-object known-return-p-slot)
3540            known-return-p)
3541      (system-area-copy src-start 0 dst-start 0 (* length sb!vm:byte-bits))
3542      (sb!vm:sanctify-for-execution code-object)
3543      #!+x86
3544      (values dst-start code-object (sap- trap-loc src-start))
3545      #!-x86
3546      (let ((new-lra (make-lisp-obj (+ (sap-int dst-start)
3547                                       sb!vm:other-pointer-type))))
3548        (set-header-data
3549         new-lra
3550         (logandc2 (+ sb!vm:code-constants-offset bogus-lra-constants 1)
3551                   1))
3552        (sb!vm:sanctify-for-execution code-object)
3553        (values new-lra code-object (sap- trap-loc src-start))))))
3554 \f
3555 ;;;; miscellaneous
3556
3557 ;;; This appears here because it cannot go with the DEBUG-FUNCTION
3558 ;;; interface since DO-DEBUG-BLOCK-LOCATIONS isn't defined until after
3559 ;;; the DEBUG-FUNCTION routines.
3560
3561 ;;; Return a code-location before the body of a function and after all
3562 ;;; the arguments are in place; or if that location can't be
3563 ;;; determined due to a lack of debug information, return NIL.
3564 (defun debug-function-start-location (debug-fun)
3565   (etypecase debug-fun
3566     (compiled-debug-function
3567      (code-location-from-pc debug-fun
3568                             (sb!c::compiled-debug-function-start-pc
3569                              (compiled-debug-function-compiler-debug-fun
3570                               debug-fun))
3571                             nil))
3572     ;; (There used to be more cases back before sbcl-0.7.0, when
3573     ;; we did special tricks to debug the IR1 interpreter.)
3574     ))
3575
3576 (defun print-code-locations (function)
3577   (let ((debug-fun (function-debug-function function)))
3578     (do-debug-function-blocks (block debug-fun)
3579       (do-debug-block-locations (loc block)
3580         (fill-in-code-location loc)
3581         (format t "~S code location at ~D"
3582                 (compiled-code-location-kind loc)
3583                 (compiled-code-location-pc loc))
3584         (sb!debug::print-code-location-source-form loc 0)
3585         (terpri)))))