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