Nearly eliminate bignum consing in the x86-64 disassembler.
[sbcl.git] / src / compiler / disassem.lisp
blobe71064e537c9dd1e975ede77e05a79eb05d1e24e
1 ;;;; machine-independent disassembler
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.
12 (in-package "SB!DISASSEM")
14 ;;; types and defaults
16 (defconstant label-column-width 7)
18 (deftype text-width () '(integer 0 1000))
19 (deftype alignment () '(integer 0 64))
20 (deftype offset () '(signed-byte 24))
21 (deftype address () '(unsigned-byte #.sb!vm:n-word-bits))
22 (deftype disassem-length () '(unsigned-byte 24))
23 (deftype column () '(integer 0 1000))
25 (defconstant max-filtered-value-index 32)
26 (deftype filtered-value-index ()
27 `(integer 0 (,max-filtered-value-index)))
28 (deftype filtered-value-vector ()
29 `(simple-array t (,max-filtered-value-index)))
31 ;;;; disassembly parameters
33 ;; With a few tweaks, you can use a running SBCL as a cross-assembler
34 ;; and disassembler for other supported backends,
35 ;; if that backend has been converted to use a distinct ASM package.
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defparameter sb!assem::*backend-instruction-set-package*
38 (find-package #.(sb-cold::backend-asm-package-name))))
40 (defvar *disassem-inst-space* nil)
42 ;;; minimum alignment of instructions, in bytes
43 (defvar *disassem-inst-alignment-bytes* sb!vm:n-word-bytes)
44 (declaim (type alignment *disassem-inst-alignment-bytes*))
46 ;; How many columns of output to allow for the address preceding each line.
47 ;; If NIL, use the minimum possible width for the disassembly range.
48 ;; If 0, do not print addresses.
49 (defvar *disassem-location-column-width* nil)
50 (declaim (type (or null text-width) *disassem-location-column-width*))
52 ;;; the width of the column in which instruction-names are printed. A
53 ;;; value of zero gives the effect of not aligning the arguments at
54 ;;; all.
55 (defvar *disassem-opcode-column-width* 0)
56 (declaim (type text-width *disassem-opcode-column-width*))
58 ;;; the width of the column in which instruction-bytes are printed. A
59 ;;; value of zero disables the printing of instruction bytes.
60 (defvar *disassem-inst-column-width* 16
61 #!+sb-doc
62 "The width of instruction bytes.")
63 (declaim (type text-width *disassem-inst-column-width*))
65 (defvar *disassem-note-column* (+ 45 *disassem-inst-column-width*)
66 #!+sb-doc
67 "The column in which end-of-line comments for notes are started.")
69 ;;;; A DCHUNK contains the bits we look at to decode an
70 ;;;; instruction.
71 ;;;; I tried to keep this abstract so that if using integers > the machine
72 ;;;; word size conses too much, it can be changed to use bit-vectors or
73 ;;;; something.
74 ;;;;
75 ;;;; KLUDGE: It's not clear that using bit-vectors would be any more efficient.
76 ;;;; Perhaps the abstraction could go away. -- WHN 19991124
78 #!-sb-fluid
79 (declaim (inline dchunk-or dchunk-and dchunk-clear dchunk-not
80 dchunk-make-mask dchunk-make-field
81 sap-ref-dchunk
82 dchunk-extract
83 dchunk=
84 dchunk-count-bits))
86 ;;; For variable-length instruction sets, such as x86, it is better to
87 ;;; define the dchunk size to be the smallest number of bits necessary
88 ;;; and sufficient to decode any instruction format, if that quantity
89 ;;; of bits is small enough to avoid bignum consing.
90 ;;; Ideally this constant would go in the 'insts' file for the architecture,
91 ;;; but there's really no easy way to do that at present.
92 (defconstant dchunk-bits
93 #!+x86-64 56
94 #!-x86-64 sb!vm:n-word-bits)
96 (deftype dchunk ()
97 `(unsigned-byte ,dchunk-bits))
98 (deftype dchunk-index ()
99 `(integer 0 ,dchunk-bits))
101 (defconstant dchunk-zero 0)
102 (defconstant dchunk-one (ldb (byte dchunk-bits 0) -1))
104 (defun dchunk-extract (chunk byte-spec)
105 (declare (type dchunk chunk))
106 (the dchunk (ldb byte-spec (the dchunk chunk))))
108 (defmacro dchunk-copy (x)
109 `(the dchunk ,x))
111 (defun dchunk-or (to from)
112 (declare (type dchunk to from))
113 (the dchunk (logior to from)))
114 (defun dchunk-and (to from)
115 (declare (type dchunk to from))
116 (the dchunk (logand to from)))
117 (defun dchunk-clear (to from)
118 (declare (type dchunk to from))
119 (the dchunk (logandc2 to from)))
120 (defun dchunk-not (from)
121 (declare (type dchunk from))
122 (the dchunk (logand dchunk-one (lognot from))))
124 (defmacro dchunk-andf (to from)
125 `(setf ,to (dchunk-and ,to ,from)))
126 (defmacro dchunk-orf (to from)
127 `(setf ,to (dchunk-or ,to ,from)))
128 (defmacro dchunk-clearf (to from)
129 `(setf ,to (dchunk-clear ,to ,from)))
131 (defun dchunk-make-mask (pos)
132 (the dchunk (mask-field pos -1)))
133 (defun dchunk-make-field (pos value)
134 (the dchunk (dpb value pos 0)))
136 (defmacro make-dchunk (value)
137 `(the dchunk ,value))
139 #-sb-xc-host ;; FIXME: function belongs in 'target-disassem'
140 (defun sap-ref-dchunk (sap byte-offset byte-order)
141 (declare (type sb!sys:system-area-pointer sap)
142 (type offset byte-offset)
143 (muffle-conditions compiler-note) ; returns possible bignum
144 ;; Not all backends can actually disassemble for either byte order.
145 (ignorable byte-order)
146 (optimize (speed 3) (safety 0)))
147 #!+x86-64
148 (logand (sb!sys:sap-ref-word sap byte-offset) dchunk-one)
149 #!-x86-64
150 (the dchunk
151 (ecase dchunk-bits
152 (32 (if (eq byte-order :big-endian)
153 (+ (ash (sb!sys:sap-ref-8 sap byte-offset) 24)
154 (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 16)
155 (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 8)
156 (sb!sys:sap-ref-8 sap (+ 3 byte-offset)))
157 (+ (sb!sys:sap-ref-8 sap byte-offset)
158 (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 8)
159 (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 16)
160 (ash (sb!sys:sap-ref-8 sap (+ 3 byte-offset)) 24))))
161 (64 (if (eq byte-order :big-endian)
162 (+ (ash (sb!sys:sap-ref-8 sap byte-offset) 56)
163 (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 48)
164 (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 40)
165 (ash (sb!sys:sap-ref-8 sap (+ 3 byte-offset)) 32)
166 (ash (sb!sys:sap-ref-8 sap (+ 4 byte-offset)) 24)
167 (ash (sb!sys:sap-ref-8 sap (+ 5 byte-offset)) 16)
168 (ash (sb!sys:sap-ref-8 sap (+ 6 byte-offset)) 8)
169 (sb!sys:sap-ref-8 sap (+ 7 byte-offset)))
170 (+ (sb!sys:sap-ref-8 sap byte-offset)
171 (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 8)
172 (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 16)
173 (ash (sb!sys:sap-ref-8 sap (+ 3 byte-offset)) 24)
174 (ash (sb!sys:sap-ref-8 sap (+ 4 byte-offset)) 32)
175 (ash (sb!sys:sap-ref-8 sap (+ 5 byte-offset)) 40)
176 (ash (sb!sys:sap-ref-8 sap (+ 6 byte-offset)) 48)
177 (ash (sb!sys:sap-ref-8 sap (+ 7 byte-offset)) 56)))))))
179 (defun dchunk-corrected-extract (from pos unit-bits byte-order)
180 (declare (type dchunk from))
181 (if (eq byte-order :big-endian)
182 (ldb (byte (byte-size pos)
183 (+ (byte-position pos) (- dchunk-bits unit-bits)))
184 (the dchunk from))
185 (ldb pos (the dchunk from))))
187 (defmacro dchunk-insertf (place pos value)
188 `(setf ,place (the dchunk (dpb ,value ,pos (the dchunk,place)))))
190 (defun dchunk= (x y)
191 (declare (type dchunk x y))
192 (= x y))
193 (defmacro dchunk-zerop (x)
194 `(dchunk= ,x dchunk-zero))
196 (defun dchunk-strict-superset-p (sup sub)
197 (and (zerop (logandc2 sub sup))
198 (not (zerop (logandc2 sup sub)))))
200 (defun dchunk-count-bits (x)
201 (declare (type dchunk x))
202 (logcount x))
204 (defstruct (instruction (:conc-name inst-)
205 (:constructor
206 make-instruction (name format-name print-name
207 length mask id printer labeller
208 prefilters control))
209 (:copier nil))
210 (name nil :type (or symbol string) :read-only t)
211 (format-name nil :type (or symbol string) :read-only t)
213 (mask dchunk-zero :type dchunk :read-only t) ; bits in the inst that are constant
214 (id dchunk-zero :type dchunk :read-only t) ; value of those constant bits
216 (length 0 :type disassem-length :read-only t) ; in bytes
218 (print-name nil :type symbol :read-only t)
220 ;; disassembly "functions"
221 (prefilters nil :type list :read-only t)
222 (labeller nil :type (or list vector) :read-only t)
223 (printer nil :type (or null function) :read-only t)
224 (control nil :type (or null function) :read-only t)
226 ;; instructions that are the same as this instruction but with more
227 ;; constraints
228 (specializers nil :type list))
229 (defmethod print-object ((inst instruction) stream)
230 (print-unreadable-object (inst stream :type t :identity t)
231 (format stream "~A(~A)" (inst-name inst) (inst-format-name inst))))
233 ;;;; an instruction space holds all known machine instructions in a
234 ;;;; form that can be easily searched
236 (defstruct (inst-space (:conc-name ispace-)
237 (:copier nil))
238 (valid-mask dchunk-zero :type dchunk) ; applies to *children*
239 (choices nil :type list))
240 (defmethod print-object ((ispace inst-space) stream)
241 (print-unreadable-object (ispace stream :type t :identity t)))
243 ;;; now that we've defined the structure, we can declaim the type of
244 ;;; the variable:
245 (declaim (type (or null inst-space) *disassem-inst-space*))
247 (defstruct (inst-space-choice (:conc-name ischoice-)
248 (:copier nil))
249 (common-id dchunk-zero :type dchunk) ; applies to *parent's* mask
250 (subspace (missing-arg) :type (or inst-space instruction)))
252 (defstruct (arg (:constructor %make-arg (name))
253 (:copier nil)
254 (:predicate nil))
255 (name nil :type symbol)
256 (fields nil :type list)
258 (value nil :type (or list integer))
259 (sign-extend-p nil :type boolean)
261 ;; functions to use
262 (printer nil :type (or null function vector))
263 (prefilter nil :type (or null function))
264 (use-label nil :type (or boolean function)))
266 (defstruct (instruction-format (:conc-name format-)
267 (:constructor make-inst-format
268 (name length default-printer args))
269 (:copier nil))
270 (name nil)
271 (args nil :type list)
273 (length 0 :type disassem-length) ; in bytes
275 (default-printer nil :type list))
277 ;;; A FUNSTATE holds the state of any arguments used in a disassembly
278 ;;; function. It is a 2-level alist. The outer list maps each ARG to
279 ;;; a list of styles in which that arg can be rendered.
280 ;;; Each rendering is named by a keyword (the key to the inner alist),
281 ;;; and is represented as a list of temp vars and values for them.
282 (defun make-funstate (args) (mapcar #'list args))
284 (defun arg-position (arg funstate)
285 ;;; The THE form is to assert that ARG is found.
286 (the filtered-value-index (position arg funstate :key #'car)))
288 (defun arg-or-lose (name funstate)
289 (or (car (assoc name funstate :key #'arg-name :test #'eq))
290 (pd-error "unknown argument ~S" name)))
292 ;;; machinery to provide more meaningful error messages during compilation
293 (defvar *current-instruction-flavor*)
294 (defun pd-error (fmt &rest args)
295 (if (boundp '*current-instruction-flavor*)
296 (error "~{A printer ~D~}: ~?" *current-instruction-flavor* fmt args)
297 (apply #'error fmt args)))
299 (defun format-or-lose (name)
300 (or (get name 'inst-format)
301 (pd-error "unknown instruction format ~S" name)))
303 ;;; Return a modified copy of ARG that has property values changed
304 ;;; depending on whether it is being used at compile-time or load-time.
305 ;;; This is to avoid evaluating #'FOO references at compile-time
306 ;;; while allowing compile-time manipulation of byte specifiers.
307 (defun massage-arg (spec when)
308 (ecase when
309 (:compile
310 ;; At compile-time we get a restricted view of the DEFINE-ARG-TYPE args,
311 ;; just enough to macroexpand :READER definitions. :TYPE and ::SIGN-EXTEND
312 ;; are as specified, but :PREFILTER, :LABELLER, and :PRINTER are not
313 ;; compile-time evaluated.
314 (loop for (indicator val) on (cdr spec) by #'cddr
315 nconc (case indicator
316 (:sign-extend ; Only a literal T or NIL is allowed
317 (list indicator (the boolean val)))
318 (:prefilter
319 ;; #'ERROR is a placeholder for any compile-time non-nil
320 ;; value. If nil, it must be literally nil, not 'NIL.
321 (list indicator (if val #'error nil)))
322 ((:field :fields :type)
323 (list indicator val)))))
324 (:eval
325 (loop for (indicator raw-val) on (cdr spec) by #'cddr
326 ;; Use NAMED-LAMBDAs to enhance debuggability,
327 for val = (if (typep raw-val '(cons (eql lambda)))
328 `(named-lambda ,(format nil "~A.~A" (car spec) indicator)
329 ,@(cdr raw-val))
330 raw-val)
331 nconc (case indicator
332 (:reader nil) ; drop it
333 (:prefilter ; Enforce compile-time-determined not-nullness.
334 (list indicator (if val `(the (not null) ,val) nil)))
335 (t (list indicator val)))))))
337 (defmacro define-instruction-format ((format-name length-in-bits
338 &key default-printer include)
339 &rest arg-specs)
340 #+sb-xc-host (declare (ignore default-printer))
341 #!+sb-doc
342 "DEFINE-INSTRUCTION-FORMAT (Name Length {Format-Key Value}*) Arg-Def*
343 Define an instruction format NAME for the disassembler's use. LENGTH is
344 the length of the format in bits.
345 Possible FORMAT-KEYs:
347 :INCLUDE other-format-name
348 Inherit all arguments and properties of the given format. Any
349 arguments defined in the current format definition will either modify
350 the copy of an existing argument (keeping in the same order with
351 respect to when prefilters are called), if it has the same name as
352 one, or be added to the end.
353 :DEFAULT-PRINTER printer-list
354 Use the given PRINTER-LIST as a format to print any instructions of
355 this format when they don't specify something else.
357 Each ARG-DEF defines one argument in the format, and is of the form
358 (Arg-Name {Arg-Key Value}*)
360 Possible ARG-KEYs (the values are evaluated unless otherwise specified):
362 :FIELDS byte-spec-list
363 The argument takes values from these fields in the instruction. If
364 the list is of length one, then the corresponding value is supplied by
365 itself; otherwise it is a list of the values. The list may be NIL.
366 :FIELD byte-spec
367 The same as :FIELDS (list byte-spec).
369 :VALUE value
370 If the argument only has one field, this is the value it should have,
371 otherwise it's a list of the values of the individual fields. This can
372 be overridden in an instruction-definition or a format definition
373 including this one by specifying another, or NIL to indicate that it's
374 variable.
376 :SIGN-EXTEND boolean
377 If non-NIL, the raw value of this argument is sign-extended,
378 immediately after being extracted from the instruction (before any
379 prefilters are run, for instance). If the argument has multiple
380 fields, they are all sign-extended.
382 :TYPE arg-type-name
383 Inherit any properties of the given argument type.
385 :PREFILTER function
386 A function which is called (along with all other prefilters, in the
387 order that their arguments appear in the instruction-format) before
388 any printing is done, to filter the raw value. Any uses of READ-SUFFIX
389 must be done inside a prefilter.
391 :PRINTER function-string-or-vector
392 A function, string, or vector which is used to print this argument.
394 :USE-LABEL
395 If non-NIL, the value of this argument is used as an address, and if
396 that address occurs inside the disassembled code, it is replaced by a
397 label. If this is a function, it is called to filter the value."
398 (aver (<= length-in-bits dchunk-bits))
399 `(progn
400 (eval-when (:compile-toplevel)
401 (%def-inst-format
402 ',format-name ',include ,length-in-bits nil
403 ,@(mapcar (lambda (arg) `(list ',(car arg) ,@(massage-arg arg :compile)))
404 arg-specs)))
405 ,@(mapcan
406 (lambda (arg-spec)
407 (awhen (getf (cdr arg-spec) :reader)
408 `((defun ,it (dchunk dstate)
409 (declare (ignorable dchunk dstate))
410 (flet ((local-filtered-value (offset)
411 (declare (type filtered-value-index offset))
412 (aref (dstate-filtered-values dstate) offset))
413 (local-extract (bytespec)
414 (dchunk-extract dchunk bytespec)))
415 (declare (ignorable #'local-filtered-value #'local-extract)
416 (inline local-filtered-value local-extract))
417 ;; Delay ARG-FORM-VALUE call until after compile-time-too
418 ;; processing of !%DEF-INSTRUCTION-FORMAT has happened.
419 (macrolet
420 ((reader ()
421 (let* ((format-args
422 (format-args (format-or-lose ',format-name)))
423 (arg (find ',(car arg-spec) format-args
424 :key #'arg-name))
425 (funstate (make-funstate format-args))
426 (*!temp-var-counter* 0)
427 (expr (arg-value-form arg funstate :numeric)))
428 `(let* ,(make-arg-temp-bindings funstate) ,expr))))
429 (reader)))))))
430 arg-specs)
431 #-sb-xc-host ; Host doesn't need the real definition.
432 (%def-inst-format
433 ',format-name ',include ,length-in-bits ,default-printer
434 ,@(mapcar (lambda (arg) `(list ',(car arg) ,@(massage-arg arg :eval)))
435 arg-specs))))
437 (defun %def-inst-format (name inherit length printer &rest arg-specs)
438 (let ((args (if inherit (copy-list (format-args (format-or-lose inherit)))))
439 (seen))
440 (dolist (arg-spec arg-specs)
441 (let* ((arg-name (car arg-spec))
442 (properties (cdr arg-spec))
443 (cell (member arg-name args :key #'arg-name)))
444 (aver (not (memq arg-name seen)))
445 (push arg-name seen)
446 (cond ((not cell)
447 (setq args (nconc args (list (apply #'modify-arg (%make-arg arg-name)
448 length properties)))))
449 (properties
450 (rplaca cell (apply #'modify-arg (copy-structure (car cell))
451 length properties))))))
452 (setf (get name 'inst-format)
453 (make-inst-format name (bits-to-bytes length) printer args))))
455 (defun modify-arg (arg format-length
456 &key (value nil value-p)
457 (type nil type-p)
458 (prefilter nil prefilter-p)
459 (printer nil printer-p)
460 (sign-extend nil sign-extend-p)
461 (use-label nil use-label-p)
462 (field nil field-p)
463 (fields nil fields-p))
464 (when field-p
465 (if fields-p
466 (error ":FIELD and :FIELDS are mutually exclusive")
467 (setf fields (list field) fields-p t)))
468 (when type-p
469 (let ((type-arg (or (get type 'arg-type)
470 (pd-error "unknown argument type: ~S" type))))
471 (setf (arg-printer arg) (arg-printer type-arg))
472 (setf (arg-prefilter arg) (arg-prefilter type-arg))
473 (setf (arg-sign-extend-p arg) (arg-sign-extend-p type-arg))
474 (setf (arg-use-label arg) (arg-use-label type-arg))))
475 (when value-p
476 (setf (arg-value arg) value))
477 (when prefilter-p
478 (setf (arg-prefilter arg) prefilter))
479 (when sign-extend-p
480 (setf (arg-sign-extend-p arg) sign-extend))
481 (when printer-p
482 (setf (arg-printer arg) printer))
483 (when use-label-p
484 (setf (arg-use-label arg) use-label))
485 (when fields-p
486 (setf (arg-fields arg)
487 (mapcar (lambda (bytespec)
488 (when (> (+ (byte-position bytespec) (byte-size bytespec))
489 format-length)
490 (error "~@<in arg ~S: ~3I~:_~
491 The field ~S doesn't fit in an ~
492 instruction-format ~W bits wide.~:>"
493 (arg-name arg) bytespec format-length))
494 (correct-dchunk-bytespec-for-endianness
495 bytespec format-length sb!c:*backend-byte-order*))
496 fields)))
497 arg)
499 (defun arg-value-form (arg funstate
500 &optional
501 (rendering :final)
502 (allow-multiple-p (neq rendering :numeric)))
503 (let ((forms (gen-arg-forms arg rendering funstate)))
504 (when (and (not allow-multiple-p)
505 (listp forms)
506 (/= (length forms) 1))
507 (pd-error "~S must not have multiple values." arg))
508 (maybe-listify forms)))
510 (defun correct-dchunk-bytespec-for-endianness (bs unit-bits byte-order)
511 (if (eq byte-order :big-endian)
512 (byte (byte-size bs) (+ (byte-position bs) (- dchunk-bits unit-bits)))
513 bs))
515 (defun make-arg-temp-bindings (funstate)
516 (let ((bindings nil))
517 ;; Prefilters have to be called in the correct order, so reverse FUNSTATE
518 ;; because we're using PUSH in the inner loop.
519 (dolist (arg-cell (reverse funstate) bindings)
520 ;; These sublists are "backwards", so PUSH ends up being correct.
521 (dolist (rendering (cdr arg-cell))
522 (let* ((binding (cdr rendering))
523 (vars (car binding))
524 (vals (cdr binding)))
525 (if (listp vars)
526 (mapc (lambda (var val) (push `(,var ,val) bindings)) vars vals)
527 (push `(,vars ,vals) bindings)))))))
529 ;;; Return the form(s) that should be evaluated to render ARG in the chosen
530 ;;; RENDERING style, which is one of :RAW, :SIGN-EXTENDED,
531 ;;; :FILTERED, :NUMERIC, and :FINAL. Each rendering depends on the preceding
532 ;;; one, so asking for :FINAL will implicitly compute all renderings.
533 (defvar *!temp-var-counter*)
534 (defun gen-arg-forms (arg rendering funstate)
535 (labels ((tempvars (n)
536 (if (plusp n)
537 (cons (package-symbolicate
538 (load-time-value (find-package "SB!DISASSEM"))
539 ".T" (write-to-string (incf *!temp-var-counter*)))
540 (tempvars (1- n))))))
541 (let* ((arg-cell (assq arg funstate))
542 (rendering-temps (cdr (assq rendering (cdr arg-cell))))
543 (vars (car rendering-temps))
544 (forms (cdr rendering-temps)))
545 (unless forms
546 (multiple-value-bind (new-forms single-value-p)
547 (%gen-arg-forms arg rendering funstate)
548 (setq forms new-forms
549 vars (cond ((or single-value-p (atom forms))
550 (if (symbolp forms) vars (car (tempvars 1))))
551 ((every #'symbolp forms)
552 ;; just use the same as the forms
553 nil)
555 (tempvars (length forms)))))
556 (push (list* rendering vars forms) (cdr arg-cell))))
557 (or vars forms))))
559 (defun maybe-listify (forms)
560 (cond ((atom forms)
561 forms)
562 ((/= (length forms) 1)
563 `(list ,@forms))
565 (car forms))))
567 ;;; DEFINE-ARG-TYPE Name {Key Value}*
569 ;;; Define a disassembler argument type NAME (which can then be referenced in
570 ;;; another argument definition using the :TYPE argument). &KEY args are:
572 ;;; :SIGN-EXTEND boolean
573 ;;; If non-NIL, the raw value of this argument is sign-extended.
575 ;;; :TYPE arg-type-name
576 ;;; Inherit any properties of given arg-type.
578 ;;; :PREFILTER function
579 ;;; A function which is called (along with all other prefilters,
580 ;;; in the order that their arguments appear in the instruction-
581 ;;; format) before any printing is done, to filter the raw value.
582 ;;; Any uses of READ-SUFFIX must be done inside a prefilter.
584 ;;; :PRINTER function-string-or-vector
585 ;;; A function, string, or vector which is used to print an argument of
586 ;;; this type.
588 ;;; :USE-LABEL
589 ;;; If non-NIL, the value of an argument of this type is used as
590 ;;; an address, and if that address occurs inside the disassembled
591 ;;; code, it is replaced by a label. If this is a function, it is
592 ;;; called to filter the value.
593 (defmacro define-arg-type (name &rest args
594 &key ((:type inherit))
595 sign-extend prefilter printer use-label)
596 (declare (ignore sign-extend prefilter printer use-label))
597 ;; FIXME: this should be an *unevaluated* macro arg (named :INHERIT)
598 (aver (typep inherit '(or null (cons (eql quote) (cons symbol null)))))
599 (let ((pair (cons name (loop for (ind val) on args by #'cddr
600 unless (eq ind :type)
601 nconc (list ind val)))))
602 `(progn
603 (eval-when (:compile-toplevel)
604 (%def-arg-type ',name ,inherit ,@(massage-arg pair :compile)))
605 #-sb-xc-host ; Host doesn't need the real definition.
606 (%def-arg-type ',name ,inherit ,@(massage-arg pair :eval)))))
608 (defun %def-arg-type (name inherit &rest properties)
609 (setf (get name 'arg-type)
610 (apply 'modify-arg (%make-arg name) nil
611 (nconc (when inherit (list :type inherit)) properties))))
613 (defun %gen-arg-forms (arg rendering funstate)
614 (declare (type arg arg) (type list funstate))
615 (ecase rendering
616 (:raw ; just extract the bits
617 (mapcar (lambda (bytespec)
618 `(the (unsigned-byte ,(byte-size bytespec))
619 (local-extract ',bytespec)))
620 (arg-fields arg)))
621 (:sign-extended ; sign-extend, or not
622 (let ((raw-forms (gen-arg-forms arg :raw funstate)))
623 (if (and (arg-sign-extend-p arg) (listp raw-forms))
624 (mapcar (lambda (form field)
625 `(the (signed-byte ,(byte-size field))
626 (sign-extend ,form ,(byte-size field))))
627 raw-forms
628 (arg-fields arg))
629 raw-forms)))
630 (:filtered ; extract from the prefiltered value vector
631 (let ((pf (arg-prefilter arg)))
632 (if pf
633 (values `(local-filtered-value ,(arg-position arg funstate)) t)
634 (gen-arg-forms arg :sign-extended funstate))))
635 (:numeric ; pass the filtered value to the label adjuster, or not
636 (let ((filtered-forms (gen-arg-forms arg :filtered funstate))
637 (use-label (arg-use-label arg)))
638 ;; use-label = T means that the prefiltered value is already an address,
639 ;; otherwise non-nil means a function to call, and NIL means not a label.
640 ;; So only the middle case needs to call ADJUST-LABEL.
641 (if (and use-label (neq use-label t))
642 `((adjust-label ,(maybe-listify filtered-forms) ,use-label))
643 filtered-forms)))
644 (:final ; if arg is not a label, return numeric value, otherwise a string
645 (let ((numeric-forms (gen-arg-forms arg :numeric funstate)))
646 (if (arg-use-label arg)
647 `((lookup-label ,(maybe-listify numeric-forms)))
648 numeric-forms)))))
650 (defun find-printer-fun (printer-source args cache *current-instruction-flavor*)
651 (let* ((source (preprocess-printer printer-source args))
652 (funstate (make-funstate args))
653 (forms (let ((*!temp-var-counter* 0))
654 (compile-printer-list source funstate)))
655 (bindings (make-arg-temp-bindings funstate))
656 (guts `(let* ,bindings ,@forms))
657 (sub-table (assq :printer cache)))
658 (or (cdr (assoc guts (cdr sub-table) :test #'equal))
659 (let ((template
660 '(lambda (chunk inst stream dstate
661 &aux (chunk (truly-the dchunk chunk))
662 (inst (truly-the instruction inst))
663 (stream (truly-the stream stream))
664 (dstate (truly-the disassem-state dstate)))
665 (macrolet ((local-format-arg (arg fmt)
666 `(funcall (formatter ,fmt) stream ,arg)))
667 (flet ((local-tab-to-arg-column ()
668 (tab (dstate-argument-column dstate) stream))
669 (local-print-name ()
670 (princ (inst-print-name inst) stream))
671 (local-write-char (ch)
672 (write-char ch stream))
673 (local-princ (thing)
674 (princ thing stream))
675 (local-princ16 (thing)
676 (princ16 thing stream))
677 (local-call-arg-printer (arg printer)
678 (funcall printer arg stream dstate))
679 (local-call-global-printer (fun)
680 (funcall fun chunk inst stream dstate))
681 (local-filtered-value (offset)
682 (declare (type filtered-value-index offset))
683 (aref (dstate-filtered-values dstate) offset))
684 (local-extract (bytespec)
685 (dchunk-extract chunk bytespec))
686 (lookup-label (lab)
687 (or (gethash lab (dstate-label-hash dstate))
688 lab))
689 (adjust-label (val adjust-fun)
690 (funcall adjust-fun val dstate)))
691 (declare (ignorable #'local-tab-to-arg-column
692 #'local-print-name
693 #'local-princ #'local-princ16
694 #'local-write-char
695 #'local-call-arg-printer
696 #'local-call-global-printer
697 #'local-extract
698 #'local-filtered-value
699 #'lookup-label #'adjust-label)
700 (inline local-tab-to-arg-column
701 local-princ local-princ16
702 local-call-arg-printer local-call-global-printer
703 local-filtered-value local-extract
704 lookup-label adjust-label))
705 :body)))))
706 (cdar (push (cons guts (compile nil (subst guts :body template)))
707 (cdr sub-table)))))))
709 (defun preprocess-test (subj form args)
710 (multiple-value-bind (subj test)
711 (if (and (consp form) (symbolp (car form)) (not (keywordp (car form))))
712 (values (car form) (cdr form))
713 (values subj form))
714 (let ((key (if (consp test) (car test) test))
715 (body (if (consp test) (cdr test) nil)))
716 (case key
717 (:constant
718 (if (null body)
719 ;; If no supplied constant values, just any constant is ok,
720 ;; just see whether there's some constant value in the arg.
721 (not
722 (null
723 (arg-value
724 (or (find subj args :key #'arg-name)
725 (pd-error "unknown argument ~S" subj)))))
726 ;; Otherwise, defer to run-time.
727 form))
728 ((:or :and :not)
729 (sharing-cons
730 form
731 subj
732 (sharing-cons
733 test
735 (sharing-mapcar
736 (lambda (sub-test)
737 (preprocess-test subj sub-test args))
738 body))))
739 (t form)))))
741 (defun preprocess-conditionals (printer args)
742 (if (atom printer)
743 printer
744 (case (car printer)
745 (:unless
746 (preprocess-conditionals
747 `(:cond ((:not ,(nth 1 printer)) ,@(nthcdr 2 printer)))
748 args))
749 (:when
750 (preprocess-conditionals `(:cond (,(cdr printer))) args))
751 (:if
752 (preprocess-conditionals
753 `(:cond (,(nth 1 printer) ,(nth 2 printer))
754 (t ,(nth 3 printer)))
755 args))
756 (:cond
757 (sharing-cons
758 printer
759 :cond
760 (sharing-mapcar
761 (lambda (clause)
762 (let ((filtered-body
763 (sharing-mapcar
764 (lambda (sub-printer)
765 (preprocess-conditionals sub-printer args))
766 (cdr clause))))
767 (sharing-cons
768 clause
769 (preprocess-test (find-first-field-name filtered-body)
770 (car clause)
771 args)
772 filtered-body)))
773 (cdr printer))))
774 (quote printer)
776 (sharing-mapcar
777 (lambda (sub-printer)
778 (preprocess-conditionals sub-printer args))
779 printer)))))
781 ;;; Return a version of the disassembly-template PRINTER with
782 ;;; compile-time tests (e.g. :constant without a value), and any
783 ;;; :CHOOSE operators resolved properly for the args ARGS.
785 ;;; (:CHOOSE Sub*) simply returns the first Sub in which every field
786 ;;; reference refers to a valid arg.
787 (defun preprocess-printer (printer args)
788 (preprocess-conditionals (preprocess-chooses printer args) args))
790 ;;; Return the first non-keyword symbol in a depth-first search of TREE.
791 (defun find-first-field-name (tree)
792 (cond ((null tree)
793 nil)
794 ((and (symbolp tree) (not (keywordp tree)))
795 tree)
796 ((atom tree)
797 nil)
798 ((eq (car tree) 'quote)
799 nil)
801 (or (find-first-field-name (car tree))
802 (find-first-field-name (cdr tree))))))
804 (defun preprocess-chooses (printer args)
805 (cond ((atom printer)
806 printer)
807 ((eq (car printer) :choose)
808 (pick-printer-choice (cdr printer) args))
810 (sharing-mapcar (lambda (sub) (preprocess-chooses sub args))
811 printer))))
813 ;;;; some simple functions that help avoid consing when we're just
814 ;;;; recursively filtering things that usually don't change
816 (defun sharing-cons (old-cons car cdr)
817 #!+sb-doc
818 "If CAR is eq to the car of OLD-CONS and CDR is eq to the CDR, return
819 OLD-CONS, otherwise return (cons CAR CDR)."
820 (if (and (eq car (car old-cons)) (eq cdr (cdr old-cons)))
821 old-cons
822 (cons car cdr)))
824 (defun sharing-mapcar (fun list)
825 (declare (type function fun))
826 #!+sb-doc
827 "A simple (one list arg) mapcar that avoids consing up a new list
828 as long as the results of calling FUN on the elements of LIST are
829 eq to the original."
830 (and list
831 (sharing-cons list
832 (funcall fun (car list))
833 (sharing-mapcar fun (cdr list)))))
835 (defun all-arg-refs-relevant-p (printer args)
836 (cond ((or (null printer) (keywordp printer) (eq printer t))
838 ((symbolp printer)
839 (find printer args :key #'arg-name))
840 ((listp printer)
841 (every (lambda (x) (all-arg-refs-relevant-p x args))
842 printer))
843 (t t)))
845 (defun pick-printer-choice (choices args)
846 (dolist (choice choices
847 (pd-error "no suitable choice found in ~S" choices))
848 (when (all-arg-refs-relevant-p choice args)
849 (return choice))))
851 (defun compile-printer-list (sources funstate)
852 (when sources
853 (cons (compile-printer-body (car sources) funstate)
854 (compile-printer-list (cdr sources) funstate))))
856 (defun compile-printer-body (source funstate)
857 (cond ((null source)
858 nil)
859 ((eq source :name)
860 `(local-print-name))
861 ((eq source :tab)
862 `(local-tab-to-arg-column))
863 ((keywordp source)
864 (pd-error "unknown printer element: ~S" source))
865 ((symbolp source)
866 (compile-print source funstate))
867 ((atom source)
868 `(local-princ ',source))
869 ((eq (car source) :using)
870 (unless (or (stringp (cadr source))
871 (and (listp (cadr source))
872 (eq (caadr source) 'function)))
873 (pd-error "The first arg to :USING must be a string or #'function."))
874 ;; For (:using #'F) to be stuffed in properly, the printer as expressed
875 ;; in its DSL would have to compile-time expand into a thing that
876 ;; reconstructs it such that #'F forms don't appear inside quoted list
877 ;; structure. Lacking the ability to do that, we treat #'F as a bit of
878 ;; syntax to be evaluated manually.
879 (compile-print (caddr source) funstate
880 (let ((f (cadr source)))
881 (if (typep f '(cons (eql function) (cons symbol null)))
882 (symbol-function (second f))
883 f))))
884 ((eq (car source) :plus-integer)
885 ;; prints the given field proceed with a + or a -
886 (let ((form
887 (arg-value-form (arg-or-lose (cadr source) funstate)
888 funstate
889 :numeric)))
890 `(progn
891 (when (>= ,form 0)
892 (local-write-char #\+))
893 (local-princ ,form))))
894 ((eq (car source) 'quote)
895 `(local-princ ,source))
896 ((eq (car source) 'function)
897 `(local-call-global-printer ,source))
898 ((eq (car source) :cond)
899 `(cond ,@(mapcar (lambda (clause)
900 `(,(compile-test (find-first-field-name
901 (cdr clause))
902 (car clause)
903 funstate)
904 ,@(compile-printer-list (cdr clause)
905 funstate)))
906 (cdr source))))
907 ;; :IF, :UNLESS, and :WHEN are replaced by :COND during preprocessing
909 `(progn ,@(compile-printer-list source funstate)))))
911 (defun compile-print (arg-name funstate &optional printer)
912 (let* ((arg (arg-or-lose arg-name funstate))
913 (printer (or printer (arg-printer arg))))
914 (etypecase printer
915 (string
916 `(local-format-arg ,(arg-value-form arg funstate) ,printer))
917 (vector
918 `(local-princ (aref ,printer ,(arg-value-form arg funstate :numeric))))
919 ((or function (cons (eql function)))
920 `(local-call-arg-printer ,(arg-value-form arg funstate) ,printer))
921 (boolean
922 `(,(if (arg-use-label arg) 'local-princ16 'local-princ)
923 ,(arg-value-form arg funstate))))))
925 (defun compare-fields-form (val-form-1 val-form-2)
926 (flet ((listify-fields (fields)
927 (cond ((symbolp fields) fields)
928 ((every #'constantp fields) `',fields)
929 (t `(list ,@fields)))))
930 (cond ((or (symbolp val-form-1) (symbolp val-form-2))
931 `(equal ,(listify-fields val-form-1)
932 ,(listify-fields val-form-2)))
934 `(and ,@(mapcar (lambda (v1 v2) `(= ,v1 ,v2))
935 val-form-1 val-form-2))))))
937 (defun compile-test (subj test funstate)
938 (when (and (consp test) (symbolp (car test)) (not (keywordp (car test))))
939 (setf subj (car test)
940 test (cdr test)))
941 (let ((key (if (consp test) (car test) test))
942 (body (if (consp test) (cdr test) nil)))
943 (cond ((null key)
944 nil)
945 ((eq key t)
947 ((eq key :constant)
948 (let* ((arg (arg-or-lose subj funstate))
949 (fields (arg-fields arg))
950 (consts body))
951 (when (not (= (length fields) (length consts)))
952 (pd-error "The number of constants doesn't match number of ~
953 fields in: (~S :constant~{ ~S~})"
954 subj body))
955 (compare-fields-form (gen-arg-forms arg :numeric funstate)
956 consts)))
957 ((eq key :positive)
958 `(> ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
960 ((eq key :negative)
961 `(< ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
963 ((eq key :same-as)
964 (let ((arg1 (arg-or-lose subj funstate))
965 (arg2 (arg-or-lose (car body) funstate)))
966 (unless (and (= (length (arg-fields arg1))
967 (length (arg-fields arg2)))
968 (every (lambda (bs1 bs2)
969 (= (byte-size bs1) (byte-size bs2)))
970 (arg-fields arg1)
971 (arg-fields arg2)))
972 (pd-error "can't compare differently sized fields: ~
973 (~S :same-as ~S)" subj (car body)))
974 (compare-fields-form (gen-arg-forms arg1 :numeric funstate)
975 (gen-arg-forms arg2 :numeric funstate))))
976 ((eq key :or)
977 `(or ,@(mapcar (lambda (sub) (compile-test subj sub funstate))
978 body)))
979 ((eq key :and)
980 `(and ,@(mapcar (lambda (sub) (compile-test subj sub funstate))
981 body)))
982 ((eq key :not)
983 `(not ,(compile-test subj (car body) funstate)))
984 ((and (consp key) (null body))
985 (compile-test subj key funstate))
987 (pd-error "bogus test-form: ~S" test)))))
989 (defun compute-mask-id (args)
990 (let ((mask dchunk-zero)
991 (id dchunk-zero))
992 (dolist (arg args (values mask id))
993 (let ((av (arg-value arg)))
994 (when av
995 (do ((fields (arg-fields arg) (cdr fields))
996 (values (if (atom av) (list av) av) (cdr values)))
997 ((null fields))
998 (let ((field-mask (dchunk-make-mask (car fields))))
999 (when (/= (dchunk-and mask field-mask) dchunk-zero)
1000 (pd-error "The field ~S in arg ~S overlaps some other field."
1001 (car fields)
1002 (arg-name arg)))
1003 (dchunk-insertf id (car fields) (car values))
1004 (dchunk-orf mask field-mask))))))))
1006 #!-sb-fluid (declaim (inline bytes-to-bits))
1007 (declaim (maybe-inline sign-extend aligned-p align tab tab0))
1009 (defun bytes-to-bits (bytes)
1010 (declare (type disassem-length bytes))
1011 (* bytes sb!vm:n-byte-bits))
1013 (defun bits-to-bytes (bits)
1014 (declare (type disassem-length bits))
1015 (multiple-value-bind (bytes rbits)
1016 (truncate bits sb!vm:n-byte-bits)
1017 (when (not (zerop rbits))
1018 (error "~W bits is not a byte-multiple." bits))
1019 bytes))
1021 (defun sign-extend (int size)
1022 (declare (type integer int)
1023 (type (integer 0 128) size))
1024 (if (logbitp (1- size) int)
1025 (dpb int (byte size 0) -1)
1026 int))
1028 ;;; Is ADDRESS aligned on a SIZE byte boundary?
1029 (defun aligned-p (address size)
1030 (declare (type address address)
1031 (type alignment size))
1032 (zerop (logand (1- size) address)))
1034 ;;; Return ADDRESS aligned *upward* to a SIZE byte boundary.
1035 (defun align (address size)
1036 (declare (type address address)
1037 (type alignment size))
1038 (logandc1 (1- size) (+ (1- size) address)))
1040 (defun tab (column stream)
1041 (funcall (formatter "~V,1t") stream column)
1042 nil)
1043 (defun tab0 (column stream)
1044 (funcall (formatter "~V,0t") stream column)
1045 nil)
1047 (defun princ16 (value stream)
1048 (write value :stream stream :radix t :base 16 :escape nil))
1050 (defstruct (storage-info (:copier nil))
1051 (groups nil :type list) ; alist of (name . location-group)
1052 (debug-vars #() :type vector))
1054 (defstruct (segment (:conc-name seg-)
1055 (:constructor %make-segment)
1056 (:copier nil))
1057 (sap-maker (missing-arg)
1058 :type (function () sb!sys:system-area-pointer))
1059 ;; Length in bytes of the range of memory covered by this segment.
1060 (length 0 :type disassem-length)
1061 (virtual-location 0 :type address)
1062 (storage-info nil :type (or null storage-info))
1063 ;; KLUDGE: CODE-COMPONENT is not a type the host understands
1064 #-sb-xc-host (code nil :type (or null sb!kernel:code-component))
1065 (unboxed-data-range nil :type (or null (cons fixnum fixnum)))
1066 (hooks nil :type list))
1068 ;;; All state during disassembly. We store some seemingly redundant
1069 ;;; information so that we can allow garbage collect during disassembly and
1070 ;;; not get tripped up by a code block being moved...
1071 (defstruct (disassem-state (:conc-name dstate-)
1072 (:constructor %make-dstate)
1073 (:copier nil))
1074 ;; offset of current pos in segment
1075 (cur-offs 0 :type offset)
1076 ;; offset of next position
1077 (next-offs 0 :type offset)
1078 ;; a sap pointing to our segment
1079 (segment-sap nil :type (or null sb!sys:system-area-pointer))
1080 ;; the current segment
1081 (segment nil :type (or null segment))
1082 ;; what to align to in most cases
1083 (alignment sb!vm:n-word-bytes :type alignment)
1084 (byte-order :little-endian
1085 :type (member :big-endian :little-endian))
1086 ;; for user code to hang stuff off of
1087 (properties nil :type list)
1088 ;; for user code to hang stuff off of, cleared each time after a
1089 ;; non-prefix instruction is processed
1090 (inst-properties nil :type (or fixnum list))
1091 (filtered-values (make-array max-filtered-value-index)
1092 :type filtered-value-vector)
1093 ;; used for prettifying printing
1094 (addr-print-len nil :type (or null (integer 0 20)))
1095 (argument-column 0 :type column)
1096 ;; to make output look nicer
1097 (output-state :beginning
1098 :type (member :beginning
1099 :block-boundary
1100 nil))
1102 ;; alist of (address . label-number)
1103 (labels nil :type list)
1104 ;; same as LABELS slot data, but in a different form
1105 (label-hash (make-hash-table) :type hash-table)
1106 ;; list of function
1107 (fun-hooks nil :type list)
1109 ;; alist of (address . label-number), popped as it's used
1110 (cur-labels nil :type list)
1111 ;; OFFS-HOOKs, popped as they're used
1112 (cur-offs-hooks nil :type list)
1114 ;; for the current location
1115 (notes nil :type list)
1117 ;; currently active source variables
1118 (current-valid-locations nil :type (or null (vector bit))))
1119 (defmethod print-object ((dstate disassem-state) stream)
1120 (print-unreadable-object (dstate stream :type t)
1121 (format stream
1122 "+~W~@[ in ~S~]"
1123 (dstate-cur-offs dstate)
1124 (dstate-segment dstate))))
1126 ;;; Return the absolute address of the current instruction in DSTATE.
1127 (defun dstate-cur-addr (dstate)
1128 (the address (+ (seg-virtual-location (dstate-segment dstate))
1129 (dstate-cur-offs dstate))))
1131 ;;; Return the absolute address of the next instruction in DSTATE.
1132 (defun dstate-next-addr (dstate)
1133 (the address (+ (seg-virtual-location (dstate-segment dstate))
1134 (dstate-next-offs dstate))))
1136 ;;; Get the value of the property called NAME in DSTATE. Also SETF'able.
1138 ;;; KLUDGE: The associated run-time machinery for this is in
1139 ;;; target-disassem.lisp (much later). This is here just to make sure
1140 ;;; it's defined before it's used. -- WHN ca. 19990701
1141 (defmacro dstate-get-prop (dstate name)
1142 `(getf (dstate-properties ,dstate) ,name))
1144 ;;; Put PROPERTY into the set of instruction properties in DSTATE.
1145 ;;; PROPERTY can be a fixnum or symbol, but any given backend
1146 ;;; must exclusively use one or the other property representation.
1147 (defun dstate-put-inst-prop (dstate property)
1148 (if (fixnump property)
1149 (setf (dstate-inst-properties dstate)
1150 (logior (or (dstate-inst-properties dstate) 0) property))
1151 (push property (dstate-inst-properties dstate))))
1153 ;;; Return non-NIL if PROPERTY is in the set of instruction properties in
1154 ;;; DSTATE. As with -PUT-INST-PROP, we can have a bitmask or a plist.
1155 (defun dstate-get-inst-prop (dstate property)
1156 (if (fixnump property)
1157 (logtest (or (dstate-inst-properties dstate) 0) property)
1158 (memq property (dstate-inst-properties dstate))))
1160 (declaim (ftype function read-suffix))
1161 (defun read-signed-suffix (length dstate)
1162 (declare (type (member 8 16 32 64) length)
1163 (type disassem-state dstate)
1164 (optimize (speed 3) (safety 0)))
1165 (sign-extend (read-suffix length dstate) length))