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