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