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