adding CFFI just in case. Need to make into a submodule at somepoint.
[CommonLispStat.git] / external / cffi.darcs / src / cffi-lispworks.lisp
blob0b0102c43500fe2c1831652abcd5ea3e552cd13b
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)
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 ;;;# Features
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66 (mapc (lambda (feature) (pushnew feature *features*))
67 '(;; Backend mis-features.
68 cffi-features:no-long-long
69 ;; OS/CPU features.
70 #+darwin cffi-features:darwin
71 #+unix cffi-features:unix
72 #+win32 cffi-features:windows
73 #+harp::pc386 cffi-features:x86
74 #+harp::powerpc cffi-features:ppc32
75 )))
77 ;;; Symbol case.
79 (defun canonicalize-symbol-name-case (name)
80 (declare (string name))
81 (string-upcase name))
83 ;;;# Basic Pointer Operations
85 (deftype foreign-pointer ()
86 'fli::pointer)
88 (defun pointerp (ptr)
89 "Return true if PTR is a foreign pointer."
90 (fli:pointerp ptr))
92 (defun pointer-eq (ptr1 ptr2)
93 "Return true if PTR1 and PTR2 point to the same address."
94 (fli:pointer-eq ptr1 ptr2))
96 ;; We use FLI:MAKE-POINTER here instead of FLI:*NULL-POINTER* since old
97 ;; versions of Lispworks don't seem to have it.
98 (defun null-pointer ()
99 "Return a null foreign pointer."
100 (fli:make-pointer :address 0 :type :void))
102 (defun null-pointer-p (ptr)
103 "Return true if PTR is a null pointer."
104 (fli:null-pointer-p ptr))
106 ;; FLI:INCF-POINTER won't work on FLI pointers to :void so we
107 ;; increment "manually."
108 (defun inc-pointer (ptr offset)
109 "Return a pointer OFFSET bytes past PTR."
110 (fli:make-pointer :type :void :address (+ (fli:pointer-address ptr) offset)))
112 (defun make-pointer (address)
113 "Return a pointer pointing to ADDRESS."
114 (fli:make-pointer :type :void :address address))
116 (defun pointer-address (ptr)
117 "Return the address pointed to by PTR."
118 (fli:pointer-address ptr))
120 ;;;# Allocation
122 (defun %foreign-alloc (size)
123 "Allocate SIZE bytes of memory and return a pointer."
124 (fli:allocate-foreign-object :type :byte :nelems size))
126 (defun foreign-free (ptr)
127 "Free a pointer PTR allocated by FOREIGN-ALLOC."
128 (fli:free-foreign-object ptr))
130 (defmacro with-foreign-pointer ((var size &optional size-var) &body body)
131 "Bind VAR to SIZE bytes of foreign memory during BODY. Both the
132 pointer in VAR and the memory it points to have dynamic extent and may
133 be stack allocated if supported by the implementation."
134 (unless size-var
135 (setf size-var (gensym "SIZE")))
136 `(fli:with-dynamic-foreign-objects ()
137 (let* ((,size-var ,size)
138 (,var (fli:alloca :type :byte :nelems ,size-var)))
139 ,@body)))
141 ;;;# Shareable Vectors
143 (defun make-shareable-byte-vector (size)
144 "Create a shareable byte vector."
145 (sys:in-static-area
146 (make-array size :element-type '(unsigned-byte 8))))
148 (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
149 "Bind PTR-VAR to a pointer at the data in VECTOR."
150 `(fli:with-dynamic-lisp-array-pointer (,ptr-var ,vector)
151 ,@body))
153 ;;;# Dereferencing
155 (defun convert-foreign-type (cffi-type)
156 "Convert a CFFI type keyword to an FLI type."
157 (ecase cffi-type
158 (:char :byte)
159 (:unsigned-char '(:unsigned :byte))
160 (:short :short)
161 (:unsigned-short '(:unsigned :short))
162 (:int :int)
163 (:unsigned-int '(:unsigned :int))
164 (:long :long)
165 (:unsigned-long '(:unsigned :long))
166 (:float :float)
167 (:double :double)
168 (:pointer :pointer)
169 (:void :void)))
171 ;;; Convert a CFFI type keyword to a symbol suitable for passing to
172 ;;; FLI:FOREIGN-TYPED-AREF.
173 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
174 (defun convert-foreign-typed-aref-type (cffi-type)
175 (ecase cffi-type
176 ((:char :short :int :long)
177 `(signed-byte ,(* 8 (%foreign-type-size cffi-type))))
178 ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long)
179 `(unsigned-byte ,(* 8 (%foreign-type-size cffi-type))))
180 (:float 'single-float)
181 (:double 'double-float)))
183 (defun %mem-ref (ptr type &optional (offset 0))
184 "Dereference an object of type TYPE OFFSET bytes from PTR."
185 (unless (zerop offset)
186 (setf ptr (inc-pointer ptr offset)))
187 (fli:dereference ptr :type (convert-foreign-type type)))
189 ;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
190 ;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-REF.
191 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
192 (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
193 (if (constantp type)
194 (let ((type (eval type)))
195 (if (eql type :pointer)
196 (let ((fli-type (convert-foreign-type type))
197 (ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
198 `(fli:dereference ,ptr-form :type ',fli-type))
199 (let ((lisp-type (convert-foreign-typed-aref-type type)))
200 `(locally
201 (declare (optimize (speed 3) (safety 0)))
202 (fli:foreign-typed-aref ',lisp-type ,ptr (the fixnum ,off))))))
203 form))
205 ;;; Open-code the call to FLI:DEREFERENCE when TYPE is constant at
206 ;;; macroexpansion time, when FLI:FOREIGN-TYPED-AREF is not available.
207 #-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
208 (define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
209 (if (constantp type)
210 (let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
211 (type (convert-foreign-type (eval type))))
212 `(fli:dereference ,ptr-form :type ',type))
213 form))
215 (defun %mem-set (value ptr type &optional (offset 0))
216 "Set the object of TYPE at OFFSET bytes from PTR."
217 (unless (zerop offset)
218 (setf ptr (inc-pointer ptr offset)))
219 (setf (fli:dereference ptr :type (convert-foreign-type type)) value))
221 ;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
222 ;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-SET.
223 #+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
224 (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
225 (if (constantp type)
226 (once-only (val)
227 (let ((type (eval type)))
228 (if (eql type :pointer)
229 (let ((fli-type (convert-foreign-type type))
230 (ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
231 `(setf (fli:dereference ,ptr-form :type ',fli-type) ,val))
232 (let ((lisp-type (convert-foreign-typed-aref-type type)))
233 `(locally
234 (declare (optimize (speed 3) (safety 0)))
235 (setf (fli:foreign-typed-aref ',lisp-type ,ptr
236 (the fixnum ,off))
237 ,val))))))
238 form))
240 ;;; Open-code the call to (SETF FLI:DEREFERENCE) when TYPE is constant
241 ;;; at macroexpansion time.
242 #-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
243 (define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
244 (if (constantp type)
245 (once-only (val)
246 (let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
247 (type (convert-foreign-type (eval type))))
248 `(setf (fli:dereference ,ptr-form :type ',type) ,val)))
249 form))
251 ;;;# Foreign Type Operations
253 (defun %foreign-type-size (type)
254 "Return the size in bytes of a foreign type."
255 (fli:size-of (convert-foreign-type type)))
257 (defun %foreign-type-alignment (type)
258 "Return the structure alignment in bytes of foreign type."
259 #+(and darwin harp::powerpc)
260 (when (eq type :double)
261 (return-from %foreign-type-alignment 8))
262 ;; Override not necessary for the remaining types...
263 (fli:align-of (convert-foreign-type type)))
265 ;;;# Calling Foreign Functions
267 (defvar *foreign-funcallable-cache* (make-hash-table :test 'equal)
268 "Caches foreign funcallables created by %FOREIGN-FUNCALL or
269 %FOREIGN-FUNCALL-POINTER. We only need to have one per each
270 signature.")
272 (defun foreign-funcall-type-and-args (args)
273 "Returns a list of types, list of args and return type."
274 (let ((return-type :void))
275 (loop for (type arg) on args by #'cddr
276 if arg collect (convert-foreign-type type) into types
277 and collect arg into fargs
278 else do (setf return-type (convert-foreign-type type))
279 finally (return (values types fargs return-type)))))
281 (defun create-foreign-funcallable (types rettype cconv)
282 "Creates a foreign funcallable for the signature TYPES -> RETTYPE."
283 (format t "~&Creating foreign funcallable for signature ~S -> ~S~%"
284 types rettype)
285 ;; yes, ugly, this most likely wants to be a top-level form...
286 (let ((internal-name (gensym)))
287 (funcall
288 (compile nil
289 `(lambda ()
290 (fli:define-foreign-funcallable ,internal-name
291 ,(loop for type in types
292 collect (list (gensym) type))
293 :result-type ,rettype
294 :language :ansi-c
295 ;; avoid warning about cdecl not being supported on mac
296 #-mac ,@(list :calling-convention cconv)))))
297 internal-name))
299 (defun get-foreign-funcallable (types rettype cconv)
300 "Returns a foreign funcallable for the signature TYPES -> RETTYPE -
301 either from the cache or newly created."
302 (let ((signature (cons rettype types)))
303 (or (gethash signature *foreign-funcallable-cache*)
304 ;; (SETF GETHASH) is supposed to be thread-safe
305 (setf (gethash signature *foreign-funcallable-cache*)
306 (create-foreign-funcallable types rettype cconv)))))
308 (defmacro %%foreign-funcall (foreign-function args cconv)
309 "Does the actual work for %FOREIGN-FUNCALL-POINTER and %FOREIGN-FUNCALL.
310 Checks if a foreign funcallable which fits ARGS already exists and creates
311 and caches it if necessary. Finally calls it."
312 (multiple-value-bind (types fargs rettype)
313 (foreign-funcall-type-and-args args)
314 `(funcall (load-time-value
315 (get-foreign-funcallable ',types ',rettype ',cconv))
316 ,foreign-function ,@fargs)))
318 (defmacro %foreign-funcall (name args &key library calling-convention)
319 "Calls a foreign function named NAME passing arguments ARGS."
320 `(%%foreign-funcall
321 (fli:make-pointer :symbol-name ,name
322 :module ',(if (eq library :default) nil library))
323 ,args ,calling-convention))
325 (defmacro %foreign-funcall-pointer (ptr args &key calling-convention)
326 "Calls a foreign function pointed at by PTR passing arguments ARGS."
327 `(%%foreign-funcall ,ptr ,args ,calling-convention))
329 (defun defcfun-helper-forms (name lisp-name rettype args types options)
330 "Return 2 values for DEFCFUN. A prelude form and a caller form."
331 (let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name))))
332 (values
333 `(fli:define-foreign-function (,ff-name ,name :source)
334 ,(mapcar (lambda (ty) (list (gensym) (convert-foreign-type ty)))
335 types)
336 :result-type ,(convert-foreign-type rettype)
337 :language :ansi-c
338 :module ',(let ((lib (getf options :library)))
339 (if (eq lib :default) nil lib))
340 ;; avoid warning about cdecl not being supported on mac platforms
341 #-mac ,@(list :calling-convention (getf options :calling-convention)))
342 `(,ff-name ,@args))))
344 ;;;# Callbacks
346 (defvar *callbacks* (make-hash-table))
348 ;;; Create a package to contain the symbols for callback functions. We
349 ;;; want to redefine callbacks with the same symbol so the internal data
350 ;;; structures are reused.
351 (defpackage #:cffi-callbacks
352 (:use))
354 ;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal
355 ;;; callback for NAME.
356 (eval-when (:compile-toplevel :load-toplevel :execute)
357 (defun intern-callback (name)
358 (intern (format nil "~A::~A" (package-name (symbol-package name))
359 (symbol-name name))
360 '#:cffi-callbacks)))
362 (defmacro %defcallback (name rettype arg-names arg-types body
363 &key calling-convention)
364 (let ((cb-name (intern-callback name)))
365 `(progn
366 (fli:define-foreign-callable
367 (,cb-name :encode :lisp
368 :result-type ,(convert-foreign-type rettype)
369 :calling-convention ,calling-convention
370 :language :ansi-c
371 :no-check nil)
372 ,(mapcar (lambda (sym type)
373 (list sym (convert-foreign-type type)))
374 arg-names arg-types)
375 ,body)
376 (setf (gethash ',name *callbacks*) ',cb-name))))
378 (defun %callback (name)
379 (multiple-value-bind (symbol winp)
380 (gethash name *callbacks*)
381 (unless winp
382 (error "Undefined callback: ~S" name))
383 (fli:make-pointer :symbol-name symbol :module :callbacks)))
385 ;;;# Loading Foreign Libraries
387 (defun %load-foreign-library (name path)
388 "Load the foreign library NAME."
389 (fli:register-module (or name path) :connection-style :immediate
390 :real-name path))
392 (defun %close-foreign-library (name)
393 "Close the foreign library NAME."
394 (fli:disconnect-module name :remove t))
396 (defun native-namestring (pathname)
397 (namestring pathname))
399 ;;;# Foreign Globals
401 (defun %foreign-symbol-pointer (name library)
402 "Returns a pointer to a foreign symbol NAME."
403 (values
404 (ignore-errors
405 (fli:make-pointer :symbol-name name :type :void
406 :module (if (eq library :default) nil library)))))