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