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