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 No alien is allocated, but VAR is established as a local name for
95 the external alien given by EXTERNAL-NAME."
98 ;; The alien is allocated on the heap, and has infinite extent. The alien
99 ;; is allocated at load time, so the same piece of memory is used each time
100 ;; this form executes.
101 (/show "entering WITH-ALIEN" bindings)
102 (with-auxiliary-alien-types env
103 (dolist (binding (reverse bindings))
106 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
108 (/show symbol type opt1 opt2)
109 (let* ((alien-type (parse-alien-type type env))
110 (datap (not (alien-fun-type-p alien-type))))
112 (multiple-value-bind (allocation initial-value)
117 (values opt1 (guess-alien-name-from-lisp-name symbol)))
121 (values :local opt1))))
122 (/show allocation initial-value)
128 (make-symbol (concatenate 'string "SAP-FOR-"
129 (symbol-name symbol)))))
130 `((let ((,sap (load-time-value (%make-alien ...))))
131 (declare (type system-area-pointer ,sap))
133 ((,symbol (sap-alien ,sap ,type)))
134 ,@(when initial-value
135 `((setq ,symbol ,initial-value)))
138 (/show0 ":EXTERN case")
139 (let ((info (make-heap-alien-info
141 :sap-form `(foreign-symbol-sap ',initial-value
144 ((,symbol (%heap-alien ',info)))
147 (/show0 ":LOCAL case")
148 (let* ((var (sb!xc:gensym "VAR"))
149 (initval (if initial-value (sb!xc:gensym "INITVAL")))
150 (info (make-local-alien-info :type alien-type))
152 `((note-local-alien-type ',info ,var)
153 (symbol-macrolet ((,symbol (local-alien ',info ,var)))
154 ,@(when initial-value
155 `((setq ,symbol ,initval)))
159 `((let ((,initval ,initial-value))
162 (/show var initval info)
164 `((let ((,var (make-local-alien ',info)))
166 ;; FIXME: This version is less efficient then it needs to be, since
167 ;; it could just save and restore the number-stack pointer once,
168 ;; instead of doing multiple decrements if there are multiple bindings.
173 (setf ,var (make-local-alien ',info))
176 (dispose-local-alien ',info ,var))))))))))))
177 (/show "revised" body)
178 (verify-local-auxiliaries-okay)
179 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
180 `(symbol-macrolet ((&auxiliary-type-definitions&
181 ,(append *new-auxiliary-types*
182 (auxiliary-type-definitions env))))
184 (let ((sb!vm::*alien-stack* sb!vm::*alien-stack*))
189 ;;;; runtime C values that don't correspond directly to Lisp types
191 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
192 ;;; 'cause it has to be real early in the cold-load order.
193 #!-sb-fluid (declaim (freeze-type alien-value))
194 (def!method print-object ((value alien-value) stream)
195 (print-unreadable-object (value stream)
197 "~S ~S #X~8,'0X ~S ~S"
199 :sap (sap-int (alien-value-sap value))
200 :type (unparse-alien-type (alien-value-type value)))))
202 #!-sb-fluid (declaim (inline null-alien))
203 (defun null-alien (x)
205 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
206 (zerop (sap-int (alien-sap x))))
208 (defmacro sap-alien (sap type &environment env)
210 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
211 evaluated.) TYPE must be pointer-like."
212 (let ((alien-type (parse-alien-type type env)))
213 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
214 `(%sap-alien ,sap ',alien-type)
215 (error "cannot make an alien of type ~S out of a SAP" type))))
217 (defun %sap-alien (sap type)
218 (declare (type system-area-pointer sap)
219 (type alien-type type))
220 (make-alien-value :sap sap :type type))
222 (defun alien-sap (alien)
224 "Return a System-Area-Pointer pointing to Alien's data."
225 (declare (type alien-value alien))
226 (alien-value-sap alien))
228 ;;;; allocation/deallocation of heap aliens
230 (defmacro make-alien (type &optional size &environment env)
232 "Allocate an alien of type TYPE in foreign heap, and return an alien
233 pointer to it. The allocated memory is not initialized, and may
234 contain garbage. The memory is allocated using malloc(3), so it can be
235 passed to foreign functions which use free(3), or released using
238 For alien stack allocation, see macro WITH-ALIEN.
240 The TYPE argument is not evaluated. If SIZE is supplied, how it is
241 interpreted depends on TYPE:
243 * When TYPE is a foreign array type, an array of that type is
244 allocated, and a pointer to it is returned. Note that you
245 must use DEREF to first access the arrey through the pointer.
247 If supplied, SIZE is used as the first dimension for the array.
249 * When TYPE is any other foreign type, then an object for that
250 type is allocated, and a pointer to it is returned. So
251 (make-alien int) returns a (* int).
253 If SIZE is specified, then a block of that many objects is
254 allocated, with the result pointing to the first one.
258 (defvar *foo* (make-alien (array char 10)))
259 (type-of *foo*) ; => (alien (* (array (signed 8) 10)))
260 (setf (deref (deref foo) 0) 10) ; => 10
262 (make-alien char 12) ; => (alien (* (signed 8)))
264 (let ((alien-type (if (alien-type-p type)
266 (parse-alien-type type env))))
267 (multiple-value-bind (size-expr element-type)
268 (if (alien-array-type-p alien-type)
269 (let ((dims (alien-array-type-dimensions alien-type)))
274 "cannot override the size of zero-dimensional arrays"))
275 (when (constantp size)
276 (setf alien-type (copy-alien-array-type alien-type))
277 (setf (alien-array-type-dimensions alien-type)
278 (cons (constant-form-value size) (cdr dims)))))
280 (setf size (car dims)))
283 (values `(* ,size ,@(cdr dims))
284 (alien-array-type-element-type alien-type)))
285 (values (or size 1) alien-type))
286 (let ((bits (alien-type-bits element-type))
287 (alignment (alien-type-alignment element-type)))
289 (error "The size of ~S is unknown."
290 (unparse-alien-type element-type)))
292 (error "The alignment of ~S is unknown."
293 (unparse-alien-type element-type)))
294 ;; This is the one place where the %SAP-ALIEN note is quite
295 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
296 ;; cannot be optimized away.
297 `(locally (declare (muffle-conditions compiler-note))
298 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
299 (%sap-alien (%make-alien (* ,(ash (+ 7 (align-offset bits alignment)) -3)
300 (the index ,size-expr)))
301 ',(make-alien-pointer-type :to alien-type)))))))
303 (defun malloc-error (bytes errno)
304 (error 'simple-storage-condition
305 :format-control "~A: malloc() of ~S bytes failed."
306 :format-arguments (list (strerror errno) bytes)))
308 ;;; Allocate a block of memory at least BITS bits long and return a
309 ;;; system area pointer to it.
310 #!-sb-fluid (declaim (inline %make-alien))
311 (defun %make-alien (bytes)
312 (declare (type index bytes)
313 (optimize (sb!c:alien-funcall-saves-fp-and-pc 0)))
314 (let ((sap (alien-funcall (extern-alien "malloc"
315 (function system-area-pointer size-t))
317 (if (and (not (eql 0 bytes)) (eql 0 (sap-int sap)))
318 (malloc-error bytes (get-errno))
321 #!-sb-fluid (declaim (inline free-alien))
322 (defun free-alien (alien)
324 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
325 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
326 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
330 (declaim (type (sfunction * system-area-pointer) %make-alien-string))
331 (defun %make-alien-string (string &key (start 0) end
332 (external-format :default)
334 ;; FIXME: This is slow. We want a function to get the length of the
335 ;; encoded string so we can allocate the foreign memory first and
336 ;; encode directly there.
337 (let* ((octets (string-to-octets string
338 :start start :end end
339 :external-format external-format
340 :null-terminate null-terminate))
341 (count (length octets))
342 (buf (%make-alien count)))
343 (sb!kernel:copy-ub8-to-system-area octets 0 buf 0 count)
346 (defun make-alien-string (string &rest rest
348 (external-format :default)
350 "Copy part of STRING delimited by START and END into freshly
351 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
352 Returns the allocated string as a (* CHAR) alien, and the number of
353 bytes allocated as secondary value.
355 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
356 true (the default), the alien string is terminated by an additional
359 (declare (ignore start end external-format null-terminate))
360 (multiple-value-bind (sap bytes)
361 (apply #'%make-alien-string string rest)
362 (values (%sap-alien sap (parse-alien-type '(* char) nil))
365 (define-compiler-macro make-alien-string (&rest args)
366 `(multiple-value-bind (sap bytes) (%make-alien-string ,@args)
367 (values (%sap-alien sap ',(parse-alien-type '(* char) nil))
370 ;;;; the SLOT operator
372 ;;; Find the field named SLOT, or die trying.
373 (defun slot-or-lose (type slot)
374 (declare (type alien-record-type type)
376 (or (find slot (alien-record-type-fields type)
377 :key #'alien-record-field-name)
378 (error "There is no slot named ~S in ~S." slot type)))
380 ;;; Extract the value from the named slot from the record ALIEN. If
381 ;;; ALIEN is actually a pointer, then DEREF it first.
382 (defun slot (alien slot)
384 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
385 (declare (type alien-value alien)
387 (optimize (inhibit-warnings 3)))
388 (let ((type (alien-value-type alien)))
391 (slot (deref alien) slot))
393 (let ((field (slot-or-lose type slot)))
394 (extract-alien-value (alien-value-sap alien)
395 (alien-record-field-offset field)
396 (alien-record-field-type field)))))))
398 ;;; Deposit the value in the specified slot of the record ALIEN. If
399 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
400 ;;; this when it can't figure out anything better.
401 (defun %set-slot (alien slot value)
402 (declare (type alien-value alien)
404 (optimize (inhibit-warnings 3)))
405 (let ((type (alien-value-type alien)))
408 (%set-slot (deref alien) slot value))
410 (let ((field (slot-or-lose type slot)))
411 (deposit-alien-value (alien-value-sap alien)
412 (alien-record-field-offset field)
413 (alien-record-field-type field)
416 ;;; Compute the address of the specified slot and return a pointer to it.
417 (defun %slot-addr (alien slot)
418 (declare (type alien-value alien)
420 (optimize (inhibit-warnings 3)))
421 (let ((type (alien-value-type alien)))
424 (%slot-addr (deref alien) slot))
426 (let* ((field (slot-or-lose type slot))
427 (offset (alien-record-field-offset field))
428 (field-type (alien-record-field-type field)))
429 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
430 (make-alien-pointer-type :to field-type)))))))
432 ;;;; the DEREF operator
434 ;;; This function does most of the work of the different DEREF
435 ;;; methods. It returns two values: the type and the offset (in bits)
436 ;;; of the referred-to alien.
437 (defun deref-guts (alien indices)
438 (declare (type alien-value alien)
440 (values alien-type integer))
441 (let ((type (alien-value-type alien)))
445 (error "too many indices when DEREF'ing ~S: ~W"
448 (let ((element-type (alien-pointer-type-to type)))
451 (* (align-offset (alien-type-bits element-type)
452 (alien-type-alignment element-type))
456 (unless (= (length indices) (length (alien-array-type-dimensions type)))
457 (error "incorrect number of indices when DEREF'ing ~S: ~W"
458 type (length indices)))
459 (labels ((frob (dims indices offset)
462 (frob (cdr dims) (cdr indices)
463 (+ (if (zerop offset)
465 (* offset (car dims)))
467 (let ((element-type (alien-array-type-element-type type)))
469 (* (align-offset (alien-type-bits element-type)
470 (alien-type-alignment element-type))
471 (frob (alien-array-type-dimensions type)
474 ;;; Dereference the alien and return the results.
475 (defun deref (alien &rest indices)
477 "De-reference an Alien pointer or array. If an array, the indices are used
478 as the indices of the array element to access. If a pointer, one index can
479 optionally be specified, giving the equivalent of C pointer arithmetic."
480 (declare (type alien-value alien)
482 (optimize (inhibit-warnings 3)))
483 (multiple-value-bind (target-type offset) (deref-guts alien indices)
484 (extract-alien-value (alien-value-sap alien)
488 (defun %set-deref (alien value &rest indices)
489 (declare (type alien-value alien)
491 (optimize (inhibit-warnings 3)))
492 (multiple-value-bind (target-type offset) (deref-guts alien indices)
493 (deposit-alien-value (alien-value-sap alien)
498 (defun %deref-addr (alien &rest indices)
499 (declare (type alien-value alien)
501 (optimize (inhibit-warnings 3)))
502 (multiple-value-bind (target-type offset) (deref-guts alien indices)
503 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
504 (make-alien-pointer-type :to target-type))))
506 ;;;; accessing heap alien variables
508 (defun %heap-alien (info)
509 (declare (type heap-alien-info info)
510 (optimize (inhibit-warnings 3)))
511 (extract-alien-value (eval (heap-alien-info-sap-form info))
513 (heap-alien-info-type info)))
515 (defun %set-heap-alien (info value)
516 (declare (type heap-alien-info info)
517 (optimize (inhibit-warnings 3)))
518 (deposit-alien-value (eval (heap-alien-info-sap-form info))
520 (heap-alien-info-type info)
523 (defun %heap-alien-addr (info)
524 (declare (type heap-alien-info info)
525 (optimize (inhibit-warnings 3)))
526 (%sap-alien (eval (heap-alien-info-sap-form info))
527 (make-alien-pointer-type :to (heap-alien-info-type info))))
529 ;;;; accessing local aliens
531 (defun make-local-alien (info)
532 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
533 (alien-sap (alien-sap alien)))
538 (extern-alien "free" (function (values) system-area-pointer))
543 (defun note-local-alien-type (info alien)
544 (declare (ignore info alien))
547 (defun local-alien (info alien)
548 (declare (ignore info))
551 (defun %set-local-alien (info alien value)
552 (declare (ignore info))
553 (setf (deref alien) value))
555 (define-setf-expander local-alien (&whole whole info alien)
556 (let ((value (gensym))
559 (info (if (and (consp info)
560 (eq (car info) 'quote))
562 (error "Something is wrong; local-alien-info not found: ~S"
567 `(if (%local-alien-forced-to-memory-p ',info)
568 (%set-local-alien ',info ,alien ,value)
569 (let* ((,info-var ',(local-alien-info-type info))
570 (,alloc-tmp (deport-alloc ,value ,info-var)))
571 (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
572 (setf ,alien (deport ,alloc-tmp ,info-var)))))
575 (defun %local-alien-forced-to-memory-p (info)
576 (local-alien-info-force-to-memory-p info))
578 (defun %local-alien-addr (info alien)
579 (declare (type local-alien-info info))
580 (unless (local-alien-info-force-to-memory-p info)
581 (error "~S isn't forced to memory. Something went wrong." alien))
584 (defun dispose-local-alien (info alien)
585 (declare (ignore info))
586 (cancel-finalization alien)
591 (defmacro cast (alien type &environment env)
593 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
594 must be Alien array, pointer or function types."
595 `(%cast ,alien ',(parse-alien-type type env)))
597 (defun %cast (alien target-type)
598 (declare (type alien-value alien)
599 (type alien-type target-type)
600 (optimize (safety 2))
601 (optimize (inhibit-warnings 3)))
602 (if (or (alien-pointer-type-p target-type)
603 (alien-array-type-p target-type)
604 (alien-fun-type-p target-type))
605 (let ((alien-type (alien-value-type alien)))
606 (if (or (alien-pointer-type-p alien-type)
607 (alien-array-type-p alien-type)
608 (alien-fun-type-p alien-type))
609 (naturalize (alien-value-sap alien) target-type)
610 (error "~S cannot be casted." alien)))
611 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
613 ;;;; the ALIEN-SIZE macro
615 (defmacro alien-size (type &optional (units :bits) &environment env)
617 "Return the size of the alien type TYPE. UNITS specifies the units to
618 use and can be either :BITS, :BYTES, or :WORDS."
619 (let* ((alien-type (parse-alien-type type env))
620 (bits (alien-type-bits alien-type)))
622 (values (ceiling bits
625 (:bytes sb!vm:n-byte-bits)
626 (:words sb!vm:n-word-bits))))
627 (error "unknown size for alien type ~S"
628 (unparse-alien-type alien-type)))))
630 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
632 (defun coerce-to-interpreted-function (lambda-form)
634 (*evaluator-mode* :interpret))
635 (coerce lambda-form 'function)))
637 (defun naturalize (alien type)
638 (declare (type alien-type type))
639 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
642 (defun deport (value type)
643 (declare (type alien-type type))
644 (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
647 (defun deport-alloc (value type)
648 (declare (type alien-type type))
649 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
652 (defun extract-alien-value (sap offset type)
653 (declare (type system-area-pointer sap)
654 (type unsigned-byte offset)
655 (type alien-type type))
656 (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
659 (defun deposit-alien-value (sap offset type value)
660 (declare (type system-area-pointer sap)
661 (type unsigned-byte offset)
662 (type alien-type type))
663 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
664 sap offset type value))
666 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
668 (defun alien-funcall (alien &rest args)
670 "Call the foreign function ALIEN with the specified arguments. ALIEN's
671 type specifies the argument and result types."
672 (declare (type alien-value alien))
673 (let ((type (alien-value-type alien)))
676 (apply #'alien-funcall (deref alien) args))
678 (unless (= (length (alien-fun-type-arg-types type))
680 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
682 (length (alien-fun-type-arg-types type))
684 (let ((stub (alien-fun-type-stub type)))
687 (let ((fun (sb!xc:gensym "FUN"))
688 (parms (make-gensym-list (length args))))
690 `(lambda (,fun ,@parms)
691 (declare (optimize (sb!c::insert-step-conditions 0)))
692 (declare (type (alien ,type) ,fun))
693 (alien-funcall ,fun ,@parms)))))
694 (setf (alien-fun-type-stub type) stub))
695 (apply stub alien args)))
697 (error "~S is not an alien function." alien)))))
699 (defmacro define-alien-routine (name result-type
703 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
705 Define a foreign interface function for the routine with the specified NAME.
706 Also automatically DECLAIM the FTYPE of the defined function.
708 NAME may be either a string, a symbol, or a list of the form (string symbol).
710 RETURN-TYPE is the alien type for the function return value. VOID may be
711 used to specify a function with no result.
713 The remaining forms specify individual arguments that are passed to the
714 routine. ARG-NAME is a symbol that names the argument, primarily for
715 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
716 way that the argument is passed.
719 An :IN argument is simply passed by value. The value to be passed is
720 obtained from argument(s) to the interface function. No values are
721 returned for :In arguments. This is the default mode.
724 The specified argument type must be a pointer to a fixed sized object.
725 A pointer to a preallocated object is passed to the routine, and the
726 the object is accessed on return, with the value being returned from
727 the interface function. :OUT and :IN-OUT cannot be used with pointers
728 to arrays, records or functions.
731 This is similar to :IN, except that the argument values are stored
732 on the stack, and a pointer to the object is passed instead of
736 This is a combination of :OUT and :COPY. A pointer to the argument is
737 passed, with the object being initialized from the supplied argument
738 and the return value being determined by accessing the object on
740 (multiple-value-bind (lisp-name alien-name)
741 (pick-lisp-and-alien-names name)
742 (collect ((docs) (lisp-args) (lisp-arg-types)
744 (cond ((eql result-type 'void)
745 ;; What values does a function return, if it
746 ;; returns no values? Exactly one - NIL. -- APD,
750 ;; FIXME: Check for VALUES.
751 (list `(alien ,result-type)))))
752 (arg-types) (alien-vars)
753 (alien-args) (results))
757 (destructuring-bind (name type &optional (style :in)) arg
758 (unless (member style '(:in :copy :out :in-out))
759 (error "bogus argument style ~S in ~S" style arg))
760 (when (and (member style '(:out :in-out))
761 (typep (parse-alien-type type lexenv)
762 'alien-pointer-type))
763 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
766 (cond ((eq style :in)
770 (setq arg-type `(* ,type))
772 (alien-vars `(,name ,type))
773 (alien-vars `(,name ,type ,name)))
774 (alien-args `(addr ,name))))
776 (unless (eq style :out)
779 ;; FIXME: It should be something
780 ;; like `(ALIEN ,ARG-TYPE), except
781 ;; for we also accept SAPs where
782 ;; pointers are required.
784 (when (or (eq style :out) (eq style :in-out))
786 (lisp-result-types `(alien ,type))))))
788 ;; The theory behind this automatic DECLAIM is that (1) if
789 ;; you're calling C, static typing is what you're doing
790 ;; anyway, and (2) such a declamation can be (especially for
791 ;; alien values) both messy to do by hand and very important
792 ;; for performance of later code which uses the return value.
793 (declaim (ftype (function ,(lisp-arg-types)
794 (values ,@(lisp-result-types) &optional))
796 (defun ,lisp-name ,(lisp-args)
799 ((,lisp-name (function ,result-type ,@(arg-types))
802 ,@(if (eq 'void result-type)
803 `((alien-funcall ,lisp-name ,@(alien-args))
804 (values nil ,@(results)))
805 `((values (alien-funcall ,lisp-name ,@(alien-args))
808 (defun alien-typep (object type)
810 "Return T iff OBJECT is an alien of type TYPE."
811 (let ((lisp-rep-type (compute-lisp-rep-type type)))
813 (typep object lisp-rep-type)
814 (and (alien-value-p object)
815 (alien-subtype-p (alien-value-type object) type)))))
819 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
821 (defvar *alien-callback-info* nil
822 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
823 information we need to manipulate callbacks after their creation. Used for
824 changing the lisp-side function they point to, invalidation, etc.")
826 (defstruct callback-info
828 function ; NULL if invalid
832 (defun callback-info-key (info)
833 (cons (callback-info-specifier info) (callback-info-function info)))
835 (defun alien-callback-info (alien)
836 (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
838 (defvar *alien-callbacks* (make-hash-table :test #'equal)
839 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
840 memoization: we don't create new callbacks if one pointing to the correct
841 function with the same specifier already exists.")
843 (defvar *alien-callback-wrappers* (make-hash-table :test #'equal)
844 "Cache of existing lisp weappers, indexed with SPECIFER. Used for memoization:
845 we don't create new wrappers if one for the same specifier already exists.")
847 (defvar *alien-callback-trampolines* (make-array 32 :fill-pointer 0 :adjustable t)
848 "Lisp trampoline store: assembler wrappers contain indexes to this, and
849 ENTER-ALIEN-CALLBACK pulls the corresponsing trampoline out and calls it.")
851 (defun %alien-callback-sap (specifier result-type argument-types function wrapper)
852 (let ((key (cons specifier function)))
853 (or (gethash key *alien-callbacks*)
854 (setf (gethash key *alien-callbacks*)
855 (let* ((index (fill-pointer *alien-callback-trampolines*))
856 ;; Aside from the INDEX this is known at
857 ;; compile-time, which could be utilized by
858 ;; having the two-stage assembler tramp &
859 ;; wrapper mentioned in [1] above: only the
860 ;; per-function tramp would need assembler at
861 ;; runtime. Possibly we could even pregenerate
862 ;; the code and just patch the index in later.
863 (assembler-wrapper (alien-callback-assembler-wrapper
864 index result-type argument-types)))
866 (alien-callback-lisp-trampoline wrapper function)
867 *alien-callback-trampolines*)
868 ;; Assembler-wrapper is static, so sap-taking is safe.
869 (let ((sap (vector-sap assembler-wrapper)))
870 (push (cons sap (make-callback-info :specifier specifier
874 *alien-callback-info*)
877 (defun alien-callback-lisp-trampoline (wrapper function)
878 (declare (function wrapper) (optimize speed))
879 (lambda (args-pointer result-pointer)
880 (funcall wrapper args-pointer result-pointer function)))
882 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
883 (let* ((arguments (make-gensym-list (length argument-types)))
884 (argument-names arguments)
885 (argument-specs (cddr specifier)))
886 `(lambda (args-pointer result-pointer function)
887 ;; FIXME: the saps are not gc safe
888 (let ((args-sap (int-sap
889 (sb!kernel:get-lisp-obj-address args-pointer)))
891 (sb!kernel:get-lisp-obj-address result-pointer))))
892 (declare (ignorable args-sap res-sap))
896 for spec in argument-specs
897 collect `(,(pop argument-names) ,spec
898 :local ,(alien-callback-accessor-form
899 spec 'args-sap offset))
900 do (incf offset (alien-callback-argument-bytes spec env)))
901 ,(flet ((store (spec real-type)
903 `(setf (deref (sap-alien res-sap (* ,spec)))
906 (funcall function ,@arguments))
907 `(funcall function ,@arguments)))
908 `(funcall function ,@arguments))))
909 (cond ((alien-void-type-p result-type)
911 ((alien-integer-type-p result-type)
912 ;; Integer types should be padded out to a full
913 ;; register width, to comply with most ABI calling
914 ;; conventions, but should be typechecked on the
915 ;; declared type width, hence the following:
916 (if (alien-integer-type-signed result-type)
918 ,(alien-type-word-aligned-bits result-type))
919 `(signed-byte ,(alien-type-bits result-type)))
922 ,(alien-type-word-aligned-bits result-type))
923 `(unsigned-byte ,(alien-type-bits result-type)))))
925 (store (unparse-alien-type result-type) nil))))))
928 (defun invalid-alien-callback (&rest arguments)
929 (declare (ignore arguments))
930 (error "Invalid alien callback called."))
933 (defun parse-callback-specification (result-type lambda-list)
935 `(function ,result-type ,@(mapcar #'second lambda-list))
936 (mapcar #'first lambda-list)))
939 (defun parse-alien-ftype (specifier env)
940 (destructuring-bind (function result-type &rest argument-types)
942 (aver (eq 'function function))
943 (values (let ((*values-type-okay* t))
944 (parse-alien-type result-type env))
945 (mapcar (lambda (spec)
946 (parse-alien-type spec env))
949 (defun alien-void-type-p (type)
950 (and (alien-values-type-p type) (not (alien-values-type-values type))))
952 (defun alien-type-word-aligned-bits (type)
953 (align-offset (alien-type-bits type) sb!vm:n-word-bits))
955 (defun alien-callback-argument-bytes (spec env)
956 (let ((type (parse-alien-type spec env)))
957 (if (or (alien-integer-type-p type)
958 (alien-float-type-p type)
959 (alien-pointer-type-p type)
960 (alien-system-area-pointer-type-p type))
961 (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
962 (error "Unsupported callback argument type: ~A" type))))
964 (defun enter-alien-callback (index return arguments)
965 (funcall (aref *alien-callback-trampolines* index)
969 ;;; To ensure that callback wrapper functions continue working even
970 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
971 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
972 (defvar *enter-alien-callback* #'enter-alien-callback)
974 ;;;; interface (not public, yet) for alien callbacks
976 (defmacro alien-callback (specifier function &environment env)
977 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
978 an alien function as a pointer to the FUNCTION. If a callback for the given
979 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
981 ;; Pull out as much work as is convenient to macro-expansion time, specifically
982 ;; everything that can be done given just the SPECIFIER and ENV.
983 (multiple-value-bind (result-type argument-types) (parse-alien-ftype specifier env)
985 (%alien-callback-sap ',specifier ',result-type ',argument-types
987 (or (gethash ',specifier *alien-callback-wrappers*)
988 (setf (gethash ',specifier *alien-callback-wrappers*)
990 ',(alien-callback-lisp-wrapper-lambda
991 specifier result-type argument-types env)))))
992 ',(parse-alien-type specifier env))))
994 (defun alien-callback-p (alien)
995 "Returns true if the alien is associated with a lisp-side callback,
996 and a secondary return value of true if the callback is still valid."
997 (let ((info (alien-callback-info alien)))
999 (values t (and (callback-info-function info) t)))))
1001 (defun alien-callback-function (alien)
1002 "Returns the lisp function designator associated with the callback."
1003 (let ((info (alien-callback-info alien)))
1005 (callback-info-function info))))
1007 (defun (setf alien-callback-function) (function alien)
1008 "Changes the lisp function designated by the callback."
1009 (let ((info (alien-callback-info alien)))
1011 (error "Not an alien callback: ~S" alien))
1013 (let ((key (callback-info-key info)))
1014 (remhash key *alien-callbacks*)
1015 (setf (gethash key *alien-callbacks*) (alien-sap alien)))
1017 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1018 (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
1020 (setf (callback-info-function info) function)
1023 (defun invalidate-alien-callback (alien)
1024 "Invalidates the callback designated by the alien, if any, allowing the
1025 associated lisp function to be GC'd, and causing further calls to the same
1026 callback signal an error."
1027 (let ((info (alien-callback-info alien)))
1028 (when (and info (callback-info-function info))
1030 (remhash (callback-info-key info) *alien-callbacks*)
1032 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1033 #'invalid-alien-callback)
1035 (setf (callback-info-function info) nil)
1038 ;;; FIXME: This call assembles a new callback for every closure,
1039 ;;; which sucks hugely. ...not that I can think of an obvious
1040 ;;; solution. Possibly maybe we could write a generalized closure
1041 ;;; callback analogous to closure_tramp, and share the actual wrapper?
1043 ;;; For lambdas that result in simple-funs we get the callback from
1044 ;;; the cache on subsequent calls.
1045 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
1046 (multiple-value-bind (specifier lambda-list)
1047 (parse-callback-specification result-type typed-lambda-list)
1048 `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
1050 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
1051 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
1052 ;;; the FDEFINITION should invalidate the callback, and redefining the
1053 ;;; callback should change existing callbacks to point to the new defintion.
1054 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
1055 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
1056 the alien callback for that function with the given alien type."
1057 (declare (symbol name))
1058 (multiple-value-bind (specifier lambda-list)
1059 (parse-callback-specification result-type typed-lambda-list)
1061 (defun ,name ,lambda-list ,@forms)
1062 (defparameter ,name (alien-callback ,specifier #',name)))))