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