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)
39 (error "~@<~:IMalformed alien name. Acceptable formats are:~
40 ~:@_ (\"alien_name\" LISP-NAME)~
41 ~:@_ FOO-BAR - equivalent to (\"foo_bar\" FOO-BAR)~
42 ~:@_ \"foo_bar\" - equivalent to (\"foo_bar\" FOO-BAR)~:@>")))
45 (values (guess-lisp-name-from-alien-name name
)
46 (coerce name
'simple-string
)))
48 (values name
(guess-alien-name-from-lisp-name name
)))
50 (unless (and (proper-list-of-length-p name
2)
51 (symbolp (second name
))
52 (stringp (first name
)))
54 (values (second name
) (coerce (first name
) 'simple-string
)))
58 (defmacro define-alien-variable
(name type
&environment env
)
59 "Define NAME as an external alien variable of type TYPE. NAME should
60 be a list of a string holding the alien name and a symbol to use as
61 the Lisp name. If NAME is just a symbol or string, then the other name
62 is guessed from the one supplied."
63 (multiple-value-bind (lisp-name alien-name
) (pick-lisp-and-alien-names name
)
64 (with-auxiliary-alien-types env
65 (let ((alien-type (parse-alien-type type env
)))
66 `(eval-when (:compile-toplevel
:load-toplevel
:execute
)
67 ,@(when *new-auxiliary-types
*
68 `((%def-auxiliary-alien-types
',*new-auxiliary-types
*
69 (sb!c
:source-location
))))
70 (%define-alien-variable
',lisp-name
73 (sb!c
:source-location
)))))))
75 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
76 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
77 (defun %define-alien-variable
(lisp-name alien-name type location
)
78 (setf (info :variable
:kind lisp-name
) :alien
)
79 (setf (info :variable
:where-from lisp-name
) :defined
)
80 (setf (info :variable
:alien-info lisp-name
)
81 (make-heap-alien-info :type type
82 :alien-name alien-name
84 (setf (info :source-location
:variable lisp-name
) location
)
87 (defun alien-value (symbol)
88 "Returns the value of the alien variable bound to SYMBOL. Signals an
89 error if SYMBOL is not bound to an alien variable, or if the alien
90 variable is undefined."
91 (%heap-alien
(or (info :variable
:alien-info symbol
)
92 (error 'unbound-variable
:name symbol
))))
94 (defmacro extern-alien
(name type
&environment env
)
95 "Access the alien variable named NAME, assuming it is of type TYPE.
97 (let* ((alien-name (etypecase name
98 (symbol (guess-alien-name-from-lisp-name name
))
100 (alien-type (parse-alien-type type env
))
101 (datap (not (alien-fun-type-p alien-type
))))
102 `(%alien-value
(foreign-symbol-sap ,alien-name
,datap
) 0 ',alien-type
)))
104 (defmacro with-alien
(bindings &body body
&environment env
)
105 "Establish some local alien variables. Each BINDING is of the form:
106 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
107 ALLOCATION should be one of:
109 The alien is allocated on the stack, and has dynamic extent.
111 No alien is allocated, but VAR is established as a local name for
112 the external alien given by EXTERNAL-NAME."
115 ;; The alien is allocated on the heap, and has infinite extent. The alien
116 ;; is allocated at load time, so the same piece of memory is used each time
117 ;; this form executes.
118 (/show
"entering WITH-ALIEN" bindings
)
119 (let (#!+c-stack-is-control-stack
120 bind-alien-stack-pointer
)
121 (with-auxiliary-alien-types env
122 (dolist (binding (reverse bindings
))
125 (symbol type
&optional opt1
(opt2 nil opt2p
))
127 (/show symbol type opt1 opt2
)
128 (let* ((alien-type (parse-alien-type type env
))
129 (datap (not (alien-fun-type-p alien-type
))))
131 (multiple-value-bind (allocation initial-value
)
136 (values opt1
(guess-alien-name-from-lisp-name symbol
)))
140 (values :local opt1
))))
141 (/show allocation initial-value
)
147 (make-symbol (concatenate 'string
"SAP-FOR-"
148 (symbol-name symbol
)))))
149 `((let ((,sap
(load-time-value (%make-alien ...
))))
150 (declare (type system-area-pointer
,sap
))
152 ((,symbol
(sap-alien ,sap
,type
)))
153 ,@(when initial-value
154 `((setq ,symbol
,initial-value
)))
157 (/show0
":EXTERN case")
161 (foreign-symbol-sap ,initial-value
,datap
) 0 ,alien-type
)))
164 (/show0
":LOCAL case")
165 (let* ((var (sb!xc
:gensym
"VAR"))
166 (initval (if initial-value
(sb!xc
:gensym
"INITVAL")))
167 (info (make-local-alien-info :type alien-type
))
169 `((note-local-alien-type ',info
,var
)
170 (symbol-macrolet ((,symbol
(local-alien ',info
,var
)))
171 ,@(when initial-value
172 `((setq ,symbol
,initval
)))
176 `((let ((,initval
,initial-value
))
179 (/show var initval info
)
180 #!+c-stack-is-control-stack
181 (progn (setf bind-alien-stack-pointer t
)
182 `((let ((,var
(make-local-alien ',info
)))
184 ;; FIXME: This version is less efficient then it needs to be, since
185 ;; it could just save and restore the number-stack pointer once,
186 ;; instead of doing multiple decrements if there are multiple bindings.
187 #!-c-stack-is-control-stack
188 `((let ((,var
(make-local-alien ',info
)))
189 (multiple-value-prog1
191 ;; No need for unwind protect here, since
192 ;; allocation involves modifying NSP, and
193 ;; NSP is saved and restored during NLX.
194 ;; And in non-transformed case it
195 ;; performs finalization.
196 (dispose-local-alien ',info
,var
))))))))))))
197 (/show
"revised" body
)
198 (verify-local-auxiliaries-okay)
199 (/show0
"back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
200 `(symbol-macrolet ((&auxiliary-type-definitions
&
201 ,(append *new-auxiliary-types
*
202 (auxiliary-type-definitions env
))))
204 #!+c-stack-is-control-stack
205 (bind-alien-stack-pointer
206 `((let ((sb!vm
::*alien-stack-pointer
* sb
!vm
::*alien-stack-pointer
*))
211 ;;;; runtime C values that don't correspond directly to Lisp types
213 (defmethod print-object ((value alien-value
) stream
)
214 ;; Don't use ":TYPE T" here - TYPE-OF isn't what we want.
215 (print-unreadable-object (value stream
)
216 (format stream
"~S ~S #X~8,'0X ~S ~/sb!impl:print-type-specifier/"
218 :sap
(sap-int (alien-value-sap value
))
219 :type
(unparse-alien-type (alien-value-type value
)))))
221 #!-sb-fluid
(declaim (inline null-alien
))
222 (defun null-alien (x)
223 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
224 (zerop (sap-int (alien-sap x
))))
226 (defmacro sap-alien
(sap type
&environment env
)
227 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
228 evaluated.) TYPE must be pointer-like."
229 (let ((alien-type (parse-alien-type type env
)))
230 (if (eq (compute-alien-rep-type alien-type
) 'system-area-pointer
)
231 `(%sap-alien
,sap
',alien-type
)
232 (error "cannot make an alien of type ~S out of a SAP" type
))))
234 (defun alien-sap (alien)
235 "Return a System-Area-Pointer pointing to Alien's data."
236 (declare (type alien-value alien
))
237 (alien-value-sap alien
))
239 ;;;; allocation/deallocation of heap aliens
241 (defmacro make-alien
(type &optional size
&environment env
)
242 "Allocate an alien of type TYPE in foreign heap, and return an alien
243 pointer to it. The allocated memory is not initialized, and may
244 contain garbage. The memory is allocated using malloc(3), so it can be
245 passed to foreign functions which use free(3), or released using
248 For alien stack allocation, see macro WITH-ALIEN.
250 The TYPE argument is not evaluated. If SIZE is supplied, how it is
251 interpreted depends on TYPE:
253 * When TYPE is a foreign array type, an array of that type is
254 allocated, and a pointer to it is returned. Note that you
255 must use DEREF to first access the array through the pointer.
257 If supplied, SIZE is used as the first dimension for the array.
259 * When TYPE is any other foreign type, then an object for that
260 type is allocated, and a pointer to it is returned. So
261 (make-alien int) returns a (* int).
263 If SIZE is specified, then a block of that many objects is
264 allocated, with the result pointing to the first one.
268 (defvar *foo* (make-alien (array char 10)))
269 (type-of *foo*) ; => (alien (* (array (signed 8) 10)))
270 (setf (deref (deref foo) 0) 10) ; => 10
272 (make-alien char 12) ; => (alien (* (signed 8)))"
273 (let ((alien-type (if (alien-type-p type
)
275 (parse-alien-type type env
))))
276 (multiple-value-bind (size-expr element-type
)
277 (if (alien-array-type-p alien-type
)
278 (let ((dims (alien-array-type-dimensions alien-type
)))
283 "cannot override the size of zero-dimensional arrays"))
284 (when (constantp size
)
285 (setf alien-type
(copy-alien-array-type alien-type
))
286 (setf (alien-array-type-dimensions alien-type
)
287 (cons (constant-form-value size
) (cdr dims
)))))
289 (setf size
(car dims
)))
292 (values `(* ,size
,@(cdr dims
))
293 (alien-array-type-element-type alien-type
)))
294 (values (or size
1) alien-type
))
295 (let ((bits (alien-type-bits element-type
))
296 (alignment (alien-type-alignment element-type
)))
298 (error "The size of ~S is unknown."
299 (unparse-alien-type element-type
)))
301 (error "The alignment of ~S is unknown."
302 (unparse-alien-type element-type
)))
303 ;; This is the one place where the %SAP-ALIEN note is quite
304 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
305 ;; cannot be optimized away.
306 `(locally (declare (muffle-conditions compiler-note
))
307 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
308 (%sap-alien
(%make-alien
(* ,(ash (+ 7 (align-offset bits alignment
)) -
3)
309 (the index
,size-expr
)))
310 ',(make-alien-pointer-type :to alien-type
)))))))
312 (defun malloc-error (bytes errno
)
313 (error 'simple-storage-condition
314 :format-control
"~A: malloc() of ~S bytes failed."
315 :format-arguments
(list (strerror errno
) bytes
)))
317 ;;; Allocate a block of memory at least BYTES bytes long and return a
318 ;;; system area pointer to it.
319 #!-sb-fluid
(declaim (inline %make-alien
))
320 (defun %make-alien
(bytes)
321 (declare (type index bytes
)
322 (optimize (sb!c
:alien-funcall-saves-fp-and-pc
0)))
323 (let ((sap (alien-funcall (extern-alien "malloc"
324 (function system-area-pointer size-t
))
326 (if (and (not (eql 0 bytes
)) (eql 0 (sap-int sap
)))
327 (malloc-error bytes
(get-errno))
330 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
331 (defvar *saved-fp-and-pcs
* nil
)
332 ;; Can't use DECLAIM since always-bound is a non-standard declaration
333 (sb!xc
:proclaim
'(sb!ext
:always-bound
*saved-fp-and-pcs
*)))
335 #!+c-stack-is-control-stack
336 (declaim (inline invoke-with-saved-fp-and-pc
))
337 ;;; On :c-stack-is-control-stack platforms, this DEFUN must appear prior to the
338 ;;; first cross-compile-time use of ALIEN-FUNCALL, the transform of which is
339 ;;; an invocation of INVOKE-WITH-SAVED-FP-AND-PC, which should be inlined.
340 ;;; Makes no sense when compiling for the host.
341 #!+(and c-stack-is-control-stack
(host-feature sb-xc
))
342 (defun invoke-with-saved-fp-and-pc (fn)
343 (declare #-sb-xc-host
(muffle-conditions compiler-note
)
344 (optimize (speed 3)))
345 (dx-let ((fp-and-pc (make-array 2 :element-type
'word
)))
346 (setf (aref fp-and-pc
0) (sb!kernel
:get-lisp-obj-address
347 (sb!kernel
:%caller-frame
))
348 (aref fp-and-pc
1) (sap-int (sb!kernel
:%caller-pc
)))
349 (dx-let ((*saved-fp-and-pcs
* (cons fp-and-pc
*saved-fp-and-pcs
*)))
352 #!-sb-fluid
(declaim (inline free-alien
))
353 (defun free-alien (alien)
354 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
355 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
356 (alien-funcall (extern-alien "free" (function (values) system-area-pointer
))
360 (declaim (type (function * (values system-area-pointer index
))
362 (defun %make-alien-string
(string &key
(start 0) end
363 (external-format :default
)
365 ;; FIXME: This is slow. We want a function to get the length of the
366 ;; encoded string so we can allocate the foreign memory first and
367 ;; encode directly there.
368 (let* ((octets (string-to-octets string
369 :start start
:end end
370 :external-format external-format
371 :null-terminate null-terminate
))
372 (count (length octets
))
373 (buf (%make-alien count
)))
374 (sb!kernel
:copy-ub8-to-system-area octets
0 buf
0 count
)
377 (defun make-alien-string (string &rest rest
379 (external-format :default
)
381 "Copy part of STRING delimited by START and END into freshly
382 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
383 Returns the allocated string as a (* CHAR) alien, and the number of
384 bytes allocated as secondary value.
386 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
387 true (the default), the alien string is terminated by an additional
389 (declare (ignore start end external-format null-terminate
))
390 (multiple-value-bind (sap bytes
)
391 (apply #'%make-alien-string string rest
)
392 (values (%sap-alien sap
(parse-alien-type '(* char
) nil
))
395 (define-compiler-macro make-alien-string
(&rest args
)
396 `(multiple-value-bind (sap bytes
) (%make-alien-string
,@args
)
397 (values (%sap-alien sap
',(parse-alien-type '(* char
) nil
))
400 ;;;; the SLOT operator
402 ;;; Find the field named SLOT, or die trying.
403 (defun slot-or-lose (type slot
)
404 (declare (type alien-record-type type
)
406 (or (find slot
(alien-record-type-fields type
)
407 :key
#'alien-record-field-name
)
408 (error "There is no slot named ~S in ~S." slot type
)))
410 ;;; Extract the value from the named slot from the record ALIEN. If
411 ;;; ALIEN is actually a pointer, then DEREF it first.
412 (defun slot (alien slot
)
413 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
414 (declare (type alien-value alien
)
416 (optimize (inhibit-warnings 3)))
417 (let ((type (alien-value-type alien
)))
420 (slot (deref alien
) slot
))
422 (let ((field (slot-or-lose type slot
)))
423 (%alien-value
(alien-value-sap alien
)
424 (alien-record-field-offset field
)
425 (alien-record-field-type field
)))))))
427 ;;; Deposit the value in the specified slot of the record ALIEN. If
428 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
429 ;;; this when it can't figure out anything better.
430 (defun %set-slot
(alien slot value
)
431 (declare (type alien-value alien
)
433 (optimize (inhibit-warnings 3)))
434 (let ((type (alien-value-type alien
)))
437 (%set-slot
(deref alien
) slot value
))
439 (let ((field (slot-or-lose type slot
)))
440 (setf (%alien-value
(alien-value-sap alien
)
441 (alien-record-field-offset field
)
442 (alien-record-field-type field
))
445 ;;; Compute the address of the specified slot and return a pointer to it.
446 (defun %slot-addr
(alien slot
)
447 (declare (type alien-value alien
)
449 (optimize (inhibit-warnings 3)))
450 (let ((type (alien-value-type alien
)))
453 (%slot-addr
(deref alien
) slot
))
455 (let* ((field (slot-or-lose type slot
))
456 (offset (alien-record-field-offset field
))
457 (field-type (alien-record-field-type field
)))
458 (%sap-alien
(sap+ (alien-sap alien
) (/ offset sb
!vm
:n-byte-bits
))
459 (make-alien-pointer-type :to field-type
)))))))
461 ;;;; the DEREF operator
463 ;;; This function does most of the work of the different DEREF
464 ;;; methods. It returns two values: the type and the offset (in bits)
465 ;;; of the referred-to alien.
466 (defun deref-guts (alien indices
)
467 (declare (type alien-value alien
)
469 (values alien-type integer
))
470 (let ((type (alien-value-type alien
)))
474 (error "too many indices when DEREF'ing ~S: ~W"
477 (let ((element-type (alien-pointer-type-to type
)))
480 (* (align-offset (alien-type-bits element-type
)
481 (alien-type-alignment element-type
))
485 (unless (= (length indices
) (length (alien-array-type-dimensions type
)))
486 (error "incorrect number of indices when DEREF'ing ~S: ~W"
487 type
(length indices
)))
488 (labels ((frob (dims indices offset
)
491 (frob (cdr dims
) (cdr indices
)
492 (+ (if (zerop offset
)
494 (* offset
(car dims
)))
496 (let ((element-type (alien-array-type-element-type type
)))
498 (* (align-offset (alien-type-bits element-type
)
499 (alien-type-alignment element-type
))
500 (frob (alien-array-type-dimensions type
)
503 ;;; Dereference the alien and return the results.
504 (defun deref (alien &rest indices
)
505 "Dereference an Alien pointer or array. If an array, the indices are used
506 as the indices of the array element to access. If a pointer, one index can
507 optionally be specified, giving the equivalent of C pointer arithmetic."
508 (declare (type alien-value alien
)
510 (optimize (inhibit-warnings 3)))
511 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
512 (%alien-value
(alien-value-sap alien
)
516 (defun %set-deref
(alien value
&rest indices
)
517 (declare (type alien-value alien
)
519 (optimize (inhibit-warnings 3)))
520 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
521 (setf (%alien-value
(alien-value-sap alien
)
526 (defun %deref-addr
(alien &rest indices
)
527 (declare (type alien-value alien
)
529 (optimize (inhibit-warnings 3)))
530 (multiple-value-bind (target-type offset
) (deref-guts alien indices
)
531 (%sap-alien
(sap+ (alien-value-sap alien
) (/ offset sb
!vm
:n-byte-bits
))
532 (make-alien-pointer-type :to target-type
))))
534 ;;;; accessing heap alien variables
536 (defun %heap-alien
(info)
537 (declare (type heap-alien-info info
)
538 (optimize (inhibit-warnings 3)))
539 (%alien-value
(heap-alien-info-sap info
)
541 (heap-alien-info-type info
)))
543 (defun %set-heap-alien
(info value
)
544 (declare (type heap-alien-info info
)
545 (optimize (inhibit-warnings 3)))
546 (setf (%alien-value
(heap-alien-info-sap info
)
548 (heap-alien-info-type info
))
551 (defun %heap-alien-addr
(info)
552 (declare (type heap-alien-info info
)
553 (optimize (inhibit-warnings 3)))
554 (%sap-alien
(heap-alien-info-sap info
)
555 (make-alien-pointer-type :to
(heap-alien-info-type info
))))
557 ;;;; accessing local aliens
559 (defun make-local-alien (info)
560 (let* ((alien (eval `(make-alien ,(local-alien-info-type info
))))
561 (alien-sap (alien-sap alien
)))
566 (extern-alien "free" (function (values) system-area-pointer
))
571 (defun note-local-alien-type (info alien
)
572 (declare (ignore info alien
))
575 (defun local-alien (info alien
)
576 (declare (ignore info
))
579 (defun %set-local-alien
(info alien value
)
580 (declare (ignore info
))
581 (setf (deref alien
) value
))
583 (define-setf-expander local-alien
(&whole whole info alien
)
584 (let ((value (gensym))
587 (info (if (and (consp info
)
588 (eq (car info
) 'quote
))
590 (error "Something is wrong; local-alien-info not found: ~S"
595 `(if (%local-alien-forced-to-memory-p
',info
)
596 (%set-local-alien
',info
,alien
,value
)
597 (let* ((,info-var
',(local-alien-info-type info
))
598 (,alloc-tmp
(deport-alloc ,value
,info-var
)))
599 (maybe-with-pinned-objects (,alloc-tmp
) (,(local-alien-info-type info
))
600 (setf ,alien
(deport ,alloc-tmp
,info-var
)))))
603 (defun %local-alien-forced-to-memory-p
(info)
604 (local-alien-info-force-to-memory-p info
))
606 (defun %local-alien-addr
(info alien
)
607 (declare (type local-alien-info info
))
608 (unless (local-alien-info-force-to-memory-p info
)
609 (error "~S isn't forced to memory. Something went wrong." alien
))
612 ;; It's not mandatory that this function not exist for x86[-64],
613 ;; however for sanity, it should not, because no call to it can occur.
615 (defun dispose-local-alien (info alien
)
616 (declare (ignore info
))
617 (cancel-finalization alien
)
622 (defmacro cast
(alien type
&environment env
)
623 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
624 must be Alien array, pointer or function types."
625 `(%cast
,alien
',(parse-alien-type type env
)))
627 (defun %cast
(alien target-type
)
628 (declare (type alien-value alien
)
629 (type alien-type target-type
)
630 (optimize (safety 2))
631 (optimize (inhibit-warnings 3)))
632 (if (or (alien-pointer-type-p target-type
)
633 (alien-array-type-p target-type
)
634 (alien-fun-type-p target-type
))
635 (let ((alien-type (alien-value-type alien
)))
636 (if (or (alien-pointer-type-p alien-type
)
637 (alien-array-type-p alien-type
)
638 (alien-fun-type-p alien-type
))
639 (naturalize (alien-value-sap alien
) target-type
)
640 (error "~S cannot be casted." alien
)))
641 (error "cannot cast to alien type ~S" (unparse-alien-type target-type
))))
643 ;;;; the ALIEN-SIZE macro
645 (defmacro alien-size
(type &optional
(units :bits
) &environment env
)
646 "Return the size of the alien type TYPE. UNITS specifies the units to
647 use and can be either :BITS, :BYTES, or :WORDS."
648 (let* ((alien-type (parse-alien-type type env
))
649 (bits (alien-type-bits alien-type
)))
651 (values (ceiling bits
654 (:bytes sb
!vm
:n-byte-bits
)
655 (:words sb
!vm
:n-word-bits
))))
656 (error "unknown size for alien type ~S"
657 (unparse-alien-type alien-type
)))))
659 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
661 (defun coerce-to-interpreted-function (lambda-form)
663 (*evaluator-mode
* :interpret
))
664 (coerce lambda-form
'function
)))
666 (defun naturalize (alien type
)
667 (declare (type alien-type type
))
668 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type
))
671 (defun deport (value type
)
672 (declare (type alien-type type
))
673 (funcall (coerce-to-interpreted-function (compute-deport-lambda type
))
676 (defun deport-alloc (value type
)
677 (declare (type alien-type type
))
678 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type
))
681 (defun %alien-value
(sap offset type
)
682 (declare (type system-area-pointer sap
)
683 (type unsigned-byte offset
)
684 (type alien-type type
))
685 (funcall (coerce-to-interpreted-function (compute-extract-lambda type
))
688 (defun (setf %alien-value
) (value sap offset type
)
689 (declare (type system-area-pointer sap
)
690 (type unsigned-byte offset
)
691 (type alien-type type
))
692 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type
))
693 value sap offset type
))
695 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
697 (defun alien-funcall (alien &rest args
)
698 "Call the foreign function ALIEN with the specified arguments. ALIEN's
699 type specifies the argument and result types."
700 (declare (type alien-value alien
))
701 (let ((type (alien-value-type alien
)))
704 (apply #'alien-funcall
(deref alien
) args
))
706 (unless (= (length (alien-fun-type-arg-types type
))
708 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
710 (length (alien-fun-type-arg-types type
))
712 (let ((stub (alien-fun-type-stub type
)))
715 (let ((fun (sb!xc
:gensym
"FUN"))
716 (parms (make-gensym-list (length args
))))
718 `(lambda (,fun
,@parms
)
719 (declare (optimize (sb!c
::insert-step-conditions
0)))
720 (declare (type (alien ,type
) ,fun
))
721 (alien-funcall ,fun
,@parms
)))))
722 (setf (alien-fun-type-stub type
) stub
))
723 (apply stub alien args
)))
725 (error "~S is not an alien function." alien
)))))
727 (defmacro define-alien-routine
(name result-type
730 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
732 Define a foreign interface function for the routine with the specified NAME.
733 Also automatically DECLAIM the FTYPE of the defined function.
735 NAME may be either a string, a symbol, or a list of the form (string symbol).
737 RETURN-TYPE is the alien type for the function return value. VOID may be
738 used to specify a function with no result.
740 The remaining forms specify individual arguments that are passed to the
741 routine. ARG-NAME is a symbol that names the argument, primarily for
742 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
743 way that the argument is passed.
746 An :IN argument is simply passed by value. The value to be passed is
747 obtained from argument(s) to the interface function. No values are
748 returned for :In arguments. This is the default mode.
751 The specified argument type must be a pointer to a fixed sized object.
752 A pointer to a preallocated object is passed to the routine, and the
753 the object is accessed on return, with the value being returned from
754 the interface function. :OUT and :IN-OUT cannot be used with pointers
755 to arrays, records or functions.
758 This is similar to :IN, except that the argument values are stored
759 on the stack, and a pointer to the object is passed instead of
763 This is a combination of :OUT and :COPY. A pointer to the argument is
764 passed, with the object being initialized from the supplied argument
765 and the return value being determined by accessing the object on
767 (multiple-value-bind (lisp-name alien-name
)
768 (pick-lisp-and-alien-names name
)
769 (collect ((docs) (lisp-args) (lisp-arg-types)
771 (cond ((eql result-type
'void
)
772 ;; What values does a function return, if it
773 ;; returns no values? Exactly one - NIL. -- APD,
777 ;; FIXME: Check for VALUES.
778 (list `(alien ,result-type
)))))
779 (arg-types) (alien-vars)
780 (alien-args) (results))
784 (destructuring-bind (name type
&optional
(style :in
)) arg
785 (unless (member style
'(:in
:copy
:out
:in-out
))
786 (error "bogus argument style ~S in ~S" style arg
))
787 (when (and (member style
'(:out
:in-out
))
788 (typep (parse-alien-type type lexenv
)
789 'alien-pointer-type
))
790 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
793 (cond ((eq style
:in
)
797 (setq arg-type
`(* ,type
))
799 (alien-vars `(,name
,type
))
800 (alien-vars `(,name
,type
,name
)))
801 (alien-args `(addr ,name
))))
803 (unless (eq style
:out
)
806 ;; FIXME: It should be something
807 ;; like `(ALIEN ,ARG-TYPE), except
808 ;; for we also accept SAPs where
809 ;; pointers are required.
811 (when (or (eq style
:out
) (eq style
:in-out
))
813 (lisp-result-types `(alien ,type
))))))
815 ;; The theory behind this automatic DECLAIM is that (1) if
816 ;; you're calling C, static typing is what you're doing
817 ;; anyway, and (2) such a declamation can be (especially for
818 ;; alien values) both messy to do by hand and very important
819 ;; for performance of later code which uses the return value.
820 (declaim (ftype (function ,(lisp-arg-types)
821 (values ,@(lisp-result-types) &optional
))
823 (defun ,lisp-name
,(lisp-args)
826 ((,lisp-name
(function ,result-type
,@(arg-types))
829 ,@(if (eq 'void result-type
)
830 `((alien-funcall ,lisp-name
,@(alien-args))
831 (values nil
,@(results)))
832 `((values (alien-funcall ,lisp-name
,@(alien-args))
835 (defun alien-typep (object type
)
836 "Return T iff OBJECT is an alien of type TYPE."
837 (let ((lisp-rep-type (compute-lisp-rep-type type
)))
839 (typep object lisp-rep-type
)
840 (and (alien-value-p object
)
841 (alien-subtype-p (alien-value-type object
) type
)))))
843 (defun alien-value-typep (object type
)
844 (when (alien-value-p object
)
845 (alien-subtype-p (alien-value-type object
) type
)))
849 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
851 (defvar *alien-callback-info
* nil
852 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
853 information we need to manipulate callbacks after their creation. Used for
854 changing the lisp-side function they point to, invalidation, etc.")
856 (defstruct callback-info
858 function
; NULL if invalid
862 (defun callback-info-key (info)
863 (cons (callback-info-specifier info
) (callback-info-function info
)))
865 (defun alien-callback-info (alien)
866 (cdr (assoc (alien-sap alien
) *alien-callback-info
* :test
#'sap
=)))
868 (defvar *alien-callbacks
* (make-hash-table :test
#'equal
)
869 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
870 memoization: we don't create new callbacks if one pointing to the correct
871 function with the same specifier already exists.")
873 (defvar *alien-callback-wrappers
* (make-hash-table :test
#'equal
)
874 "Cache of existing lisp wrappers, indexed with SPECIFER. Used for memoization:
875 we don't create new wrappers if one for the same specifier already exists.")
877 (defvar *alien-callback-trampolines
* (make-array 32 :fill-pointer
0 :adjustable t
)
878 "Lisp trampoline store: assembler wrappers contain indexes to this, and
879 ENTER-ALIEN-CALLBACK pulls the corresponding trampoline out and calls it.")
881 (defun %alien-callback-sap
(specifier result-type argument-types function wrapper
883 (declare #!-x86
(ignore call-type
))
884 (let ((key (list specifier function
)))
885 (or (gethash key
*alien-callbacks
*)
886 (setf (gethash key
*alien-callbacks
*)
887 (let* ((index (fill-pointer *alien-callback-trampolines
*))
888 ;; Aside from the INDEX this is known at
889 ;; compile-time, which could be utilized by
890 ;; having the two-stage assembler tramp &
891 ;; wrapper mentioned in [1] above: only the
892 ;; per-function tramp would need assembler at
893 ;; runtime. Possibly we could even pregenerate
894 ;; the code and just patch the index in later.
896 (alien-callback-assembler-wrapper
897 index result-type argument-types
899 (if (eq call-type
:stdcall
)
902 (mapcar 'alien-type-word-aligned-bits
907 (alien-callback-lisp-trampoline wrapper function
)
908 *alien-callback-trampolines
*)
909 ;; Assembler-wrapper is static, so sap-taking is safe.
910 (let ((sap (vector-sap assembler-wrapper
)))
911 (push (cons sap
(make-callback-info :specifier specifier
915 *alien-callback-info
*)
918 (defun alien-callback-lisp-trampoline (wrapper function
)
919 (declare (function wrapper
) (optimize speed
))
920 (lambda (args-pointer result-pointer
)
921 (funcall wrapper args-pointer result-pointer function
)))
923 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env
)
924 (let* ((arguments (make-gensym-list (length argument-types
)))
925 (argument-names arguments
)
926 (argument-specs (cddr specifier
)))
927 `(lambda (args-pointer result-pointer function
)
928 ;; FIXME: the saps are not gc safe
929 (let ((args-sap (int-sap
930 (sb!kernel
:get-lisp-obj-address args-pointer
)))
932 (sb!kernel
:get-lisp-obj-address result-pointer
))))
933 (declare (ignorable args-sap res-sap
))
937 for spec in argument-specs
938 ;; KLUDGE: At least one platform requires additional
939 ;; alignment beyond a single machine word for certain
940 ;; arguments. Accept an additional delta (for the
941 ;; alignment) to apply to subsequent arguments to
942 ;; account for the alignment gaps as a secondary
943 ;; value, so that we don't have to update unaffected
945 for
(accessor-form alignment
)
946 = (multiple-value-list
947 (alien-callback-accessor-form spec
'args-sap offset
))
948 collect
`(,(pop argument-names
) ,spec
949 :local
,accessor-form
)
950 do
(incf offset
(+ (alien-callback-argument-bytes spec env
)
952 ,(flet ((store (spec real-type
)
954 `(setf (deref (sap-alien res-sap
(* ,spec
)))
957 (funcall function
,@arguments
))
958 `(funcall function
,@arguments
)))
959 `(funcall function
,@arguments
))))
960 (cond ((alien-void-type-p result-type
)
962 ((alien-integer-type-p result-type
)
963 ;; Integer types should be padded out to a full
964 ;; register width, to comply with most ABI calling
965 ;; conventions, but should be typechecked on the
966 ;; declared type width, hence the following:
967 (if (alien-integer-type-signed result-type
)
969 ,(alien-type-word-aligned-bits result-type
))
970 `(signed-byte ,(alien-type-bits result-type
)))
973 ,(alien-type-word-aligned-bits result-type
))
974 `(unsigned-byte ,(alien-type-bits result-type
)))))
976 (store (unparse-alien-type result-type
) nil
))))))
979 (defun invalid-alien-callback (&rest arguments
)
980 (declare (ignore arguments
))
981 (error "Invalid alien callback called."))
983 (defun parse-callback-specification (result-type lambda-list
)
985 `(function ,result-type
,@(mapcar #'second lambda-list
))
986 (mapcar #'first lambda-list
)))
988 (defun parse-alien-ftype (specifier env
)
989 (destructuring-bind (function result-type
&rest argument-types
)
991 (aver (eq 'function function
))
992 (multiple-value-bind (bare-result-type calling-convention
)
993 (typecase result-type
994 ((cons calling-convention
*)
995 (values (second result-type
) (first result-type
)))
997 (values (let ((*values-type-okay
* t
))
998 (parse-alien-type bare-result-type env
))
999 (mapcar (lambda (spec)
1000 (parse-alien-type spec env
))
1002 calling-convention
))))
1004 (defun alien-void-type-p (type)
1005 (and (alien-values-type-p type
) (not (alien-values-type-values type
))))
1007 (defun alien-type-word-aligned-bits (type)
1008 (align-offset (alien-type-bits type
) sb
!vm
:n-word-bits
))
1010 (defun alien-callback-argument-bytes (spec env
)
1011 (let ((type (parse-alien-type spec env
)))
1012 (if (or (alien-integer-type-p type
)
1013 (alien-float-type-p type
)
1014 (alien-pointer-type-p type
)
1015 (alien-system-area-pointer-type-p type
))
1016 (ceiling (alien-type-word-aligned-bits type
) sb
!vm
:n-byte-bits
)
1017 (error "Unsupported callback argument type: ~A" type
))))
1019 (defun enter-alien-callback (index return arguments
)
1020 (funcall (aref *alien-callback-trampolines
* index
)
1024 ;;; To ensure that callback wrapper functions continue working even
1025 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
1026 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
1027 (defvar *enter-alien-callback
* #'enter-alien-callback
)
1029 ;;;; interface (not public, yet) for alien callbacks
1032 (defmacro alien-callback
(specifier function
&environment env
)
1033 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
1034 an alien function as a pointer to the FUNCTION. If a callback for the given
1035 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
1037 ;; Pull out as much work as is convenient to macro-expansion time, specifically
1038 ;; everything that can be done given just the SPECIFIER and ENV.
1039 (multiple-value-bind (result-type argument-types call-type
)
1040 (parse-alien-ftype specifier env
)
1042 (%alien-callback-sap
',specifier
',result-type
',argument-types
1044 (or (gethash ',specifier
*alien-callback-wrappers
*)
1045 (setf (gethash ',specifier
*alien-callback-wrappers
*)
1047 ',(alien-callback-lisp-wrapper-lambda
1048 specifier result-type argument-types env
))))
1050 ',(parse-alien-type specifier env
)))))
1052 (defun alien-callback-p (alien)
1053 "Returns true if the alien is associated with a lisp-side callback,
1054 and a secondary return value of true if the callback is still valid."
1055 (let ((info (alien-callback-info alien
)))
1057 (values t
(and (callback-info-function info
) t
)))))
1059 (defun alien-callback-function (alien)
1060 "Returns the lisp function designator associated with the callback."
1061 (let ((info (alien-callback-info alien
)))
1063 (callback-info-function info
))))
1065 (defun (setf alien-callback-function
) (function alien
)
1066 "Changes the lisp function designated by the callback."
1067 (let ((info (alien-callback-info alien
)))
1069 (error "Not an alien callback: ~S" alien
))
1071 (let ((key (callback-info-key info
)))
1072 (remhash key
*alien-callbacks
*)
1073 (setf (gethash key
*alien-callbacks
*) (alien-sap alien
)))
1075 (setf (aref *alien-callback-trampolines
* (callback-info-index info
))
1076 (alien-callback-lisp-trampoline (callback-info-wrapper info
) function
))
1078 (setf (callback-info-function info
) function
)
1081 (defun invalidate-alien-callback (alien)
1082 "Invalidates the callback designated by the alien, if any, allowing the
1083 associated lisp function to be GC'd, and causing further calls to the same
1084 callback signal an error."
1085 (let ((info (alien-callback-info alien
)))
1086 (when (and info
(callback-info-function info
))
1088 (remhash (callback-info-key info
) *alien-callbacks
*)
1090 (setf (aref *alien-callback-trampolines
* (callback-info-index info
))
1091 #'invalid-alien-callback
)
1093 (setf (callback-info-function info
) nil
)
1096 ;;; FIXME: This call assembles a new callback for every closure,
1097 ;;; which sucks hugely. ...not that I can think of an obvious
1098 ;;; solution. Possibly maybe we could write a generalized closure
1099 ;;; callback analogous to closure_tramp, and share the actual wrapper?
1101 ;;; For lambdas that result in simple-funs we get the callback from
1102 ;;; the cache on subsequent calls.
1104 (defmacro alien-lambda
(result-type typed-lambda-list
&body forms
)
1105 (multiple-value-bind (specifier lambda-list
)
1106 (parse-callback-specification result-type typed-lambda-list
)
1107 `(alien-callback ,specifier
(lambda ,lambda-list
,@forms
))))
1109 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
1110 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
1111 ;;; the FDEFINITION should invalidate the callback, and redefining the
1112 ;;; callback should change existing callbacks to point to the new defintion.
1113 (defmacro define-alien-callback
(name result-type typed-lambda-list
&body forms
)
1114 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
1115 the alien callback for that function with the given alien type."
1116 (declare (symbol name
))
1117 (multiple-value-bind (specifier lambda-list
)
1118 (parse-callback-specification result-type typed-lambda-list
)
1120 (defun ,name
,lambda-list
,@forms
)
1121 (defparameter ,name
(alien-callback ,specifier
#',name
)))))