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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5