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