PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/local-lisp/slime/swank-cmucl.lisp

https://bitbucket.org/sakito/dot.emacs.d/
Lisp | 2578 lines | 2025 code | 318 blank | 235 comment | 69 complexity | ff4a846397a167fa5dd1d90df48a40dc MD5 | raw file
Possible License(s): GPL-3.0, CC-BY-SA-4.0, GPL-2.0, Unlicense
  1. ;;; -*- indent-tabs-mode: nil; outline-regexp: ";;;;+" -*-
  2. ;;;
  3. ;;; License: Public Domain
  4. ;;;
  5. ;;;; Introduction
  6. ;;;
  7. ;;; This is the CMUCL implementation of the `swank-backend' package.
  8. (in-package :swank-backend)
  9. (import-swank-mop-symbols :pcl '(:slot-definition-documentation))
  10. (defun swank-mop:slot-definition-documentation (slot)
  11. (documentation slot t))
  12. ;;;; "Hot fixes"
  13. ;;;
  14. ;;; Here are necessary bugfixes to the oldest supported version of
  15. ;;; CMUCL (currently 18e). Any fixes placed here should also be
  16. ;;; submitted to the `cmucl-imp' mailing list and confirmed as
  17. ;;; good. When a new release is made that includes the fixes we should
  18. ;;; promptly delete them from here. It is enough to be compatible with
  19. ;;; the latest release.
  20. (in-package :lisp)
  21. ;;; `READ-SEQUENCE' with large sequences has problems in 18e. This new
  22. ;;; definition works better.
  23. #+cmu18
  24. (progn
  25. (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
  26. (when s
  27. (setf (symbol-value s) nil)))
  28. (defun read-into-simple-string (s stream start end)
  29. (declare (type simple-string s))
  30. (declare (type stream stream))
  31. (declare (type index start end))
  32. (unless (subtypep (stream-element-type stream) 'character)
  33. (error 'type-error
  34. :datum (read-char stream nil #\Null)
  35. :expected-type (stream-element-type stream)
  36. :format-control "Trying to read characters from a binary stream."))
  37. ;; Let's go as low level as it seems reasonable.
  38. (let* ((numbytes (- end start))
  39. (total-bytes 0))
  40. ;; read-n-bytes may return fewer bytes than requested, so we need
  41. ;; to keep trying.
  42. (loop while (plusp numbytes) do
  43. (let ((bytes-read (system:read-n-bytes stream s start numbytes nil)))
  44. (when (zerop bytes-read)
  45. (return-from read-into-simple-string total-bytes))
  46. (incf total-bytes bytes-read)
  47. (incf start bytes-read)
  48. (decf numbytes bytes-read)))
  49. total-bytes))
  50. (let ((s (find-symbol (string :*enable-package-locked-errors*) :lisp)))
  51. (when s
  52. (setf (symbol-value s) t)))
  53. )
  54. (in-package :swank-backend)
  55. ;;;; TCP server
  56. ;;;
  57. ;;; In CMUCL we support all communication styles. By default we use
  58. ;;; `:SIGIO' because it is the most responsive, but it's somewhat
  59. ;;; dangerous: CMUCL is not in general "signal safe", and you don't
  60. ;;; know for sure what you'll be interrupting. Both `:FD-HANDLER' and
  61. ;;; `:SPAWN' are reasonable alternatives.
  62. (defimplementation preferred-communication-style ()
  63. :sigio)
  64. #-(or darwin mips)
  65. (defimplementation create-socket (host port)
  66. (let* ((addr (resolve-hostname host))
  67. (addr (if (not (find-symbol "SOCKET-ERROR" :ext))
  68. (ext:htonl addr)
  69. addr)))
  70. (ext:create-inet-listener port :stream :reuse-address t :host addr)))
  71. ;; There seems to be a bug in create-inet-listener on Mac/OSX and Irix.
  72. #+(or darwin mips)
  73. (defimplementation create-socket (host port)
  74. (declare (ignore host))
  75. (ext:create-inet-listener port :stream :reuse-address t))
  76. (defimplementation local-port (socket)
  77. (nth-value 1 (ext::get-socket-host-and-port (socket-fd socket))))
  78. (defimplementation close-socket (socket)
  79. (let ((fd (socket-fd socket)))
  80. (sys:invalidate-descriptor fd)
  81. (ext:close-socket fd)))
  82. (defimplementation accept-connection (socket &key
  83. external-format buffering timeout)
  84. (declare (ignore timeout))
  85. (make-socket-io-stream (ext:accept-tcp-connection socket)
  86. (or buffering :full)
  87. (or external-format :iso-8859-1)))
  88. ;;;;; Sockets
  89. (defimplementation socket-fd (socket)
  90. "Return the filedescriptor for the socket represented by SOCKET."
  91. (etypecase socket
  92. (fixnum socket)
  93. (sys:fd-stream (sys:fd-stream-fd socket))))
  94. (defun resolve-hostname (hostname)
  95. "Return the IP address of HOSTNAME as an integer (in host byte-order)."
  96. (let ((hostent (ext:lookup-host-entry hostname)))
  97. (car (ext:host-entry-addr-list hostent))))
  98. (defvar *external-format-to-coding-system*
  99. '((:iso-8859-1
  100. "latin-1" "latin-1-unix" "iso-latin-1-unix"
  101. "iso-8859-1" "iso-8859-1-unix")
  102. #+unicode
  103. (:utf-8 "utf-8" "utf-8-unix")))
  104. (defimplementation find-external-format (coding-system)
  105. (car (rassoc-if (lambda (x) (member coding-system x :test #'equal))
  106. *external-format-to-coding-system*)))
  107. (defun make-socket-io-stream (fd buffering external-format)
  108. "Create a new input/output fd-stream for FD."
  109. #-unicode(declare (ignore external-format))
  110. (sys:make-fd-stream fd :input t :output t :element-type 'base-char
  111. :buffering buffering
  112. #+unicode :external-format
  113. #+unicode external-format))
  114. (defimplementation make-fd-stream (fd external-format)
  115. (make-socket-io-stream fd :full external-format))
  116. (defimplementation dup (fd)
  117. (multiple-value-bind (clone error) (unix:unix-dup fd)
  118. (unless clone (error "dup failed: ~a" (unix:get-unix-error-msg error)))
  119. clone))
  120. (defimplementation command-line-args ()
  121. ext:*command-line-strings*)
  122. (defimplementation exec-image (image-file args)
  123. (multiple-value-bind (ok error)
  124. (unix:unix-execve (car (command-line-args))
  125. (list* (car (command-line-args))
  126. "-core" image-file
  127. "-noinit"
  128. args))
  129. (error "~a" (unix:get-unix-error-msg error))
  130. ok))
  131. ;;;;; Signal-driven I/O
  132. (defimplementation install-sigint-handler (function)
  133. (sys:enable-interrupt :sigint (lambda (signal code scp)
  134. (declare (ignore signal code scp))
  135. (funcall function))))
  136. (defvar *sigio-handlers* '()
  137. "List of (key . function) pairs.
  138. All functions are called on SIGIO, and the key is used for removing
  139. specific functions.")
  140. (defun reset-sigio-handlers () (setq *sigio-handlers* '()))
  141. ;; All file handlers are invalid afer reload.
  142. (pushnew 'reset-sigio-handlers ext:*after-save-initializations*)
  143. (defun set-sigio-handler ()
  144. (sys:enable-interrupt :sigio (lambda (signal code scp)
  145. (sigio-handler signal code scp))))
  146. (defun sigio-handler (signal code scp)
  147. (declare (ignore signal code scp))
  148. (mapc #'funcall (mapcar #'cdr *sigio-handlers*)))
  149. (defun fcntl (fd command arg)
  150. "fcntl(2) - manipulate a file descriptor."
  151. (multiple-value-bind (ok error) (unix:unix-fcntl fd command arg)
  152. (cond (ok)
  153. (t (error "fcntl: ~A" (unix:get-unix-error-msg error))))))
  154. (defimplementation add-sigio-handler (socket fn)
  155. (set-sigio-handler)
  156. (let ((fd (socket-fd socket)))
  157. (fcntl fd unix:f-setown (unix:unix-getpid))
  158. (let ((old-flags (fcntl fd unix:f-getfl 0)))
  159. (fcntl fd unix:f-setfl (logior old-flags unix:fasync)))
  160. (assert (not (assoc fd *sigio-handlers*)))
  161. (push (cons fd fn) *sigio-handlers*)))
  162. (defimplementation remove-sigio-handlers (socket)
  163. (let ((fd (socket-fd socket)))
  164. (when (assoc fd *sigio-handlers*)
  165. (setf *sigio-handlers* (remove fd *sigio-handlers* :key #'car))
  166. (let ((old-flags (fcntl fd unix:f-getfl 0)))
  167. (fcntl fd unix:f-setfl (logandc2 old-flags unix:fasync)))
  168. (sys:invalidate-descriptor fd))
  169. (assert (not (assoc fd *sigio-handlers*)))
  170. (when (null *sigio-handlers*)
  171. (sys:default-interrupt :sigio))))
  172. ;;;;; SERVE-EVENT
  173. (defimplementation add-fd-handler (socket fn)
  174. (let ((fd (socket-fd socket)))
  175. (sys:add-fd-handler fd :input (lambda (_) _ (funcall fn)))))
  176. (defimplementation remove-fd-handlers (socket)
  177. (sys:invalidate-descriptor (socket-fd socket)))
  178. (defimplementation wait-for-input (streams &optional timeout)
  179. (assert (member timeout '(nil t)))
  180. (loop
  181. (let ((ready (remove-if-not #'listen streams)))
  182. (when ready (return ready)))
  183. (when timeout (return nil))
  184. (multiple-value-bind (in out) (make-pipe)
  185. (let* ((f (constantly t))
  186. (handlers (loop for s in (cons in (mapcar #'to-fd-stream streams))
  187. collect (add-one-shot-handler s f))))
  188. (unwind-protect
  189. (let ((*interrupt-queued-handler* (lambda ()
  190. (write-char #\! out))))
  191. (when (check-slime-interrupts) (return :interrupt))
  192. (sys:serve-event))
  193. (mapc #'sys:remove-fd-handler handlers)
  194. (close in)
  195. (close out))))))
  196. (defun to-fd-stream (stream)
  197. (etypecase stream
  198. (sys:fd-stream stream)
  199. (synonym-stream
  200. (to-fd-stream
  201. (symbol-value (synonym-stream-symbol stream))))
  202. (two-way-stream
  203. (to-fd-stream (two-way-stream-input-stream stream)))))
  204. (defun add-one-shot-handler (stream function)
  205. (let (handler)
  206. (setq handler (sys:add-fd-handler (sys:fd-stream-fd stream) :input
  207. (lambda (fd)
  208. (declare (ignore fd))
  209. (sys:remove-fd-handler handler)
  210. (funcall function stream))))))
  211. (defun make-pipe ()
  212. (multiple-value-bind (in out) (unix:unix-pipe)
  213. (values (sys:make-fd-stream in :input t :buffering :none)
  214. (sys:make-fd-stream out :output t :buffering :none))))
  215. ;;;; Stream handling
  216. ;;; XXX: How come we don't use Gray streams in CMUCL too? -luke (15/May/2004)
  217. (defimplementation make-output-stream (write-string)
  218. (make-slime-output-stream write-string))
  219. (defimplementation make-input-stream (read-string)
  220. (make-slime-input-stream read-string))
  221. (defstruct (slime-output-stream
  222. (:include lisp::lisp-stream
  223. (lisp::misc #'sos/misc)
  224. (lisp::out #'sos/write-char)
  225. (lisp::sout #'sos/write-string))
  226. (:conc-name sos.)
  227. (:print-function %print-slime-output-stream)
  228. (:constructor make-slime-output-stream (output-fn)))
  229. (output-fn nil :type function)
  230. (buffer (make-string 4000) :type string)
  231. (index 0 :type kernel:index)
  232. (column 0 :type kernel:index))
  233. (defun %print-slime-output-stream (s stream d)
  234. (declare (ignore d))
  235. (print-unreadable-object (s stream :type t :identity t)))
  236. (defun sos/write-char (stream char)
  237. (let ((pending-output nil))
  238. (system:without-interrupts
  239. (let ((buffer (sos.buffer stream))
  240. (index (sos.index stream)))
  241. (setf (schar buffer index) char)
  242. (setf (sos.index stream) (1+ index))
  243. (incf (sos.column stream))
  244. (when (char= #\newline char)
  245. (setf (sos.column stream) 0)
  246. #+(or)(setq pending-output (sos/reset-buffer stream))
  247. )
  248. (when (= index (1- (length buffer)))
  249. (setq pending-output (sos/reset-buffer stream)))))
  250. (when pending-output
  251. (funcall (sos.output-fn stream) pending-output)))
  252. char)
  253. (defun sos/write-string (stream string start end)
  254. (loop for i from start below end
  255. do (sos/write-char stream (aref string i))))
  256. (defun sos/flush (stream)
  257. (let ((string (sos/reset-buffer stream)))
  258. (when string
  259. (funcall (sos.output-fn stream) string))
  260. nil))
  261. (defun sos/reset-buffer (stream)
  262. (system:without-interrupts
  263. (let ((end (sos.index stream)))
  264. (unless (zerop end)
  265. (prog1 (subseq (sos.buffer stream) 0 end)
  266. (setf (sos.index stream) 0))))))
  267. (defun sos/misc (stream operation &optional arg1 arg2)
  268. (declare (ignore arg1 arg2))
  269. (case operation
  270. ((:force-output :finish-output) (sos/flush stream))
  271. (:charpos (sos.column stream))
  272. (:line-length 75)
  273. (:file-position nil)
  274. (:element-type 'base-char)
  275. (:get-command nil)
  276. (:close nil)
  277. (t (format *terminal-io* "~&~Astream: ~S~%" stream operation))))
  278. (defstruct (slime-input-stream
  279. (:include string-stream
  280. (lisp::in #'sis/in)
  281. (lisp::misc #'sis/misc))
  282. (:conc-name sis.)
  283. (:print-function %print-slime-output-stream)
  284. (:constructor make-slime-input-stream (input-fn)))
  285. (input-fn nil :type function)
  286. (buffer "" :type string)
  287. (index 0 :type kernel:index))
  288. (defun sis/in (stream eof-errorp eof-value)
  289. (let ((index (sis.index stream))
  290. (buffer (sis.buffer stream)))
  291. (when (= index (length buffer))
  292. (let ((string (funcall (sis.input-fn stream))))
  293. (cond ((zerop (length string))
  294. (return-from sis/in
  295. (if eof-errorp
  296. (error (make-condition 'end-of-file :stream stream))
  297. eof-value)))
  298. (t
  299. (setf buffer string)
  300. (setf (sis.buffer stream) buffer)
  301. (setf index 0)))))
  302. (prog1 (aref buffer index)
  303. (setf (sis.index stream) (1+ index)))))
  304. (defun sis/misc (stream operation &optional arg1 arg2)
  305. (declare (ignore arg2))
  306. (ecase operation
  307. (:file-position nil)
  308. (:file-length nil)
  309. (:unread (setf (aref (sis.buffer stream)
  310. (decf (sis.index stream)))
  311. arg1))
  312. (:clear-input
  313. (setf (sis.index stream) 0
  314. (sis.buffer stream) ""))
  315. (:listen (< (sis.index stream) (length (sis.buffer stream))))
  316. (:charpos nil)
  317. (:line-length nil)
  318. (:get-command nil)
  319. (:element-type 'base-char)
  320. (:close nil)
  321. (:interactive-p t)))
  322. ;;;; Compilation Commands
  323. (defvar *previous-compiler-condition* nil
  324. "Used to detect duplicates.")
  325. (defvar *previous-context* nil
  326. "Previous compiler error context.")
  327. (defvar *buffer-name* nil
  328. "The name of the Emacs buffer we are compiling from.
  329. NIL if we aren't compiling from a buffer.")
  330. (defvar *buffer-start-position* nil)
  331. (defvar *buffer-substring* nil)
  332. (defimplementation call-with-compilation-hooks (function)
  333. (let ((*previous-compiler-condition* nil)
  334. (*previous-context* nil)
  335. (*print-readably* nil))
  336. (handler-bind ((c::compiler-error #'handle-notification-condition)
  337. (c::style-warning #'handle-notification-condition)
  338. (c::warning #'handle-notification-condition))
  339. (funcall function))))
  340. (defimplementation swank-compile-file (input-file output-file
  341. load-p external-format
  342. &key policy)
  343. (declare (ignore external-format policy))
  344. (clear-xref-info input-file)
  345. (with-compilation-hooks ()
  346. (let ((*buffer-name* nil)
  347. (ext:*ignore-extra-close-parentheses* nil))
  348. (multiple-value-bind (output-file warnings-p failure-p)
  349. (compile-file input-file :output-file output-file)
  350. (values output-file warnings-p
  351. (or failure-p
  352. (when load-p
  353. ;; Cache the latest source file for definition-finding.
  354. (source-cache-get input-file
  355. (file-write-date input-file))
  356. (not (load output-file)))))))))
  357. (defimplementation swank-compile-string (string &key buffer position filename
  358. policy)
  359. (declare (ignore filename policy))
  360. (with-compilation-hooks ()
  361. (let ((*buffer-name* buffer)
  362. (*buffer-start-position* position)
  363. (*buffer-substring* string)
  364. (source-info (list :emacs-buffer buffer
  365. :emacs-buffer-offset position
  366. :emacs-buffer-string string)))
  367. (with-input-from-string (stream string)
  368. (let ((failurep (ext:compile-from-stream stream :source-info
  369. source-info)))
  370. (not failurep))))))
  371. ;;;;; Trapping notes
  372. ;;;
  373. ;;; We intercept conditions from the compiler and resignal them as
  374. ;;; `SWANK:COMPILER-CONDITION's.
  375. (defun handle-notification-condition (condition)
  376. "Handle a condition caused by a compiler warning."
  377. (unless (eq condition *previous-compiler-condition*)
  378. (let ((context (c::find-error-context nil)))
  379. (setq *previous-compiler-condition* condition)
  380. (setq *previous-context* context)
  381. (signal-compiler-condition condition context))))
  382. (defun signal-compiler-condition (condition context)
  383. (signal (make-condition
  384. 'compiler-condition
  385. :original-condition condition
  386. :severity (severity-for-emacs condition)
  387. :message (compiler-condition-message condition)
  388. :source-context (compiler-error-context context)
  389. :location (if (read-error-p condition)
  390. (read-error-location condition)
  391. (compiler-note-location context)))))
  392. (defun severity-for-emacs (condition)
  393. "Return the severity of CONDITION."
  394. (etypecase condition
  395. ((satisfies read-error-p) :read-error)
  396. (c::compiler-error :error)
  397. (c::style-warning :note)
  398. (c::warning :warning)))
  399. (defun read-error-p (condition)
  400. (eq (type-of condition) 'c::compiler-read-error))
  401. (defun compiler-condition-message (condition)
  402. "Briefly describe a compiler error for Emacs.
  403. When Emacs presents the message it already has the source popped up
  404. and the source form highlighted. This makes much of the information in
  405. the error-context redundant."
  406. (princ-to-string condition))
  407. (defun compiler-error-context (error-context)
  408. "Describe context information for Emacs."
  409. (declare (type (or c::compiler-error-context null) error-context))
  410. (multiple-value-bind (enclosing source)
  411. (if error-context
  412. (values (c::compiler-error-context-enclosing-source error-context)
  413. (c::compiler-error-context-source error-context)))
  414. (if (or enclosing source)
  415. (format nil "~@[--> ~{~<~%--> ~1:;~A ~>~}~%~]~
  416. ~@[==>~{~&~A~}~]"
  417. enclosing source))))
  418. (defun read-error-location (condition)
  419. (let* ((finfo (car (c::source-info-current-file c::*source-info*)))
  420. (file (c::file-info-name finfo))
  421. (pos (c::compiler-read-error-position condition)))
  422. (cond ((and (eq file :stream) *buffer-name*)
  423. (make-location (list :buffer *buffer-name*)
  424. (list :offset *buffer-start-position* pos)))
  425. ((and (pathnamep file) (not *buffer-name*))
  426. (make-location (list :file (unix-truename file))
  427. (list :position (1+ pos))))
  428. (t (break)))))
  429. (defun compiler-note-location (context)
  430. "Derive the location of a complier message from its context.
  431. Return a `location' record, or (:error REASON) on failure."
  432. (if (null context)
  433. (note-error-location)
  434. (with-struct (c::compiler-error-context- file-name
  435. original-source
  436. original-source-path) context
  437. (or (locate-compiler-note file-name original-source
  438. (reverse original-source-path))
  439. (note-error-location)))))
  440. (defun note-error-location ()
  441. "Pseudo-location for notes that can't be located."
  442. (cond (*compile-file-truename*
  443. (make-location (list :file (unix-truename *compile-file-truename*))
  444. (list :eof)))
  445. (*buffer-name*
  446. (make-location (list :buffer *buffer-name*)
  447. (list :position *buffer-start-position*)))
  448. (t (list :error "No error location available."))))
  449. (defun locate-compiler-note (file source source-path)
  450. (cond ((and (eq file :stream) *buffer-name*)
  451. ;; Compiling from a buffer
  452. (make-location (list :buffer *buffer-name*)
  453. (list :offset *buffer-start-position*
  454. (source-path-string-position
  455. source-path *buffer-substring*))))
  456. ((and (pathnamep file) (null *buffer-name*))
  457. ;; Compiling from a file
  458. (make-location (list :file (unix-truename file))
  459. (list :position (1+ (source-path-file-position
  460. source-path file)))))
  461. ((and (eq file :lisp) (stringp source))
  462. ;; No location known, but we have the source form.
  463. ;; XXX How is this case triggered? -luke (16/May/2004)
  464. ;; This can happen if the compiler needs to expand a macro
  465. ;; but the macro-expander is not yet compiled. Calling the
  466. ;; (interpreted) macro-expander triggers IR1 conversion of
  467. ;; the lambda expression for the expander and invokes the
  468. ;; compiler recursively.
  469. (make-location (list :source-form source)
  470. (list :position 1)))))
  471. (defun unix-truename (pathname)
  472. (ext:unix-namestring (truename pathname)))
  473. ;;;; XREF
  474. ;;;
  475. ;;; Cross-reference support is based on the standard CMUCL `XREF'
  476. ;;; package. This package has some caveats: XREF information is
  477. ;;; recorded during compilation and not preserved in fasl files, and
  478. ;;; XREF recording is disabled by default. Redefining functions can
  479. ;;; also cause duplicate references to accumulate, but
  480. ;;; `swank-compile-file' will automatically clear out any old records
  481. ;;; from the same filename.
  482. ;;;
  483. ;;; To enable XREF recording, set `c:*record-xref-info*' to true. To
  484. ;;; clear out the XREF database call `xref:init-xref-database'.
  485. (defmacro defxref (name function)
  486. `(defimplementation ,name (name)
  487. (xref-results (,function name))))
  488. (defxref who-calls xref:who-calls)
  489. (defxref who-references xref:who-references)
  490. (defxref who-binds xref:who-binds)
  491. (defxref who-sets xref:who-sets)
  492. ;;; More types of XREF information were added since 18e:
  493. ;;;
  494. #-cmu18
  495. (progn
  496. (defxref who-macroexpands xref:who-macroexpands)
  497. ;; XXX
  498. (defimplementation who-specializes (symbol)
  499. (let* ((methods (xref::who-specializes (find-class symbol)))
  500. (locations (mapcar #'method-location methods)))
  501. (mapcar #'list methods locations))))
  502. (defun xref-results (contexts)
  503. (mapcar (lambda (xref)
  504. (list (xref:xref-context-name xref)
  505. (resolve-xref-location xref)))
  506. contexts))
  507. (defun resolve-xref-location (xref)
  508. (let ((name (xref:xref-context-name xref))
  509. (file (xref:xref-context-file xref))
  510. (source-path (xref:xref-context-source-path xref)))
  511. (cond ((and file source-path)
  512. (let ((position (source-path-file-position source-path file)))
  513. (make-location (list :file (unix-truename file))
  514. (list :position (1+ position)))))
  515. (file
  516. (make-location (list :file (unix-truename file))
  517. (list :function-name (string name))))
  518. (t
  519. `(:error ,(format nil "Unknown source location: ~S ~S ~S "
  520. name file source-path))))))
  521. (defun clear-xref-info (namestring)
  522. "Clear XREF notes pertaining to NAMESTRING.
  523. This is a workaround for a CMUCL bug: XREF records are cumulative."
  524. (when c:*record-xref-info*
  525. (let ((filename (truename namestring)))
  526. (dolist (db (list xref::*who-calls*
  527. #-cmu18 xref::*who-is-called*
  528. #-cmu18 xref::*who-macroexpands*
  529. xref::*who-references*
  530. xref::*who-binds*
  531. xref::*who-sets*))
  532. (maphash (lambda (target contexts)
  533. ;; XXX update during traversal?
  534. (setf (gethash target db)
  535. (delete filename contexts
  536. :key #'xref:xref-context-file
  537. :test #'equalp)))
  538. db)))))
  539. ;;;; Find callers and callees
  540. ;;;
  541. ;;; Find callers and callees by looking at the constant pool of
  542. ;;; compiled code objects. We assume every fdefn object in the
  543. ;;; constant pool corresponds to a call to that function. A better
  544. ;;; strategy would be to use the disassembler to find actual
  545. ;;; call-sites.
  546. (labels ((make-stack () (make-array 100 :fill-pointer 0 :adjustable t))
  547. (map-cpool (code fun)
  548. (declare (type kernel:code-component code) (type function fun))
  549. (loop for i from vm:code-constants-offset
  550. below (kernel:get-header-data code)
  551. do (funcall fun (kernel:code-header-ref code i))))
  552. (callees (fun)
  553. (let ((callees (make-stack)))
  554. (map-cpool (vm::find-code-object fun)
  555. (lambda (o)
  556. (when (kernel:fdefn-p o)
  557. (vector-push-extend (kernel:fdefn-function o)
  558. callees))))
  559. (coerce callees 'list)))
  560. (callers (fun)
  561. (declare (function fun))
  562. (let ((callers (make-stack)))
  563. (ext:gc :full t)
  564. ;; scan :dynamic first to avoid the need for even more gcing
  565. (dolist (space '(:dynamic :read-only :static))
  566. (vm::map-allocated-objects
  567. (lambda (obj header size)
  568. (declare (type fixnum header) (ignore size))
  569. (when (= vm:code-header-type header)
  570. (map-cpool obj
  571. (lambda (c)
  572. (when (and (kernel:fdefn-p c)
  573. (eq (kernel:fdefn-function c) fun))
  574. (vector-push-extend obj callers))))))
  575. space)
  576. (ext:gc))
  577. (coerce callers 'list)))
  578. (entry-points (code)
  579. (loop for entry = (kernel:%code-entry-points code)
  580. then (kernel::%function-next entry)
  581. while entry
  582. collect entry))
  583. (guess-main-entry-point (entry-points)
  584. (or (find-if (lambda (fun)
  585. (ext:valid-function-name-p
  586. (kernel:%function-name fun)))
  587. entry-points)
  588. (car entry-points)))
  589. (fun-dspec (fun)
  590. (list (kernel:%function-name fun) (function-location fun)))
  591. (code-dspec (code)
  592. (let ((eps (entry-points code))
  593. (di (kernel:%code-debug-info code)))
  594. (cond (eps (fun-dspec (guess-main-entry-point eps)))
  595. (di (list (c::debug-info-name di)
  596. (debug-info-function-name-location di)))
  597. (t (list (princ-to-string code)
  598. `(:error "No src-loc available")))))))
  599. (declare (inline map-cpool))
  600. (defimplementation list-callers (symbol)
  601. (mapcar #'code-dspec (callers (coerce symbol 'function) )))
  602. (defimplementation list-callees (symbol)
  603. (mapcar #'fun-dspec (callees symbol))))
  604. (defun test-list-callers (count)
  605. (let ((funsyms '()))
  606. (do-all-symbols (s)
  607. (when (and (fboundp s)
  608. (functionp (symbol-function s))
  609. (not (macro-function s))
  610. (not (special-operator-p s)))
  611. (push s funsyms)))
  612. (let ((len (length funsyms)))
  613. (dotimes (i count)
  614. (let ((sym (nth (random len) funsyms)))
  615. (format t "~s -> ~a~%" sym (mapcar #'car (list-callers sym))))))))
  616. ;; (test-list-callers 100)
  617. ;;;; Resolving source locations
  618. ;;;
  619. ;;; Our mission here is to "resolve" references to code locations into
  620. ;;; actual file/buffer names and character positions. The references
  621. ;;; we work from come out of the compiler's statically-generated debug
  622. ;;; information, such as `code-location''s and `debug-source''s. For
  623. ;;; more details, see the "Debugger Programmer's Interface" section of
  624. ;;; the CMUCL manual.
  625. ;;;
  626. ;;; The first step is usually to find the corresponding "source-path"
  627. ;;; for the location. Once we have the source-path we can pull up the
  628. ;;; source file and `READ' our way through to the right position. The
  629. ;;; main source-code groveling work is done in
  630. ;;; `swank-source-path-parser.lisp'.
  631. (defvar *debug-definition-finding* nil
  632. "When true don't handle errors while looking for definitions.
  633. This is useful when debugging the definition-finding code.")
  634. (defvar *source-snippet-size* 256
  635. "Maximum number of characters in a snippet of source code.
  636. Snippets at the beginning of definitions are used to tell Emacs what
  637. the definitions looks like, so that it can accurately find them by
  638. text search.")
  639. (defmacro safe-definition-finding (&body body)
  640. "Execute BODY and return the source-location it returns.
  641. If an error occurs and `*debug-definition-finding*' is false, then
  642. return an error pseudo-location.
  643. The second return value is NIL if no error occurs, otherwise it is the
  644. condition object."
  645. `(flet ((body () ,@body))
  646. (if *debug-definition-finding*
  647. (body)
  648. (handler-case (values (progn ,@body) nil)
  649. (error (c) (values `(:error ,(trim-whitespace (princ-to-string c)))
  650. c))))))
  651. (defun trim-whitespace (string)
  652. (string-trim #(#\newline #\space #\tab) string))
  653. (defun code-location-source-location (code-location)
  654. "Safe wrapper around `code-location-from-source-location'."
  655. (safe-definition-finding
  656. (source-location-from-code-location code-location)))
  657. (defun source-location-from-code-location (code-location)
  658. "Return the source location for CODE-LOCATION."
  659. (let ((debug-fun (di:code-location-debug-function code-location)))
  660. (when (di::bogus-debug-function-p debug-fun)
  661. ;; Those lousy cheapskates! They've put in a bogus debug source
  662. ;; because the code was compiled at a low debug setting.
  663. (error "Bogus debug function: ~A" debug-fun)))
  664. (let* ((debug-source (di:code-location-debug-source code-location))
  665. (from (di:debug-source-from debug-source))
  666. (name (di:debug-source-name debug-source)))
  667. (ecase from
  668. (:file
  669. (location-in-file name code-location debug-source))
  670. (:stream
  671. (location-in-stream code-location debug-source))
  672. (:lisp
  673. ;; The location comes from a form passed to `compile'.
  674. ;; The best we can do is return the form itself for printing.
  675. (make-location
  676. (list :source-form (with-output-to-string (*standard-output*)
  677. (debug::print-code-location-source-form
  678. code-location 100 t)))
  679. (list :position 1))))))
  680. (defun location-in-file (filename code-location debug-source)
  681. "Resolve the source location for CODE-LOCATION in FILENAME."
  682. (let* ((code-date (di:debug-source-created debug-source))
  683. (root-number (di:debug-source-root-number debug-source))
  684. (source-code (get-source-code filename code-date)))
  685. (with-input-from-string (s source-code)
  686. (make-location (list :file (unix-truename filename))
  687. (list :position (1+ (code-location-stream-position
  688. code-location s root-number)))
  689. `(:snippet ,(read-snippet s))))))
  690. (defun location-in-stream (code-location debug-source)
  691. "Resolve the source location for a CODE-LOCATION from a stream.
  692. This only succeeds if the code was compiled from an Emacs buffer."
  693. (unless (debug-source-info-from-emacs-buffer-p debug-source)
  694. (error "The code is compiled from a non-SLIME stream."))
  695. (let* ((info (c::debug-source-info debug-source))
  696. (string (getf info :emacs-buffer-string))
  697. (position (code-location-string-offset
  698. code-location
  699. string)))
  700. (make-location
  701. (list :buffer (getf info :emacs-buffer))
  702. (list :offset (getf info :emacs-buffer-offset) position)
  703. (list :snippet (with-input-from-string (s string)
  704. (file-position s position)
  705. (read-snippet s))))))
  706. ;;;;; Function-name locations
  707. ;;;
  708. (defun debug-info-function-name-location (debug-info)
  709. "Return a function-name source-location for DEBUG-INFO.
  710. Function-name source-locations are a fallback for when precise
  711. positions aren't available."
  712. (with-struct (c::debug-info- (fname name) source) debug-info
  713. (with-struct (c::debug-source- info from name) (car source)
  714. (ecase from
  715. (:file
  716. (make-location (list :file (namestring (truename name)))
  717. (list :function-name (string fname))))
  718. (:stream
  719. (assert (debug-source-info-from-emacs-buffer-p (car source)))
  720. (make-location (list :buffer (getf info :emacs-buffer))
  721. (list :function-name (string fname))))
  722. (:lisp
  723. (make-location (list :source-form (princ-to-string (aref name 0)))
  724. (list :position 1)))))))
  725. (defun debug-source-info-from-emacs-buffer-p (debug-source)
  726. "Does the `info' slot of DEBUG-SOURCE contain an Emacs buffer location?
  727. This is true for functions that were compiled directly from buffers."
  728. (info-from-emacs-buffer-p (c::debug-source-info debug-source)))
  729. (defun info-from-emacs-buffer-p (info)
  730. (and info
  731. (consp info)
  732. (eq :emacs-buffer (car info))))
  733. ;;;;; Groveling source-code for positions
  734. (defun code-location-stream-position (code-location stream root)
  735. "Return the byte offset of CODE-LOCATION in STREAM. Extract the
  736. toplevel-form-number and form-number from CODE-LOCATION and use that
  737. to find the position of the corresponding form.
  738. Finish with STREAM positioned at the start of the code location."
  739. (let* ((location (debug::maybe-block-start-location code-location))
  740. (tlf-offset (- (di:code-location-top-level-form-offset location)
  741. root))
  742. (form-number (di:code-location-form-number location)))
  743. (let ((pos (form-number-stream-position tlf-offset form-number stream)))
  744. (file-position stream pos)
  745. pos)))
  746. (defun form-number-stream-position (tlf-number form-number stream)
  747. "Return the starting character position of a form in STREAM.
  748. TLF-NUMBER is the top-level-form number.
  749. FORM-NUMBER is an index into a source-path table for the TLF."
  750. (multiple-value-bind (tlf position-map) (read-source-form tlf-number stream)
  751. (let* ((path-table (di:form-number-translations tlf 0))
  752. (source-path
  753. (if (<= (length path-table) form-number) ; source out of sync?
  754. (list 0) ; should probably signal a condition
  755. (reverse (cdr (aref path-table form-number))))))
  756. (source-path-source-position source-path tlf position-map))))
  757. (defun code-location-string-offset (code-location string)
  758. "Return the byte offset of CODE-LOCATION in STRING.
  759. See CODE-LOCATION-STREAM-POSITION."
  760. (with-input-from-string (s string)
  761. (code-location-stream-position code-location s 0)))
  762. ;;;; Finding definitions
  763. ;;; There are a great many different types of definition for us to
  764. ;;; find. We search for definitions of every kind and return them in a
  765. ;;; list.
  766. (defimplementation find-definitions (name)
  767. (append (function-definitions name)
  768. (setf-definitions name)
  769. (variable-definitions name)
  770. (class-definitions name)
  771. (type-definitions name)
  772. (compiler-macro-definitions name)
  773. (source-transform-definitions name)
  774. (function-info-definitions name)
  775. (ir1-translator-definitions name)
  776. (template-definitions name)
  777. (primitive-definitions name)
  778. (vm-support-routine-definitions name)
  779. ))
  780. ;;;;; Functions, macros, generic functions, methods
  781. ;;;
  782. ;;; We make extensive use of the compile-time debug information that
  783. ;;; CMUCL records, in particular "debug functions" and "code
  784. ;;; locations." Refer to the "Debugger Programmer's Interface" section
  785. ;;; of the CMUCL manual for more details.
  786. (defun function-definitions (name)
  787. "Return definitions for NAME in the \"function namespace\", i.e.,
  788. regular functions, generic functions, methods and macros.
  789. NAME can any valid function name (e.g, (setf car))."
  790. (let ((macro? (and (symbolp name) (macro-function name)))
  791. (function? (and (ext:valid-function-name-p name)
  792. (ext:info :function :definition name)
  793. (if (symbolp name) (fboundp name) t))))
  794. (cond (macro?
  795. (list `((defmacro ,name)
  796. ,(function-location (macro-function name)))))
  797. (function?
  798. (let ((function (fdefinition name)))
  799. (if (genericp function)
  800. (gf-definitions name function)
  801. (list (list `(function ,name)
  802. (function-location function)))))))))
  803. ;;;;;; Ordinary (non-generic/macro/special) functions
  804. ;;;
  805. ;;; First we test if FUNCTION is a closure created by defstruct, and
  806. ;;; if so extract the defstruct-description (`dd') from the closure
  807. ;;; and find the constructor for the struct. Defstruct creates a
  808. ;;; defun for the default constructor and we use that as an
  809. ;;; approximation to the source location of the defstruct.
  810. ;;;
  811. ;;; For an ordinary function we return the source location of the
  812. ;;; first code-location we find.
  813. ;;;
  814. (defun function-location (function)
  815. "Return the source location for FUNCTION."
  816. (cond ((struct-closure-p function)
  817. (struct-closure-location function))
  818. ((c::byte-function-or-closure-p function)
  819. (byte-function-location function))
  820. (t
  821. (compiled-function-location function))))
  822. (defun compiled-function-location (function)
  823. "Return the location of a regular compiled function."
  824. (multiple-value-bind (code-location error)
  825. (safe-definition-finding (function-first-code-location function))
  826. (cond (error (list :error (princ-to-string error)))
  827. (t (code-location-source-location code-location)))))
  828. (defun function-first-code-location (function)
  829. "Return the first code-location we can find for FUNCTION."
  830. (and (function-has-debug-function-p function)
  831. (di:debug-function-start-location
  832. (di:function-debug-function function))))
  833. (defun function-has-debug-function-p (function)
  834. (di:function-debug-function function))
  835. (defun function-code-object= (closure function)
  836. (and (eq (vm::find-code-object closure)
  837. (vm::find-code-object function))
  838. (not (eq closure function))))
  839. (defun byte-function-location (fun)
  840. "Return the location of the byte-compiled function FUN."
  841. (etypecase fun
  842. ((or c::hairy-byte-function c::simple-byte-function)
  843. (let* ((di (kernel:%code-debug-info (c::byte-function-component fun))))
  844. (if di
  845. (debug-info-function-name-location di)
  846. `(:error
  847. ,(format nil "Byte-function without debug-info: ~a" fun)))))
  848. (c::byte-closure
  849. (byte-function-location (c::byte-closure-function fun)))))
  850. ;;; Here we deal with structure accessors. Note that `dd' is a
  851. ;;; "defstruct descriptor" structure in CMUCL. A `dd' describes a
  852. ;;; `defstruct''d structure.
  853. (defun struct-closure-p (function)
  854. "Is FUNCTION a closure created by defstruct?"
  855. (or (function-code-object= function #'kernel::structure-slot-accessor)
  856. (function-code-object= function #'kernel::structure-slot-setter)
  857. (function-code-object= function #'kernel::%defstruct)))
  858. (defun struct-closure-location (function)
  859. "Return the location of the structure that FUNCTION belongs to."
  860. (assert (struct-closure-p function))
  861. (safe-definition-finding
  862. (dd-location (struct-closure-dd function))))
  863. (defun struct-closure-dd (function)
  864. "Return the defstruct-definition (dd) of FUNCTION."
  865. (assert (= (kernel:get-type function) vm:closure-header-type))
  866. (flet ((find-layout (function)
  867. (sys:find-if-in-closure
  868. (lambda (x)
  869. (let ((value (if (di::indirect-value-cell-p x)
  870. (c:value-cell-ref x)
  871. x)))
  872. (when (kernel::layout-p value)
  873. (return-from find-layout value))))
  874. function)))
  875. (kernel:layout-info (find-layout function))))
  876. (defun dd-location (dd)
  877. "Return the location of a `defstruct'."
  878. ;; Find the location in a constructor.
  879. (function-location (struct-constructor dd)))
  880. (defun struct-constructor (dd)
  881. "Return a constructor function from a defstruct definition.
  882. Signal an error if no constructor can be found."
  883. (let* ((constructor (or (kernel:dd-default-constructor dd)
  884. (car (kernel::dd-constructors dd))))
  885. (sym (if (consp constructor) (car constructor) constructor)))
  886. (unless sym
  887. (error "Cannot find structure's constructor: ~S" (kernel::dd-name dd)))
  888. (coerce sym 'function)))
  889. ;;;;;; Generic functions and methods
  890. (defun gf-definitions (name function)
  891. "Return the definitions of a generic function and its methods."
  892. (cons (list `(defgeneric ,name) (gf-location function))
  893. (gf-method-definitions function)))
  894. (defun gf-location (gf)
  895. "Return the location of the generic function GF."
  896. (definition-source-location gf (pcl::generic-function-name gf)))
  897. (defun gf-method-definitions (gf)
  898. "Return the locations of all methods of the generic function GF."
  899. (mapcar #'method-definition (pcl::generic-function-methods gf)))
  900. (defun method-definition (method)
  901. (list (method-dspec method)
  902. (method-location method)))
  903. (defun method-dspec (method)
  904. "Return a human-readable \"definition specifier\" for METHOD."
  905. (let* ((gf (pcl:method-generic-function method))
  906. (name (pcl:generic-function-name gf))
  907. (specializers (pcl:method-specializers method))
  908. (qualifiers (pcl:method-qualifiers method)))
  909. `(method ,name ,@qualifiers ,(pcl::unparse-specializers specializers))))
  910. ;; XXX maybe special case setters/getters
  911. (defun method-location (method)
  912. (function-location (or (pcl::method-fast-function method)
  913. (pcl:method-function method))))
  914. (defun genericp (fn)
  915. (typep fn 'generic-function))
  916. ;;;;;; Types and classes
  917. (defun type-definitions (name)
  918. "Return `deftype' locations for type NAME."
  919. (maybe-make-definition (ext:info :type :expander name) 'deftype name))
  920. (defun maybe-make-definition (function kind name)
  921. "If FUNCTION is non-nil then return its definition location."
  922. (if function
  923. (list (list `(,kind ,name) (function-location function)))))
  924. (defun class-definitions (name)
  925. "Return the definition locations for the class called NAME."
  926. (if (symbolp name)
  927. (let ((class (kernel::find-class name nil)))
  928. (etypecase class
  929. (null '())
  930. (kernel::structure-class
  931. (list (list `(defstruct ,name) (dd-location (find-dd name)))))
  932. #+(or)
  933. (conditions::condition-class
  934. (list (list `(define-condition ,name)
  935. (condition-class-location class))))
  936. (kernel::standard-class
  937. (list (list `(defclass ,name)
  938. (class-location (find-class name)))))
  939. ((or kernel::built-in-class
  940. conditions::condition-class
  941. kernel:funcallable-structure-class)
  942. (list (list `(kernel::define-type-class ,name)
  943. `(:error
  944. ,(format nil "No source info for ~A" name)))))))))
  945. (defun class-location (class)
  946. "Return the `defclass' location for CLASS."
  947. (definition-source-location class (pcl:class-name class)))
  948. (defun find-dd (name)
  949. "Find the defstruct-definition by the name of its structure-class."
  950. (let ((layout (ext:info :type :compiler-layout name)))
  951. (if layout
  952. (kernel:layout-info layout))))
  953. (defun condition-class-location (class)
  954. (let ((slots (conditions::condition-class-slots class))
  955. (name (conditions::condition-class-name class)))
  956. (cond ((null slots)
  957. `(:error ,(format nil "No location info for condition: ~A" name)))
  958. (t
  959. ;; Find the class via one of its slot-reader methods.
  960. (let* ((slot (first slots))
  961. (gf (fdefinition
  962. (first (conditions::condition-slot-readers slot)))))
  963. (method-location
  964. (first
  965. (pcl:compute-applicable-methods-using-classes
  966. gf (list (find-class name))))))))))
  967. (defun make-name-in-file-location (file string)
  968. (multiple-value-bind (filename c)
  969. (ignore-errors
  970. (unix-truename (merge-pathnames (make-pathname :type "lisp")
  971. file)))
  972. (cond (filename (make-location `(:file ,filename)
  973. `(:function-name ,(string string))))
  974. (t (list :error (princ-to-string c))))))
  975. (defun source-location-form-numbers (location)
  976. (c::decode-form-numbers (c::form-numbers-form-numbers location)))
  977. (defun source-location-tlf-number (location)
  978. (nth-value 0 (source-location-form-numbers location)))
  979. (defun source-location-form-number (location)
  980. (nth-value 1 (source-location-form-numbers location)))
  981. (defun resolve-file-source-location (location)
  982. (let ((filename (c::file-source-location-pathname location))
  983. (tlf-number (source-location-tlf-number location))
  984. (form-number (source-location-form-number location)))
  985. (with-open-file (s filename)
  986. (let ((pos (form-number-stream-position tlf-number form-number s)))
  987. (make-location `(:file ,(unix-truename filename))
  988. `(:position ,(1+ pos)))))))
  989. (defun resolve-stream-source-location (location)
  990. (let ((info (c::stream-source-location-user-info location))
  991. (tlf-number (source-location-tlf-number location))
  992. (form-number (source-location-form-number location)))
  993. ;; XXX duplication in frame-source-location
  994. (assert (info-from-emacs-buffer-p info))
  995. (destructuring-bind (&key emacs-buffer emacs-buffer-string
  996. emacs-buffer-offset) info
  997. (with-input-from-string (s emacs-buffer-string)
  998. (let ((pos (form-number-stream-position tlf-number form-number s)))
  999. (make-location `(:buffer ,emacs-buffer)
  1000. `(:offset ,emacs-buffer-offset ,pos)))))))
  1001. ;; XXX predicates for 18e backward compatibilty. Remove them when
  1002. ;; we're 19a only.
  1003. (defun file-source-location-p (object)
  1004. (when (fboundp 'c::file-source-location-p)
  1005. (c::file-source-location-p object)))
  1006. (defun stream-source-location-p (object)
  1007. (when (fboundp 'c::stream-source-location-p)
  1008. (c::stream-source-location-p object)))
  1009. (defun source-location-p (object)
  1010. (or (file-source-location-p object)
  1011. (stream-source-location-p object)))
  1012. (defun resolve-source-location (location)
  1013. (etypecase location
  1014. ((satisfies file-source-location-p)
  1015. (resolve-file-source-location location))
  1016. ((satisfies stream-source-location-p)
  1017. (resolve-stream-source-location location))))
  1018. (defun definition-source-location (object name)
  1019. (let ((source (pcl::definition-source object)))
  1020. (etypecase source
  1021. (null
  1022. `(:error ,(format nil "No source info for: ~A" object)))
  1023. ((satisfies source-location-p)
  1024. (resolve-source-location source))
  1025. (pathname
  1026. (make-name-in-file-location source name))
  1027. (cons
  1028. (destructuring-bind ((dg name) pathname) source
  1029. (declare (ignore dg))
  1030. (etypecase pathname
  1031. (pathname (make-name-in-file-location pathname (string name)))
  1032. (null `(:error ,(format nil "Cannot resolve: ~S" source)))))))))
  1033. (defun setf-definitions (name)
  1034. (let ((f (or (ext:info :setf :inverse name)
  1035. (ext:info :setf :expander name)
  1036. (and (symbolp name)
  1037. (fboundp `(setf ,name))
  1038. (fdefinition `(setf ,name))))))
  1039. (if f
  1040. `(((setf ,name) ,(function-location (cond ((functionp f) f)
  1041. ((macro-function f))
  1042. ((fdefinition f)))))))))
  1043. (defun variable-location (symbol)
  1044. (multiple-value-bind (location foundp)
  1045. ;; XXX for 18e compatibilty. rewrite this when we drop 18e
  1046. ;; support.
  1047. (ignore-errors (eval `(ext:info :source-location :defvar ',symbol)))
  1048. (if (and foundp location)
  1049. (resolve-source-location location)
  1050. `(:error ,(format nil "No source info for variable ~S" symbol)))))
  1051. (defun variable-definitions (name)
  1052. (if (symbolp name)
  1053. (multiple-value-bind (kind recorded-p) (ext:info :variable :kind name)
  1054. (if recorded-p
  1055. (list (list `(variable ,kind ,name)
  1056. (variable-location name)))))))
  1057. (defun compiler-macro-definitions (symbol)
  1058. (maybe-make-definition (compiler-macro-function symbol)
  1059. 'define-compiler-macro
  1060. symbol))
  1061. (defun source-transform-definitions (name)
  1062. (maybe-make-definition (ext:info :function :source-transform name)
  1063. 'c:def-source-transform
  1064. name))
  1065. (defun function-info-definitions (name)
  1066. (let ((info (ext:info :function :info name)))
  1067. (if info
  1068. (append (loop for transform in (c::function-info-transforms info)
  1069. collect (list `(c:deftransform ,name
  1070. ,(c::type-specifier
  1071. (c::transform-type transform)))
  1072. (function-location (c::transform-function
  1073. transform))))
  1074. (maybe-make-definition (c::function-info-derive-type info)
  1075. 'c::derive-type name)
  1076. (maybe-make-definition (c::function-info-optimizer info)
  1077. 'c::optimizer name)
  1078. (maybe-make-definition (c::function-info-ltn-annotate info)
  1079. 'c::ltn-annotate name)
  1080. (maybe-make-definition (c::function-info-ir2-convert info)
  1081. 'c::ir2-convert name)
  1082. (loop for template in (c::function-info-templates info)
  1083. collect (list `(,(type-of template)
  1084. ,(c::template-name template))
  1085. (function-location
  1086. (c::vop-info-generator-function
  1087. template))))))))
  1088. (defun ir1-translator-definitions (name)
  1089. (maybe-make-definition (ext:info :function :ir1-convert name)
  1090. 'c:def-ir1-translator name))
  1091. (defun template-definitions (name)
  1092. (let* ((templates (c::backend-template-names c::*backend*))
  1093. (template (gethash name templates)))
  1094. (etypecase template
  1095. (null)
  1096. (c::vop-info
  1097. (maybe-make-definition (c::vop-info-generator-function template)
  1098. (type-of template) name)))))
  1099. ;; for cases like: (%primitive NAME ...)
  1100. (defun primitive-definitions (name)
  1101. (let ((csym (find-symbol (string name) 'c)))
  1102. (and csym
  1103. (not (eq csym name))
  1104. (template-definitions csym))))
  1105. (defun vm-support-routine-definitions (name)
  1106. (let ((sr (c::backend-support-routines c::*backend*))
  1107. (name (find-symbol (string name) 'c)))
  1108. (and name
  1109. (slot-exists-p sr name)
  1110. (maybe-make-definition (slot-value sr name)
  1111. (find-symbol (string 'vm-support-routine) 'c)
  1112. name))))
  1113. ;;;; Documentation.
  1114. (defimplementation describe-symbol-for-emacs (symbol)
  1115. (let ((result '()))
  1116. (flet ((doc (kind)
  1117. (or (documentation symbol kind) :not-documented))
  1118. (maybe-push (property value)
  1119. (when value
  1120. (setf result (list* property value result)))))
  1121. (maybe-push
  1122. :variable (multiple-value-bind (kind recorded-p)
  1123. (ext:info variable kind symbol)
  1124. (declare (ignore kind))
  1125. (if (or (boundp symbol) recorded-p)
  1126. (doc 'variable))))
  1127. (when (fboundp symbol)
  1128. (maybe-push
  1129. (cond ((macro-function symbol) :macro)
  1130. ((special-operator-p symbol) :special-operator)
  1131. ((genericp (fdefinition symbol)) :generic-function)
  1132. (t :function))
  1133. (doc 'function)))
  1134. (maybe-push
  1135. :setf (if (or (ext:info setf inverse symbol)
  1136. (ext:info setf expander symbol))
  1137. (doc 'setf)))
  1138. (maybe-push
  1139. :type (if (ext:info type kind symbol)
  1140. (doc 'type)))
  1141. (maybe-push
  1142. :class (if (find-class symbol nil)
  1143. (doc 'class)))
  1144. (maybe-push
  1145. :alien-type (if (not (eq (ext:info alien-type kind symbol) :unknown))
  1146. (doc 'alien-type)))
  1147. (maybe-push
  1148. :alien-struct (if (ext:info alien-type struct symbol)
  1149. (doc nil)))
  1150. (maybe-push
  1151. :alien-union (if (ext:info alien-type union symbol)
  1152. (doc nil)))
  1153. (maybe-push
  1154. :alien-enum (if (ext:info alien-type enum symbol)
  1155. (doc nil)))
  1156. result)))
  1157. (defimplementation describe-definition (symbol namespace)
  1158. (describe (ecase namespace
  1159. (:variable
  1160. symbol)
  1161. ((:function :generic-function)
  1162. (symbol-function symbol))
  1163. (:setf
  1164. (or (ext:info setf inverse symbol)
  1165. (ext:info setf expander symbol)))
  1166. (:type
  1167. (kernel:values-specifier-type symbol))
  1168. (:class
  1169. (find-class symbol))
  1170. (:alien-struct
  1171. (ext:info :alien-type :struct symbol))
  1172. (:alien-union
  1173. (ext:info :alien-type :union symbol))
  1174. (:alien-enum
  1175. (ext:info :alien-type :enum symbol))
  1176. (:alien-type
  1177. (ecase (ext:info :alien-type :kind symbol)
  1178. (:primitive
  1179. (let ((alien::*values-type-okay* t))
  1180. (funcall (ext:info :alien-type :translator symbol)
  1181. (list symbol))))
  1182. ((:defined)
  1183. (ext:info :alien-type :definition symbol))
  1184. (:unknown :unkown))))))
  1185. ;;;;; Argument lists
  1186. (defimplementation arglist (fun)
  1187. (etypecase fun
  1188. (function (function-arglist fun))
  1189. (symbol (function-arglist (or (macro-function fun)
  1190. (symbol-function fun))))))
  1191. (defun function-arglist (fun)
  1192. (let ((arglist
  1193. (cond ((eval:interpreted-function-p fun)
  1194. (eval:interpreted-function-arglist fun))
  1195. ((pcl::generic-function-p fun)
  1196. (pcl:generic-function-lambda-list fun))
  1197. ((c::byte-function-or-closure-p fun)
  1198. (byte-code-function-arglist fun))
  1199. ((kernel:%function-arglist (kernel:%function-self fun))
  1200. (handler-case (read-arglist fun)
  1201. (error () :not-available)))
  1202. ;; this should work both for compiled-debug-function
  1203. ;; and for interpreted-debug-function
  1204. (t
  1205. (handler-case (debug-function-arglist
  1206. (di::function-debug-function fun))
  1207. (di:unhandled-condition () :not-available))))))
  1208. (check-type arglist (or list (member :not-available)))
  1209. arglist))
  1210. (defimplementation function-name (function)
  1211. (cond ((eval:interpreted-function-p function)
  1212. (eval:interpreted-function-name function))
  1213. ((pcl::generic-function-p function)
  1214. (pcl::generic-function-name function))
  1215. ((c::byte-function-or-closure-p function)
  1216. (c::byte-function-name function))
  1217. (t (kernel:%function-name (kernel:%function-self function)))))
  1218. ;;; A simple case: the arglist is available as a string that we can
  1219. ;;; `read'.
  1220. (defun read-arglist (fn)
  1221. "Parse the arglist-string of the function object FN."
  1222. (let ((string (kernel:%function-arglist
  1223. (kernel:%function-self fn)))
  1224. (package (find-package
  1225. (c::compiled-debug-info-package
  1226. (kernel:%code-debug-info
  1227. (vm::find-code-object fn))))))
  1228. (with-standard-io-syntax
  1229. (let ((*package* (or package *package*)))
  1230. (read-from-string string)))))
  1231. ;;; A harder case: an approximate arglist is derived from available
  1232. ;;; debugging information.
  1233. (defun debug-function-arglist (debug-function)
  1234. "Derive the argument list of DEBUG-FUNCTION from debug info."
  1235. (let ((args (di::debug-function-lambda-list debug-function))
  1236. (required '())
  1237. (optional '())
  1238. (rest '())
  1239. (key '()))
  1240. ;; collect the names of debug-vars
  1241. (dolist (arg args)
  1242. (etypecase arg
  1243. (di::debug-variable
  1244. (push (di::debug-variable-symbol arg) required))
  1245. ((member :deleted)
  1246. (push ':deleted required))
  1247. (cons
  1248. (ecase (car arg)
  1249. (:keyword
  1250. (push (second arg) key))
  1251. (:optional
  1252. (push (debug-variable-symbol-or-deleted (second arg)) optional))
  1253. (:rest
  1254. (push (debug-variable-symbol-or-deleted (second arg)) rest))))))
  1255. ;; intersperse lambda keywords as needed
  1256. (append (nreverse required)
  1257. (if optional (cons '&optional (nreverse optional)))
  1258. (if rest (cons '&rest (nreverse rest)))
  1259. (if key (cons '&key (nreverse key))))))
  1260. (defun debug-variable-symbol-or-deleted (var)
  1261. (etypecase var
  1262. (di:debug-variable
  1263. (di::debug-variable-symbol var))
  1264. ((member :deleted)
  1265. '#:deleted)))
  1266. (defun symbol-debug-function-arglist (fname)
  1267. "Return FNAME's debug-function-arglist and %function-arglist.
  1268. A utility for debugging DEBUG-FUNCTION-ARGLIST."
  1269. (let ((fn (fdefinition fname)))
  1270. (values (debug-function-arglist (di::function-debug-function fn))
  1271. (kernel:%function-arglist (kernel:%function-self fn)))))
  1272. ;;; Deriving arglists for byte-compiled functions:
  1273. ;;;
  1274. (defun byte-code-function-arglist (fn)
  1275. ;; There doesn't seem to be much arglist information around for
  1276. ;; byte-code functions. Use the arg-count and return something like
  1277. ;; (arg0 arg1 ...)
  1278. (etypecase fn
  1279. (c::simple-byte-function
  1280. (loop for i from 0 below (c::simple-byte-function-num-args fn)
  1281. collect (make-arg-symbol i)))
  1282. (c::hairy-byte-function
  1283. (hairy-byte-function-arglist fn))
  1284. (c::byte-closure
  1285. (byte-code-function-arglist (c::byte-closure-function fn)))))
  1286. (defun make-arg-symbol (i)
  1287. (make-symbol (format nil "~A~D" (string 'arg) i)))
  1288. ;;; A "hairy" byte-function is one that takes a variable number of
  1289. ;;; arguments. `hairy-byte-function' is a type from the bytecode
  1290. ;;; interpreter.
  1291. ;;;
  1292. (defun hairy-byte-function-arglist (fn)
  1293. (let ((counter -1))
  1294. (flet ((next-arg () (make-arg-symbol (incf counter))))
  1295. (with-struct (c::hairy-byte-function- min-args max-args rest-arg-p
  1296. keywords-p keywords) fn
  1297. (let ((arglist '())
  1298. (optional (- max-args min-args)))
  1299. ;; XXX isn't there a better way to write this?
  1300. ;; (Looks fine to me. -luke)
  1301. (dotimes (i min-args)
  1302. (push (next-arg) arglist))
  1303. (when (plusp optional)
  1304. (push '&optional arglist)
  1305. (dotimes (i optional)
  1306. (push (next-arg) arglist)))
  1307. (when rest-arg-p
  1308. (push '&rest arglist)
  1309. (push (next-arg) arglist))
  1310. (when keywords-p
  1311. (push '&key arglist)
  1312. (loop for (key _ __) in keywords
  1313. do (push key arglist))
  1314. (when (eq keywords-p :allow-others)
  1315. (push '&allow-other-keys arglist)))
  1316. (nreverse arglist))))))
  1317. ;;;; Miscellaneous.
  1318. (defimplementation macroexpand-all (form)
  1319. (walker:macroexpand-all form))
  1320. (defimplementation compiler-macroexpand-1 (form &optional env)
  1321. (ext:compiler-macroexpand-1 form env))
  1322. (defimplementation compiler-macroexpand (form &optional env)
  1323. (ext:compiler-macroexpand form env))
  1324. (defimplementation set-default-directory (directory)
  1325. (setf (ext:default-directory) (namestring directory))
  1326. ;; Setting *default-pathname-defaults* to an absolute directory
  1327. ;; makes the behavior of MERGE-PATHNAMES a bit more intuitive.
  1328. (setf *default-pathname-defaults* (pathname (ext:default-directory)))
  1329. (default-directory))
  1330. (defimplementation default-directory ()
  1331. (namestring (ext:default-directory)))
  1332. (defimplementation getpid ()
  1333. (unix:unix-getpid))
  1334. (defimplementation lisp-implementation-type-name ()
  1335. "cmucl")
  1336. (defimplementation quit-lisp ()
  1337. (ext::quit))
  1338. ;;; source-path-{stream,file,string,etc}-position moved into
  1339. ;;; swank-source-path-parser
  1340. ;;;; Debugging
  1341. (defvar *sldb-stack-top*)
  1342. (defimplementation call-with-debugging-environment (debugger-loop-fn)
  1343. (unix:unix-sigsetmask 0)
  1344. (let* ((*sldb-stack-top* (or debug:*stack-top-hint* (di:top-frame)))
  1345. (debug:*stack-top-hint* nil)
  1346. (kernel:*current-level* 0))
  1347. (handler-bind ((di::unhandled-condition
  1348. (lambda (condition)
  1349. (error (make-condition
  1350. 'sldb-condition
  1351. :original-condition condition)))))
  1352. (unwind-protect
  1353. (progn
  1354. #+(or)(sys:scrub-control-stack)
  1355. (funcall debugger-loop-fn))
  1356. #+(or)(sys:scrub-control-stack)
  1357. ))))
  1358. (defun frame-down (frame)
  1359. (handler-case (di:frame-down frame)
  1360. (di:no-debug-info () nil)))
  1361. (defun nth-frame (index)
  1362. (do ((frame *sldb-stack-top* (frame-down frame))
  1363. (i index (1- i)))
  1364. ((zerop i) frame)))
  1365. (defimplementation compute-backtrace (start end)
  1366. (let ((end (or end most-positive-fixnum)))
  1367. (loop for f = (nth-frame start) then (frame-down f)
  1368. for i from start below end
  1369. while f collect f)))
  1370. (defimplementation print-frame (frame stream)
  1371. (let ((*standard-output* stream))
  1372. (handler-case
  1373. (debug::print-frame-call frame :verbosity 1 :number nil)
  1374. (error (e)
  1375. (ignore-errors (princ e stream))))))
  1376. (defimplementation frame-source-location (index)
  1377. (let ((frame (nth-frame index)))
  1378. (cond ((foreign-frame-p frame) (foreign-frame-source-location frame))
  1379. ((code-location-source-location (di:frame-code-location frame))))))
  1380. (defimplementation eval-in-frame (form index)
  1381. (di:eval-in-frame (nth-frame index) form))
  1382. (defun frame-debug-vars (frame)
  1383. "Return a vector of debug-variables in frame."
  1384. (let ((loc (di:frame-code-location frame)))
  1385. (remove-if
  1386. (lambda (v)
  1387. (not (eq (di:debug-variable-validity v loc) :valid)))
  1388. (di::debug-function-debug-variables (di:frame-debug-function frame)))))
  1389. (defun debug-var-value (var frame)
  1390. (let* ((loc (di:frame-code-location frame))
  1391. (validity (di:debug-variable-validity var loc)))
  1392. (ecase validity
  1393. (:valid (di:debug-variable-value var frame))
  1394. ((:invalid :unknown) (make-symbol (string validity))))))
  1395. (defimplementation frame-locals (index)
  1396. (let ((frame (nth-frame index)))
  1397. (loop for v across (frame-debug-vars frame)
  1398. collect (list :name (di:debug-variable-symbol v)
  1399. :id (di:debug-variable-id v)
  1400. :value (debug-var-value v frame)))))
  1401. (defimplementation frame-var-value (frame var)
  1402. (let* ((frame (nth-frame frame))
  1403. (dvar (aref (frame-debug-vars frame) var)))
  1404. (debug-var-value dvar frame)))
  1405. (defimplementation frame-catch-tags (index)
  1406. (mapcar #'car (di:frame-catches (nth-frame index))))
  1407. (defimplementation return-from-frame (index form)
  1408. (let ((sym (find-symbol (string 'find-debug-tag-for-frame)
  1409. :debug-internals)))
  1410. (if sym
  1411. (let* ((frame (nth-frame index))
  1412. (probe (funcall sym frame)))
  1413. (cond (probe (throw (car probe) (eval-in-frame form index)))
  1414. (t (format nil "Cannot return from frame: ~S" frame))))
  1415. "return-from-frame is not implemented in this version of CMUCL.")))
  1416. (defimplementation activate-stepping (frame)
  1417. (set-step-breakpoints (nth-frame frame)))
  1418. (defimplementation sldb-break-on-return (frame)
  1419. (break-on-return (nth-frame frame)))
  1420. ;;; We set the breakpoint in the caller which might be a bit confusing.
  1421. ;;;
  1422. (defun break-on-return (frame)
  1423. (let* ((caller (di:frame-down frame))
  1424. (cl (di:frame-code-location caller)))
  1425. (flet ((hook (frame bp)
  1426. (when (frame-pointer= frame caller)
  1427. (di:delete-breakpoint bp)
  1428. (signal-breakpoint bp frame))))
  1429. (let* ((info (ecase (di:code-location-kind cl)
  1430. ((:single-value-return :unknown-return) nil)
  1431. (:known-return (debug-function-returns
  1432. (di:frame-debug-function frame)))))
  1433. (bp (di:make-breakpoint #'hook cl :kind :code-location
  1434. :info info)))
  1435. (di:activate-breakpoint bp)
  1436. `(:ok ,(format nil "Set breakpoint in ~A" caller))))))
  1437. (defun frame-pointer= (frame1 frame2)
  1438. "Return true if the frame pointers of FRAME1 and FRAME2 are the same."
  1439. (sys:sap= (di::frame-pointer frame1) (di::frame-pointer frame2)))
  1440. ;;; The PC in escaped frames at a single-return-value point is
  1441. ;;; actually vm:single-value-return-byte-offset bytes after the
  1442. ;;; position given in the debug info. Here we try to recognize such
  1443. ;;; cases.
  1444. ;;;
  1445. (defun next-code-locations (frame code-location)
  1446. "Like `debug::next-code-locations' but be careful in escaped frames."
  1447. (let ((next (debug::next-code-locations code-location)))
  1448. (flet ((adjust-pc ()
  1449. (let ((cl (di::copy-compiled-code-location code-location)))
  1450. (incf (di::compiled-code-location-pc cl)
  1451. vm:single-value-return-byte-offset)
  1452. cl)))
  1453. (cond ((and (di::compiled-frame-escaped frame)
  1454. (eq (di:code-location-kind code-location)
  1455. :single-value-return)
  1456. (= (length next) 1)
  1457. (di:code-location= (car next) (adjust-pc)))
  1458. (debug::next-code-locations (car next)))
  1459. (t
  1460. next)))))
  1461. (defun set-step-breakpoints (frame)
  1462. (let ((cl (di:frame-code-location frame)))
  1463. (when (di:debug-block-elsewhere-p (di:code-location-debug-block cl))
  1464. (error "Cannot step in elsewhere code"))
  1465. (let* ((debug::*bad-code-location-types*
  1466. (remove :call-site debug::*bad-code-location-types*))
  1467. (next (next-code-locations frame cl)))
  1468. (cond (next
  1469. (let ((steppoints '()))
  1470. (flet ((hook (bp-frame bp)
  1471. (signal-breakpoint bp bp-frame)
  1472. (mapc #'di:delete-breakpoint steppoints)))
  1473. (dolist (code-location next)
  1474. (let ((bp (di:make-breakpoint #'hook code-location
  1475. :kind :code-location)))
  1476. (di:activate-breakpoint bp)
  1477. (push bp steppoints))))))
  1478. (t
  1479. (break-on-return frame))))))
  1480. ;; XXX the return values at return breakpoints should be passed to the
  1481. ;; user hooks. debug-int.lisp should be changed to do this cleanly.
  1482. ;;; The sigcontext and the PC for a breakpoint invocation are not
  1483. ;;; passed to user hook functions, but we need them to extract return
  1484. ;;; values. So we advice di::handle-breakpoint and bind the values to
  1485. ;;; special variables.
  1486. ;;;
  1487. (defvar *breakpoint-sigcontext*)
  1488. (defvar *breakpoint-pc*)
  1489. ;; XXX don't break old versions without fwrappers. Remove this one day.
  1490. #+#.(cl:if (cl:find-package :fwrappers) '(and) '(or))
  1491. (progn
  1492. (fwrappers:define-fwrapper bind-breakpoint-sigcontext (offset c sigcontext)
  1493. (let ((*breakpoint-sigcontext* sigcontext)
  1494. (*breakpoint-pc* offset))
  1495. (fwrappers:call-next-function)))
  1496. (fwrappers:set-fwrappers 'di::handle-breakpoint '())
  1497. (fwrappers:fwrap 'di::handle-breakpoint #'bind-breakpoint-sigcontext))
  1498. (defun sigcontext-object (sc index)
  1499. "Extract the lisp object in sigcontext SC at offset INDEX."
  1500. (kernel:make-lisp-obj (vm:sigcontext-register sc index)))
  1501. (defun known-return-point-values (sigcontext sc-offsets)
  1502. (let ((fp (system:int-sap (vm:sigcontext-register sigcontext
  1503. vm::cfp-offset))))
  1504. (system:without-gcing
  1505. (loop for sc-offset across sc-offsets
  1506. collect (di::sub-access-debug-var-slot fp sc-offset sigcontext)))))
  1507. ;;; CMUCL returns the first few values in registers and the rest on
  1508. ;;; the stack. In the multiple value case, the number of values is
  1509. ;;; stored in a dedicated register. The values of the registers can be
  1510. ;;; accessed in the sigcontext for the breakpoint. There are 3 kinds
  1511. ;;; of return conventions: :single-value-return, :unknown-return, and
  1512. ;;; :known-return.
  1513. ;;;
  1514. ;;; The :single-value-return convention returns the value in a
  1515. ;;; register without setting the nargs registers.
  1516. ;;;
  1517. ;;; The :unknown-return variant is used for multiple values. A
  1518. ;;; :unknown-return point consists actually of 2 breakpoints: one for
  1519. ;;; the single value case and one for the general case. The single
  1520. ;;; value breakpoint comes vm:single-value-return-byte-offset after
  1521. ;;; the multiple value breakpoint.
  1522. ;;;
  1523. ;;; The :known-return convention is used by local functions.
  1524. ;;; :known-return is currently not supported because we don't know
  1525. ;;; where the values are passed.
  1526. ;;;
  1527. (defun breakpoint-values (breakpoint)
  1528. "Return the list of return values for a return point."
  1529. (flet ((1st (sc) (sigcontext-object sc (car vm::register-arg-offsets))))
  1530. (let ((sc (locally (declare (optimize (speed 0)))
  1531. (alien:sap-alien *breakpoint-sigcontext* (* unix:sigcontext))))
  1532. (cl (di:breakpoint-what breakpoint)))
  1533. (ecase (di:code-location-kind cl)
  1534. (:single-value-return
  1535. (list (1st sc)))
  1536. (:known-return
  1537. (let ((info (di:breakpoint-info breakpoint)))
  1538. (if (vectorp info)
  1539. (known-return-point-values sc info)
  1540. (progn
  1541. ;;(break)
  1542. (list "<<known-return convention not supported>>" info)))))
  1543. (:unknown-return
  1544. (let ((mv-return-pc (di::compiled-code-location-pc cl)))
  1545. (if (= mv-return-pc *breakpoint-pc*)
  1546. (mv-function-end-breakpoint-values sc)
  1547. (list (1st sc)))))))))
  1548. ;; XXX: di::get-function-end-breakpoint-values takes 2 arguments in
  1549. ;; newer versions of CMUCL (after ~March 2005).
  1550. (defun mv-function-end-breakpoint-values (sigcontext)
  1551. (let ((sym (find-symbol "FUNCTION-END-BREAKPOINT-VALUES/STANDARD" :di)))
  1552. (cond (sym (funcall sym sigcontext))
  1553. (t (funcall 'di::get-function-end-breakpoint-values sigcontext)))))
  1554. (defun debug-function-returns (debug-fun)
  1555. "Return the return style of DEBUG-FUN."
  1556. (let* ((cdfun (di::compiled-debug-function-compiler-debug-fun debug-fun)))
  1557. (c::compiled-debug-function-returns cdfun)))
  1558. (define-condition breakpoint (simple-condition)
  1559. ((message :initarg :message :reader breakpoint.message)
  1560. (values :initarg :values :reader breakpoint.values))
  1561. (:report (lambda (c stream) (princ (breakpoint.message c) stream))))
  1562. (defimplementation condition-extras (condition)
  1563. (typecase condition
  1564. (breakpoint
  1565. ;; pop up the source buffer
  1566. `((:show-frame-source 0)))
  1567. (t '())))
  1568. (defun signal-breakpoint (breakpoint frame)
  1569. "Signal a breakpoint condition for BREAKPOINT in FRAME.
  1570. Try to create a informative message."
  1571. (flet ((brk (values fstring &rest args)
  1572. (let ((msg (apply #'format nil fstring args))
  1573. (debug:*stack-top-hint* frame))
  1574. (break 'breakpoint :message msg :values values))))
  1575. (with-struct (di::breakpoint- kind what) breakpoint
  1576. (case kind
  1577. (:code-location
  1578. (case (di:code-location-kind what)
  1579. ((:single-value-return :known-return :unknown-return)
  1580. (let ((values (breakpoint-values breakpoint)))
  1581. (brk values "Return value: ~{~S ~}" values)))
  1582. (t
  1583. #+(or)
  1584. (when (eq (di:code-location-kind what) :call-site)
  1585. (call-site-function breakpoint frame))
  1586. (brk nil "Breakpoint: ~S ~S"
  1587. (di:code-location-kind what)
  1588. (di::compiled-code-location-pc what)))))
  1589. (:function-start
  1590. (brk nil "Function start breakpoint"))
  1591. (t (brk nil "Breakpoint: ~A in ~A" breakpoint frame))))))
  1592. (defimplementation sldb-break-at-start (fname)
  1593. (let ((debug-fun (di:function-debug-function (coerce fname 'function))))
  1594. (cond ((not debug-fun)
  1595. `(:error ,(format nil "~S has no debug-function" fname)))
  1596. (t
  1597. (flet ((hook (frame bp &optional args cookie)
  1598. (declare (ignore args cookie))
  1599. (signal-breakpoint bp frame)))
  1600. (let ((bp (di:make-breakpoint #'hook debug-fun
  1601. :kind :function-start)))
  1602. (di:activate-breakpoint bp)
  1603. `(:ok ,(format nil "Set breakpoint in ~S" fname))))))))
  1604. (defun frame-cfp (frame)
  1605. "Return the Control-Stack-Frame-Pointer for FRAME."
  1606. (etypecase frame
  1607. (di::compiled-frame (di::frame-pointer frame))
  1608. ((or di::interpreted-frame null) -1)))
  1609. (defun frame-ip (frame)
  1610. "Return the (absolute) instruction pointer and the relative pc of FRAME."
  1611. (if (not frame)
  1612. -1
  1613. (let ((debug-fun (di::frame-debug-function frame)))
  1614. (etypecase debug-fun
  1615. (di::compiled-debug-function
  1616. (let* ((code-loc (di:frame-code-location frame))
  1617. (component (di::compiled-debug-function-component debug-fun))
  1618. (pc (di::compiled-code-location-pc code-loc))
  1619. (ip (sys:without-gcing
  1620. (sys:sap-int
  1621. (sys:sap+ (kernel:code-instructions component) pc)))))
  1622. (values ip pc)))
  1623. (di::interpreted-debug-function -1)
  1624. (di::bogus-debug-function
  1625. #-x86
  1626. (let* ((real (di::frame-real-frame (di::frame-up frame)))
  1627. (fp (di::frame-pointer real)))
  1628. ;;#+(or)
  1629. (progn
  1630. (format *debug-io* "Frame-real-frame = ~S~%" real)
  1631. (format *debug-io* "fp = ~S~%" fp)
  1632. (format *debug-io* "lra = ~S~%"
  1633. (kernel:stack-ref fp vm::lra-save-offset)))
  1634. (values
  1635. (sys:int-sap
  1636. (- (kernel:get-lisp-obj-address
  1637. (kernel:stack-ref fp vm::lra-save-offset))
  1638. (- (ash vm:function-code-offset vm:word-shift)
  1639. vm:function-pointer-type)))
  1640. 0))
  1641. #+x86
  1642. (let ((fp (di::frame-pointer (di:frame-up frame))))
  1643. (multiple-value-bind (ra ofp) (di::x86-call-context fp)
  1644. (declare (ignore ofp))
  1645. (values ra 0))))))))
  1646. (defun frame-registers (frame)
  1647. "Return the lisp registers CSP, CFP, IP, OCFP, LRA for FRAME-NUMBER."
  1648. (let* ((cfp (frame-cfp frame))
  1649. (csp (frame-cfp (di::frame-up frame)))
  1650. (ip (frame-ip frame))
  1651. (ocfp (frame-cfp (di::frame-down frame)))
  1652. (lra (frame-ip (di::frame-down frame))))
  1653. (values csp cfp ip ocfp lra)))
  1654. (defun print-frame-registers (frame-number)
  1655. (let ((frame (di::frame-real-frame (nth-frame frame-number))))
  1656. (flet ((fixnum (p) (etypecase p
  1657. (integer p)
  1658. (sys:system-area-pointer (sys:sap-int p)))))
  1659. (apply #'format t "~
  1660. ~8X Stack Pointer
  1661. ~8X Frame Pointer
  1662. ~8X Instruction Pointer
  1663. ~8X Saved Frame Pointer
  1664. ~8X Saved Instruction Pointer~%" (mapcar #'fixnum
  1665. (multiple-value-list (frame-registers frame)))))))
  1666. (defvar *gdb-program-name*
  1667. (ext:enumerate-search-list (p "path:gdb")
  1668. (when (probe-file p)
  1669. (return p))))
  1670. (defimplementation disassemble-frame (frame-number)
  1671. (print-frame-registers frame-number)
  1672. (terpri)
  1673. (let* ((frame (di::frame-real-frame (nth-frame frame-number)))
  1674. (debug-fun (di::frame-debug-function frame)))
  1675. (etypecase debug-fun
  1676. (di::compiled-debug-function
  1677. (let* ((component (di::compiled-debug-function-component debug-fun))
  1678. (fun (di:debug-function-function debug-fun)))
  1679. (if fun
  1680. (disassemble fun)
  1681. (disassem:disassemble-code-component component))))
  1682. (di::bogus-debug-function
  1683. (cond ((probe-file *gdb-program-name*)
  1684. (let ((ip (sys:sap-int (frame-ip frame))))
  1685. (princ (gdb-command "disas 0x~x" ip))))
  1686. (t
  1687. (format t "~%[Disassembling bogus frames not implemented]")))))))
  1688. (defmacro with-temporary-file ((stream filename) &body body)
  1689. `(call/temporary-file (lambda (,stream ,filename) . ,body)))
  1690. (defun call/temporary-file (fun)
  1691. (let ((name (system::pick-temporary-file-name)))
  1692. (unwind-protect
  1693. (with-open-file (stream name :direction :output :if-exists :supersede)
  1694. (funcall fun stream name))
  1695. (delete-file name))))
  1696. (defun gdb-command (format-string &rest args)
  1697. (let ((str (gdb-exec (format nil
  1698. "interpreter-exec mi2 \"attach ~d\"~%~
  1699. interpreter-exec console ~s~%detach"
  1700. (getpid)
  1701. (apply #'format nil format-string args))))
  1702. (prompt (format nil
  1703. #-(and darwin x86) "~%^done~%(gdb) ~%"
  1704. #+(and darwin x86)
  1705. "~%^done,thread-id=\"1\"~%(gdb) ~%")))
  1706. (subseq str (+ (or (search prompt str) 0) (length prompt)))))
  1707. (defun gdb-exec (cmd)
  1708. (with-temporary-file (file filename)
  1709. (write-string cmd file)
  1710. (force-output file)
  1711. (let* ((output (make-string-output-stream))
  1712. ;; gdb on sparc needs to know the executable to find the
  1713. ;; symbols. Without this, gdb can't disassemble anything.
  1714. ;; NOTE: We assume that the first entry in
  1715. ;; lisp::*cmucl-lib* is the bin directory where lisp is
  1716. ;; located. If this is not true, we'll have to do
  1717. ;; something better to find the lisp executable.
  1718. (lisp-path
  1719. #+sparc
  1720. (list
  1721. (namestring
  1722. (probe-file
  1723. (merge-pathnames "lisp" (car (lisp::parse-unix-search-path
  1724. lisp::*cmucl-lib*))))))
  1725. #-sparc
  1726. nil)
  1727. (proc (ext:run-program *gdb-program-name*
  1728. `(,@lisp-path "-batch" "-x" ,filename)
  1729. :wait t
  1730. :output output)))
  1731. (assert (eq (ext:process-status proc) :exited))
  1732. (assert (eq (ext:process-exit-code proc) 0))
  1733. (get-output-stream-string output))))
  1734. (defun foreign-frame-p (frame)
  1735. #-x86
  1736. (let ((ip (frame-ip frame)))
  1737. (and (sys:system-area-pointer-p ip)
  1738. (typep (di::frame-debug-function frame) 'di::bogus-debug-function)))
  1739. #+x86
  1740. (let ((ip (frame-ip frame)))
  1741. (and (sys:system-area-pointer-p ip)
  1742. (multiple-value-bind (pc code)
  1743. (di::compute-lra-data-from-pc ip)
  1744. (declare (ignore pc))
  1745. (not code)))))
  1746. (defun foreign-frame-source-location (frame)
  1747. (let ((ip (sys:sap-int (frame-ip frame))))
  1748. (cond ((probe-file *gdb-program-name*)
  1749. (parse-gdb-line-info (gdb-command "info line *0x~x" ip)))
  1750. (t `(:error "no srcloc available for ~a" frame)))))
  1751. ;; The output of gdb looks like:
  1752. ;; Line 215 of "../../src/lisp/x86-assem.S"
  1753. ;; starts at address 0x805318c <Ldone+11>
  1754. ;; and ends at 0x805318e <Ldone+13>.
  1755. ;; The ../../ are fixed up with the "target:" search list which might
  1756. ;; be wrong sometimes.
  1757. (defun parse-gdb-line-info (string)
  1758. (with-input-from-string (*standard-input* string)
  1759. (let ((w1 (read-word)))
  1760. (cond ((equal w1 "Line")
  1761. (let ((line (read-word)))
  1762. (assert (equal (read-word) "of"))
  1763. (let* ((file (read-from-string (read-word)))
  1764. (pathname
  1765. (or (probe-file file)
  1766. (probe-file (format nil "target:lisp/~a" file))
  1767. file)))
  1768. (make-location (list :file (unix-truename pathname))
  1769. (list :line (parse-integer line))))))
  1770. (t
  1771. `(:error ,string))))))
  1772. (defun read-word (&optional (stream *standard-input*))
  1773. (peek-char t stream)
  1774. (concatenate 'string (loop until (whitespacep (peek-char nil stream))
  1775. collect (read-char stream))))
  1776. (defun whitespacep (char)
  1777. (member char '(#\space #\newline)))
  1778. ;;;; Inspecting
  1779. (defconstant +lowtag-symbols+
  1780. '(vm:even-fixnum-type
  1781. vm:function-pointer-type
  1782. vm:other-immediate-0-type
  1783. vm:list-pointer-type
  1784. vm:odd-fixnum-type
  1785. vm:instance-pointer-type
  1786. vm:other-immediate-1-type
  1787. vm:other-pointer-type)
  1788. "Names of the constants that specify type tags.
  1789. The `symbol-value' of each element is a type tag.")
  1790. (defconstant +header-type-symbols+
  1791. (labels ((suffixp (suffix string)
  1792. (and (>= (length string) (length suffix))
  1793. (string= string suffix :start1 (- (length string)
  1794. (length suffix)))))
  1795. (header-type-symbol-p (x)
  1796. (and (suffixp "-TYPE" (symbol-name x))
  1797. (not (member x +lowtag-symbols+))
  1798. (boundp x)
  1799. (typep (symbol-value x) 'fixnum))))
  1800. (remove-if-not #'header-type-symbol-p
  1801. (append (apropos-list "-TYPE" "VM")
  1802. (apropos-list "-TYPE" "BIGNUM"))))
  1803. "A list of names of the type codes in boxed objects.")
  1804. (defimplementation describe-primitive-type (object)
  1805. (with-output-to-string (*standard-output*)
  1806. (let* ((lowtag (kernel:get-lowtag object))
  1807. (lowtag-symbol (find lowtag +lowtag-symbols+ :key #'symbol-value)))
  1808. (format t "lowtag: ~A" lowtag-symbol)
  1809. (when (member lowtag (list vm:other-pointer-type
  1810. vm:function-pointer-type
  1811. vm:other-immediate-0-type
  1812. vm:other-immediate-1-type
  1813. ))
  1814. (let* ((type (kernel:get-type object))
  1815. (type-symbol (find type +header-type-symbols+
  1816. :key #'symbol-value)))
  1817. (format t ", type: ~A" type-symbol))))))
  1818. (defmethod emacs-inspect ((o t))
  1819. (cond ((di::indirect-value-cell-p o)
  1820. `("Value: " (:value ,(c:value-cell-ref o))))
  1821. ((alien::alien-value-p o)
  1822. (inspect-alien-value o))
  1823. (t
  1824. (cmucl-inspect o))))
  1825. (defun cmucl-inspect (o)
  1826. (destructuring-bind (text labeledp . parts) (inspect::describe-parts o)
  1827. (list* (format nil "~A~%" text)
  1828. (if labeledp
  1829. (loop for (label . value) in parts
  1830. append (label-value-line label value))
  1831. (loop for value in parts for i from 0
  1832. append (label-value-line i value))))))
  1833. (defmethod emacs-inspect ((o function))
  1834. (let ((header (kernel:get-type o)))
  1835. (cond ((= header vm:function-header-type)
  1836. (append (label-value-line*
  1837. ("Self" (kernel:%function-self o))
  1838. ("Next" (kernel:%function-next o))
  1839. ("Name" (kernel:%function-name o))
  1840. ("Arglist" (kernel:%function-arglist o))
  1841. ("Type" (kernel:%function-type o))
  1842. ("Code" (kernel:function-code-header o)))
  1843. (list
  1844. (with-output-to-string (s)
  1845. (disassem:disassemble-function o :stream s)))))
  1846. ((= header vm:closure-header-type)
  1847. (list* (format nil "~A is a closure.~%" o)
  1848. (append
  1849. (label-value-line "Function" (kernel:%closure-function o))
  1850. `("Environment:" (:newline))
  1851. (loop for i from 0 below (1- (kernel:get-closure-length o))
  1852. append (label-value-line
  1853. i (kernel:%closure-index-ref o i))))))
  1854. ((eval::interpreted-function-p o)
  1855. (cmucl-inspect o))
  1856. (t
  1857. (call-next-method)))))
  1858. (defmethod emacs-inspect ((o kernel:funcallable-instance))
  1859. (append (label-value-line*
  1860. (:function (kernel:%funcallable-instance-function o))
  1861. (:lexenv (kernel:%funcallable-instance-lexenv o))
  1862. (:layout (kernel:%funcallable-instance-layout o)))
  1863. (cmucl-inspect o)))
  1864. (defmethod emacs-inspect ((o kernel:code-component))
  1865. (append
  1866. (label-value-line*
  1867. ("code-size" (kernel:%code-code-size o))
  1868. ("entry-points" (kernel:%code-entry-points o))
  1869. ("debug-info" (kernel:%code-debug-info o))
  1870. ("trace-table-offset" (kernel:code-header-ref
  1871. o vm:code-trace-table-offset-slot)))
  1872. `("Constants:" (:newline))
  1873. (loop for i from vm:code-constants-offset
  1874. below (kernel:get-header-data o)
  1875. append (label-value-line i (kernel:code-header-ref o i)))
  1876. `("Code:"
  1877. (:newline)
  1878. , (with-output-to-string (*standard-output*)
  1879. (cond ((c::compiled-debug-info-p (kernel:%code-debug-info o))
  1880. (disassem:disassemble-code-component o))
  1881. ((or
  1882. (c::debug-info-p (kernel:%code-debug-info o))
  1883. (consp (kernel:code-header-ref
  1884. o vm:code-trace-table-offset-slot)))
  1885. (c:disassem-byte-component o))
  1886. (t
  1887. (disassem:disassemble-memory
  1888. (disassem::align
  1889. (+ (logandc2 (kernel:get-lisp-obj-address o)
  1890. vm:lowtag-mask)
  1891. (* vm:code-constants-offset vm:word-bytes))
  1892. (ash 1 vm:lowtag-bits))
  1893. (ash (kernel:%code-code-size o) vm:word-shift))))))))
  1894. (defmethod emacs-inspect ((o kernel:fdefn))
  1895. (label-value-line*
  1896. ("name" (kernel:fdefn-name o))
  1897. ("function" (kernel:fdefn-function o))
  1898. ("raw-addr" (sys:sap-ref-32
  1899. (sys:int-sap (kernel:get-lisp-obj-address o))
  1900. (* vm:fdefn-raw-addr-slot vm:word-bytes)))))
  1901. #+(or)
  1902. (defmethod emacs-inspect ((o array))
  1903. (if (typep o 'simple-array)
  1904. (call-next-method)
  1905. (label-value-line*
  1906. (:header (describe-primitive-type o))
  1907. (:rank (array-rank o))
  1908. (:fill-pointer (kernel:%array-fill-pointer o))
  1909. (:fill-pointer-p (kernel:%array-fill-pointer-p o))
  1910. (:elements (kernel:%array-available-elements o))
  1911. (:data (kernel:%array-data-vector o))
  1912. (:displacement (kernel:%array-displacement o))
  1913. (:displaced-p (kernel:%array-displaced-p o))
  1914. (:dimensions (array-dimensions o)))))
  1915. (defmethod emacs-inspect ((o simple-vector))
  1916. (append
  1917. (label-value-line*
  1918. (:header (describe-primitive-type o))
  1919. (:length (c::vector-length o)))
  1920. (loop for i below (length o)
  1921. append (label-value-line i (aref o i)))))
  1922. (defun inspect-alien-record (alien)
  1923. (with-struct (alien::alien-value- sap type) alien
  1924. (with-struct (alien::alien-record-type- kind name fields) type
  1925. (append
  1926. (label-value-line*
  1927. (:sap sap)
  1928. (:kind kind)
  1929. (:name name))
  1930. (loop for field in fields
  1931. append (let ((slot (alien::alien-record-field-name field)))
  1932. (declare (optimize (speed 0)))
  1933. (label-value-line slot (alien:slot alien slot))))))))
  1934. (defun inspect-alien-pointer (alien)
  1935. (with-struct (alien::alien-value- sap type) alien
  1936. (label-value-line*
  1937. (:sap sap)
  1938. (:type type)
  1939. (:to (alien::deref alien)))))
  1940. (defun inspect-alien-value (alien)
  1941. (typecase (alien::alien-value-type alien)
  1942. (alien::alien-record-type (inspect-alien-record alien))
  1943. (alien::alien-pointer-type (inspect-alien-pointer alien))
  1944. (t (cmucl-inspect alien))))
  1945. (defimplementation eval-context (obj)
  1946. (cond ((typep (class-of obj) 'structure-class)
  1947. (let* ((dd (kernel:layout-info (kernel:layout-of obj)))
  1948. (slots (kernel:dd-slots dd)))
  1949. (list* (cons '*package*
  1950. (symbol-package (if slots
  1951. (kernel:dsd-name (car slots))
  1952. (kernel:dd-name dd))))
  1953. (loop for slot in slots collect
  1954. (cons (kernel:dsd-name slot)
  1955. (funcall (kernel:dsd-accessor slot) obj))))))))
  1956. ;;;; Profiling
  1957. (defimplementation profile (fname)
  1958. (eval `(profile:profile ,fname)))
  1959. (defimplementation unprofile (fname)
  1960. (eval `(profile:unprofile ,fname)))
  1961. (defimplementation unprofile-all ()
  1962. (eval `(profile:unprofile))
  1963. "All functions unprofiled.")
  1964. (defimplementation profile-report ()
  1965. (eval `(profile:report-time)))
  1966. (defimplementation profile-reset ()
  1967. (eval `(profile:reset-time))
  1968. "Reset profiling counters.")
  1969. (defimplementation profiled-functions ()
  1970. profile:*timed-functions*)
  1971. (defimplementation profile-package (package callers methods)
  1972. (profile:profile-all :package package
  1973. :callers-p callers
  1974. #-cmu18e :methods #-cmu18e methods))
  1975. ;;;; Multiprocessing
  1976. #+mp
  1977. (progn
  1978. (defimplementation initialize-multiprocessing (continuation)
  1979. (mp::init-multi-processing)
  1980. (mp:make-process continuation :name "swank")
  1981. ;; Threads magic: this never returns! But top-level becomes
  1982. ;; available again.
  1983. (unless mp::*idle-process*
  1984. (mp::startup-idle-and-top-level-loops)))
  1985. (defimplementation spawn (fn &key name)
  1986. (mp:make-process fn :name (or name "Anonymous")))
  1987. (defvar *thread-id-counter* 0)
  1988. (defimplementation thread-id (thread)
  1989. (or (getf (mp:process-property-list thread) 'id)
  1990. (setf (getf (mp:process-property-list thread) 'id)
  1991. (incf *thread-id-counter*))))
  1992. (defimplementation find-thread (id)
  1993. (find id (all-threads)
  1994. :key (lambda (p) (getf (mp:process-property-list p) 'id))))
  1995. (defimplementation thread-name (thread)
  1996. (mp:process-name thread))
  1997. (defimplementation thread-status (thread)
  1998. (mp:process-whostate thread))
  1999. (defimplementation current-thread ()
  2000. mp:*current-process*)
  2001. (defimplementation all-threads ()
  2002. (copy-list mp:*all-processes*))
  2003. (defimplementation interrupt-thread (thread fn)
  2004. (mp:process-interrupt thread fn))
  2005. (defimplementation kill-thread (thread)
  2006. (mp:destroy-process thread))
  2007. (defvar *mailbox-lock* (mp:make-lock "mailbox lock"))
  2008. (defstruct (mailbox (:conc-name mailbox.))
  2009. (mutex (mp:make-lock "process mailbox"))
  2010. (queue '() :type list))
  2011. (defun mailbox (thread)
  2012. "Return THREAD's mailbox."
  2013. (mp:with-lock-held (*mailbox-lock*)
  2014. (or (getf (mp:process-property-list thread) 'mailbox)
  2015. (setf (getf (mp:process-property-list thread) 'mailbox)
  2016. (make-mailbox)))))
  2017. (defimplementation send (thread message)
  2018. (check-slime-interrupts)
  2019. (let* ((mbox (mailbox thread)))
  2020. (mp:with-lock-held ((mailbox.mutex mbox))
  2021. (setf (mailbox.queue mbox)
  2022. (nconc (mailbox.queue mbox) (list message))))))
  2023. (defimplementation receive-if (test &optional timeout)
  2024. (let ((mbox (mailbox mp:*current-process*)))
  2025. (assert (or (not timeout) (eq timeout t)))
  2026. (loop
  2027. (check-slime-interrupts)
  2028. (mp:with-lock-held ((mailbox.mutex mbox))
  2029. (let* ((q (mailbox.queue mbox))
  2030. (tail (member-if test q)))
  2031. (when tail
  2032. (setf (mailbox.queue mbox)
  2033. (nconc (ldiff q tail) (cdr tail)))
  2034. (return (car tail)))))
  2035. (when (eq timeout t) (return (values nil t)))
  2036. (mp:process-wait-with-timeout
  2037. "receive-if" 0.5
  2038. (lambda () (some test (mailbox.queue mbox)))))))
  2039. ) ;; #+mp
  2040. ;;;; GC hooks
  2041. ;;;
  2042. ;;; Display GC messages in the echo area to avoid cluttering the
  2043. ;;; normal output.
  2044. ;;;
  2045. ;; this should probably not be here, but where else?
  2046. (defun background-message (message)
  2047. (funcall (find-symbol (string :background-message) :swank)
  2048. message))
  2049. (defun print-bytes (nbytes &optional stream)
  2050. "Print the number NBYTES to STREAM in KB, MB, or GB units."
  2051. (let ((names '((0 bytes) (10 kb) (20 mb) (30 gb) (40 tb) (50 eb))))
  2052. (multiple-value-bind (power name)
  2053. (loop for ((p1 n1) (p2 n2)) on names
  2054. while n2 do
  2055. (when (<= (expt 2 p1) nbytes (1- (expt 2 p2)))
  2056. (return (values p1 n1))))
  2057. (cond (name
  2058. (format stream "~,1F ~A" (/ nbytes (expt 2 power)) name))
  2059. (t
  2060. (format stream "~:D bytes" nbytes))))))
  2061. (defconstant gc-generations 6)
  2062. #+gencgc
  2063. (defun generation-stats ()
  2064. "Return a string describing the size distribution among the generations."
  2065. (let* ((alloc (loop for i below gc-generations
  2066. collect (lisp::gencgc-stats i)))
  2067. (sum (coerce (reduce #'+ alloc) 'float)))
  2068. (format nil "~{~3F~^/~}"
  2069. (mapcar (lambda (size) (/ size sum))
  2070. alloc))))
  2071. (defvar *gc-start-time* 0)
  2072. (defun pre-gc-hook (bytes-in-use)
  2073. (setq *gc-start-time* (get-internal-real-time))
  2074. (let ((msg (format nil "[Commencing GC with ~A in use.]"
  2075. (print-bytes bytes-in-use))))
  2076. (background-message msg)))
  2077. (defun post-gc-hook (bytes-retained bytes-freed trigger)
  2078. (declare (ignore trigger))
  2079. (let* ((seconds (/ (- (get-internal-real-time) *gc-start-time*)
  2080. internal-time-units-per-second))
  2081. (msg (format nil "[GC done. ~A freed ~A retained ~A ~4F sec]"
  2082. (print-bytes bytes-freed)
  2083. (print-bytes bytes-retained)
  2084. #+gencgc(generation-stats)
  2085. #-gencgc""
  2086. seconds)))
  2087. (background-message msg)))
  2088. (defun install-gc-hooks ()
  2089. (setq ext:*gc-notify-before* #'pre-gc-hook)
  2090. (setq ext:*gc-notify-after* #'post-gc-hook))
  2091. (defun remove-gc-hooks ()
  2092. (setq ext:*gc-notify-before* #'lisp::default-gc-notify-before)
  2093. (setq ext:*gc-notify-after* #'lisp::default-gc-notify-after))
  2094. (defvar *install-gc-hooks* t
  2095. "If non-nil install GC hooks")
  2096. (defimplementation emacs-connected ()
  2097. (when *install-gc-hooks*
  2098. (install-gc-hooks)))
  2099. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2100. ;;Trace implementations
  2101. ;;In CMUCL, we have:
  2102. ;; (trace <name>)
  2103. ;; (trace (method <name> <qualifier>? (<specializer>+)))
  2104. ;; (trace :methods t '<name>) ;;to trace all methods of the gf <name>
  2105. ;; <name> can be a normal name or a (setf name)
  2106. (defun tracedp (spec)
  2107. (member spec (eval '(trace)) :test #'equal))
  2108. (defun toggle-trace-aux (spec &rest options)
  2109. (cond ((tracedp spec)
  2110. (eval `(untrace ,spec))
  2111. (format nil "~S is now untraced." spec))
  2112. (t
  2113. (eval `(trace ,spec ,@options))
  2114. (format nil "~S is now traced." spec))))
  2115. (defimplementation toggle-trace (spec)
  2116. (ecase (car spec)
  2117. ((setf)
  2118. (toggle-trace-aux spec))
  2119. ((:defgeneric)
  2120. (let ((name (second spec)))
  2121. (toggle-trace-aux name :methods name)))
  2122. ((:defmethod)
  2123. (cond ((fboundp `(method ,@(cdr spec)))
  2124. (toggle-trace-aux `(method ,(cdr spec))))
  2125. ;; Man, is this ugly
  2126. ((fboundp `(pcl::fast-method ,@(cdr spec)))
  2127. (toggle-trace-aux `(pcl::fast-method ,@(cdr spec))))
  2128. (t
  2129. (error 'undefined-function :name (cdr spec)))))
  2130. ((:call)
  2131. (destructuring-bind (caller callee) (cdr spec)
  2132. (toggle-trace-aux (process-fspec callee)
  2133. :wherein (list (process-fspec caller)))))
  2134. ;; doesn't work properly
  2135. ;; ((:labels :flet) (toggle-trace-aux (process-fspec spec)))
  2136. ))
  2137. (defun process-fspec (fspec)
  2138. (cond ((consp fspec)
  2139. (ecase (first fspec)
  2140. ((:defun :defgeneric) (second fspec))
  2141. ((:defmethod)
  2142. `(method ,(second fspec) ,@(third fspec) ,(fourth fspec)))
  2143. ((:labels) `(labels ,(third fspec) ,(process-fspec (second fspec))))
  2144. ((:flet) `(flet ,(third fspec) ,(process-fspec (second fspec))))))
  2145. (t
  2146. fspec)))
  2147. ;;; Weak datastructures
  2148. (defimplementation make-weak-key-hash-table (&rest args)
  2149. (apply #'make-hash-table :weak-p t args))
  2150. ;;; Save image
  2151. (defimplementation save-image (filename &optional restart-function)
  2152. (multiple-value-bind (pid error) (unix:unix-fork)
  2153. (when (not pid) (error "fork: ~A" (unix:get-unix-error-msg error)))
  2154. (cond ((= pid 0)
  2155. (apply #'ext:save-lisp
  2156. filename
  2157. (if restart-function
  2158. `(:init-function ,restart-function))))
  2159. (t
  2160. (let ((status (waitpid pid)))
  2161. (destructuring-bind (&key exited? status &allow-other-keys) status
  2162. (assert (and exited? (equal status 0)) ()
  2163. "Invalid exit status: ~a" status)))))))
  2164. (defun waitpid (pid)
  2165. (alien:with-alien ((status c-call:int))
  2166. (let ((code (alien:alien-funcall
  2167. (alien:extern-alien
  2168. waitpid (alien:function c-call:int c-call:int
  2169. (* c-call:int) c-call:int))
  2170. pid (alien:addr status) 0)))
  2171. (cond ((= code -1) (error "waitpid: ~A" (unix:get-unix-error-msg)))
  2172. (t (assert (= code pid))
  2173. (decode-wait-status status))))))
  2174. (defun decode-wait-status (status)
  2175. (let ((output (with-output-to-string (s)
  2176. (call-program (list (process-status-program)
  2177. (format nil "~d" status))
  2178. :output s))))
  2179. (read-from-string output)))
  2180. (defun call-program (args &key output)
  2181. (destructuring-bind (program &rest args) args
  2182. (let ((process (ext:run-program program args :output output)))
  2183. (when (not program) (error "fork failed"))
  2184. (unless (and (eq (ext:process-status process) :exited)
  2185. (= (ext:process-exit-code process) 0))
  2186. (error "Non-zero exit status")))))
  2187. (defvar *process-status-program* nil)
  2188. (defun process-status-program ()
  2189. (or *process-status-program*
  2190. (setq *process-status-program*
  2191. (compile-process-status-program))))
  2192. (defun compile-process-status-program ()
  2193. (let ((infile (system::pick-temporary-file-name
  2194. "/tmp/process-status~d~c.c")))
  2195. (with-open-file (stream infile :direction :output :if-exists :supersede)
  2196. (format stream "
  2197. #include <stdio.h>
  2198. #include <stdlib.h>
  2199. #include <sys/types.h>
  2200. #include <sys/wait.h>
  2201. #include <assert.h>
  2202. #define FLAG(value) (value ? \"t\" : \"nil\")
  2203. int main (int argc, char** argv) {
  2204. assert (argc == 2);
  2205. {
  2206. char* endptr = NULL;
  2207. char* arg = argv[1];
  2208. long int status = strtol (arg, &endptr, 10);
  2209. assert (endptr != arg && *endptr == '\\0');
  2210. printf (\"(:exited? %s :status %d :signal? %s :signal %d :coredump? %s\"
  2211. \" :stopped? %s :stopsig %d)\\n\",
  2212. FLAG(WIFEXITED(status)), WEXITSTATUS(status),
  2213. FLAG(WIFSIGNALED(status)), WTERMSIG(status),
  2214. FLAG(WCOREDUMP(status)),
  2215. FLAG(WIFSTOPPED(status)), WSTOPSIG(status));
  2216. fflush (NULL);
  2217. return 0;
  2218. }
  2219. }
  2220. ")
  2221. (finish-output stream))
  2222. (let* ((outfile (system::pick-temporary-file-name))
  2223. (args (list "cc" "-o" outfile infile)))
  2224. (warn "Running cc: ~{~a ~}~%" args)
  2225. (call-program args :output t)
  2226. (delete-file infile)
  2227. outfile)))
  2228. #+#.(swank-backend:with-symbol 'unicode-complete 'lisp)
  2229. (defun match-semi-standard (prefix matchp)
  2230. ;; Handle the CMUCL's short character names.
  2231. (loop for name in lisp::char-name-alist
  2232. when (funcall matchp prefix (car name))
  2233. collect (car name)))
  2234. #+#.(swank-backend:with-symbol 'unicode-complete 'lisp)
  2235. (defimplementation character-completion-set (prefix matchp)
  2236. (let ((names (lisp::unicode-complete prefix)))
  2237. ;; Match prefix against semistandard names. If there's a match,
  2238. ;; add it to our list of matches.
  2239. (let ((semi-standard (match-semi-standard prefix matchp)))
  2240. (when semi-standard
  2241. (setf names (append semi-standard names))))
  2242. (setf names (mapcar #'string-capitalize names))
  2243. (loop for n in names
  2244. when (funcall matchp prefix n)
  2245. collect n)))