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