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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5