changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / lisp/std/alien.lisp

changeset 680: 5f88b237ce29
parent: 2b7d5a8d63ac
child: 2bad47888dbf
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 27 Sep 2024 20:19:10 -0400
permissions: -rw-r--r--
description: added skc, fixed alien c-string functions, upgrades and fixes for rocksdb/rdb
1 ;;; alien.lisp --- foreign alien friends
2 
3 ;;
4 
5 ;;; Commentary:
6 
7 ;; FFI in Lisp is somewhat different than FFI in other host langs. As
8 ;; such, we usually refer to our Lispy FFI interfaces inline with the
9 ;; CMUCL terminology: alien interfaces.
10 
11 ;; ref: https://www.sbcl.org/manual/#Foreign-Function-Interface for details
12 
13 ;; sb-alien is a high-level interface which automatically converts C
14 ;; memory pointers to lisp objects and back, but this can be slow for
15 ;; large or complex objects.
16 
17 ;; The lower-level interface is based on System Area Pointers (or
18 ;; SAPs), which provide untyped access to foreign memory.
19 
20 ;; Objects which can't be automatically converted into Lisp values are
21 ;; represented by objects of type ALIEN-VALUE.
22 
23 ;;; Code:
24 (in-package :std/alien)
25 ;; (shadowing-import
26 ;; '(sb-unix::syscall sb-unix::syscall* sb-unix::int-syscall
27 ;; sb-unix::with-restarted-syscall sb-unix::void-syscall) :std)
28 
29 ;; (reexport-from :sb-vm
30 ;; :include
31 ;; '(:with-pinned-objects :with-pinned-object-iterator :with-code-pages-pinned
32 ;; :sanctify-for-execution))
33 
34 (defun shared-object-name (name &optional path)
35  "Return a filename with the correct extension for a shared library."
36  (let ((name #+darwin (format nil "lib~a.dylib" name)
37  #-darwin (format nil "lib~a.so" name)))
38  (if path
39  (merge-pathnames name path)
40  (pathname name))))
41 
42 (defun list-all-shared-objects ()
43  sb-alien::*shared-objects*)
44 
45 (defmacro define-alien-loader (name &optional export (root "/usr/local/lib/") path)
46  "Define a default loader function named load-NAME which calls
47 SB-ALIEN:LOAD-SHARED-OBJECT."
48  (let* ((fname (sb-int:symbolicate (format nil "~@:(load-~a~)" name))))
49  `(prog1
50  (defun ,fname (&optional save)
51  (prog1 (sb-alien:load-shared-object (shared-object-name ',(or path name) ,root) :dont-save (not save))
52  (pushnew ,(sb-int:keywordicate (string-upcase name)) *features*)))
53  ,@(when export (list `(export '(,fname)))))))
54 
55 (defmacro define-opaque (ty &optional no-export foreign-type)
56  `(prog1
57  (define-alien-type ,ty (struct ,(or foreign-type (symbolicate ty '-t))))
58  ,(unless no-export `(export '(,ty)))))
59 
60 (defun setfa (place from)
61  (loop for x across from
62  for i from 0 below (length from)
63  do (setf (deref place i) x)))
64 
65 (defun copy-c-string (src dest &aux (index 0))
66  (declare (type sb-int:index index))
67  (loop (let ((b (sb-sys:sap-ref-8 src index)))
68  (when (= b 0)
69  (setf (fill-pointer dest) index)
70  (return))
71  (setf (char dest index) (code-char b))
72  (incf index))))
73 
74 (defun clone-strings (list)
75  (let ((len (length list)))
76  (with-alien ((x (* (* char)) (make-alien (* char) len)))
77  (labels ((populate (list index)
78  (declare (type sb-int:index index))
79  (if list
80  (let ((array (sb-ext:string-to-octets (car list) :null-terminate t)))
81  (sb-sys:with-pinned-objects (array)
82  (setf (deref x index) (sap-alien (sb-sys:vector-sap array) (* char)))
83  (populate (cdr list) (1+ index))))
84  x)))
85  (cast (populate list 0) (* c-string))))))
86 
87 (defun c-strings-to-string-list (c-strings)
88  (declare (type (alien (* c-string)) c-strings))
89  (let ((reversed-result nil))
90  (dotimes (i most-positive-fixnum)
91  (declare (type sb-int:index i))
92  (let ((c-string (deref c-strings i)))
93  (if c-string
94  (push c-string reversed-result)
95  (return (nreverse reversed-result)))))))
96 
97 (defun clone-octets-to-alien (lispa alien)
98  (declare (optimize (speed 3))
99  ((vector (unsigned-byte 8)) lispa))
100  ;; (setf aliena (cast aliena (array (unsigned 8))))
101  (loop for i from 0 below (length lispa)
102  do (setf (deref alien i)
103  (aref lispa i)))
104  alien)
105 
106 (defun octets-to-alien (lispa)
107  (let ((a (make-alien (unsigned 8) (length lispa))))
108  (clone-octets-to-alien lispa a)))
109 
110 ;; TODO 2024-09-19: maybe want to return values, second being the length?
111 (defun octets-to-alien-array (lispa)
112  (cast (octets-to-alien lispa) (array (unsigned 8))))
113 
114 (defun clone-octets-from-alien (aliena lispa &optional len)
115  (declare (optimize (speed 3))
116  (vector lispa))
117  (unless len (setf len (length lispa)))
118  (loop for i from 0 below len
119  do (setf (aref lispa i)
120  (deref aliena i)))
121  lispa)
122 
123 (defun foreign-int-to-integer (buffer size)
124  "Check SIZE of int BUFFER. return BUFFER."
125  (assert (= size (sb-alien:alien-size sb-alien:int :bytes)))
126  buffer)
127 
128 (defun foreign-int-to-bool (x size)
129  (if (zerop (foreign-int-to-integer x size))
130  nil
131  t))
132 
133 (defun bool-to-foreign-int (val)
134  (if val 1 0))
135 
136 (define-condition invalid-enum-variant (simple-error) ())
137 (define-condition invalid-enum-value (simple-error) ())
138 
139 (defun invalid-enum-variant (var enum)
140  (error 'invalid-enum-variant
141  :format-control "~A is not a variant of enum ~A"
142  :format-arguments (list var enum)))
143 
144 (defun invalid-enum-value (var enum)
145  (error 'invalid-enum-value
146  :format-control "~A is not a value associated with a variant of enum ~A"
147  :format-arguments (list var enum)))
148 
149 (defmacro define-alien-enum ((name type &key (test 'eql) (default :error)) &rest forms)
150  "Define a pseudo-enum type, used to work-around difficulties working with
151 SB-ALIEN, groveller, typedef enums, etc.
152 
153 NAME specified the name of the alien-type and keyword-based lookup
154 function. Additionally a NAME* reverse-lookup function is provided.
155 
156 Two hash-tables are defined in the environment of the accessor functions
157 containing the variants. These are technically exposed anaphors
158 %lisp-enum-table and %lisp-enum-table*."
159  (setf forms (loop for (k . v) on forms by #'cddr
160  collect (cons k v)))
161  (with-gensyms (val)
162  (let ((%lisp-enum-table (make-hash-table :test test :size (length forms)))
163  (%lisp-enum-table* (make-hash-table :test 'equal :size (length forms)))) ; TODO: may want this to be EQL,
164  ; taking strings for now.
165  (mapc (lambda (x) (setf (gethash (car x) %lisp-enum-table) (eval (cadr x)))) forms)
166  (mapc (lambda (x) (setf (gethash (eval (cadr x)) %lisp-enum-table*) (car x))) forms)
167  `(progn
168  (define-alien-type ,name ,type)
169  (defun ,name (,val)
170  ,(format nil "Given a keyword naming a variant of ~A, return the associated value." name)
171  (let ((found (gethash ,val ,%lisp-enum-table ,default)))
172  ,@(when (eql default :error)
173  `((when (eql found :error) (invalid-enum-variant ,val ',name))))
174  found))
175  (defun ,(symbolicate name '*) (,val)
176  ,(format nil "Given a ~A, check that it is equal to one of the variants of ~A and return
177 it. This function returns a second value which indicates the name of the
178 variant associated with this value." type name)
179  (std:when-let ((found (gethash ,val ,%lisp-enum-table*
180  ,default)))
181  ,@(when (eql default :error)
182  `((when (eql found :error) (invalid-enum-value ,val ',name))))
183  (values ,val found)))))))
184 
185 ;; from CFFI
186 (defmacro with-alien-slots (vars struct &body body)
187  "Create local symbol macros for each var in VARS to reference
188 foreign slots in STRUCT. Similar to WITH-SLOTS.
189 Each var can be of the form:
190  name name bound to slot of same name
191  (* name) name bound to pointer to slot of same name
192  (name slot-name) name bound to slot-name
193  (name :pointer slot-name) name bound to pointer to slot-name"
194  `(symbol-macrolet
195  ,(loop for var in vars
196  collect
197  (if (listp var)
198  (let ((p1 (first var)) (p2 (second var)) (p3 (third var)))
199  (if (eq (sb-int:keywordicate p1) :*)
200  `(,p2 (addr (slot ,struct ',p2)))
201  (if (eq (sb-int:keywordicate p2) :*)
202  `(,p1 (addr (slot ,struct ',p3)))
203  `(,p1 (slot ,struct ',p2)))))
204  `(,var (slot ,struct ',var))))
205  ,@body))
206 
207 (defun num-cpus ()
208  "Return the number of CPU threads online."
209  (alien-funcall (extern-alien "sysconf" (function int int)) sb-unix:sc-nprocessors-onln))
210 
211 (defvar *cpus* (num-cpus))
212 
213 ;;; C Standard
214 
215 ;; types
216 (define-alien-type loff-t long-long)
217 
218 (define-alien-routine memset void (ptr (* t)) (constant int) (size size-t))