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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5