1 ;;;; This file contains parts of the ALIEN implementation that
2 ;;;; are not part of the compiler.
4 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!ALIEN")
15 (/show0 "target-alieneval.lisp 15")
19 ;;; Make a string out of the symbol, converting all uppercase letters to
20 ;;; lower case and hyphens into underscores.
21 (eval-when (:compile-toplevel :load-toplevel :execute)
22 (defun guess-alien-name-from-lisp-name (lisp-name)
23 (declare (type symbol lisp-name))
24 (nsubstitute #\_ #\- (string-downcase (symbol-name lisp-name)))))
26 ;;; The opposite of GUESS-ALIEN-NAME-FROM-LISP-NAME. Make a symbol out
27 ;;; of the string, converting all lowercase letters to uppercase and
28 ;;; underscores into hyphens.
29 (eval-when (:compile-toplevel :load-toplevel :execute)
30 (defun guess-lisp-name-from-alien-name (alien-name)
31 (declare (type simple-string alien-name))
32 (intern (nsubstitute #\- #\_ (string-upcase alien-name)))))
34 ;;; Extract the Lisp and alien names from NAME. If only one is given,
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defun pick-lisp-and-alien-names (name)
40 (values (guess-lisp-name-from-alien-name name) name))
42 (values name (guess-alien-name-from-lisp-name name)))
44 (unless (proper-list-of-length-p name 2)
45 (error "badly formed alien name"))
46 (values (cadr name) (car name))))))
48 (defmacro define-alien-variable (name type &environment env)
50 "Define NAME as an external alien variable of type TYPE. NAME should be
51 a list of a string holding the alien name and a symbol to use as the Lisp
52 name. If NAME is just a symbol or string, then the other name is guessed
53 from the one supplied."
54 (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
55 (with-auxiliary-alien-types env
56 (let ((alien-type (parse-alien-type type env)))
57 `(eval-when (:compile-toplevel :load-toplevel :execute)
58 ,@(when *new-auxiliary-types*
59 `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
60 (%define-alien-variable ',lisp-name
64 (defmacro def-alien-variable (&rest rest)
65 (deprecation-warning 'def-alien-variable 'define-alien-variable)
66 `(define-alien-variable ,@rest))
68 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
69 (eval-when (:compile-toplevel :load-toplevel :execute)
70 (defun %define-alien-variable (lisp-name alien-name type)
71 (setf (info :variable :kind lisp-name) :alien)
72 (setf (info :variable :where-from lisp-name) :defined)
73 (clear-info :variable :constant-value lisp-name)
74 (setf (info :variable :alien-info lisp-name)
75 (make-heap-alien-info :type type
76 :sap-form `(foreign-symbol-address
79 (defmacro extern-alien (name type &environment env)
81 "Access the alien variable named NAME, assuming it is of type TYPE. This
83 (let ((alien-name (etypecase name
84 (symbol (guess-alien-name-from-lisp-name name))
86 `(%heap-alien ',(make-heap-alien-info
87 :type (parse-alien-type type env)
88 :sap-form `(foreign-symbol-address ',alien-name)))))
90 (defmacro with-alien (bindings &body body &environment env)
92 "Establish some local alien variables. Each BINDING is of the form:
93 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
94 ALLOCATION should be one of:
96 The alien is allocated on the stack, and has dynamic extent.
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
102 No alien is allocated, but VAR is established as a local name for
103 the external alien given by EXTERNAL-NAME."
104 (/show "entering WITH-ALIEN" bindings)
105 (with-auxiliary-alien-types env
106 (dolist (binding (reverse bindings))
109 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
111 (/show symbol type opt1 opt2)
112 (let ((alien-type (parse-alien-type type env)))
114 (multiple-value-bind (allocation initial-value)
119 (values opt1 (guess-alien-name-from-lisp-name symbol)))
123 (values :local opt1))))
124 (/show allocation initial-value)
130 (make-symbol (concatenate 'string "SAP-FOR-"
131 (symbol-name symbol)))))
132 `((let ((,sap (load-time-value (%make-alien ...))))
133 (declare (type system-area-pointer ,sap))
135 ((,symbol (sap-alien ,sap ,type)))
136 ,@(when initial-value
137 `((setq ,symbol ,initial-value)))
140 (/show0 ":EXTERN case")
141 (let ((info (make-heap-alien-info
143 :sap-form `(foreign-symbol-address
146 ((,symbol (%heap-alien ',info)))
149 (/show0 ":LOCAL case")
151 (initval (if initial-value (gensym)))
152 (info (make-local-alien-info :type alien-type)))
153 (/show var initval info)
154 `((let ((,var (make-local-alien ',info))
155 ,@(when initial-value
156 `((,initval ,initial-value))))
157 (note-local-alien-type ',info ,var)
158 (multiple-value-prog1
160 ((,symbol (local-alien ',info ,var)))
161 ,@(when initial-value
162 `((setq ,symbol ,initval)))
164 (dispose-local-alien ',info ,var))))))))))))
165 (/show "revised" body)
166 (verify-local-auxiliaries-okay)
167 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
168 `(symbol-macrolet ((&auxiliary-type-definitions&
169 ,(append *new-auxiliary-types*
170 (auxiliary-type-definitions env))))
173 ;;;; runtime C values that don't correspond directly to Lisp types
175 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
176 ;;; 'cause it has to be real early in the cold-load order.
177 #!-sb-fluid (declaim (freeze-type alien-value))
178 (def!method print-object ((value alien-value) stream)
179 (print-unreadable-object (value stream)
181 "~S ~S #X~8,'0X ~S ~S"
183 :sap (sap-int (alien-value-sap value))
184 :type (unparse-alien-type (alien-value-type value)))))
186 #!-sb-fluid (declaim (inline null-alien))
187 (defun null-alien (x)
189 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
190 (zerop (sap-int (alien-sap x))))
192 (defmacro sap-alien (sap type &environment env)
194 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
195 evaluated.) TYPE must be pointer-like."
196 (let ((alien-type (parse-alien-type type env)))
197 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
198 `(%sap-alien ,sap ',alien-type)
199 (error "cannot make an alien of type ~S out of a SAP" type))))
201 (defun %sap-alien (sap type)
202 (declare (type system-area-pointer sap)
203 (type alien-type type))
204 (make-alien-value :sap sap :type type))
206 (defun alien-sap (alien)
208 "Return a System-Area-Pointer pointing to Alien's data."
209 (declare (type alien-value alien))
210 (alien-value-sap alien))
212 ;;;; allocation/deallocation of heap aliens
214 (defmacro make-alien (type &optional size &environment env)
216 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
217 is supplied, how it is interpreted depends on TYPE. If TYPE is an array
218 type, SIZE is used as the first dimension for the allocated array. If TYPE
219 is not an array, then SIZE is the number of elements to allocate. The
220 memory is allocated using ``malloc'', so it can be passed to foreign
221 functions which use ``free''."
222 (let ((alien-type (if (alien-type-p type)
224 (parse-alien-type type env))))
225 (multiple-value-bind (size-expr element-type)
226 (if (alien-array-type-p alien-type)
227 (let ((dims (alien-array-type-dimensions alien-type)))
232 "cannot override the size of zero-dimensional arrays"))
233 (when (constantp size)
234 (setf alien-type (copy-alien-array-type alien-type))
235 (setf (alien-array-type-dimensions alien-type)
236 (cons (eval size) (cdr dims)))))
238 (setf size (car dims)))
241 (values `(* ,size ,@(cdr dims))
242 (alien-array-type-element-type alien-type)))
243 (values (or size 1) alien-type))
244 (let ((bits (alien-type-bits element-type))
245 (alignment (alien-type-alignment element-type)))
247 (error "The size of ~S is unknown."
248 (unparse-alien-type element-type)))
250 (error "The alignment of ~S is unknown."
251 (unparse-alien-type element-type)))
252 `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
254 ',(make-alien-pointer-type :to alien-type))))))
256 ;;; Allocate a block of memory at least BITS bits long and return a
257 ;;; system area pointer to it.
258 #!-sb-fluid (declaim (inline %make-alien))
259 (defun %make-alien (bits)
260 (declare (type index bits))
261 (alien-funcall (extern-alien "malloc"
262 (function system-area-pointer unsigned))
263 (ash (the index (+ bits 7)) -3)))
265 #!-sb-fluid (declaim (inline free-alien))
266 (defun free-alien (alien)
268 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
269 by MAKE-ALIEN or malloc(3)."
270 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
274 ;;;; the SLOT operator
276 ;;; Find the field named SLOT, or die trying.
277 (defun slot-or-lose (type slot)
278 (declare (type alien-record-type type)
280 (or (find slot (alien-record-type-fields type)
281 :key #'alien-record-field-name)
282 (error "There is no slot named ~S in ~S." slot type)))
284 ;;; Extract the value from the named slot from the record ALIEN. If
285 ;;; ALIEN is actually a pointer, then DEREF it first.
286 (defun slot (alien slot)
288 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
289 (declare (type alien-value alien)
291 (optimize (inhibit-warnings 3)))
292 (let ((type (alien-value-type alien)))
295 (slot (deref alien) slot))
297 (let ((field (slot-or-lose type slot)))
298 (extract-alien-value (alien-value-sap alien)
299 (alien-record-field-offset field)
300 (alien-record-field-type field)))))))
302 ;;; Deposit the value in the specified slot of the record ALIEN. If
303 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
304 ;;; this when it can't figure out anything better.
305 (defun %set-slot (alien slot value)
306 (declare (type alien-value alien)
308 (optimize (inhibit-warnings 3)))
309 (let ((type (alien-value-type alien)))
312 (%set-slot (deref alien) slot value))
314 (let ((field (slot-or-lose type slot)))
315 (deposit-alien-value (alien-value-sap alien)
316 (alien-record-field-offset field)
317 (alien-record-field-type field)
320 ;;; Compute the address of the specified slot and return a pointer to it.
321 (defun %slot-addr (alien slot)
322 (declare (type alien-value alien)
324 (optimize (inhibit-warnings 3)))
325 (let ((type (alien-value-type alien)))
328 (%slot-addr (deref alien) slot))
330 (let* ((field (slot-or-lose type slot))
331 (offset (alien-record-field-offset field))
332 (field-type (alien-record-field-type field)))
333 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
334 (make-alien-pointer-type :to field-type)))))))
336 ;;;; the DEREF operator
338 ;;; This function does most of the work of the different DEREF
339 ;;; methods. It returns two values: the type and the offset (in bits)
340 ;;; of the referred-to alien.
341 (defun deref-guts (alien indices)
342 (declare (type alien-value alien)
344 (values alien-type integer))
345 (let ((type (alien-value-type alien)))
349 (error "too many indices when DEREF'ing ~S: ~W"
352 (let ((element-type (alien-pointer-type-to type)))
355 (* (align-offset (alien-type-bits element-type)
356 (alien-type-alignment element-type))
360 (unless (= (length indices) (length (alien-array-type-dimensions type)))
361 (error "incorrect number of indices when DEREF'ing ~S: ~W"
362 type (length indices)))
363 (labels ((frob (dims indices offset)
366 (frob (cdr dims) (cdr indices)
367 (+ (if (zerop offset)
369 (* offset (car dims)))
371 (let ((element-type (alien-array-type-element-type type)))
373 (* (align-offset (alien-type-bits element-type)
374 (alien-type-alignment element-type))
375 (frob (alien-array-type-dimensions type)
378 ;;; Dereference the alien and return the results.
379 (defun deref (alien &rest indices)
381 "De-reference an Alien pointer or array. If an array, the indices are used
382 as the indices of the array element to access. If a pointer, one index can
383 optionally be specified, giving the equivalent of C pointer arithmetic."
384 (declare (type alien-value alien)
386 (optimize (inhibit-warnings 3)))
387 (multiple-value-bind (target-type offset) (deref-guts alien indices)
388 (extract-alien-value (alien-value-sap alien)
392 (defun %set-deref (alien value &rest indices)
393 (declare (type alien-value alien)
395 (optimize (inhibit-warnings 3)))
396 (multiple-value-bind (target-type offset) (deref-guts alien indices)
397 (deposit-alien-value (alien-value-sap alien)
402 (defun %deref-addr (alien &rest indices)
403 (declare (type alien-value alien)
405 (optimize (inhibit-warnings 3)))
406 (multiple-value-bind (target-type offset) (deref-guts alien indices)
407 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
408 (make-alien-pointer-type :to target-type))))
410 ;;;; accessing heap alien variables
412 (defun %heap-alien (info)
413 (declare (type heap-alien-info info)
414 (optimize (inhibit-warnings 3)))
415 (extract-alien-value (eval (heap-alien-info-sap-form info))
417 (heap-alien-info-type info)))
419 (defun %set-heap-alien (info value)
420 (declare (type heap-alien-info info)
421 (optimize (inhibit-warnings 3)))
422 (deposit-alien-value (eval (heap-alien-info-sap-form info))
424 (heap-alien-info-type info)
427 (defun %heap-alien-addr (info)
428 (declare (type heap-alien-info info)
429 (optimize (inhibit-warnings 3)))
430 (%sap-alien (eval (heap-alien-info-sap-form info))
431 (make-alien-pointer-type :to (heap-alien-info-type info))))
433 ;;;; accessing local aliens
435 (defun make-local-alien (info)
436 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
437 (alien-sap (alien-sap alien)))
442 (extern-alien "free" (function (values) system-area-pointer))
446 (defun note-local-alien-type (info alien)
447 (declare (ignore info alien))
450 (defun local-alien (info alien)
451 (declare (ignore info))
454 (defun %set-local-alien (info alien value)
455 (declare (ignore info))
456 (setf (deref alien) value))
458 (define-setf-expander local-alien (&whole whole info alien)
459 (let ((value (gensym))
460 (info (if (and (consp info)
461 (eq (car info) 'quote))
463 (error "Something is wrong; local-alien-info not found: ~S"
468 `(if (%local-alien-forced-to-memory-p ',info)
469 (%set-local-alien ',info ,alien ,value)
471 (deport ,value ',(local-alien-info-type info))))
474 (defun %local-alien-forced-to-memory-p (info)
475 (local-alien-info-force-to-memory-p info))
477 (defun %local-alien-addr (info alien)
478 (declare (type local-alien-info info))
479 (unless (local-alien-info-force-to-memory-p info)
480 (error "~S isn't forced to memory. Something went wrong." alien))
483 (defun dispose-local-alien (info alien)
484 (declare (ignore info))
485 (cancel-finalization alien)
490 (defmacro cast (alien type &environment env)
492 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
493 must be Alien array, pointer or function types."
494 `(%cast ,alien ',(parse-alien-type type env)))
496 (defun %cast (alien target-type)
497 (declare (type alien-value alien)
498 (type alien-type target-type)
499 (optimize (safety 2))
500 (optimize (inhibit-warnings 3)))
501 (if (or (alien-pointer-type-p target-type)
502 (alien-array-type-p target-type)
503 (alien-fun-type-p target-type))
504 (let ((alien-type (alien-value-type alien)))
505 (if (or (alien-pointer-type-p alien-type)
506 (alien-array-type-p alien-type)
507 (alien-fun-type-p alien-type))
508 (naturalize (alien-value-sap alien) target-type)
509 (error "~S cannot be casted." alien)))
510 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
512 ;;;; the ALIEN-SIZE macro
514 (defmacro alien-size (type &optional (units :bits) &environment env)
516 "Return the size of the alien type TYPE. UNITS specifies the units to
517 use and can be either :BITS, :BYTES, or :WORDS."
518 (let* ((alien-type (parse-alien-type type env))
519 (bits (alien-type-bits alien-type)))
521 (values (ceiling bits
524 (:bytes sb!vm:n-byte-bits)
525 (:words sb!vm:n-word-bits))))
526 (error "unknown size for alien type ~S"
527 (unparse-alien-type alien-type)))))
529 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
531 (defun naturalize (alien type)
532 (declare (type alien-type type))
533 (funcall (coerce (compute-naturalize-lambda type) 'function)
536 (defun deport (value type)
537 (declare (type alien-type type))
538 (funcall (coerce (compute-deport-lambda type) 'function)
541 (defun extract-alien-value (sap offset type)
542 (declare (type system-area-pointer sap)
543 (type unsigned-byte offset)
544 (type alien-type type))
545 (funcall (coerce (compute-extract-lambda type) 'function)
548 (defun deposit-alien-value (sap offset type value)
549 (declare (type system-area-pointer sap)
550 (type unsigned-byte offset)
551 (type alien-type type))
552 (funcall (coerce (compute-deposit-lambda type) 'function)
553 sap offset type value))
555 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
557 (defun alien-funcall (alien &rest args)
559 "Call the foreign function ALIEN with the specified arguments. ALIEN's
560 type specifies the argument and result types."
561 (declare (type alien-value alien))
562 (let ((type (alien-value-type alien)))
565 (apply #'alien-funcall (deref alien) args))
567 (unless (= (length (alien-fun-type-arg-types type))
569 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
571 (length (alien-fun-type-arg-types type))
573 (let ((stub (alien-fun-type-stub type)))
577 (parms (make-gensym-list (length args))))
579 `(lambda (,fun ,@parms)
580 (declare (type (alien ,type) ,fun))
581 (alien-funcall ,fun ,@parms)))))
582 (setf (alien-fun-type-stub type) stub))
583 (apply stub alien args)))
585 (error "~S is not an alien function." alien)))))
587 (defmacro define-alien-routine (name result-type
591 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
593 Define a foreign interface function for the routine with the specified NAME.
594 Also automatically DECLAIM the FTYPE of the defined function.
596 NAME may be either a string, a symbol, or a list of the form (string symbol).
598 RETURN-TYPE is the alien type for the function return value. VOID may be
599 used to specify a function with no result.
601 The remaining forms specify individual arguments that are passed to the
602 routine. ARG-NAME is a symbol that names the argument, primarily for
603 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
604 way that the argument is passed.
607 An :IN argument is simply passed by value. The value to be passed is
608 obtained from argument(s) to the interface function. No values are
609 returned for :In arguments. This is the default mode.
612 The specified argument type must be a pointer to a fixed sized object.
613 A pointer to a preallocated object is passed to the routine, and the
614 the object is accessed on return, with the value being returned from
615 the interface function. :OUT and :IN-OUT cannot be used with pointers
616 to arrays, records or functions.
619 This is similar to :IN, except that the argument values are stored
620 on the stack, and a pointer to the object is passed instead of
624 This is a combination of :OUT and :COPY. A pointer to the argument is
625 passed, with the object being initialized from the supplied argument
626 and the return value being determined by accessing the object on
628 (multiple-value-bind (lisp-name alien-name)
629 (pick-lisp-and-alien-names name)
630 (collect ((docs) (lisp-args) (lisp-arg-types)
632 (cond ((eql result-type 'void)
633 ;; What values does a function return, if it
634 ;; returns no values? Exactly one - NIL. -- APD,
638 ;; FIXME: Check for VALUES.
639 (list `(alien ,result-type)))))
640 (arg-types) (alien-vars)
641 (alien-args) (results))
645 (destructuring-bind (name type &optional (style :in)) arg
646 (unless (member style '(:in :copy :out :in-out))
647 (error "bogus argument style ~S in ~S" style arg))
648 (when (and (member style '(:out :in-out))
649 (typep (parse-alien-type type lexenv)
650 'alien-pointer-type))
651 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
654 (cond ((eq style :in)
658 (setq arg-type `(* ,type))
660 (alien-vars `(,name ,type))
661 (alien-vars `(,name ,type ,name)))
662 (alien-args `(addr ,name))))
664 (unless (eq style :out)
667 ;; FIXME: It should be something
668 ;; like `(ALIEN ,ARG-TYPE), except
669 ;; for we also accept SAPs where
670 ;; pointers are required.
672 (when (or (eq style :out) (eq style :in-out))
674 (lisp-result-types `(alien ,type))))))
676 ;; The theory behind this automatic DECLAIM is that (1) if
677 ;; you're calling C, static typing is what you're doing
678 ;; anyway, and (2) such a declamation can be (especially for
679 ;; alien values) both messy to do by hand and very important
680 ;; for performance of later code which uses the return value.
681 (declaim (ftype (function ,(lisp-arg-types)
682 (values ,@(lisp-result-types) &optional))
684 (defun ,lisp-name ,(lisp-args)
687 ((,lisp-name (function ,result-type ,@(arg-types))
691 (values (alien-funcall ,lisp-name ,@(alien-args))
694 (if (alien-values-type-p result-type)
695 ;; FIXME: RESULT-TYPE is a type specifier, so it
696 ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
697 ;; that if RESULT-TYPE is VOID, then this code
698 ;; disagrees with the computation of the return type
699 ;; and with all usages of this macro. -- APD,
701 (let ((temps (make-gensym-list
703 (alien-values-type-values result-type)))))
704 `(multiple-value-bind ,temps
705 (alien-funcall ,lisp-name ,@(alien-args))
706 (values ,@temps ,@(results))))
707 (values (alien-funcall ,lisp-name ,@(alien-args))
710 (defmacro def-alien-routine (&rest rest)
711 (deprecation-warning 'def-alien-routine 'define-alien-routine)
712 `(define-alien-routine ,@rest))
714 (defun alien-typep (object type)
716 "Return T iff OBJECT is an alien of type TYPE."
717 (let ((lisp-rep-type (compute-lisp-rep-type type)))
719 (typep object lisp-rep-type)
720 (and (alien-value-p object)
721 (alien-subtype-p (alien-value-type object) type)))))