Update local CFFI to darcs from 1.6.08
[CommonLispStat.git] / external / cffi.darcs / _darcs / pristine / src / cffi-lispworks.lisp
blob9c53fafeca3c1f0bc41ae9e55d91d98d5489e061
1 ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
2 ;;;
3 ;;; cffi-lispworks.lisp --- Lispworks CFFI-SYS implementation.
4 ;;;
5 ;;; Copyright (C) 2005-2006, James Bielman <jamesjb@jamesjb.com>
6 ;;;
7 ;;; Permission is hereby granted, free of charge, to any person
8 ;;; obtaining a copy of this software and associated documentation
9 ;;; files (the "Software"), to deal in the Software without
10 ;;; restriction, including without limitation the rights to use, copy,
11 ;;; modify, merge, publish, distribute, sublicense, and/or sell copies
12 ;;; of the Software, and to permit persons to whom the Software is
13 ;;; furnished to do so, subject to the following conditions:
14 ;;;
15 ;;; The above copyright notice and this permission notice shall be
16 ;;; included in all copies or substantial portions of the Software.
17 ;;;
18 ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 ;;; DEALINGS IN THE SOFTWARE.
26 ;;;
28 ;;;# Administrivia
30 (defpackage #:cffi-sys
31 (:use #:cl #:cffi-utils #:alexandria)
32 (:export
33 #:canonicalize-symbol-name-case
34 #:foreign-pointer
35 #:pointerp
36 #:pointer-eq
37 #:null-pointer
38 #:null-pointer-p
39 #:inc-pointer
40 #:make-pointer
41 #:pointer-address
42 #:%foreign-alloc
43 #:foreign-free
44 #:with-foreign-pointer
45 #:%foreign-funcall
46 #:%foreign-funcall-pointer
47 #:%foreign-type-alignment
48 #:%foreign-type-size
49 #:%load-foreign-library
50 #:%close-foreign-library
51 #:native-namestring
52 #:%mem-ref
53 #:%mem-set
54 #:make-shareable-byte-vector
55 #:with-pointer-to-vector-data
56 #:%foreign-symbol-pointer
57 #:defcfun-helper-forms
58 #:%defcallback
59 #:%callback))
61 (in-package #:cffi-sys)
63 ;;;# Mis-features
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66 (mapc (lambda (feature) (pushnew feature *features*))
67 '(#-lispworks-64bit cffi-features:no-long-long)))
69 ;;;# Symbol Case
71 (defun canonicalize-symbol-name-case (name)
72 (declare (string name))
73 (string-upcase name))
75 ;;;# Basic Pointer Operations
77 (deftype foreign-pointer ()
78 'fli::pointer)
80 (defun pointerp (ptr)
81 "Return true if PTR is a foreign pointer."
82 (fli:pointerp ptr))
84 (defun pointer-eq (ptr1 ptr2)
85 "Return true if PTR1 and PTR2 point to the same address."
86 (fli:pointer-eq ptr1 ptr2))
88 ;; We use FLI:MAKE-POINTER here instead of FLI:*NULL-POINTER* since old
89 ;; versions of Lispworks don't seem to have it.
90 (defun null-pointer ()
91 "Return a null foreign pointer."
92 (fli:make-pointer :address 0 :type :void))
94 (defun null-pointer-p (ptr)
95 "Return true if PTR is a null pointer."
96 (fli:null-pointer-p ptr))
98 ;; FLI:INCF-POINTER won't work on FLI pointers to :void so we
99 ;; increment "manually."
100 (defun inc-pointer (ptr offset)
101 "Return a pointer OFFSET bytes past PTR."
102 (fli:make-pointer :type :void :address (+ (fli:pointer-address ptr) offset)))
104 (defun make-pointer (address)
105 "Return a pointer pointing to ADDRESS."
106 (fli:make-pointer :type :void :address address))
108 (defun pointer-address (ptr)
109 "Return the address pointed to by PTR."
110 (fli:pointer-address ptr))
112 ;;;# Allocation
114 (defun %foreign-alloc (size)
115 "Allocate SIZE bytes of memory and return a pointer."
116 (fli:allocate-foreign-object :type :byte :nelems size))
118 (defun foreign-free (ptr)
119 "Free a pointer PTR allocated by FOREIGN-ALLOC."
120 (fli:free-foreign-object ptr))
122 (defmacro with-foreign-pointer ((var size &optional size-var) &body body)
123 "Bind VAR to SIZE bytes of foreign memory during BODY. Both the
124 pointer in VAR and the memory it points to have dynamic extent and may
125 be stack allocated if supported by the implementation."
126 (unless size-var
127 (setf size-var (gensym "SIZE")))
128 `(fli:with-dynamic-foreign-objects ()
129 (let* ((,size-var ,size)
130 (,var (fli:alloca :type :byte :nelems ,size-var)))
131 ,@body)))
133 ;;;# Shareable Vectors
135 (defun make-shareable-byte-vector (size)
136 "Create a shareable byte vector."
137 (sys:in-static-area
138 (make-array size :element-type '(unsigned-byte 8))))
140 (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
141 "Bind PTR-VAR to a pointer at the data in VECTOR."
142 `(fli:with-dynamic-lisp-array-pointer (,ptr-var ,vector)
143 ,@body))
145 ;;;# Dereferencing
147 (defun convert-foreign-type (cffi-type)
148 "Convert a CFFI type keyword to an FLI type."
149 (ecase cffi-type
150 (:char :byte)
151 (:unsigned-char '(:unsigned :byte))
152 (:short :short)
153 (:unsigned-short '(:unsigned :short))
154 (:int :int)
155 (:unsigned-int '(:unsigned :int))
156 (:long :long)
157 (:unsigned-long '(:unsigned :long))
158 #+lispworks-64bit
159 (:long-long '(:long :long))
160 #+lispworks-64bit
161 (:unsigned-long-long '(:unsigned :long :long))
162 (:float :float)
163 (:double :double)
164 (:pointer :pointer)
165 (:void :void)))
167 ;;; Convert a CFFI type keyword to a symbol suitable for passing to
168 ;;; FLI:FOREIGN-TYPED-AREF.
169 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
170 (defun convert-foreign-typed-aref-type (cffi-type)
171 (ecase cffi-type
172 ((:char :short :int :long #+lispworks-64bit :long-long)
173 `(signed-byte ,(* 8 (%foreign-type-size cffi-type))))
174 ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long
175 #+lispworks-64bit :unsigned-long-long)
176 `(unsigned-byte ,(* 8 (%foreign-type-size cffi-type))))
177 (:float 'single-float)
178 (:double 'double-float)))
180 (defun %mem-ref (ptr type &optional (offset 0))
181 "Dereference an object of type TYPE OFFSET bytes from PTR."
182 (unless (zerop offset)
183 (setf ptr (inc-pointer ptr offset)))
184 (fli:dereference ptr :type (convert-foreign-type type)))
186 ;; Lispworks 5.0 on 64-bit platforms doesn't have [u]int64 support in
187 ;; FOREIGN-TYPED-AREF. That was implemented in 5.1.
188 #+(and lispworks-64bit lispworks5.0)
189 (defun 64-bit-type-p (type)
190 (member type '(:long :unsigned-long :long-long :unsigned-long-long)))
192 ;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
193 ;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-REF.
194 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
195 (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
196 (if (constantp type)
197 (let ((type (eval type)))
198 (if (or #+(and lispworks-64bit lispworks5.0) (64-bit-type-p type)
199 (eql type :pointer))
200 (let ((fli-type (convert-foreign-type type))
201 (ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
202 `(fli:dereference ,ptr-form :type ',fli-type))
203 (let ((lisp-type (convert-foreign-typed-aref-type type)))
204 `(locally
205 (declare (optimize (speed 3) (safety 0)))
206 (fli:foreign-typed-aref ',lisp-type ,ptr (the fixnum ,off))))))
207 form))
209 ;;; Open-code the call to FLI:DEREFERENCE when TYPE is constant at
210 ;;; macroexpansion time, when FLI:FOREIGN-TYPED-AREF is not available.
211 #-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
212 (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
213 (if (constantp type)
214 (let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
215 (type (convert-foreign-type (eval type))))
216 `(fli:dereference ,ptr-form :type ',type))
217 form))
219 (defun %mem-set (value ptr type &optional (offset 0))
220 "Set the object of TYPE at OFFSET bytes from PTR."
221 (unless (zerop offset)
222 (setf ptr (inc-pointer ptr offset)))
223 (setf (fli:dereference ptr :type (convert-foreign-type type)) value))
225 ;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
226 ;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-SET.
227 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
228 (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
229 (if (constantp type)
230 (once-only (val)
231 (let ((type (eval type)))
232 (if (or #+(and lispworks-64bit lispworks5.0) (64-bit-type-p type)
233 (eql type :pointer))
234 (let ((fli-type (convert-foreign-type type))
235 (ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
236 `(setf (fli:dereference ,ptr-form :type ',fli-type) ,val))
237 (let ((lisp-type (convert-foreign-typed-aref-type type)))
238 `(locally
239 (declare (optimize (speed 3) (safety 0)))
240 (setf (fli:foreign-typed-aref ',lisp-type ,ptr
241 (the fixnum ,off))
242 ,val))))))
243 form))
245 ;;; Open-code the call to (SETF FLI:DEREFERENCE) when TYPE is constant
246 ;;; at macroexpansion time.
247 #-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
248 (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
249 (if (constantp type)
250 (once-only (val)
251 (let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
252 (type (convert-foreign-type (eval type))))
253 `(setf (fli:dereference ,ptr-form :type ',type) ,val)))
254 form))
256 ;;;# Foreign Type Operations
258 (defun %foreign-type-size (type)
259 "Return the size in bytes of a foreign type."
260 (fli:size-of (convert-foreign-type type)))
262 (defun %foreign-type-alignment (type)
263 "Return the structure alignment in bytes of foreign type."
264 #+(and darwin harp::powerpc)
265 (when (eq type :double)
266 (return-from %foreign-type-alignment 8))
267 ;; Override not necessary for the remaining types...
268 (fli:align-of (convert-foreign-type type)))
270 ;;;# Calling Foreign Functions
272 (defvar *foreign-funcallable-cache* (make-hash-table :test 'equal)
273 "Caches foreign funcallables created by %FOREIGN-FUNCALL or
274 %FOREIGN-FUNCALL-POINTER. We only need to have one per each
275 signature.")
277 (defun foreign-funcall-type-and-args (args)
278 "Returns a list of types, list of args and return type."
279 (let ((return-type :void))
280 (loop for (type arg) on args by #'cddr
281 if arg collect (convert-foreign-type type) into types
282 and collect arg into fargs
283 else do (setf return-type (convert-foreign-type type))
284 finally (return (values types fargs return-type)))))
286 (defun create-foreign-funcallable (types rettype cconv)
287 "Creates a foreign funcallable for the signature TYPES -> RETTYPE."
288 (format t "~&Creating foreign funcallable for signature ~S -> ~S~%"
289 types rettype)
290 ;; yes, ugly, this most likely wants to be a top-level form...
291 (let ((internal-name (gensym)))
292 (funcall
293 (compile nil
294 `(lambda ()
295 (fli:define-foreign-funcallable ,internal-name
296 ,(loop for type in types
297 collect (list (gensym) type))
298 :result-type ,rettype
299 :language :ansi-c
300 ;; avoid warning about cdecl not being supported on mac
301 #-mac ,@(list :calling-convention cconv)))))
302 internal-name))
304 (defun get-foreign-funcallable (types rettype cconv)
305 "Returns a foreign funcallable for the signature TYPES -> RETTYPE -
306 either from the cache or newly created."
307 (let ((signature (cons rettype types)))
308 (or (gethash signature *foreign-funcallable-cache*)
309 ;; (SETF GETHASH) is supposed to be thread-safe
310 (setf (gethash signature *foreign-funcallable-cache*)
311 (create-foreign-funcallable types rettype cconv)))))
313 (defmacro %%foreign-funcall (foreign-function args cconv)
314 "Does the actual work for %FOREIGN-FUNCALL-POINTER and %FOREIGN-FUNCALL.
315 Checks if a foreign funcallable which fits ARGS already exists and creates
316 and caches it if necessary. Finally calls it."
317 (multiple-value-bind (types fargs rettype)
318 (foreign-funcall-type-and-args args)
319 `(funcall (load-time-value
320 (get-foreign-funcallable ',types ',rettype ',cconv))
321 ,foreign-function ,@fargs)))
323 (defmacro %foreign-funcall (name args &key library calling-convention)
324 "Calls a foreign function named NAME passing arguments ARGS."
325 `(%%foreign-funcall
326 (fli:make-pointer :symbol-name ,name
327 :module ',(if (eq library :default) nil library))
328 ,args ,calling-convention))
330 (defmacro %foreign-funcall-pointer (ptr args &key calling-convention)
331 "Calls a foreign function pointed at by PTR passing arguments ARGS."
332 `(%%foreign-funcall ,ptr ,args ,calling-convention))
334 (defun defcfun-helper-forms (name lisp-name rettype args types options)
335 "Return 2 values for DEFCFUN. A prelude form and a caller form."
336 (let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name))))
337 (values
338 `(fli:define-foreign-function (,ff-name ,name :source)
339 ,(mapcar (lambda (ty) (list (gensym) (convert-foreign-type ty)))
340 types)
341 :result-type ,(convert-foreign-type rettype)
342 :language :ansi-c
343 :module ',(let ((lib (getf options :library)))
344 (if (eq lib :default) nil lib))
345 ;; avoid warning about cdecl not being supported on mac platforms
346 #-mac ,@(list :calling-convention (getf options :calling-convention)))
347 `(,ff-name ,@args))))
349 ;;;# Callbacks
351 (defvar *callbacks* (make-hash-table))
353 ;;; Create a package to contain the symbols for callback functions. We
354 ;;; want to redefine callbacks with the same symbol so the internal data
355 ;;; structures are reused.
356 (defpackage #:cffi-callbacks
357 (:use))
359 ;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal
360 ;;; callback for NAME.
361 (eval-when (:compile-toplevel :load-toplevel :execute)
362 (defun intern-callback (name)
363 (intern (format nil "~A::~A" (package-name (symbol-package name))
364 (symbol-name name))
365 '#:cffi-callbacks)))
367 (defmacro %defcallback (name rettype arg-names arg-types body
368 &key calling-convention)
369 (let ((cb-name (intern-callback name)))
370 `(progn
371 (fli:define-foreign-callable
372 (,cb-name :encode :lisp
373 :result-type ,(convert-foreign-type rettype)
374 :calling-convention ,calling-convention
375 :language :ansi-c
376 :no-check nil)
377 ,(mapcar (lambda (sym type)
378 (list sym (convert-foreign-type type)))
379 arg-names arg-types)
380 ,body)
381 (setf (gethash ',name *callbacks*) ',cb-name))))
383 (defun %callback (name)
384 (multiple-value-bind (symbol winp)
385 (gethash name *callbacks*)
386 (unless winp
387 (error "Undefined callback: ~S" name))
388 (fli:make-pointer :symbol-name symbol :module :callbacks)))
390 ;;;# Loading Foreign Libraries
392 (defun %load-foreign-library (name path)
393 "Load the foreign library NAME."
394 (fli:register-module (or name path) :connection-style :immediate
395 :real-name path))
397 (defun %close-foreign-library (name)
398 "Close the foreign library NAME."
399 (fli:disconnect-module name :remove t))
401 (defun native-namestring (pathname)
402 (namestring pathname))
404 ;;;# Foreign Globals
406 (defun %foreign-symbol-pointer (name library)
407 "Returns a pointer to a foreign symbol NAME."
408 (values
409 (ignore-errors
410 (fli:make-pointer :symbol-name name :type :void
411 :module (if (eq library :default) nil library)))))