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 ',alien-name t)))))
78 (defmacro extern-alien (name type &environment env)
80 "Access the alien variable named NAME, assuming it is of type TYPE. This
82 (let* ((alien-name (etypecase name
83 (symbol (guess-alien-name-from-lisp-name name))
85 (alien-type (parse-alien-type type env))
86 (datap (not (alien-fun-type-p alien-type))))
87 `(%heap-alien ',(make-heap-alien-info
89 :sap-form `(foreign-symbol-address ',alien-name ,datap)))))
91 (defmacro with-alien (bindings &body body &environment env)
93 "Establish some local alien variables. Each BINDING is of the form:
94 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
95 ALLOCATION should be one of:
97 The alien is allocated on the stack, and has dynamic extent.
99 The alien is allocated on the heap, and has infinite extent. The alien
100 is allocated at load time, so the same piece of memory is used each time
103 No alien is allocated, but VAR is established as a local name for
104 the external alien given by EXTERNAL-NAME."
105 (/show "entering WITH-ALIEN" bindings)
106 (with-auxiliary-alien-types env
107 (dolist (binding (reverse bindings))
110 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
112 (/show symbol type opt1 opt2)
113 (let* ((alien-type (parse-alien-type type env))
114 (datap (not (alien-fun-type-p alien-type))))
116 (multiple-value-bind (allocation initial-value)
121 (values opt1 (guess-alien-name-from-lisp-name symbol)))
125 (values :local opt1))))
126 (/show allocation initial-value)
132 (make-symbol (concatenate 'string "SAP-FOR-"
133 (symbol-name symbol)))))
134 `((let ((,sap (load-time-value (%make-alien ...))))
135 (declare (type system-area-pointer ,sap))
137 ((,symbol (sap-alien ,sap ,type)))
138 ,@(when initial-value
139 `((setq ,symbol ,initial-value)))
142 (/show0 ":EXTERN case")
143 (let ((info (make-heap-alien-info
145 :sap-form `(foreign-symbol-address
149 ((,symbol (%heap-alien ',info)))
152 (/show0 ":LOCAL case")
154 (initval (if initial-value (gensym)))
155 (info (make-local-alien-info :type alien-type)))
156 (/show var initval info)
157 `((let ((,var (make-local-alien ',info))
158 ,@(when initial-value
159 `((,initval ,initial-value))))
160 (note-local-alien-type ',info ,var)
161 (multiple-value-prog1
163 ((,symbol (local-alien ',info ,var)))
164 ,@(when initial-value
165 `((setq ,symbol ,initval)))
167 (dispose-local-alien ',info ,var))))))))))))
168 (/show "revised" body)
169 (verify-local-auxiliaries-okay)
170 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
171 `(symbol-macrolet ((&auxiliary-type-definitions&
172 ,(append *new-auxiliary-types*
173 (auxiliary-type-definitions env))))
176 ;;;; runtime C values that don't correspond directly to Lisp types
178 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
179 ;;; 'cause it has to be real early in the cold-load order.
180 #!-sb-fluid (declaim (freeze-type alien-value))
181 (def!method print-object ((value alien-value) stream)
182 (print-unreadable-object (value stream)
184 "~S ~S #X~8,'0X ~S ~S"
186 :sap (sap-int (alien-value-sap value))
187 :type (unparse-alien-type (alien-value-type value)))))
189 #!-sb-fluid (declaim (inline null-alien))
190 (defun null-alien (x)
192 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
193 (zerop (sap-int (alien-sap x))))
195 (defmacro sap-alien (sap type &environment env)
197 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
198 evaluated.) TYPE must be pointer-like."
199 (let ((alien-type (parse-alien-type type env)))
200 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
201 `(%sap-alien ,sap ',alien-type)
202 (error "cannot make an alien of type ~S out of a SAP" type))))
204 (defun %sap-alien (sap type)
205 (declare (type system-area-pointer sap)
206 (type alien-type type))
207 (make-alien-value :sap sap :type type))
209 (defun alien-sap (alien)
211 "Return a System-Area-Pointer pointing to Alien's data."
212 (declare (type alien-value alien))
213 (alien-value-sap alien))
215 ;;;; allocation/deallocation of heap aliens
217 (defmacro make-alien (type &optional size &environment env)
219 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
220 is supplied, how it is interpreted depends on TYPE. If TYPE is an array
221 type, SIZE is used as the first dimension for the allocated array. If TYPE
222 is not an array, then SIZE is the number of elements to allocate. The
223 memory is allocated using ``malloc'', so it can be passed to foreign
224 functions which use ``free''."
225 (let ((alien-type (if (alien-type-p type)
227 (parse-alien-type type env))))
228 (multiple-value-bind (size-expr element-type)
229 (if (alien-array-type-p alien-type)
230 (let ((dims (alien-array-type-dimensions alien-type)))
235 "cannot override the size of zero-dimensional arrays"))
236 (when (constantp size)
237 (setf alien-type (copy-alien-array-type alien-type))
238 (setf (alien-array-type-dimensions alien-type)
239 (cons (eval size) (cdr dims)))))
241 (setf size (car dims)))
244 (values `(* ,size ,@(cdr dims))
245 (alien-array-type-element-type alien-type)))
246 (values (or size 1) alien-type))
247 (let ((bits (alien-type-bits element-type))
248 (alignment (alien-type-alignment element-type)))
250 (error "The size of ~S is unknown."
251 (unparse-alien-type element-type)))
253 (error "The alignment of ~S is unknown."
254 (unparse-alien-type element-type)))
255 `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
257 ',(make-alien-pointer-type :to alien-type))))))
259 ;;; Allocate a block of memory at least BITS bits long and return a
260 ;;; system area pointer to it.
261 #!-sb-fluid (declaim (inline %make-alien))
262 (defun %make-alien (bits)
263 (declare (type index bits))
264 (alien-funcall (extern-alien "malloc"
265 (function system-area-pointer unsigned))
266 (ash (the index (+ bits 7)) -3)))
268 #!-sb-fluid (declaim (inline free-alien))
269 (defun free-alien (alien)
271 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
272 by MAKE-ALIEN or malloc(3)."
273 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
277 ;;;; the SLOT operator
279 ;;; Find the field named SLOT, or die trying.
280 (defun slot-or-lose (type slot)
281 (declare (type alien-record-type type)
283 (or (find slot (alien-record-type-fields type)
284 :key #'alien-record-field-name)
285 (error "There is no slot named ~S in ~S." slot type)))
287 ;;; Extract the value from the named slot from the record ALIEN. If
288 ;;; ALIEN is actually a pointer, then DEREF it first.
289 (defun slot (alien slot)
291 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
292 (declare (type alien-value alien)
294 (optimize (inhibit-warnings 3)))
295 (let ((type (alien-value-type alien)))
298 (slot (deref alien) slot))
300 (let ((field (slot-or-lose type slot)))
301 (extract-alien-value (alien-value-sap alien)
302 (alien-record-field-offset field)
303 (alien-record-field-type field)))))))
305 ;;; Deposit the value in the specified slot of the record ALIEN. If
306 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
307 ;;; this when it can't figure out anything better.
308 (defun %set-slot (alien slot value)
309 (declare (type alien-value alien)
311 (optimize (inhibit-warnings 3)))
312 (let ((type (alien-value-type alien)))
315 (%set-slot (deref alien) slot value))
317 (let ((field (slot-or-lose type slot)))
318 (deposit-alien-value (alien-value-sap alien)
319 (alien-record-field-offset field)
320 (alien-record-field-type field)
323 ;;; Compute the address of the specified slot and return a pointer to it.
324 (defun %slot-addr (alien slot)
325 (declare (type alien-value alien)
327 (optimize (inhibit-warnings 3)))
328 (let ((type (alien-value-type alien)))
331 (%slot-addr (deref alien) slot))
333 (let* ((field (slot-or-lose type slot))
334 (offset (alien-record-field-offset field))
335 (field-type (alien-record-field-type field)))
336 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
337 (make-alien-pointer-type :to field-type)))))))
339 ;;;; the DEREF operator
341 ;;; This function does most of the work of the different DEREF
342 ;;; methods. It returns two values: the type and the offset (in bits)
343 ;;; of the referred-to alien.
344 (defun deref-guts (alien indices)
345 (declare (type alien-value alien)
347 (values alien-type integer))
348 (let ((type (alien-value-type alien)))
352 (error "too many indices when DEREF'ing ~S: ~W"
355 (let ((element-type (alien-pointer-type-to type)))
358 (* (align-offset (alien-type-bits element-type)
359 (alien-type-alignment element-type))
363 (unless (= (length indices) (length (alien-array-type-dimensions type)))
364 (error "incorrect number of indices when DEREF'ing ~S: ~W"
365 type (length indices)))
366 (labels ((frob (dims indices offset)
369 (frob (cdr dims) (cdr indices)
370 (+ (if (zerop offset)
372 (* offset (car dims)))
374 (let ((element-type (alien-array-type-element-type type)))
376 (* (align-offset (alien-type-bits element-type)
377 (alien-type-alignment element-type))
378 (frob (alien-array-type-dimensions type)
381 ;;; Dereference the alien and return the results.
382 (defun deref (alien &rest indices)
384 "De-reference an Alien pointer or array. If an array, the indices are used
385 as the indices of the array element to access. If a pointer, one index can
386 optionally be specified, giving the equivalent of C pointer arithmetic."
387 (declare (type alien-value alien)
389 (optimize (inhibit-warnings 3)))
390 (multiple-value-bind (target-type offset) (deref-guts alien indices)
391 (extract-alien-value (alien-value-sap alien)
395 (defun %set-deref (alien value &rest indices)
396 (declare (type alien-value alien)
398 (optimize (inhibit-warnings 3)))
399 (multiple-value-bind (target-type offset) (deref-guts alien indices)
400 (deposit-alien-value (alien-value-sap alien)
405 (defun %deref-addr (alien &rest indices)
406 (declare (type alien-value alien)
408 (optimize (inhibit-warnings 3)))
409 (multiple-value-bind (target-type offset) (deref-guts alien indices)
410 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
411 (make-alien-pointer-type :to target-type))))
413 ;;;; accessing heap alien variables
415 (defun %heap-alien (info)
416 (declare (type heap-alien-info info)
417 (optimize (inhibit-warnings 3)))
418 (extract-alien-value (eval (heap-alien-info-sap-form info))
420 (heap-alien-info-type info)))
422 (defun %set-heap-alien (info value)
423 (declare (type heap-alien-info info)
424 (optimize (inhibit-warnings 3)))
425 (deposit-alien-value (eval (heap-alien-info-sap-form info))
427 (heap-alien-info-type info)
430 (defun %heap-alien-addr (info)
431 (declare (type heap-alien-info info)
432 (optimize (inhibit-warnings 3)))
433 (%sap-alien (eval (heap-alien-info-sap-form info))
434 (make-alien-pointer-type :to (heap-alien-info-type info))))
436 ;;;; accessing local aliens
438 (defun make-local-alien (info)
439 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
440 (alien-sap (alien-sap alien)))
445 (extern-alien "free" (function (values) system-area-pointer))
449 (defun note-local-alien-type (info alien)
450 (declare (ignore info alien))
453 (defun local-alien (info alien)
454 (declare (ignore info))
457 (defun %set-local-alien (info alien value)
458 (declare (ignore info))
459 (setf (deref alien) value))
461 (define-setf-expander local-alien (&whole whole info alien)
462 (let ((value (gensym))
463 (info (if (and (consp info)
464 (eq (car info) 'quote))
466 (error "Something is wrong; local-alien-info not found: ~S"
471 `(if (%local-alien-forced-to-memory-p ',info)
472 (%set-local-alien ',info ,alien ,value)
474 (deport ,value ',(local-alien-info-type info))))
477 (defun %local-alien-forced-to-memory-p (info)
478 (local-alien-info-force-to-memory-p info))
480 (defun %local-alien-addr (info alien)
481 (declare (type local-alien-info info))
482 (unless (local-alien-info-force-to-memory-p info)
483 (error "~S isn't forced to memory. Something went wrong." alien))
486 (defun dispose-local-alien (info alien)
487 (declare (ignore info))
488 (cancel-finalization alien)
493 (defmacro cast (alien type &environment env)
495 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
496 must be Alien array, pointer or function types."
497 `(%cast ,alien ',(parse-alien-type type env)))
499 (defun %cast (alien target-type)
500 (declare (type alien-value alien)
501 (type alien-type target-type)
502 (optimize (safety 2))
503 (optimize (inhibit-warnings 3)))
504 (if (or (alien-pointer-type-p target-type)
505 (alien-array-type-p target-type)
506 (alien-fun-type-p target-type))
507 (let ((alien-type (alien-value-type alien)))
508 (if (or (alien-pointer-type-p alien-type)
509 (alien-array-type-p alien-type)
510 (alien-fun-type-p alien-type))
511 (naturalize (alien-value-sap alien) target-type)
512 (error "~S cannot be casted." alien)))
513 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
515 ;;;; the ALIEN-SIZE macro
517 (defmacro alien-size (type &optional (units :bits) &environment env)
519 "Return the size of the alien type TYPE. UNITS specifies the units to
520 use and can be either :BITS, :BYTES, or :WORDS."
521 (let* ((alien-type (parse-alien-type type env))
522 (bits (alien-type-bits alien-type)))
524 (values (ceiling bits
527 (:bytes sb!vm:n-byte-bits)
528 (:words sb!vm:n-word-bits))))
529 (error "unknown size for alien type ~S"
530 (unparse-alien-type alien-type)))))
532 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
534 (defun naturalize (alien type)
535 (declare (type alien-type type))
536 (funcall (coerce (compute-naturalize-lambda type) 'function)
539 (defun deport (value type)
540 (declare (type alien-type type))
541 (funcall (coerce (compute-deport-lambda type) 'function)
544 (defun extract-alien-value (sap offset type)
545 (declare (type system-area-pointer sap)
546 (type unsigned-byte offset)
547 (type alien-type type))
548 (funcall (coerce (compute-extract-lambda type) 'function)
551 (defun deposit-alien-value (sap offset type value)
552 (declare (type system-area-pointer sap)
553 (type unsigned-byte offset)
554 (type alien-type type))
555 (funcall (coerce (compute-deposit-lambda type) 'function)
556 sap offset type value))
558 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
560 (defun alien-funcall (alien &rest args)
562 "Call the foreign function ALIEN with the specified arguments. ALIEN's
563 type specifies the argument and result types."
564 (declare (type alien-value alien))
565 (let ((type (alien-value-type alien)))
568 (apply #'alien-funcall (deref alien) args))
570 (unless (= (length (alien-fun-type-arg-types type))
572 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
574 (length (alien-fun-type-arg-types type))
576 (let ((stub (alien-fun-type-stub type)))
580 (parms (make-gensym-list (length args))))
582 `(lambda (,fun ,@parms)
583 (declare (type (alien ,type) ,fun))
584 (alien-funcall ,fun ,@parms)))))
585 (setf (alien-fun-type-stub type) stub))
586 (apply stub alien args)))
588 (error "~S is not an alien function." alien)))))
590 (defmacro define-alien-routine (name result-type
594 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
596 Define a foreign interface function for the routine with the specified NAME.
597 Also automatically DECLAIM the FTYPE of the defined function.
599 NAME may be either a string, a symbol, or a list of the form (string symbol).
601 RETURN-TYPE is the alien type for the function return value. VOID may be
602 used to specify a function with no result.
604 The remaining forms specify individual arguments that are passed to the
605 routine. ARG-NAME is a symbol that names the argument, primarily for
606 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
607 way that the argument is passed.
610 An :IN argument is simply passed by value. The value to be passed is
611 obtained from argument(s) to the interface function. No values are
612 returned for :In arguments. This is the default mode.
615 The specified argument type must be a pointer to a fixed sized object.
616 A pointer to a preallocated object is passed to the routine, and the
617 the object is accessed on return, with the value being returned from
618 the interface function. :OUT and :IN-OUT cannot be used with pointers
619 to arrays, records or functions.
622 This is similar to :IN, except that the argument values are stored
623 on the stack, and a pointer to the object is passed instead of
627 This is a combination of :OUT and :COPY. A pointer to the argument is
628 passed, with the object being initialized from the supplied argument
629 and the return value being determined by accessing the object on
631 (multiple-value-bind (lisp-name alien-name)
632 (pick-lisp-and-alien-names name)
633 (collect ((docs) (lisp-args) (lisp-arg-types)
635 (cond ((eql result-type 'void)
636 ;; What values does a function return, if it
637 ;; returns no values? Exactly one - NIL. -- APD,
641 ;; FIXME: Check for VALUES.
642 (list `(alien ,result-type)))))
643 (arg-types) (alien-vars)
644 (alien-args) (results))
648 (destructuring-bind (name type &optional (style :in)) arg
649 (unless (member style '(:in :copy :out :in-out))
650 (error "bogus argument style ~S in ~S" style arg))
651 (when (and (member style '(:out :in-out))
652 (typep (parse-alien-type type lexenv)
653 'alien-pointer-type))
654 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
657 (cond ((eq style :in)
661 (setq arg-type `(* ,type))
663 (alien-vars `(,name ,type))
664 (alien-vars `(,name ,type ,name)))
665 (alien-args `(addr ,name))))
667 (unless (eq style :out)
670 ;; FIXME: It should be something
671 ;; like `(ALIEN ,ARG-TYPE), except
672 ;; for we also accept SAPs where
673 ;; pointers are required.
675 (when (or (eq style :out) (eq style :in-out))
677 (lisp-result-types `(alien ,type))))))
679 ;; The theory behind this automatic DECLAIM is that (1) if
680 ;; you're calling C, static typing is what you're doing
681 ;; anyway, and (2) such a declamation can be (especially for
682 ;; alien values) both messy to do by hand and very important
683 ;; for performance of later code which uses the return value.
684 (declaim (ftype (function ,(lisp-arg-types)
685 (values ,@(lisp-result-types) &optional))
687 (defun ,lisp-name ,(lisp-args)
690 ((,lisp-name (function ,result-type ,@(arg-types))
694 (values (alien-funcall ,lisp-name ,@(alien-args))
697 (if (alien-values-type-p result-type)
698 ;; FIXME: RESULT-TYPE is a type specifier, so it
699 ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
700 ;; that if RESULT-TYPE is VOID, then this code
701 ;; disagrees with the computation of the return type
702 ;; and with all usages of this macro. -- APD,
704 (let ((temps (make-gensym-list
706 (alien-values-type-values result-type)))))
707 `(multiple-value-bind ,temps
708 (alien-funcall ,lisp-name ,@(alien-args))
709 (values ,@temps ,@(results))))
710 (values (alien-funcall ,lisp-name ,@(alien-args))
713 (defmacro def-alien-routine (&rest rest)
714 (deprecation-warning 'def-alien-routine 'define-alien-routine)
715 `(define-alien-routine ,@rest))
717 (defun alien-typep (object type)
719 "Return T iff OBJECT is an alien of type TYPE."
720 (let ((lisp-rep-type (compute-lisp-rep-type type)))
722 (typep object lisp-rep-type)
723 (and (alien-value-p object)
724 (alien-subtype-p (alien-value-type object) type)))))