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