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