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