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)
39 (error "~@<~:IMalformed alien name. Acceptable formats are:~
40 ~:@_ (\"alien_name\" LISP-NAME)~
41 ~:@_ FOO-BAR - equivalent to (\"foo_bar\" FOO-BAR)~
42 ~:@_ \"foo_bar\" - equivalent to (\"foo_bar\" FOO-BAR)~:@>")))
45 (values (guess-lisp-name-from-alien-name name)
46 (coerce name 'simple-string)))
48 (values name (guess-alien-name-from-lisp-name name)))
50 (unless (and (proper-list-of-length-p name 2)
51 (symbolp (second name))
52 (stringp (first name)))
54 (values (second name) (coerce (first name) 'simple-string)))
58 (defmacro define-alien-variable (name type &environment env)
60 "Define NAME as an external alien variable of type TYPE. NAME should
61 be a list of a string holding the alien name and a symbol to use as
62 the Lisp name. If NAME is just a symbol or string, then the other name
63 is guessed from the one supplied."
64 (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
65 (with-auxiliary-alien-types env
66 (let ((alien-type (parse-alien-type type env)))
67 `(eval-when (:compile-toplevel :load-toplevel :execute)
68 ,@(when *new-auxiliary-types*
69 `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
70 (%define-alien-variable ',lisp-name
74 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
75 (eval-when (:compile-toplevel :load-toplevel :execute)
76 (defun %define-alien-variable (lisp-name alien-name type)
77 (setf (info :variable :kind lisp-name) :alien)
78 (setf (info :variable :where-from lisp-name) :defined)
79 (setf (info :variable :alien-info lisp-name)
80 (make-heap-alien-info :type type
81 :alien-name alien-name
84 (defun alien-value (symbol)
86 "Returns the value of the alien variable bound to SYMBOL. Signals an
87 error if SYMBOL is not bound to an alien variable, or if the alien
88 variable is undefined."
89 (%heap-alien (or (info :variable :alien-info symbol)
90 (error 'unbound-variable :name symbol))))
92 (defmacro extern-alien (name type &environment env)
94 "Access the alien variable named NAME, assuming it is of type TYPE.
96 (let* ((alien-name (etypecase name
97 (symbol (guess-alien-name-from-lisp-name name))
99 (alien-type (parse-alien-type type env))
100 (datap (not (alien-fun-type-p alien-type))))
101 `(%alien-value (foreign-symbol-sap ,alien-name ,datap) 0 ',alien-type)))
103 (defmacro with-alien (bindings &body body &environment env)
105 "Establish some local alien variables. Each BINDING is of the form:
106 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
107 ALLOCATION should be one of:
109 The alien is allocated on the stack, and has dynamic extent.
111 No alien is allocated, but VAR is established as a local name for
112 the external alien given by EXTERNAL-NAME."
115 ;; The alien is allocated on the heap, and has infinite extent. The alien
116 ;; is allocated at load time, so the same piece of memory is used each time
117 ;; this form executes.
118 (/show "entering WITH-ALIEN" bindings)
119 (with-auxiliary-alien-types env
120 (dolist (binding (reverse bindings))
123 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
125 (/show symbol type opt1 opt2)
126 (let* ((alien-type (parse-alien-type type env))
127 (datap (not (alien-fun-type-p alien-type))))
129 (multiple-value-bind (allocation initial-value)
134 (values opt1 (guess-alien-name-from-lisp-name symbol)))
138 (values :local opt1))))
139 (/show allocation initial-value)
145 (make-symbol (concatenate 'string "SAP-FOR-"
146 (symbol-name symbol)))))
147 `((let ((,sap (load-time-value (%make-alien ...))))
148 (declare (type system-area-pointer ,sap))
150 ((,symbol (sap-alien ,sap ,type)))
151 ,@(when initial-value
152 `((setq ,symbol ,initial-value)))
155 (/show0 ":EXTERN case")
159 (foreign-symbol-sap ,initial-value ,datap) 0 ,alien-type)))
162 (/show0 ":LOCAL case")
163 (let* ((var (sb!xc:gensym "VAR"))
164 (initval (if initial-value (sb!xc:gensym "INITVAL")))
165 (info (make-local-alien-info :type alien-type))
167 `((note-local-alien-type ',info ,var)
168 (symbol-macrolet ((,symbol (local-alien ',info ,var)))
169 ,@(when initial-value
170 `((setq ,symbol ,initval)))
174 `((let ((,initval ,initial-value))
177 (/show var initval info)
179 `((let ((,var (make-local-alien ',info)))
181 ;; FIXME: This version is less efficient then it needs to be, since
182 ;; it could just save and restore the number-stack pointer once,
183 ;; instead of doing multiple decrements if there are multiple bindings.
188 (setf ,var (make-local-alien ',info))
191 (dispose-local-alien ',info ,var))))))))))))
192 (/show "revised" body)
193 (verify-local-auxiliaries-okay)
194 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
195 `(symbol-macrolet ((&auxiliary-type-definitions&
196 ,(append *new-auxiliary-types*
197 (auxiliary-type-definitions env))))
199 (let ((sb!vm::*alien-stack* sb!vm::*alien-stack*))
204 ;;;; runtime C values that don't correspond directly to Lisp types
206 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
207 ;;; 'cause it has to be real early in the cold-load order.
208 #!-sb-fluid (declaim (freeze-type alien-value))
209 (def!method print-object ((value alien-value) stream)
210 (print-unreadable-object (value stream)
212 "~S ~S #X~8,'0X ~S ~S"
214 :sap (sap-int (alien-value-sap value))
215 :type (unparse-alien-type (alien-value-type value)))))
217 #!-sb-fluid (declaim (inline null-alien))
218 (defun null-alien (x)
220 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
221 (zerop (sap-int (alien-sap x))))
223 (defmacro sap-alien (sap type &environment env)
225 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
226 evaluated.) TYPE must be pointer-like."
227 (let ((alien-type (parse-alien-type type env)))
228 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
229 `(%sap-alien ,sap ',alien-type)
230 (error "cannot make an alien of type ~S out of a SAP" type))))
232 (defun %sap-alien (sap type)
233 (declare (type system-area-pointer sap)
234 (type alien-type type))
235 (make-alien-value :sap sap :type type))
237 (defun alien-sap (alien)
239 "Return a System-Area-Pointer pointing to Alien's data."
240 (declare (type alien-value alien))
241 (alien-value-sap alien))
243 ;;;; allocation/deallocation of heap aliens
245 (defmacro make-alien (type &optional size &environment env)
247 "Allocate an alien of type TYPE in foreign heap, and return an alien
248 pointer to it. The allocated memory is not initialized, and may
249 contain garbage. The memory is allocated using malloc(3), so it can be
250 passed to foreign functions which use free(3), or released using
253 For alien stack allocation, see macro WITH-ALIEN.
255 The TYPE argument is not evaluated. If SIZE is supplied, how it is
256 interpreted depends on TYPE:
258 * When TYPE is a foreign array type, an array of that type is
259 allocated, and a pointer to it is returned. Note that you
260 must use DEREF to first access the arrey through the pointer.
262 If supplied, SIZE is used as the first dimension for the array.
264 * When TYPE is any other foreign type, then an object for that
265 type is allocated, and a pointer to it is returned. So
266 (make-alien int) returns a (* int).
268 If SIZE is specified, then a block of that many objects is
269 allocated, with the result pointing to the first one.
273 (defvar *foo* (make-alien (array char 10)))
274 (type-of *foo*) ; => (alien (* (array (signed 8) 10)))
275 (setf (deref (deref foo) 0) 10) ; => 10
277 (make-alien char 12) ; => (alien (* (signed 8)))
279 (let ((alien-type (if (alien-type-p type)
281 (parse-alien-type type env))))
282 (multiple-value-bind (size-expr element-type)
283 (if (alien-array-type-p alien-type)
284 (let ((dims (alien-array-type-dimensions alien-type)))
289 "cannot override the size of zero-dimensional arrays"))
290 (when (constantp size)
291 (setf alien-type (copy-alien-array-type alien-type))
292 (setf (alien-array-type-dimensions alien-type)
293 (cons (constant-form-value size) (cdr dims)))))
295 (setf size (car dims)))
298 (values `(* ,size ,@(cdr dims))
299 (alien-array-type-element-type alien-type)))
300 (values (or size 1) alien-type))
301 (let ((bits (alien-type-bits element-type))
302 (alignment (alien-type-alignment element-type)))
304 (error "The size of ~S is unknown."
305 (unparse-alien-type element-type)))
307 (error "The alignment of ~S is unknown."
308 (unparse-alien-type element-type)))
309 ;; This is the one place where the %SAP-ALIEN note is quite
310 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
311 ;; cannot be optimized away.
312 `(locally (declare (muffle-conditions compiler-note))
313 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
314 (%sap-alien (%make-alien (* ,(ash (+ 7 (align-offset bits alignment)) -3)
315 (the index ,size-expr)))
316 ',(make-alien-pointer-type :to alien-type)))))))
318 (defun malloc-error (bytes errno)
319 (error 'simple-storage-condition
320 :format-control "~A: malloc() of ~S bytes failed."
321 :format-arguments (list (strerror errno) bytes)))
323 ;;; Allocate a block of memory at least BITS bits long and return a
324 ;;; system area pointer to it.
325 #!-sb-fluid (declaim (inline %make-alien))
326 (defun %make-alien (bytes)
327 (declare (type index bytes)
328 (optimize (sb!c:alien-funcall-saves-fp-and-pc 0)))
329 (let ((sap (alien-funcall (extern-alien "malloc"
330 (function system-area-pointer size-t))
332 (if (and (not (eql 0 bytes)) (eql 0 (sap-int sap)))
333 (malloc-error bytes (get-errno))
336 #!-sb-fluid (declaim (inline free-alien))
337 (defun free-alien (alien)
339 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
340 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
341 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
345 (declaim (type (sfunction * system-area-pointer) %make-alien-string))
346 (defun %make-alien-string (string &key (start 0) end
347 (external-format :default)
349 ;; FIXME: This is slow. We want a function to get the length of the
350 ;; encoded string so we can allocate the foreign memory first and
351 ;; encode directly there.
352 (let* ((octets (string-to-octets string
353 :start start :end end
354 :external-format external-format
355 :null-terminate null-terminate))
356 (count (length octets))
357 (buf (%make-alien count)))
358 (sb!kernel:copy-ub8-to-system-area octets 0 buf 0 count)
361 (defun make-alien-string (string &rest rest
363 (external-format :default)
365 "Copy part of STRING delimited by START and END into freshly
366 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
367 Returns the allocated string as a (* CHAR) alien, and the number of
368 bytes allocated as secondary value.
370 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
371 true (the default), the alien string is terminated by an additional
374 (declare (ignore start end external-format null-terminate))
375 (multiple-value-bind (sap bytes)
376 (apply #'%make-alien-string string rest)
377 (values (%sap-alien sap (parse-alien-type '(* char) nil))
380 (define-compiler-macro make-alien-string (&rest args)
381 `(multiple-value-bind (sap bytes) (%make-alien-string ,@args)
382 (values (%sap-alien sap ',(parse-alien-type '(* char) nil))
385 ;;;; the SLOT operator
387 ;;; Find the field named SLOT, or die trying.
388 (defun slot-or-lose (type slot)
389 (declare (type alien-record-type type)
391 (or (find slot (alien-record-type-fields type)
392 :key #'alien-record-field-name)
393 (error "There is no slot named ~S in ~S." slot type)))
395 ;;; Extract the value from the named slot from the record ALIEN. If
396 ;;; ALIEN is actually a pointer, then DEREF it first.
397 (defun slot (alien slot)
399 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
400 (declare (type alien-value alien)
402 (optimize (inhibit-warnings 3)))
403 (let ((type (alien-value-type alien)))
406 (slot (deref alien) slot))
408 (let ((field (slot-or-lose type slot)))
409 (%alien-value (alien-value-sap alien)
410 (alien-record-field-offset field)
411 (alien-record-field-type field)))))))
413 ;;; Deposit the value in the specified slot of the record ALIEN. If
414 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
415 ;;; this when it can't figure out anything better.
416 (defun %set-slot (alien slot value)
417 (declare (type alien-value alien)
419 (optimize (inhibit-warnings 3)))
420 (let ((type (alien-value-type alien)))
423 (%set-slot (deref alien) slot value))
425 (let ((field (slot-or-lose type slot)))
426 (setf (%alien-value (alien-value-sap alien)
427 (alien-record-field-offset field)
428 (alien-record-field-type field))
431 ;;; Compute the address of the specified slot and return a pointer to it.
432 (defun %slot-addr (alien slot)
433 (declare (type alien-value alien)
435 (optimize (inhibit-warnings 3)))
436 (let ((type (alien-value-type alien)))
439 (%slot-addr (deref alien) slot))
441 (let* ((field (slot-or-lose type slot))
442 (offset (alien-record-field-offset field))
443 (field-type (alien-record-field-type field)))
444 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
445 (make-alien-pointer-type :to field-type)))))))
447 ;;;; the DEREF operator
449 ;;; This function does most of the work of the different DEREF
450 ;;; methods. It returns two values: the type and the offset (in bits)
451 ;;; of the referred-to alien.
452 (defun deref-guts (alien indices)
453 (declare (type alien-value alien)
455 (values alien-type integer))
456 (let ((type (alien-value-type alien)))
460 (error "too many indices when DEREF'ing ~S: ~W"
463 (let ((element-type (alien-pointer-type-to type)))
466 (* (align-offset (alien-type-bits element-type)
467 (alien-type-alignment element-type))
471 (unless (= (length indices) (length (alien-array-type-dimensions type)))
472 (error "incorrect number of indices when DEREF'ing ~S: ~W"
473 type (length indices)))
474 (labels ((frob (dims indices offset)
477 (frob (cdr dims) (cdr indices)
478 (+ (if (zerop offset)
480 (* offset (car dims)))
482 (let ((element-type (alien-array-type-element-type type)))
484 (* (align-offset (alien-type-bits element-type)
485 (alien-type-alignment element-type))
486 (frob (alien-array-type-dimensions type)
489 ;;; Dereference the alien and return the results.
490 (defun deref (alien &rest indices)
492 "De-reference an Alien pointer or array. If an array, the indices are used
493 as the indices of the array element to access. If a pointer, one index can
494 optionally be specified, giving the equivalent of C pointer arithmetic."
495 (declare (type alien-value alien)
497 (optimize (inhibit-warnings 3)))
498 (multiple-value-bind (target-type offset) (deref-guts alien indices)
499 (%alien-value (alien-value-sap alien)
503 (defun %set-deref (alien value &rest indices)
504 (declare (type alien-value alien)
506 (optimize (inhibit-warnings 3)))
507 (multiple-value-bind (target-type offset) (deref-guts alien indices)
508 (setf (%alien-value (alien-value-sap alien)
513 (defun %deref-addr (alien &rest indices)
514 (declare (type alien-value alien)
516 (optimize (inhibit-warnings 3)))
517 (multiple-value-bind (target-type offset) (deref-guts alien indices)
518 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
519 (make-alien-pointer-type :to target-type))))
521 ;;;; accessing heap alien variables
523 (defun %heap-alien (info)
524 (declare (type heap-alien-info info)
525 (optimize (inhibit-warnings 3)))
526 (%alien-value (heap-alien-info-sap info)
528 (heap-alien-info-type info)))
530 (defun %set-heap-alien (info value)
531 (declare (type heap-alien-info info)
532 (optimize (inhibit-warnings 3)))
533 (setf (%alien-value (heap-alien-info-sap info)
535 (heap-alien-info-type info))
538 (defun %heap-alien-addr (info)
539 (declare (type heap-alien-info info)
540 (optimize (inhibit-warnings 3)))
541 (%sap-alien (heap-alien-info-sap info)
542 (make-alien-pointer-type :to (heap-alien-info-type info))))
544 ;;;; accessing local aliens
546 (defun make-local-alien (info)
547 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
548 (alien-sap (alien-sap alien)))
553 (extern-alien "free" (function (values) system-area-pointer))
558 (defun note-local-alien-type (info alien)
559 (declare (ignore info alien))
562 (defun local-alien (info alien)
563 (declare (ignore info))
566 (defun %set-local-alien (info alien value)
567 (declare (ignore info))
568 (setf (deref alien) value))
570 (define-setf-expander local-alien (&whole whole info alien)
571 (let ((value (gensym))
574 (info (if (and (consp info)
575 (eq (car info) 'quote))
577 (error "Something is wrong; local-alien-info not found: ~S"
582 `(if (%local-alien-forced-to-memory-p ',info)
583 (%set-local-alien ',info ,alien ,value)
584 (let* ((,info-var ',(local-alien-info-type info))
585 (,alloc-tmp (deport-alloc ,value ,info-var)))
586 (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
587 (setf ,alien (deport ,alloc-tmp ,info-var)))))
590 (defun %local-alien-forced-to-memory-p (info)
591 (local-alien-info-force-to-memory-p info))
593 (defun %local-alien-addr (info alien)
594 (declare (type local-alien-info info))
595 (unless (local-alien-info-force-to-memory-p info)
596 (error "~S isn't forced to memory. Something went wrong." alien))
599 (defun dispose-local-alien (info alien)
600 (declare (ignore info))
601 (cancel-finalization alien)
606 (defmacro cast (alien type &environment env)
608 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
609 must be Alien array, pointer or function types."
610 `(%cast ,alien ',(parse-alien-type type env)))
612 (defun %cast (alien target-type)
613 (declare (type alien-value alien)
614 (type alien-type target-type)
615 (optimize (safety 2))
616 (optimize (inhibit-warnings 3)))
617 (if (or (alien-pointer-type-p target-type)
618 (alien-array-type-p target-type)
619 (alien-fun-type-p target-type))
620 (let ((alien-type (alien-value-type alien)))
621 (if (or (alien-pointer-type-p alien-type)
622 (alien-array-type-p alien-type)
623 (alien-fun-type-p alien-type))
624 (naturalize (alien-value-sap alien) target-type)
625 (error "~S cannot be casted." alien)))
626 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
628 ;;;; the ALIEN-SIZE macro
630 (defmacro alien-size (type &optional (units :bits) &environment env)
632 "Return the size of the alien type TYPE. UNITS specifies the units to
633 use and can be either :BITS, :BYTES, or :WORDS."
634 (let* ((alien-type (parse-alien-type type env))
635 (bits (alien-type-bits alien-type)))
637 (values (ceiling bits
640 (:bytes sb!vm:n-byte-bits)
641 (:words sb!vm:n-word-bits))))
642 (error "unknown size for alien type ~S"
643 (unparse-alien-type alien-type)))))
645 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
647 (defun coerce-to-interpreted-function (lambda-form)
649 (*evaluator-mode* :interpret))
650 (coerce lambda-form 'function)))
652 (defun naturalize (alien type)
653 (declare (type alien-type type))
654 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
657 (defun deport (value type)
658 (declare (type alien-type type))
659 (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
662 (defun deport-alloc (value type)
663 (declare (type alien-type type))
664 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
667 (defun %alien-value (sap offset type)
668 (declare (type system-area-pointer sap)
669 (type unsigned-byte offset)
670 (type alien-type type))
671 (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
674 (defun (setf %alien-value) (value sap offset type)
675 (declare (type system-area-pointer sap)
676 (type unsigned-byte offset)
677 (type alien-type type))
678 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
679 value sap offset type))
681 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
683 (defun alien-funcall (alien &rest args)
685 "Call the foreign function ALIEN with the specified arguments. ALIEN's
686 type specifies the argument and result types."
687 (declare (type alien-value alien))
688 (let ((type (alien-value-type alien)))
691 (apply #'alien-funcall (deref alien) args))
693 (unless (= (length (alien-fun-type-arg-types type))
695 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
697 (length (alien-fun-type-arg-types type))
699 (let ((stub (alien-fun-type-stub type)))
702 (let ((fun (sb!xc:gensym "FUN"))
703 (parms (make-gensym-list (length args))))
705 `(lambda (,fun ,@parms)
706 (declare (optimize (sb!c::insert-step-conditions 0)))
707 (declare (type (alien ,type) ,fun))
708 (alien-funcall ,fun ,@parms)))))
709 (setf (alien-fun-type-stub type) stub))
710 (apply stub alien args)))
712 (error "~S is not an alien function." alien)))))
714 (defmacro define-alien-routine (name result-type
718 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
720 Define a foreign interface function for the routine with the specified NAME.
721 Also automatically DECLAIM the FTYPE of the defined function.
723 NAME may be either a string, a symbol, or a list of the form (string symbol).
725 RETURN-TYPE is the alien type for the function return value. VOID may be
726 used to specify a function with no result.
728 The remaining forms specify individual arguments that are passed to the
729 routine. ARG-NAME is a symbol that names the argument, primarily for
730 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
731 way that the argument is passed.
734 An :IN argument is simply passed by value. The value to be passed is
735 obtained from argument(s) to the interface function. No values are
736 returned for :In arguments. This is the default mode.
739 The specified argument type must be a pointer to a fixed sized object.
740 A pointer to a preallocated object is passed to the routine, and the
741 the object is accessed on return, with the value being returned from
742 the interface function. :OUT and :IN-OUT cannot be used with pointers
743 to arrays, records or functions.
746 This is similar to :IN, except that the argument values are stored
747 on the stack, and a pointer to the object is passed instead of
751 This is a combination of :OUT and :COPY. A pointer to the argument is
752 passed, with the object being initialized from the supplied argument
753 and the return value being determined by accessing the object on
755 (multiple-value-bind (lisp-name alien-name)
756 (pick-lisp-and-alien-names name)
757 (collect ((docs) (lisp-args) (lisp-arg-types)
759 (cond ((eql result-type 'void)
760 ;; What values does a function return, if it
761 ;; returns no values? Exactly one - NIL. -- APD,
765 ;; FIXME: Check for VALUES.
766 (list `(alien ,result-type)))))
767 (arg-types) (alien-vars)
768 (alien-args) (results))
772 (destructuring-bind (name type &optional (style :in)) arg
773 (unless (member style '(:in :copy :out :in-out))
774 (error "bogus argument style ~S in ~S" style arg))
775 (when (and (member style '(:out :in-out))
776 (typep (parse-alien-type type lexenv)
777 'alien-pointer-type))
778 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
781 (cond ((eq style :in)
785 (setq arg-type `(* ,type))
787 (alien-vars `(,name ,type))
788 (alien-vars `(,name ,type ,name)))
789 (alien-args `(addr ,name))))
791 (unless (eq style :out)
794 ;; FIXME: It should be something
795 ;; like `(ALIEN ,ARG-TYPE), except
796 ;; for we also accept SAPs where
797 ;; pointers are required.
799 (when (or (eq style :out) (eq style :in-out))
801 (lisp-result-types `(alien ,type))))))
803 ;; The theory behind this automatic DECLAIM is that (1) if
804 ;; you're calling C, static typing is what you're doing
805 ;; anyway, and (2) such a declamation can be (especially for
806 ;; alien values) both messy to do by hand and very important
807 ;; for performance of later code which uses the return value.
808 (declaim (ftype (function ,(lisp-arg-types)
809 (values ,@(lisp-result-types) &optional))
811 (defun ,lisp-name ,(lisp-args)
814 ((,lisp-name (function ,result-type ,@(arg-types))
817 ,@(if (eq 'void result-type)
818 `((alien-funcall ,lisp-name ,@(alien-args))
819 (values nil ,@(results)))
820 `((values (alien-funcall ,lisp-name ,@(alien-args))
823 (defun alien-typep (object type)
825 "Return T iff OBJECT is an alien of type TYPE."
826 (let ((lisp-rep-type (compute-lisp-rep-type type)))
828 (typep object lisp-rep-type)
829 (and (alien-value-p object)
830 (alien-subtype-p (alien-value-type object) type)))))
832 (defun alien-value-typep (object type)
833 (when (alien-value-p object)
834 (alien-subtype-p (alien-value-type object) type)))
838 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
840 (defvar *alien-callback-info* nil
841 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
842 information we need to manipulate callbacks after their creation. Used for
843 changing the lisp-side function they point to, invalidation, etc.")
845 (defstruct callback-info
847 function ; NULL if invalid
851 (defun callback-info-key (info)
852 (cons (callback-info-specifier info) (callback-info-function info)))
854 (defun alien-callback-info (alien)
855 (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
857 (defvar *alien-callbacks* (make-hash-table :test #'equal)
858 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
859 memoization: we don't create new callbacks if one pointing to the correct
860 function with the same specifier already exists.")
862 (defvar *alien-callback-wrappers* (make-hash-table :test #'equal)
863 "Cache of existing lisp weappers, indexed with SPECIFER. Used for memoization:
864 we don't create new wrappers if one for the same specifier already exists.")
866 (defvar *alien-callback-trampolines* (make-array 32 :fill-pointer 0 :adjustable t)
867 "Lisp trampoline store: assembler wrappers contain indexes to this, and
868 ENTER-ALIEN-CALLBACK pulls the corresponsing trampoline out and calls it.")
870 (defun %alien-callback-sap (specifier result-type argument-types function wrapper
872 (declare #!-x86 (ignore call-type))
873 (let ((key (list specifier function)))
874 (or (gethash key *alien-callbacks*)
875 (setf (gethash key *alien-callbacks*)
876 (let* ((index (fill-pointer *alien-callback-trampolines*))
877 ;; Aside from the INDEX this is known at
878 ;; compile-time, which could be utilized by
879 ;; having the two-stage assembler tramp &
880 ;; wrapper mentioned in [1] above: only the
881 ;; per-function tramp would need assembler at
882 ;; runtime. Possibly we could even pregenerate
883 ;; the code and just patch the index in later.
885 (alien-callback-assembler-wrapper
886 index result-type argument-types
888 (if (eq call-type :stdcall)
891 (mapcar 'alien-type-word-aligned-bits
896 (alien-callback-lisp-trampoline wrapper function)
897 *alien-callback-trampolines*)
898 ;; Assembler-wrapper is static, so sap-taking is safe.
899 (let ((sap (vector-sap assembler-wrapper)))
900 (push (cons sap (make-callback-info :specifier specifier
904 *alien-callback-info*)
907 (defun alien-callback-lisp-trampoline (wrapper function)
908 (declare (function wrapper) (optimize speed))
909 (lambda (args-pointer result-pointer)
910 (funcall wrapper args-pointer result-pointer function)))
912 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
913 (let* ((arguments (make-gensym-list (length argument-types)))
914 (argument-names arguments)
915 (argument-specs (cddr specifier)))
916 `(lambda (args-pointer result-pointer function)
917 ;; FIXME: the saps are not gc safe
918 (let ((args-sap (int-sap
919 (sb!kernel:get-lisp-obj-address args-pointer)))
921 (sb!kernel:get-lisp-obj-address result-pointer))))
922 (declare (ignorable args-sap res-sap))
926 for spec in argument-specs
927 collect `(,(pop argument-names) ,spec
928 :local ,(alien-callback-accessor-form
929 spec 'args-sap offset))
930 do (incf offset (alien-callback-argument-bytes spec env)))
931 ,(flet ((store (spec real-type)
933 `(setf (deref (sap-alien res-sap (* ,spec)))
936 (funcall function ,@arguments))
937 `(funcall function ,@arguments)))
938 `(funcall function ,@arguments))))
939 (cond ((alien-void-type-p result-type)
941 ((alien-integer-type-p result-type)
942 ;; Integer types should be padded out to a full
943 ;; register width, to comply with most ABI calling
944 ;; conventions, but should be typechecked on the
945 ;; declared type width, hence the following:
946 (if (alien-integer-type-signed result-type)
948 ,(alien-type-word-aligned-bits result-type))
949 `(signed-byte ,(alien-type-bits result-type)))
952 ,(alien-type-word-aligned-bits result-type))
953 `(unsigned-byte ,(alien-type-bits result-type)))))
955 (store (unparse-alien-type result-type) nil))))))
958 (defun invalid-alien-callback (&rest arguments)
959 (declare (ignore arguments))
960 (error "Invalid alien callback called."))
963 (defun parse-callback-specification (result-type lambda-list)
965 `(function ,result-type ,@(mapcar #'second lambda-list))
966 (mapcar #'first lambda-list)))
969 (defun parse-alien-ftype (specifier env)
970 (destructuring-bind (function result-type &rest argument-types)
972 (aver (eq 'function function))
973 (multiple-value-bind (bare-result-type calling-convention)
974 (typecase result-type
975 ((cons calling-convention *)
976 (values (second result-type) (first result-type)))
978 (values (let ((*values-type-okay* t))
979 (parse-alien-type bare-result-type env))
980 (mapcar (lambda (spec)
981 (parse-alien-type spec env))
983 calling-convention))))
985 (defun alien-void-type-p (type)
986 (and (alien-values-type-p type) (not (alien-values-type-values type))))
988 (defun alien-type-word-aligned-bits (type)
989 (align-offset (alien-type-bits type) sb!vm:n-word-bits))
991 (defun alien-callback-argument-bytes (spec env)
992 (let ((type (parse-alien-type spec env)))
993 (if (or (alien-integer-type-p type)
994 (alien-float-type-p type)
995 (alien-pointer-type-p type)
996 (alien-system-area-pointer-type-p type))
997 (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
998 (error "Unsupported callback argument type: ~A" type))))
1000 (defun enter-alien-callback (index return arguments)
1001 (funcall (aref *alien-callback-trampolines* index)
1005 ;;; To ensure that callback wrapper functions continue working even
1006 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
1007 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
1008 (defvar *enter-alien-callback* #'enter-alien-callback)
1010 ;;;; interface (not public, yet) for alien callbacks
1012 (defmacro alien-callback (specifier function &environment env)
1013 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
1014 an alien function as a pointer to the FUNCTION. If a callback for the given
1015 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
1017 ;; Pull out as much work as is convenient to macro-expansion time, specifically
1018 ;; everything that can be done given just the SPECIFIER and ENV.
1019 (multiple-value-bind (result-type argument-types call-type)
1020 (parse-alien-ftype specifier env)
1022 (%alien-callback-sap ',specifier ',result-type ',argument-types
1024 (or (gethash ',specifier *alien-callback-wrappers*)
1025 (setf (gethash ',specifier *alien-callback-wrappers*)
1027 ',(alien-callback-lisp-wrapper-lambda
1028 specifier result-type argument-types env))))
1030 ',(parse-alien-type specifier env))))
1032 (defun alien-callback-p (alien)
1033 "Returns true if the alien is associated with a lisp-side callback,
1034 and a secondary return value of true if the callback is still valid."
1035 (let ((info (alien-callback-info alien)))
1037 (values t (and (callback-info-function info) t)))))
1039 (defun alien-callback-function (alien)
1040 "Returns the lisp function designator associated with the callback."
1041 (let ((info (alien-callback-info alien)))
1043 (callback-info-function info))))
1045 (defun (setf alien-callback-function) (function alien)
1046 "Changes the lisp function designated by the callback."
1047 (let ((info (alien-callback-info alien)))
1049 (error "Not an alien callback: ~S" alien))
1051 (let ((key (callback-info-key info)))
1052 (remhash key *alien-callbacks*)
1053 (setf (gethash key *alien-callbacks*) (alien-sap alien)))
1055 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1056 (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
1058 (setf (callback-info-function info) function)
1061 (defun invalidate-alien-callback (alien)
1062 "Invalidates the callback designated by the alien, if any, allowing the
1063 associated lisp function to be GC'd, and causing further calls to the same
1064 callback signal an error."
1065 (let ((info (alien-callback-info alien)))
1066 (when (and info (callback-info-function info))
1068 (remhash (callback-info-key info) *alien-callbacks*)
1070 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1071 #'invalid-alien-callback)
1073 (setf (callback-info-function info) nil)
1076 ;;; FIXME: This call assembles a new callback for every closure,
1077 ;;; which sucks hugely. ...not that I can think of an obvious
1078 ;;; solution. Possibly maybe we could write a generalized closure
1079 ;;; callback analogous to closure_tramp, and share the actual wrapper?
1081 ;;; For lambdas that result in simple-funs we get the callback from
1082 ;;; the cache on subsequent calls.
1083 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
1084 (multiple-value-bind (specifier lambda-list)
1085 (parse-callback-specification result-type typed-lambda-list)
1086 `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
1088 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
1089 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
1090 ;;; the FDEFINITION should invalidate the callback, and redefining the
1091 ;;; callback should change existing callbacks to point to the new defintion.
1092 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
1093 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
1094 the alien callback for that function with the given alien type."
1095 (declare (symbol name))
1096 (multiple-value-bind (specifier lambda-list)
1097 (parse-callback-specification result-type typed-lambda-list)
1099 (defun ,name ,lambda-list ,@forms)
1100 (defparameter ,name (alien-callback ,specifier #',name)))))