Remove some test noise. A drop in the ocean unfortunately.
[sbcl.git] / src / code / target-alieneval.lisp
blobfbc67a2244aad2ca3f37683bd74928215f0021e3
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 #!+sb-doc
60 "Define NAME as an external alien variable of type TYPE. NAME should
61 be a list of a string holding the alien name and a symbol to use as
62 the Lisp name. If NAME is just a symbol or string, then the other name
63 is guessed from the one supplied."
64 (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
65 (with-auxiliary-alien-types env
66 (let ((alien-type (parse-alien-type type env)))
67 `(eval-when (:compile-toplevel :load-toplevel :execute)
68 ,@(when *new-auxiliary-types*
69 `((%def-auxiliary-alien-types ',*new-auxiliary-types*
70 (sb!c:source-location))))
71 (%define-alien-variable ',lisp-name
72 ',alien-name
73 ',alien-type
74 (sb!c:source-location)))))))
76 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
77 (eval-when (:compile-toplevel :load-toplevel :execute)
78 (defun %define-alien-variable (lisp-name alien-name type location)
79 (setf (info :variable :kind lisp-name) :alien)
80 (setf (info :variable :where-from lisp-name) :defined)
81 (setf (info :variable :alien-info lisp-name)
82 (make-heap-alien-info :type type
83 :alien-name alien-name
84 :datap t))
85 (setf (info :source-location :variable lisp-name) location)))
87 (defun alien-value (symbol)
88 #!+sb-doc
89 "Returns the value of the alien variable bound to SYMBOL. Signals an
90 error if SYMBOL is not bound to an alien variable, or if the alien
91 variable is undefined."
92 (%heap-alien (or (info :variable :alien-info symbol)
93 (error 'unbound-variable :name symbol))))
95 (defmacro extern-alien (name type &environment env)
96 #!+sb-doc
97 "Access the alien variable named NAME, assuming it is of type TYPE.
98 This is SETFable."
99 (let* ((alien-name (etypecase name
100 (symbol (guess-alien-name-from-lisp-name name))
101 (string name)))
102 (alien-type (parse-alien-type type env))
103 (datap (not (alien-fun-type-p alien-type))))
104 `(%alien-value (foreign-symbol-sap ,alien-name ,datap) 0 ',alien-type)))
106 (defmacro with-alien (bindings &body body &environment env)
107 #!+sb-doc
108 "Establish some local alien variables. Each BINDING is of the form:
109 VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
110 ALLOCATION should be one of:
111 :LOCAL (the default)
112 The alien is allocated on the stack, and has dynamic extent.
113 :EXTERN
114 No alien is allocated, but VAR is established as a local name for
115 the external alien given by EXTERNAL-NAME."
116 ;; FIXME:
117 ;; :STATIC
118 ;; The alien is allocated on the heap, and has infinite extent. The alien
119 ;; is allocated at load time, so the same piece of memory is used each time
120 ;; this form executes.
121 (/show "entering WITH-ALIEN" bindings)
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 #!+(or x86 x86-64)
182 `((let ((,var (make-local-alien ',info)))
183 ,@body-forms))
184 ;; FIXME: This version is less efficient then it needs to be, since
185 ;; it could just save and restore the number-stack pointer once,
186 ;; instead of doing multiple decrements if there are multiple bindings.
187 #!-(or x86 x86-64)
188 `((let ((,var (make-local-alien ',info)))
189 (multiple-value-prog1
190 (progn ,@body-forms)
191 ;; No need for unwind protect here, since
192 ;; allocation involves modifying NSP, and
193 ;; NSP is saved and restored during NLX.
194 ;; And in non-transformed case it
195 ;; performs finalization.
196 (dispose-local-alien ',info ,var))))))))))))
197 (/show "revised" body)
198 (verify-local-auxiliaries-okay)
199 (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
200 `(symbol-macrolet ((&auxiliary-type-definitions&
201 ,(append *new-auxiliary-types*
202 (auxiliary-type-definitions env))))
203 #!+(or x86 x86-64)
204 (let ((sb!vm::*alien-stack-pointer* sb!vm::*alien-stack-pointer*))
205 ,@body)
206 #!-(or x86 x86-64)
207 ,@body)))
209 ;;;; runtime C values that don't correspond directly to Lisp types
211 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
212 ;;; 'cause it has to be real early in the cold-load order.
213 #!-sb-fluid (declaim (freeze-type alien-value))
214 (def!method print-object ((value alien-value) stream)
215 (print-unreadable-object (value stream)
216 ;; See identical kludge in host-alieneval.
217 (let ((sb!pretty:*pprint-quote-with-syntactic-sugar* nil))
218 (declare (special sb!pretty:*pprint-quote-with-syntactic-sugar*))
219 (format stream
220 "~S ~S #X~8,'0X ~S ~S"
221 'alien-value
222 :sap (sap-int (alien-value-sap value))
223 :type (unparse-alien-type (alien-value-type value))))))
225 #!-sb-fluid (declaim (inline null-alien))
226 (defun null-alien (x)
227 #!+sb-doc
228 "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
229 (zerop (sap-int (alien-sap x))))
231 (defmacro sap-alien (sap type &environment env)
232 #!+sb-doc
233 "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
234 evaluated.) TYPE must be pointer-like."
235 (let ((alien-type (parse-alien-type type env)))
236 (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
237 `(%sap-alien ,sap ',alien-type)
238 (error "cannot make an alien of type ~S out of a SAP" type))))
240 (defun %sap-alien (sap type)
241 (declare (type system-area-pointer sap)
242 (type alien-type type))
243 (make-alien-value :sap sap :type type))
245 (defun alien-sap (alien)
246 #!+sb-doc
247 "Return a System-Area-Pointer pointing to Alien's data."
248 (declare (type alien-value alien))
249 (alien-value-sap alien))
251 ;;;; allocation/deallocation of heap aliens
253 (defmacro make-alien (type &optional size &environment env)
254 #!+sb-doc
255 "Allocate an alien of type TYPE in foreign heap, and return an alien
256 pointer to it. The allocated memory is not initialized, and may
257 contain garbage. The memory is allocated using malloc(3), so it can be
258 passed to foreign functions which use free(3), or released using
259 FREE-ALIEN.
261 For alien stack allocation, see macro WITH-ALIEN.
263 The TYPE argument is not evaluated. If SIZE is supplied, how it is
264 interpreted depends on TYPE:
266 * When TYPE is a foreign array type, an array of that type is
267 allocated, and a pointer to it is returned. Note that you
268 must use DEREF to first access the array through the pointer.
270 If supplied, SIZE is used as the first dimension for the array.
272 * When TYPE is any other foreign type, then an object for that
273 type is allocated, and a pointer to it is returned. So
274 (make-alien int) returns a (* int).
276 If SIZE is specified, then a block of that many objects is
277 allocated, with the result pointing to the first one.
279 Examples:
281 (defvar *foo* (make-alien (array char 10)))
282 (type-of *foo*) ; => (alien (* (array (signed 8) 10)))
283 (setf (deref (deref foo) 0) 10) ; => 10
285 (make-alien char 12) ; => (alien (* (signed 8)))"
286 (let ((alien-type (if (alien-type-p type)
287 type
288 (parse-alien-type type env))))
289 (multiple-value-bind (size-expr element-type)
290 (if (alien-array-type-p alien-type)
291 (let ((dims (alien-array-type-dimensions alien-type)))
292 (cond
293 (size
294 (unless dims
295 (error
296 "cannot override the size of zero-dimensional arrays"))
297 (when (constantp size)
298 (setf alien-type (copy-alien-array-type alien-type))
299 (setf (alien-array-type-dimensions alien-type)
300 (cons (constant-form-value size) (cdr dims)))))
301 (dims
302 (setf size (car dims)))
304 (setf size 1)))
305 (values `(* ,size ,@(cdr dims))
306 (alien-array-type-element-type alien-type)))
307 (values (or size 1) alien-type))
308 (let ((bits (alien-type-bits element-type))
309 (alignment (alien-type-alignment element-type)))
310 (unless bits
311 (error "The size of ~S is unknown."
312 (unparse-alien-type element-type)))
313 (unless alignment
314 (error "The alignment of ~S is unknown."
315 (unparse-alien-type element-type)))
316 ;; This is the one place where the %SAP-ALIEN note is quite
317 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
318 ;; cannot be optimized away.
319 `(locally (declare (muffle-conditions compiler-note))
320 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
321 (%sap-alien (%make-alien (* ,(ash (+ 7 (align-offset bits alignment)) -3)
322 (the index ,size-expr)))
323 ',(make-alien-pointer-type :to alien-type)))))))
325 (defun malloc-error (bytes errno)
326 (error 'simple-storage-condition
327 :format-control "~A: malloc() of ~S bytes failed."
328 :format-arguments (list (strerror errno) bytes)))
330 ;;; Allocate a block of memory at least BYTES bytes long and return a
331 ;;; system area pointer to it.
332 #!-sb-fluid (declaim (inline %make-alien))
333 (defun %make-alien (bytes)
334 (declare (type index bytes)
335 (optimize (sb!c:alien-funcall-saves-fp-and-pc 0)))
336 (let ((sap (alien-funcall (extern-alien "malloc"
337 (function system-area-pointer size-t))
338 bytes)))
339 (if (and (not (eql 0 bytes)) (eql 0 (sap-int sap)))
340 (malloc-error bytes (get-errno))
341 sap)))
343 #!-sb-fluid (declaim (inline free-alien))
344 (defun free-alien (alien)
345 #!+sb-doc
346 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
347 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
348 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
349 (alien-sap alien))
350 nil)
352 (declaim (type (sfunction * system-area-pointer) %make-alien-string))
353 (defun %make-alien-string (string &key (start 0) end
354 (external-format :default)
355 (null-terminate t))
356 ;; FIXME: This is slow. We want a function to get the length of the
357 ;; encoded string so we can allocate the foreign memory first and
358 ;; encode directly there.
359 (let* ((octets (string-to-octets string
360 :start start :end end
361 :external-format external-format
362 :null-terminate null-terminate))
363 (count (length octets))
364 (buf (%make-alien count)))
365 (sb!kernel:copy-ub8-to-system-area octets 0 buf 0 count)
366 buf))
368 (defun make-alien-string (string &rest rest
369 &key (start 0) end
370 (external-format :default)
371 (null-terminate t))
372 #!+sb-doc
373 "Copy part of STRING delimited by START and END into freshly
374 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
375 Returns the allocated string as a (* CHAR) alien, and the number of
376 bytes allocated as secondary value.
378 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
379 true (the default), the alien string is terminated by an additional
380 null byte."
381 (declare (ignore start end external-format null-terminate))
382 (multiple-value-bind (sap bytes)
383 (apply #'%make-alien-string string rest)
384 (values (%sap-alien sap (parse-alien-type '(* char) nil))
385 bytes)))
387 (define-compiler-macro make-alien-string (&rest args)
388 `(multiple-value-bind (sap bytes) (%make-alien-string ,@args)
389 (values (%sap-alien sap ',(parse-alien-type '(* char) nil))
390 bytes)))
392 ;;;; the SLOT operator
394 ;;; Find the field named SLOT, or die trying.
395 (defun slot-or-lose (type slot)
396 (declare (type alien-record-type type)
397 (type symbol slot))
398 (or (find slot (alien-record-type-fields type)
399 :key #'alien-record-field-name)
400 (error "There is no slot named ~S in ~S." slot type)))
402 ;;; Extract the value from the named slot from the record ALIEN. If
403 ;;; ALIEN is actually a pointer, then DEREF it first.
404 (defun slot (alien slot)
405 #!+sb-doc
406 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
407 (declare (type alien-value alien)
408 (type symbol slot)
409 (optimize (inhibit-warnings 3)))
410 (let ((type (alien-value-type alien)))
411 (etypecase type
412 (alien-pointer-type
413 (slot (deref alien) slot))
414 (alien-record-type
415 (let ((field (slot-or-lose type slot)))
416 (%alien-value (alien-value-sap alien)
417 (alien-record-field-offset field)
418 (alien-record-field-type field)))))))
420 ;;; Deposit the value in the specified slot of the record ALIEN. If
421 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
422 ;;; this when it can't figure out anything better.
423 (defun %set-slot (alien slot value)
424 (declare (type alien-value alien)
425 (type symbol slot)
426 (optimize (inhibit-warnings 3)))
427 (let ((type (alien-value-type alien)))
428 (etypecase type
429 (alien-pointer-type
430 (%set-slot (deref alien) slot value))
431 (alien-record-type
432 (let ((field (slot-or-lose type slot)))
433 (setf (%alien-value (alien-value-sap alien)
434 (alien-record-field-offset field)
435 (alien-record-field-type field))
436 value))))))
438 ;;; Compute the address of the specified slot and return a pointer to it.
439 (defun %slot-addr (alien slot)
440 (declare (type alien-value alien)
441 (type symbol slot)
442 (optimize (inhibit-warnings 3)))
443 (let ((type (alien-value-type alien)))
444 (etypecase type
445 (alien-pointer-type
446 (%slot-addr (deref alien) slot))
447 (alien-record-type
448 (let* ((field (slot-or-lose type slot))
449 (offset (alien-record-field-offset field))
450 (field-type (alien-record-field-type field)))
451 (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
452 (make-alien-pointer-type :to field-type)))))))
454 ;;;; the DEREF operator
456 ;;; This function does most of the work of the different DEREF
457 ;;; methods. It returns two values: the type and the offset (in bits)
458 ;;; of the referred-to alien.
459 (defun deref-guts (alien indices)
460 (declare (type alien-value alien)
461 (type list indices)
462 (values alien-type integer))
463 (let ((type (alien-value-type alien)))
464 (etypecase type
465 (alien-pointer-type
466 (when (cdr indices)
467 (error "too many indices when DEREF'ing ~S: ~W"
468 type
469 (length indices)))
470 (let ((element-type (alien-pointer-type-to type)))
471 (values element-type
472 (if indices
473 (* (align-offset (alien-type-bits element-type)
474 (alien-type-alignment element-type))
475 (car indices))
476 0))))
477 (alien-array-type
478 (unless (= (length indices) (length (alien-array-type-dimensions type)))
479 (error "incorrect number of indices when DEREF'ing ~S: ~W"
480 type (length indices)))
481 (labels ((frob (dims indices offset)
482 (if (null dims)
483 offset
484 (frob (cdr dims) (cdr indices)
485 (+ (if (zerop offset)
487 (* offset (car dims)))
488 (car indices))))))
489 (let ((element-type (alien-array-type-element-type type)))
490 (values element-type
491 (* (align-offset (alien-type-bits element-type)
492 (alien-type-alignment element-type))
493 (frob (alien-array-type-dimensions type)
494 indices 0)))))))))
496 ;;; Dereference the alien and return the results.
497 (defun deref (alien &rest indices)
498 #!+sb-doc
499 "Dereference an Alien pointer or array. If an array, the indices are used
500 as the indices of the array element to access. If a pointer, one index can
501 optionally be specified, giving the equivalent of C pointer arithmetic."
502 (declare (type alien-value alien)
503 (type list indices)
504 (optimize (inhibit-warnings 3)))
505 (multiple-value-bind (target-type offset) (deref-guts alien indices)
506 (%alien-value (alien-value-sap alien)
507 offset
508 target-type)))
510 (defun %set-deref (alien value &rest indices)
511 (declare (type alien-value alien)
512 (type list indices)
513 (optimize (inhibit-warnings 3)))
514 (multiple-value-bind (target-type offset) (deref-guts alien indices)
515 (setf (%alien-value (alien-value-sap alien)
516 offset
517 target-type)
518 value)))
520 (defun %deref-addr (alien &rest indices)
521 (declare (type alien-value alien)
522 (type list indices)
523 (optimize (inhibit-warnings 3)))
524 (multiple-value-bind (target-type offset) (deref-guts alien indices)
525 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
526 (make-alien-pointer-type :to target-type))))
528 ;;;; accessing heap alien variables
530 (defun %heap-alien (info)
531 (declare (type heap-alien-info info)
532 (optimize (inhibit-warnings 3)))
533 (%alien-value (heap-alien-info-sap info)
535 (heap-alien-info-type info)))
537 (defun %set-heap-alien (info value)
538 (declare (type heap-alien-info info)
539 (optimize (inhibit-warnings 3)))
540 (setf (%alien-value (heap-alien-info-sap info)
542 (heap-alien-info-type info))
543 value))
545 (defun %heap-alien-addr (info)
546 (declare (type heap-alien-info info)
547 (optimize (inhibit-warnings 3)))
548 (%sap-alien (heap-alien-info-sap info)
549 (make-alien-pointer-type :to (heap-alien-info-type info))))
551 ;;;; accessing local aliens
553 (defun make-local-alien (info)
554 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
555 (alien-sap (alien-sap alien)))
556 (finalize
557 alien
558 (lambda ()
559 (alien-funcall
560 (extern-alien "free" (function (values) system-area-pointer))
561 alien-sap))
562 :dont-save t)
563 alien))
565 (defun note-local-alien-type (info alien)
566 (declare (ignore info alien))
567 nil)
569 (defun local-alien (info alien)
570 (declare (ignore info))
571 (deref alien))
573 (defun %set-local-alien (info alien value)
574 (declare (ignore info))
575 (setf (deref alien) value))
577 (define-setf-expander local-alien (&whole whole info alien)
578 (let ((value (gensym))
579 (info-var (gensym))
580 (alloc-tmp (gensym))
581 (info (if (and (consp info)
582 (eq (car info) 'quote))
583 (second info)
584 (error "Something is wrong; local-alien-info not found: ~S"
585 whole))))
586 (values nil
588 (list value)
589 `(if (%local-alien-forced-to-memory-p ',info)
590 (%set-local-alien ',info ,alien ,value)
591 (let* ((,info-var ',(local-alien-info-type info))
592 (,alloc-tmp (deport-alloc ,value ,info-var)))
593 (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
594 (setf ,alien (deport ,alloc-tmp ,info-var)))))
595 whole)))
597 (defun %local-alien-forced-to-memory-p (info)
598 (local-alien-info-force-to-memory-p info))
600 (defun %local-alien-addr (info alien)
601 (declare (type local-alien-info info))
602 (unless (local-alien-info-force-to-memory-p info)
603 (error "~S isn't forced to memory. Something went wrong." alien))
604 alien)
606 ;; It's not mandatory that this function not exist for x86[-64],
607 ;; however for sanity, it should not, because no call to it can occur.
608 #!-(or x86 x86-64)
609 (defun dispose-local-alien (info alien)
610 (declare (ignore info))
611 (cancel-finalization alien)
612 (free-alien alien))
614 ;;;; the CAST macro
616 (defmacro cast (alien type &environment env)
617 #!+sb-doc
618 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
619 must be Alien array, pointer or function types."
620 `(%cast ,alien ',(parse-alien-type type env)))
622 (defun %cast (alien target-type)
623 (declare (type alien-value alien)
624 (type alien-type target-type)
625 (optimize (safety 2))
626 (optimize (inhibit-warnings 3)))
627 (if (or (alien-pointer-type-p target-type)
628 (alien-array-type-p target-type)
629 (alien-fun-type-p target-type))
630 (let ((alien-type (alien-value-type alien)))
631 (if (or (alien-pointer-type-p alien-type)
632 (alien-array-type-p alien-type)
633 (alien-fun-type-p alien-type))
634 (naturalize (alien-value-sap alien) target-type)
635 (error "~S cannot be casted." alien)))
636 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
638 ;;;; the ALIEN-SIZE macro
640 (defmacro alien-size (type &optional (units :bits) &environment env)
641 #!+sb-doc
642 "Return the size of the alien type TYPE. UNITS specifies the units to
643 use and can be either :BITS, :BYTES, or :WORDS."
644 (let* ((alien-type (parse-alien-type type env))
645 (bits (alien-type-bits alien-type)))
646 (if bits
647 (values (ceiling bits
648 (ecase units
649 (:bits 1)
650 (:bytes sb!vm:n-byte-bits)
651 (:words sb!vm:n-word-bits))))
652 (error "unknown size for alien type ~S"
653 (unparse-alien-type alien-type)))))
655 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
657 (defun coerce-to-interpreted-function (lambda-form)
658 (let (#!+sb-eval
659 (*evaluator-mode* :interpret))
660 (coerce lambda-form 'function)))
662 (defun naturalize (alien type)
663 (declare (type alien-type type))
664 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
665 alien type))
667 (defun deport (value type)
668 (declare (type alien-type type))
669 (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
670 value type))
672 (defun deport-alloc (value type)
673 (declare (type alien-type type))
674 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
675 value type))
677 (defun %alien-value (sap offset type)
678 (declare (type system-area-pointer sap)
679 (type unsigned-byte offset)
680 (type alien-type type))
681 (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
682 sap offset type))
684 (defun (setf %alien-value) (value sap offset type)
685 (declare (type system-area-pointer sap)
686 (type unsigned-byte offset)
687 (type alien-type type))
688 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
689 value sap offset type))
691 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
693 (defun alien-funcall (alien &rest args)
694 #!+sb-doc
695 "Call the foreign function ALIEN with the specified arguments. ALIEN's
696 type specifies the argument and result types."
697 (declare (type alien-value alien))
698 (let ((type (alien-value-type alien)))
699 (typecase type
700 (alien-pointer-type
701 (apply #'alien-funcall (deref alien) args))
702 (alien-fun-type
703 (unless (= (length (alien-fun-type-arg-types type))
704 (length args))
705 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
706 type
707 (length (alien-fun-type-arg-types type))
708 (length args)))
709 (let ((stub (alien-fun-type-stub type)))
710 (unless stub
711 (setf stub
712 (let ((fun (sb!xc:gensym "FUN"))
713 (parms (make-gensym-list (length args))))
714 (compile nil
715 `(lambda (,fun ,@parms)
716 (declare (optimize (sb!c::insert-step-conditions 0)))
717 (declare (type (alien ,type) ,fun))
718 (alien-funcall ,fun ,@parms)))))
719 (setf (alien-fun-type-stub type) stub))
720 (apply stub alien args)))
722 (error "~S is not an alien function." alien)))))
724 (defmacro define-alien-routine (name result-type
725 &rest args
726 &environment lexenv)
727 #!+sb-doc
728 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
730 Define a foreign interface function for the routine with the specified NAME.
731 Also automatically DECLAIM the FTYPE of the defined function.
733 NAME may be either a string, a symbol, or a list of the form (string symbol).
735 RETURN-TYPE is the alien type for the function return value. VOID may be
736 used to specify a function with no result.
738 The remaining forms specify individual arguments that are passed to the
739 routine. ARG-NAME is a symbol that names the argument, primarily for
740 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
741 way that the argument is passed.
744 An :IN argument is simply passed by value. The value to be passed is
745 obtained from argument(s) to the interface function. No values are
746 returned for :In arguments. This is the default mode.
748 :OUT
749 The specified argument type must be a pointer to a fixed sized object.
750 A pointer to a preallocated object is passed to the routine, and the
751 the object is accessed on return, with the value being returned from
752 the interface function. :OUT and :IN-OUT cannot be used with pointers
753 to arrays, records or functions.
755 :COPY
756 This is similar to :IN, except that the argument values are stored
757 on the stack, and a pointer to the object is passed instead of
758 the value itself.
760 :IN-OUT
761 This is a combination of :OUT and :COPY. A pointer to the argument is
762 passed, with the object being initialized from the supplied argument
763 and the return value being determined by accessing the object on
764 return."
765 (multiple-value-bind (lisp-name alien-name)
766 (pick-lisp-and-alien-names name)
767 (collect ((docs) (lisp-args) (lisp-arg-types)
768 (lisp-result-types
769 (cond ((eql result-type 'void)
770 ;; What values does a function return, if it
771 ;; returns no values? Exactly one - NIL. -- APD,
772 ;; 2003-03-02
773 (list 'null))
775 ;; FIXME: Check for VALUES.
776 (list `(alien ,result-type)))))
777 (arg-types) (alien-vars)
778 (alien-args) (results))
779 (dolist (arg args)
780 (if (stringp arg)
781 (docs arg)
782 (destructuring-bind (name type &optional (style :in)) arg
783 (unless (member style '(:in :copy :out :in-out))
784 (error "bogus argument style ~S in ~S" style arg))
785 (when (and (member style '(:out :in-out))
786 (typep (parse-alien-type type lexenv)
787 'alien-pointer-type))
788 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
789 type))
790 (let (arg-type)
791 (cond ((eq style :in)
792 (setq arg-type type)
793 (alien-args name))
795 (setq arg-type `(* ,type))
796 (if (eq style :out)
797 (alien-vars `(,name ,type))
798 (alien-vars `(,name ,type ,name)))
799 (alien-args `(addr ,name))))
800 (arg-types arg-type)
801 (unless (eq style :out)
802 (lisp-args name)
803 (lisp-arg-types t
804 ;; FIXME: It should be something
805 ;; like `(ALIEN ,ARG-TYPE), except
806 ;; for we also accept SAPs where
807 ;; pointers are required.
809 (when (or (eq style :out) (eq style :in-out))
810 (results name)
811 (lisp-result-types `(alien ,type))))))
812 `(progn
813 ;; The theory behind this automatic DECLAIM is that (1) if
814 ;; you're calling C, static typing is what you're doing
815 ;; anyway, and (2) such a declamation can be (especially for
816 ;; alien values) both messy to do by hand and very important
817 ;; for performance of later code which uses the return value.
818 (declaim (ftype (function ,(lisp-arg-types)
819 (values ,@(lisp-result-types) &optional))
820 ,lisp-name))
821 (defun ,lisp-name ,(lisp-args)
822 ,@(docs)
823 (with-alien
824 ((,lisp-name (function ,result-type ,@(arg-types))
825 :extern ,alien-name)
826 ,@(alien-vars))
827 ,@(if (eq 'void result-type)
828 `((alien-funcall ,lisp-name ,@(alien-args))
829 (values nil ,@(results)))
830 `((values (alien-funcall ,lisp-name ,@(alien-args))
831 ,@(results))))))))))
833 (defun alien-typep (object type)
834 #!+sb-doc
835 "Return T iff OBJECT is an alien of type TYPE."
836 (let ((lisp-rep-type (compute-lisp-rep-type type)))
837 (if lisp-rep-type
838 (typep object lisp-rep-type)
839 (and (alien-value-p object)
840 (alien-subtype-p (alien-value-type object) type)))))
842 (defun alien-value-typep (object type)
843 (when (alien-value-p object)
844 (alien-subtype-p (alien-value-type object) type)))
846 ;;;; ALIEN CALLBACKS
847 ;;;;
848 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
850 (defvar *alien-callback-info* nil
851 #!+sb-doc
852 "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
853 information we need to manipulate callbacks after their creation. Used for
854 changing the lisp-side function they point to, invalidation, etc.")
856 (defstruct callback-info
857 specifier
858 function ; NULL if invalid
859 wrapper
860 index)
862 (defun callback-info-key (info)
863 (cons (callback-info-specifier info) (callback-info-function info)))
865 (defun alien-callback-info (alien)
866 (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
868 (defvar *alien-callbacks* (make-hash-table :test #'equal)
869 #!+sb-doc
870 "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
871 memoization: we don't create new callbacks if one pointing to the correct
872 function with the same specifier already exists.")
874 (defvar *alien-callback-wrappers* (make-hash-table :test #'equal)
875 #!+sb-doc
876 "Cache of existing lisp wrappers, indexed with SPECIFER. Used for memoization:
877 we don't create new wrappers if one for the same specifier already exists.")
879 (defvar *alien-callback-trampolines* (make-array 32 :fill-pointer 0 :adjustable t)
880 #!+sb-doc
881 "Lisp trampoline store: assembler wrappers contain indexes to this, and
882 ENTER-ALIEN-CALLBACK pulls the corresponding trampoline out and calls it.")
884 (defun %alien-callback-sap (specifier result-type argument-types function wrapper
885 &optional call-type)
886 (declare #!-x86 (ignore call-type))
887 (let ((key (list specifier function)))
888 (or (gethash key *alien-callbacks*)
889 (setf (gethash key *alien-callbacks*)
890 (let* ((index (fill-pointer *alien-callback-trampolines*))
891 ;; Aside from the INDEX this is known at
892 ;; compile-time, which could be utilized by
893 ;; having the two-stage assembler tramp &
894 ;; wrapper mentioned in [1] above: only the
895 ;; per-function tramp would need assembler at
896 ;; runtime. Possibly we could even pregenerate
897 ;; the code and just patch the index in later.
898 (assembler-wrapper
899 (alien-callback-assembler-wrapper
900 index result-type argument-types
901 #!+x86
902 (if (eq call-type :stdcall)
903 (ceiling
904 (apply #'+
905 (mapcar 'alien-type-word-aligned-bits
906 argument-types))
908 0))))
909 (vector-push-extend
910 (alien-callback-lisp-trampoline wrapper function)
911 *alien-callback-trampolines*)
912 ;; Assembler-wrapper is static, so sap-taking is safe.
913 (let ((sap (vector-sap assembler-wrapper)))
914 (push (cons sap (make-callback-info :specifier specifier
915 :function function
916 :wrapper wrapper
917 :index index))
918 *alien-callback-info*)
919 sap))))))
921 (defun alien-callback-lisp-trampoline (wrapper function)
922 (declare (function wrapper) (optimize speed))
923 (lambda (args-pointer result-pointer)
924 (funcall wrapper args-pointer result-pointer function)))
926 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
927 (let* ((arguments (make-gensym-list (length argument-types)))
928 (argument-names arguments)
929 (argument-specs (cddr specifier)))
930 `(lambda (args-pointer result-pointer function)
931 ;; FIXME: the saps are not gc safe
932 (let ((args-sap (int-sap
933 (sb!kernel:get-lisp-obj-address args-pointer)))
934 (res-sap (int-sap
935 (sb!kernel:get-lisp-obj-address result-pointer))))
936 (declare (ignorable args-sap res-sap))
937 (with-alien
938 ,(loop
939 with offset = 0
940 for spec in argument-specs
941 collect `(,(pop argument-names) ,spec
942 :local ,(alien-callback-accessor-form
943 spec 'args-sap offset))
944 do (incf offset (alien-callback-argument-bytes spec env)))
945 ,(flet ((store (spec real-type)
946 (if spec
947 `(setf (deref (sap-alien res-sap (* ,spec)))
948 ,(if real-type
949 `(the ,real-type
950 (funcall function ,@arguments))
951 `(funcall function ,@arguments)))
952 `(funcall function ,@arguments))))
953 (cond ((alien-void-type-p result-type)
954 (store nil nil))
955 ((alien-integer-type-p result-type)
956 ;; Integer types should be padded out to a full
957 ;; register width, to comply with most ABI calling
958 ;; conventions, but should be typechecked on the
959 ;; declared type width, hence the following:
960 (if (alien-integer-type-signed result-type)
961 (store `(signed
962 ,(alien-type-word-aligned-bits result-type))
963 `(signed-byte ,(alien-type-bits result-type)))
964 (store
965 `(unsigned
966 ,(alien-type-word-aligned-bits result-type))
967 `(unsigned-byte ,(alien-type-bits result-type)))))
969 (store (unparse-alien-type result-type) nil))))))
970 (values))))
972 (defun invalid-alien-callback (&rest arguments)
973 (declare (ignore arguments))
974 (error "Invalid alien callback called."))
976 (defun parse-callback-specification (result-type lambda-list)
977 (values
978 `(function ,result-type ,@(mapcar #'second lambda-list))
979 (mapcar #'first lambda-list)))
981 (defun parse-alien-ftype (specifier env)
982 (destructuring-bind (function result-type &rest argument-types)
983 specifier
984 (aver (eq 'function function))
985 (multiple-value-bind (bare-result-type calling-convention)
986 (typecase result-type
987 ((cons calling-convention *)
988 (values (second result-type) (first result-type)))
989 (t result-type))
990 (values (let ((*values-type-okay* t))
991 (parse-alien-type bare-result-type env))
992 (mapcar (lambda (spec)
993 (parse-alien-type spec env))
994 argument-types)
995 calling-convention))))
997 (defun alien-void-type-p (type)
998 (and (alien-values-type-p type) (not (alien-values-type-values type))))
1000 (defun alien-type-word-aligned-bits (type)
1001 (align-offset (alien-type-bits type) sb!vm:n-word-bits))
1003 (defun alien-callback-argument-bytes (spec env)
1004 (let ((type (parse-alien-type spec env)))
1005 (if (or (alien-integer-type-p type)
1006 (alien-float-type-p type)
1007 (alien-pointer-type-p type)
1008 (alien-system-area-pointer-type-p type))
1009 (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
1010 (error "Unsupported callback argument type: ~A" type))))
1012 (defun enter-alien-callback (index return arguments)
1013 (funcall (aref *alien-callback-trampolines* index)
1014 return
1015 arguments))
1017 ;;; To ensure that callback wrapper functions continue working even
1018 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
1019 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
1020 (defvar *enter-alien-callback* #'enter-alien-callback)
1022 ;;;; interface (not public, yet) for alien callbacks
1024 (defmacro alien-callback (specifier function &environment env)
1025 #!+sb-doc
1026 "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
1027 an alien function as a pointer to the FUNCTION. If a callback for the given
1028 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
1029 one."
1030 ;; Pull out as much work as is convenient to macro-expansion time, specifically
1031 ;; everything that can be done given just the SPECIFIER and ENV.
1032 (multiple-value-bind (result-type argument-types call-type)
1033 (parse-alien-ftype specifier env)
1034 `(%sap-alien
1035 (%alien-callback-sap ',specifier ',result-type ',argument-types
1036 ,function
1037 (or (gethash ',specifier *alien-callback-wrappers*)
1038 (setf (gethash ',specifier *alien-callback-wrappers*)
1039 (compile nil
1040 ',(alien-callback-lisp-wrapper-lambda
1041 specifier result-type argument-types env))))
1042 ,call-type)
1043 ',(parse-alien-type specifier env))))
1045 (defun alien-callback-p (alien)
1046 #!+sb-doc
1047 "Returns true if the alien is associated with a lisp-side callback,
1048 and a secondary return value of true if the callback is still valid."
1049 (let ((info (alien-callback-info alien)))
1050 (when info
1051 (values t (and (callback-info-function info) t)))))
1053 (defun alien-callback-function (alien)
1054 #!+sb-doc
1055 "Returns the lisp function designator associated with the callback."
1056 (let ((info (alien-callback-info alien)))
1057 (when info
1058 (callback-info-function info))))
1060 (defun (setf alien-callback-function) (function alien)
1061 #!+sb-doc
1062 "Changes the lisp function designated by the callback."
1063 (let ((info (alien-callback-info alien)))
1064 (unless info
1065 (error "Not an alien callback: ~S" alien))
1066 ;; sap cache
1067 (let ((key (callback-info-key info)))
1068 (remhash key *alien-callbacks*)
1069 (setf (gethash key *alien-callbacks*) (alien-sap alien)))
1070 ;; trampoline
1071 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1072 (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
1073 ;; metadata
1074 (setf (callback-info-function info) function)
1075 function))
1077 (defun invalidate-alien-callback (alien)
1078 #!+sb-doc
1079 "Invalidates the callback designated by the alien, if any, allowing the
1080 associated lisp function to be GC'd, and causing further calls to the same
1081 callback signal an error."
1082 (let ((info (alien-callback-info alien)))
1083 (when (and info (callback-info-function info))
1084 ;; sap cache
1085 (remhash (callback-info-key info) *alien-callbacks*)
1086 ;; trampoline
1087 (setf (aref *alien-callback-trampolines* (callback-info-index info))
1088 #'invalid-alien-callback)
1089 ;; metadata
1090 (setf (callback-info-function info) nil)
1091 t)))
1093 ;;; FIXME: This call assembles a new callback for every closure,
1094 ;;; which sucks hugely. ...not that I can think of an obvious
1095 ;;; solution. Possibly maybe we could write a generalized closure
1096 ;;; callback analogous to closure_tramp, and share the actual wrapper?
1098 ;;; For lambdas that result in simple-funs we get the callback from
1099 ;;; the cache on subsequent calls.
1100 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
1101 (multiple-value-bind (specifier lambda-list)
1102 (parse-callback-specification result-type typed-lambda-list)
1103 `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
1105 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
1106 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
1107 ;;; the FDEFINITION should invalidate the callback, and redefining the
1108 ;;; callback should change existing callbacks to point to the new defintion.
1109 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
1110 #!+sb-doc
1111 "Defines #'NAME as a function with the given body and lambda-list, and NAME as
1112 the alien callback for that function with the given alien type."
1113 (declare (symbol name))
1114 (multiple-value-bind (specifier lambda-list)
1115 (parse-callback-specification result-type typed-lambda-list)
1116 `(progn
1117 (defun ,name ,lambda-list ,@forms)
1118 (defparameter ,name (alien-callback ,specifier #',name)))))