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