/[slime]/slime/swank-cmucl.lisp
ViewVC logotype

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5