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