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