Omit unused structure copiers
[sbcl.git] / src / code / target-alieneval.lisp
blob59f8b4e1440803b81b71265b0660f904f20fa23b
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
5 ;;;; more information.
6 ;;;;
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")
17 ;;;; alien variables
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,
35 ;;; guess the other.
36 (eval-when (:compile-toplevel :load-toplevel :execute)
37 (defun pick-lisp-and-alien-names (name)
38 (flet ((oops ()
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)~:@>")))
43 (etypecase name
44 (string
45 (values (guess-lisp-name-from-alien-name name)
46 (coerce name 'simple-string)))
47 (symbol
48 (values name (guess-alien-name-from-lisp-name name)))
49 (list
50 (unless (and (proper-list-of-length-p name 2)
51 (symbolp (second name))
52 (stringp (first name)))
53 (oops))
54 (values (second name) (coerce (first name) 'simple-string)))
56 (oops))))))
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
71 ',alien-name
72 ',alien-type
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
83 :datap t))
84 (setf (info :source-location :variable lisp-name) location)
85 lisp-name))
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.
96 This is SETFable."
97 (let* ((alien-name (possibly-base-stringize
98 (etypecase name
99 (symbol (guess-alien-name-from-lisp-name name))
100 (string name))))
101 (alien-type (parse-alien-type type env))
102 (datap (not (alien-fun-type-p alien-type))))
103 `(%alien-value (foreign-symbol-sap ,alien-name ,datap) 0 ',alien-type)))
105 (defmacro with-alien (bindings &body body &environment env)
106 "Establish some local alien variables. Each BINDING is of the form:
107 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
108 ALLOCATION should be one of:
109 :LOCAL (the default)
110 The alien is allocated on the stack, and has dynamic extent.
111 :EXTERN
112 No alien is allocated, but VAR is established as a local name for
113 the external alien given by EXTERNAL-NAME."
114 ;; FIXME:
115 ;; :STATIC
116 ;; The alien is allocated on the heap, and has infinite extent. The alien
117 ;; is allocated at load time, so the same piece of memory is used each time
118 ;; this form executes.
119 (/show "entering WITH-ALIEN" bindings)
120 (let (#!+c-stack-is-control-stack
121 bind-alien-stack-pointer)
122 (with-auxiliary-alien-types env
123 (dolist (binding (reverse bindings))
124 (/show binding)
125 (destructuring-bind
126 (symbol type &optional opt1 (opt2 nil opt2p))
127 binding
128 (/show symbol type opt1 opt2)
129 (let* ((alien-type (parse-alien-type type env))
130 (datap (not (alien-fun-type-p alien-type))))
131 (/show alien-type)
132 (multiple-value-bind (allocation initial-value)
133 (if opt2p
134 (values opt1 opt2)
135 (case opt1
136 (:extern
137 (values opt1 (guess-alien-name-from-lisp-name symbol)))
138 (:static
139 (values opt1 nil))
141 (values :local opt1))))
142 (/show allocation initial-value)
143 (setf body
144 (ecase allocation
145 #+nil
146 (:static
147 (let ((sap
148 (make-symbol (concatenate 'string "SAP-FOR-"
149 (symbol-name symbol)))))
150 `((let ((,sap (load-time-value (%make-alien ...))))
151 (declare (type system-area-pointer ,sap))
152 (symbol-macrolet
153 ((,symbol (sap-alien ,sap ,type)))
154 ,@(when initial-value
155 `((setq ,symbol ,initial-value)))
156 ,@body)))))
157 (:extern
158 (/show0 ":EXTERN case")
159 `((symbol-macrolet
160 ((,symbol
161 (%alien-value
162 (foreign-symbol-sap ,initial-value ,datap) 0 ,alien-type)))
163 ,@body)))
164 (:local
165 (/show0 ":LOCAL case")
166 (let* ((var (sb!xc:gensym "VAR"))
167 (initval (if initial-value (sb!xc:gensym "INITVAL")))
168 (info (make-local-alien-info :type alien-type))
169 (inner-body
170 `((note-local-alien-type ',info ,var)
171 (symbol-macrolet ((,symbol (local-alien ',info ,var)))
172 ,@(when initial-value
173 `((setq ,symbol ,initval)))
174 ,@body)))
175 (body-forms
176 (if initial-value
177 `((let ((,initval ,initial-value))
178 ,@inner-body))
179 inner-body)))
180 (/show var initval info)
181 #!+c-stack-is-control-stack
182 (progn (setf bind-alien-stack-pointer t)
183 `((let ((,var (make-local-alien ',info)))
184 ,@body-forms)))
185 ;; FIXME: This version is less efficient then it needs to be, since
186 ;; it could just save and restore the number-stack pointer once,
187 ;; instead of doing multiple decrements if there are multiple bindings.
188 #!-c-stack-is-control-stack
189 `((let ((,var (make-local-alien ',info)))
190 (multiple-value-prog1
191 (progn ,@body-forms)
192 ;; No need for unwind protect here, since
193 ;; allocation involves modifying NSP, and
194 ;; NSP is saved and restored during NLX.
195 ;; And in non-transformed case it
196 ;; performs finalization.
197 (dispose-local-alien ',info ,var))))))))))))
198 (/show "revised" body)
199 (verify-local-auxiliaries-okay)
200 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
201 `(symbol-macrolet ((&auxiliary-type-definitions&
202 ,(append *new-auxiliary-types*
203 (auxiliary-type-definitions env))))
204 ,@(cond
205 #!+c-stack-is-control-stack
206 (bind-alien-stack-pointer
207 `((let ((sb!vm::*alien-stack-pointer* sb!vm::*alien-stack-pointer*))
208 ,@body)))
210 body))))))
212 ;;;; runtime C values that don't correspond directly to Lisp types
214 (defmethod print-object ((value alien-value) stream)
215 ;; Don't use ":TYPE T" here - TYPE-OF isn't what we want.
216 (print-unreadable-object (value stream)
217 (format stream "~S ~S #X~8,'0X ~S ~/sb!impl:print-type-specifier/"
218 'alien-value
219 :sap (sap-int (alien-value-sap value))
220 :type (unparse-alien-type (alien-value-type value)))))
222 #!-sb-fluid (declaim (inline null-alien))
223 (defun null-alien (x)
224 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
225 (zerop (sap-int (alien-sap x))))
227 (defmacro sap-alien (sap type &environment env)
228 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
229 evaluated.) TYPE must be pointer-like."
230 (let ((alien-type (parse-alien-type type env)))
231 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
232 `(%sap-alien ,sap ',alien-type)
233 (error "cannot make an alien of type ~S out of a SAP" type))))
235 (defun alien-sap (alien)
236 "Return a System-Area-Pointer pointing to Alien's data."
237 (declare (type alien-value alien))
238 (alien-value-sap alien))
240 ;;;; allocation/deallocation of heap aliens
242 (defmacro make-alien (type &optional size &environment env)
243 "Allocate an alien of type TYPE in foreign heap, and return an alien
244 pointer to it. The allocated memory is not initialized, and may
245 contain garbage. The memory is allocated using malloc(3), so it can be
246 passed to foreign functions which use free(3), or released using
247 FREE-ALIEN.
249 For alien stack allocation, see macro WITH-ALIEN.
251 The TYPE argument is not evaluated. If SIZE is supplied, how it is
252 interpreted depends on TYPE:
254 * When TYPE is a foreign array type, an array of that type is
255 allocated, and a pointer to it is returned. Note that you
256 must use DEREF to first access the array through the pointer.
258 If supplied, SIZE is used as the first dimension for the array.
260 * When TYPE is any other foreign type, then an object for that
261 type is allocated, and a pointer to it is returned. So
262 (make-alien int) returns a (* int).
264 If SIZE is specified, then a block of that many objects is
265 allocated, with the result pointing to the first one.
267 Examples:
269 (defvar *foo* (make-alien (array char 10)))
270 (type-of *foo*) ; => (alien (* (array (signed 8) 10)))
271 (setf (deref (deref foo) 0) 10) ; => 10
273 (make-alien char 12) ; => (alien (* (signed 8)))"
274 (let ((alien-type (if (alien-type-p type)
275 type
276 (parse-alien-type type env))))
277 (multiple-value-bind (size-expr element-type)
278 (if (alien-array-type-p alien-type)
279 (let ((dims (alien-array-type-dimensions alien-type)))
280 (cond
281 (size
282 (unless dims
283 (error
284 "cannot override the size of zero-dimensional arrays"))
285 (when (constantp size)
286 (setf alien-type (copy-structure alien-type))
287 (setf (alien-array-type-dimensions alien-type)
288 (cons (constant-form-value size) (cdr dims)))))
289 (dims
290 (setf size (car dims)))
292 (setf size 1)))
293 (values `(* ,size ,@(cdr dims))
294 (alien-array-type-element-type alien-type)))
295 (values (or size 1) alien-type))
296 (let ((bits (alien-type-bits element-type))
297 (alignment (alien-type-alignment element-type)))
298 (unless bits
299 (error "The size of ~S is unknown."
300 (unparse-alien-type element-type)))
301 (unless alignment
302 (error "The alignment of ~S is unknown."
303 (unparse-alien-type element-type)))
304 ;; This is the one place where the %SAP-ALIEN note is quite
305 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
306 ;; cannot be optimized away.
307 `(locally (declare (muffle-conditions compiler-note))
308 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
309 (%sap-alien (%make-alien (* ,(ash (+ 7 (align-offset bits alignment)) -3)
310 (the index ,size-expr)))
311 ',(make-alien-pointer-type :to alien-type)))))))
313 (defun malloc-error (bytes errno)
314 (error 'simple-storage-condition
315 :format-control "~A: malloc() of ~S bytes failed."
316 :format-arguments (list (strerror errno) bytes)))
318 ;;; Allocate a block of memory at least BYTES bytes long and return a
319 ;;; system area pointer to it.
320 #!-sb-fluid (declaim (inline %make-alien))
321 (defun %make-alien (bytes)
322 (declare (type index bytes)
323 (optimize (sb!c:alien-funcall-saves-fp-and-pc 0)))
324 (let ((sap (alien-funcall (extern-alien "malloc"
325 (function system-area-pointer size-t))
326 bytes)))
327 (if (and (not (eql 0 bytes)) (eql 0 (sap-int sap)))
328 (malloc-error bytes (get-errno))
329 sap)))
331 (eval-when (:compile-toplevel :load-toplevel :execute)
332 (defvar *saved-fp-and-pcs* nil)
333 ;; Can't use DECLAIM since always-bound is a non-standard declaration
334 (sb!xc:proclaim '(sb!ext:always-bound *saved-fp-and-pcs*)))
336 #!+c-stack-is-control-stack
337 (declaim (inline invoke-with-saved-fp-and-pc))
338 ;;; On :c-stack-is-control-stack platforms, this DEFUN must appear prior to the
339 ;;; first cross-compile-time use of ALIEN-FUNCALL, the transform of which is
340 ;;; an invocation of INVOKE-WITH-SAVED-FP-AND-PC, which should be inlined.
341 ;;; Makes no sense when compiling for the host.
342 #!+(and c-stack-is-control-stack (host-feature sb-xc))
343 (defun invoke-with-saved-fp-and-pc (fn)
344 (declare #-sb-xc-host (muffle-conditions compiler-note)
345 (optimize (speed 3)))
346 (dx-let ((fp-and-pc (make-array 2 :element-type 'word)))
347 (setf (aref fp-and-pc 0) (sb!kernel:get-lisp-obj-address
348 (sb!kernel:%caller-frame))
349 (aref fp-and-pc 1) (sap-int (sb!kernel:%caller-pc)))
350 (dx-let ((*saved-fp-and-pcs* (cons fp-and-pc *saved-fp-and-pcs*)))
351 (funcall fn))))
353 #!-sb-fluid (declaim (inline free-alien))
354 (defun free-alien (alien)
355 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
356 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
357 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
358 (alien-sap alien))
359 nil)
361 (declaim (type (function * (values system-area-pointer index))
362 %make-alien-string))
363 (defun %make-alien-string (string &key (start 0) end
364 (external-format :default)
365 (null-terminate t))
366 ;; FIXME: This is slow. We want a function to get the length of the
367 ;; encoded string so we can allocate the foreign memory first and
368 ;; encode directly there.
369 (let* ((octets (string-to-octets string
370 :start start :end end
371 :external-format external-format
372 :null-terminate null-terminate))
373 (count (length octets))
374 (buf (%make-alien count)))
375 (sb!kernel:copy-ub8-to-system-area octets 0 buf 0 count)
376 (values buf count)))
378 (defun make-alien-string (string &rest rest
379 &key (start 0) end
380 (external-format :default)
381 (null-terminate t))
382 "Copy part of STRING delimited by START and END into freshly
383 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
384 Returns the allocated string as a (* CHAR) alien, and the number of
385 bytes allocated as secondary value.
387 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
388 true (the default), the alien string is terminated by an additional
389 null byte."
390 (declare (ignore start end external-format null-terminate))
391 (multiple-value-bind (sap bytes)
392 (apply #'%make-alien-string string rest)
393 (values (%sap-alien sap (parse-alien-type '(* char) nil))
394 bytes)))
396 (define-compiler-macro make-alien-string (&rest args)
397 `(multiple-value-bind (sap bytes) (%make-alien-string ,@args)
398 (values (%sap-alien sap ',(parse-alien-type '(* char) nil))
399 bytes)))
401 ;;;; the SLOT operator
403 ;;; Find the field named SLOT, or die trying.
404 (defun slot-or-lose (type slot)
405 (declare (type alien-record-type type)
406 (type symbol slot))
407 (or (find slot (alien-record-type-fields type)
408 :key #'alien-record-field-name)
409 (error "There is no slot named ~S in ~S." slot type)))
411 ;;; Extract the value from the named slot from the record ALIEN. If
412 ;;; ALIEN is actually a pointer, then DEREF it first.
413 (defun slot (alien slot)
414 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
415 (declare (type alien-value alien)
416 (type symbol slot)
417 (optimize (inhibit-warnings 3)))
418 (let ((type (alien-value-type alien)))
419 (etypecase type
420 (alien-pointer-type
421 (slot (deref alien) slot))
422 (alien-record-type
423 (let ((field (slot-or-lose type slot)))
424 (%alien-value (alien-value-sap alien)
425 (alien-record-field-offset field)
426 (alien-record-field-type field)))))))
428 ;;; Deposit the value in the specified slot of the record ALIEN. If
429 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
430 ;;; this when it can't figure out anything better.
431 (defun %set-slot (alien slot value)
432 (declare (type alien-value alien)
433 (type symbol slot)
434 (optimize (inhibit-warnings 3)))
435 (let ((type (alien-value-type alien)))
436 (etypecase type
437 (alien-pointer-type
438 (%set-slot (deref alien) slot value))
439 (alien-record-type
440 (let ((field (slot-or-lose type slot)))
441 (setf (%alien-value (alien-value-sap alien)
442 (alien-record-field-offset field)
443 (alien-record-field-type field))
444 value))))))
446 ;;; Compute the address of the specified slot and return a pointer to it.
447 (defun %slot-addr (alien slot)
448 (declare (type alien-value alien)
449 (type symbol slot)
450 (optimize (inhibit-warnings 3)))
451 (let ((type (alien-value-type alien)))
452 (etypecase type
453 (alien-pointer-type
454 (%slot-addr (deref alien) slot))
455 (alien-record-type
456 (let* ((field (slot-or-lose type slot))
457 (offset (alien-record-field-offset field))
458 (field-type (alien-record-field-type field)))
459 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
460 (make-alien-pointer-type :to field-type)))))))
462 ;;;; the DEREF operator
464 ;;; This function does most of the work of the different DEREF
465 ;;; methods. It returns two values: the type and the offset (in bits)
466 ;;; of the referred-to alien.
467 (defun deref-guts (alien indices)
468 (declare (type alien-value alien)
469 (type list indices)
470 (values alien-type integer))
471 (let ((type (alien-value-type alien)))
472 (etypecase type
473 (alien-pointer-type
474 (when (cdr indices)
475 (error "too many indices when DEREF'ing ~S: ~W"
476 type
477 (length indices)))
478 (let ((element-type (alien-pointer-type-to type)))
479 (values element-type
480 (if indices
481 (* (align-offset (alien-type-bits element-type)
482 (alien-type-alignment element-type))
483 (car indices))
484 0))))
485 (alien-array-type
486 (unless (= (length indices) (length (alien-array-type-dimensions type)))
487 (error "incorrect number of indices when DEREF'ing ~S: ~W"
488 type (length indices)))
489 (labels ((frob (dims indices offset)
490 (if (null dims)
491 offset
492 (frob (cdr dims) (cdr indices)
493 (+ (if (zerop offset)
495 (* offset (car dims)))
496 (car indices))))))
497 (let ((element-type (alien-array-type-element-type type)))
498 (values element-type
499 (* (align-offset (alien-type-bits element-type)
500 (alien-type-alignment element-type))
501 (frob (alien-array-type-dimensions type)
502 indices 0)))))))))
504 ;;; Dereference the alien and return the results.
505 (defun deref (alien &rest indices)
506 "Dereference an Alien pointer or array. If an array, the indices are used
507 as the indices of the array element to access. If a pointer, one index can
508 optionally be specified, giving the equivalent of C pointer arithmetic."
509 (declare (type alien-value alien)
510 (type list indices)
511 (optimize (inhibit-warnings 3)))
512 (multiple-value-bind (target-type offset) (deref-guts alien indices)
513 (%alien-value (alien-value-sap alien)
514 offset
515 target-type)))
517 (defun %set-deref (alien value &rest indices)
518 (declare (type alien-value alien)
519 (type list indices)
520 (optimize (inhibit-warnings 3)))
521 (multiple-value-bind (target-type offset) (deref-guts alien indices)
522 (setf (%alien-value (alien-value-sap alien)
523 offset
524 target-type)
525 value)))
527 (defun %deref-addr (alien &rest indices)
528 (declare (type alien-value alien)
529 (type list indices)
530 (optimize (inhibit-warnings 3)))
531 (multiple-value-bind (target-type offset) (deref-guts alien indices)
532 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
533 (make-alien-pointer-type :to target-type))))
535 ;;;; accessing heap alien variables
537 (defun %heap-alien (info)
538 (declare (type heap-alien-info info)
539 (optimize (inhibit-warnings 3)))
540 (%alien-value (heap-alien-info-sap info)
542 (heap-alien-info-type info)))
544 (defun %set-heap-alien (info value)
545 (declare (type heap-alien-info info)
546 (optimize (inhibit-warnings 3)))
547 (setf (%alien-value (heap-alien-info-sap info)
549 (heap-alien-info-type info))
550 value))
552 (defun %heap-alien-addr (info)
553 (declare (type heap-alien-info info)
554 (optimize (inhibit-warnings 3)))
555 (%sap-alien (heap-alien-info-sap info)
556 (make-alien-pointer-type :to (heap-alien-info-type info))))
558 ;;;; accessing local aliens
560 (defun make-local-alien (info)
561 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
562 (alien-sap (alien-sap alien)))
563 (finalize
564 alien
565 (lambda ()
566 (alien-funcall
567 (extern-alien "free" (function (values) system-area-pointer))
568 alien-sap))
569 :dont-save t)
570 alien))
572 (defun note-local-alien-type (info alien)
573 (declare (ignore info alien))
574 nil)
576 (defun local-alien (info alien)
577 (declare (ignore info))
578 (deref alien))
580 (defun %set-local-alien (info alien value)
581 (declare (ignore info))
582 (setf (deref alien) value))
584 (define-setf-expander local-alien (&whole whole info alien)
585 (let ((value (gensym))
586 (info-var (gensym))
587 (alloc-tmp (gensym))
588 (info (if (and (consp info)
589 (eq (car info) 'quote))
590 (second info)
591 (error "Something is wrong; local-alien-info not found: ~S"
592 whole))))
593 (values nil
595 (list value)
596 `(if (%local-alien-forced-to-memory-p ',info)
597 (%set-local-alien ',info ,alien ,value)
598 (let* ((,info-var ',(local-alien-info-type info))
599 (,alloc-tmp (deport-alloc ,value ,info-var)))
600 (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
601 (setf ,alien (deport ,alloc-tmp ,info-var)))))
602 whole)))
604 (defun %local-alien-forced-to-memory-p (info)
605 (local-alien-info-force-to-memory-p info))
607 (defun %local-alien-addr (info alien)
608 (declare (type local-alien-info info))
609 (unless (local-alien-info-force-to-memory-p info)
610 (error "~S isn't forced to memory. Something went wrong." alien))
611 alien)
613 ;; It's not mandatory that this function not exist for x86[-64],
614 ;; however for sanity, it should not, because no call to it can occur.
615 #!-(or x86 x86-64)
616 (defun dispose-local-alien (info alien)
617 (declare (ignore info))
618 (cancel-finalization alien)
619 (free-alien alien))
621 ;;;; the CAST macro
623 (defmacro cast (alien type &environment env)
624 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
625 must be Alien array, pointer or function types."
626 `(%cast ,alien ',(parse-alien-type type env)))
628 (defun %cast (alien target-type)
629 (declare (type alien-value alien)
630 (type alien-type target-type)
631 (optimize (safety 2))
632 (optimize (inhibit-warnings 3)))
633 (if (or (alien-pointer-type-p target-type)
634 (alien-array-type-p target-type)
635 (alien-fun-type-p target-type))
636 (let ((alien-type (alien-value-type alien)))
637 (if (or (alien-pointer-type-p alien-type)
638 (alien-array-type-p alien-type)
639 (alien-fun-type-p alien-type))
640 (naturalize (alien-value-sap alien) target-type)
641 (error "~S cannot be casted." alien)))
642 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
644 ;;;; the ALIEN-SIZE macro
646 (defmacro alien-size (type &optional (units :bits) &environment env)
647 "Return the size of the alien type TYPE. UNITS specifies the units to
648 use and can be either :BITS, :BYTES, or :WORDS."
649 (let* ((alien-type (parse-alien-type type env))
650 (bits (alien-type-bits alien-type)))
651 (if bits
652 (values (ceiling bits
653 (ecase units
654 (:bits 1)
655 (:bytes sb!vm:n-byte-bits)
656 (:words sb!vm:n-word-bits))))
657 (error "unknown size for alien type ~S"
658 (unparse-alien-type alien-type)))))
660 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
662 ;;; There is little cost to making an interpreted function,
663 ;;; however it is even better if we can share the function object,
664 ;;; especially with sb-fasteval which avoids work on repeated invocations.
665 ;;; sb-eval doesn't optimize its IR in the same way,
666 ;;; but this is still a boon from a memory consumption stance.
668 ;;; GLOBALDB-SXHASHOID serves as a nice hash function for this purpose anyway.
669 ;;; Arguably we could key the cache off the internalized alien-type object
670 ;;; which induced creation of an interpreted lambda, rather than the s-expr,
671 ;;; but we'd need to get the TYPE and the method {NATURALIZE, DEPORT, etc} here,
672 ;;; so it would be a more invasive change.
674 (defun-cached (coerce-to-interpreted-function
675 :hash-bits 8 :hash-function #'globaldb-sxhashoid)
676 ((lambda-form equal))
677 (let (#!+(or sb-eval sb-fasteval)
678 (*evaluator-mode* :interpret))
679 (coerce lambda-form 'function)))
681 (defun naturalize (alien type)
682 (declare (type alien-type type))
683 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
684 alien type))
686 (defun deport (value type)
687 (declare (type alien-type type))
688 (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
689 value type))
691 (defun deport-alloc (value type)
692 (declare (type alien-type type))
693 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
694 value type))
696 (defun %alien-value (sap offset type)
697 (declare (type system-area-pointer sap)
698 (type unsigned-byte offset)
699 (type alien-type type))
700 (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
701 sap offset type))
703 (defun (setf %alien-value) (value sap offset type)
704 (declare (type system-area-pointer sap)
705 (type unsigned-byte offset)
706 (type alien-type type))
707 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
708 value sap offset type))
710 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
712 (defun alien-funcall (alien &rest args)
713 "Call the foreign function ALIEN with the specified arguments. ALIEN's
714 type specifies the argument and result types."
715 (declare (type alien-value alien))
716 (let ((type (alien-value-type alien)))
717 (typecase type
718 (alien-pointer-type
719 (apply #'alien-funcall (deref alien) args))
720 (alien-fun-type
721 (unless (= (length (alien-fun-type-arg-types type))
722 (length args))
723 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
724 type
725 (length (alien-fun-type-arg-types type))
726 (length args)))
727 (let ((stub (alien-fun-type-stub type)))
728 (unless stub
729 (setf stub
730 (let ((fun (sb!xc:gensym "FUN"))
731 (parms (make-gensym-list (length args))))
732 (compile nil
733 `(lambda (,fun ,@parms)
734 (declare (optimize (sb!c::insert-step-conditions 0)))
735 (declare (type (alien ,type) ,fun))
736 (alien-funcall ,fun ,@parms)))))
737 (setf (alien-fun-type-stub type) stub))
738 (apply stub alien args)))
740 (error "~S is not an alien function." alien)))))
742 (defmacro define-alien-routine (name result-type
743 &rest args
744 &environment lexenv)
745 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
747 Define a foreign interface function for the routine with the specified NAME.
748 Also automatically DECLAIM the FTYPE of the defined function.
750 NAME may be either a string, a symbol, or a list of the form (string symbol).
752 RETURN-TYPE is the alien type for the function return value. VOID may be
753 used to specify a function with no result.
755 The remaining forms specify individual arguments that are passed to the
756 routine. ARG-NAME is a symbol that names the argument, primarily for
757 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
758 way that the argument is passed.
761 An :IN argument is simply passed by value. The value to be passed is
762 obtained from argument(s) to the interface function. No values are
763 returned for :In arguments. This is the default mode.
765 :OUT
766 The specified argument type must be a pointer to a fixed sized object.
767 A pointer to a preallocated object is passed to the routine, and the
768 the object is accessed on return, with the value being returned from
769 the interface function. :OUT and :IN-OUT cannot be used with pointers
770 to arrays, records or functions.
772 :COPY
773 This is similar to :IN, except that the argument values are stored
774 on the stack, and a pointer to the object is passed instead of
775 the value itself.
777 :IN-OUT
778 This is a combination of :OUT and :COPY. A pointer to the argument is
779 passed, with the object being initialized from the supplied argument
780 and the return value being determined by accessing the object on
781 return."
782 (multiple-value-bind (lisp-name alien-name)
783 (pick-lisp-and-alien-names name)
784 (collect ((docs) (lisp-args) (lisp-arg-types)
785 (lisp-result-types
786 (cond ((eql result-type 'void)
787 ;; What values does a function return, if it
788 ;; returns no values? Exactly one - NIL. -- APD,
789 ;; 2003-03-02
790 (list 'null))
792 ;; FIXME: Check for VALUES.
793 (list `(alien ,result-type)))))
794 (arg-types) (alien-vars)
795 (alien-args) (results))
796 (dolist (arg args)
797 (if (stringp arg)
798 (docs arg)
799 (destructuring-bind (name type &optional (style :in)) arg
800 (unless (member style '(:in :copy :out :in-out))
801 (error "bogus argument style ~S in ~S" style arg))
802 (when (and (member style '(:out :in-out))
803 (typep (parse-alien-type type lexenv)
804 'alien-pointer-type))
805 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
806 type))
807 (let (arg-type)
808 (cond ((eq style :in)
809 (setq arg-type type)
810 (alien-args name))
812 (setq arg-type `(* ,type))
813 (if (eq style :out)
814 (alien-vars `(,name ,type))
815 (alien-vars `(,name ,type ,name)))
816 (alien-args `(addr ,name))))
817 (arg-types arg-type)
818 (unless (eq style :out)
819 (lisp-args name)
820 (lisp-arg-types t
821 ;; FIXME: It should be something
822 ;; like `(ALIEN ,ARG-TYPE), except
823 ;; for we also accept SAPs where
824 ;; pointers are required.
826 (when (or (eq style :out) (eq style :in-out))
827 (results name)
828 (lisp-result-types `(alien ,type))))))
829 `(progn
830 ;; The theory behind this automatic DECLAIM is that (1) if
831 ;; you're calling C, static typing is what you're doing
832 ;; anyway, and (2) such a declamation can be (especially for
833 ;; alien values) both messy to do by hand and very important
834 ;; for performance of later code which uses the return value.
835 (declaim (ftype (function ,(lisp-arg-types)
836 (values ,@(lisp-result-types) &optional))
837 ,lisp-name))
838 (defun ,lisp-name ,(lisp-args)
839 ,@(docs)
840 (with-alien
841 ((,lisp-name (function ,result-type ,@(arg-types))
842 :extern ,alien-name)
843 ,@(alien-vars))
844 ,@(if (eq 'void result-type)
845 `((alien-funcall ,lisp-name ,@(alien-args))
846 (values nil ,@(results)))
847 `((values (alien-funcall ,lisp-name ,@(alien-args))
848 ,@(results))))))))))
850 (defun alien-typep (object type)
851 "Return T iff OBJECT is an alien of type TYPE."
852 (let ((lisp-rep-type (compute-lisp-rep-type type)))
853 (if lisp-rep-type
854 (typep object lisp-rep-type)
855 (and (alien-value-p object)
856 (alien-subtype-p (alien-value-type object) type)))))
858 (defun alien-value-typep (object type)
859 (when (alien-value-p object)
860 (alien-subtype-p (alien-value-type object) type)))
862 ;;;; ALIEN CALLBACKS
863 ;;;;
864 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
866 (defvar *alien-callback-info* nil
867 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
868 information we need to manipulate callbacks after their creation. Used for
869 changing the lisp-side function they point to, invalidation, etc.")
871 (defstruct (callback-info
872 (:copier nil))
873 specifier
874 function ; NULL if invalid
875 wrapper
876 index)
878 (defun callback-info-key (info)
879 (cons (callback-info-specifier info) (callback-info-function info)))
881 (defun alien-callback-info (alien)
882 (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
884 (define-load-time-global *alien-callbacks* (make-hash-table :test #'equal)
885 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
886 memoization: we don't create new callbacks if one pointing to the correct
887 function with the same specifier already exists.")
889 (define-load-time-global *alien-callback-wrappers* (make-hash-table :test #'equal)
890 "Cache of existing lisp wrappers, indexed with SPECIFER. Used for memoization:
891 we don't create new wrappers if one for the same specifier already exists.")
893 (define-load-time-global *alien-callback-trampolines*
894 (make-array 32 :fill-pointer 0 :adjustable t)
895 "Lisp trampoline store: assembler wrappers contain indexes to this, and
896 ENTER-ALIEN-CALLBACK pulls the corresponding trampoline out and calls it.")
898 (defun %alien-callback-sap (specifier result-type argument-types function wrapper
899 &optional call-type)
900 (declare #!-x86 (ignore call-type))
901 (let ((key (list specifier function)))
902 (or (gethash key *alien-callbacks*)
903 (setf (gethash key *alien-callbacks*)
904 (let* ((index (fill-pointer *alien-callback-trampolines*))
905 ;; Aside from the INDEX this is known at
906 ;; compile-time, which could be utilized by
907 ;; having the two-stage assembler tramp &
908 ;; wrapper mentioned in [1] above: only the
909 ;; per-function tramp would need assembler at
910 ;; runtime. Possibly we could even pregenerate
911 ;; the code and just patch the index in later.
912 (assembler-wrapper
913 (alien-callback-assembler-wrapper
914 index result-type argument-types
915 #!+x86
916 (if (eq call-type :stdcall)
917 (ceiling
918 (apply #'+
919 (mapcar 'alien-type-word-aligned-bits
920 argument-types))
922 0))))
923 (vector-push-extend
924 (alien-callback-lisp-trampoline wrapper function)
925 *alien-callback-trampolines*)
926 ;; Assembler-wrapper is static, so sap-taking is safe.
927 (let ((sap (vector-sap assembler-wrapper)))
928 (push (cons sap (make-callback-info :specifier specifier
929 :function function
930 :wrapper wrapper
931 :index index))
932 *alien-callback-info*)
933 sap))))))
935 (defun alien-callback-lisp-trampoline (wrapper function)
936 (declare (function wrapper) (optimize speed))
937 (lambda (args-pointer result-pointer)
938 (funcall wrapper args-pointer result-pointer function)))
940 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
941 (let* ((arguments (make-gensym-list (length argument-types)))
942 (argument-names arguments)
943 (argument-specs (cddr specifier)))
944 `(lambda (args-pointer result-pointer function)
945 ;; FIXME: the saps are not gc safe
946 (let ((args-sap (int-sap
947 (sb!kernel:get-lisp-obj-address args-pointer)))
948 (res-sap (int-sap
949 (sb!kernel:get-lisp-obj-address result-pointer))))
950 (declare (ignorable args-sap res-sap))
951 (with-alien
952 ,(loop
953 with offset = 0
954 for spec in argument-specs
955 ;; KLUDGE: At least one platform requires additional
956 ;; alignment beyond a single machine word for certain
957 ;; arguments. Accept an additional delta (for the
958 ;; alignment) to apply to subsequent arguments to
959 ;; account for the alignment gaps as a secondary
960 ;; value, so that we don't have to update unaffected
961 ;; backends.
962 for (accessor-form alignment)
963 = (multiple-value-list
964 (alien-callback-accessor-form spec 'args-sap offset))
965 collect `(,(pop argument-names) ,spec
966 :local ,accessor-form)
967 do (incf offset (+ (alien-callback-argument-bytes spec env)
968 (or alignment 0))))
969 ,(flet ((store (spec real-type)
970 (if spec
971 `(setf (deref (sap-alien res-sap (* ,spec)))
972 ,(if real-type
973 `(the ,real-type
974 (funcall function ,@arguments))
975 `(funcall function ,@arguments)))
976 `(funcall function ,@arguments))))
977 (cond ((alien-void-type-p result-type)
978 (store nil nil))
979 ((alien-integer-type-p result-type)
980 ;; Integer types should be padded out to a full
981 ;; register width, to comply with most ABI calling
982 ;; conventions, but should be typechecked on the
983 ;; declared type width, hence the following:
984 (if (alien-integer-type-signed result-type)
985 (store `(signed
986 ,(alien-type-word-aligned-bits result-type))
987 `(signed-byte ,(alien-type-bits result-type)))
988 (store
989 `(unsigned
990 ,(alien-type-word-aligned-bits result-type))
991 `(unsigned-byte ,(alien-type-bits result-type)))))
993 (store (unparse-alien-type result-type) nil))))))
994 (values))))
996 (defun invalid-alien-callback (&rest arguments)
997 (declare (ignore arguments))
998 (error "Invalid alien callback called."))
1000 (defun parse-callback-specification (result-type lambda-list)
1001 (values
1002 `(function ,result-type ,@(mapcar #'second lambda-list))
1003 (mapcar #'first lambda-list)))
1005 (defun parse-alien-ftype (specifier env)
1006 (destructuring-bind (function result-type &rest argument-types)
1007 specifier
1008 (aver (eq 'function function))
1009 (multiple-value-bind (bare-result-type calling-convention)
1010 (typecase result-type
1011 ((cons calling-convention *)
1012 (values (second result-type) (first result-type)))
1013 (t result-type))
1014 (values (let ((*values-type-okay* t))
1015 (parse-alien-type bare-result-type env))
1016 (mapcar (lambda (spec)
1017 (parse-alien-type spec env))
1018 argument-types)
1019 calling-convention))))
1021 (defun alien-void-type-p (type)
1022 (and (alien-values-type-p type) (not (alien-values-type-values type))))
1024 (defun alien-type-word-aligned-bits (type)
1025 (align-offset (alien-type-bits type) sb!vm:n-word-bits))
1027 (defun alien-callback-argument-bytes (spec env)
1028 (let ((type (parse-alien-type spec env)))
1029 (if (or (alien-integer-type-p type)
1030 (alien-float-type-p type)
1031 (alien-pointer-type-p type)
1032 (alien-system-area-pointer-type-p type))
1033 (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
1034 (error "Unsupported callback argument type: ~A" type))))
1036 (defun enter-alien-callback (index return arguments)
1037 (funcall (aref *alien-callback-trampolines* index)
1038 return
1039 arguments))
1041 ;;;; interface (not public, yet) for alien callbacks
1043 (let ()
1044 (defmacro alien-callback (specifier function &environment env)
1045 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
1046 an alien function as a pointer to the FUNCTION. If a callback for the given
1047 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
1048 one."
1049 ;; Pull out as much work as is convenient to macro-expansion time, specifically
1050 ;; everything that can be done given just the SPECIFIER and ENV.
1051 (multiple-value-bind (result-type argument-types call-type)
1052 (parse-alien-ftype specifier env)
1053 `(%sap-alien
1054 (%alien-callback-sap ',specifier ',result-type ',argument-types
1055 ,function
1056 (or (gethash ',specifier *alien-callback-wrappers*)
1057 (setf (gethash ',specifier *alien-callback-wrappers*)
1058 (compile nil
1059 ',(alien-callback-lisp-wrapper-lambda
1060 specifier result-type argument-types env))))
1061 ,call-type)
1062 ',(parse-alien-type specifier env)))))
1064 (defun alien-callback-p (alien)
1065 "Returns true if the alien is associated with a lisp-side callback,
1066 and a secondary return value of true if the callback is still valid."
1067 (let ((info (alien-callback-info alien)))
1068 (when info
1069 (values t (and (callback-info-function info) t)))))
1071 (defun alien-callback-function (alien)
1072 "Returns the lisp function designator associated with the callback."
1073 (let ((info (alien-callback-info alien)))
1074 (when info
1075 (callback-info-function info))))
1077 (defun (setf alien-callback-function) (function alien)
1078 "Changes the lisp function designated by the callback."
1079 (let ((info (alien-callback-info alien)))
1080 (unless info
1081 (error "Not an alien callback: ~S" alien))
1082 ;; sap cache
1083 (let ((key (callback-info-key info)))
1084 (remhash key *alien-callbacks*)
1085 (setf (gethash key *alien-callbacks*) (alien-sap alien)))
1086 ;; trampoline
1087 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1088 (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
1089 ;; metadata
1090 (setf (callback-info-function info) function)
1091 function))
1093 (defun invalidate-alien-callback (alien)
1094 "Invalidates the callback designated by the alien, if any, allowing the
1095 associated lisp function to be GC'd, and causing further calls to the same
1096 callback signal an error."
1097 (let ((info (alien-callback-info alien)))
1098 (when (and info (callback-info-function info))
1099 ;; sap cache
1100 (remhash (callback-info-key info) *alien-callbacks*)
1101 ;; trampoline
1102 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1103 #'invalid-alien-callback)
1104 ;; metadata
1105 (setf (callback-info-function info) nil)
1106 t)))
1108 ;;; FIXME: This call assembles a new callback for every closure,
1109 ;;; which sucks hugely. ...not that I can think of an obvious
1110 ;;; solution. Possibly maybe we could write a generalized closure
1111 ;;; callback analogous to closure_tramp, and share the actual wrapper?
1113 ;;; For lambdas that result in simple-funs we get the callback from
1114 ;;; the cache on subsequent calls.
1115 (let ()
1116 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
1117 (multiple-value-bind (specifier lambda-list)
1118 (parse-callback-specification result-type typed-lambda-list)
1119 `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
1121 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
1122 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
1123 ;;; the FDEFINITION should invalidate the callback, and redefining the
1124 ;;; callback should change existing callbacks to point to the new defintion.
1125 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
1126 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
1127 the alien callback for that function with the given alien type."
1128 (declare (symbol name))
1129 (multiple-value-bind (specifier lambda-list)
1130 (parse-callback-specification result-type typed-lambda-list)
1131 `(progn
1132 (defun ,name ,lambda-list ,@forms)
1133 (defparameter ,name (alien-callback ,specifier #',name)))))