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

Contents of /slime/swank-cmucl.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.236 - (show annotations)
Mon Nov 21 16:34:12 2011 UTC (2 years, 4 months ago) by heller
Branch: MAIN
Changes since 1.235: +11 -0 lines
* slime.el (sldb-eval-in-frame): Try to figure the package out.
Ask Lisp if the function for frame was defined in a particular
package and use it to read the form.
(sldb-read-form-for-frame): New helper.

* swank-backend (frame-package): New.
* swank-cmucl (frame-package): Implement it.

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