0.pre7.59:
[sbcl.git] / src / compiler / target-disassem.lisp
1 ;;;; disassembler-related stuff not needed in cross-compilation host
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!DISASSEM")
13
14 ;;;; FIXME: A lot of stupid package prefixes would go away if DISASSEM
15 ;;;; would use the SB!DI package. And some more would go away if it would
16 ;;;; use SB!SYS (in order to get to the SAP-FOO operators).
17 \f
18 ;;;; combining instructions where one specializes another
19
20 ;;; Return non-NIL if the instruction SPECIAL is a more specific
21 ;;; version of GENERAL (i.e., the same instruction, but with more
22 ;;; constraints).
23 (defun inst-specializes-p (special general)
24   (declare (type instruction special general))
25   (let ((smask (inst-mask special))
26         (gmask (inst-mask general)))
27     (and (dchunk= (inst-id general)
28                   (dchunk-and (inst-id special) gmask))
29          (dchunk-strict-superset-p smask gmask))))
30
31 ;;; a bit arbitrary, but should work ok...
32 ;;;
33 ;;; Return an integer corresponding to the specificity of the
34 ;;; instruction INST.
35 (defun specializer-rank (inst)
36   (declare (type instruction inst))
37   (* (dchunk-count-bits (inst-mask inst)) 4))
38
39 ;;; Order the list of instructions INSTS with more specific (more
40 ;;; constant bits, or same-as argument constains) ones first. Returns
41 ;;; the ordered list.
42 (defun order-specializers (insts)
43   (declare (type list insts))
44   (sort insts #'> :key #'specializer-rank))
45
46 (defun specialization-error (insts)
47   (error "~@<internal disassembler error: ~2I~_Instructions either aren't related or conflict in some way: ~4I~_~S~:>"
48          insts))
49
50 ;;; Given a list of instructions INSTS, Sees if one of these instructions is a
51 ;;; more general form of all the others, in which case they are put into its
52 ;;; specializers list, and it is returned. Otherwise an error is signaled.
53 (defun try-specializing (insts)
54   (declare (type list insts))
55   (let ((masters (copy-list insts)))
56     (dolist (possible-master insts)
57       (dolist (possible-specializer insts)
58         (unless (or (eq possible-specializer possible-master)
59                     (inst-specializes-p possible-specializer possible-master))
60           (setf masters (delete possible-master masters))
61           (return)                      ; exit the inner loop
62           )))
63     (cond ((null masters)
64            (specialization-error insts))
65           ((cdr masters)
66            (error "multiple specializing masters: ~S" masters))
67           (t
68            (let ((master (car masters)))
69              (setf (inst-specializers master)
70                    (order-specializers (remove master insts)))
71              master)))))
72 \f
73 ;;;; choosing an instruction
74
75 #!-sb-fluid (declaim (inline inst-matches-p choose-inst-specialization))
76
77 ;;; Return non-NIL if all constant-bits in INST match CHUNK.
78 (defun inst-matches-p (inst chunk)
79   (declare (type instruction inst)
80            (type dchunk chunk))
81   (dchunk= (dchunk-and (inst-mask inst) chunk) (inst-id inst)))
82
83 ;;; Given an instruction object, INST, and a bit-pattern, CHUNK, pick
84 ;;; the most specific instruction on INST's specializer list whose
85 ;;; constraints are met by CHUNK. If none do, then return INST.
86 (defun choose-inst-specialization (inst chunk)
87   (declare (type instruction inst)
88            (type dchunk chunk))
89   (or (dolist (spec (inst-specializers inst) nil)
90         (declare (type instruction spec))
91         (when (inst-matches-p spec chunk)
92           (return spec)))
93       inst))
94 \f
95 ;;;; searching for an instruction in instruction space
96
97 ;;; Return the instruction object within INST-SPACE corresponding to the
98 ;;; bit-pattern CHUNK, or NIL if there isn't one.
99 (defun find-inst (chunk inst-space)
100   (declare (type dchunk chunk)
101            (type (or null inst-space instruction) inst-space))
102   (etypecase inst-space
103     (null nil)
104     (instruction
105      (if (inst-matches-p inst-space chunk)
106          (choose-inst-specialization inst-space chunk)
107          nil))
108     (inst-space
109      (let* ((mask (ispace-valid-mask inst-space))
110             (id (dchunk-and mask chunk)))
111        (declare (type dchunk id mask))
112        (dolist (choice (ispace-choices inst-space))
113          (declare (type inst-space-choice choice))
114          (when (dchunk= id (ischoice-common-id choice))
115            (return (find-inst chunk (ischoice-subspace choice)))))))))
116 \f
117 ;;;; building the instruction space
118
119 ;;; Returns an instruction-space object corresponding to the list of
120 ;;; instructions INSTS. If the optional parameter INITIAL-MASK is
121 ;;; supplied, only bits it has set are used.
122 (defun build-inst-space (insts &optional (initial-mask dchunk-one))
123   ;; This is done by finding any set of bits that's common to
124   ;; all instructions, building an instruction-space node that selects on those
125   ;; bits, and recursively handle sets of instructions with a common value for
126   ;; these bits (which, since there should be fewer instructions than in INSTS,
127   ;; should have some additional set of bits to select on, etc). If there
128   ;; are no common bits, or all instructions have the same value within those
129   ;; bits, TRY-SPECIALIZING is called, which handles the cases of many
130   ;; variations on a single instruction.
131   (declare (type list insts)
132            (type dchunk initial-mask))
133   (cond ((null insts)
134          nil)
135         ((null (cdr insts))
136          (car insts))
137         (t
138          (let ((vmask (dchunk-copy initial-mask)))
139            (dolist (inst insts)
140              (dchunk-andf vmask (inst-mask inst)))
141            (if (dchunk-zerop vmask)
142                (try-specializing insts)
143                (let ((buckets nil))
144                  (dolist (inst insts)
145                    (let* ((common-id (dchunk-and (inst-id inst) vmask))
146                           (bucket (assoc common-id buckets :test #'dchunk=)))
147                      (cond ((null bucket)
148                             (push (list common-id inst) buckets))
149                            (t
150                             (push inst (cdr bucket))))))
151                  (let ((submask (dchunk-clear initial-mask vmask)))
152                    (if (= (length buckets) 1)
153                        (try-specializing insts)
154                        (make-inst-space
155                         :valid-mask vmask
156                         :choices (mapcar (lambda (bucket)
157                                            (make-inst-space-choice
158                                             :subspace (build-inst-space
159                                                        (cdr bucket)
160                                                        submask)
161                                             :common-id (car bucket)))
162                                          buckets))))))))))
163 \f
164 ;;;; an inst-space printer for debugging purposes
165
166 (defun print-masked-binary (num mask word-size &optional (show word-size))
167   (do ((bit (1- word-size) (1- bit)))
168       ((< bit 0))
169     (write-char (cond ((logbitp bit mask)
170                        (if (logbitp bit num) #\1 #\0))
171                       ((< bit show) #\x)
172                       (t #\space)))))
173
174 (defun print-inst-bits (inst)
175   (print-masked-binary (inst-id inst)
176                        (inst-mask inst)
177                        dchunk-bits
178                        (bytes-to-bits (inst-length inst))))
179
180 ;;; Print a nicely-formatted version of INST-SPACE.
181 (defun print-inst-space (inst-space &optional (indent 0))
182   (etypecase inst-space
183     (null)
184     (instruction
185      (format t "~Vt[~A(~A)~40T" indent
186              (inst-name inst-space)
187              (inst-format-name inst-space))
188      (print-inst-bits inst-space)
189      (dolist (inst (inst-specializers inst-space))
190        (format t "~%~Vt:~A~40T" indent (inst-name inst))
191        (print-inst-bits inst))
192      (write-char #\])
193      (terpri))
194     (inst-space
195      (format t "~Vt---- ~8,'0X ----~%"
196              indent
197              (ispace-valid-mask inst-space))
198      (map nil
199           (lambda (choice)
200             (format t "~Vt~8,'0X ==>~%"
201                     (+ 2 indent)
202                     (ischoice-common-id choice))
203             (print-inst-space (ischoice-subspace choice)
204                               (+ 4 indent)))
205           (ispace-choices inst-space)))))
206 \f
207 ;;;; (The actual disassembly part follows.)
208 \f
209 ;;; Code object layout:
210 ;;;     header-word
211 ;;;     code-size (starting from first inst, in words)
212 ;;;     entry-points (points to first function header)
213 ;;;     debug-info
214 ;;;     trace-table-offset (starting from first inst, in bytes)
215 ;;;     constant1
216 ;;;     constant2
217 ;;;     ...
218 ;;;     <padding to dual-word boundary>
219 ;;;     start of instructions
220 ;;;     ...
221 ;;;     function-headers and lra's buried in here randomly
222 ;;;     ...
223 ;;;     start of trace-table
224 ;;;     <padding to dual-word boundary>
225 ;;;
226 ;;; Function header layout (dual word aligned):
227 ;;;     header-word
228 ;;;     self pointer
229 ;;;     next pointer (next function header)
230 ;;;     name
231 ;;;     arglist
232 ;;;     type
233 ;;;
234 ;;; LRA layout (dual word aligned):
235 ;;;     header-word
236
237 #!-sb-fluid (declaim (inline words-to-bytes bytes-to-words))
238
239 (eval-when (:compile-toplevel :load-toplevel :execute)
240   ;;; Convert a word-offset NUM to a byte-offset.
241   (defun words-to-bytes (num)
242     (declare (type offset num))
243     (ash num sb!vm:word-shift))
244   ) ; EVAL-WHEN
245
246 ;;; Convert a byte-offset NUM to a word-offset.
247 (defun bytes-to-words (num)
248   (declare (type offset num))
249   (ash num (- sb!vm:word-shift)))
250
251 (defconstant lra-size (words-to-bytes 1))
252 \f
253 (defstruct (offs-hook (:copier nil))
254   (offset 0 :type offset)
255   (function (required-argument) :type function)
256   (before-address nil :type (member t nil)))
257
258 (defstruct (segment (:conc-name seg-)
259                     (:constructor %make-segment)
260                     (:copier nil))
261   (sap-maker (required-argument)
262              :type (function () sb!sys:system-area-pointer))
263   (length 0 :type length)
264   (virtual-location 0 :type address)
265   (storage-info nil :type (or null storage-info))
266   (code nil :type (or null sb!kernel:code-component))
267   (hooks nil :type list))
268 (def!method print-object ((seg segment) stream)
269   (print-unreadable-object (seg stream :type t)
270     (let ((addr (sb!sys:sap-int (funcall (seg-sap-maker seg)))))
271       (format stream "#X~X[~D]~:[ (#X~X)~;~*~]~@[ in ~S~]"
272               addr
273               (seg-length seg)
274               (= (seg-virtual-location seg) addr)
275               (seg-virtual-location seg)
276               (seg-code seg)))))
277 \f
278 ;;; All state during disassembly. We store some seemingly redundant
279 ;;; information so that we can allow garbage collect during disassembly and
280 ;;; not get tripped up by a code block being moved...
281 (defstruct (disassem-state (:conc-name dstate-)
282                            (:constructor %make-dstate)
283                            (:copier nil))
284   (cur-offs 0 :type offset)             ; offset of current pos in segment
285   (next-offs 0 :type offset)            ; offset of next position
286
287   (segment-sap (required-argument) :type sb!sys:system-area-pointer)
288                                         ; a sap pointing to our segment
289   (segment nil :type (or null segment)) ; the current segment
290
291   (alignment sb!vm:word-bytes :type alignment) ; what to align to in most cases
292   (byte-order :little-endian
293               :type (member :big-endian :little-endian))
294
295   (properties nil :type list)           ; for user code to hang stuff off of
296   (filtered-values (make-array max-filtered-value-index)
297                    :type filtered-value-vector)
298
299   (addr-print-len nil :type             ; used for prettifying printing
300                   (or null (integer 0 20)))
301   (argument-column 0 :type column)
302   (output-state :beginning              ; to make output look nicer
303                 :type (member :beginning
304                               :block-boundary
305                               nil))
306
307   (labels nil :type list)               ; alist of (address . label-number)
308   (label-hash (make-hash-table)         ; same thing in a different form
309               :type hash-table)
310
311   (fun-hooks nil :type list)            ; list of function
312
313   ;; these next two are popped as they are used
314   (cur-labels nil :type list)           ; alist of (address . label-number)
315   (cur-offs-hooks nil :type list)       ; list of offs-hook
316
317   (notes nil :type list)                ; for the current location
318
319   (current-valid-locations nil          ; currently active source variables
320                            :type (or null (vector bit))))
321 (def!method print-object ((dstate disassem-state) stream)
322   (print-unreadable-object (dstate stream :type t)
323     (format stream
324             "+~D~@[ in ~S~]"
325             (dstate-cur-offs dstate)
326             (dstate-segment dstate))))
327
328 ;;; Return the absolute address of the current instruction in DSTATE.
329 (defun dstate-cur-addr (dstate)
330   (the address (+ (seg-virtual-location (dstate-segment dstate))
331                   (dstate-cur-offs dstate))))
332
333 ;;; Return the absolute address of the next instruction in DSTATE.
334 (defun dstate-next-addr (dstate)
335   (the address (+ (seg-virtual-location (dstate-segment dstate))
336                   (dstate-next-offs dstate))))
337 \f
338 ;;;; function ops
339
340 (defun fun-self (fun)
341   (declare (type compiled-function fun))
342   (sb!kernel:%simple-fun-self fun))
343
344 (defun fun-code (fun)
345   (declare (type compiled-function fun))
346   (sb!kernel:fun-code-header (fun-self fun)))
347
348 (defun fun-next (fun)
349   (declare (type compiled-function fun))
350   (sb!kernel:%simple-fun-next fun))
351
352 (defun fun-address (function)
353   (declare (type compiled-function function))
354   (- (sb!kernel:get-lisp-obj-address function) sb!vm:fun-pointer-lowtag))
355
356 ;;; the offset of FUNCTION from the start of its code-component's
357 ;;; instruction area
358 (defun fun-insts-offset (function)
359   (declare (type compiled-function function))
360   (- (fun-address function)
361      (sb!sys:sap-int (sb!kernel:code-instructions (fun-code function)))))
362
363 ;;; the offset of FUNCTION from the start of its code-component
364 (defun fun-offset (function)
365   (declare (type compiled-function function))
366   (words-to-bytes (sb!kernel:get-closure-length function)))
367 \f
368 ;;;; operations on code-components (which hold the instructions for
369 ;;;; one or more functions)
370
371 ;;; Return the length of the instruction area in CODE-COMPONENT.
372 (defun code-inst-area-length (code-component)
373   (declare (type sb!kernel:code-component code-component))
374   (sb!kernel:code-header-ref code-component
375                              sb!vm:code-trace-table-offset-slot))
376
377 ;;; Return the address of the instruction area in CODE-COMPONENT.
378 (defun code-inst-area-address (code-component)
379   (declare (type sb!kernel:code-component code-component))
380   (sb!sys:sap-int (sb!kernel:code-instructions code-component)))
381
382 ;;; Return the first function in CODE-COMPONENT.
383 (defun code-first-function (code-component)
384   (declare (type sb!kernel:code-component code-component))
385   (sb!kernel:code-header-ref code-component
386                              sb!vm:code-trace-table-offset-slot))
387
388 (defun segment-offs-to-code-offs (offset segment)
389   (sb!sys:without-gcing
390    (let* ((seg-base-addr (sb!sys:sap-int (funcall (seg-sap-maker segment))))
391           (code-addr
392            (logandc1 sb!vm:lowtag-mask
393                      (sb!kernel:get-lisp-obj-address (seg-code segment))))
394           (addr (+ offset seg-base-addr)))
395      (declare (type address seg-base-addr code-addr addr))
396      (- addr code-addr))))
397
398 (defun code-offs-to-segment-offs (offset segment)
399   (sb!sys:without-gcing
400    (let* ((seg-base-addr (sb!sys:sap-int (funcall (seg-sap-maker segment))))
401           (code-addr
402            (logandc1 sb!vm:lowtag-mask
403                      (sb!kernel:get-lisp-obj-address (seg-code segment))))
404           (addr (+ offset code-addr)))
405      (declare (type address seg-base-addr code-addr addr))
406      (- addr seg-base-addr))))
407
408 (defun code-insts-offs-to-segment-offs (offset segment)
409   (sb!sys:without-gcing
410    (let* ((seg-base-addr (sb!sys:sap-int (funcall (seg-sap-maker segment))))
411           (code-insts-addr
412            (sb!sys:sap-int (sb!kernel:code-instructions (seg-code segment))))
413           (addr (+ offset code-insts-addr)))
414      (declare (type address seg-base-addr code-insts-addr addr))
415      (- addr seg-base-addr))))
416 \f
417 (defun lra-hook (chunk stream dstate)
418   (declare (type dchunk chunk)
419            (ignore chunk)
420            (type (or null stream) stream)
421            (type disassem-state dstate))
422   (when (and (aligned-p (+ (seg-virtual-location (dstate-segment dstate))
423                            (dstate-cur-offs dstate))
424                         (* 2 sb!vm:word-bytes))
425              ;; Check type.
426              (= (sb!sys:sap-ref-8 (dstate-segment-sap dstate)
427                                   (if (eq (dstate-byte-order dstate)
428                                           :little-endian)
429                                       (dstate-cur-offs dstate)
430                                       (+ (dstate-cur-offs dstate)
431                                          (1- lra-size))))
432                 sb!vm:return-pc-header-widetag))
433     (unless (null stream)
434       (princ '.lra stream))
435     (incf (dstate-next-offs dstate) lra-size))
436   nil)
437
438 ;;; Print the function-header (entry-point) pseudo-instruction at the
439 ;;; current location in DSTATE to STREAM.
440 (defun fun-header-hook (stream dstate)
441   (declare (type (or null stream) stream)
442            (type disassem-state dstate))
443   (unless (null stream)
444     (let* ((seg (dstate-segment dstate))
445            (code (seg-code seg))
446            (woffs
447             (bytes-to-words
448              (segment-offs-to-code-offs (dstate-cur-offs dstate) seg)))
449            (name
450             (sb!kernel:code-header-ref code
451                                        (+ woffs
452                                           sb!vm:simple-fun-name-slot)))
453            (args
454             (sb!kernel:code-header-ref code
455                                        (+ woffs
456                                           sb!vm:simple-fun-arglist-slot)))
457            (type
458             (sb!kernel:code-header-ref code
459                                        (+ woffs
460                                           sb!vm:simple-fun-type-slot))))
461       (format stream ".~A ~S~:A" 'entry name args)
462       (note (lambda (stream)
463               (format stream "~:S" type)) ; use format to print NIL as ()
464             dstate)))
465   (incf (dstate-next-offs dstate)
466         (words-to-bytes sb!vm:simple-fun-code-offset)))
467 \f
468 (defun alignment-hook (chunk stream dstate)
469   (declare (type dchunk chunk)
470            (ignore chunk)
471            (type (or null stream) stream)
472            (type disassem-state dstate))
473   (let ((location
474          (+ (seg-virtual-location (dstate-segment dstate))
475             (dstate-cur-offs dstate)))
476         (alignment (dstate-alignment dstate)))
477     (unless (aligned-p location alignment)
478       (when stream
479         (format stream "~A~Vt~D~%" '.align
480                 (dstate-argument-column dstate)
481                 alignment))
482       (incf(dstate-next-offs dstate)
483            (- (align location alignment) location)))
484     nil))
485
486 (defun rewind-current-segment (dstate segment)
487   (declare (type disassem-state dstate)
488            (type segment segment))
489   (setf (dstate-segment dstate) segment)
490   (setf (dstate-cur-offs-hooks dstate)
491         (stable-sort (nreverse (copy-list (seg-hooks segment)))
492                      (lambda (oh1 oh2)
493                        (or (< (offs-hook-offset oh1) (offs-hook-offset oh2))
494                            (and (= (offs-hook-offset oh1)
495                                    (offs-hook-offset oh2))
496                                 (offs-hook-before-address oh1)
497                                 (not (offs-hook-before-address oh2)))))))
498   (setf (dstate-cur-offs dstate) 0)
499   (setf (dstate-cur-labels dstate) (dstate-labels dstate)))
500
501 (defun do-offs-hooks (before-address stream dstate)
502   (declare (type (or null stream) stream)
503            (type disassem-state dstate))
504   (let ((cur-offs (dstate-cur-offs dstate)))
505     (setf (dstate-next-offs dstate) cur-offs)
506     (loop
507       (let ((next-hook (car (dstate-cur-offs-hooks dstate))))
508         (when (null next-hook)
509           (return))
510         (let ((hook-offs (offs-hook-offset next-hook)))
511           (when (or (> hook-offs cur-offs)
512                     (and (= hook-offs cur-offs)
513                          before-address
514                          (not (offs-hook-before-address next-hook))))
515             (return))
516           (unless (< hook-offs cur-offs)
517             (funcall (offs-hook-function next-hook) stream dstate))
518           (pop (dstate-cur-offs-hooks dstate))
519           (unless (= (dstate-next-offs dstate) cur-offs)
520             (return)))))))
521
522 (defun do-fun-hooks (chunk stream dstate)
523   (let ((hooks (dstate-fun-hooks dstate))
524         (cur-offs (dstate-cur-offs dstate)))
525     (setf (dstate-next-offs dstate) cur-offs)
526     (dolist (hook hooks nil)
527       (let ((prefix-p (funcall hook chunk stream dstate)))
528         (unless (= (dstate-next-offs dstate) cur-offs)
529           (return prefix-p))))))
530
531 (defun handle-bogus-instruction (stream dstate)
532   (let ((alignment (dstate-alignment dstate)))
533     (unless (null stream)
534       (multiple-value-bind (words bytes)
535           (truncate alignment sb!vm:word-bytes)
536         (when (> words 0)
537           (print-words words stream dstate))
538         (when (> bytes 0)
539           (print-bytes bytes stream dstate))))
540     (incf (dstate-next-offs dstate) alignment)))
541
542 ;;; Iterate through the instructions in SEGMENT, calling FUNCTION for
543 ;;; each instruction, with arguments of CHUNK, STREAM, and DSTATE.
544 (defun map-segment-instructions (function segment dstate &optional stream)
545   (declare (type function function)
546            (type segment segment)
547            (type disassem-state dstate)
548            (type (or null stream) stream))
549
550   (let ((ispace (get-inst-space))
551         (prefix-p nil)) ; just processed a prefix inst
552
553     (rewind-current-segment dstate segment)
554
555     (loop
556       (when (>= (dstate-cur-offs dstate)
557                 (seg-length (dstate-segment dstate)))
558         ;; done!
559         (return))
560
561       (setf (dstate-next-offs dstate) (dstate-cur-offs dstate))
562
563       (do-offs-hooks t stream dstate)
564       (unless (or prefix-p (null stream))
565         (print-current-address stream dstate))
566       (do-offs-hooks nil stream dstate)
567
568       (unless (> (dstate-next-offs dstate) (dstate-cur-offs dstate))
569         (sb!sys:without-gcing
570          (setf (dstate-segment-sap dstate) (funcall (seg-sap-maker segment)))
571
572          (let ((chunk
573                 (sap-ref-dchunk (dstate-segment-sap dstate)
574                                 (dstate-cur-offs dstate)
575                                 (dstate-byte-order dstate))))
576            (let ((fun-prefix-p (do-fun-hooks chunk stream dstate)))
577              (if (> (dstate-next-offs dstate) (dstate-cur-offs dstate))
578                  (setf prefix-p fun-prefix-p)
579                  (let ((inst (find-inst chunk ispace)))
580                    (cond ((null inst)
581                           (handle-bogus-instruction stream dstate))
582                          (t
583                           (setf (dstate-next-offs dstate)
584                                 (+ (dstate-cur-offs dstate)
585                                    (inst-length inst)))
586
587                           (let ((prefilter (inst-prefilter inst))
588                                 (control (inst-control inst)))
589                             (when prefilter
590                               (funcall prefilter chunk dstate))
591
592                             (funcall function chunk inst)
593
594                             (setf prefix-p (null (inst-printer inst)))
595
596                             (when control
597                               (funcall control chunk inst stream dstate))))))
598                  )))))
599
600       (setf (dstate-cur-offs dstate) (dstate-next-offs dstate))
601
602       (unless (null stream)
603         (unless prefix-p
604           (print-notes-and-newline stream dstate))
605         (setf (dstate-output-state dstate) nil)))))
606 \f
607 ;;; Make an initial non-printing disassembly pass through DSTATE,
608 ;;; noting any addresses that are referenced by instructions in this
609 ;;; segment.
610 (defun add-segment-labels (segment dstate)
611   ;; add labels at the beginning with a label-number of nil; we'll notice
612   ;; later and fill them in (and sort them)
613   (declare (type disassem-state dstate))
614   (let ((labels (dstate-labels dstate)))
615     (map-segment-instructions
616      (lambda (chunk inst)
617        (declare (type dchunk chunk) (type instruction inst))
618        (let ((labeller (inst-labeller inst)))
619          (when labeller
620            (setf labels (funcall labeller chunk labels dstate)))))
621      segment
622      dstate)
623     (setf (dstate-labels dstate) labels)
624     ;; erase any notes that got there by accident
625     (setf (dstate-notes dstate) nil)))
626
627 ;;; If any labels in DSTATE have been added since the last call to
628 ;;; this function, give them label-numbers, enter them in the
629 ;;; hash-table, and make sure the label list is in sorted order.
630 (defun number-labels (dstate)
631   (let ((labels (dstate-labels dstate)))
632     (when (and labels (null (cdar labels)))
633       ;; at least one label left un-numbered
634       (setf labels (sort labels #'< :key #'car))
635       (let ((max -1)
636             (label-hash (dstate-label-hash dstate)))
637         (dolist (label labels)
638           (when (not (null (cdr label)))
639             (setf max (max max (cdr label)))))
640         (dolist (label labels)
641           (when (null (cdr label))
642             (incf max)
643             (setf (cdr label) max)
644             (setf (gethash (car label) label-hash)
645                   (format nil "L~D" max)))))
646       (setf (dstate-labels dstate) labels))))
647 \f
648 ;;; Get the instruction-space, creating it if necessary.
649 (defun get-inst-space ()
650   (let ((ispace *disassem-inst-space*))
651     (when (null ispace)
652       (let ((insts nil))
653         (maphash (lambda (name inst-flavs)
654                    (declare (ignore name))
655                    (dolist (flav inst-flavs)
656                      (push flav insts)))
657                  *disassem-insts*)
658         (setf ispace (build-inst-space insts)))
659       (setf *disassem-inst-space* ispace))
660     ispace))
661 \f
662 ;;;; Add global hooks.
663
664 (defun add-offs-hook (segment addr hook)
665   (let ((entry (cons addr hook)))
666     (if (null (seg-hooks segment))
667         (setf (seg-hooks segment) (list entry))
668         (push entry (cdr (last (seg-hooks segment)))))))
669
670 (defun add-offs-note-hook (segment addr note)
671   (add-offs-hook segment
672                  addr
673                  (lambda (stream dstate)
674                    (declare (type (or null stream) stream)
675                             (type disassem-state dstate))
676                    (when stream
677                      (note note dstate)))))
678
679 (defun add-offs-comment-hook (segment addr comment)
680   (add-offs-hook segment
681                  addr
682                  (lambda (stream dstate)
683                    (declare (type (or null stream) stream)
684                             (ignore dstate))
685                    (when stream
686                      (write-string ";;; " stream)
687                      (etypecase comment
688                        (string
689                         (write-string comment stream))
690                        (function
691                         (funcall comment stream)))
692                      (terpri stream)))))
693
694 (defun add-fun-hook (dstate function)
695   (push function (dstate-fun-hooks dstate)))
696 \f
697 (defun set-location-printing-range (dstate from length)
698   (setf (dstate-addr-print-len dstate)
699         ;; 4 bits per hex digit
700         (ceiling (integer-length (logxor from (+ from length))) 4)))
701
702 ;;; Print the current address in DSTATE to STREAM, plus any labels that
703 ;;; correspond to it, and leave the cursor in the instruction column.
704 (defun print-current-address (stream dstate)
705   (declare (type stream stream)
706            (type disassem-state dstate))
707   (let* ((location
708           (+ (seg-virtual-location (dstate-segment dstate))
709              (dstate-cur-offs dstate)))
710          (location-column-width *disassem-location-column-width*)
711          (plen (dstate-addr-print-len dstate)))
712
713     (when (null plen)
714       (setf plen location-column-width)
715       (let ((seg (dstate-segment dstate)))
716         (set-location-printing-range dstate
717                                      (seg-virtual-location seg)
718                                      (seg-length seg))))
719     (when (eq (dstate-output-state dstate) :beginning)
720       (setf plen location-column-width))
721
722     (fresh-line stream)
723
724     (setf location-column-width (+ 2 location-column-width))
725     (princ "; " stream)
726
727     ;; print the location
728     ;; [this is equivalent to (format stream "~V,'0x:" plen printed-value), but
729     ;;  usually avoids any consing]
730     (tab0 (- location-column-width plen) stream)
731     (let* ((printed-bits (* 4 plen))
732            (printed-value (ldb (byte printed-bits 0) location))
733            (leading-zeros
734             (truncate (- printed-bits (integer-length printed-value)) 4)))
735       (dotimes (i leading-zeros)
736         (write-char #\0 stream))
737       (unless (zerop printed-value)
738         (write printed-value :stream stream :base 16 :radix nil))
739       (write-char #\: stream))
740
741     ;; print any labels
742     (loop
743       (let* ((next-label (car (dstate-cur-labels dstate)))
744              (label-location (car next-label)))
745         (when (or (null label-location) (> label-location location))
746           (return))
747         (unless (< label-location location)
748           (format stream " L~D:" (cdr next-label)))
749         (pop (dstate-cur-labels dstate))))
750
751     ;; move to the instruction column
752     (tab0 (+ location-column-width 1 label-column-width) stream)
753     ))
754 \f
755 (eval-when (:compile-toplevel :execute)
756   (sb!xc:defmacro with-print-restrictions (&rest body)
757     `(let ((*print-pretty* t)
758            (*print-lines* 2)
759            (*print-length* 4)
760            (*print-level* 3))
761        ,@body)))
762
763 ;;; Print a newline to STREAM, inserting any pending notes in DSTATE
764 ;;; as end-of-line comments. If there is more than one note, a
765 ;;; separate line will be used for each one.
766 (defun print-notes-and-newline (stream dstate)
767   (declare (type stream stream)
768            (type disassem-state dstate))
769   (with-print-restrictions
770     (dolist (note (dstate-notes dstate))
771       (format stream "~Vt " *disassem-note-column*)
772       (pprint-logical-block (stream nil :per-line-prefix "; ")
773       (etypecase note
774         (string
775          (write-string note stream))
776         (function
777          (funcall note stream))))
778       (terpri stream))
779     (fresh-line stream)
780     (setf (dstate-notes dstate) nil)))
781
782 ;;; Disassemble NUM bytes to STREAM as simple `BYTE' instructions.
783 (defun print-bytes (num stream dstate)
784   (declare (type offset num)
785            (type stream stream)
786            (type disassem-state dstate))
787   (format stream "~A~Vt" 'BYTE (dstate-argument-column dstate))
788   (let ((sap (dstate-segment-sap dstate))
789         (start-offs (dstate-cur-offs dstate)))
790     (dotimes (offs num)
791       (unless (zerop offs)
792         (write-string ", " stream))
793       (format stream "#X~2,'0x" (sb!sys:sap-ref-8 sap (+ offs start-offs))))))
794
795 ;;; Disassemble NUM machine-words to STREAM as simple `WORD' instructions.
796 (defun print-words (num stream dstate)
797   (declare (type offset num)
798            (type stream stream)
799            (type disassem-state dstate))
800   (format stream "~A~Vt" 'WORD (dstate-argument-column dstate))
801   (let ((sap (dstate-segment-sap dstate))
802         (start-offs (dstate-cur-offs dstate))
803         (byte-order (dstate-byte-order dstate)))
804     (dotimes (word-offs num)
805       (unless (zerop word-offs)
806         (write-string ", " stream))
807       (let ((word 0) (bit-shift 0))
808         (dotimes (byte-offs sb!vm:word-bytes)
809           (let ((byte
810                  (sb!sys:sap-ref-8
811                         sap
812                         (+ start-offs
813                            (* word-offs sb!vm:word-bytes)
814                            byte-offs))))
815             (setf word
816                   (if (eq byte-order :big-endian)
817                       (+ (ash word sb!vm:byte-bits) byte)
818                       (+ word (ash byte bit-shift))))
819             (incf bit-shift sb!vm:byte-bits)))
820         (format stream "#X~V,'0X" (ash sb!vm:n-word-bits -2) word)))))
821 \f
822 (defvar *default-dstate-hooks* (list #'lra-hook))
823
824 ;;; Make a disassembler-state object.
825 (defun make-dstate (&optional (fun-hooks *default-dstate-hooks*))
826   (let ((sap
827          (sb!sys:vector-sap (coerce #() '(vector (unsigned-byte 8)))))
828         (alignment *disassem-inst-alignment-bytes*)
829         (arg-column
830          (+ (or *disassem-opcode-column-width* 0)
831             *disassem-location-column-width*
832             1
833             label-column-width)))
834
835     (when (> alignment 1)
836       (push #'alignment-hook fun-hooks))
837
838     (%make-dstate :segment-sap sap
839                   :fun-hooks fun-hooks
840                   :argument-column arg-column
841                   :alignment alignment
842                   :byte-order sb!c:*backend-byte-order*)))
843
844 (defun add-fun-header-hooks (segment)
845   (declare (type segment segment))
846   (do ((fun (sb!kernel:code-header-ref (seg-code segment)
847                                        sb!vm:code-entry-points-slot)
848             (fun-next fun))
849        (length (seg-length segment)))
850       ((null fun))
851     (let ((offset (code-offs-to-segment-offs (fun-offset fun) segment)))
852       (when (<= 0 offset length)
853         (push (make-offs-hook :offset offset :function #'fun-header-hook)
854               (seg-hooks segment))))))
855 \f
856 ;;; A SAP-MAKER is a no-argument function that returns a SAP.
857
858 #!-sb-fluid (declaim (inline sap-maker))
859
860 (defun sap-maker (function input offset)
861   (declare (optimize (speed 3))
862            (type (function (t) sb!sys:system-area-pointer) function)
863            (type offset offset))
864   (let ((old-sap (sb!sys:sap+ (funcall function input) offset)))
865     (declare (type sb!sys:system-area-pointer old-sap))
866     (lambda ()
867       (let ((new-addr
868              (+ (sb!sys:sap-int (funcall function input)) offset)))
869         ;; Saving the sap like this avoids consing except when the sap
870         ;; changes (because the sap-int, arith, etc., get inlined).
871         (declare (type address new-addr))
872         (if (= (sb!sys:sap-int old-sap) new-addr)
873             old-sap
874             (setf old-sap (sb!sys:int-sap new-addr)))))))
875
876 (defun vector-sap-maker (vector offset)
877   (declare (optimize (speed 3))
878            (type offset offset))
879   (sap-maker #'sb!sys:vector-sap vector offset))
880
881 (defun code-sap-maker (code offset)
882   (declare (optimize (speed 3))
883            (type sb!kernel:code-component code)
884            (type offset offset))
885   (sap-maker #'sb!kernel:code-instructions code offset))
886
887 (defun memory-sap-maker (address)
888   (declare (optimize (speed 3))
889            (type address address))
890   (let ((sap (sb!sys:int-sap address)))
891     (lambda () sap)))
892 \f
893 ;;; Return a memory segment located at the system-area-pointer returned by
894 ;;; SAP-MAKER and LENGTH bytes long in the disassem-state object DSTATE.
895 ;;;
896 ;;; &KEY arguments include :VIRTUAL-LOCATION (by default the same as
897 ;;; the address), :DEBUG-FUN, :SOURCE-FORM-CACHE (a
898 ;;; SOURCE-FORM-CACHE object), and :HOOKS (a list of OFFS-HOOK
899 ;;; objects).
900 (defun make-segment (sap-maker length
901                      &key
902                      code virtual-location
903                      debug-fun source-form-cache
904                      hooks)
905   (declare (type (function () sb!sys:system-area-pointer) sap-maker)
906            (type length length)
907            (type (or null address) virtual-location)
908            (type (or null sb!di:debug-fun) debug-fun)
909            (type (or null source-form-cache) source-form-cache))
910   (let* ((segment
911           (%make-segment
912            :sap-maker sap-maker
913            :length length
914            :virtual-location (or virtual-location
915                                  (sb!sys:sap-int (funcall sap-maker)))
916            :hooks hooks
917            :code code)))
918     (add-debugging-hooks segment debug-fun source-form-cache)
919     (add-fun-header-hooks segment)
920     segment))
921
922 (defun make-vector-segment (vector offset &rest args)
923   (declare (type vector vector)
924            (type offset offset)
925            (inline make-segment))
926   (apply #'make-segment (vector-sap-maker vector offset) args))
927
928 (defun make-code-segment (code offset length &rest args)
929   (declare (type sb!kernel:code-component code)
930            (type offset offset)
931            (inline make-segment))
932   (apply #'make-segment (code-sap-maker code offset) length :code code args))
933
934 (defun make-memory-segment (address &rest args)
935   (declare (type address address)
936            (inline make-segment))
937   (apply #'make-segment (memory-sap-maker address) args))
938 \f
939 ;;; just for fun
940 (defun print-fun-headers (function)
941   (declare (type compiled-function function))
942   (let* ((self (fun-self function))
943          (code (sb!kernel:fun-code-header self)))
944     (format t "Code-header ~S: size: ~S, trace-table-offset: ~S~%"
945             code
946             (sb!kernel:code-header-ref code
947                                        sb!vm:code-code-size-slot)
948             (sb!kernel:code-header-ref code
949                                        sb!vm:code-trace-table-offset-slot))
950     (do ((fun (sb!kernel:code-header-ref code sb!vm:code-entry-points-slot)
951               (fun-next fun)))
952         ((null fun))
953       (let ((fun-offset (sb!kernel:get-closure-length fun)))
954         ;; There is function header fun-offset words from the
955         ;; code header.
956         (format t "Fun-header ~S at offset ~D (words): ~S~A => ~S~%"
957                 fun
958                 fun-offset
959                 (sb!kernel:code-header-ref
960                  code (+ fun-offset sb!vm:simple-fun-name-slot))
961                 (sb!kernel:code-header-ref
962                  code (+ fun-offset sb!vm:simple-fun-arglist-slot))
963                 (sb!kernel:code-header-ref
964                  code (+ fun-offset sb!vm:simple-fun-type-slot)))))))
965 \f
966 ;;; getting at the source code...
967
968 (defstruct (source-form-cache (:conc-name sfcache-)
969                               (:copier nil))
970   (debug-source nil :type (or null sb!di:debug-source))
971   (top-level-form-index -1 :type fixnum)
972   (top-level-form nil :type list)
973   (form-number-mapping-table nil :type (or null (vector list)))
974   (last-location-retrieved nil :type (or null sb!di:code-location))
975   (last-form-retrieved -1 :type fixnum))
976
977 (defun get-top-level-form (debug-source tlf-index)
978   (let ((name (sb!di:debug-source-name debug-source)))
979     (ecase (sb!di:debug-source-from debug-source)
980       (:file
981        (cond ((not (probe-file name))
982               (warn "The source file ~S no longer seems to exist." name)
983               nil)
984              (t
985               (let ((start-positions
986                      (sb!di:debug-source-start-positions debug-source)))
987                 (cond ((null start-positions)
988                        (warn "There is no start positions map.")
989                        nil)
990                       (t
991                        (let* ((local-tlf-index
992                                (- tlf-index
993                                   (sb!di:debug-source-root-number
994                                    debug-source)))
995                               (char-offset
996                                (aref start-positions local-tlf-index)))
997                          (with-open-file (f name)
998                            (cond ((= (sb!di:debug-source-created debug-source)
999                                      (file-write-date name))
1000                                   (file-position f char-offset))
1001                                  (t
1002                                   (warn "Source file ~S has been modified; ~@
1003                                          using form offset instead of file index."
1004                                         name)
1005                                   (let ((*read-suppress* t))
1006                                     (dotimes (i local-tlf-index) (read f)))))
1007                            (let ((*readtable* (copy-readtable)))
1008                              (set-dispatch-macro-character
1009                               #\# #\.
1010                               (lambda (stream sub-char &rest rest)
1011                                 (declare (ignore rest sub-char))
1012                                 (let ((token (read stream t nil t)))
1013                                   (format nil "#.~S" token))))
1014                              (read f))
1015                            ))))))))
1016       (:lisp
1017        (aref name tlf-index)))))
1018
1019 (defun cache-valid (loc cache)
1020   (and cache
1021        (and (eq (sb!di:code-location-debug-source loc)
1022                 (sfcache-debug-source cache))
1023             (eq (sb!di:code-location-top-level-form-offset loc)
1024                 (sfcache-top-level-form-index cache)))))
1025
1026 (defun get-source-form (loc context &optional cache)
1027   (let* ((cache-valid (cache-valid loc cache))
1028          (tlf-index (sb!di:code-location-top-level-form-offset loc))
1029          (form-number (sb!di:code-location-form-number loc))
1030          (top-level-form
1031           (if cache-valid
1032               (sfcache-top-level-form cache)
1033               (get-top-level-form (sb!di:code-location-debug-source loc)
1034                                   tlf-index)))
1035          (mapping-table
1036           (if cache-valid
1037               (sfcache-form-number-mapping-table cache)
1038               (sb!di:form-number-translations top-level-form tlf-index))))
1039     (when (and (not cache-valid) cache)
1040       (setf (sfcache-debug-source cache) (sb!di:code-location-debug-source loc)
1041             (sfcache-top-level-form-index cache) tlf-index
1042             (sfcache-top-level-form cache) top-level-form
1043             (sfcache-form-number-mapping-table cache) mapping-table))
1044     (cond ((null top-level-form)
1045            nil)
1046           ((> form-number (length mapping-table))
1047            (warn "bogus form-number in form!  The source file has probably ~@
1048                   been changed too much to cope with.")
1049            (when cache
1050              ;; Disable future warnings.
1051              (setf (sfcache-top-level-form cache) nil))
1052            nil)
1053           (t
1054            (when cache
1055              (setf (sfcache-last-location-retrieved cache) loc)
1056              (setf (sfcache-last-form-retrieved cache) form-number))
1057            (sb!di:source-path-context top-level-form
1058                                       (aref mapping-table form-number)
1059                                       context)))))
1060
1061 (defun get-different-source-form (loc context &optional cache)
1062   (if (and (cache-valid loc cache)
1063            (or (= (sb!di:code-location-form-number loc)
1064                   (sfcache-last-form-retrieved cache))
1065                (and (sfcache-last-location-retrieved cache)
1066                     (sb!di:code-location=
1067                      loc
1068                      (sfcache-last-location-retrieved cache)))))
1069       (values nil nil)
1070       (values (get-source-form loc context cache) t)))
1071 \f
1072 ;;;; stuff to use debugging-info to augment the disassembly
1073
1074 (defun code-fun-map (code)
1075   (declare (type sb!kernel:code-component code))
1076   (sb!di::get-debug-info-fun-map (sb!kernel:%code-debug-info code)))
1077
1078 (defstruct (location-group (:copier nil))
1079   (locations #() :type (vector (or list fixnum))))
1080
1081 (defstruct (storage-info (:copier nil))
1082   (groups nil :type list)               ; alist of (name . location-group)
1083   (debug-vars #() :type vector))
1084
1085 ;;; Return the vector of DEBUG-VARs currently associated with DSTATE.
1086 (defun dstate-debug-vars (dstate)
1087   (declare (type disassem-state dstate))
1088   (storage-info-debug-vars (seg-storage-info (dstate-segment dstate))))
1089
1090 ;;; Given the OFFSET of a location within the location-group called
1091 ;;; LG-NAME, see whether there's a current mapping to a source
1092 ;;; variable in DSTATE, and if so, return the offset of that variable
1093 ;;; in the current debug-var vector.
1094 (defun find-valid-storage-location (offset lg-name dstate)
1095   (declare (type offset offset)
1096            (type symbol lg-name)
1097            (type disassem-state dstate))
1098   (let* ((storage-info
1099           (seg-storage-info (dstate-segment dstate)))
1100          (location-group
1101           (and storage-info
1102                (cdr (assoc lg-name (storage-info-groups storage-info)))))
1103          (currently-valid
1104           (dstate-current-valid-locations dstate)))
1105     (and location-group
1106          (not (null currently-valid))
1107          (let ((locations (location-group-locations location-group)))
1108            (and (< offset (length locations))
1109                 (let ((used-by (aref locations offset)))
1110                   (and used-by
1111                        (let ((debug-var-num
1112                               (typecase used-by
1113                                 (fixnum
1114                                  (and (not
1115                                        (zerop (bit currently-valid used-by)))
1116                                       used-by))
1117                                 (list
1118                                  (some (lambda (num)
1119                                          (and (not
1120                                                (zerop
1121                                                 (bit currently-valid num)))
1122                                               num))
1123                                        used-by)))))
1124                          (and debug-var-num
1125                               (progn
1126                                 ;; Found a valid storage reference!
1127                                 ;; can't use it again until it's revalidated...
1128                                 (setf (bit (dstate-current-valid-locations
1129                                             dstate)
1130                                            debug-var-num)
1131                                       0)
1132                                 debug-var-num))
1133                          ))))))))
1134
1135 ;;; Return a new vector which has the same contents as the old one
1136 ;;; VEC, plus new cells (for a total size of NEW-LEN). The additional
1137 ;;; elements are initialized to INITIAL-ELEMENT.
1138 (defun grow-vector (vec new-len &optional initial-element)
1139   (declare (type vector vec)
1140            (type fixnum new-len))
1141   (let ((new
1142          (make-sequence `(vector ,(array-element-type vec) ,new-len)
1143                         new-len
1144                         :initial-element initial-element)))
1145     (dotimes (i (length vec))
1146       (setf (aref new i) (aref vec i)))
1147     new))
1148
1149 ;;; Return a STORAGE-INFO struction describing the object-to-source
1150 ;;; variable mappings from DEBUG-FUN.
1151 (defun storage-info-for-debug-fun (debug-fun)
1152   (declare (type sb!di:debug-fun debug-fun))
1153   (let ((sc-vec sb!c::*backend-sc-numbers*)
1154         (groups nil)
1155         (debug-vars (sb!di::debug-fun-debug-vars
1156                      debug-fun)))
1157     (and debug-vars
1158          (dotimes (debug-var-offset
1159                    (length debug-vars)
1160                    (make-storage-info :groups groups
1161                                       :debug-vars debug-vars))
1162            (let ((debug-var (aref debug-vars debug-var-offset)))
1163              #+nil
1164              (format t ";;; At offset ~D: ~S~%" debug-var-offset debug-var)
1165              (let* ((sc-offset
1166                      (sb!di::compiled-debug-var-sc-offset debug-var))
1167                     (sb-name
1168                      (sb!c:sb-name
1169                       (sb!c:sc-sb (aref sc-vec
1170                                         (sb!c:sc-offset-scn sc-offset))))))
1171                #+nil
1172                (format t ";;; SET: ~S[~D]~%"
1173                        sb-name (sb!c:sc-offset-offset sc-offset))
1174                (unless (null sb-name)
1175                  (let ((group (cdr (assoc sb-name groups))))
1176                    (when (null group)
1177                      (setf group (make-location-group))
1178                      (push `(,sb-name . ,group) groups))
1179                    (let* ((locations (location-group-locations group))
1180                           (length (length locations))
1181                           (offset (sb!c:sc-offset-offset sc-offset)))
1182                      (when (>= offset length)
1183                        (setf locations
1184                              (grow-vector locations
1185                                           (max (* 2 length)
1186                                                (1+ offset))
1187                                           nil)
1188                              (location-group-locations group)
1189                              locations))
1190                      (let ((already-there (aref locations offset)))
1191                        (cond ((null already-there)
1192                               (setf (aref locations offset) debug-var-offset))
1193                              ((eql already-there debug-var-offset))
1194                              (t
1195                               (if (listp already-there)
1196                                   (pushnew debug-var-offset
1197                                            (aref locations offset))
1198                                   (setf (aref locations offset)
1199                                         (list debug-var-offset
1200                                               already-there)))))
1201                        )))))))
1202          )))
1203
1204 (defun source-available-p (debug-fun)
1205   (handler-case
1206       (sb!di:do-debug-fun-blocks (block debug-fun)
1207         (declare (ignore block))
1208         (return t))
1209     (sb!di:no-debug-blocks () nil)))
1210
1211 (defun print-block-boundary (stream dstate)
1212   (let ((os (dstate-output-state dstate)))
1213     (when (not (eq os :beginning))
1214       (when (not (eq os :block-boundary))
1215         (terpri stream))
1216       (setf (dstate-output-state dstate)
1217             :block-boundary))))
1218
1219 ;;; Add hooks to track to track the source code in SEGMENT during
1220 ;;; disassembly. SFCACHE can be either NIL or it can be a
1221 ;;; SOURCE-FORM-CACHE structure, in which case it is used to cache
1222 ;;; forms from files.
1223 (defun add-source-tracking-hooks (segment debug-fun &optional sfcache)
1224   (declare (type segment segment)
1225            (type (or null sb!di:debug-fun) debug-fun)
1226            (type (or null source-form-cache) sfcache))
1227   (let ((last-block-pc -1))
1228     (flet ((add-hook (pc fun &optional before-address)
1229              (push (make-offs-hook
1230                     :offset pc ;; ##### FIX to account for non-zero offs in code
1231                     :function fun
1232                     :before-address before-address)
1233                    (seg-hooks segment))))
1234       (handler-case
1235           (sb!di:do-debug-fun-blocks (block debug-fun)
1236             (let ((first-location-in-block-p t))
1237               (sb!di:do-debug-block-locations (loc block)
1238                 (let ((pc (sb!di::compiled-code-location-pc loc)))
1239
1240                   ;; Put blank lines in at block boundaries
1241                   (when (and first-location-in-block-p
1242                              (/= pc last-block-pc))
1243                     (setf first-location-in-block-p nil)
1244                     (add-hook pc
1245                               (lambda (stream dstate)
1246                                 (print-block-boundary stream dstate))
1247                               t)
1248                     (setf last-block-pc pc))
1249
1250                   ;; Print out corresponding source; this information is not
1251                   ;; all that accurate, but it's better than nothing
1252                   (unless (zerop (sb!di:code-location-form-number loc))
1253                     (multiple-value-bind (form new)
1254                         (get-different-source-form loc 0 sfcache)
1255                       (when new
1256                          (let ((at-block-begin (= pc last-block-pc)))
1257                            (add-hook
1258                             pc
1259                             (lambda (stream dstate)
1260                               (declare (ignore dstate))
1261                               (when stream
1262                                 (unless at-block-begin
1263                                   (terpri stream))
1264                                 (format stream ";;; [~D] "
1265                                         (sb!di:code-location-form-number
1266                                          loc))
1267                                 (prin1-short form stream)
1268                                 (terpri stream)
1269                                 (terpri stream)))
1270                             t)))))
1271
1272                   ;; Keep track of variable live-ness as best we can.
1273                   (let ((live-set
1274                          (copy-seq (sb!di::compiled-code-location-live-set
1275                                     loc))))
1276                     (add-hook
1277                      pc
1278                      (lambda (stream dstate)
1279                        (declare (ignore stream))
1280                        (setf (dstate-current-valid-locations dstate)
1281                              live-set)
1282                        #+nil
1283                        (note (lambda (stream)
1284                                (let ((*print-length* nil))
1285                                  (format stream "live set: ~S"
1286                                          live-set)))
1287                              dstate))))
1288                   ))))
1289         (sb!di:no-debug-blocks () nil)))))
1290
1291 (defun add-debugging-hooks (segment debug-fun &optional sfcache)
1292   (when debug-fun
1293     (setf (seg-storage-info segment)
1294           (storage-info-for-debug-fun debug-fun))
1295     (add-source-tracking-hooks segment debug-fun sfcache)
1296     (let ((kind (sb!di:debug-fun-kind debug-fun)))
1297       (flet ((anh (n)
1298                (push (make-offs-hook
1299                       :offset 0
1300                       :function (lambda (stream dstate)
1301                                   (declare (ignore stream))
1302                                   (note n dstate)))
1303                      (seg-hooks segment))))
1304         (case kind
1305           (:external)
1306           ((nil)
1307            (anh "no-arg-parsing entry point"))
1308           (t
1309            (anh (lambda (stream)
1310                   (format stream "~S entry point" kind)))))))))
1311 \f
1312 ;;; Return a list of the segments of memory containing machine code
1313 ;;; instructions for FUNCTION.
1314 (defun get-function-segments (function)
1315   (declare (type compiled-function function))
1316   (let* ((code (fun-code function))
1317          (fun-map (code-fun-map code))
1318          (fname (sb!kernel:%simple-fun-name function))
1319          (sfcache (make-source-form-cache)))
1320     (let ((first-block-seen-p nil)
1321           (nil-block-seen-p nil)
1322           (last-offset 0)
1323           (last-debug-fun nil)
1324           (segments nil))
1325       (flet ((add-seg (offs len df)
1326                (when (> len 0)
1327                  (push (make-code-segment code offs len
1328                                           :debug-fun df
1329                                           :source-form-cache sfcache)
1330                        segments))))
1331         (dotimes (fmap-index (length fun-map))
1332           (let ((fmap-entry (aref fun-map fmap-index)))
1333             (etypecase fmap-entry
1334               (integer
1335                (when first-block-seen-p
1336                  (add-seg last-offset
1337                           (- fmap-entry last-offset)
1338                           last-debug-fun)
1339                  (setf last-debug-fun nil))
1340                (setf last-offset fmap-entry))
1341               (sb!c::compiled-debug-fun
1342                (let ((name (sb!c::compiled-debug-fun-name fmap-entry))
1343                      (kind (sb!c::compiled-debug-fun-kind fmap-entry)))
1344                  #+nil
1345                  (format t ";;; SAW ~S ~S ~S,~S ~D,~D~%"
1346                          name kind first-block-seen-p nil-block-seen-p
1347                          last-offset
1348                          (sb!c::compiled-debug-fun-start-pc fmap-entry))
1349                  (cond (#+nil (eq last-offset fun-offset)
1350                               (and (equal name fname) (not first-block-seen-p))
1351                               (setf first-block-seen-p t))
1352                        ((eq kind :external)
1353                         (when first-block-seen-p
1354                           (return)))
1355                        ((eq kind nil)
1356                         (when nil-block-seen-p
1357                           (return))
1358                         (when first-block-seen-p
1359                           (setf nil-block-seen-p t))))
1360                  (setf last-debug-fun
1361                        (sb!di::make-compiled-debug-fun fmap-entry code))
1362                  )))))
1363         (let ((max-offset (code-inst-area-length code)))
1364           (when (and first-block-seen-p last-debug-fun)
1365             (add-seg last-offset
1366                      (- max-offset last-offset)
1367                      last-debug-fun))
1368           (if (null segments)
1369               (let ((offs (fun-insts-offset function)))
1370                 (make-code-segment code offs (- max-offset offs)))
1371               (nreverse segments)))))))
1372
1373 ;;; Return a list of the segments of memory containing machine code
1374 ;;; instructions for the code-component CODE. If START-OFFSET and/or
1375 ;;; LENGTH is supplied, only that part of the code-segment is used
1376 ;;; (but these are constrained to lie within the code-segment).
1377 (defun get-code-segments (code
1378                           &optional
1379                           (start-offset 0)
1380                           (length (code-inst-area-length code)))
1381   (declare (type sb!kernel:code-component code)
1382            (type offset start-offset)
1383            (type length length))
1384   (let ((segments nil))
1385     (when code
1386       (let ((fun-map (code-fun-map code))
1387             (sfcache (make-source-form-cache)))
1388         (let ((last-offset 0)
1389               (last-debug-fun nil))
1390           (flet ((add-seg (offs len df)
1391                    (let* ((restricted-offs
1392                            (min (max start-offset offs)
1393                                 (+ start-offset length)))
1394                           (restricted-len
1395                            (- (min (max start-offset (+ offs len))
1396                                    (+ start-offset length))
1397                               restricted-offs)))
1398                      (when (> restricted-len 0)
1399                        (push (make-code-segment code
1400                                                 restricted-offs restricted-len
1401                                                 :debug-fun df
1402                                                 :source-form-cache sfcache)
1403                              segments)))))
1404             (dotimes (fun-map-index (length fun-map))
1405               (let ((fun-map-entry (aref fun-map fun-map-index)))
1406                 (etypecase fun-map-entry
1407                   (integer
1408                    (add-seg last-offset (- fun-map-entry last-offset)
1409                             last-debug-fun)
1410                    (setf last-debug-fun nil)
1411                    (setf last-offset fun-map-entry))
1412                   (sb!c::compiled-debug-fun
1413                    (setf last-debug-fun
1414                          (sb!di::make-compiled-debug-fun fun-map-entry
1415                                                          code))))))
1416             (when last-debug-fun
1417               (add-seg last-offset
1418                        (- (code-inst-area-length code) last-offset)
1419                        last-debug-fun))))))
1420     (if (null segments)
1421         (make-code-segment code start-offset length)
1422         (nreverse segments))))
1423 \f
1424 ;;; Return two values: the amount by which the last instruction in the
1425 ;;; segment goes past the end of the segment, and the offset of the
1426 ;;; end of the segment from the beginning of that instruction. If all
1427 ;;; instructions fit perfectly, return 0 and 0.
1428 (defun segment-overflow (segment dstate)
1429   (declare (type segment segment)
1430            (type disassem-state dstate))
1431   (let ((seglen (seg-length segment))
1432         (last-start 0))
1433     (map-segment-instructions (lambda (chunk inst)
1434                                 (declare (ignore chunk inst))
1435                                 (setf last-start (dstate-cur-offs dstate)))
1436                               segment
1437                               dstate)
1438     (values (- (dstate-cur-offs dstate) seglen)
1439             (- seglen last-start))))
1440
1441 ;;; Compute labels for all the memory segments in SEGLIST and adds
1442 ;;; them to DSTATE. It's important to call this function with all the
1443 ;;; segments you're interested in, so that it can find references from
1444 ;;; one to another.
1445 (defun label-segments (seglist dstate)
1446   (declare (type list seglist)
1447            (type disassem-state dstate))
1448   (dolist (seg seglist)
1449     (add-segment-labels seg dstate))
1450   ;; Now remove any labels that don't point anywhere in the segments
1451   ;; we have.
1452   (setf (dstate-labels dstate)
1453         (remove-if (lambda (lab)
1454                      (not
1455                       (some (lambda (seg)
1456                               (let ((start (seg-virtual-location seg)))
1457                                 (<= start
1458                                     (car lab)
1459                                     (+ start (seg-length seg)))))
1460                             seglist)))
1461                    (dstate-labels dstate))))
1462
1463 ;;; Disassemble the machine code instructions in SEGMENT to STREAM.
1464 (defun disassemble-segment (segment stream dstate)
1465   (declare (type segment segment)
1466            (type stream stream)
1467            (type disassem-state dstate))
1468   (let ((*print-pretty* nil)) ; otherwise the pp conses hugely
1469     (number-labels dstate)
1470     (map-segment-instructions
1471      (lambda (chunk inst)
1472        (declare (type dchunk chunk) (type instruction inst))
1473        (let ((printer (inst-printer inst)))
1474          (when printer
1475            (funcall printer chunk inst stream dstate))))
1476      segment
1477      dstate
1478      stream)))
1479
1480 ;;; Disassemble the machine code instructions in each memory segment
1481 ;;; in SEGMENTS in turn to STREAM.
1482 (defun disassemble-segments (segments stream dstate)
1483   (declare (type list segments)
1484            (type stream stream)
1485            (type disassem-state dstate))
1486   (unless (null segments)
1487     (let ((first (car segments))
1488           (last (car (last segments))))
1489       (set-location-printing-range dstate
1490                                   (seg-virtual-location first)
1491                                   (- (+ (seg-virtual-location last)
1492                                         (seg-length last))
1493                                      (seg-virtual-location first)))
1494       (setf (dstate-output-state dstate) :beginning)
1495       (dolist (seg segments)
1496         (disassemble-segment seg stream dstate)))))
1497 \f
1498 ;;;; top-level functions
1499
1500 ;;; Disassemble the machine code instructions for FUNCTION.
1501 (defun disassemble-function (function &key
1502                                       (stream *standard-output*)
1503                                       (use-labels t))
1504   (declare (type compiled-function function)
1505            (type stream stream)
1506            (type (member t nil) use-labels))
1507   (let* ((dstate (make-dstate))
1508          (segments (get-function-segments function)))
1509     (when use-labels
1510       (label-segments segments dstate))
1511     (disassemble-segments segments stream dstate)))
1512
1513 (defun compile-function-lambda-expr (function)
1514   (declare (type function function))
1515   (multiple-value-bind (lambda closurep name)
1516       (function-lambda-expression function)
1517     (declare (ignore name))
1518     (when closurep
1519       (error "can't compile a lexical closure"))
1520     (compile nil lambda)))
1521
1522 (defun compiled-function-or-lose (thing &optional (name thing))
1523   (cond ((or (symbolp thing)
1524              (and (listp thing)
1525                   (eq (car thing) 'setf)))
1526          (compiled-function-or-lose (fdefinition thing) thing))
1527         ((functionp thing)
1528          thing)
1529         ((and (listp thing)
1530               (eq (car thing) 'lambda))
1531          (compile nil thing))
1532         (t
1533          (error "can't make a compiled function from ~S" name))))
1534
1535 (defun disassemble (object &key
1536                            (stream *standard-output*)
1537                            (use-labels t))
1538   #!+sb-doc
1539   "Disassemble the compiled code associated with OBJECT, which can be a
1540   function, a lambda expression, or a symbol with a function definition. If
1541   it is not already compiled, the compiler is called to produce something to
1542   disassemble."
1543   (declare (type (or function symbol cons) object)
1544            (type (or (member t) stream) stream)
1545            (type (member t nil) use-labels))
1546   (pprint-logical-block (*standard-output* nil :per-line-prefix "; ")
1547     (disassemble-function (compiled-function-or-lose object)
1548                           :stream stream
1549                           :use-labels use-labels)
1550     nil))
1551
1552 ;;; Disassembles the given area of memory starting at ADDRESS and
1553 ;;; LENGTH long. Note that if CODE-COMPONENT is NIL and this memory
1554 ;;; could move during a GC, you'd better disable it around the call to
1555 ;;; this function.
1556 (defun disassemble-memory (address
1557                            length
1558                            &key
1559                            (stream *standard-output*)
1560                            code-component
1561                            (use-labels t))
1562   (declare (type (or address sb!sys:system-area-pointer) address)
1563            (type length length)
1564            (type stream stream)
1565            (type (or null sb!kernel:code-component) code-component)
1566            (type (member t nil) use-labels))
1567   (let* ((address
1568           (if (sb!sys:system-area-pointer-p address)
1569               (sb!sys:sap-int address)
1570               address))
1571          (dstate (make-dstate))
1572          (segments
1573           (if code-component
1574               (let ((code-offs
1575                      (- address
1576                         (sb!sys:sap-int
1577                          (sb!kernel:code-instructions code-component)))))
1578                 (when (or (< code-offs 0)
1579                           (> code-offs (code-inst-area-length code-component)))
1580                   (error "address ~X not in the code component ~S"
1581                          address code-component))
1582                 (get-code-segments code-component code-offs length))
1583               (list (make-memory-segment address length)))))
1584     (when use-labels
1585       (label-segments segments dstate))
1586     (disassemble-segments segments stream dstate)))
1587
1588 ;;; Disassemble the machine code instructions associated with
1589 ;;; CODE-COMPONENT (this may include multiple entry points).
1590 (defun disassemble-code-component (code-component &key
1591                                                   (stream *standard-output*)
1592                                                   (use-labels t))
1593   (declare (type (or null sb!kernel:code-component compiled-function)
1594                  code-component)
1595            (type stream stream)
1596            (type (member t nil) use-labels))
1597   (let* ((code-component
1598           (if (functionp code-component)
1599               (fun-code code-component)
1600               code-component))
1601          (dstate (make-dstate))
1602          (segments (get-code-segments code-component)))
1603     (when use-labels
1604       (label-segments segments dstate))
1605     (disassemble-segments segments stream dstate)))
1606 \f
1607 ;;; code for making useful segments from arbitrary lists of code-blocks
1608
1609 ;;; the maximum size of an instruction. Note that this includes
1610 ;;; pseudo-instructions like error traps with their associated
1611 ;;; operands, so it should be big enough to include them, i.e. it's
1612 ;;; not just 4 on a risc machine!
1613 (defconstant max-instruction-size 16)
1614
1615 (defun add-block-segments (seg-code-block
1616                            seglist
1617                            location
1618                            connecting-vec
1619                            dstate)
1620   (declare (type list seglist)
1621            (type integer location)
1622            (type (or null (vector (unsigned-byte 8))) connecting-vec)
1623            (type disassem-state dstate))
1624   (flet ((addit (seg overflow)
1625            (let ((length (+ (seg-length seg) overflow)))
1626              (when (> length 0)
1627                (setf (seg-length seg) length)
1628                (incf location length)
1629                (push seg seglist)))))
1630     (let ((connecting-overflow 0)
1631           (amount (length seg-code-block)))
1632       (when connecting-vec
1633         ;; Tack on some of the new block to the old overflow vector.
1634         (let* ((beginning-of-block-amount
1635                 (if seg-code-block (min max-instruction-size amount) 0))
1636                (connecting-vec
1637                 (if seg-code-block
1638                     (concatenate
1639                      '(vector (unsigned-byte 8))
1640                      connecting-vec
1641                      (subseq seg-code-block 0 beginning-of-block-amount))
1642                     connecting-vec)))
1643           (when (and (< (length connecting-vec) max-instruction-size)
1644                      (not (null seg-code-block)))
1645             (return-from add-block-segments
1646               ;; We want connecting vectors to be large enough to hold
1647               ;; any instruction, and since the current seg-code-block
1648               ;; wasn't large enough to do this (and is now entirely
1649               ;; on the end of the overflow-vector), just save it for
1650               ;; next time.
1651               (values seglist location connecting-vec)))
1652           (when (> (length connecting-vec) 0)
1653             (let ((seg
1654                    (make-vector-segment connecting-vec
1655                                         0
1656                                         (- (length connecting-vec)
1657                                            beginning-of-block-amount)
1658                                         :virtual-location location)))
1659               (setf connecting-overflow (segment-overflow seg dstate))
1660               (addit seg connecting-overflow)))))
1661       (cond ((null seg-code-block)
1662              ;; nothing more to add
1663              (values seglist location nil))
1664             ((< (- amount connecting-overflow) max-instruction-size)
1665              ;; We can't create a segment with the minimum size
1666              ;; required for an instruction, so just keep on accumulating
1667              ;; in the overflow vector for the time-being.
1668              (values seglist
1669                      location
1670                      (subseq seg-code-block connecting-overflow amount)))
1671             (t
1672              ;; Put as much as we can into a new segment, and the rest
1673              ;; into the overflow-vector.
1674              (let* ((initial-length
1675                      (- amount connecting-overflow max-instruction-size))
1676                     (seg
1677                      (make-vector-segment seg-code-block
1678                                           connecting-overflow
1679                                           initial-length
1680                                           :virtual-location location))
1681                     (overflow
1682                      (segment-overflow seg dstate)))
1683                (addit seg overflow)
1684                (values seglist
1685                        location
1686                        (subseq seg-code-block
1687                                (+ connecting-overflow (seg-length seg))
1688                                amount))))))))
1689 \f
1690 ;;;; code to disassemble assembler segments
1691
1692 (defun assem-segment-to-disassem-segments (assem-segment dstate)
1693   (declare (type sb!assem:segment assem-segment)
1694            (type disassem-state dstate))
1695   (let ((location 0)
1696         (disassem-segments nil)
1697         (connecting-vec nil))
1698     (sb!assem:on-segment-contents-vectorly
1699      assem-segment
1700      (lambda (seg-code-block)
1701        (multiple-value-setq (disassem-segments location connecting-vec)
1702          (add-block-segments seg-code-block
1703                              disassem-segments
1704                              location
1705                              connecting-vec
1706                              dstate))))
1707     (when connecting-vec
1708       (setf disassem-segments
1709             (add-block-segments nil
1710                                 disassem-segments
1711                                 location
1712                                 connecting-vec
1713                                 dstate)))
1714     (sort disassem-segments #'< :key #'seg-virtual-location)))
1715
1716 ;;; Disassemble the machine code instructions associated with
1717 ;;; ASSEM-SEGMENT (of type assem:segment).
1718 (defun disassemble-assem-segment (assem-segment stream)
1719   (declare (type sb!assem:segment assem-segment)
1720            (type stream stream))
1721   (let* ((dstate (make-dstate))
1722          (disassem-segments
1723           (assem-segment-to-disassem-segments assem-segment dstate)))
1724     (label-segments disassem-segments dstate)
1725     (disassemble-segments disassem-segments stream dstate)))
1726 \f
1727 ;;; routines to find things in the Lisp environment
1728
1729 ;;; an alist of (SYMBOL-SLOT-OFFSET . ACCESS-FUNCTION-NAME) for slots
1730 ;;; in a symbol object that we know about
1731 (defparameter *grokked-symbol-slots*
1732   (sort `((,sb!vm:symbol-value-slot . symbol-value)
1733           (,sb!vm:symbol-plist-slot . symbol-plist)
1734           (,sb!vm:symbol-name-slot . symbol-name)
1735           (,sb!vm:symbol-package-slot . symbol-package))
1736         #'<
1737         :key #'car))
1738
1739 ;;; Given ADDRESS, try and figure out if which slot of which symbol is
1740 ;;; being referred to. Of course we can just give up, so it's not a
1741 ;;; big deal... Return two values, the symbol and the name of the
1742 ;;; access function of the slot.
1743 (defun grok-symbol-slot-ref (address)
1744   (declare (type address address))
1745   (if (not (aligned-p address sb!vm:word-bytes))
1746       (values nil nil)
1747       (do ((slots-tail *grokked-symbol-slots* (cdr slots-tail)))
1748           ((null slots-tail)
1749            (values nil nil))
1750         (let* ((field (car slots-tail))
1751                (slot-offset (words-to-bytes (car field)))
1752                (maybe-symbol-addr (- address slot-offset))
1753                (maybe-symbol
1754                 (sb!kernel:make-lisp-obj
1755                  (+ maybe-symbol-addr sb!vm:other-pointer-lowtag))))
1756           (when (symbolp maybe-symbol)
1757             (return (values maybe-symbol (cdr field))))))))
1758
1759 (defvar *address-of-nil-object* (sb!kernel:get-lisp-obj-address nil))
1760
1761 ;;; Given a BYTE-OFFSET from NIL, try and figure out which slot of
1762 ;;; which symbol is being referred to. Of course we can just give up,
1763 ;;; so it's not a big deal... Return two values, the symbol and the
1764 ;;; access function.
1765 (defun grok-nil-indexed-symbol-slot-ref (byte-offset)
1766   (declare (type offset byte-offset))
1767   (grok-symbol-slot-ref (+ *address-of-nil-object* byte-offset)))
1768
1769 ;;; Return the Lisp object located BYTE-OFFSET from NIL.
1770 (defun get-nil-indexed-object (byte-offset)
1771   (declare (type offset byte-offset))
1772   (sb!kernel:make-lisp-obj (+ *address-of-nil-object* byte-offset)))
1773
1774 ;;; Return two values; the Lisp object located at BYTE-OFFSET in the
1775 ;;; constant area of the code-object in the current segment and T, or
1776 ;;; NIL and NIL if there is no code-object in the current segment.
1777 (defun get-code-constant (byte-offset dstate)
1778   #!+sb-doc
1779   (declare (type offset byte-offset)
1780            (type disassem-state dstate))
1781   (let ((code (seg-code (dstate-segment dstate))))
1782     (if code
1783         (values
1784          (sb!kernel:code-header-ref code
1785                                     (ash (+ byte-offset
1786                                             sb!vm:other-pointer-lowtag)
1787                                          (- sb!vm:word-shift)))
1788          t)
1789         (values nil nil))))
1790
1791 (defun get-code-constant-absolute (addr dstate)
1792   (declare (type address addr))
1793   (declare (type disassem-state dstate))
1794   (let ((code (seg-code (dstate-segment dstate))))
1795     (if (null code)
1796       (return-from get-code-constant-absolute (values nil nil)))
1797     (let ((code-size (ash (sb!kernel:get-header-data code) sb!vm:word-shift)))
1798       (sb!sys:without-gcing
1799        (let ((code-addr (- (sb!kernel:get-lisp-obj-address code)
1800                            sb!vm:other-pointer-lowtag)))
1801          (if (or (< addr code-addr) (>= addr (+ code-addr code-size)))
1802            (values nil nil)
1803            (values (sb!kernel:code-header-ref
1804                     code
1805                     (ash (- addr code-addr) (- sb!vm:word-shift)))
1806                    t)))))))
1807
1808 (defvar *assembler-routines-by-addr* nil)
1809
1810 (defvar *foreign-symbols-by-addr* nil)
1811
1812 ;;; Build an address-name hash-table from the name-address hash
1813 (defun invert-address-hash (htable &optional (addr-hash (make-hash-table)))
1814   (maphash (lambda (name address)
1815              (setf (gethash address addr-hash) name))
1816            htable)
1817   addr-hash)
1818
1819 ;;; Return the name of the primitive Lisp assembler routine or foreign
1820 ;;; symbol located at ADDRESS, or NIL if there isn't one.
1821 (defun find-assembler-routine (address)
1822   (declare (type address address))
1823   (when (null *assembler-routines-by-addr*)
1824     (setf *assembler-routines-by-addr*
1825           (invert-address-hash sb!fasl:*assembler-routines*))
1826     (setf *assembler-routines-by-addr*
1827           (invert-address-hash sb!fasl:*static-foreign-symbols*
1828                                *assembler-routines-by-addr*)))
1829   (gethash address *assembler-routines-by-addr*))
1830 \f
1831 ;;;; some handy function for machine-dependent code to use...
1832
1833 #!-sb-fluid (declaim (maybe-inline sap-ref-int read-suffix))
1834
1835 (defun sap-ref-int (sap offset length byte-order)
1836   (declare (type sb!sys:system-area-pointer sap)
1837            (type (unsigned-byte 16) offset)
1838            (type (member 1 2 4) length)
1839            (type (member :little-endian :big-endian) byte-order)
1840            (optimize (speed 3) (safety 0)))
1841   (ecase length
1842     (1 (sb!sys:sap-ref-8 sap offset))
1843     (2 (if (eq byte-order :big-endian)
1844            (+ (ash (sb!sys:sap-ref-8 sap offset) 8)
1845               (sb!sys:sap-ref-8 sap (+ offset 1)))
1846            (+ (ash (sb!sys:sap-ref-8 sap (+ offset 1)) 8)
1847               (sb!sys:sap-ref-8 sap offset))))
1848     (4 (if (eq byte-order :big-endian)
1849            (+ (ash (sb!sys:sap-ref-8 sap offset) 24)
1850               (ash (sb!sys:sap-ref-8 sap (+ 1 offset)) 16)
1851               (ash (sb!sys:sap-ref-8 sap (+ 2 offset)) 8)
1852               (sb!sys:sap-ref-8 sap (+ 3 offset)))
1853            (+ (sb!sys:sap-ref-8 sap offset)
1854               (ash (sb!sys:sap-ref-8 sap (+ 1 offset)) 8)
1855               (ash (sb!sys:sap-ref-8 sap (+ 2 offset)) 16)
1856               (ash (sb!sys:sap-ref-8 sap (+ 3 offset)) 24))))))
1857
1858 (defun read-suffix (length dstate)
1859   (declare (type (member 8 16 32) length)
1860            (type disassem-state dstate)
1861            (optimize (speed 3) (safety 0)))
1862   (let ((length (ecase length (8 1) (16 2) (32 4))))
1863     (declare (type (unsigned-byte 3) length))
1864     (prog1
1865       (sap-ref-int (dstate-segment-sap dstate)
1866                    (dstate-next-offs dstate)
1867                    length
1868                    (dstate-byte-order dstate))
1869       (incf (dstate-next-offs dstate) length))))
1870 \f
1871 ;;;; optional routines to make notes about code
1872
1873 ;;; Store NOTE (which can be either a string or a function with a
1874 ;;; single stream argument) to be printed as an end-of-line comment
1875 ;;; after the current instruction is disassembled.
1876 (defun note (note dstate)
1877   (declare (type (or string function) note)
1878            (type disassem-state dstate))
1879   (push note (dstate-notes dstate)))
1880
1881 (defun prin1-short (thing stream)
1882   (with-print-restrictions
1883     (prin1 thing stream)))
1884
1885 (defun prin1-quoted-short (thing stream)
1886   (if (self-evaluating-p thing)
1887       (prin1-short thing stream)
1888       (prin1-short `',thing stream)))
1889
1890 ;;; Store a note about the lisp constant located BYTE-OFFSET bytes
1891 ;;; from the current code-component, to be printed as an end-of-line
1892 ;;; comment after the current instruction is disassembled.
1893 (defun note-code-constant (byte-offset dstate)
1894   (declare (type offset byte-offset)
1895            (type disassem-state dstate))
1896   (multiple-value-bind (const valid)
1897       (get-code-constant byte-offset dstate)
1898     (when valid
1899       (note (lambda (stream)
1900               (prin1-quoted-short const stream))
1901             dstate))
1902     const))
1903
1904 ;;; Store a note about the lisp constant located at ADDR in the
1905 ;;; current code-component, to be printed as an end-of-line comment
1906 ;;; after the current instruction is disassembled.
1907 (defun note-code-constant-absolute (addr dstate)
1908   (declare (type address addr)
1909            (type disassem-state dstate))
1910   (multiple-value-bind (const valid)
1911       (get-code-constant-absolute addr dstate)
1912     (when valid
1913       (note (lambda (stream)
1914               (prin1-quoted-short const stream))
1915             dstate))
1916     (values const valid)))
1917
1918 ;;; If the memory address located NIL-BYTE-OFFSET bytes from the
1919 ;;; constant NIL is a valid slot in a symbol, store a note describing
1920 ;;; which symbol and slot, to be printed as an end-of-line comment
1921 ;;; after the current instruction is disassembled. Returns non-NIL iff
1922 ;;; a note was recorded.
1923 (defun maybe-note-nil-indexed-symbol-slot-ref (nil-byte-offset dstate)
1924   (declare (type offset nil-byte-offset)
1925            (type disassem-state dstate))
1926   (multiple-value-bind (symbol access-fun)
1927       (grok-nil-indexed-symbol-slot-ref nil-byte-offset)
1928     (when access-fun
1929       (note (lambda (stream)
1930               (prin1 (if (eq access-fun 'symbol-value)
1931                          symbol
1932                          `(,access-fun ',symbol))
1933                      stream))
1934             dstate))
1935     access-fun))
1936
1937 ;;; If the memory address located NIL-BYTE-OFFSET bytes from the
1938 ;;; constant NIL is a valid lisp object, store a note describing which
1939 ;;; symbol and slot, to be printed as an end-of-line comment after the
1940 ;;; current instruction is disassembled. Returns non-NIL iff a note
1941 ;;; was recorded.
1942 (defun maybe-note-nil-indexed-object (nil-byte-offset dstate)
1943   (declare (type offset nil-byte-offset)
1944            (type disassem-state dstate))
1945   (let ((obj (get-nil-indexed-object nil-byte-offset)))
1946     (note (lambda (stream)
1947             (prin1-quoted-short obj stream))
1948           dstate)
1949     t))
1950
1951 ;;; If ADDRESS is the address of a primitive assembler routine or
1952 ;;; foreign symbol, store a note describing which one, to be printed
1953 ;;; as an end-of-line comment after the current instruction is
1954 ;;; disassembled. Returns non-NIL iff a note was recorded. If
1955 ;;; NOTE-ADDRESS-P is non-NIL, a note of the address is also made.
1956 (defun maybe-note-assembler-routine (address note-address-p dstate)
1957   (declare (type disassem-state dstate))
1958   (unless (typep address 'address)
1959     (return-from maybe-note-assembler-routine nil))
1960   (let ((name (find-assembler-routine address)))
1961     (unless (null name)
1962       (note (lambda (stream)
1963               (if note-address-p
1964                   (format stream "#x~8,'0x: ~a" address name)
1965                   (princ name stream)))
1966             dstate))
1967     name))
1968
1969 ;;; If there's a valid mapping from OFFSET in the storage class
1970 ;;; SC-NAME to a source variable, make a note of the source-variable
1971 ;;; name, to be printed as an end-of-line comment after the current
1972 ;;; instruction is disassembled. Returns non-NIL iff a note was
1973 ;;; recorded.
1974 (defun maybe-note-single-storage-ref (offset sc-name dstate)
1975   (declare (type offset offset)
1976            (type symbol sc-name)
1977            (type disassem-state dstate))
1978   (let ((storage-location
1979          (find-valid-storage-location offset sc-name dstate)))
1980     (when storage-location
1981       (note (lambda (stream)
1982               (princ (sb!di:debug-var-symbol
1983                       (aref (storage-info-debug-vars
1984                              (seg-storage-info (dstate-segment dstate)))
1985                             storage-location))
1986                      stream))
1987             dstate)
1988       t)))
1989
1990 ;;; If there's a valid mapping from OFFSET in the storage-base called
1991 ;;; SB-NAME to a source variable, make a note equating ASSOC-WITH with
1992 ;;; the source-variable name, to be printed as an end-of-line comment
1993 ;;; after the current instruction is disassembled. Returns non-NIL iff
1994 ;;; a note was recorded.
1995 (defun maybe-note-associated-storage-ref (offset sb-name assoc-with dstate)
1996   (declare (type offset offset)
1997            (type symbol sb-name)
1998            (type (or symbol string) assoc-with)
1999            (type disassem-state dstate))
2000   (let ((storage-location
2001          (find-valid-storage-location offset sb-name dstate)))
2002     (when storage-location
2003       (note (lambda (stream)
2004               (format stream "~A = ~S"
2005                       assoc-with
2006                       (sb!di:debug-var-symbol
2007                        (aref (dstate-debug-vars dstate)
2008                              storage-location))
2009                       stream))
2010             dstate)
2011       t)))
2012 \f
2013 (defun get-internal-error-name (errnum)
2014   (car (svref sb!c:*backend-internal-errors* errnum)))
2015
2016 (defun get-sc-name (sc-offs)
2017   (sb!c::location-print-name
2018    ;; FIXME: This seems like an awful lot of computation just to get a name.
2019    ;; Couldn't we just use lookup in *BACKEND-SC-NAMES*, without having to cons
2020    ;; up a new object?
2021    (sb!c:make-random-tn :kind :normal
2022                         :sc (svref sb!c:*backend-sc-numbers*
2023                                    (sb!c:sc-offset-scn sc-offs))
2024                         :offset (sb!c:sc-offset-offset sc-offs))))
2025
2026 ;;; When called from an error break instruction's :DISASSEM-CONTROL (or
2027 ;;; :DISASSEM-PRINTER) function, will correctly deal with printing the
2028 ;;; arguments to the break.
2029 ;;;
2030 ;;; ERROR-PARSE-FUN should be a function that accepts:
2031 ;;;   1) a SYSTEM-AREA-POINTER
2032 ;;;   2) a BYTE-OFFSET from the SAP to begin at
2033 ;;;   3) optionally, LENGTH-ONLY, which if non-NIL, means to only return
2034 ;;;      the byte length of the arguments (to avoid unnecessary consing)
2035 ;;; It should read information from the SAP starting at BYTE-OFFSET, and
2036 ;;; return four values:
2037 ;;;   1) the error number
2038 ;;;   2) the total length, in bytes, of the information
2039 ;;;   3) a list of SC-OFFSETs of the locations of the error parameters
2040 ;;;   4) a list of the length (as read from the SAP), in bytes, of each
2041 ;;;      of the return values.
2042 (defun handle-break-args (error-parse-fun stream dstate)
2043   (declare (type function error-parse-fun)
2044            (type (or null stream) stream)
2045            (type disassem-state dstate))
2046   (multiple-value-bind (errnum adjust sc-offsets lengths)
2047       (funcall error-parse-fun
2048                (dstate-segment-sap dstate)
2049                (dstate-next-offs dstate)
2050                (null stream))
2051     (when stream
2052       (setf (dstate-cur-offs dstate)
2053             (dstate-next-offs dstate))
2054       (flet ((emit-err-arg (note)
2055                (let ((num (pop lengths)))
2056                  (print-notes-and-newline stream dstate)
2057                  (print-current-address stream dstate)
2058                  (print-bytes num stream dstate)
2059                  (incf (dstate-cur-offs dstate) num)
2060                  (when note
2061                    (note note dstate)))))
2062         (emit-err-arg nil)
2063         (emit-err-arg (symbol-name (get-internal-error-name errnum)))
2064         (dolist (sc-offs sc-offsets)
2065           (emit-err-arg (get-sc-name sc-offs)))))
2066     (incf (dstate-next-offs dstate)
2067           adjust)))