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 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
65 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
66 (defun %define-alien-variable
(lisp-name alien-name type
)
67 (setf (info :variable
:kind lisp-name
) :alien
)
68 (setf (info :variable
:where-from lisp-name
) :defined
)
69 (setf (info :variable
:alien-info lisp-name
)
70 (make-heap-alien-info :type type
71 :sap-form
`(foreign-symbol-sap ',alien-name t
)))))
73 (defmacro extern-alien
(name type
&environment env
)
75 "Access the alien variable named NAME, assuming it is of type TYPE. This
77 (let* ((alien-name (etypecase name
78 (symbol (guess-alien-name-from-lisp-name name
))
80 (alien-type (parse-alien-type type env
))
81 (datap (not (alien-fun-type-p alien-type
))))
82 `(%heap-alien
',(make-heap-alien-info
84 :sap-form
`(foreign-symbol-sap ',alien-name
,datap
)))))
86 (defmacro with-alien
(bindings &body body
&environment env
)
88 "Establish some local alien variables. Each BINDING is of the form:
89 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
90 ALLOCATION should be one of:
92 The alien is allocated on the stack, and has dynamic extent.
94 The alien is allocated on the heap, and has infinite extent. The alien
95 is allocated at load time, so the same piece of memory is used each time
98 No alien is allocated, but VAR is established as a local name for
99 the external alien given by EXTERNAL-NAME."
100 (/show
"entering WITH-ALIEN" bindings
)
101 (with-auxiliary-alien-types env
102 (dolist (binding (reverse bindings
))
105 (symbol type
&optional
(opt1 nil opt1p
) (opt2 nil opt2p
))
107 (/show symbol type opt1 opt2
)
108 (let* ((alien-type (parse-alien-type type env
))
109 (datap (not (alien-fun-type-p alien-type
))))
111 (multiple-value-bind (allocation initial-value
)
116 (values opt1
(guess-alien-name-from-lisp-name symbol
)))
120 (values :local opt1
))))
121 (/show allocation initial-value
)
127 (make-symbol (concatenate 'string
"SAP-FOR-"
128 (symbol-name symbol
)))))
129 `((let ((,sap
(load-time-value (%make-alien ...
))))
130 (declare (type system-area-pointer
,sap
))
132 ((,symbol
(sap-alien ,sap
,type
)))
133 ,@(when initial-value
134 `((setq ,symbol
,initial-value
)))
137 (/show0
":EXTERN case")
138 (let ((info (make-heap-alien-info
140 :sap-form
`(foreign-symbol-sap ',initial-value
143 ((,symbol
(%heap-alien
',info
)))
146 (/show0
":LOCAL case")
148 (initval (if initial-value
(gensym)))
149 (info (make-local-alien-info :type alien-type
)))
150 (/show var initval info
)
151 `((let ((,var
(make-local-alien ',info
))
152 ,@(when initial-value
153 `((,initval
,initial-value
))))
154 (note-local-alien-type ',info
,var
)
155 (multiple-value-prog1
157 ((,symbol
(local-alien ',info
,var
)))
158 ,@(when initial-value
159 `((setq ,symbol
,initval
)))
161 (dispose-local-alien ',info
,var
))))))))))))
162 (/show
"revised" body
)
163 (verify-local-auxiliaries-okay)
164 (/show0
"back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
165 `(symbol-macrolet ((&auxiliary-type-definitions
&
166 ,(append *new-auxiliary-types
*
167 (auxiliary-type-definitions env
))))
170 ;;;; runtime C values that don't correspond directly to Lisp types
172 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
173 ;;; 'cause it has to be real early in the cold-load order.
174 #!-sb-fluid
(declaim (freeze-type alien-value
))
175 (def!method print-object
((value alien-value
) stream
)
176 (print-unreadable-object (value stream
)
178 "~S ~S #X~8,'0X ~S ~S"
180 :sap
(sap-int (alien-value-sap value
))
181 :type
(unparse-alien-type (alien-value-type value
)))))
183 #!-sb-fluid
(declaim (inline null-alien
))
184 (defun null-alien (x)
186 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
187 (zerop (sap-int (alien-sap x
))))
189 (defmacro sap-alien
(sap type
&environment env
)
191 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
192 evaluated.) TYPE must be pointer-like."
193 (let ((alien-type (parse-alien-type type env
)))
194 (if (eq (compute-alien-rep-type alien-type
) 'system-area-pointer
)
195 `(%sap-alien
,sap
',alien-type
)
196 (error "cannot make an alien of type ~S out of a SAP" type
))))
198 (defun %sap-alien
(sap type
)
199 (declare (type system-area-pointer sap
)
200 (type alien-type type
))
201 (make-alien-value :sap sap
:type type
))
203 (defun alien-sap (alien)
205 "Return a System-Area-Pointer pointing to Alien's data."
206 (declare (type alien-value alien
))
207 (alien-value-sap alien
))
209 ;;;; allocation/deallocation of heap aliens
211 (defmacro make-alien
(type &optional size
&environment env
)
213 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
214 is supplied, how it is interpreted depends on TYPE. If TYPE is an array type,
215 SIZE is used as the first dimension for the allocated array. If TYPE is not an
216 array, then SIZE is the number of elements to allocate. The memory is
217 allocated using ``malloc'', so it can be passed to foreign functions which use
219 (let ((alien-type (if (alien-type-p type
)
221 (parse-alien-type type env
))))
222 (multiple-value-bind (size-expr element-type
)
223 (if (alien-array-type-p alien-type
)
224 (let ((dims (alien-array-type-dimensions alien-type
)))
229 "cannot override the size of zero-dimensional arrays"))
230 (when (constantp size
)
231 (setf alien-type
(copy-alien-array-type alien-type
))
232 (setf (alien-array-type-dimensions alien-type
)
233 (cons (constant-form-value size
) (cdr dims
)))))
235 (setf size
(car dims
)))
238 (values `(* ,size
,@(cdr dims
))
239 (alien-array-type-element-type alien-type
)))
240 (values (or size
1) alien-type
))
241 (let ((bits (alien-type-bits element-type
))
242 (alignment (alien-type-alignment element-type
)))
244 (error "The size of ~S is unknown."
245 (unparse-alien-type element-type
)))
247 (error "The alignment of ~S is unknown."
248 (unparse-alien-type element-type
)))
249 ;; This is the one place where the %SAP-ALIEN note is quite
250 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
251 ;; cannot be optimized away.
252 `(locally (declare (muffle-conditions compiler-note
))
253 (%sap-alien
(%make-alien
(* ,(align-offset bits alignment
)
255 ',(make-alien-pointer-type :to alien-type
)))))))
257 ;;; Allocate a block of memory at least BITS bits long and return a
258 ;;; system area pointer to it.
259 #!-sb-fluid
(declaim (inline %make-alien
))
260 (defun %make-alien
(bits)
261 (declare (type index bits
))
262 (alien-funcall (extern-alien "malloc"
263 (function system-area-pointer unsigned
))
264 (ash (the index
(+ bits
7)) -
3)))
266 #!-sb-fluid
(declaim (inline free-alien
))
267 (defun free-alien (alien)
269 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
270 by MAKE-ALIEN or malloc(3)."
271 (alien-funcall (extern-alien "free" (function (values) system-area-pointer
))
275 ;;;; the SLOT operator
277 ;;; Find the field named SLOT, or die trying.
278 (defun slot-or-lose (type slot
)
279 (declare (type alien-record-type type
)
281 (or (find slot
(alien-record-type-fields type
)
282 :key
#'alien-record-field-name
)
283 (error "There is no slot named ~S in ~S." slot type
)))
285 ;;; Extract the value from the named slot from the record ALIEN. If
286 ;;; ALIEN is actually a pointer, then DEREF it first.
287 (defun slot (alien slot
)
289 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
290 (declare (type alien-value alien
)
292 (optimize (inhibit-warnings 3)))
293 (let ((type (alien-value-type alien
)))
296 (slot (deref alien
) slot
))
298 (let ((field (slot-or-lose type slot
)))
299 (extract-alien-value (alien-value-sap alien
)
300 (alien-record-field-offset field
)
301 (alien-record-field-type field
)))))))
303 ;;; Deposit the value in the specified slot of the record ALIEN. If
304 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
305 ;;; this when it can't figure out anything better.
306 (defun %set-slot
(alien slot value
)
307 (declare (type alien-value alien
)
309 (optimize (inhibit-warnings 3)))
310 (let ((type (alien-value-type alien
)))
313 (%set-slot
(deref alien
) slot value
))
315 (let ((field (slot-or-lose type slot
)))
316 (deposit-alien-value (alien-value-sap alien
)
317 (alien-record-field-offset field
)
318 (alien-record-field-type field
)
321 ;;; Compute the address of the specified slot and return a pointer to it.
322 (defun %slot-addr
(alien slot
)
323 (declare (type alien-value alien
)
325 (optimize (inhibit-warnings 3)))
326 (let ((type (alien-value-type alien
)))
329 (%slot-addr
(deref alien
) slot
))
331 (let* ((field (slot-or-lose type slot
))
332 (offset (alien-record-field-offset field
))
333 (field-type (alien-record-field-type field
)))
334 (%sap-alien
(sap+ (alien-sap alien
) (/ offset sb
!vm
:n-byte-bits
))
335 (make-alien-pointer-type :to field-type
)))))))
337 ;;;; the DEREF operator
339 ;;; This function does most of the work of the different DEREF
340 ;;; methods. It returns two values: the type and the offset (in bits)
341 ;;; of the referred-to alien.
342 (defun deref-guts (alien indices
)
343 (declare (type alien-value alien
)
345 (values alien-type integer
))
346 (let ((type (alien-value-type alien
)))
350 (error "too many indices when DEREF'ing ~S: ~W"
353 (let ((element-type (alien-pointer-type-to type
)))
356 (* (align-offset (alien-type-bits element-type
)
357 (alien-type-alignment element-type
))
361 (unless (= (length indices
) (length (alien-array-type-dimensions type
)))
362 (error "incorrect number of indices when DEREF'ing ~S: ~W"
363 type
(length indices
)))
364 (labels ((frob (dims indices offset
)
367 (frob (cdr dims
) (cdr indices
)
368 (+ (if (zerop offset
)
370 (* offset
(car dims
)))
372 (let ((element-type (alien-array-type-element-type type
)))
374 (* (align-offset (alien-type-bits element-type
)
375 (alien-type-alignment element-type
))
376 (frob (alien-array-type-dimensions type
)
379 ;;; Dereference the alien and return the results.
380 (defun deref (alien &rest indices
)
382 "De-reference an Alien pointer or array. If an array, the indices are used
383 as the indices of the array element to access. If a pointer, one index can
384 optionally be specified, giving the equivalent of C pointer arithmetic."
385 (declare (type alien-value alien
)
387 (optimize (inhibit-warnings 3)))
388 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
389 (extract-alien-value (alien-value-sap alien
)
393 (defun %set-deref
(alien value
&rest indices
)
394 (declare (type alien-value alien
)
396 (optimize (inhibit-warnings 3)))
397 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
398 (deposit-alien-value (alien-value-sap alien
)
403 (defun %deref-addr
(alien &rest indices
)
404 (declare (type alien-value alien
)
406 (optimize (inhibit-warnings 3)))
407 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
408 (%sap-alien
(sap+ (alien-value-sap alien
) (/ offset sb
!vm
:n-byte-bits
))
409 (make-alien-pointer-type :to target-type
))))
411 ;;;; accessing heap alien variables
413 (defun %heap-alien
(info)
414 (declare (type heap-alien-info info
)
415 (optimize (inhibit-warnings 3)))
416 (extract-alien-value (eval (heap-alien-info-sap-form info
))
418 (heap-alien-info-type info
)))
420 (defun %set-heap-alien
(info value
)
421 (declare (type heap-alien-info info
)
422 (optimize (inhibit-warnings 3)))
423 (deposit-alien-value (eval (heap-alien-info-sap-form info
))
425 (heap-alien-info-type info
)
428 (defun %heap-alien-addr
(info)
429 (declare (type heap-alien-info info
)
430 (optimize (inhibit-warnings 3)))
431 (%sap-alien
(eval (heap-alien-info-sap-form info
))
432 (make-alien-pointer-type :to
(heap-alien-info-type info
))))
434 ;;;; accessing local aliens
436 (defun make-local-alien (info)
437 (let* ((alien (eval `(make-alien ,(local-alien-info-type info
))))
438 (alien-sap (alien-sap alien
)))
443 (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))
464 (info (if (and (consp info
)
465 (eq (car info
) 'quote
))
467 (error "Something is wrong; local-alien-info not found: ~S"
472 `(if (%local-alien-forced-to-memory-p
',info
)
473 (%set-local-alien
',info
,alien
,value
)
474 (let* ((,info-var
',(local-alien-info-type info
))
475 (,alloc-tmp
(deport-alloc ,value
,info-var
)))
476 (maybe-with-pinned-objects (,alloc-tmp
) (,(local-alien-info-type info
))
477 (setf ,alien
(deport ,alloc-tmp
,info-var
)))))
480 (defun %local-alien-forced-to-memory-p
(info)
481 (local-alien-info-force-to-memory-p info
))
483 (defun %local-alien-addr
(info alien
)
484 (declare (type local-alien-info info
))
485 (unless (local-alien-info-force-to-memory-p info
)
486 (error "~S isn't forced to memory. Something went wrong." alien
))
489 (defun dispose-local-alien (info alien
)
490 (declare (ignore info
))
491 (cancel-finalization alien
)
496 (defmacro cast
(alien type
&environment env
)
498 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
499 must be Alien array, pointer or function types."
500 `(%cast
,alien
',(parse-alien-type type env
)))
502 (defun %cast
(alien target-type
)
503 (declare (type alien-value alien
)
504 (type alien-type target-type
)
505 (optimize (safety 2))
506 (optimize (inhibit-warnings 3)))
507 (if (or (alien-pointer-type-p target-type
)
508 (alien-array-type-p target-type
)
509 (alien-fun-type-p target-type
))
510 (let ((alien-type (alien-value-type alien
)))
511 (if (or (alien-pointer-type-p alien-type
)
512 (alien-array-type-p alien-type
)
513 (alien-fun-type-p alien-type
))
514 (naturalize (alien-value-sap alien
) target-type
)
515 (error "~S cannot be casted." alien
)))
516 (error "cannot cast to alien type ~S" (unparse-alien-type target-type
))))
518 ;;;; the ALIEN-SIZE macro
520 (defmacro alien-size
(type &optional
(units :bits
) &environment env
)
522 "Return the size of the alien type TYPE. UNITS specifies the units to
523 use and can be either :BITS, :BYTES, or :WORDS."
524 (let* ((alien-type (parse-alien-type type env
))
525 (bits (alien-type-bits alien-type
)))
527 (values (ceiling bits
530 (:bytes sb
!vm
:n-byte-bits
)
531 (:words sb
!vm
:n-word-bits
))))
532 (error "unknown size for alien type ~S"
533 (unparse-alien-type alien-type
)))))
535 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
537 (defun coerce-to-interpreted-function (lambda-form)
539 (*evaluator-mode
* :interpret
))
540 (coerce lambda-form
'function
)))
542 (defun naturalize (alien type
)
543 (declare (type alien-type type
))
544 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type
))
547 (defun deport (value type
)
548 (declare (type alien-type type
))
549 (funcall (coerce-to-interpreted-function (compute-deport-lambda type
))
552 (defun deport-alloc (value type
)
553 (declare (type alien-type type
))
554 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type
))
557 (defun extract-alien-value (sap offset type
)
558 (declare (type system-area-pointer sap
)
559 (type unsigned-byte offset
)
560 (type alien-type type
))
561 (funcall (coerce-to-interpreted-function (compute-extract-lambda type
))
564 (defun deposit-alien-value (sap offset type value
)
565 (declare (type system-area-pointer sap
)
566 (type unsigned-byte offset
)
567 (type alien-type type
))
568 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type
))
569 sap offset type value
))
571 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
573 (defun alien-funcall (alien &rest args
)
575 "Call the foreign function ALIEN with the specified arguments. ALIEN's
576 type specifies the argument and result types."
577 (declare (type alien-value alien
))
578 (let ((type (alien-value-type alien
)))
581 (apply #'alien-funcall
(deref alien
) args
))
583 (unless (= (length (alien-fun-type-arg-types type
))
585 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
587 (length (alien-fun-type-arg-types type
))
589 (let ((stub (alien-fun-type-stub type
)))
593 (parms (make-gensym-list (length args
))))
595 `(lambda (,fun
,@parms
)
596 (declare (optimize (sb!c
::insert-step-conditions
0)))
597 (declare (type (alien ,type
) ,fun
))
598 (alien-funcall ,fun
,@parms
)))))
599 (setf (alien-fun-type-stub type
) stub
))
600 (apply stub alien args
)))
602 (error "~S is not an alien function." alien
)))))
604 (defmacro define-alien-routine
(name result-type
608 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
610 Define a foreign interface function for the routine with the specified NAME.
611 Also automatically DECLAIM the FTYPE of the defined function.
613 NAME may be either a string, a symbol, or a list of the form (string symbol).
615 RETURN-TYPE is the alien type for the function return value. VOID may be
616 used to specify a function with no result.
618 The remaining forms specify individual arguments that are passed to the
619 routine. ARG-NAME is a symbol that names the argument, primarily for
620 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
621 way that the argument is passed.
624 An :IN argument is simply passed by value. The value to be passed is
625 obtained from argument(s) to the interface function. No values are
626 returned for :In arguments. This is the default mode.
629 The specified argument type must be a pointer to a fixed sized object.
630 A pointer to a preallocated object is passed to the routine, and the
631 the object is accessed on return, with the value being returned from
632 the interface function. :OUT and :IN-OUT cannot be used with pointers
633 to arrays, records or functions.
636 This is similar to :IN, except that the argument values are stored
637 on the stack, and a pointer to the object is passed instead of
641 This is a combination of :OUT and :COPY. A pointer to the argument is
642 passed, with the object being initialized from the supplied argument
643 and the return value being determined by accessing the object on
645 (multiple-value-bind (lisp-name alien-name
)
646 (pick-lisp-and-alien-names name
)
647 (collect ((docs) (lisp-args) (lisp-arg-types)
649 (cond ((eql result-type
'void
)
650 ;; What values does a function return, if it
651 ;; returns no values? Exactly one - NIL. -- APD,
655 ;; FIXME: Check for VALUES.
656 (list `(alien ,result-type
)))))
657 (arg-types) (alien-vars)
658 (alien-args) (results))
662 (destructuring-bind (name type
&optional
(style :in
)) arg
663 (unless (member style
'(:in
:copy
:out
:in-out
))
664 (error "bogus argument style ~S in ~S" style arg
))
665 (when (and (member style
'(:out
:in-out
))
666 (typep (parse-alien-type type lexenv
)
667 'alien-pointer-type
))
668 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
671 (cond ((eq style
:in
)
675 (setq arg-type
`(* ,type
))
677 (alien-vars `(,name
,type
))
678 (alien-vars `(,name
,type
,name
)))
679 (alien-args `(addr ,name
))))
681 (unless (eq style
:out
)
684 ;; FIXME: It should be something
685 ;; like `(ALIEN ,ARG-TYPE), except
686 ;; for we also accept SAPs where
687 ;; pointers are required.
689 (when (or (eq style
:out
) (eq style
:in-out
))
691 (lisp-result-types `(alien ,type
))))))
693 ;; The theory behind this automatic DECLAIM is that (1) if
694 ;; you're calling C, static typing is what you're doing
695 ;; anyway, and (2) such a declamation can be (especially for
696 ;; alien values) both messy to do by hand and very important
697 ;; for performance of later code which uses the return value.
698 (declaim (ftype (function ,(lisp-arg-types)
699 (values ,@(lisp-result-types) &optional
))
701 (defun ,lisp-name
,(lisp-args)
704 ((,lisp-name
(function ,result-type
,@(arg-types))
708 (values (alien-funcall ,lisp-name
,@(alien-args))
711 (if (alien-values-type-p result-type
)
712 ;; FIXME: RESULT-TYPE is a type specifier, so it
713 ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
714 ;; that if RESULT-TYPE is VOID, then this code
715 ;; disagrees with the computation of the return type
716 ;; and with all usages of this macro. -- APD,
718 (let ((temps (make-gensym-list
720 (alien-values-type-values result-type
)))))
721 `(multiple-value-bind ,temps
722 (alien-funcall ,lisp-name
,@(alien-args))
723 (values ,@temps
,@(results))))
724 (values (alien-funcall ,lisp-name
,@(alien-args))
727 (defun alien-typep (object type
)
729 "Return T iff OBJECT is an alien of type TYPE."
730 (let ((lisp-rep-type (compute-lisp-rep-type type
)))
732 (typep object lisp-rep-type
)
733 (and (alien-value-p object
)
734 (alien-subtype-p (alien-value-type object
) type
)))))
738 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
740 (defvar *alien-callback-info
* nil
741 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
742 information we need to manipulate callbacks after their creation. Used for
743 changing the lisp-side function they point to, invalidation, etc.")
745 (defstruct callback-info
747 function
; NULL if invalid
751 (defun callback-info-key (info)
752 (cons (callback-info-specifier info
) (callback-info-function info
)))
754 (defun alien-callback-info (alien)
755 (cdr (assoc (alien-sap alien
) *alien-callback-info
* :test
#'sap
=)))
757 (defvar *alien-callbacks
* (make-hash-table :test
#'equal
)
758 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
759 memoization: we don't create new callbacks if one pointing to the correct
760 function with the same specifier already exists.")
762 (defvar *alien-callback-wrappers
* (make-hash-table :test
#'equal
)
763 "Cache of existing lisp weappers, indexed with SPECIFER. Used for memoization:
764 we don't create new wrappers if one for the same specifier already exists.")
766 (defvar *alien-callback-trampolines
* (make-array 32 :fill-pointer
0 :adjustable t
)
767 "Lisp trampoline store: assembler wrappers contain indexes to this, and
768 ENTER-ALIEN-CALLBACK pulls the corresponsing trampoline out and calls it.")
770 (defun %alien-callback-sap
(specifier result-type argument-types function wrapper
)
771 (let ((key (cons specifier function
)))
772 (or (gethash key
*alien-callbacks
*)
773 (setf (gethash key
*alien-callbacks
*)
774 (let* ((index (fill-pointer *alien-callback-trampolines
*))
775 ;; Aside from the INDEX this is known at
776 ;; compile-time, which could be utilized by
777 ;; having the two-stage assembler tramp &
778 ;; wrapper mentioned in [1] above: only the
779 ;; per-function tramp would need assembler at
780 ;; runtime. Possibly we could even pregenerate
781 ;; the code and just patch the index in later.
782 (assembler-wrapper (alien-callback-assembler-wrapper
783 index result-type argument-types
)))
785 (alien-callback-lisp-trampoline wrapper function
)
786 *alien-callback-trampolines
*)
787 ;; Assembler-wrapper is static, so sap-taking is safe.
788 (let ((sap (vector-sap assembler-wrapper
)))
789 (push (cons sap
(make-callback-info :specifier specifier
793 *alien-callback-info
*)
796 (defun alien-callback-lisp-trampoline (wrapper function
)
797 (declare (function wrapper
) (optimize speed
))
798 (lambda (args-pointer result-pointer
)
799 (funcall wrapper args-pointer result-pointer function
)))
801 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env
)
802 (let* ((arguments (make-gensym-list (length argument-types
)))
803 (argument-names arguments
)
804 (argument-specs (cddr specifier
)))
805 `(lambda (args-pointer result-pointer function
)
806 ;; FIXME: the saps are not gc safe
807 (let ((args-sap (int-sap
808 (sb!kernel
:get-lisp-obj-address args-pointer
)))
810 (sb!kernel
:get-lisp-obj-address result-pointer
))))
811 (declare (ignorable args-sap res-sap
))
815 for spec in argument-specs
816 collect
`(,(pop argument-names
) ,spec
817 :local
,(alien-callback-accessor-form
818 spec
'args-sap offset
))
819 do
(incf offset
(alien-callback-argument-bytes spec env
)))
820 ,(flet ((store (spec)
822 `(setf (deref (sap-alien res-sap
(* ,spec
)))
823 (funcall function
,@arguments
))
824 `(funcall function
,@arguments
))))
825 (cond ((alien-void-type-p result-type
)
827 ((alien-integer-type-p result-type
)
828 (if (alien-integer-type-signed result-type
)
830 ,(alien-type-word-aligned-bits result-type
)))
833 ,(alien-type-word-aligned-bits result-type
)))))
835 (store (unparse-alien-type result-type
)))))))
838 (defun invalid-alien-callback (&rest arguments
)
839 (declare (ignore arguments
))
840 (error "Invalid alien callback called."))
843 (defun parse-callback-specification (result-type lambda-list
)
845 `(function ,result-type
,@(mapcar #'second lambda-list
))
846 (mapcar #'first lambda-list
)))
849 (defun parse-alien-ftype (specifier env
)
850 (destructuring-bind (function result-type
&rest argument-types
)
852 (aver (eq 'function function
))
853 (values (let ((*values-type-okay
* t
))
854 (parse-alien-type result-type env
))
855 (mapcar (lambda (spec)
856 (parse-alien-type spec env
))
859 (defun alien-void-type-p (type)
860 (and (alien-values-type-p type
) (not (alien-values-type-values type
))))
862 (defun alien-type-word-aligned-bits (type)
863 (align-offset (alien-type-bits type
) sb
!vm
:n-word-bits
))
865 (defun alien-callback-argument-bytes (spec env
)
866 (let ((type (parse-alien-type spec env
)))
867 (if (or (alien-integer-type-p type
)
868 (alien-float-type-p type
)
869 (alien-pointer-type-p type
)
870 (alien-system-area-pointer-type-p type
))
871 (ceiling (alien-type-word-aligned-bits type
) sb
!vm
:n-byte-bits
)
872 (error "Unsupported callback argument type: ~A" type
))))
874 (defun enter-alien-callback (index return arguments
)
875 (funcall (aref *alien-callback-trampolines
* index
)
879 ;;; To ensure that callback wrapper functions continue working even
880 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
881 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
882 (defvar *enter-alien-callback
* #'enter-alien-callback
)
884 ;;;; interface (not public, yet) for alien callbacks
886 (defmacro alien-callback
(specifier function
&environment env
)
887 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
888 an alien function as a pointer to the FUNCTION. If a callback for the given
889 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
891 ;; Pull out as much work as is convenient to macro-expansion time, specifically
892 ;; everything that can be done given just the SPECIFIER and ENV.
893 (multiple-value-bind (result-type argument-types
) (parse-alien-ftype specifier env
)
895 (%alien-callback-sap
',specifier
',result-type
',argument-types
897 (or (gethash ',specifier
*alien-callback-wrappers
*)
898 (setf (gethash ',specifier
*alien-callback-wrappers
*)
900 ',(alien-callback-lisp-wrapper-lambda
901 specifier result-type argument-types env
)))))
902 ',(parse-alien-type specifier env
))))
904 (defun alien-callback-p (alien)
905 "Returns true if the alien is associated with a lisp-side callback,
906 and a secondary return value of true if the callback is still valid."
907 (let ((info (alien-callback-info alien
)))
909 (values t
(and (callback-info-function info
) t
)))))
911 (defun alien-callback-function (alien)
912 "Returns the lisp function designator associated with the callback."
913 (let ((info (alien-callback-info alien
)))
915 (callback-info-function info
))))
917 (defun (setf alien-callback-function
) (function alien
)
918 "Changes the lisp function designated by the callback."
919 (let ((info (alien-callback-info alien
)))
921 (error "Not an alien callback: ~S" alien
))
923 (let ((key (callback-info-key info
)))
924 (remhash key
*alien-callbacks
*)
925 (setf (gethash key
*alien-callbacks
*) (alien-sap alien
)))
927 (setf (aref *alien-callback-trampolines
* (callback-info-index info
))
928 (alien-callback-lisp-trampoline (callback-info-wrapper info
) function
))
930 (setf (callback-info-function info
) function
)
933 (defun invalidate-alien-callback (alien)
934 "Invalidates the callback designated by the alien, if any, allowing the
935 associated lisp function to be GC'd, and causing further calls to the same
936 callback signal an error."
937 (let ((info (alien-callback-info alien
)))
938 (when (and info
(callback-info-function info
))
940 (remhash (callback-info-key info
) *alien-callbacks
*)
942 (setf (aref *alien-callback-trampolines
* (callback-info-index info
))
943 #'invalid-alien-callback
)
945 (setf (callback-info-function info
) nil
)
948 ;;; FIXME: This call assembles a new callback for every closure,
949 ;;; which sucks hugely. ...not that I can think of an obvious
950 ;;; solution. Possibly maybe we could write a generalized closure
951 ;;; callback analogous to closure_tramp, and share the actual wrapper?
953 ;;; For lambdas that result in simple-funs we get the callback from
954 ;;; the cache on subsequent calls.
955 (defmacro alien-lambda
(result-type typed-lambda-list
&body forms
)
956 (multiple-value-bind (specifier lambda-list
)
957 (parse-callback-specification result-type typed-lambda-list
)
958 `(alien-callback ,specifier
(lambda ,lambda-list
,@forms
))))
960 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
961 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
962 ;;; the FDEFINITION should invalidate the callback, and redefining the
963 ;;; callback should change existing callbacks to point to the new defintion.
964 (defmacro define-alien-callback
(name result-type typed-lambda-list
&body forms
)
965 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
966 the alien callback for that function with the given alien type."
967 (declare (symbol name
))
968 (multiple-value-bind (specifier lambda-list
)
969 (parse-callback-specification result-type typed-lambda-list
)
971 (defun ,name
,lambda-list
,@forms
)
972 (defparameter ,name
(alien-callback ,specifier
#',name
)))))