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