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