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