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