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 (/show ":EXTERN case")
141 (let ((info (make-heap-alien-info
143 :sap-form `(foreign-symbol-address
146 ((,symbol (%heap-alien ',info)))
149 (/show ":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 (/show "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)
183 (sap-int (alien-value-sap value)))))
185 #!-sb-fluid (declaim (inline null-alien))
186 (defun null-alien (x)
188 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
189 (zerop (sap-int (alien-sap x))))
191 (defmacro sap-alien (sap type &environment env)
193 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
194 evaluated.) TYPE must be pointer-like."
195 (let ((alien-type (parse-alien-type type env)))
196 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
197 `(%sap-alien ,sap ',alien-type)
198 (error "cannot make an alien of type ~S out of a SAP" type))))
200 (defun %sap-alien (sap type)
201 (declare (type system-area-pointer sap)
202 (type alien-type type))
203 (make-alien-value :sap sap :type type))
205 (defun alien-sap (alien)
207 "Return a System-Area-Pointer pointing to Alien's data."
208 (declare (type alien-value alien))
209 (alien-value-sap alien))
211 ;;;; allocation/deallocation of heap aliens
213 (defmacro make-alien (type &optional size &environment env)
215 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
216 is supplied, how it is interpreted depends on TYPE. If TYPE is an array
217 type, SIZE is used as the first dimension for the allocated array. If TYPE
218 is not an array, then SIZE is the number of elements to allocate. The
219 memory is allocated using ``malloc'', so it can be passed to foreign
220 functions which use ``free''."
221 (let ((alien-type (if (alien-type-p type)
223 (parse-alien-type type env))))
224 (multiple-value-bind (size-expr element-type)
225 (if (alien-array-type-p alien-type)
226 (let ((dims (alien-array-type-dimensions alien-type)))
231 "cannot override the size of zero-dimensional arrays"))
232 (when (constantp size)
233 (setf alien-type (copy-alien-array-type alien-type))
234 (setf (alien-array-type-dimensions alien-type)
235 (cons (eval size) (cdr dims)))))
237 (setf size (car dims)))
240 (values `(* ,size ,@(cdr dims))
241 (alien-array-type-element-type alien-type)))
242 (values (or size 1) alien-type))
243 (let ((bits (alien-type-bits element-type))
244 (alignment (alien-type-alignment element-type)))
246 (error "The size of ~S is unknown."
247 (unparse-alien-type element-type)))
249 (error "The alignment of ~S is unknown."
250 (unparse-alien-type element-type)))
251 `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
253 ',(make-alien-pointer-type :to alien-type))))))
255 ;;; Allocate a block of memory at least BITS bits long and return a
256 ;;; system area pointer to it.
257 #!-sb-fluid (declaim (inline %make-alien))
258 (defun %make-alien (bits)
259 (declare (type index bits))
260 (alien-funcall (extern-alien "malloc"
261 (function system-area-pointer unsigned))
262 (ash (the index (+ bits 7)) -3)))
264 #!-sb-fluid (declaim (inline free-alien))
265 (defun free-alien (alien)
267 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
268 by MAKE-ALIEN or malloc(3)."
269 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
273 ;;;; the SLOT operator
275 ;;; Find the field named SLOT, or die trying.
276 (defun slot-or-lose (type slot)
277 (declare (type alien-record-type type)
279 (or (find slot (alien-record-type-fields type)
280 :key #'alien-record-field-name)
281 (error "There is no slot named ~S in ~S." slot type)))
283 ;;; Extract the value from the named slot from the record ALIEN. If
284 ;;; ALIEN is actually a pointer, then DEREF it first.
285 (defun slot (alien slot)
287 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
288 (declare (type alien-value alien)
290 (optimize (inhibit-warnings 3)))
291 (let ((type (alien-value-type alien)))
294 (slot (deref alien) slot))
296 (let ((field (slot-or-lose type slot)))
297 (extract-alien-value (alien-value-sap alien)
298 (alien-record-field-offset field)
299 (alien-record-field-type field)))))))
301 ;;; Deposit the value in the specified slot of the record ALIEN. If
302 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
303 ;;; this when it can't figure out anything better.
304 (defun %set-slot (alien slot value)
305 (declare (type alien-value alien)
307 (optimize (inhibit-warnings 3)))
308 (let ((type (alien-value-type alien)))
311 (%set-slot (deref alien) slot value))
313 (let ((field (slot-or-lose type slot)))
314 (deposit-alien-value (alien-value-sap alien)
315 (alien-record-field-offset field)
316 (alien-record-field-type field)
319 ;;; Compute the address of the specified slot and return a pointer to it.
320 (defun %slot-addr (alien slot)
321 (declare (type alien-value alien)
323 (optimize (inhibit-warnings 3)))
324 (let ((type (alien-value-type alien)))
327 (%slot-addr (deref alien) slot))
329 (let* ((field (slot-or-lose type slot))
330 (offset (alien-record-field-offset field))
331 (field-type (alien-record-field-type field)))
332 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
333 (make-alien-pointer-type :to field-type)))))))
335 ;;;; the DEREF operator
337 ;;; This function does most of the work of the different DEREF
338 ;;; methods. It returns two values: the type and the offset (in bits)
339 ;;; of the referred-to alien.
340 (defun deref-guts (alien indices)
341 (declare (type alien-value alien)
343 (values alien-type integer))
344 (let ((type (alien-value-type alien)))
348 (error "too many indices when DEREF'ing ~S: ~W"
351 (let ((element-type (alien-pointer-type-to type)))
354 (* (align-offset (alien-type-bits element-type)
355 (alien-type-alignment element-type))
359 (unless (= (length indices) (length (alien-array-type-dimensions type)))
360 (error "incorrect number of indices when DEREF'ing ~S: ~W"
361 type (length indices)))
362 (labels ((frob (dims indices offset)
365 (frob (cdr dims) (cdr indices)
366 (+ (if (zerop offset)
368 (* offset (car dims)))
370 (let ((element-type (alien-array-type-element-type type)))
372 (* (align-offset (alien-type-bits element-type)
373 (alien-type-alignment element-type))
374 (frob (alien-array-type-dimensions type)
377 ;;; Dereference the alien and return the results.
378 (defun deref (alien &rest indices)
380 "De-reference an Alien pointer or array. If an array, the indices are used
381 as the indices of the array element to access. If a pointer, one index can
382 optionally be specified, giving the equivalent of C pointer arithmetic."
383 (declare (type alien-value alien)
385 (optimize (inhibit-warnings 3)))
386 (multiple-value-bind (target-type offset) (deref-guts alien indices)
387 (extract-alien-value (alien-value-sap alien)
391 (defun %set-deref (alien value &rest indices)
392 (declare (type alien-value alien)
394 (optimize (inhibit-warnings 3)))
395 (multiple-value-bind (target-type offset) (deref-guts alien indices)
396 (deposit-alien-value (alien-value-sap alien)
401 (defun %deref-addr (alien &rest indices)
402 (declare (type alien-value alien)
404 (optimize (inhibit-warnings 3)))
405 (multiple-value-bind (target-type offset) (deref-guts alien indices)
406 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
407 (make-alien-pointer-type :to target-type))))
409 ;;;; accessing heap alien variables
411 (defun %heap-alien (info)
412 (declare (type heap-alien-info info)
413 (optimize (inhibit-warnings 3)))
414 (extract-alien-value (eval (heap-alien-info-sap-form info))
416 (heap-alien-info-type info)))
418 (defun %set-heap-alien (info value)
419 (declare (type heap-alien-info info)
420 (optimize (inhibit-warnings 3)))
421 (deposit-alien-value (eval (heap-alien-info-sap-form info))
423 (heap-alien-info-type info)
426 (defun %heap-alien-addr (info)
427 (declare (type heap-alien-info info)
428 (optimize (inhibit-warnings 3)))
429 (%sap-alien (eval (heap-alien-info-sap-form info))
430 (make-alien-pointer-type :to (heap-alien-info-type info))))
432 ;;;; accessing local aliens
434 (defun make-local-alien (info)
435 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
436 (alien-sap (alien-sap alien)))
441 (extern-alien "free" (function (values) system-area-pointer))
445 (defun note-local-alien-type (info alien)
446 (declare (ignore info alien))
449 (defun local-alien (info alien)
450 (declare (ignore info))
453 (defun %set-local-alien (info alien value)
454 (declare (ignore info))
455 (setf (deref alien) value))
457 (define-setf-expander local-alien (&whole whole info alien)
458 (let ((value (gensym))
459 (info (if (and (consp info)
460 (eq (car info) 'quote))
462 (error "Something is wrong; local-alien-info not found: ~S"
467 `(if (%local-alien-forced-to-memory-p ',info)
468 (%set-local-alien ',info ,alien ,value)
470 (deport ,value ',(local-alien-info-type info))))
473 (defun %local-alien-forced-to-memory-p (info)
474 (local-alien-info-force-to-memory-p info))
476 (defun %local-alien-addr (info alien)
477 (declare (type local-alien-info info))
478 (unless (local-alien-info-force-to-memory-p info)
479 (error "~S isn't forced to memory. Something went wrong." alien))
482 (defun dispose-local-alien (info alien)
483 (declare (ignore info))
484 (cancel-finalization alien)
489 (defmacro cast (alien type &environment env)
491 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
492 must be Alien array, pointer or function types."
493 `(%cast ,alien ',(parse-alien-type type env)))
495 (defun %cast (alien target-type)
496 (declare (type alien-value alien)
497 (type alien-type target-type)
498 (optimize (safety 2))
499 (optimize (inhibit-warnings 3)))
500 (if (or (alien-pointer-type-p target-type)
501 (alien-array-type-p target-type)
502 (alien-fun-type-p target-type))
503 (let ((alien-type (alien-value-type alien)))
504 (if (or (alien-pointer-type-p alien-type)
505 (alien-array-type-p alien-type)
506 (alien-fun-type-p alien-type))
507 (naturalize (alien-value-sap alien) target-type)
508 (error "~S cannot be casted." alien)))
509 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
511 ;;;; the ALIEN-SIZE macro
513 (defmacro alien-size (type &optional (units :bits) &environment env)
515 "Return the size of the alien type TYPE. UNITS specifies the units to
516 use and can be either :BITS, :BYTES, or :WORDS."
517 (let* ((alien-type (parse-alien-type type env))
518 (bits (alien-type-bits alien-type)))
520 (values (ceiling bits
523 (:bytes sb!vm:n-byte-bits)
524 (:words sb!vm:n-word-bits))))
525 (error "unknown size for alien type ~S"
526 (unparse-alien-type alien-type)))))
528 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
530 (defun naturalize (alien type)
531 (declare (type alien-type type))
532 (funcall (coerce (compute-naturalize-lambda type) 'function)
535 (defun deport (value type)
536 (declare (type alien-type type))
537 (funcall (coerce (compute-deport-lambda type) 'function)
540 (defun extract-alien-value (sap offset type)
541 (declare (type system-area-pointer sap)
542 (type unsigned-byte offset)
543 (type alien-type type))
544 (funcall (coerce (compute-extract-lambda type) 'function)
547 (defun deposit-alien-value (sap offset type value)
548 (declare (type system-area-pointer sap)
549 (type unsigned-byte offset)
550 (type alien-type type))
551 (funcall (coerce (compute-deposit-lambda type) 'function)
552 sap offset type value))
554 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
556 (defun alien-funcall (alien &rest args)
558 "Call the foreign function ALIEN with the specified arguments. ALIEN's
559 type specifies the argument and result types."
560 (declare (type alien-value alien))
561 (let ((type (alien-value-type alien)))
564 (apply #'alien-funcall (deref alien) args))
566 (unless (= (length (alien-fun-type-arg-types type))
568 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
570 (length (alien-fun-type-arg-types type))
572 (let ((stub (alien-fun-type-stub type)))
576 (parms (make-gensym-list (length args))))
578 `(lambda (,fun ,@parms)
579 (declare (type (alien ,type) ,fun))
580 (alien-funcall ,fun ,@parms)))))
581 (setf (alien-fun-type-stub type) stub))
582 (apply stub alien args)))
584 (error "~S is not an alien function." alien)))))
586 (defmacro define-alien-routine (name result-type
590 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
592 Define a foreign interface function for the routine with the specified NAME.
593 Also automatically DECLAIM the FTYPE of the defined function.
595 NAME may be either a string, a symbol, or a list of the form (string symbol).
597 RETURN-TYPE is the alien type for the function return value. VOID may be
598 used to specify a function with no result.
600 The remaining forms specify individual arguments that are passed to the
601 routine. ARG-NAME is a symbol that names the argument, primarily for
602 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
603 way that the argument is passed.
606 An :IN argument is simply passed by value. The value to be passed is
607 obtained from argument(s) to the interface function. No values are
608 returned for :In arguments. This is the default mode.
611 The specified argument type must be a pointer to a fixed sized object.
612 A pointer to a preallocated object is passed to the routine, and the
613 the object is accessed on return, with the value being returned from
614 the interface function. :OUT and :IN-OUT cannot be used with pointers
615 to arrays, records or functions.
618 This is similar to :IN, except that the argument values are stored
619 on the stack, and a pointer to the object is passed instead of
623 This is a combination of :OUT and :COPY. A pointer to the argument is
624 passed, with the object being initialized from the supplied argument
625 and the return value being determined by accessing the object on
627 (multiple-value-bind (lisp-name alien-name)
628 (pick-lisp-and-alien-names name)
629 (collect ((docs) (lisp-args) (lisp-arg-types)
631 (cond ((eql result-type 'void)
632 ;; What values does a function return, if it
633 ;; returns no values? Exactly one - NIL. -- APD,
637 ;; FIXME: Check for VALUES.
638 (list `(alien ,result-type)))))
639 (arg-types) (alien-vars)
640 (alien-args) (results))
644 (destructuring-bind (name type &optional (style :in)) arg
645 (unless (member style '(:in :copy :out :in-out))
646 (error "bogus argument style ~S in ~S" style arg))
647 (when (and (member style '(:out :in-out))
648 (typep (parse-alien-type type lexenv)
649 'alien-pointer-type))
650 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
653 (cond ((eq style :in)
657 (setq arg-type `(* ,type))
659 (alien-vars `(,name ,type))
660 (alien-vars `(,name ,type ,name)))
661 (alien-args `(addr ,name))))
663 (unless (eq style :out)
666 ;; FIXME: It should be something
667 ;; like `(ALIEN ,ARG-TYPE), except
668 ;; for we also accept SAPs where
669 ;; pointers are required.
671 (when (or (eq style :out) (eq style :in-out))
673 (lisp-result-types `(alien ,type))))))
675 ;; The theory behind this automatic DECLAIM is that (1) if
676 ;; you're calling C, static typing is what you're doing
677 ;; anyway, and (2) such a declamation can be (especially for
678 ;; alien values) both messy to do by hand and very important
679 ;; for performance of later code which uses the return value.
680 (declaim (ftype (function ,(lisp-arg-types)
681 (values ,@(lisp-result-types) &optional))
683 (defun ,lisp-name ,(lisp-args)
686 ((,lisp-name (function ,result-type ,@(arg-types))
690 (values (alien-funcall ,lisp-name ,@(alien-args))
693 (if (alien-values-type-p result-type)
694 ;; FIXME: RESULT-TYPE is a type specifier, so it
695 ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
696 ;; that if RESULT-TYPE is VOID, then this code
697 ;; disagrees with the computation of the return type
698 ;; and with all usages of this macro. -- APD,
700 (let ((temps (make-gensym-list
702 (alien-values-type-values result-type)))))
703 `(multiple-value-bind ,temps
704 (alien-funcall ,lisp-name ,@(alien-args))
705 (values ,@temps ,@(results))))
706 (values (alien-funcall ,lisp-name ,@(alien-args))
709 (defmacro def-alien-routine (&rest rest)
710 (deprecation-warning 'def-alien-routine 'define-alien-routine)
711 `(define-alien-routine ,@rest))
713 (defun alien-typep (object type)
715 "Return T iff OBJECT is an alien of type TYPE."
716 (let ((lisp-rep-type (compute-lisp-rep-type type)))
718 (typep object lisp-rep-type)
719 (and (alien-value-p object)
720 (alien-subtype-p (alien-value-type object) type)))))