Debian Codegraph @

src/lsp/ffi.lsp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; indent-tabs-mode: nil; Package: SYSTEM -*-
2 ;;;; vim: set filetype=lisp tabstop=8 shiftwidth=2 expandtab:
3
4 ;;;;
5 ;;;; Copyright (c) 2001, Juan Jose Garcia-Ripoll
6 ;;;;
7 ;;;; See file 'LICENSE' for the copyright details.
8
9 ;;;; FFI Symbols used in the foreign function interface
10
11 (in-package "FFI")
12
13 (import 'si:null-pointer-p)
14 (export 'si:null-pointer-p)
15
16 #-ecl-min
17 (clines "#include <string.h>")
18
19 (defmacro def-constant (name value &key (export nil))
20 "Macro to define a constant and to export it"
21 `(eval-when (:compile-toplevel :load-toplevel :execute)
22 (defconstant ,name ,value)
23 ,(when export (list 'export `(quote ,name)))
24 ',name))
25
26 ;;;----------------------------------------------------------------------
27 ;;; FOREIGN TYPES
28 ;;;
29
30 (defparameter *ffi-types* (make-hash-table :size 128))
31
32 (defparameter *use-dffi* t)
33
34 (defmacro def-foreign-type (name definition)
35 "Syntax: (def-foreign-type name definition)
36
37 Defines a new foreign type."
38 `(eval-when (:compile-toplevel :load-toplevel :execute)
39 (setf (gethash ',name ffi::*ffi-types*) ',definition)))
40
41 (defmacro def-type (name definition)
42 (declare (ignore definition))
43 `(deftype ,name () t))
44
45 (defun %convert-to-ffi-type (type &optional context)
46 (if (atom type)
47 (if (member type context)
48 type
49 (multiple-value-bind (value present-p) (gethash type *ffi-types* type)
50 (if present-p
51 (%convert-to-ffi-type value (cons type context))
52 value)))
53 (cons (%convert-to-ffi-type (first type) context)
54 (%convert-to-ffi-type (rest type) context))))
55
56 (defmacro %align-data (data align)
57 `(setf ,data (* (ceiling (/ ,data ,align)) ,align)))
58
59 (defun size-of-foreign-type (name)
60 "Syntax: (size-of-foreign-type ftype)
61
62 Returns the number of data bytes used by a foreign object type. This
63 does not include any Lisp storage overhead."
64 (let* ((size 0) align
65 (type (%convert-to-ffi-type name)))
66 (unless type
67 (error "Incomplete or unknown foreign type ~A" name))
68 (cond ((symbolp type)
69 (setf size (si:size-of-foreign-elt-type type)
70 align (si:alignment-of-foreign-elt-type type)))
71 ((atom type)
72 (error "~A is not a valid foreign type identifier" name))
73 ((eq (setf name (first type)) :struct)
74 (setf size (slot-position type nil))
75 (when (rest type)
76 (setf align (apply #'max (mapcar #'(lambda (field)
77 (multiple-value-bind (field-size field-align)
78 (size-of-foreign-type (second field))
79 (declare (ignore field-size))
80 field-align))
81 (rest type))))
82 (%align-data size align)))
83 ((eq name :array)
84 (unless (and (setf size (third type)) (realp size))
85 (error "Incomplete foreign type: ~S" type))
86 (multiple-value-bind (elt-size elt-align)
87 (size-of-foreign-type (second type))
88 (setf size (* size elt-size)
89 align elt-align)))
90 ((eq name :union)
91 (dolist (field (rest type))
92 (multiple-value-bind (field-size field-align)
93 (size-of-foreign-type (second field))
94 (when (> field-size size)
95 (setf size field-size))
96 (when (or (null align) (> field-align align))
97 (setf align field-align)))))
98 ((eq name '*)
99 (setf size (si:size-of-foreign-elt-type :pointer-void)
100 align (si:alignment-of-foreign-elt-type :pointer-void)))
101 ((eq name 'quote)
102 (return-from size-of-foreign-type
103 (size-of-foreign-type (second type))))
104 (t
105 (error "~A does not denote a foreign type" name)))
106 (values size (or align 0))))
107
108 (defun allocate-foreign-object (type &optional (size 0 size-flag))
109 "Syntax: (allocate-foreign-object type &optional (size 0)
110
111 Allocates an instance of a foreign object. It returns a pointer to the
112 object."
113 (let ((type-size (size-of-foreign-type type)))
114 (cond ((null size-flag)
115 (si::allocate-foreign-data type type-size))
116 ((and (typep size 'fixnum) (>= size 0))
117 (let ((bytes (* size type-size)))
118 (si::allocate-foreign-data `(:array ,type ,size) bytes)))
119 (t
120 (error "~A is not a valid array dimension size" size)))))
121
122 (defun free-foreign-object (ptr)
123 "Syntax: (free-foreign-object ptr)
124
125 Frees memory that was allocated for a foreign object."
126 (si::free-foreign-data ptr))
127
128 ;;;----------------------------------------------------------------------
129 ;;; ENUMERATION TYPES
130 ;;;
131
132 (defmacro def-enum (name values-list &key (separator-string "#"))
133 "Syntax: (def-enum name (&rest values-list) &key (separator-string \"#\")
134
135 Defines a C enumeration"
136 (let ((constants '())
137 (value -1)
138 field
139 forms)
140 (setf #| name (string name) |#
141 separator-string (string separator-string))
142 (dolist (item values-list)
143 (cond ((symbolp item)
144 (setf field item)
145 (incf value))
146 ((and (consp item)
147 (symbolp (setf field (first item)))
148 (integerp (setf value (second item)))
149 (endp (cddr item))))
150 (t
151 (error "Not a valid argument to DEF-ENUM~%~a" values-list)))
152 (setf field (concatenate 'string
153 (symbol-name name)
154 separator-string
155 (string field)))
156 (push `(defconstant ,(intern field (symbol-package name))
157 ',value)
158 forms))
159 `(progn
160 (def-foreign-type ,name :int)
161 ,@forms)))
162
163
164 ;;;----------------------------------------------------------------------
165 ;;; STRUCTURE TYPES
166 ;;;
167 ;;; The structure type is represented by the following list:
168 ;;;
169 ;;; (STRUCT (SLOT-NAME1 . SLOT-TYPE1)*)
170 ;;;
171 ;;; FIXME! We do not care about slot alignment!
172 ;;;
173
174 (defmacro def-struct (name &rest slots)
175 "Syntax: (def-struct name (SLOT-NAME . SLOT-TYPE)*)
176
177 Defines a C structure. SLOT-TYPE is denoted by a FFI type."
178 (let ((struct-type (list :struct))
179 field
180 type)
181 (dolist (item (subst `(* ,name) :pointer-self slots))
182 (if (and (consp item)
183 (= (length item) 2)
184 (symbolp (setf field (first item))))
185 (setf type (second item))
186 (error "Not a valid DEF-STRUCT slot ~A" item))
187 (push (list field type) struct-type))
188 `(def-foreign-type ,name ,(nreverse struct-type))))
189
190 (defun slot-position (type field)
191 (setf type (%convert-to-ffi-type type))
192 (let ((ndx 0)
193 (is-union nil))
194 (cond ((atom type)
195 (error "~A is not a foreign STRUCT or UNION type" type))
196 ((eq (first type) :struct))
197 ((eq (first type) :union)
198 (setf is-union t))
199 (t
200 (error "~A is not a foreign STRUCT or UNION type" type)))
201 (dolist (slot (rest type))
202 (let* ((slot-name (car slot))
203 (slot-type (cadr slot)))
204 (multiple-value-bind (slot-size slot-align)
205 (size-of-foreign-type slot-type)
206 (%align-data ndx slot-align)
207 (when (eq slot-name field)
208 (return-from slot-position (values ndx slot-type slot-size)))
209 (unless is-union
210 (incf ndx slot-size)))))
211 (values ndx nil nil)))
212
213 (defun get-slot-value (object struct-type field)
214 "Syntax: (get-slot-value object struct-type field)
215
216 Accesses a FIELD value from a OBJECT of type STRUCT-TYPE."
217 (multiple-value-bind (slot-ndx slot-type slot-size)
218 (slot-position struct-type field)
219 (unless slot-size
220 (error "~A is not a field of the type ~A" field struct-type))
221 (%foreign-data-ref object slot-ndx slot-type slot-size)))
222
223 (defun (setf get-slot-value) (value object struct-type field)
224 (multiple-value-bind (slot-ndx slot-type slot-size)
225 (slot-position struct-type field)
226 (unless slot-size
227 (error "~A is not a field of the type ~A" field struct-type))
228 (%foreign-data-set object slot-ndx slot-type value)))
229
230 (defun get-slot-pointer (object struct-type field)
231 "Syntax: (get-slot-pointer object struct-type field)
232
233 Accesses a FIELD pointer value from a OBJECT of type STRUCT-TYPE."
234 (multiple-value-bind (slot-ndx slot-type slot-size)
235 (slot-position struct-type field)
236 (unless slot-size
237 (error "~A is not a field of the type ~A" field struct-type))
238 (si::foreign-data-pointer object slot-ndx slot-size slot-type)))
239
240
241 ;;;----------------------------------------------------------------------
242 ;;; ARRAYS
243 ;;;
244
245 (defmacro def-array-pointer (name element-type)
246 `(def-foreign-type ,name (* ,element-type)))
247
248 (defun deref-array (array array-type position)
249 "Syntax: (deref-array array type position)
250
251 Dereferences (retrieves) the value of the foreign ARRAY element on the
252 POSITION."
253 (setf array-type (%convert-to-ffi-type array-type))
254 (let* ((element-type (second array-type))
255 (element-size (size-of-foreign-type element-type))
256 (ndx (* position element-size))
257 (length (or (third array-type) '*)))
258 (unless (or (eq length '*)
259 (> length position -1))
260 (error "Out of bounds when accessing array ~A." array))
261 (%foreign-data-ref (si::foreign-data-recast array (+ ndx element-size) array-type) ndx element-type element-size)))
262
263 (defun (setf deref-array) (value array array-type position)
264 (setf array-type (%convert-to-ffi-type array-type))
265 (let* ((element-type (second array-type))
266 (element-size (size-of-foreign-type element-type))
267 (ndx (* position element-size))
268 (length (or (third array-type) '*)))
269 (unless (or (eq length '*)
270 (> length position -1))
271 (error "Out of bounds when accessing array ~A." array))
272 (%foreign-data-set (si::foreign-data-recast array (+ ndx element-size) array-type) ndx element-type value)))
273
274 (defun %foreign-data-set (obj ndx type value)
275 (cond ((foreign-elt-type-p type)
276 (si::foreign-data-set-elt obj ndx type value))
277 ((atom type)
278 (error "Unknown foreign primitive type: ~A" type))
279 ((eq (first type) '*)
280 (si::foreign-data-set-elt obj ndx :pointer-void value))
281 (t
282 (si::foreign-data-set obj ndx value))))
283
284 (defun %foreign-data-ref (obj ndx type &optional (size 0 size-p))
285 (cond ((foreign-elt-type-p type)
286 (si::foreign-data-ref-elt obj ndx type))
287 ((atom type)
288 (error "Unknown foreign primitive type: ~A" type))
289 ((eq (first type) '*)
290 (si::foreign-data-recast (si::foreign-data-ref-elt obj ndx :pointer-void)
291 (size-of-foreign-type (second type))
292 type))
293 (t
294 (si::foreign-data-ref obj ndx (if size-p size (size-of-foreign-type type)) type))))
295
296 ;;;----------------------------------------------------------------------
297 ;;; UNIONS
298 ;;;
299
300 (defmacro def-union (name &rest slots)
301 "Syntax: (def-union name (field-name field-type)*)
302
303 Defines a foreign union type."
304 (let ((struct-type (list :union))
305 field
306 type)
307 (dolist (item (subst `(* ,struct-type) :pointer-self slots))
308 (unless (and (consp item)
309 (= (length item) 2)
310 (symbolp (setf field (first item))))
311 (error "Not a valid DEF-UNION slot ~A" item))
312 (setf type (second item))
313 (push (list field type) struct-type))
314 `(def-foreign-type ,name ,(nreverse struct-type))))
315
316 ;;;----------------------------------------------------------------------
317 ;;; POINTERS
318 ;;;
319
320 (defparameter +null-cstring-pointer+ (si:allocate-foreign-data :pointer-void 0))
321
322 (defun pointer-address (ptr)
323 "Syntax: (pointer-address ptr)
324
325 Returns the address as an integer of a pointer."
326 (si::foreign-data-address ptr))
327
328 (defun deref-pointer (ptr ftype)
329 "Syntax: (deref-pointer ptr ftype)
330
331 Returns the object to which a pointer points."
332 ;; FIXME! No checking!
333 (setf ftype (%convert-to-ffi-type ftype))
334 (cond ((foreign-elt-type-p ftype)
335 (si::foreign-data-ref-elt ptr 0 ftype))
336 ((atom ftype)
337 (error "Unknown foreign primitive type: ~A" ftype))
338 ((eq (first ftype) '*)
339 (si::foreign-data-recast (si::foreign-data-ref-elt ptr 0 :pointer-void)
340 (size-of-foreign-type (second ftype))
341 (second ftype)))
342 (t
343 (error "Cannot dereference pointer to foreign data, ~A" ptr))
344 ))
345
346 (defun (setf deref-pointer) (value ptr type)
347 ;; FIXME! No checking!
348 (setf type (%convert-to-ffi-type type))
349 (if (foreign-elt-type-p type)
350 (si::foreign-data-set-elt ptr 0 type value)
351 (si::foreign-data-set ptr 0 value)))
352
353 (defun make-null-pointer (ftype)
354 "Syntax; (make-null-pointer ftype)
355
356 Creates a NULL pointer of a specified type."
357 ;(setf ftype (%convert-to-ffi-type ftype))
358 (si::allocate-foreign-data ftype 0))
359
360 (defun make-pointer (addr type)
361 (c-inline (type (size-of-foreign-type type) addr) (:object :unsigned-long :unsigned-long) :object
362 "ecl_make_foreign_data(#0, #1, (void*)#2)"
363 :side-effects t
364 :one-liner t))
365
366 #+(OR) ;; Already defined in core
367 (defun null-pointer-p (object)
368 (si::null-pointer-p object))
369
370
371 ;;;----------------------------------------------------------------------
372 ;;; CHARACTERS AND STRINGS
373 ;;;
374 ;;; ECL always returns characters when dereferencing (:array * :char)
375 ;;;
376
377 (defun null-char-p (char)
378 "Syntax: (null-char-p char)
379
380 Tests a character for NULL value."
381 (eq char #.(code-char 0)))
382
383 (defun ensure-char-character (char)
384 "Syntax: (ensure-char-character object)
385
386 Ensures that a dereferenced char or integer is a lisp character."
387 (cond ((characterp char) char)
388 ((integerp char) (code-char char))
389 (t (error "~a cannot be coerced to type CHARACTER" char))))
390
391 (defun ensure-char-integer (char)
392 "Syntax: (ensure-char-integer object)
393
394 Ensures that a dereferenced char or integer is a lisp integer."
395 (cond ((characterp char) (char-code char))
396 ((integerp char) char)
397 (t (error "~a cannot be coerced to type INTEGER" char))))
398
399 (defun ensure-char-storable (char)
400 char)
401
402 (defun char-array-to-pointer (obj)
403 (si::foreign-data-pointer obj 0 1 '(* :unsigned-char)))
404
405 (defmacro convert-from-cstring (object)
406 "Syntax: (convert-from-cstring object)
407
408 Converts a Lisp string to a cstring. This is most often used when
409 processing the results of a foreign function that returns a cstring."
410 object)
411
412 (defmacro convert-to-cstring (object)
413 "Syntax: (convert-to-cstring object)
414
415 Converts cstring OBJECT to a Lisp string. Allocates memory."
416 ;; This enforces that the string contains only as many characters as the
417 ;; fill-pointer determines Since ECL always sets a 0 character after the
418 ;; last element of a string, this way, the string is always zero-terminated
419 `(si:copy-to-simple-base-string ,object))
420
421 (defmacro free-cstring (cstring)
422 "Syntax: (free-cstring cstring)
423
424 Free memory used by CSTRING."
425 cstring)
426
427 (defmacro with-cstring ((cstring string) &body body)
428 "Syntax: (with-cstring (cstring string) &body body)
429
430 Binds CSTRING to a cstring created from conversion of a STRING and
431 evaluated the BODY. Automatically frees the CSTRING."
432 `(let ((,cstring (convert-to-cstring ,string))) ,@body))
433
434 (defmacro with-cstrings (bindings &rest body)
435 "Syntax: (with-cstrings ((cstring string)*) &body body)
436
437 See: WITH-CSTRING. Works similar to LET*."
438 (if bindings
439 `(with-cstring ,(car bindings)
440 (with-cstrings ,(cdr bindings)
441 ,@body))
442 `(progn ,@body)))
443
444 (defun foreign-string-length (foreign-string)
445 (c-inline (foreign-string) (t) :int
446 "strlen((#0)->foreign.data)"
447 :side-effects nil
448 :one-liner t))
449
450 (defun convert-from-foreign-string (foreign-string
451 &key length (null-terminated-p t))
452 "Syntax: (convert-from-foreign-string
453 foreign-string &key length (null-terminated-p t)
454
455 Returns a Lisp string from a foreign string FOREIGN-STRING. Can
456 translate ASCII and binary strings."
457 (cond ((and (not length) null-terminated-p)
458 (setf length (foreign-string-length foreign-string)))
459 ((not (integerp length))
460 (error "~A is not a valid string length" length)))
461 (c-inline (foreign-string length) (t fixnum) string
462 "{
463 cl_index length = #1;
464 cl_object output = ecl_alloc_simple_base_string(length);
465 memcpy(output->base_string.self, (#0)->foreign.data, length);
466 @(return) = output;
467 }"
468 :one-liner nil
469 :side-effects t))
470
471 (defun convert-to-foreign-string (string-designator)
472 "Syntax: (convert-to-foreign-string string-designator)
473
474 Converts a Lisp string to a foreign string. Memory should be freed
475 with free-foreign-object."
476 (let ((cstring (convert-to-cstring (string string-designator)))
477 (foreign-type '(* :char)))
478 (c-inline (cstring foreign-type) (t t) t
479 "{
480 cl_object lisp_string = #0;
481 cl_index size = lisp_string->base_string.fillp;
482 cl_object output = ecl_allocate_foreign_data(#1, size+1);
483 memcpy(output->foreign.data, lisp_string->base_string.self, size);
484 output->foreign.data[size] = '\\0';
485 @(return) = output;
486 }"
487 :one-liner nil
488 :side-effects t)
489 ))
490
491 (defun allocate-foreign-string (size &key (unsigned T))
492 "Syntax: (allocate-foreign-string size &key (unsigned t))
493
494 Allocates space for a foreign string. Memory should be freed with
495 FREE-FOREIGN-OBJECT. Initial contents of the string are undefined."
496 (si::allocate-foreign-data `(* ,(if unsigned :unsigned-char :char))
497 (1+ size)))
498
499 (defmacro with-foreign-string ((foreign-string lisp-string) &rest body)
500 "Syntax: (with-foreign-string ((foreign-string lisp-string) &rest body)
501
502 Binds FOREIGN-STRING to a foreign string created from conversion of a
503 STRING and evaluated the BODY. Automatically frees the FOREIGN-STRING."
504 `(let* ((,foreign-string (convert-to-foreign-string ,lisp-string)))
505 (mp:without-interrupts
506 (unwind-protect
507 (mp:with-restored-interrupts ,@body)
508 (free-foreign-object ,foreign-string)))))
509
510 (defmacro with-foreign-strings (bindings &rest body)
511 "Syntax: (with-foreign-strings ((foreign-string string)*) &body body)
512
513 See: WITH-FOREIGN-STRING. Works similar to LET*."
514 (if bindings
515 `(with-foreign-string ,(car bindings)
516 (with-foreign-strings ,(cdr bindings)
517 ,@body))
518 `(progn ,@body)))
519
520 ;;;----------------------------------------------------------------------
521 ;;; MACROLOGY
522 ;;;
523
524 (defmacro with-foreign-object ((var type) &body body)
525 "Syntax: (with-foreign-object (var type) &body body)
526
527 Wraps the allocation, binding and destruction of a foreign object
528 around a body of code"
529 `(let ((,var (allocate-foreign-object ,type)))
530 (mp:without-interrupts
531 (unwind-protect
532 (mp:with-restored-interrupts ,@body)
533 (free-foreign-object ,var)))))
534
535 (defmacro with-foreign-objects (bindings &rest body)
536 (if bindings
537 `(with-foreign-object ,(car bindings)
538 (with-foreign-objects ,(cdr bindings)
539 ,@body))
540 `(progn ,@body)))
541
542 (defmacro with-cast-pointer (bind &body body)
543 "Syntax: (with-cast-pointer (var ptr ftype) &body body)
544
545 Executes BODY with PTR cast to be a pointer to type FTYPE. VAR will be
546 bound to this value during the execution of body."
547 (let (binding-name ptr type)
548 (case (length bind)
549 (2 (setf binding-name (first bind)
550 ptr binding-name
551 type (second bind)))
552 (3 (setf binding-name (first bind)
553 ptr (second bind)
554 type (third bind)))
555 (otherwise (error "Arguments missing in WITH-CAST-POINTER")))
556 `(let ((,binding-name (si::foreign-data-pointer (si::foreign-data-recast ,ptr (size-of-foreign-type ',type) :void) 0
557 (size-of-foreign-type ',type)
558 ',type)))
559 ,@body)))
560
561 ;;;----------------------------------------------------------------------
562 ;;; INTERFACE TO C FUNCTIONS AND VARIABLES
563 ;;;
564
565 (defun lisp-to-c-name (name)
566 (cond ((or (stringp name)
567 (symbolp name))
568 (values name (intern (string-upcase (substitute #\- #\_ (string name))))))
569 ((and (consp name)
570 (= (length name) 2))
571 (values (first name) (second name)))))
572
573 (defun %convert-to-arg-type (type)
574 (let ((type (%convert-to-ffi-type type)))
575 (cond ((atom type) type)
576 ((eq (first type) '*) :pointer-void)
577 ((eq (first type) :array) :pointer-void)
578 (t (error "Unsupported argument type: ~A" type))
579 )))
580
581 (defun %convert-to-return-type (type)
582 (let ((type (%convert-to-ffi-type type)))
583 (cond ((atom type) type)
584 ((eq (first type) '*) (second type))
585 (t type))))
586
587 (defun produce-function-call (c-name nargs)
588 (declare (si::c-local))
589 (format nil "~a(~a)" c-name
590 (subseq "#0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#a,#b,#c,#d,#e,#f,#g,#h,#i,#j,#k,#l,#m,#n,#o,#p,#q,#r,#s,#t,#u,#v,#w,#x,#y,#z"
591 0 (max 0 (1- (* nargs 3))))))
592
593 ;;; FIXME! We should turn this into a closure generator that produces no code.
594 #+dffi
595 (defmacro def-lib-function (name args &key returning module (call :default))
596 (multiple-value-bind (c-name lisp-name) (lisp-to-c-name name)
597 (let* ((return-type (ffi::%convert-to-return-type returning))
598 (argtypes (mapcar #'(lambda (a) (ffi::%convert-to-arg-type (second a))) args)))
599 `(let ((c-fun (si::find-foreign-symbol ',c-name ,module :pointer-void 0)))
600 (defun ,lisp-name ,(mapcar #'first args)
601 (si::call-cfun c-fun ',return-type ',argtypes (list ,@(mapcar #'first args)) ,call))))))
602
603 (defmacro def-function (name args &key module (returning :void) (call :default))
604 "Syntax: (def-function name args
605 &key module (returning :void) (call :default)
606
607 Declares a foreign function."
608 (declare (ignorable call))
609 #+DFFI
610 (when (and module *use-dffi*)
611 (return-from def-function
612 `(def-lib-function ,name ,args :returning ,returning :module ,module :call ,call)))
613 (multiple-value-bind (c-name lisp-name)
614 (lisp-to-c-name name)
615 (let* ((arguments (mapcar #'first args))
616 (arg-types (mapcar #'(lambda (type) (%convert-to-arg-type (second type))) args))
617 (return-type (%convert-to-return-type returning))
618 (nargs (length arguments))
619 (c-string (produce-function-call c-name nargs))
620 (casting-required (not (or (member return-type '(:void :cstring))
621 (foreign-elt-type-p return-type))))
622 (inline-form `(c-inline ,arguments ,arg-types
623 ,(if casting-required :pointer-void return-type)
624 ,c-string
625 :one-liner t
626 :side-effects t)))
627 (when casting-required
628 (setf inline-form
629 `(si::foreign-data-recast ,inline-form
630 (size-of-foreign-type ',return-type)
631 ',return-type)))
632 (when (> nargs 36)
633 (error "FFI can only handle C functions with up to 36 arguments"))
634 `(defun ,lisp-name (,@arguments)
635 ,inline-form)
636 )))
637
638 (defmacro def-foreign-var (name type module)
639 "Syntax: (def-foreign-var name type module)
640
641 Defines a symbol macro which can be used to access (get and set) the
642 value of a variable in foreign code."
643 (declare (ignorable module))
644 (multiple-value-bind (c-name lisp-name)
645 (lisp-to-c-name name)
646 (let* ((ffi-type (%convert-to-ffi-type type))
647 (can-deref (or (foreign-elt-type-p ffi-type)
648 (and (consp ffi-type)
649 (member (first ffi-type) '(* :array)))))
650 (inline-form (cond #+dffi
651 ((and module *use-dffi*)
652 `(si::find-foreign-symbol ,c-name ,module ',type ,(size-of-foreign-type type)))
653 (t
654 `(c-inline () () :object
655 ,(format nil "ecl_make_foreign_data(@~S, ~A, &~A)"
656 type (size-of-foreign-type type) c-name)
657 :side-effects t :one-liner t)))))
658 (if can-deref
659 `(progn
660 (put-sysprop ',lisp-name 'ffi-foreign-var ,inline-form)
661 (eval-when (:compile-toplevel :load-toplevel :execute)
662 (define-symbol-macro ,lisp-name
663 (ffi:deref-pointer (get-sysprop ',lisp-name 'ffi-foreign-var) ',type)
664 )))
665 `(defparameter ,lisp-name ,inline-form))
666 )))
667
668 (defun find-foreign-library (names directories &key drive-letters types)
669 "Syntax: (find-foreign-library names directories &key drive-letters type)
670
671 Finds a foreign library by searching through a number of possible
672 locations. Returns the path of the first found file."
673 (unless (listp names)
674 (setq names (list names)))
675 (unless (listp directories)
676 (setq directories (list directories)))
677 (unless types
678 (setq types #+win32 '("lib")
679 #-win32 '("so" "a")))
680 (unless (listp types)
681 (setq types (list types)))
682 (unless (listp drive-letters)
683 (setq drive-letters (list drive-letters)))
684 #-msvc
685 (setq drive-letters '(nil))
686 #+msvc
687 (unless drive-letters
688 (setq drive-letters '(nil)))
689 (dolist (d drive-letters)
690 (dolist (p directories)
691 (dolist (n names)
692 (dolist (e types)
693 (let ((full-path (probe-file (make-pathname
694 :device d
695 :directory (etypecase p
696 (pathname (pathname-directory p))
697 (string (pathname-directory (parse-namestring p)))
698 (list p))
699 :name n
700 :type e))))
701 (when full-path
702 (return-from find-foreign-library full-path))
703 )))))
704 nil)
705
706 (defparameter +loaded-libraries+ nil)
707
708 (defun do-load-foreign-library (tmp &optional system-library)
709 (let* ((path (cond ((pathnamep tmp) tmp)
710 ((probe-file (setf tmp (string tmp))) tmp)
711 (t (compile-file-pathname tmp :type #+msvc :lib #-msvc :dll))))
712 (filename (namestring path))
713 (pack (find-package "COMPILER"))
714 (flag (if system-library
715 (concatenate 'string "-l" tmp)
716 filename)))
717 (unless (find filename ffi::+loaded-libraries+ :test #'string-equal)
718 (setf (symbol-value (intern "*LD-FLAGS*" pack))
719 (concatenate 'string (symbol-value (intern "*LD-FLAGS*" pack)) " " flag))
720 (setf (symbol-value (intern "*LD-BUNDLE-FLAGS*" pack))
721 (concatenate 'string (symbol-value (intern "*LD-BUNDLE-FLAGS*" pack))
722 " " flag))
723 (setf (symbol-value (intern "*LD-SHARED-FLAGS*" pack))
724 (concatenate 'string (symbol-value (intern "*LD-SHARED-FLAGS*" pack))
725 " " flag))
726 (push filename ffi::+loaded-libraries+))
727 t))
728
729 (defmacro load-foreign-library (filename &key module supporting-libraries force-load
730 system-library &environment env)
731 "Syntax: (load-foreign-library filename
732 &key module supporting-libraries force-load system-library)
733
734 Loads a foreign library."
735 (declare (ignore module force-load supporting-libraries))
736 (let ((compile-form (and (constantp filename env)
737 `((ext:with-backend
738 :c/c++ (eval-when (:compile-toplevel)
739 (do-load-foreign-library ,filename
740 ,(ext:constant-form-value system-library)))
741 :bytecodes nil))))
742 (dyn-form #+dffi (when (and (not system-library) *use-dffi*)
743 `((si:load-foreign-module ,filename)))
744 #-dffi nil))
745 `(progn ,@compile-form ,@dyn-form)))
746
747 ;;;----------------------------------------------------------------------
748 ;;; CALLBACKS
749 ;;;
750
751 #-dffi
752 (defmacro defcallback (&rest args)
753 (error "DEFCALLBACK cannot be used in interpreted forms"))
754
755 #+dffi
756 (defmacro defcallback (name ret-type arg-desc &body body)
757 (if *use-dffi*
758 (multiple-value-bind (name call-type) (if (consp name)
759 (values-list name)
760 (values name :default))
761 (let ((arg-types (mapcar #'second arg-desc))
762 (arg-names (mapcar #'first arg-desc))
763 (ret-type (typecase ret-type
764 ((member nil :void) :void)
765 ((cons (member * array)) :pointer-void)
766 (otherwise ret-type))))
767 `(si::make-dynamic-callback
768 #'(ext::lambda-block ,name ,arg-names ,@body)
769 ',name ',ret-type ',arg-types ,call-type)))
770 (error "DEFCALLBACK cannot be used in interpreted forms when DFFI is disabled.")))
771
772 (defun callback (name)
773 (let ((x (si::get-sysprop name :callback)))
774 (unless x
775 (error "There is no callback with name ~a" name))
776 x))
777
778 ;;;----------------------------------------------------------------------
779 ;;; COMPATIBILITY WITH OLDER FFI
780 ;;;
781
782 (defun clines (&rest c/c++-code)
783 "Syntax: (clines &rest c/c++-code)
784
785 CLINES is used to inline C/C++ declarations (strings) at the beginning
786 of the produced C/C++ header file. Works only in the compiled code and
787 is required to be a toplevel form."
788 (error "The special form clines cannot be used in the interpreter: ~A"
789 c/c++-code))
790
791 (eval-when (:load-toplevel :execute)
792 (defmacro c-inline (lisp-values arg-c-types return-type c/c++-code
793 &key (side-effects t) one-liner)
794 `(error "The special form c-inline cannot be used in the interpreter: ~S"
795 (list (list ,@lisp-values) ',arg-c-types ',return-type
796 ,c/c++-code
797 :side-effects ,side-effects
798 :one-liner ,one-liner)))
799 (defmacro c-progn (args &rest body)
800 (declare (ignore args))
801 '(error "The special form c-progn cannot be used in the interpreter.")))
802
803 (defmacro definline (fun arg-types type code)
804 "Syntax: (definline symbol (&rest arg-types) result-type &body body) " "
805
806 DEFINLINE behaves like a DEFCBODY (see), but also instructs the LISP compiler
807 to expand inline any call to function SYMBOL into code corresponding
808 to the C language expression BODY, whenever it can determine that
809 the actual arguments are of the specified type."
810 `(eval-when (:compile-toplevel :load-toplevel :execute)
811 ;; defCbody must go first, because it clears symbol-plist of fun
812 (defCbody ,fun ,arg-types ,type ,code)
813 (declaim (ftype (function ,arg-types ,type) ,fun))
814 (c::def-inline ,fun :always ,arg-types ,type ,code)))
815
816 (defmacro defla (name args &body body)
817 "Syntax: (defla name args &body body)
818
819 Used to DEFine Lisp Alternative. For the interpreter, DEFLA is equivalent to
820 DEFUN, but the compiler ignores this form."
821 `(eval-when (:execute)
822 (defun ,name ,args ,@body)))
823
824 (defmacro defcbody (name arg-types result-type c-expression)
825 "Syntax: (defcbody name arg-types result-type c-expression)
826
827 The compiler defines a Lisp function named by NAME whose body consists
828 of the C code of the string C-EXPRESSION. In the C-EXPRESSION one can
829 reference the arguments of the function as \"#0\", \"#1\", etc.
830
831 The interpreter ignores this form. ARG-TYPES are argument types of
832 the defined Lisp function and RESULT-TYPE is its return type."
833 (let ((args (mapcar #'(lambda (x) (declare (ignore x)) (gensym))
834 arg-types)))
835 `(defun ,name ,args
836 (c-inline ,args ,arg-types ,result-type
837 ,c-expression :one-liner t))))
838
839 (defmacro defentry (name arg-types c-name &key no-interrupts)
840 "Syntax: (defentry name arg-types (result-type function-name)
841 &key no-interrupts)
842
843 The compiler defines a Lisp function named by NAME whose body consists
844 of a calling sequence to the C language function named by
845 FUNCTION-NAME.
846
847 The interpreter ignores this form. ARG-TYPES are argument types of
848 the C function and RESULT-TYPE is its return type."
849 (let ((output-type :object)
850 (args (mapcar #'(lambda (x) (declare (ignore x)) (gensym))
851 arg-types)))
852 (if (consp c-name)
853 (setf output-type (first c-name)
854 c-name (second c-name)))
855 (let* ((call (produce-function-call (string c-name) (length arg-types)))
856 (full-text (if no-interrupts
857 (concatenate 'string
858 "ecl_disable_interrupts();@(return)="
859 call
860 ";ecl_enable_interrupts();")
861 call)))
862 `(defun ,name ,args
863 (c-inline ,args ,arg-types ,output-type
864 ,full-text
865 :one-liner ,(not no-interrupts))))))
866