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