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 def-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 (%def-alien-variable ',lisp-name
64 ;;; Do the actual work of DEF-ALIEN-VARIABLE.
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66 (defun %def-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 (clear-info :variable :constant-value lisp-name)
70 (setf (info :variable :alien-info lisp-name)
71 (make-heap-alien-info :type type
72 :sap-form `(foreign-symbol-address
75 (defmacro extern-alien (name type &environment env)
77 "Access the alien variable named NAME, assuming it is of type TYPE. This
79 (let ((alien-name (etypecase name
80 (symbol (guess-alien-name-from-lisp-name name))
82 `(%heap-alien ',(make-heap-alien-info
83 :type (parse-alien-type type env)
84 :sap-form `(foreign-symbol-address ',alien-name)))))
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 The alien is allocated on the heap, and has infinite extent. The alien
95 is allocated at load time, so the same piece of memory is used each time
98 No alien is allocated, but VAR is established as a local name for
99 the external alien given by EXTERNAL-NAME."
100 (with-auxiliary-alien-types env
101 (dolist (binding (reverse bindings))
103 (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
105 (let ((alien-type (parse-alien-type type env)))
106 (multiple-value-bind (allocation initial-value)
111 (values opt1 (guess-alien-name-from-lisp-name symbol)))
115 (values :local opt1))))
121 (make-symbol (concatenate 'string "SAP-FOR-"
122 (symbol-name symbol)))))
123 `((let ((,sap (load-time-value (%make-alien ...))))
124 (declare (type system-area-pointer ,sap))
126 ((,symbol (sap-alien ,sap ,type)))
127 ,@(when initial-value
128 `((setq ,symbol ,initial-value)))
131 (let ((info (make-heap-alien-info
133 :sap-form `(foreign-symbol-address
136 ((,symbol (%heap-alien ',info)))
140 (initval (if initial-value (gensym)))
141 (info (make-local-alien-info :type alien-type)))
142 `((let ((,var (make-local-alien ',info))
143 ,@(when initial-value
144 `((,initval ,initial-value))))
145 (note-local-alien-type ',info ,var)
146 (multiple-value-prog1
148 ((,symbol (local-alien ',info ,var)))
149 ,@(when initial-value
150 `((setq ,symbol ,initval)))
152 (dispose-local-alien ',info ,var))))))))))))
153 (verify-local-auxiliaries-okay)
154 `(symbol-macrolet ((&auxiliary-type-definitions&
155 ,(append *new-auxiliary-types*
156 (auxiliary-type-definitions env))))
159 ;;;; runtime C values that don't correspond directly to Lisp types
161 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
162 ;;; 'cause it has to be real early in the cold-load order.
163 #!-sb-fluid (declaim (freeze-type alien-value))
164 (def!method print-object ((value alien-value) stream)
165 (print-unreadable-object (value stream)
169 (sap-int (alien-value-sap value)))))
171 #!-sb-fluid (declaim (inline null-alien))
172 (defun null-alien (x)
174 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
175 (zerop (sap-int (alien-sap x))))
177 (defmacro sap-alien (sap type &environment env)
179 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
180 evaluated.) TYPE must be pointer-like."
181 (let ((alien-type (parse-alien-type type env)))
182 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
183 `(%sap-alien ,sap ',alien-type)
184 (error "cannot make aliens of type ~S out of SAPs" type))))
186 (defun %sap-alien (sap type)
187 (declare (type system-area-pointer sap)
188 (type alien-type type))
189 (make-alien-value :sap sap :type type))
191 (defun alien-sap (alien)
193 "Return a System-Area-Pointer pointing to Alien's data."
194 (declare (type alien-value alien))
195 (alien-value-sap alien))
197 ;;;; allocation/deallocation of heap aliens
199 (defmacro make-alien (type &optional size &environment env)
201 "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
202 is supplied, how it is interpreted depends on TYPE. If TYPE is an array
203 type, SIZE is used as the first dimension for the allocated array. If TYPE
204 is not an array, then SIZE is the number of elements to allocate. The
205 memory is allocated using ``malloc'', so it can be passed to foreign
206 functions which use ``free''."
207 (let ((alien-type (if (alien-type-p type)
209 (parse-alien-type type env))))
210 (multiple-value-bind (size-expr element-type)
211 (if (alien-array-type-p alien-type)
212 (let ((dims (alien-array-type-dimensions alien-type)))
217 "cannot override the size of zero-dimensional arrays"))
218 (when (constantp size)
219 (setf alien-type (copy-alien-array-type alien-type))
220 (setf (alien-array-type-dimensions alien-type)
221 (cons (eval size) (cdr dims)))))
223 (setf size (car dims)))
226 (values `(* ,size ,@(cdr dims))
227 (alien-array-type-element-type alien-type)))
228 (values (or size 1) alien-type))
229 (let ((bits (alien-type-bits element-type))
230 (alignment (alien-type-alignment element-type)))
232 (error "The size of ~S is unknown."
233 (unparse-alien-type element-type)))
235 (error "The alignment of ~S is unknown."
236 (unparse-alien-type element-type)))
237 `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
239 ',(make-alien-pointer-type :to alien-type))))))
241 ;;; Allocate a block of memory at least BITS bits long and return a
242 ;;; system area pointer to it.
243 #!-sb-fluid (declaim (inline %make-alien))
244 (defun %make-alien (bits)
245 (declare (type index bits))
246 (alien-funcall (extern-alien "malloc"
247 (function system-area-pointer unsigned))
248 (ash (the index (+ bits 7)) -3)))
250 #!-sb-fluid (declaim (inline free-alien))
251 (defun free-alien (alien)
253 "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
254 by MAKE-ALIEN or malloc(3)."
255 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
259 ;;;; the SLOT operator
261 ;;; Find the field named SLOT, or die trying.
262 (defun slot-or-lose (type slot)
263 (declare (type alien-record-type type)
265 (or (find slot (alien-record-type-fields type)
266 :key #'alien-record-field-name)
267 (error "There is no slot named ~S in ~S." slot type)))
269 ;;; Extract the value from the named slot from the record ALIEN. If
270 ;;; ALIEN is actually a pointer, then DEREF it first.
271 (defun slot (alien slot)
273 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
274 (declare (type alien-value alien)
276 (optimize (inhibit-warnings 3)))
277 (let ((type (alien-value-type alien)))
280 (slot (deref alien) slot))
282 (let ((field (slot-or-lose type slot)))
283 (extract-alien-value (alien-value-sap alien)
284 (alien-record-field-offset field)
285 (alien-record-field-type field)))))))
287 ;;; Deposit the value in the specified slot of the record ALIEN. If
288 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
289 ;;; this when it can't figure out anything better.
290 (defun %set-slot (alien slot value)
291 (declare (type alien-value alien)
293 (optimize (inhibit-warnings 3)))
294 (let ((type (alien-value-type alien)))
297 (%set-slot (deref alien) slot value))
299 (let ((field (slot-or-lose type slot)))
300 (deposit-alien-value (alien-value-sap alien)
301 (alien-record-field-offset field)
302 (alien-record-field-type field)
305 ;;; Compute the address of the specified slot and return a pointer to it.
306 (defun %slot-addr (alien slot)
307 (declare (type alien-value alien)
309 (optimize (inhibit-warnings 3)))
310 (let ((type (alien-value-type alien)))
313 (%slot-addr (deref alien) slot))
315 (let* ((field (slot-or-lose type slot))
316 (offset (alien-record-field-offset field))
317 (field-type (alien-record-field-type field)))
318 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:byte-bits))
319 (make-alien-pointer-type :to field-type)))))))
321 ;;;; the DEREF operator
323 ;;; This function does most of the work of the different DEREF
324 ;;; methods. It returns two values: the type and the offset (in bits)
325 ;;; of the referred-to alien.
326 (defun deref-guts (alien indices)
327 (declare (type alien-value alien)
329 (values alien-type integer))
330 (let ((type (alien-value-type alien)))
334 (error "too many indices when derefing ~S: ~D"
337 (let ((element-type (alien-pointer-type-to type)))
340 (* (align-offset (alien-type-bits element-type)
341 (alien-type-alignment element-type))
345 (unless (= (length indices) (length (alien-array-type-dimensions type)))
346 (error "incorrect number of indices when derefing ~S: ~D"
347 type (length indices)))
348 (labels ((frob (dims indices offset)
351 (frob (cdr dims) (cdr indices)
352 (+ (if (zerop offset)
354 (* offset (car dims)))
356 (let ((element-type (alien-array-type-element-type type)))
358 (* (align-offset (alien-type-bits element-type)
359 (alien-type-alignment element-type))
360 (frob (alien-array-type-dimensions type)
363 ;;; Dereference the alien and return the results.
364 (defun deref (alien &rest indices)
366 "De-reference an Alien pointer or array. If an array, the indices are used
367 as the indices of the array element to access. If a pointer, one index can
368 optionally be specified, giving the equivalent of C pointer arithmetic."
369 (declare (type alien-value alien)
371 (optimize (inhibit-warnings 3)))
372 (multiple-value-bind (target-type offset) (deref-guts alien indices)
373 (extract-alien-value (alien-value-sap alien)
377 (defun %set-deref (alien value &rest indices)
378 (declare (type alien-value alien)
380 (optimize (inhibit-warnings 3)))
381 (multiple-value-bind (target-type offset) (deref-guts alien indices)
382 (deposit-alien-value (alien-value-sap alien)
387 (defun %deref-addr (alien &rest indices)
388 (declare (type alien-value alien)
390 (optimize (inhibit-warnings 3)))
391 (multiple-value-bind (target-type offset) (deref-guts alien indices)
392 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:byte-bits))
393 (make-alien-pointer-type :to target-type))))
395 ;;;; accessing heap alien variables
397 (defun %heap-alien (info)
398 (declare (type heap-alien-info info)
399 (optimize (inhibit-warnings 3)))
400 (extract-alien-value (eval (heap-alien-info-sap-form info))
402 (heap-alien-info-type info)))
404 (defun %set-heap-alien (info value)
405 (declare (type heap-alien-info info)
406 (optimize (inhibit-warnings 3)))
407 (deposit-alien-value (eval (heap-alien-info-sap-form info))
409 (heap-alien-info-type info)
412 (defun %heap-alien-addr (info)
413 (declare (type heap-alien-info info)
414 (optimize (inhibit-warnings 3)))
415 (%sap-alien (eval (heap-alien-info-sap-form info))
416 (make-alien-pointer-type :to (heap-alien-info-type info))))
418 ;;;; accessing local aliens
420 (defun make-local-alien (info)
421 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
422 (alien-sap (alien-sap alien)))
427 (extern-alien "free" (function (values) system-area-pointer))
431 (defun note-local-alien-type (info alien)
432 (declare (ignore info alien))
435 (defun local-alien (info alien)
436 (declare (ignore info))
439 (defun %set-local-alien (info alien value)
440 (declare (ignore info))
441 (setf (deref alien) value))
443 (define-setf-expander local-alien (&whole whole info alien)
444 (let ((value (gensym))
445 (info (if (and (consp info)
446 (eq (car info) 'quote))
448 (error "Something is wrong; local-alien-info not found: ~S"
453 (if sb!c:*converting-for-interpreter*
454 `(%set-local-alien ',info ,alien ,value)
455 `(if (%local-alien-forced-to-memory-p ',info)
456 (%set-local-alien ',info ,alien ,value)
458 (deport ,value ',(local-alien-info-type info)))))
461 (defun %local-alien-forced-to-memory-p (info)
462 (local-alien-info-force-to-memory-p info))
464 (defun %local-alien-addr (info alien)
465 (declare (type local-alien-info info))
466 (unless (local-alien-info-force-to-memory-p info)
467 (error "~S isn't forced to memory. Something went wrong." alien))
470 (defun dispose-local-alien (info alien)
471 (declare (ignore info))
472 (cancel-finalization alien)
477 (defmacro cast (alien type &environment env)
479 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
480 must be Alien array, pointer or function types."
481 `(%cast ,alien ',(parse-alien-type type env)))
483 (defun %cast (alien target-type)
484 (declare (type alien-value alien)
485 (type alien-type target-type)
486 (optimize (safety 2))
487 (optimize (inhibit-warnings 3)))
488 (if (or (alien-pointer-type-p target-type)
489 (alien-array-type-p target-type)
490 (alien-function-type-p target-type))
491 (let ((alien-type (alien-value-type alien)))
492 (if (or (alien-pointer-type-p alien-type)
493 (alien-array-type-p alien-type)
494 (alien-function-type-p alien-type))
495 (naturalize (alien-value-sap alien) target-type)
496 (error "~S cannot be casted." alien)))
497 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
499 ;;;; the ALIEN-SIZE macro
501 (defmacro alien-size (type &optional (units :bits) &environment env)
503 "Return the size of the alien type TYPE. UNITS specifies the units to
504 use and can be either :BITS, :BYTES, or :WORDS."
505 (let* ((alien-type (parse-alien-type type env))
506 (bits (alien-type-bits alien-type)))
508 (values (ceiling bits
511 (:bytes sb!vm:byte-bits)
512 (:words sb!vm:word-bits))))
513 (error "unknown size for alien type ~S"
514 (unparse-alien-type alien-type)))))
516 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
518 (defun naturalize (alien type)
519 (declare (type alien-type type))
520 (funcall (coerce (compute-naturalize-lambda type) 'function)
523 (defun deport (value type)
524 (declare (type alien-type type))
525 (funcall (coerce (compute-deport-lambda type) 'function)
528 (defun extract-alien-value (sap offset type)
529 (declare (type system-area-pointer sap)
530 (type unsigned-byte offset)
531 (type alien-type type))
532 (funcall (coerce (compute-extract-lambda type) 'function)
535 (defun deposit-alien-value (sap offset type value)
536 (declare (type system-area-pointer sap)
537 (type unsigned-byte offset)
538 (type alien-type type))
539 (funcall (coerce (compute-deposit-lambda type) 'function)
540 sap offset type value))
542 ;;;; ALIEN-FUNCALL, DEF-ALIEN-ROUTINE
544 (defun alien-funcall (alien &rest args)
546 "Call the foreign function ALIEN with the specified arguments. ALIEN's
547 type specifies the argument and result types."
548 (declare (type alien-value alien))
549 (let ((type (alien-value-type alien)))
552 (apply #'alien-funcall (deref alien) args))
554 (unless (= (length (alien-function-type-arg-types type))
556 (error "wrong number of arguments for ~S~%expected ~D, got ~D"
558 (length (alien-function-type-arg-types type))
560 (let ((stub (alien-function-type-stub type)))
564 (parms (make-gensym-list (length args))))
566 `(lambda (,fun ,@parms)
567 (declare (type (alien ,type) ,fun))
568 (alien-funcall ,fun ,@parms)))))
569 (setf (alien-function-type-stub type) stub))
570 (apply stub alien args)))
572 (error "~S is not an alien function." alien)))))
574 (defmacro def-alien-routine (name result-type &rest args &environment env)
576 "Def-C-Routine Name Result-Type
577 {(Arg-Name Arg-Type [Style])}*
579 Define a foreign interface function for the routine with the specified Name,
580 which may be either a string, symbol or list of the form (string symbol).
581 Return-Type is the Alien type for the function return value. VOID may be
582 used to specify a function with no result.
584 The remaining forms specifiy individual arguments that are passed to the
585 routine. Arg-Name is a symbol that names the argument, primarily for
586 documentation. Arg-Type is the C-Type of the argument. Style specifies the
587 say that the argument is passed.
590 An :In argument is simply passed by value. The value to be passed is
591 obtained from argument(s) to the interface function. No values are
592 returned for :In arguments. This is the default mode.
595 The specified argument type must be a pointer to a fixed sized object.
596 A pointer to a preallocated object is passed to the routine, and the
597 the object is accessed on return, with the value being returned from
598 the interface function. :OUT and :IN-OUT cannot be used with pointers
599 to arrays, records or functions.
602 Similar to :IN, except that the argument values are stored in on
603 the stack, and a pointer to the object is passed instead of
604 the values themselves.
607 A combination of :OUT and :COPY. A pointer to the argument is passed,
608 with the object being initialized from the supplied argument and
609 the return value being determined by accessing the object on return."
610 (multiple-value-bind (lisp-name alien-name)
611 (pick-lisp-and-alien-names name)
612 (collect ((docs) (lisp-args) (arg-types) (alien-vars)
613 (alien-args) (results))
617 (destructuring-bind (name type &optional (style :in)) arg
618 (unless (member style '(:in :copy :out :in-out))
619 (error "bogus argument style ~S in ~S" style arg))
620 (unless (eq style :out)
622 (when (and (member style '(:out :in-out))
623 (typep (parse-alien-type type env)
624 'alien-pointer-type))
625 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
627 (cond ((eq style :in)
631 (arg-types `(* ,type))
633 (alien-vars `(,name ,type))
634 (alien-vars `(,name ,type ,name)))
635 (alien-args `(addr ,name))))
636 (when (or (eq style :out) (eq style :in-out))
638 `(defun ,lisp-name ,(lisp-args)
641 ((,lisp-name (function ,result-type ,@(arg-types))
644 ,(if (alien-values-type-p result-type)
645 (let ((temps (make-gensym-list
647 (alien-values-type-values result-type)))))
648 `(multiple-value-bind ,temps
649 (alien-funcall ,lisp-name ,@(alien-args))
650 (values ,@temps ,@(results))))
651 `(values (alien-funcall ,lisp-name ,@(alien-args))
654 (defun alien-typep (object type)
656 "Return T iff OBJECT is an alien of type TYPE."
657 (let ((lisp-rep-type (compute-lisp-rep-type type)))
659 (typep object lisp-rep-type)
660 (and (alien-value-p object)
661 (alien-subtype-p (alien-value-type object) type)))))