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