1 ;;;; This file contains parts of the ALIEN implementation that
2 ;;;; are not part of the compiler.
4 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!ALIEN")
15 (/show0 "target-alieneval.lisp 15")
19 ;;; Make a string out of the symbol, converting all uppercase letters to
20 ;;; lower case and hyphens into underscores.
21 (eval-when (:compile-toplevel :load-toplevel :execute)
22 (defun guess-alien-name-from-lisp-name (lisp-name)
23 (declare (type symbol lisp-name))
24 (nsubstitute #\_ #\- (string-downcase (symbol-name lisp-name)))))
26 ;;; The opposite of GUESS-ALIEN-NAME-FROM-LISP-NAME. Make a symbol out
27 ;;; of the string, converting all lowercase letters to uppercase and
28 ;;; underscores into hyphens.
29 (eval-when (:compile-toplevel :load-toplevel :execute)
30 (defun guess-lisp-name-from-alien-name (alien-name)
31 (declare (type simple-string alien-name))
32 (intern (nsubstitute #\- #\_ (string-upcase alien-name)))))
34 ;;; Extract the Lisp and alien names from NAME. If only one is given,
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defun pick-lisp-and-alien-names (name)
40 (values (guess-lisp-name-from-alien-name name) name))
42 (values name (guess-alien-name-from-lisp-name name)))
44 (unless (proper-list-of-length-p name 2)
45 (error "badly formed alien name"))
46 (values (cadr name) (car name))))))
48 (defmacro define-alien-variable (name type &environment env)
50 "Define NAME as an external alien variable of type TYPE. NAME should be
51 a list of a string holding the alien name and a symbol to use as the Lisp
52 name. If NAME is just a symbol or string, then the other name is guessed
53 from the one supplied."
54 (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
55 (with-auxiliary-alien-types env
56 (let ((alien-type (parse-alien-type type env)))
57 `(eval-when (:compile-toplevel :load-toplevel :execute)
58 ,@(when *new-auxiliary-types*
59 `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
60 (%define-alien-variable ',lisp-name
64 (defmacro def-alien-variable (&rest rest)
65 (deprecation-warning 'def-alien-variable 'define-alien-variable)
66 `(define-alien-variable ,@rest))
68 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
69 (eval-when (:compile-toplevel :load-toplevel :execute)
70 (defun %define-alien-variable (lisp-name alien-name type)
71 (setf (info :variable :kind lisp-name) :alien)
72 (setf (info :variable :where-from lisp-name) :defined)
73 (clear-info :variable :constant-value lisp-name)
74 (setf (info :variable :alien-info lisp-name)
75 (make-heap-alien-info :type type
76 :sap-form `(foreign-symbol-sap ',alien-name t)))))
78 (defmacro extern-alien (name type &environment env)
80 "Access the alien variable named NAME, assuming it is of type TYPE. This
82 (let* ((alien-name (etypecase name
83 (symbol (guess-alien-name-from-lisp-name name))
85 (alien-type (parse-alien-type type env))
86 (datap (not (alien-fun-type-p alien-type))))
87 `(%heap-alien ',(make-heap-alien-info
89 :sap-form `(foreign-symbol-sap ',alien-name ,datap)))))
91 (defmacro with-alien (bindings &body body &environment env)
93 "Establish some local alien variables. Each BINDING is of the form:
94 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
95 ALLOCATION should be one of:
97 The alien is allocated on the stack, and has dynamic extent.
99 The alien is allocated on the heap, and has infinite extent. The alien
100 is allocated at load time, so the same piece of memory is used each time
103 No alien is allocated, but VAR is established as a local name for
104 the external alien given by EXTERNAL-NAME."
105 (/show "entering WITH-ALIEN" bindings)
106 (with-auxiliary-alien-types env
107 (dolist (binding (reverse bindings))
110 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
112 (/show symbol type opt1 opt2)
113 (let* ((alien-type (parse-alien-type type env))
114 (datap (not (alien-fun-type-p alien-type))))
116 (multiple-value-bind (allocation initial-value)
121 (values opt1 (guess-alien-name-from-lisp-name symbol)))
125 (values :local opt1))))
126 (/show allocation initial-value)
132 (make-symbol (concatenate 'string "SAP-FOR-"
133 (symbol-name symbol)))))
134 `((let ((,sap (load-time-value (%make-alien ...))))
135 (declare (type system-area-pointer ,sap))
137 ((,symbol (sap-alien ,sap ,type)))
138 ,@(when initial-value
139 `((setq ,symbol ,initial-value)))
142 (/show0 ":EXTERN case")
143 (let ((info (make-heap-alien-info
145 :sap-form `(foreign-symbol-sap ',initial-value
148 ((,symbol (%heap-alien ',info)))
151 (/show0 ":LOCAL case")
153 (initval (if initial-value (gensym)))
154 (info (make-local-alien-info :type alien-type)))
155 (/show var initval info)
156 `((let ((,var (make-local-alien ',info))
157 ,@(when initial-value
158 `((,initval ,initial-value))))
159 (note-local-alien-type ',info ,var)
160 (multiple-value-prog1
162 ((,symbol (local-alien ',info ,var)))
163 ,@(when initial-value
164 `((setq ,symbol ,initval)))
166 (dispose-local-alien ',info ,var))))))))))))
167 (/show "revised" body)
168 (verify-local-auxiliaries-okay)
169 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
170 `(symbol-macrolet ((&auxiliary-type-definitions&
171 ,(append *new-auxiliary-types*
172 (auxiliary-type-definitions env))))
175 ;;;; runtime C values that don't correspond directly to Lisp types
177 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
178 ;;; 'cause it has to be real early in the cold-load order.
179 #!-sb-fluid (declaim (freeze-type alien-value))
180 (def!method print-object ((value alien-value) stream)
181 (print-unreadable-object (value stream)
183 "~S ~S #X~8,'0X ~S ~S"
185 :sap (sap-int (alien-value-sap value))
186 :type (unparse-alien-type (alien-value-type value)))))
188 #!-sb-fluid (declaim (inline null-alien))
189 (defun null-alien (x)
191 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
192 (zerop (sap-int (alien-sap x))))
194 (defmacro sap-alien (sap type &environment env)
196 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
197 evaluated.) TYPE must be pointer-like."
198 (let ((alien-type (parse-alien-type type env)))
199 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
200 `(%sap-alien ,sap ',alien-type)
201 (error "cannot make an alien of type ~S out of a SAP" type))))
203 (defun %sap-alien (sap type)
204 (declare (type system-area-pointer sap)
205 (type alien-type type))
206 (make-alien-value :sap sap :type type))
208 (defun alien-sap (alien)
210 "Return a System-Area-Pointer pointing to Alien's data."
211 (declare (type alien-value alien))
212 (alien-value-sap alien))
214 ;;;; allocation/deallocation of heap aliens
216 (defmacro make-alien (type &optional size &environment env)
218 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
219 is supplied, how it is interpreted depends on TYPE. If TYPE is an array
220 type, SIZE is used as the first dimension for the allocated array. If TYPE
221 is not an array, then SIZE is the number of elements to allocate. The
222 memory is allocated using ``malloc'', so it can be passed to foreign
223 functions which use ``free''."
224 (let ((alien-type (if (alien-type-p type)
226 (parse-alien-type type env))))
227 (multiple-value-bind (size-expr element-type)
228 (if (alien-array-type-p alien-type)
229 (let ((dims (alien-array-type-dimensions alien-type)))
234 "cannot override the size of zero-dimensional arrays"))
235 (when (constantp size)
236 (setf alien-type (copy-alien-array-type alien-type))
237 (setf (alien-array-type-dimensions alien-type)
238 (cons (eval size) (cdr dims)))))
240 (setf size (car dims)))
243 (values `(* ,size ,@(cdr dims))
244 (alien-array-type-element-type alien-type)))
245 (values (or size 1) alien-type))
246 (let ((bits (alien-type-bits element-type))
247 (alignment (alien-type-alignment element-type)))
249 (error "The size of ~S is unknown."
250 (unparse-alien-type element-type)))
252 (error "The alignment of ~S is unknown."
253 (unparse-alien-type element-type)))
254 `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
256 ',(make-alien-pointer-type :to alien-type))))))
258 ;;; Allocate a block of memory at least BITS bits long and return a
259 ;;; system area pointer to it.
260 #!-sb-fluid (declaim (inline %make-alien))
261 (defun %make-alien (bits)
262 (declare (type index bits))
263 (alien-funcall (extern-alien "malloc"
264 (function system-area-pointer unsigned))
265 (ash (the index (+ bits 7)) -3)))
267 #!-sb-fluid (declaim (inline free-alien))
268 (defun free-alien (alien)
270 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
271 by MAKE-ALIEN or malloc(3)."
272 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
276 ;;;; the SLOT operator
278 ;;; Find the field named SLOT, or die trying.
279 (defun slot-or-lose (type slot)
280 (declare (type alien-record-type type)
282 (or (find slot (alien-record-type-fields type)
283 :key #'alien-record-field-name)
284 (error "There is no slot named ~S in ~S." slot type)))
286 ;;; Extract the value from the named slot from the record ALIEN. If
287 ;;; ALIEN is actually a pointer, then DEREF it first.
288 (defun slot (alien slot)
290 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
291 (declare (type alien-value alien)
293 (optimize (inhibit-warnings 3)))
294 (let ((type (alien-value-type alien)))
297 (slot (deref alien) slot))
299 (let ((field (slot-or-lose type slot)))
300 (extract-alien-value (alien-value-sap alien)
301 (alien-record-field-offset field)
302 (alien-record-field-type field)))))))
304 ;;; Deposit the value in the specified slot of the record ALIEN. If
305 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
306 ;;; this when it can't figure out anything better.
307 (defun %set-slot (alien slot value)
308 (declare (type alien-value alien)
310 (optimize (inhibit-warnings 3)))
311 (let ((type (alien-value-type alien)))
314 (%set-slot (deref alien) slot value))
316 (let ((field (slot-or-lose type slot)))
317 (deposit-alien-value (alien-value-sap alien)
318 (alien-record-field-offset field)
319 (alien-record-field-type field)
322 ;;; Compute the address of the specified slot and return a pointer to it.
323 (defun %slot-addr (alien slot)
324 (declare (type alien-value alien)
326 (optimize (inhibit-warnings 3)))
327 (let ((type (alien-value-type alien)))
330 (%slot-addr (deref alien) slot))
332 (let* ((field (slot-or-lose type slot))
333 (offset (alien-record-field-offset field))
334 (field-type (alien-record-field-type field)))
335 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
336 (make-alien-pointer-type :to field-type)))))))
338 ;;;; the DEREF operator
340 ;;; This function does most of the work of the different DEREF
341 ;;; methods. It returns two values: the type and the offset (in bits)
342 ;;; of the referred-to alien.
343 (defun deref-guts (alien indices)
344 (declare (type alien-value alien)
346 (values alien-type integer))
347 (let ((type (alien-value-type alien)))
351 (error "too many indices when DEREF'ing ~S: ~W"
354 (let ((element-type (alien-pointer-type-to type)))
357 (* (align-offset (alien-type-bits element-type)
358 (alien-type-alignment element-type))
362 (unless (= (length indices) (length (alien-array-type-dimensions type)))
363 (error "incorrect number of indices when DEREF'ing ~S: ~W"
364 type (length indices)))
365 (labels ((frob (dims indices offset)
368 (frob (cdr dims) (cdr indices)
369 (+ (if (zerop offset)
371 (* offset (car dims)))
373 (let ((element-type (alien-array-type-element-type type)))
375 (* (align-offset (alien-type-bits element-type)
376 (alien-type-alignment element-type))
377 (frob (alien-array-type-dimensions type)
380 ;;; Dereference the alien and return the results.
381 (defun deref (alien &rest indices)
383 "De-reference an Alien pointer or array. If an array, the indices are used
384 as the indices of the array element to access. If a pointer, one index can
385 optionally be specified, giving the equivalent of C pointer arithmetic."
386 (declare (type alien-value alien)
388 (optimize (inhibit-warnings 3)))
389 (multiple-value-bind (target-type offset) (deref-guts alien indices)
390 (extract-alien-value (alien-value-sap alien)
394 (defun %set-deref (alien value &rest indices)
395 (declare (type alien-value alien)
397 (optimize (inhibit-warnings 3)))
398 (multiple-value-bind (target-type offset) (deref-guts alien indices)
399 (deposit-alien-value (alien-value-sap alien)
404 (defun %deref-addr (alien &rest indices)
405 (declare (type alien-value alien)
407 (optimize (inhibit-warnings 3)))
408 (multiple-value-bind (target-type offset) (deref-guts alien indices)
409 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
410 (make-alien-pointer-type :to target-type))))
412 ;;;; accessing heap alien variables
414 (defun %heap-alien (info)
415 (declare (type heap-alien-info info)
416 (optimize (inhibit-warnings 3)))
417 (extract-alien-value (eval (heap-alien-info-sap-form info))
419 (heap-alien-info-type info)))
421 (defun %set-heap-alien (info value)
422 (declare (type heap-alien-info info)
423 (optimize (inhibit-warnings 3)))
424 (deposit-alien-value (eval (heap-alien-info-sap-form info))
426 (heap-alien-info-type info)
429 (defun %heap-alien-addr (info)
430 (declare (type heap-alien-info info)
431 (optimize (inhibit-warnings 3)))
432 (%sap-alien (eval (heap-alien-info-sap-form info))
433 (make-alien-pointer-type :to (heap-alien-info-type info))))
435 ;;;; accessing local aliens
437 (defun make-local-alien (info)
438 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
439 (alien-sap (alien-sap alien)))
444 (extern-alien "free" (function (values) system-area-pointer))
448 (defun note-local-alien-type (info alien)
449 (declare (ignore info alien))
452 (defun local-alien (info alien)
453 (declare (ignore info))
456 (defun %set-local-alien (info alien value)
457 (declare (ignore info))
458 (setf (deref alien) value))
460 (define-setf-expander local-alien (&whole whole info alien)
461 (let ((value (gensym))
462 (info (if (and (consp info)
463 (eq (car info) 'quote))
465 (error "Something is wrong; local-alien-info not found: ~S"
470 `(if (%local-alien-forced-to-memory-p ',info)
471 (%set-local-alien ',info ,alien ,value)
473 (deport ,value ',(local-alien-info-type info))))
476 (defun %local-alien-forced-to-memory-p (info)
477 (local-alien-info-force-to-memory-p info))
479 (defun %local-alien-addr (info alien)
480 (declare (type local-alien-info info))
481 (unless (local-alien-info-force-to-memory-p info)
482 (error "~S isn't forced to memory. Something went wrong." alien))
485 (defun dispose-local-alien (info alien)
486 (declare (ignore info))
487 (cancel-finalization alien)
492 (defmacro cast (alien type &environment env)
494 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
495 must be Alien array, pointer or function types."
496 `(%cast ,alien ',(parse-alien-type type env)))
498 (defun %cast (alien target-type)
499 (declare (type alien-value alien)
500 (type alien-type target-type)
501 (optimize (safety 2))
502 (optimize (inhibit-warnings 3)))
503 (if (or (alien-pointer-type-p target-type)
504 (alien-array-type-p target-type)
505 (alien-fun-type-p target-type))
506 (let ((alien-type (alien-value-type alien)))
507 (if (or (alien-pointer-type-p alien-type)
508 (alien-array-type-p alien-type)
509 (alien-fun-type-p alien-type))
510 (naturalize (alien-value-sap alien) target-type)
511 (error "~S cannot be casted." alien)))
512 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
514 ;;;; the ALIEN-SIZE macro
516 (defmacro alien-size (type &optional (units :bits) &environment env)
518 "Return the size of the alien type TYPE. UNITS specifies the units to
519 use and can be either :BITS, :BYTES, or :WORDS."
520 (let* ((alien-type (parse-alien-type type env))
521 (bits (alien-type-bits alien-type)))
523 (values (ceiling bits
526 (:bytes sb!vm:n-byte-bits)
527 (:words sb!vm:n-word-bits))))
528 (error "unknown size for alien type ~S"
529 (unparse-alien-type alien-type)))))
531 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
533 (defun naturalize (alien type)
534 (declare (type alien-type type))
535 (funcall (coerce (compute-naturalize-lambda type) 'function)
538 (defun deport (value type)
539 (declare (type alien-type type))
540 (funcall (coerce (compute-deport-lambda type) 'function)
543 (defun extract-alien-value (sap offset type)
544 (declare (type system-area-pointer sap)
545 (type unsigned-byte offset)
546 (type alien-type type))
547 (funcall (coerce (compute-extract-lambda type) 'function)
550 (defun deposit-alien-value (sap offset type value)
551 (declare (type system-area-pointer sap)
552 (type unsigned-byte offset)
553 (type alien-type type))
554 (funcall (coerce (compute-deposit-lambda type) 'function)
555 sap offset type value))
557 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
559 (defun alien-funcall (alien &rest args)
561 "Call the foreign function ALIEN with the specified arguments. ALIEN's
562 type specifies the argument and result types."
563 (declare (type alien-value alien))
564 (let ((type (alien-value-type alien)))
567 (apply #'alien-funcall (deref alien) args))
569 (unless (= (length (alien-fun-type-arg-types type))
571 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
573 (length (alien-fun-type-arg-types type))
575 (let ((stub (alien-fun-type-stub type)))
579 (parms (make-gensym-list (length args))))
581 `(lambda (,fun ,@parms)
582 (declare (optimize (sb!c::insert-step-conditions 0)))
583 (declare (type (alien ,type) ,fun))
584 (alien-funcall ,fun ,@parms)))))
585 (setf (alien-fun-type-stub type) stub))
586 (apply stub alien args)))
588 (error "~S is not an alien function." alien)))))
590 (defmacro define-alien-routine (name result-type
594 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
596 Define a foreign interface function for the routine with the specified NAME.
597 Also automatically DECLAIM the FTYPE of the defined function.
599 NAME may be either a string, a symbol, or a list of the form (string symbol).
601 RETURN-TYPE is the alien type for the function return value. VOID may be
602 used to specify a function with no result.
604 The remaining forms specify individual arguments that are passed to the
605 routine. ARG-NAME is a symbol that names the argument, primarily for
606 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
607 way that the argument is passed.
610 An :IN argument is simply passed by value. The value to be passed is
611 obtained from argument(s) to the interface function. No values are
612 returned for :In arguments. This is the default mode.
615 The specified argument type must be a pointer to a fixed sized object.
616 A pointer to a preallocated object is passed to the routine, and the
617 the object is accessed on return, with the value being returned from
618 the interface function. :OUT and :IN-OUT cannot be used with pointers
619 to arrays, records or functions.
622 This is similar to :IN, except that the argument values are stored
623 on the stack, and a pointer to the object is passed instead of
627 This is a combination of :OUT and :COPY. A pointer to the argument is
628 passed, with the object being initialized from the supplied argument
629 and the return value being determined by accessing the object on
631 (multiple-value-bind (lisp-name alien-name)
632 (pick-lisp-and-alien-names name)
633 (collect ((docs) (lisp-args) (lisp-arg-types)
635 (cond ((eql result-type 'void)
636 ;; What values does a function return, if it
637 ;; returns no values? Exactly one - NIL. -- APD,
641 ;; FIXME: Check for VALUES.
642 (list `(alien ,result-type)))))
643 (arg-types) (alien-vars)
644 (alien-args) (results))
648 (destructuring-bind (name type &optional (style :in)) arg
649 (unless (member style '(:in :copy :out :in-out))
650 (error "bogus argument style ~S in ~S" style arg))
651 (when (and (member style '(:out :in-out))
652 (typep (parse-alien-type type lexenv)
653 'alien-pointer-type))
654 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
657 (cond ((eq style :in)
661 (setq arg-type `(* ,type))
663 (alien-vars `(,name ,type))
664 (alien-vars `(,name ,type ,name)))
665 (alien-args `(addr ,name))))
667 (unless (eq style :out)
670 ;; FIXME: It should be something
671 ;; like `(ALIEN ,ARG-TYPE), except
672 ;; for we also accept SAPs where
673 ;; pointers are required.
675 (when (or (eq style :out) (eq style :in-out))
677 (lisp-result-types `(alien ,type))))))
679 ;; The theory behind this automatic DECLAIM is that (1) if
680 ;; you're calling C, static typing is what you're doing
681 ;; anyway, and (2) such a declamation can be (especially for
682 ;; alien values) both messy to do by hand and very important
683 ;; for performance of later code which uses the return value.
684 (declaim (ftype (function ,(lisp-arg-types)
685 (values ,@(lisp-result-types) &optional))
687 (defun ,lisp-name ,(lisp-args)
690 ((,lisp-name (function ,result-type ,@(arg-types))
694 (values (alien-funcall ,lisp-name ,@(alien-args))
697 (if (alien-values-type-p result-type)
698 ;; FIXME: RESULT-TYPE is a type specifier, so it
699 ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
700 ;; that if RESULT-TYPE is VOID, then this code
701 ;; disagrees with the computation of the return type
702 ;; and with all usages of this macro. -- APD,
704 (let ((temps (make-gensym-list
706 (alien-values-type-values result-type)))))
707 `(multiple-value-bind ,temps
708 (alien-funcall ,lisp-name ,@(alien-args))
709 (values ,@temps ,@(results))))
710 (values (alien-funcall ,lisp-name ,@(alien-args))
713 (defmacro def-alien-routine (&rest rest)
714 (deprecation-warning 'def-alien-routine 'define-alien-routine)
715 `(define-alien-routine ,@rest))
717 (defun alien-typep (object type)
719 "Return T iff OBJECT is an alien of type TYPE."
720 (let ((lisp-rep-type (compute-lisp-rep-type type)))
722 (typep object lisp-rep-type)
723 (and (alien-value-p object)
724 (alien-subtype-p (alien-value-type object) type)))))
728 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
730 (defvar *alien-callback-info* nil
731 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
732 information we need to manipulate callbacks after their creation. Used for
733 changing the lisp-side function they point to, invalidation, etc.")
735 (defstruct callback-info
737 function ; NULL if invalid
741 (defun callback-info-key (info)
742 (cons (callback-info-specifier info) (callback-info-function info)))
744 (defun alien-callback-info (alien)
745 (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
747 (defvar *alien-callbacks* (make-hash-table :test #'equal)
748 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
749 memoization: we don't create new callbacks if one pointing to the correct
750 function with the same specifier already exists.")
752 (defvar *alien-callback-wrappers* (make-hash-table :test #'equal)
753 "Cache of existing lisp weappers, indexed with SPECIFER. Used for memoization:
754 we don't create new wrappers if one for the same specifier already exists.")
756 (defvar *alien-callback-trampolines* (make-array 32 :fill-pointer 0 :adjustable t)
757 "Lisp trampoline store: assembler wrappers contain indexes to this, and
758 ENTER-ALIEN-CALLBACK pulls the corresponsing trampoline out and calls it.")
760 (defun %alien-callback-sap (specifier result-type argument-types function wrapper)
761 (let ((key (cons specifier function)))
762 (or (gethash key *alien-callbacks*)
763 (setf (gethash key *alien-callbacks*)
764 (let* ((index (fill-pointer *alien-callback-trampolines*))
765 ;; Aside from the INDEX this is known at
766 ;; compile-time, which could be utilized by
767 ;; having the two-stage assembler tramp &
768 ;; wrapper mentioned in [1] above: only the
769 ;; per-function tramp would need assembler at
770 ;; runtime. Possibly we could even pregenerate
771 ;; the code and just patch the index in later.
772 (assembler-wrapper (alien-callback-assembler-wrapper
773 index result-type argument-types)))
775 (alien-callback-lisp-trampoline wrapper function)
776 *alien-callback-trampolines*)
777 (let ((sap (vector-sap assembler-wrapper)))
778 (push (cons sap (make-callback-info :specifier specifier
782 *alien-callback-info*)
785 (defun alien-callback-lisp-trampoline (wrapper function)
786 (declare (function wrapper) (optimize speed))
787 (lambda (args-pointer result-pointer)
788 (funcall wrapper args-pointer result-pointer function)))
790 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
791 (let* ((arguments (make-gensym-list (length argument-types)))
792 (argument-names arguments)
793 (argument-specs (cddr specifier)))
794 `(lambda (args-pointer result-pointer function)
795 ;; FIXME: the saps are not gc safe
796 (let ((args-sap (int-sap
797 (sb!kernel:get-lisp-obj-address args-pointer)))
799 (sb!kernel:get-lisp-obj-address result-pointer))))
802 for spec in argument-specs
803 for offset = 0 ; FIXME: Should this not be AND OFFSET ...?
804 then (+ offset (alien-callback-argument-bytes spec env))
805 collect `(,(pop argument-names) ,spec
806 :local ,(alien-callback-accessor-form
807 spec 'args-sap offset)))
808 ,(flet ((store (spec)
810 `(setf (deref (sap-alien res-sap (* ,spec)))
811 (funcall function ,@arguments))
812 `(funcall function ,@arguments))))
813 (cond ((alien-void-type-p result-type)
815 ((alien-integer-type-p result-type)
816 (if (alien-integer-type-signed result-type)
818 ,(alien-type-word-aligned-bits result-type)))
821 ,(alien-type-word-aligned-bits result-type)))))
823 (store (unparse-alien-type result-type)))))))
826 (defun invalid-alien-callback (&rest arguments)
827 (declare (ignore arguments))
828 (error "Invalid alien callback called."))
831 (defun parse-callback-specification (result-type lambda-list)
833 `(function ,result-type ,@(mapcar #'second lambda-list))
834 (mapcar #'first lambda-list)))
837 (defun parse-alien-ftype (specifier env)
838 (destructuring-bind (function result-type &rest argument-types)
840 (aver (eq 'function function))
841 (values (parse-alien-type result-type env)
842 (mapcar (lambda (spec)
843 (parse-alien-type spec env))
846 (defun alien-void-type-p (type)
847 (and (alien-values-type-p type) (not (alien-values-type-values type))))
849 (defun alien-type-word-aligned-bits (type)
850 (align-offset (alien-type-bits type) sb!vm:n-word-bits))
852 (defun alien-callback-argument-bytes (spec env)
853 (let ((type (parse-alien-type spec env)))
854 (if (or (alien-integer-type-p type)
855 (alien-float-type-p type)
856 (alien-pointer-type-p type)
857 (alien-system-area-pointer-type-p type))
858 (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
859 (error "Unsupported callback argument type: ~A" type))))
861 (defun enter-alien-callback (index return arguments)
862 (funcall (aref *alien-callback-trampolines* index)
866 ;;;; interface (not public, yet) for alien callbacks
868 (defmacro alien-callback (specifier function &environment env)
869 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
870 an alien function as a pointer to the FUNCTION. If a callback for the given
871 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
873 ;; Pull out as much work as is convenient to macro-expansion time, specifically
874 ;; everything that can be done given just the SPECIFIER and ENV.
875 (multiple-value-bind (result-type argument-types) (parse-alien-ftype specifier env)
877 (%alien-callback-sap ',specifier ',result-type ',argument-types
879 (or (gethash ',specifier *alien-callback-wrappers*)
880 (setf (gethash ',specifier *alien-callback-wrappers*)
881 ,(alien-callback-lisp-wrapper-lambda
882 specifier result-type argument-types env))))
883 ',(parse-alien-type specifier env))))
885 (defun alien-callback-p (alien)
886 "Returns true if the alien is associated with a lisp-side callback,
887 and a secondary return value of true if the callback is still valid."
888 (let ((info (alien-callback-info alien)))
890 (values t (and (callback-info-function info) t)))))
892 (defun alien-callback-function (alien)
893 "Returns the lisp function designator associated with the callback."
894 (let ((info (alien-callback-info alien)))
896 (callback-info-function info))))
898 (defun (setf alien-callback-function) (function alien)
899 "Changes the lisp function designated by the callback."
900 (let ((info (alien-callback-info alien)))
902 (error "Not an alien callback: ~S" alien))
904 (let ((key (callback-info-key info)))
905 (remhash key *alien-callbacks*)
906 (setf (gethash key *alien-callbacks*) (alien-sap alien)))
908 (setf (aref *alien-callback-trampolines* (callback-info-index info))
909 (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
911 (setf (callback-info-function info) function)
914 (defun invalidate-alien-callback (alien)
915 "Invalidates the callback designated by the alien, if any, allowing the
916 associated lisp function to be GC'd, and causing further calls to the same
917 callback signal an error."
918 (let ((info (alien-callback-info alien)))
919 (when (and info (callback-info-function info))
921 (remhash (callback-info-key info) *alien-callbacks*)
923 (setf (aref *alien-callback-trampolines* (callback-info-index info))
924 #'invalid-alien-callback)
926 (setf (callback-info-function info) nil)
929 ;;; FIXME: This calls assembles a new callback for every closure,
930 ;;; which suck hugely. ...not that I can think of an obvious
931 ;;; solution. Possibly maybe we could write a generalized closure
932 ;;; callback analogous to closure_tramp, and share the actual wrapper?
934 ;;; For lambdas that result in simple-funs we get the callback from
935 ;;; the cache on subsequent calls.
936 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
937 (multiple-value-bind (specifier lambda-list)
938 (parse-callback-specification result-type typed-lambda-list)
939 `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
941 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
942 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
943 ;;; the FDEFINITION should invalidate the callback, and redefining the
944 ;;; callback should change existing callbacks to point to the new defintion.
945 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
946 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
947 the alien callback for that function with the given alien type."
948 (declare (symbol name))
949 (multiple-value-bind (specifier lambda-list)
950 (parse-callback-specification result-type typed-lambda-list)
952 (defun ,name ,lambda-list ,@forms)
953 (defparameter ,name (alien-callback ,specifier #',name)))))