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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5