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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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