Record XREFs for symbols that name functions.
[sbcl.git] / src / code / target-alieneval.lisp
blobc9371fd53d73d9d5d10bc0cf1d97d74aa54f3271
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 (typecase 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 (gensym "VAR"))
159 (initval (if initial-value (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 (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
266 (make-alien-array-type
267 :dimensions (cons (constant-form-value size) (cdr dims))
268 :element-type (alien-array-type-element-type alien-type)
269 :bits (alien-type-bits alien-type)
270 :alignment (alien-type-alignment alien-type)))))
271 (dims
272 (setf size (car dims)))
274 (setf size 1)))
275 (values `(* ,size ,@(cdr dims))
276 (alien-array-type-element-type alien-type)))
277 (values (or size 1) alien-type))
278 (let ((bits (alien-type-bits element-type))
279 (alignment (alien-type-alignment element-type)))
280 (unless bits
281 (error "The size of ~S is unknown."
282 (unparse-alien-type element-type)))
283 (unless alignment
284 (error "The alignment of ~S is unknown."
285 (unparse-alien-type element-type)))
286 ;; This is the one place where the %SAP-ALIEN note is quite
287 ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
288 ;; cannot be optimized away.
289 `(locally (declare (muffle-conditions compiler-note))
290 ;; FIXME: Do we really need the ASH/+7 here after ALIGN-OFFSET?
291 (%sap-alien (%make-alien (* ,(ash (+ 7 (align-offset bits alignment)) -3)
292 (the index ,size-expr)))
293 ',(make-alien-pointer-type :to alien-type)))))))
295 (defun malloc-error (bytes)
296 (error 'simple-storage-condition
297 :format-control "~A: malloc() of ~S bytes failed."
298 :format-arguments (list (strerror (get-errno)) bytes)))
300 ;;; Allocate a block of memory at least BYTES bytes long and return a
301 ;;; system area pointer to it.
302 (declaim (inline %make-alien))
303 (defun %make-alien (bytes)
304 (declare (type index bytes)
305 (optimize (sb-c:alien-funcall-saves-fp-and-pc 0)))
306 (let ((sap (alien-funcall (extern-alien "malloc"
307 (function system-area-pointer size-t))
308 bytes)))
309 (if (and (eql 0 (sap-int sap)) (not (eql 0 bytes)))
310 (malloc-error bytes)
311 sap)))
313 #+c-stack-is-control-stack
314 (declaim (inline invoke-with-saved-fp))
315 ;;; On :c-stack-is-control-stack platforms, this DEFUN must appear prior to the
316 ;;; first cross-compile-time use of ALIEN-FUNCALL, the transform of which is
317 ;;; an invocation of INVOKE-WITH-SAVED-FP, which should be inlined.
318 #+c-stack-is-control-stack
319 (defun invoke-with-saved-fp (fn)
320 (declare (muffle-conditions compiler-note)
321 (optimize (speed 3)))
322 ;; No need to link to the previous value, it can be fetched from the binding stack.
323 (let ((*saved-fp* (sb-c::current-fp-fixnum)))
324 (funcall fn)))
326 (declaim (inline free-alien))
327 (defun free-alien (alien)
328 "Dispose of the storage pointed to by ALIEN. The ALIEN must have been
329 allocated by MAKE-ALIEN, MAKE-ALIEN-STRING or malloc(3)."
330 (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
331 (alien-sap alien))
332 nil)
334 (declaim (type (function * (values system-area-pointer index))
335 %make-alien-string))
336 (defun %make-alien-string (string &key (start 0) end
337 (external-format :default)
338 (null-terminate t))
339 ;; FIXME: This is slow. We want a function to get the length of the
340 ;; encoded string so we can allocate the foreign memory first and
341 ;; encode directly there.
342 (let* ((octets (string-to-octets string
343 :start start :end end
344 :external-format external-format
345 :null-terminate null-terminate))
346 (count (length octets))
347 (buf (%make-alien count)))
348 (sb-kernel:copy-ub8-to-system-area octets 0 buf 0 count)
349 (values buf count)))
351 (defun make-alien-string (string &rest rest
352 &key (start 0) end
353 (external-format :default)
354 (null-terminate t))
355 "Copy part of STRING delimited by START and END into freshly
356 allocated foreign memory, freeable using free(3) or FREE-ALIEN.
357 Returns the allocated string as a (* CHAR) alien, and the number of
358 bytes allocated as secondary value.
360 The string is encoded using EXTERNAL-FORMAT. If NULL-TERMINATE is
361 true (the default), the alien string is terminated by an additional
362 null byte."
363 (declare (ignore start end external-format null-terminate))
364 (multiple-value-bind (sap bytes)
365 (apply #'%make-alien-string string rest)
366 (values (%sap-alien sap (parse-alien-type '(* char) nil))
367 bytes)))
369 (define-compiler-macro make-alien-string (&rest args)
370 `(multiple-value-bind (sap bytes) (%make-alien-string ,@args)
371 (values (%sap-alien sap ',(parse-alien-type '(* char) nil))
372 bytes)))
374 ;;;; the SLOT operator
376 ;;; Find the field named SLOT, or die trying.
377 (defun slot-or-lose (type slot)
378 (declare (type alien-record-type type)
379 (type symbol slot))
380 (or (find slot (alien-record-type-fields type)
381 :key #'alien-record-field-name)
382 (error "There is no slot named ~S in ~S." slot type)))
384 ;;; Extract the value from the named slot from the record ALIEN. If
385 ;;; ALIEN is actually a pointer, then DEREF it first.
386 (defun slot (alien slot)
387 "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
388 (declare (type alien-value alien)
389 (type symbol slot))
390 (let ((type (alien-value-type alien)))
391 (etypecase type
392 (alien-pointer-type
393 (slot (deref alien) slot))
394 (alien-record-type
395 (let ((field (slot-or-lose type slot)))
396 (%alien-value (alien-value-sap alien)
397 (alien-record-field-offset field)
398 (alien-record-field-type field)))))))
400 ;;; Deposit the value in the specified slot of the record ALIEN. If
401 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
402 ;;; this when it can't figure out anything better.
403 (defun %set-slot (alien slot value)
404 (declare (type alien-value alien)
405 (type symbol slot))
406 (let ((type (alien-value-type alien)))
407 (etypecase type
408 (alien-pointer-type
409 (%set-slot (deref alien) slot value))
410 (alien-record-type
411 (let ((field (slot-or-lose type slot)))
412 (setf (%alien-value (alien-value-sap alien)
413 (alien-record-field-offset field)
414 (alien-record-field-type field))
415 value))))))
417 ;;; Compute the address of the specified slot and return a pointer to it.
418 (defun %slot-addr (alien slot)
419 (declare (type alien-value alien)
420 (type symbol slot))
421 (let ((type (alien-value-type alien)))
422 (etypecase type
423 (alien-pointer-type
424 (%slot-addr (deref alien) slot))
425 (alien-record-type
426 (let* ((field (slot-or-lose type slot))
427 (offset (alien-record-field-offset field))
428 (field-type (alien-record-field-type field)))
429 (%sap-alien (sap+ (alien-sap alien) (/ offset sb-vm:n-byte-bits))
430 (make-alien-pointer-type :to field-type)))))))
432 ;;;; the DEREF operator
434 ;;; This function does most of the work of the different DEREF
435 ;;; methods. It returns two values: the type and the offset (in bits)
436 ;;; of the referred-to alien.
437 (defun deref-guts (alien indices)
438 (declare (type alien-value alien)
439 (type list indices)
440 (values alien-type integer))
441 (let ((type (alien-value-type alien)))
442 (etypecase type
443 (alien-pointer-type
444 (when (cdr indices)
445 (error "too many indices when DEREF'ing ~S: ~W"
446 type
447 (length indices)))
448 (let ((element-type (alien-pointer-type-to type)))
449 (values element-type
450 (if indices
451 (* (align-offset (alien-type-bits element-type)
452 (alien-type-alignment element-type))
453 (car indices))
454 0))))
455 (alien-array-type
456 (unless (= (length indices) (length (alien-array-type-dimensions type)))
457 (error "incorrect number of indices when DEREF'ing ~S: ~W"
458 type (length indices)))
459 (labels ((frob (dims indices offset)
460 (if (null dims)
461 offset
462 (frob (cdr dims) (cdr indices)
463 (+ (if (zerop offset)
465 (* offset (car dims)))
466 (car indices))))))
467 (let ((element-type (alien-array-type-element-type type)))
468 (values element-type
469 (* (align-offset (alien-type-bits element-type)
470 (alien-type-alignment element-type))
471 (frob (alien-array-type-dimensions type)
472 indices 0)))))))))
474 ;;; Dereference the alien and return the results.
475 (defun deref (alien &rest indices)
476 "Dereference an Alien pointer or array. If an array, the indices are used
477 as the indices of the array element to access. If a pointer, one index can
478 optionally be specified, giving the equivalent of C pointer arithmetic."
479 (declare (type alien-value alien)
480 (type list indices))
481 (multiple-value-bind (target-type offset) (deref-guts alien indices)
482 (%alien-value (alien-value-sap alien)
483 offset
484 target-type)))
486 (defun %set-deref (alien value &rest indices)
487 (declare (type alien-value alien)
488 (type list indices))
489 (multiple-value-bind (target-type offset) (deref-guts alien indices)
490 (setf (%alien-value (alien-value-sap alien)
491 offset
492 target-type)
493 value)))
495 (defun %deref-addr (alien &rest indices)
496 (declare (type alien-value alien)
497 (type list indices))
498 (multiple-value-bind (target-type offset) (deref-guts alien indices)
499 (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb-vm:n-byte-bits))
500 (make-alien-pointer-type :to target-type))))
502 ;;;; accessing heap alien variables
504 (defun %heap-alien (info)
505 (declare (type heap-alien-info info))
506 (%alien-value (heap-alien-info-sap info)
508 (heap-alien-info-type info)))
510 (defun %set-heap-alien (info value)
511 (declare (type heap-alien-info info))
512 (setf (%alien-value (heap-alien-info-sap info)
514 (heap-alien-info-type info))
515 value))
517 (defun %heap-alien-addr (info)
518 (declare (type heap-alien-info info))
519 (%sap-alien (heap-alien-info-sap info)
520 (make-alien-pointer-type :to (heap-alien-info-type info))))
522 ;;;; accessing local aliens
524 (defun make-local-alien (info)
525 (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
526 (alien-sap (alien-sap alien)))
527 (finalize
528 alien
529 (lambda ()
530 (alien-funcall
531 (extern-alien "free" (function (values) system-area-pointer))
532 alien-sap))
533 :dont-save t)
534 alien))
536 (defun note-local-alien-type (info alien)
537 (declare (ignore info alien))
538 nil)
540 (defun local-alien (info alien)
541 (declare (ignore info))
542 (deref alien))
544 (defun %set-local-alien (info alien value)
545 (declare (ignore info))
546 (setf (deref alien) value))
548 (define-setf-expander local-alien (&whole whole info alien)
549 (let ((value (gensym))
550 (info-var (gensym))
551 (alloc-tmp (gensym))
552 (info (if (and (consp info)
553 (eq (car info) 'quote))
554 (second info)
555 (error "Something is wrong; local-alien-info not found: ~S"
556 whole))))
557 (values nil
559 (list value)
560 `(if (%local-alien-forced-to-memory-p ',info)
561 (%set-local-alien ',info ,alien ,value)
562 (let* ((,info-var ',(local-alien-info-type info))
563 (,alloc-tmp (deport-alloc ,value ,info-var)))
564 (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
565 (setf ,alien (deport ,alloc-tmp ,info-var)))))
566 whole)))
568 (defun %local-alien-forced-to-memory-p (info)
569 (local-alien-info-force-to-memory-p info))
571 (defun %local-alien-addr (info alien)
572 (declare (type local-alien-info info))
573 (unless (local-alien-info-force-to-memory-p info)
574 (error "~S isn't forced to memory. Something went wrong." alien))
575 alien)
578 ;;;; the ADDR macro
580 (defmacro addr (expr &environment env)
581 "Return an Alien pointer to the data addressed by Expr, which must be a call
582 to SLOT or DEREF, or a reference to an Alien variable."
583 (let ((form (%macroexpand expr env)))
584 (or (typecase form
585 (cons
586 (case (car form)
587 (slot
588 (cons '%slot-addr (cdr form)))
589 (deref
590 (cons '%deref-addr (cdr form)))
591 (%heap-alien
592 (cons '%heap-alien-addr (cdr form)))
593 (local-alien
594 (let ((info (let ((info-arg (second form)))
595 (and (consp info-arg)
596 (eq (car info-arg) 'quote)
597 (second info-arg)))))
598 (unless (local-alien-info-p info)
599 (error "Something is wrong, LOCAL-ALIEN-INFO not found: ~S"
600 form))
601 (setf (local-alien-info-force-to-memory-p info) t))
602 (cons '%local-alien-addr (cdr form)))))
603 (symbol
604 (let ((kind (info :variable :kind form)))
605 (when (eq kind :alien)
606 `(%heap-alien-addr ',(info :variable :alien-info form))))))
607 (error "~S is not a valid L-value." form))))
609 (push '("SB-ALIEN" define-alien-type-class define-alien-type-method)
610 *!removable-symbols*)
613 ;;;; the CAST macro
615 (defmacro cast (alien type &environment env)
616 "Convert ALIEN to an Alien of the specified TYPE (not evaluated.) Both types
617 must be Alien array, pointer or function types."
618 `(%cast ,alien ',(parse-alien-type type env)))
620 (defun %cast (alien target-type)
621 (declare (type alien-value alien)
622 (type alien-type target-type)
623 (optimize (safety 2)))
624 (if (or (alien-pointer-type-p target-type)
625 (alien-array-type-p target-type)
626 (alien-fun-type-p target-type))
627 (let ((alien-type (alien-value-type alien)))
628 (if (or (alien-pointer-type-p alien-type)
629 (alien-array-type-p alien-type)
630 (alien-fun-type-p alien-type))
631 (naturalize (alien-value-sap alien) target-type)
632 (error "~S cannot be casted." alien)))
633 (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
635 ;;;; the ALIEN-SIZE macro
637 (defmacro alien-size (type &optional (units :bits) &environment env)
638 "Return the size of the alien type TYPE. UNITS specifies the units to
639 use and can be either :BITS, :BYTES, or :WORDS."
640 (let* ((alien-type (parse-alien-type type env))
641 (bits (alien-type-bits alien-type)))
642 (if bits
643 (values (ceiling bits
644 (ecase units
645 (:bits 1)
646 (:bytes sb-vm:n-byte-bits)
647 (:words sb-vm:n-word-bits))))
648 (error "unknown size for alien type ~S"
649 (unparse-alien-type alien-type)))))
651 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
653 ;;; There is little cost to making an interpreted function,
654 ;;; however it is even better if we can share the function object,
655 ;;; especially with sb-fasteval which avoids work on repeated invocations.
656 ;;; sb-eval doesn't optimize its IR in the same way,
657 ;;; but this is still a boon from a memory consumption stance.
659 ;;; GLOBALDB-SXHASHOID serves as a nice hash function for this purpose anyway.
660 ;;; Arguably we could key the cache off the internalized alien-type object
661 ;;; which induced creation of an interpreted lambda, rather than the s-expr,
662 ;;; but we'd need to get the TYPE and the method {NATURALIZE, DEPORT, etc} here,
663 ;;; so it would be a more invasive change.
665 (defun-cached (coerce-to-interpreted-function
666 :hash-bits 8 :hash-function #'globaldb-sxhashoid)
667 ((lambda-form equal))
668 (let (#+(or sb-eval sb-fasteval)
669 (*evaluator-mode* :interpret))
670 (coerce lambda-form 'function)))
672 (defun naturalize (alien type)
673 (declare (type alien-type type))
674 (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
675 alien type))
677 (defun deport (value type)
678 (declare (type alien-type type))
679 (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
680 value type))
682 (defun deport-alloc (value type)
683 (declare (type alien-type type))
684 (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
685 value type))
687 (defun %alien-value (sap offset type)
688 (declare (type system-area-pointer sap)
689 (type unsigned-byte offset)
690 (type alien-type type))
691 (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
692 sap offset type))
694 (defun (setf %alien-value) (value sap offset type)
695 (declare (type system-area-pointer sap)
696 (type unsigned-byte offset)
697 (type alien-type type))
698 (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
699 value sap offset type))
701 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
703 (defun alien-funcall (alien &rest args)
704 "Call the foreign function ALIEN with the specified arguments. ALIEN's
705 type specifies the argument and result types."
706 (declare (type alien-value alien))
707 (let ((type (alien-value-type alien)))
708 (typecase type
709 (alien-pointer-type
710 (apply #'alien-funcall (deref alien) args))
711 (alien-fun-type
712 (unless (= (length (alien-fun-type-arg-types type))
713 (length args))
714 (error "wrong number of arguments for ~S~%expected ~W, got ~W"
715 type
716 (length (alien-fun-type-arg-types type))
717 (length args)))
718 (let ((stub (alien-fun-type-stub type)))
719 (unless stub
720 (setf stub
721 (let ((fun (gensym "FUN"))
722 (parms (make-gensym-list (length args))))
723 (compile nil
724 `(lambda (,fun ,@parms)
725 (declare (optimize (sb-c:insert-step-conditions 0)))
726 (declare (type (alien ,type) ,fun))
727 (alien-funcall ,fun ,@parms)))))
728 (setf (alien-fun-type-stub type) stub))
729 (apply stub alien args)))
731 (error "~S is not an alien function." alien)))))
733 (defmacro define-alien-routine (name result-type
734 &rest args
735 &environment lexenv)
736 "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
738 Define a foreign interface function for the routine with the specified NAME.
739 Also automatically DECLAIM the FTYPE of the defined function.
741 NAME may be either a string, a symbol, or a list of the form (string symbol).
743 RETURN-TYPE is the alien type for the function return value. VOID may be
744 used to specify a function with no result.
746 The remaining forms specify individual arguments that are passed to the
747 routine. ARG-NAME is a symbol that names the argument, primarily for
748 documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
749 way that the argument is passed.
752 An :IN argument is simply passed by value. The value to be passed is
753 obtained from argument(s) to the interface function. No values are
754 returned for :In arguments. This is the default mode.
756 :OUT
757 The specified argument type must be a pointer to a fixed sized object.
758 A pointer to a preallocated object is passed to the routine, and the
759 the object is accessed on return, with the value being returned from
760 the interface function. :OUT and :IN-OUT cannot be used with pointers
761 to arrays, records or functions.
763 :COPY
764 This is similar to :IN, except that the argument values are stored
765 on the stack, and a pointer to the object is passed instead of
766 the value itself.
768 :IN-OUT
769 This is a combination of :OUT and :COPY. A pointer to the argument is
770 passed, with the object being initialized from the supplied argument
771 and the return value being determined by accessing the object on
772 return."
773 (binding* (((lisp-name alien-name) (pick-lisp-and-alien-names name))
774 ;; The local name is uninterned so that we don't preclude
775 ;; (defconstant kill 9)
776 ;; (define-alien-routine "kill" int (pid int) (sig int))
777 ;; which, if we didn't hide the local name, would get:
778 ;; "Attempt to bind a constant variable with SYMBOL-MACROLET: KILL"
779 (local-name (copy-symbol lisp-name)))
780 (collect ((docs) (lisp-args) (lisp-arg-types)
781 (lisp-result-types
782 (cond ((eql result-type 'void)
783 ;; What values does a function return, if it
784 ;; returns no values? Exactly one - NIL. -- APD,
785 ;; 2003-03-02
786 (list 'null))
788 ;; FIXME: Check for VALUES.
789 (list `(alien ,result-type)))))
790 (arg-types) (alien-vars)
791 (alien-args) (results))
792 (dolist (arg args)
793 (cond ((stringp arg)
794 (docs arg))
795 ((eq arg '&optional)
796 (arg-types arg))
798 (destructuring-bind (name type &optional (style :in)) arg
799 (unless (member style '(:in :copy :out :in-out))
800 (error "bogus argument style ~S in ~S" style arg))
801 (when (and (member style '(:out :in-out))
802 (typep (parse-alien-type type lexenv)
803 'alien-pointer-type))
804 (error "can't use :OUT or :IN-OUT on pointer-like type:~% ~S"
805 type))
806 (let (arg-type)
807 (cond ((eq style :in)
808 (setq arg-type type)
809 (alien-args name))
811 (setq arg-type `(* ,type))
812 (if (eq style :out)
813 (alien-vars `(,name ,type))
814 (alien-vars `(,name ,type ,name)))
815 (alien-args `(addr ,name))))
816 (arg-types arg-type)
817 (unless (eq style :out)
818 (lisp-args name)
819 (lisp-arg-types t
820 ;; FIXME: It should be something
821 ;; like `(ALIEN ,ARG-TYPE), except
822 ;; for we also accept SAPs where
823 ;; pointers are required.
825 (when (or (eq style :out) (eq style :in-out))
826 (results name)
827 (lisp-result-types `(alien ,type)))))))
828 `(progn
829 ;; The theory behind this automatic DECLAIM is that (1) if
830 ;; you're calling C, static typing is what you're doing
831 ;; anyway, and (2) such a declamation can be (especially for
832 ;; alien values) both messy to do by hand and very important
833 ;; for performance of later code which uses the return value.
834 (declaim (ftype (function ,(lisp-arg-types)
835 (values ,@(lisp-result-types) &optional))
836 ,lisp-name))
837 (defun ,lisp-name ,(lisp-args)
838 ,@(docs)
839 (with-alien
840 ((,local-name (function ,result-type ,@(arg-types))
841 :extern ,alien-name)
842 ,@(alien-vars))
843 ,@(if (eq 'void result-type)
844 `((alien-funcall ,local-name ,@(alien-args))
845 (values nil ,@(results)))
846 `((values (alien-funcall ,local-name ,@(alien-args))
847 ,@(results))))))))))
849 (defun alien-typep (object type)
850 "Return T iff OBJECT is an alien of type TYPE."
851 (let ((lisp-rep-type (compute-lisp-rep-type type)))
852 (if lisp-rep-type
853 (typep object lisp-rep-type)
854 (and (alien-value-p object)
855 (alien-subtype-p (alien-value-type object) type)))))
857 (defun alien-value-typep (object type)
858 (when (alien-value-p object)
859 (alien-subtype-p (alien-value-type object) type)))
861 (defun alien-void-type-p (type)
862 (and (alien-values-type-p type) (not (alien-values-type-values type))))