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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5