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