0.8.14.5: Join the foreign legion!
[sbcl.git] / src / code / target-alieneval.lisp
1 ;;;; This file contains parts of the ALIEN implementation that
2 ;;;; are not part of the compiler.
3
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.
12
13 (in-package "SB!ALIEN")
14
15 (/show0 "target-alieneval.lisp 15")
16 \f
17 ;;;; alien variables
18
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)))))
25
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)))))
33
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     (etypecase name
39       (string
40        (values (guess-lisp-name-from-alien-name name) name))
41       (symbol
42        (values name (guess-alien-name-from-lisp-name name)))
43       (list
44        (unless (proper-list-of-length-p name 2)
45          (error "badly formed alien name"))
46        (values (cadr name) (car name))))))
47
48 (defmacro define-alien-variable (name type &environment env)
49   #!+sb-doc
50   "Define NAME as an external alien variable of type TYPE. NAME should be
51    a list of a string holding the alien name and a symbol to use as the Lisp
52    name. If NAME is just a symbol or string, then the other name is guessed
53    from the one supplied."
54   (multiple-value-bind (lisp-name alien-name) (pick-lisp-and-alien-names name)
55     (with-auxiliary-alien-types env
56       (let ((alien-type (parse-alien-type type env)))
57         `(eval-when (:compile-toplevel :load-toplevel :execute)
58            ,@(when *new-auxiliary-types*
59                `((%def-auxiliary-alien-types ',*new-auxiliary-types*)))
60            (%define-alien-variable ',lisp-name
61                                    ',alien-name
62                                    ',alien-type))))))
63
64 (defmacro def-alien-variable (&rest rest)
65   (deprecation-warning 'def-alien-variable 'define-alien-variable)
66   `(define-alien-variable ,@rest))
67
68 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
69 (eval-when (:compile-toplevel :load-toplevel :execute)
70   (defun %define-alien-variable (lisp-name alien-name type)
71     (setf (info :variable :kind lisp-name) :alien)
72     (setf (info :variable :where-from lisp-name) :defined)
73     (clear-info :variable :constant-value lisp-name)
74     (setf (info :variable :alien-info lisp-name)
75           (make-heap-alien-info :type type
76                                 :sap-form `(foreign-symbol-address ',alien-name t)))))
77
78 (defmacro extern-alien (name type &environment env)
79   #!+sb-doc
80   "Access the alien variable named NAME, assuming it is of type TYPE. This
81    is SETFable."
82   (let* ((alien-name (etypecase name
83                        (symbol (guess-alien-name-from-lisp-name name))
84                        (string name)))
85          (alien-type (parse-alien-type type env))
86          (datap (not (alien-fun-type-p alien-type))))
87     `(%heap-alien ',(make-heap-alien-info
88                      :type alien-type
89                      :sap-form `(foreign-symbol-address ',alien-name ,datap)))))
90
91 (defmacro with-alien (bindings &body body &environment env)
92   #!+sb-doc
93   "Establish some local alien variables. Each BINDING is of the form:
94      VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
95    ALLOCATION should be one of:
96      :LOCAL (the default)
97        The alien is allocated on the stack, and has dynamic extent.
98      :STATIC
99        The alien is allocated on the heap, and has infinite extent. The alien
100        is allocated at load time, so the same piece of memory is used each time
101        this form executes.
102      :EXTERN
103        No alien is allocated, but VAR is established as a local name for
104        the external alien given by EXTERNAL-NAME."
105   (/show "entering WITH-ALIEN" bindings)
106   (with-auxiliary-alien-types env
107     (dolist (binding (reverse bindings))
108       (/show binding)
109       (destructuring-bind
110           (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
111           binding
112         (/show symbol type opt1 opt2)
113         (let* ((alien-type (parse-alien-type type env))
114                (datap (not (alien-fun-type-p alien-type))))
115           (/show alien-type)
116           (multiple-value-bind (allocation initial-value)
117               (if opt2p
118                   (values opt1 opt2)
119                   (case opt1
120                     (:extern
121                      (values opt1 (guess-alien-name-from-lisp-name symbol)))
122                     (:static
123                      (values opt1 nil))
124                     (t
125                      (values :local opt1))))
126             (/show allocation initial-value)
127             (setf body
128                   (ecase allocation
129                     #+nil
130                     (:static
131                      (let ((sap
132                             (make-symbol (concatenate 'string "SAP-FOR-"
133                                                       (symbol-name symbol)))))
134                        `((let ((,sap (load-time-value (%make-alien ...))))
135                            (declare (type system-area-pointer ,sap))
136                            (symbol-macrolet
137                             ((,symbol (sap-alien ,sap ,type)))
138                             ,@(when initial-value
139                                 `((setq ,symbol ,initial-value)))
140                             ,@body)))))
141                     (:extern
142                      (/show0 ":EXTERN case")
143                      (let ((info (make-heap-alien-info
144                                   :type alien-type
145                                   :sap-form `(foreign-symbol-address
146                                               ',initial-value
147                                               ,datap))))
148                        `((symbol-macrolet
149                           ((,symbol (%heap-alien ',info)))
150                           ,@body))))
151                     (:local
152                      (/show0 ":LOCAL case")
153                      (let ((var (gensym))
154                            (initval (if initial-value (gensym)))
155                            (info (make-local-alien-info :type alien-type)))
156                        (/show var initval info)
157                        `((let ((,var (make-local-alien ',info))
158                                ,@(when initial-value
159                                    `((,initval ,initial-value))))
160                            (note-local-alien-type ',info ,var)
161                            (multiple-value-prog1
162                                (symbol-macrolet
163                                 ((,symbol (local-alien ',info ,var)))
164                                 ,@(when initial-value
165                                     `((setq ,symbol ,initval)))
166                                 ,@body)
167                                (dispose-local-alien ',info ,var))))))))))))
168     (/show "revised" body)
169     (verify-local-auxiliaries-okay)
170     (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
171     `(symbol-macrolet ((&auxiliary-type-definitions&
172                         ,(append *new-auxiliary-types*
173                                  (auxiliary-type-definitions env))))
174        ,@body)))
175 \f
176 ;;;; runtime C values that don't correspond directly to Lisp types
177
178 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
179 ;;; 'cause it has to be real early in the cold-load order.
180 #!-sb-fluid (declaim (freeze-type alien-value))
181 (def!method print-object ((value alien-value) stream)
182   (print-unreadable-object (value stream)
183     (format stream
184             "~S ~S #X~8,'0X ~S ~S"
185             'alien-value
186             :sap (sap-int (alien-value-sap value))
187             :type (unparse-alien-type (alien-value-type value)))))
188
189 #!-sb-fluid (declaim (inline null-alien))
190 (defun null-alien (x)
191   #!+sb-doc
192   "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
193   (zerop (sap-int (alien-sap x))))
194
195 (defmacro sap-alien (sap type &environment env)
196   #!+sb-doc
197   "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
198    evaluated.) TYPE must be pointer-like."
199   (let ((alien-type (parse-alien-type type env)))
200     (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
201         `(%sap-alien ,sap ',alien-type)
202         (error "cannot make an alien of type ~S out of a SAP" type))))
203
204 (defun %sap-alien (sap type)
205   (declare (type system-area-pointer sap)
206            (type alien-type type))
207   (make-alien-value :sap sap :type type))
208
209 (defun alien-sap (alien)
210   #!+sb-doc
211   "Return a System-Area-Pointer pointing to Alien's data."
212   (declare (type alien-value alien))
213   (alien-value-sap alien))
214 \f
215 ;;;; allocation/deallocation of heap aliens
216
217 (defmacro make-alien (type &optional size &environment env)
218   #!+sb-doc
219   "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
220    is supplied, how it is interpreted depends on TYPE. If TYPE is an array
221    type, SIZE is used as the first dimension for the allocated array. If TYPE
222    is not an array, then SIZE is the number of elements to allocate. The
223    memory is allocated using ``malloc'', so it can be passed to foreign
224    functions which use ``free''."
225   (let ((alien-type (if (alien-type-p type)
226                         type
227                         (parse-alien-type type env))))
228     (multiple-value-bind (size-expr element-type)
229         (if (alien-array-type-p alien-type)
230             (let ((dims (alien-array-type-dimensions alien-type)))
231               (cond
232                (size
233                 (unless dims
234                   (error
235                    "cannot override the size of zero-dimensional arrays"))
236                 (when (constantp size)
237                   (setf alien-type (copy-alien-array-type alien-type))
238                   (setf (alien-array-type-dimensions alien-type)
239                         (cons (eval size) (cdr dims)))))
240                (dims
241                 (setf size (car dims)))
242                (t
243                 (setf size 1)))
244               (values `(* ,size ,@(cdr dims))
245                       (alien-array-type-element-type alien-type)))
246             (values (or size 1) alien-type))
247       (let ((bits (alien-type-bits element-type))
248             (alignment (alien-type-alignment element-type)))
249         (unless bits
250           (error "The size of ~S is unknown."
251                  (unparse-alien-type element-type)))
252         (unless alignment
253           (error "The alignment of ~S is unknown."
254                  (unparse-alien-type element-type)))
255         `(%sap-alien (%make-alien (* ,(align-offset bits alignment)
256                                      ,size-expr))
257                      ',(make-alien-pointer-type :to alien-type))))))
258
259 ;;; Allocate a block of memory at least BITS bits long and return a
260 ;;; system area pointer to it.
261 #!-sb-fluid (declaim (inline %make-alien))
262 (defun %make-alien (bits)
263   (declare (type index bits))
264   (alien-funcall (extern-alien "malloc"
265                                (function system-area-pointer unsigned))
266                  (ash (the index (+ bits 7)) -3)))
267
268 #!-sb-fluid (declaim (inline free-alien))
269 (defun free-alien (alien)
270   #!+sb-doc
271   "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
272    by MAKE-ALIEN or malloc(3)."
273   (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
274                  (alien-sap alien))
275   nil)
276 \f
277 ;;;; the SLOT operator
278
279 ;;; Find the field named SLOT, or die trying.
280 (defun slot-or-lose (type slot)
281   (declare (type alien-record-type type)
282            (type symbol slot))
283   (or (find slot (alien-record-type-fields type)
284             :key #'alien-record-field-name)
285       (error "There is no slot named ~S in ~S." slot type)))
286
287 ;;; Extract the value from the named slot from the record ALIEN. If
288 ;;; ALIEN is actually a pointer, then DEREF it first.
289 (defun slot (alien slot)
290   #!+sb-doc
291   "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
292   (declare (type alien-value alien)
293            (type symbol slot)
294            (optimize (inhibit-warnings 3)))
295   (let ((type (alien-value-type alien)))
296     (etypecase type
297       (alien-pointer-type
298        (slot (deref alien) slot))
299       (alien-record-type
300        (let ((field (slot-or-lose type slot)))
301          (extract-alien-value (alien-value-sap alien)
302                               (alien-record-field-offset field)
303                               (alien-record-field-type field)))))))
304
305 ;;; Deposit the value in the specified slot of the record ALIEN. If
306 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
307 ;;; this when it can't figure out anything better.
308 (defun %set-slot (alien slot value)
309   (declare (type alien-value alien)
310            (type symbol slot)
311            (optimize (inhibit-warnings 3)))
312   (let ((type (alien-value-type alien)))
313     (etypecase type
314       (alien-pointer-type
315        (%set-slot (deref alien) slot value))
316       (alien-record-type
317        (let ((field (slot-or-lose type slot)))
318          (deposit-alien-value (alien-value-sap alien)
319                               (alien-record-field-offset field)
320                               (alien-record-field-type field)
321                               value))))))
322
323 ;;; Compute the address of the specified slot and return a pointer to it.
324 (defun %slot-addr (alien slot)
325   (declare (type alien-value alien)
326            (type symbol slot)
327            (optimize (inhibit-warnings 3)))
328   (let ((type (alien-value-type alien)))
329     (etypecase type
330       (alien-pointer-type
331        (%slot-addr (deref alien) slot))
332       (alien-record-type
333        (let* ((field (slot-or-lose type slot))
334               (offset (alien-record-field-offset field))
335               (field-type (alien-record-field-type field)))
336          (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
337                      (make-alien-pointer-type :to field-type)))))))
338 \f
339 ;;;; the DEREF operator
340
341 ;;; This function does most of the work of the different DEREF
342 ;;; methods. It returns two values: the type and the offset (in bits)
343 ;;; of the referred-to alien.
344 (defun deref-guts (alien indices)
345   (declare (type alien-value alien)
346            (type list indices)
347            (values alien-type integer))
348   (let ((type (alien-value-type alien)))
349     (etypecase type
350       (alien-pointer-type
351        (when (cdr indices)
352          (error "too many indices when DEREF'ing ~S: ~W"
353                 type
354                 (length indices)))
355        (let ((element-type (alien-pointer-type-to type)))
356          (values element-type
357                  (if indices
358                      (* (align-offset (alien-type-bits element-type)
359                                       (alien-type-alignment element-type))
360                         (car indices))
361                      0))))
362       (alien-array-type
363        (unless (= (length indices) (length (alien-array-type-dimensions type)))
364          (error "incorrect number of indices when DEREF'ing ~S: ~W"
365                 type (length indices)))
366        (labels ((frob (dims indices offset)
367                   (if (null dims)
368                       offset
369                       (frob (cdr dims) (cdr indices)
370                         (+ (if (zerop offset)
371                                0
372                                (* offset (car dims)))
373                            (car indices))))))
374          (let ((element-type (alien-array-type-element-type type)))
375            (values element-type
376                    (* (align-offset (alien-type-bits element-type)
377                                     (alien-type-alignment element-type))
378                       (frob (alien-array-type-dimensions type)
379                         indices 0)))))))))
380
381 ;;; Dereference the alien and return the results.
382 (defun deref (alien &rest indices)
383   #!+sb-doc
384   "De-reference an Alien pointer or array. If an array, the indices are used
385    as the indices of the array element to access. If a pointer, one index can
386    optionally be specified, giving the equivalent of C pointer arithmetic."
387   (declare (type alien-value alien)
388            (type list indices)
389            (optimize (inhibit-warnings 3)))
390   (multiple-value-bind (target-type offset) (deref-guts alien indices)
391     (extract-alien-value (alien-value-sap alien)
392                          offset
393                          target-type)))
394
395 (defun %set-deref (alien value &rest indices)
396   (declare (type alien-value alien)
397            (type list indices)
398            (optimize (inhibit-warnings 3)))
399   (multiple-value-bind (target-type offset) (deref-guts alien indices)
400     (deposit-alien-value (alien-value-sap alien)
401                          offset
402                          target-type
403                          value)))
404
405 (defun %deref-addr (alien &rest indices)
406   (declare (type alien-value alien)
407            (type list indices)
408            (optimize (inhibit-warnings 3)))
409   (multiple-value-bind (target-type offset) (deref-guts alien indices)
410     (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
411                 (make-alien-pointer-type :to target-type))))
412 \f
413 ;;;; accessing heap alien variables
414
415 (defun %heap-alien (info)
416   (declare (type heap-alien-info info)
417            (optimize (inhibit-warnings 3)))
418   (extract-alien-value (eval (heap-alien-info-sap-form info))
419                        0
420                        (heap-alien-info-type info)))
421
422 (defun %set-heap-alien (info value)
423   (declare (type heap-alien-info info)
424            (optimize (inhibit-warnings 3)))
425   (deposit-alien-value (eval (heap-alien-info-sap-form info))
426                        0
427                        (heap-alien-info-type info)
428                        value))
429
430 (defun %heap-alien-addr (info)
431   (declare (type heap-alien-info info)
432            (optimize (inhibit-warnings 3)))
433   (%sap-alien (eval (heap-alien-info-sap-form info))
434               (make-alien-pointer-type :to (heap-alien-info-type info))))
435 \f
436 ;;;; accessing local aliens
437
438 (defun make-local-alien (info)
439   (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
440          (alien-sap (alien-sap alien)))
441     (finalize
442      alien
443      (lambda ()
444        (alien-funcall
445         (extern-alien "free" (function (values) system-area-pointer))
446         alien-sap)))
447     alien))
448
449 (defun note-local-alien-type (info alien)
450   (declare (ignore info alien))
451   nil)
452
453 (defun local-alien (info alien)
454   (declare (ignore info))
455   (deref alien))
456
457 (defun %set-local-alien (info alien value)
458   (declare (ignore info))
459   (setf (deref alien) value))
460
461 (define-setf-expander local-alien (&whole whole info alien)
462   (let ((value (gensym))
463         (info (if (and (consp info)
464                        (eq (car info) 'quote))
465                   (second info)
466                   (error "Something is wrong; local-alien-info not found: ~S"
467                          whole))))
468     (values nil
469             nil
470             (list value)
471             `(if (%local-alien-forced-to-memory-p ',info)
472                  (%set-local-alien ',info ,alien ,value)
473                  (setf ,alien
474                        (deport ,value ',(local-alien-info-type info))))
475             whole)))
476
477 (defun %local-alien-forced-to-memory-p (info)
478   (local-alien-info-force-to-memory-p info))
479
480 (defun %local-alien-addr (info alien)
481   (declare (type local-alien-info info))
482   (unless (local-alien-info-force-to-memory-p info)
483     (error "~S isn't forced to memory. Something went wrong." alien))
484   alien)
485
486 (defun dispose-local-alien (info alien)
487   (declare (ignore info))
488   (cancel-finalization alien)
489   (free-alien alien))
490 \f
491 ;;;; the CAST macro
492
493 (defmacro cast (alien type &environment env)
494   #!+sb-doc
495   "Convert ALIEN to an Alien of the specified TYPE (not evaluated.)  Both types
496    must be Alien array, pointer or function types."
497   `(%cast ,alien ',(parse-alien-type type env)))
498
499 (defun %cast (alien target-type)
500   (declare (type alien-value alien)
501            (type alien-type target-type)
502            (optimize (safety 2))
503            (optimize (inhibit-warnings 3)))
504   (if (or (alien-pointer-type-p target-type)
505           (alien-array-type-p target-type)
506           (alien-fun-type-p target-type))
507       (let ((alien-type (alien-value-type alien)))
508         (if (or (alien-pointer-type-p alien-type)
509                 (alien-array-type-p alien-type)
510                 (alien-fun-type-p alien-type))
511             (naturalize (alien-value-sap alien) target-type)
512             (error "~S cannot be casted." alien)))
513       (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
514 \f
515 ;;;; the ALIEN-SIZE macro
516
517 (defmacro alien-size (type &optional (units :bits) &environment env)
518   #!+sb-doc
519   "Return the size of the alien type TYPE. UNITS specifies the units to
520    use and can be either :BITS, :BYTES, or :WORDS."
521   (let* ((alien-type (parse-alien-type type env))
522          (bits (alien-type-bits alien-type)))
523     (if bits
524         (values (ceiling bits
525                          (ecase units
526                            (:bits 1)
527                            (:bytes sb!vm:n-byte-bits)
528                            (:words sb!vm:n-word-bits))))
529         (error "unknown size for alien type ~S"
530                (unparse-alien-type alien-type)))))
531 \f
532 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
533
534 (defun naturalize (alien type)
535   (declare (type alien-type type))
536   (funcall (coerce (compute-naturalize-lambda type) 'function)
537            alien type))
538
539 (defun deport (value type)
540   (declare (type alien-type type))
541   (funcall (coerce (compute-deport-lambda type) 'function)
542            value type))
543
544 (defun extract-alien-value (sap offset type)
545   (declare (type system-area-pointer sap)
546            (type unsigned-byte offset)
547            (type alien-type type))
548   (funcall (coerce (compute-extract-lambda type) 'function)
549            sap offset type))
550
551 (defun deposit-alien-value (sap offset type value)
552   (declare (type system-area-pointer sap)
553            (type unsigned-byte offset)
554            (type alien-type type))
555   (funcall (coerce (compute-deposit-lambda type) 'function)
556            sap offset type value))
557 \f
558 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
559
560 (defun alien-funcall (alien &rest args)
561   #!+sb-doc
562   "Call the foreign function ALIEN with the specified arguments. ALIEN's
563    type specifies the argument and result types."
564   (declare (type alien-value alien))
565   (let ((type (alien-value-type alien)))
566     (typecase type
567       (alien-pointer-type
568        (apply #'alien-funcall (deref alien) args))
569       (alien-fun-type
570        (unless (= (length (alien-fun-type-arg-types type))
571                   (length args))
572          (error "wrong number of arguments for ~S~%expected ~W, got ~W"
573                 type
574                 (length (alien-fun-type-arg-types type))
575                 (length args)))
576        (let ((stub (alien-fun-type-stub type)))
577          (unless stub
578            (setf stub
579                  (let ((fun (gensym))
580                        (parms (make-gensym-list (length args))))
581                    (compile nil
582                             `(lambda (,fun ,@parms)
583                                (declare (type (alien ,type) ,fun))
584                                (alien-funcall ,fun ,@parms)))))
585            (setf (alien-fun-type-stub type) stub))
586          (apply stub alien args)))
587       (t
588        (error "~S is not an alien function." alien)))))
589
590 (defmacro define-alien-routine (name result-type
591                                      &rest args
592                                      &environment lexenv)
593   #!+sb-doc
594   "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
595
596   Define a foreign interface function for the routine with the specified NAME.
597   Also automatically DECLAIM the FTYPE of the defined function.
598
599   NAME may be either a string, a symbol, or a list of the form (string symbol).
600
601   RETURN-TYPE is the alien type for the function return value. VOID may be
602   used to specify a function with no result. 
603
604   The remaining forms specify individual arguments that are passed to the
605   routine. ARG-NAME is a symbol that names the argument, primarily for
606   documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
607   way that the argument is passed.
608
609   :IN
610         An :IN argument is simply passed by value. The value to be passed is
611         obtained from argument(s) to the interface function. No values are
612         returned for :In arguments. This is the default mode.
613
614   :OUT
615         The specified argument type must be a pointer to a fixed sized object.
616         A pointer to a preallocated object is passed to the routine, and the
617         the object is accessed on return, with the value being returned from
618         the interface function. :OUT and :IN-OUT cannot be used with pointers
619         to arrays, records or functions.
620
621   :COPY
622         This is similar to :IN, except that the argument values are stored
623         on the stack, and a pointer to the object is passed instead of
624         the value itself.
625
626   :IN-OUT
627         This is a combination of :OUT and :COPY. A pointer to the argument is
628         passed, with the object being initialized from the supplied argument
629         and the return value being determined by accessing the object on
630         return."
631   (multiple-value-bind (lisp-name alien-name)
632       (pick-lisp-and-alien-names name)
633     (collect ((docs) (lisp-args) (lisp-arg-types)
634               (lisp-result-types
635                (cond ((eql result-type 'void)
636                       ;; What values does a function return, if it
637                       ;; returns no values? Exactly one - NIL. -- APD,
638                       ;; 2003-03-02
639                       (list 'null))
640                      (t
641                       ;; FIXME: Check for VALUES.
642                       (list `(alien ,result-type)))))
643               (arg-types) (alien-vars)
644               (alien-args) (results))
645       (dolist (arg args)
646         (if (stringp arg)
647             (docs arg)
648             (destructuring-bind (name type &optional (style :in)) arg
649               (unless (member style '(:in :copy :out :in-out))
650                 (error "bogus argument style ~S in ~S" style arg))
651               (when (and (member style '(:out :in-out))
652                          (typep (parse-alien-type type lexenv)
653                                 'alien-pointer-type))
654                 (error "can't use :OUT or :IN-OUT on pointer-like type:~%  ~S"
655                        type))
656               (let (arg-type)
657                 (cond ((eq style :in)
658                        (setq arg-type type)
659                        (alien-args name))
660                       (t
661                        (setq arg-type `(* ,type))
662                        (if (eq style :out)
663                            (alien-vars `(,name ,type))
664                            (alien-vars `(,name ,type ,name)))
665                        (alien-args `(addr ,name))))
666                 (arg-types arg-type)
667                 (unless (eq style :out)
668                   (lisp-args name)
669                   (lisp-arg-types t
670                                   ;; FIXME: It should be something
671                                   ;; like `(ALIEN ,ARG-TYPE), except
672                                   ;; for we also accept SAPs where
673                                   ;; pointers are required.
674                                   )))
675               (when (or (eq style :out) (eq style :in-out))
676                 (results name)
677                 (lisp-result-types `(alien ,type))))))
678       `(progn
679          ;; The theory behind this automatic DECLAIM is that (1) if
680          ;; you're calling C, static typing is what you're doing
681          ;; anyway, and (2) such a declamation can be (especially for
682          ;; alien values) both messy to do by hand and very important
683          ;; for performance of later code which uses the return value.
684          (declaim (ftype (function ,(lisp-arg-types)
685                                    (values ,@(lisp-result-types) &optional))
686                          ,lisp-name))
687          (defun ,lisp-name ,(lisp-args)
688            ,@(docs)
689            (with-alien
690             ((,lisp-name (function ,result-type ,@(arg-types))
691                          :extern ,alien-name)
692              ,@(alien-vars))
693              #-nil
694              (values (alien-funcall ,lisp-name ,@(alien-args))
695                      ,@(results))
696              #+nil
697              (if (alien-values-type-p result-type)
698                  ;; FIXME: RESULT-TYPE is a type specifier, so it
699                  ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
700                  ;; that if RESULT-TYPE is VOID, then this code
701                  ;; disagrees with the computation of the return type
702                  ;; and with all usages of this macro. -- APD,
703                  ;; 2002-03-02
704                  (let ((temps (make-gensym-list
705                                (length
706                                 (alien-values-type-values result-type)))))
707                    `(multiple-value-bind ,temps
708                         (alien-funcall ,lisp-name ,@(alien-args))
709                       (values ,@temps ,@(results))))
710                  (values (alien-funcall ,lisp-name ,@(alien-args))
711                          ,@(results)))))))))
712
713 (defmacro def-alien-routine (&rest rest)
714   (deprecation-warning 'def-alien-routine 'define-alien-routine)
715   `(define-alien-routine ,@rest))
716 \f
717 (defun alien-typep (object type)
718   #!+sb-doc
719   "Return T iff OBJECT is an alien of type TYPE."
720   (let ((lisp-rep-type (compute-lisp-rep-type type)))
721     (if lisp-rep-type
722         (typep object lisp-rep-type)
723         (and (alien-value-p object)
724              (alien-subtype-p (alien-value-type object) type)))))