1.0.9.17: Delete deprecated DEF-ALIENs.
[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 ;;; Do the actual work of DEFINE-ALIEN-VARIABLE.
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66   (defun %define-alien-variable (lisp-name alien-name type)
67     (setf (info :variable :kind lisp-name) :alien)
68     (setf (info :variable :where-from lisp-name) :defined)
69     (clear-info :variable :constant-value lisp-name)
70     (setf (info :variable :alien-info lisp-name)
71           (make-heap-alien-info :type type
72                                 :sap-form `(foreign-symbol-sap ',alien-name t)))))
73
74 (defmacro extern-alien (name type &environment env)
75   #!+sb-doc
76   "Access the alien variable named NAME, assuming it is of type TYPE. This
77    is SETFable."
78   (let* ((alien-name (etypecase name
79                        (symbol (guess-alien-name-from-lisp-name name))
80                        (string name)))
81          (alien-type (parse-alien-type type env))
82          (datap (not (alien-fun-type-p alien-type))))
83     `(%heap-alien ',(make-heap-alien-info
84                      :type alien-type
85                      :sap-form `(foreign-symbol-sap ',alien-name ,datap)))))
86
87 (defmacro with-alien (bindings &body body &environment env)
88   #!+sb-doc
89   "Establish some local alien variables. Each BINDING is of the form:
90      VAR TYPE [ ALLOCATION ] [ INITIAL-VALUE | EXTERNAL-NAME ]
91    ALLOCATION should be one of:
92      :LOCAL (the default)
93        The alien is allocated on the stack, and has dynamic extent.
94      :STATIC
95        The alien is allocated on the heap, and has infinite extent. The alien
96        is allocated at load time, so the same piece of memory is used each time
97        this form executes.
98      :EXTERN
99        No alien is allocated, but VAR is established as a local name for
100        the external alien given by EXTERNAL-NAME."
101   (/show "entering WITH-ALIEN" bindings)
102   (with-auxiliary-alien-types env
103     (dolist (binding (reverse bindings))
104       (/show binding)
105       (destructuring-bind
106           (symbol type &optional (opt1 nil opt1p) (opt2 nil opt2p))
107           binding
108         (/show symbol type opt1 opt2)
109         (let* ((alien-type (parse-alien-type type env))
110                (datap (not (alien-fun-type-p alien-type))))
111           (/show alien-type)
112           (multiple-value-bind (allocation initial-value)
113               (if opt2p
114                   (values opt1 opt2)
115                   (case opt1
116                     (:extern
117                      (values opt1 (guess-alien-name-from-lisp-name symbol)))
118                     (:static
119                      (values opt1 nil))
120                     (t
121                      (values :local opt1))))
122             (/show allocation initial-value)
123             (setf body
124                   (ecase allocation
125                     #+nil
126                     (:static
127                      (let ((sap
128                             (make-symbol (concatenate 'string "SAP-FOR-"
129                                                       (symbol-name symbol)))))
130                        `((let ((,sap (load-time-value (%make-alien ...))))
131                            (declare (type system-area-pointer ,sap))
132                            (symbol-macrolet
133                             ((,symbol (sap-alien ,sap ,type)))
134                             ,@(when initial-value
135                                 `((setq ,symbol ,initial-value)))
136                             ,@body)))))
137                     (:extern
138                      (/show0 ":EXTERN case")
139                      (let ((info (make-heap-alien-info
140                                   :type alien-type
141                                   :sap-form `(foreign-symbol-sap ',initial-value
142                                                                  ,datap))))
143                        `((symbol-macrolet
144                           ((,symbol (%heap-alien ',info)))
145                           ,@body))))
146                     (:local
147                      (/show0 ":LOCAL case")
148                      (let ((var (gensym))
149                            (initval (if initial-value (gensym)))
150                            (info (make-local-alien-info :type alien-type)))
151                        (/show var initval info)
152                        `((let ((,var (make-local-alien ',info))
153                                ,@(when initial-value
154                                    `((,initval ,initial-value))))
155                            (note-local-alien-type ',info ,var)
156                            (multiple-value-prog1
157                                (symbol-macrolet
158                                 ((,symbol (local-alien ',info ,var)))
159                                 ,@(when initial-value
160                                     `((setq ,symbol ,initval)))
161                                 ,@body)
162                                (dispose-local-alien ',info ,var))))))))))))
163     (/show "revised" body)
164     (verify-local-auxiliaries-okay)
165     (/show0 "back from VERIFY-LOCAL-AUXILIARIES-OK, returning")
166     `(symbol-macrolet ((&auxiliary-type-definitions&
167                         ,(append *new-auxiliary-types*
168                                  (auxiliary-type-definitions env))))
169        ,@body)))
170 \f
171 ;;;; runtime C values that don't correspond directly to Lisp types
172
173 ;;; Note: The DEFSTRUCT for ALIEN-VALUE lives in a separate file
174 ;;; 'cause it has to be real early in the cold-load order.
175 #!-sb-fluid (declaim (freeze-type alien-value))
176 (def!method print-object ((value alien-value) stream)
177   (print-unreadable-object (value stream)
178     (format stream
179             "~S ~S #X~8,'0X ~S ~S"
180             'alien-value
181             :sap (sap-int (alien-value-sap value))
182             :type (unparse-alien-type (alien-value-type value)))))
183
184 #!-sb-fluid (declaim (inline null-alien))
185 (defun null-alien (x)
186   #!+sb-doc
187   "Return true if X (which must be an ALIEN pointer) is null, false otherwise."
188   (zerop (sap-int (alien-sap x))))
189
190 (defmacro sap-alien (sap type &environment env)
191   #!+sb-doc
192   "Convert the system area pointer SAP to an ALIEN of the specified TYPE (not
193    evaluated.) TYPE must be pointer-like."
194   (let ((alien-type (parse-alien-type type env)))
195     (if (eq (compute-alien-rep-type alien-type) 'system-area-pointer)
196         `(%sap-alien ,sap ',alien-type)
197         (error "cannot make an alien of type ~S out of a SAP" type))))
198
199 (defun %sap-alien (sap type)
200   (declare (type system-area-pointer sap)
201            (type alien-type type))
202   (make-alien-value :sap sap :type type))
203
204 (defun alien-sap (alien)
205   #!+sb-doc
206   "Return a System-Area-Pointer pointing to Alien's data."
207   (declare (type alien-value alien))
208   (alien-value-sap alien))
209 \f
210 ;;;; allocation/deallocation of heap aliens
211
212 (defmacro make-alien (type &optional size &environment env)
213   #!+sb-doc
214   "Allocate an alien of type TYPE and return an alien pointer to it. If SIZE
215 is supplied, how it is interpreted depends on TYPE. If TYPE is an array type,
216 SIZE is used as the first dimension for the allocated array. If TYPE is not an
217 array, then SIZE is the number of elements to allocate. The memory is
218 allocated using ``malloc'', so it can be passed to foreign functions which use
219 ``free''."
220   (let ((alien-type (if (alien-type-p type)
221                         type
222                         (parse-alien-type type env))))
223     (multiple-value-bind (size-expr element-type)
224         (if (alien-array-type-p alien-type)
225             (let ((dims (alien-array-type-dimensions alien-type)))
226               (cond
227                 (size
228                  (unless dims
229                    (error
230                     "cannot override the size of zero-dimensional arrays"))
231                  (when (constantp size)
232                    (setf alien-type (copy-alien-array-type alien-type))
233                    (setf (alien-array-type-dimensions alien-type)
234                          (cons (constant-form-value size) (cdr dims)))))
235                 (dims
236                  (setf size (car dims)))
237                 (t
238                  (setf size 1)))
239               (values `(* ,size ,@(cdr dims))
240                       (alien-array-type-element-type alien-type)))
241             (values (or size 1) alien-type))
242       (let ((bits (alien-type-bits element-type))
243             (alignment (alien-type-alignment element-type)))
244         (unless bits
245           (error "The size of ~S is unknown."
246                  (unparse-alien-type element-type)))
247         (unless alignment
248           (error "The alignment of ~S is unknown."
249                  (unparse-alien-type element-type)))
250         ;; This is the one place where the %SAP-ALIEN note is quite
251         ;; undesirable, in most uses of MAKE-ALIEN the %SAP-ALIEN
252         ;; cannot be optimized away.
253         `(locally (declare (muffle-conditions compiler-note))
254            (%sap-alien (%make-alien (* ,(align-offset bits alignment)
255                                        ,size-expr))
256                        ',(make-alien-pointer-type :to alien-type)))))))
257
258 ;;; Allocate a block of memory at least BITS bits long and return a
259 ;;; system area pointer to it.
260 #!-sb-fluid (declaim (inline %make-alien))
261 (defun %make-alien (bits)
262   (declare (type index bits))
263   (alien-funcall (extern-alien "malloc"
264                                (function system-area-pointer unsigned))
265                  (ash (the index (+ bits 7)) -3)))
266
267 #!-sb-fluid (declaim (inline free-alien))
268 (defun free-alien (alien)
269   #!+sb-doc
270   "Dispose of the storage pointed to by ALIEN. ALIEN must have been allocated
271    by MAKE-ALIEN or malloc(3)."
272   (alien-funcall (extern-alien "free" (function (values) system-area-pointer))
273                  (alien-sap alien))
274   nil)
275 \f
276 ;;;; the SLOT operator
277
278 ;;; Find the field named SLOT, or die trying.
279 (defun slot-or-lose (type slot)
280   (declare (type alien-record-type type)
281            (type symbol slot))
282   (or (find slot (alien-record-type-fields type)
283             :key #'alien-record-field-name)
284       (error "There is no slot named ~S in ~S." slot type)))
285
286 ;;; Extract the value from the named slot from the record ALIEN. If
287 ;;; ALIEN is actually a pointer, then DEREF it first.
288 (defun slot (alien slot)
289   #!+sb-doc
290   "Extract SLOT from the Alien STRUCT or UNION ALIEN. May be set with SETF."
291   (declare (type alien-value alien)
292            (type symbol slot)
293            (optimize (inhibit-warnings 3)))
294   (let ((type (alien-value-type alien)))
295     (etypecase type
296       (alien-pointer-type
297        (slot (deref alien) slot))
298       (alien-record-type
299        (let ((field (slot-or-lose type slot)))
300          (extract-alien-value (alien-value-sap alien)
301                               (alien-record-field-offset field)
302                               (alien-record-field-type field)))))))
303
304 ;;; Deposit the value in the specified slot of the record ALIEN. If
305 ;;; the ALIEN is really a pointer, DEREF it first. The compiler uses
306 ;;; this when it can't figure out anything better.
307 (defun %set-slot (alien slot value)
308   (declare (type alien-value alien)
309            (type symbol slot)
310            (optimize (inhibit-warnings 3)))
311   (let ((type (alien-value-type alien)))
312     (etypecase type
313       (alien-pointer-type
314        (%set-slot (deref alien) slot value))
315       (alien-record-type
316        (let ((field (slot-or-lose type slot)))
317          (deposit-alien-value (alien-value-sap alien)
318                               (alien-record-field-offset field)
319                               (alien-record-field-type field)
320                               value))))))
321
322 ;;; Compute the address of the specified slot and return a pointer to it.
323 (defun %slot-addr (alien slot)
324   (declare (type alien-value alien)
325            (type symbol slot)
326            (optimize (inhibit-warnings 3)))
327   (let ((type (alien-value-type alien)))
328     (etypecase type
329       (alien-pointer-type
330        (%slot-addr (deref alien) slot))
331       (alien-record-type
332        (let* ((field (slot-or-lose type slot))
333               (offset (alien-record-field-offset field))
334               (field-type (alien-record-field-type field)))
335          (%sap-alien (sap+ (alien-sap alien) (/ offset sb!vm:n-byte-bits))
336                      (make-alien-pointer-type :to field-type)))))))
337 \f
338 ;;;; the DEREF operator
339
340 ;;; This function does most of the work of the different DEREF
341 ;;; methods. It returns two values: the type and the offset (in bits)
342 ;;; of the referred-to alien.
343 (defun deref-guts (alien indices)
344   (declare (type alien-value alien)
345            (type list indices)
346            (values alien-type integer))
347   (let ((type (alien-value-type alien)))
348     (etypecase type
349       (alien-pointer-type
350        (when (cdr indices)
351          (error "too many indices when DEREF'ing ~S: ~W"
352                 type
353                 (length indices)))
354        (let ((element-type (alien-pointer-type-to type)))
355          (values element-type
356                  (if indices
357                      (* (align-offset (alien-type-bits element-type)
358                                       (alien-type-alignment element-type))
359                         (car indices))
360                      0))))
361       (alien-array-type
362        (unless (= (length indices) (length (alien-array-type-dimensions type)))
363          (error "incorrect number of indices when DEREF'ing ~S: ~W"
364                 type (length indices)))
365        (labels ((frob (dims indices offset)
366                   (if (null dims)
367                       offset
368                       (frob (cdr dims) (cdr indices)
369                         (+ (if (zerop offset)
370                                0
371                                (* offset (car dims)))
372                            (car indices))))))
373          (let ((element-type (alien-array-type-element-type type)))
374            (values element-type
375                    (* (align-offset (alien-type-bits element-type)
376                                     (alien-type-alignment element-type))
377                       (frob (alien-array-type-dimensions type)
378                         indices 0)))))))))
379
380 ;;; Dereference the alien and return the results.
381 (defun deref (alien &rest indices)
382   #!+sb-doc
383   "De-reference an Alien pointer or array. If an array, the indices are used
384    as the indices of the array element to access. If a pointer, one index can
385    optionally be specified, giving the equivalent of C pointer arithmetic."
386   (declare (type alien-value alien)
387            (type list indices)
388            (optimize (inhibit-warnings 3)))
389   (multiple-value-bind (target-type offset) (deref-guts alien indices)
390     (extract-alien-value (alien-value-sap alien)
391                          offset
392                          target-type)))
393
394 (defun %set-deref (alien value &rest indices)
395   (declare (type alien-value alien)
396            (type list indices)
397            (optimize (inhibit-warnings 3)))
398   (multiple-value-bind (target-type offset) (deref-guts alien indices)
399     (deposit-alien-value (alien-value-sap alien)
400                          offset
401                          target-type
402                          value)))
403
404 (defun %deref-addr (alien &rest indices)
405   (declare (type alien-value alien)
406            (type list indices)
407            (optimize (inhibit-warnings 3)))
408   (multiple-value-bind (target-type offset) (deref-guts alien indices)
409     (%sap-alien (sap+ (alien-value-sap alien) (/ offset sb!vm:n-byte-bits))
410                 (make-alien-pointer-type :to target-type))))
411 \f
412 ;;;; accessing heap alien variables
413
414 (defun %heap-alien (info)
415   (declare (type heap-alien-info info)
416            (optimize (inhibit-warnings 3)))
417   (extract-alien-value (eval (heap-alien-info-sap-form info))
418                        0
419                        (heap-alien-info-type info)))
420
421 (defun %set-heap-alien (info value)
422   (declare (type heap-alien-info info)
423            (optimize (inhibit-warnings 3)))
424   (deposit-alien-value (eval (heap-alien-info-sap-form info))
425                        0
426                        (heap-alien-info-type info)
427                        value))
428
429 (defun %heap-alien-addr (info)
430   (declare (type heap-alien-info info)
431            (optimize (inhibit-warnings 3)))
432   (%sap-alien (eval (heap-alien-info-sap-form info))
433               (make-alien-pointer-type :to (heap-alien-info-type info))))
434 \f
435 ;;;; accessing local aliens
436
437 (defun make-local-alien (info)
438   (let* ((alien (eval `(make-alien ,(local-alien-info-type info))))
439          (alien-sap (alien-sap alien)))
440     (finalize
441      alien
442      (lambda ()
443        (alien-funcall
444         (extern-alien "free" (function (values) system-area-pointer))
445         alien-sap))
446      :dont-save t)
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-var (gensym))
464         (alloc-tmp (gensym))
465         (info (if (and (consp info)
466                        (eq (car info) 'quote))
467                   (second info)
468                   (error "Something is wrong; local-alien-info not found: ~S"
469                          whole))))
470     (values nil
471             nil
472             (list value)
473             `(if (%local-alien-forced-to-memory-p ',info)
474                  (%set-local-alien ',info ,alien ,value)
475                    (let* ((,info-var ',(local-alien-info-type info))
476                           (,alloc-tmp (deport-alloc ,value ,info-var)))
477                      (maybe-with-pinned-objects (,alloc-tmp) (,(local-alien-info-type info))
478                        (setf ,alien (deport ,alloc-tmp ,info-var)))))
479             whole)))
480
481 (defun %local-alien-forced-to-memory-p (info)
482   (local-alien-info-force-to-memory-p info))
483
484 (defun %local-alien-addr (info alien)
485   (declare (type local-alien-info info))
486   (unless (local-alien-info-force-to-memory-p info)
487     (error "~S isn't forced to memory. Something went wrong." alien))
488   alien)
489
490 (defun dispose-local-alien (info alien)
491   (declare (ignore info))
492   (cancel-finalization alien)
493   (free-alien alien))
494 \f
495 ;;;; the CAST macro
496
497 (defmacro cast (alien type &environment env)
498   #!+sb-doc
499   "Convert ALIEN to an Alien of the specified TYPE (not evaluated.)  Both types
500    must be Alien array, pointer or function types."
501   `(%cast ,alien ',(parse-alien-type type env)))
502
503 (defun %cast (alien target-type)
504   (declare (type alien-value alien)
505            (type alien-type target-type)
506            (optimize (safety 2))
507            (optimize (inhibit-warnings 3)))
508   (if (or (alien-pointer-type-p target-type)
509           (alien-array-type-p target-type)
510           (alien-fun-type-p target-type))
511       (let ((alien-type (alien-value-type alien)))
512         (if (or (alien-pointer-type-p alien-type)
513                 (alien-array-type-p alien-type)
514                 (alien-fun-type-p alien-type))
515             (naturalize (alien-value-sap alien) target-type)
516             (error "~S cannot be casted." alien)))
517       (error "cannot cast to alien type ~S" (unparse-alien-type target-type))))
518 \f
519 ;;;; the ALIEN-SIZE macro
520
521 (defmacro alien-size (type &optional (units :bits) &environment env)
522   #!+sb-doc
523   "Return the size of the alien type TYPE. UNITS specifies the units to
524    use and can be either :BITS, :BYTES, or :WORDS."
525   (let* ((alien-type (parse-alien-type type env))
526          (bits (alien-type-bits alien-type)))
527     (if bits
528         (values (ceiling bits
529                          (ecase units
530                            (:bits 1)
531                            (:bytes sb!vm:n-byte-bits)
532                            (:words sb!vm:n-word-bits))))
533         (error "unknown size for alien type ~S"
534                (unparse-alien-type alien-type)))))
535 \f
536 ;;;; NATURALIZE, DEPORT, EXTRACT-ALIEN-VALUE, DEPOSIT-ALIEN-VALUE
537
538 (defun coerce-to-interpreted-function (lambda-form)
539   (let (#!+sb-eval
540         (*evaluator-mode* :interpret))
541     (coerce lambda-form 'function)))
542
543 (defun naturalize (alien type)
544   (declare (type alien-type type))
545   (funcall (coerce-to-interpreted-function (compute-naturalize-lambda type))
546            alien type))
547
548 (defun deport (value type)
549   (declare (type alien-type type))
550   (funcall (coerce-to-interpreted-function (compute-deport-lambda type))
551            value type))
552
553 (defun deport-alloc (value type)
554   (declare (type alien-type type))
555   (funcall (coerce-to-interpreted-function (compute-deport-alloc-lambda type))
556            value type))
557
558 (defun extract-alien-value (sap offset type)
559   (declare (type system-area-pointer sap)
560            (type unsigned-byte offset)
561            (type alien-type type))
562   (funcall (coerce-to-interpreted-function (compute-extract-lambda type))
563            sap offset type))
564
565 (defun deposit-alien-value (sap offset type value)
566   (declare (type system-area-pointer sap)
567            (type unsigned-byte offset)
568            (type alien-type type))
569   (funcall (coerce-to-interpreted-function (compute-deposit-lambda type))
570            sap offset type value))
571 \f
572 ;;;; ALIEN-FUNCALL, DEFINE-ALIEN-ROUTINE
573
574 (defun alien-funcall (alien &rest args)
575   #!+sb-doc
576   "Call the foreign function ALIEN with the specified arguments. ALIEN's
577    type specifies the argument and result types."
578   (declare (type alien-value alien))
579   (let ((type (alien-value-type alien)))
580     (typecase type
581       (alien-pointer-type
582        (apply #'alien-funcall (deref alien) args))
583       (alien-fun-type
584        (unless (= (length (alien-fun-type-arg-types type))
585                   (length args))
586          (error "wrong number of arguments for ~S~%expected ~W, got ~W"
587                 type
588                 (length (alien-fun-type-arg-types type))
589                 (length args)))
590        (let ((stub (alien-fun-type-stub type)))
591          (unless stub
592            (setf stub
593                  (let ((fun (gensym))
594                        (parms (make-gensym-list (length args))))
595                    (compile nil
596                             `(lambda (,fun ,@parms)
597                                (declare (optimize (sb!c::insert-step-conditions 0)))
598                                (declare (type (alien ,type) ,fun))
599                                (alien-funcall ,fun ,@parms)))))
600            (setf (alien-fun-type-stub type) stub))
601          (apply stub alien args)))
602       (t
603        (error "~S is not an alien function." alien)))))
604
605 (defmacro define-alien-routine (name result-type
606                                      &rest args
607                                      &environment lexenv)
608   #!+sb-doc
609   "DEFINE-ALIEN-ROUTINE Name Result-Type {(Arg-Name Arg-Type [Style])}*
610
611   Define a foreign interface function for the routine with the specified NAME.
612   Also automatically DECLAIM the FTYPE of the defined function.
613
614   NAME may be either a string, a symbol, or a list of the form (string symbol).
615
616   RETURN-TYPE is the alien type for the function return value. VOID may be
617   used to specify a function with no result.
618
619   The remaining forms specify individual arguments that are passed to the
620   routine. ARG-NAME is a symbol that names the argument, primarily for
621   documentation. ARG-TYPE is the C type of the argument. STYLE specifies the
622   way that the argument is passed.
623
624   :IN
625         An :IN argument is simply passed by value. The value to be passed is
626         obtained from argument(s) to the interface function. No values are
627         returned for :In arguments. This is the default mode.
628
629   :OUT
630         The specified argument type must be a pointer to a fixed sized object.
631         A pointer to a preallocated object is passed to the routine, and the
632         the object is accessed on return, with the value being returned from
633         the interface function. :OUT and :IN-OUT cannot be used with pointers
634         to arrays, records or functions.
635
636   :COPY
637         This is similar to :IN, except that the argument values are stored
638         on the stack, and a pointer to the object is passed instead of
639         the value itself.
640
641   :IN-OUT
642         This is a combination of :OUT and :COPY. A pointer to the argument is
643         passed, with the object being initialized from the supplied argument
644         and the return value being determined by accessing the object on
645         return."
646   (multiple-value-bind (lisp-name alien-name)
647       (pick-lisp-and-alien-names name)
648     (collect ((docs) (lisp-args) (lisp-arg-types)
649               (lisp-result-types
650                (cond ((eql result-type 'void)
651                       ;; What values does a function return, if it
652                       ;; returns no values? Exactly one - NIL. -- APD,
653                       ;; 2003-03-02
654                       (list 'null))
655                      (t
656                       ;; FIXME: Check for VALUES.
657                       (list `(alien ,result-type)))))
658               (arg-types) (alien-vars)
659               (alien-args) (results))
660       (dolist (arg args)
661         (if (stringp arg)
662             (docs arg)
663             (destructuring-bind (name type &optional (style :in)) arg
664               (unless (member style '(:in :copy :out :in-out))
665                 (error "bogus argument style ~S in ~S" style arg))
666               (when (and (member style '(:out :in-out))
667                          (typep (parse-alien-type type lexenv)
668                                 'alien-pointer-type))
669                 (error "can't use :OUT or :IN-OUT on pointer-like type:~%  ~S"
670                        type))
671               (let (arg-type)
672                 (cond ((eq style :in)
673                        (setq arg-type type)
674                        (alien-args name))
675                       (t
676                        (setq arg-type `(* ,type))
677                        (if (eq style :out)
678                            (alien-vars `(,name ,type))
679                            (alien-vars `(,name ,type ,name)))
680                        (alien-args `(addr ,name))))
681                 (arg-types arg-type)
682                 (unless (eq style :out)
683                   (lisp-args name)
684                   (lisp-arg-types t
685                                   ;; FIXME: It should be something
686                                   ;; like `(ALIEN ,ARG-TYPE), except
687                                   ;; for we also accept SAPs where
688                                   ;; pointers are required.
689                                   )))
690               (when (or (eq style :out) (eq style :in-out))
691                 (results name)
692                 (lisp-result-types `(alien ,type))))))
693       `(progn
694          ;; The theory behind this automatic DECLAIM is that (1) if
695          ;; you're calling C, static typing is what you're doing
696          ;; anyway, and (2) such a declamation can be (especially for
697          ;; alien values) both messy to do by hand and very important
698          ;; for performance of later code which uses the return value.
699          (declaim (ftype (function ,(lisp-arg-types)
700                                    (values ,@(lisp-result-types) &optional))
701                          ,lisp-name))
702          (defun ,lisp-name ,(lisp-args)
703            ,@(docs)
704            (with-alien
705             ((,lisp-name (function ,result-type ,@(arg-types))
706                          :extern ,alien-name)
707              ,@(alien-vars))
708              #-nil
709              (values (alien-funcall ,lisp-name ,@(alien-args))
710                      ,@(results))
711              #+nil
712              (if (alien-values-type-p result-type)
713                  ;; FIXME: RESULT-TYPE is a type specifier, so it
714                  ;; cannot be of type ALIEN-VALUES-TYPE. Also note,
715                  ;; that if RESULT-TYPE is VOID, then this code
716                  ;; disagrees with the computation of the return type
717                  ;; and with all usages of this macro. -- APD,
718                  ;; 2002-03-02
719                  (let ((temps (make-gensym-list
720                                (length
721                                 (alien-values-type-values result-type)))))
722                    `(multiple-value-bind ,temps
723                         (alien-funcall ,lisp-name ,@(alien-args))
724                       (values ,@temps ,@(results))))
725                  (values (alien-funcall ,lisp-name ,@(alien-args))
726                          ,@(results)))))))))
727 \f
728 (defun alien-typep (object type)
729   #!+sb-doc
730   "Return T iff OBJECT is an alien of type TYPE."
731   (let ((lisp-rep-type (compute-lisp-rep-type type)))
732     (if lisp-rep-type
733         (typep object lisp-rep-type)
734         (and (alien-value-p object)
735              (alien-subtype-p (alien-value-type object) type)))))
736
737 ;;;; ALIEN CALLBACKS
738 ;;;;
739 ;;;; See "Foreign Linkage / Callbacks" in the SBCL Internals manual.
740
741 (defvar *alien-callback-info* nil
742   "Maps SAPs to corresponding CALLBACK-INFO structures: contains all the
743 information we need to manipulate callbacks after their creation. Used for
744 changing the lisp-side function they point to, invalidation, etc.")
745
746 (defstruct callback-info
747   specifier
748   function ; NULL if invalid
749   wrapper
750   index)
751
752 (defun callback-info-key (info)
753   (cons (callback-info-specifier info) (callback-info-function info)))
754
755 (defun alien-callback-info (alien)
756   (cdr (assoc (alien-sap alien) *alien-callback-info* :test #'sap=)))
757
758 (defvar *alien-callbacks* (make-hash-table :test #'equal)
759   "Cache of existing callback SAPs, indexed with (SPECIFER . FUNCTION). Used for
760 memoization: we don't create new callbacks if one pointing to the correct
761 function with the same specifier already exists.")
762
763 (defvar *alien-callback-wrappers* (make-hash-table :test #'equal)
764   "Cache of existing lisp weappers, indexed with SPECIFER. Used for memoization:
765 we don't create new wrappers if one for the same specifier already exists.")
766
767 (defvar *alien-callback-trampolines* (make-array 32 :fill-pointer 0 :adjustable t)
768   "Lisp trampoline store: assembler wrappers contain indexes to this, and
769 ENTER-ALIEN-CALLBACK pulls the corresponsing trampoline out and calls it.")
770
771 (defun %alien-callback-sap (specifier result-type argument-types function wrapper)
772   (let ((key (cons specifier function)))
773     (or (gethash key *alien-callbacks*)
774         (setf (gethash key *alien-callbacks*)
775               (let* ((index (fill-pointer *alien-callback-trampolines*))
776                      ;; Aside from the INDEX this is known at
777                      ;; compile-time, which could be utilized by
778                      ;; having the two-stage assembler tramp &
779                      ;; wrapper mentioned in [1] above: only the
780                      ;; per-function tramp would need assembler at
781                      ;; runtime. Possibly we could even pregenerate
782                      ;; the code and just patch the index in later.
783                      (assembler-wrapper (alien-callback-assembler-wrapper
784                                          index result-type argument-types)))
785                 (vector-push-extend
786                  (alien-callback-lisp-trampoline wrapper function)
787                  *alien-callback-trampolines*)
788                 ;; Assembler-wrapper is static, so sap-taking is safe.
789                 (let ((sap (vector-sap assembler-wrapper)))
790                   (push (cons sap (make-callback-info :specifier specifier
791                                                       :function function
792                                                       :wrapper wrapper
793                                                       :index index))
794                         *alien-callback-info*)
795                   sap))))))
796
797 (defun alien-callback-lisp-trampoline (wrapper function)
798   (declare (function wrapper) (optimize speed))
799   (lambda (args-pointer result-pointer)
800     (funcall wrapper args-pointer result-pointer function)))
801
802 (defun alien-callback-lisp-wrapper-lambda (specifier result-type argument-types env)
803   (let* ((arguments (make-gensym-list (length argument-types)))
804          (argument-names arguments)
805          (argument-specs (cddr specifier)))
806     `(lambda (args-pointer result-pointer function)
807        ;; FIXME: the saps are not gc safe
808        (let ((args-sap (int-sap
809                         (sb!kernel:get-lisp-obj-address args-pointer)))
810              (res-sap (int-sap
811                        (sb!kernel:get-lisp-obj-address result-pointer))))
812          (declare (ignorable args-sap res-sap))
813          (with-alien
814              ,(loop
815                  with offset = 0
816                  for spec in argument-specs
817                  collect `(,(pop argument-names) ,spec
818                             :local ,(alien-callback-accessor-form
819                                      spec 'args-sap offset))
820                  do (incf offset (alien-callback-argument-bytes spec env)))
821            ,(flet ((store (spec)
822                           (if spec
823                               `(setf (deref (sap-alien res-sap (* ,spec)))
824                                      (funcall function ,@arguments))
825                               `(funcall function ,@arguments))))
826                   (cond ((alien-void-type-p result-type)
827                          (store nil))
828                         ((alien-integer-type-p result-type)
829                          (if (alien-integer-type-signed result-type)
830                              (store `(signed
831                                       ,(alien-type-word-aligned-bits result-type)))
832                              (store
833                               `(unsigned
834                                 ,(alien-type-word-aligned-bits result-type)))))
835                         (t
836                          (store (unparse-alien-type result-type)))))))
837        (values))))
838
839 (defun invalid-alien-callback (&rest arguments)
840   (declare (ignore arguments))
841   (error "Invalid alien callback called."))
842
843
844 (defun parse-callback-specification (result-type lambda-list)
845   (values
846    `(function ,result-type ,@(mapcar #'second lambda-list))
847    (mapcar #'first lambda-list)))
848
849
850 (defun parse-alien-ftype (specifier env)
851   (destructuring-bind (function result-type &rest argument-types)
852       specifier
853     (aver (eq 'function function))
854     (values (let ((*values-type-okay* t))
855               (parse-alien-type result-type env))
856             (mapcar (lambda (spec)
857                       (parse-alien-type spec env))
858                     argument-types))))
859
860 (defun alien-void-type-p (type)
861   (and (alien-values-type-p type) (not (alien-values-type-values type))))
862
863 (defun alien-type-word-aligned-bits (type)
864   (align-offset (alien-type-bits type) sb!vm:n-word-bits))
865
866 (defun alien-callback-argument-bytes (spec env)
867   (let ((type (parse-alien-type spec env)))
868     (if (or (alien-integer-type-p type)
869             (alien-float-type-p type)
870             (alien-pointer-type-p type)
871             (alien-system-area-pointer-type-p type))
872         (ceiling (alien-type-word-aligned-bits type) sb!vm:n-byte-bits)
873         (error "Unsupported callback argument type: ~A" type))))
874
875 (defun enter-alien-callback (index return arguments)
876   (funcall (aref *alien-callback-trampolines* index)
877            return
878            arguments))
879
880 ;;; To ensure that callback wrapper functions continue working even
881 ;;; if #'ENTER-ALIEN-CALLBACK moves in memory, access to it is indirected
882 ;;; through the *ENTER-ALIEN-CALLBACK* static symbol. -- JES, 2006-01-01
883 (defvar *enter-alien-callback* #'enter-alien-callback)
884
885 ;;;; interface (not public, yet) for alien callbacks
886
887 (defmacro alien-callback (specifier function &environment env)
888   "Returns an alien-value with of alien ftype SPECIFIER, that can be passed to
889 an alien function as a pointer to the FUNCTION. If a callback for the given
890 SPECIFIER and FUNCTION already exists, it is returned instead of consing a new
891 one."
892   ;; Pull out as much work as is convenient to macro-expansion time, specifically
893   ;; everything that can be done given just the SPECIFIER and ENV.
894   (multiple-value-bind (result-type argument-types) (parse-alien-ftype specifier env)
895     `(%sap-alien
896       (%alien-callback-sap ',specifier ',result-type ',argument-types
897                            ,function
898                            (or (gethash ',specifier *alien-callback-wrappers*)
899                                (setf (gethash ',specifier *alien-callback-wrappers*)
900                                      (compile nil
901                                               ',(alien-callback-lisp-wrapper-lambda
902                                                  specifier result-type argument-types env)))))
903       ',(parse-alien-type specifier env))))
904
905 (defun alien-callback-p (alien)
906   "Returns true if the alien is associated with a lisp-side callback,
907 and a secondary return value of true if the callback is still valid."
908   (let ((info (alien-callback-info alien)))
909     (when info
910       (values t (and (callback-info-function info) t)))))
911
912 (defun alien-callback-function (alien)
913   "Returns the lisp function designator associated with the callback."
914   (let ((info (alien-callback-info alien)))
915     (when info
916       (callback-info-function info))))
917
918 (defun (setf alien-callback-function) (function alien)
919   "Changes the lisp function designated by the callback."
920   (let ((info (alien-callback-info alien)))
921     (unless info
922       (error "Not an alien callback: ~S" alien))
923     ;; sap cache
924     (let ((key (callback-info-key info)))
925       (remhash key *alien-callbacks*)
926       (setf (gethash key *alien-callbacks*) (alien-sap alien)))
927     ;; trampoline
928     (setf (aref *alien-callback-trampolines* (callback-info-index info))
929           (alien-callback-lisp-trampoline (callback-info-wrapper info) function))
930     ;; metadata
931     (setf (callback-info-function info) function)
932     function))
933
934 (defun invalidate-alien-callback (alien)
935   "Invalidates the callback designated by the alien, if any, allowing the
936 associated lisp function to be GC'd, and causing further calls to the same
937 callback signal an error."
938   (let ((info (alien-callback-info alien)))
939     (when (and info (callback-info-function info))
940       ;; sap cache
941       (remhash (callback-info-key info) *alien-callbacks*)
942       ;; trampoline
943       (setf (aref *alien-callback-trampolines* (callback-info-index info))
944             #'invalid-alien-callback)
945       ;; metadata
946       (setf (callback-info-function info) nil)
947       t)))
948
949 ;;; FIXME: This call assembles a new callback for every closure,
950 ;;; which sucks hugely. ...not that I can think of an obvious
951 ;;; solution. Possibly maybe we could write a generalized closure
952 ;;; callback analogous to closure_tramp, and share the actual wrapper?
953 ;;;
954 ;;; For lambdas that result in simple-funs we get the callback from
955 ;;; the cache on subsequent calls.
956 (defmacro alien-lambda (result-type typed-lambda-list &body forms)
957   (multiple-value-bind (specifier lambda-list)
958       (parse-callback-specification result-type typed-lambda-list)
959     `(alien-callback ,specifier (lambda ,lambda-list ,@forms))))
960
961 ;;; FIXME: Should subsequent (SETF FDEFINITION) affect the callback or not?
962 ;;; What about subsequent DEFINE-ALIEN-CALLBACKs? My guess is that changing
963 ;;; the FDEFINITION should invalidate the callback, and redefining the
964 ;;; callback should change existing callbacks to point to the new defintion.
965 (defmacro define-alien-callback (name result-type typed-lambda-list &body forms)
966   "Defines #'NAME as a function with the given body and lambda-list, and NAME as
967 the alien callback for that function with the given alien type."
968   (declare (symbol name))
969   (multiple-value-bind (specifier lambda-list)
970       (parse-callback-specification result-type typed-lambda-list)
971     `(progn
972        (defun ,name ,lambda-list ,@forms)
973        (defparameter ,name (alien-callback ,specifier #',name)))))