source: trunk/abcl/src/org/armedbear/lisp/disassemble.lisp @ 15579

Last change on this file since 15579 was 15579, checked in by Mark Evenson, 10 months ago

Edit docstrings around disassembler machinery

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 10.7 KB
Line 
1;;; disassemble.lisp
2;;;
3;;; Copyright (C) 2005 Peter Graves
4;;; $Id: disassemble.lisp 15579 2022-05-23 06:23:39Z mevenson $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package :system)
33(require :clos)
34
35(defvar *disassembler-function* nil
36  "The underlying function last used for CL:DISASSEMBLE or nil if not invoked
37
38Available disassemblers are configured by pushing a strategy to
39SYSTEM:*DISASSEMBLERS*.  The function SYSTEM:CHOOSE-DISASSEMBLER is
40used to select a current strategy from this list of strategies.")
41
42(defvar *disassemblers*
43  `((:system-javap . disassemble-class-bytes))
44  "Methods of invoking CL:DISASSEMBLE consisting of a list of (KEYWORD FUNCTION) pairs
45
46The pairs (KEYWORD FUNCTION) contain a KEYWORD uniquely identifying a
47particular disassembler and a SYMBOL designating its invocation function.
48
49The KEYWORD values are used by SYS:CHOOSE-DISASSEMBLER to install a
50given disassembler as the one used by CL:DISASSEMBLE.  Additional
51disassemblers/decompilers are packaged in the ABCL-INTROSPECT contrib.
52
53The initial default is :SYSTEM-JAVAP which attempts to invoke the
54javap command line tool shipped as part of the Java Developement Kit
55which may or may not be installed locally.
56")
57
58(defun choose-disassembler (&optional name)
59  "Report current disassembler that would be used by CL:DISASSEMBLE
60
61When the optional keyword NAME is specified, select the associated
62disassembler from SYS:*DISASSEMBLERS* for future invocations of
63CL:DISASSEMBLE."
64  (flet ((sane-disassembler-p (disassembler)
65           (and disassembler
66                (fboundp disassembler))))
67    (setf *disassembler-function*
68          (if name
69              (let ((disassembler (cdr (assoc name *disassemblers*))))
70                (if (sane-disassembler-p disassembler)
71                    disassembler
72                    (error "Disassembler ~a doesn't appear to work." name)))
73              (if (sane-disassembler-p *disassembler-function*)
74                  *disassembler-function*
75                  ;; simplest strategy: choose the first working one
76                  (loop
77                    :for (nil . disassembler) in *disassemblers*
78                    :when (sane-disassembler-p disassembler)
79                      :do (return disassembler)
80                    :finally (warn "Can't find suitable disassembler.")))))))
81
82(eval-when (:compile-toplevel :load-toplevel :execute)
83  (defmacro with-open ((name value) &body body)
84    `(let ((,name ,value))
85       (unwind-protect
86           (progn ,@body)
87         (java:jcall-raw "close" ,name)))))
88
89(defun read-byte-array-from-stream (stream)
90  (let ((buffer (java:jnew-array (java:jclass "byte") 4096)))
91    (with-open (output (java:jnew "java.io.ByteArrayOutputStream"))
92      (loop
93        for length = (java:jcall "read" stream buffer)
94        until (eql length -1)
95        do (java:jcall-raw "write" output buffer 0 length))
96      (java:jcall-raw "flush" output)
97      (java:jcall-raw "toByteArray" output))))
98
99(defun class-resource-path (class)
100  (format NIL "~A.class" (substitute #\/ #\. (java:jcall "getName" class))))
101
102(defun class-bytes (class)
103  (with-open (stream (java:jcall-raw
104                      "getResourceAsStream"
105                      (java:jcall-raw "getClassLoader" class)
106                      (class-resource-path class)))
107    (read-byte-array-from-stream stream)))
108
109(defun disassemble-bytes (bytes)
110  "Disassemble jvm code BYTES returning a string."
111  (funcall (or *disassembler-function* (choose-disassembler))
112           bytes))
113
114(defun disassemble-function (arg)
115  (let ((function (cond ((java::java-object-p arg) 
116                         (cond ((java::jinstance-of-p arg "java.lang.Class")
117                                arg)
118                               ((java::jinstance-of-p arg "java.lang.reflect.Method")
119                                (java::jmethod-declaring-class arg))
120                               ))
121                        ((functionp arg)
122                         arg)
123                        ((symbolp arg)
124                         (or (macro-function arg) (symbol-function arg)))
125                        (t arg))))
126    (when (typep function 'generic-function)
127      (setf function (mop::funcallable-instance-function function)))
128    ;; use isInstance instead of jinstance-of-p
129    ;; because the latter checked java-object-p
130    ;; which fails since its a lisp object
131    (when (and (java:jcall "isInstance"  (java:jclass "org.armedbear.lisp.Closure") function)
132               (not (java:jcall "isInstance"  (java:jclass "org.armedbear.lisp.CompiledClosure") function)))
133      (return-from disassemble-function 
134        (with-output-to-string (s)
135          (format s "Not a compiled function: ~%")
136          (pprint (java:jcall "getBody" function) s))))
137    (let ((bytes (or (and (java:jcall "isInstance" (java:jclass "org.armedbear.lisp.Function") function)
138                          (ignore-errors (getf (function-plist function))) 'class-bytes)
139                     (and (java:jcall "isInstance" (java:jclass "org.armedbear.lisp.CompiledClosure") function)
140                          (equalp (java::jcall "getName" (java::jobject-class 
141                                                          (java:jcall "getClassLoader" (java::jcall "getClass" function))))
142                                  "org.armedbear.lisp.FaslClassLoader")
143                          (fasl-compiled-closure-class-bytes function)))))
144      ;; we've got bytes here then we've covered the case that the disassembler already handled
145      ;; If not then we've either got a primitive (in function) or we got passed a method object as arg.
146      (if bytes
147          (disassemble-bytes bytes)
148          (let ((class (if (java:java-object-p function) function (java:jcall "getClass" function))))
149            (let ((classloader (java:jcall "getClassLoader" class)))
150              (if (or (java:jinstance-of-p classloader "org.armedbear.lisp.MemoryClassLoader")
151                      (java:jinstance-of-p classloader "org.armedbear.lisp.FaslClassLoader"))
152                  (disassemble-bytes
153                   (or
154                    (ignore-errors
155                     (java:jcall "getFunctionClassBytes" classloader class))
156                    ;;; alanr found that in certain situations (under
157                    ;;; OSGI?) that one has to explicitly FUNCALL the
158                    ;;; function slot, so we fall back to that strategy.
159                    (ignore-errors
160                     (funcall (java:jfield "org.armedbear.lisp.Function" "FUNCTION_CLASS_BYTES") function))))
161                  (disassemble-bytes
162                   (read-byte-array-from-stream
163                    (java:jcall-raw
164                     "getResourceAsStream"
165                     (java:jcall-raw "getClassLoader" class)
166                     (class-resource-path class)))))))))))
167
168(defparameter +propertyList+ 
169  (load-time-value
170   (let ((it (find "propertyList" (java::jcall "getDeclaredFields" (java::jclass "org.armedbear.lisp.Function")) :key (lambda(e)(java::jcall "getName" e)) :test 'equal)))
171     (java::jcall "setAccessible" it t)
172     it)))
173
174(defun function-plist (function)
175  (java::jcall "get" +propertylist+ function))
176
177(defun (setf function-plist) (new function)
178  (java::jcall "set" +propertylist+ function new))
179
180;; PITA. make loadedFrom public
181;;; TODO Java9 work out a sensible story to preserve existing values if required
182(defun get-loaded-from (function)
183  (let* ((jfield (find "loadedFrom" (java:jcall "getDeclaredFields" (java:jclass "org.armedbear.lisp.Function")) 
184                       :key 'java:jfield-name :test 'equal)))
185    (java:jcall "setAccessible" jfield java:+true+)
186    (java:jcall "get" jfield function)))
187
188(defun set-loaded-from (function value)
189  (let* ((jfield (find "loadedFrom" (java:jcall "getDeclaredFields" (java:jclass "org.armedbear.lisp.Function")) 
190                       :key 'java:jfield-name :test 'equal)))
191    (java:jcall "setAccessible" jfield java:+true+)
192    (java:jcall "set" jfield function value)))
193
194;; because getFunctionClassBytes gets a null pointer exception
195(defun fasl-compiled-closure-class-bytes (function)
196  (let* ((loaded-from (get-loaded-from function))
197         (class-name (subseq (java:jcall "getName" (java:jcall "getClass" function)) (length "org.armedbear.lisp.")))
198         (url (if (not (eq (pathname-device loaded-from) :unspecific))
199                  ;; we're loading from a jar
200                  (java:jnew "java.net.URL" 
201                             (namestring (make-pathname :directory (pathname-directory loaded-from)
202                                                               :device (pathname-device loaded-from)
203                                                               :name class-name :type "cls")))
204                  ;; we're loading from a fasl file
205                  (java:jnew "java.net.URL" (namestring (make-pathname :device (list loaded-from)
206                                                                       :name class-name :type "cls"))))))
207    (read-byte-array-from-stream (java:jcall "openStream" url))))
208
209;; closure bindings
210;; (get-java-field (elt (#"get" (elt (#"getFields" (#"getClass" #'foo)) 0) #'foo) 0) "value")
211
212(defun disassemble (arg)
213  (print-lines-with-prefix (disassemble-function arg)))
214
215(defun print-lines-with-prefix (string)
216  (with-input-from-string (stream string)
217    (loop
218      (let ((line (read-line stream nil)))
219        (unless line (return))
220        (write-string "; ")
221        (write-string line)
222        (terpri)))))
223
Note: See TracBrowser for help on using the repository browser.