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