0.7.0.5:
[sbcl.git] / src / code / foreign.lisp
1 ;;;; support for dynamically loading foreign object files and
2 ;;;; resolving symbols therein
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") ; (SB-ALIEN, not SB!ALIEN, since we're in warm load.)
14
15 (defun pick-temporary-file-name (&optional
16                                  ;; KLUDGE: There are various security
17                                  ;; nastyisms associated with easily
18                                  ;; guessable temporary file names,
19                                  ;; and we haven't done anything to
20                                  ;; work around them here. -- pointed
21                                  ;; out by Dan Barlow on sbcl-devel
22                                  ;; 20000702
23                                  (base "/tmp/sbcl-tmp-~D~C"))
24   (let ((code (char-code #\A)))
25     (loop
26       (let ((name (format nil base (sb-unix:unix-getpid) (code-char code))))
27         (multiple-value-bind (fd errno)
28             (sb-unix:unix-open name
29                                (logior sb-unix:o_wronly
30                                        sb-unix:o_creat
31                                        sb-unix:o_excl)
32                                #o666)
33           (cond ((not (null fd))
34                  (sb-unix:unix-close fd)
35                  (return name))
36                 ((not (= errno sb-unix:eexist))
37                  (simple-file-perror "couldn't create temporary file ~S"
38                                      name
39                                      errno))
40                 ;; KLUDGE: depends on ASCII character ordering -- WHN 20000128
41                 ((= code (char-code #\Z))
42                  (setf code (char-code #\a)))
43                 ((= code (char-code #\z))
44                  (return nil))
45                 (t
46                  (incf code))))))))
47
48
49 ;;; On any OS where we don't support foreign object file loading, any
50 ;;; query of a foreign symbol value is answered with "no definition
51 ;;; known", i.e. NIL.
52 ;;;
53 ;;; (On any OS which *does* support foreign object file loading, this
54 ;;; placeholder implementation is overwritten by a subsequent real
55 ;;; implementation.)
56 ;;;
57 ;;; You may want to use SB-SYS:FOREIGN-SYMBOL-ADDRESS instead of
58 ;;; calling this directly; see code/target-load.lisp.
59 (defun get-dynamic-foreign-symbol-address (symbol)
60   (declare (type simple-string symbol) (ignore symbol))
61   nil)
62
63 ;;; dlsym()-based implementation of GET-DYNAMIC-FOREIGN-SYMBOL-ADDRESS
64 ;;; and functions (e.g. LOAD-FOREIGN) which affect it.  This should 
65 ;;; work on any ELF system with dlopen(3) and dlsym(3)
66 #-(or linux FreeBSD)
67 (macrolet ((define-unsupported-fun (fun-name)
68              `(defun ,fun-name (&rest rest)
69                 "unsupported on this system"
70                 (declare (ignore rest))
71                 (error 'unsupported-operator :name ',fun-name))))
72   (define-unsupported-fun load-1-foreign)
73   (define-unsupported-fun load-foreign))
74 #+(or linux FreeBSD)
75 (progn
76
77 ;;; flags for dlopen()
78 (defconstant rtld-lazy 1)               ; lazy function call binding?
79 (defconstant rtld-now 2)                ; immediate function call binding?
80 (defconstant rtld-global #x100)         ; symbols of loaded obj file
81                                         ; (and its dependencies) made
82                                         ; visible (as though the
83                                         ; obj file were linked directly
84                                         ; into the program)?
85
86 ;;; a list of handles returned from dlopen(3) (or possibly some
87 ;;; bogus value temporarily during initialization)
88 (defvar *handles-from-dlopen* nil)
89
90 ;;; Dynamically loaded stuff isn't there upon restoring from a save.
91 ;;; Clearing the variable this way was originally done primarily for
92 ;;; Irix, which resolves tzname at runtime, resulting in
93 ;;; *HANDLES-FROM-DLOPEN* (which was then called *TABLES-FROM-DLOPEN*)
94 ;;; being set in the saved core image, resulting in havoc upon
95 ;;; restart; but it seems harmless and tidy for other OSes too.
96 ;;;
97 ;;; Of course, it can be inconvenient that dynamically loaded stuff
98 ;;; goes away when we save and restore. However,
99 ;;;  (1) trying to avoid it by system programming here could open a
100 ;;;      huge can of worms, since e.g. now we would need to worry about
101 ;;;      libraries possibly being in different locations (file locations
102 ;;;      or memory locations) at restore time than at save time; and
103 ;;;  (2) by the time the application programmer is so deep into the
104 ;;;      the use of hard core extension features as to be doing
105 ;;;      dynamic loading of foreign files and saving/restoring cores,
106 ;;;      he probably has the sophistication to write his own after-save
107 ;;;      code to reload the libraries without much difficulty.
108
109 ;;; dan 2001.05.10 suspects that objection (1) is bogus for
110 ;;; dlsym()-enabled systems
111
112 (push (lambda () (setq *handles-from-dlopen* nil))
113       *after-save-initializations*)
114
115 (defvar *dso-linker* "/usr/bin/ld")
116 (defvar *dso-linker-options* '("-G" "-o"))
117
118
119 (sb-alien:define-alien-routine dlopen system-area-pointer
120   (file sb-alien:c-string) (mode sb-alien:int))
121 (sb-alien:define-alien-routine dlsym system-area-pointer
122   (lib system-area-pointer)
123   (name sb-alien:c-string))
124 (sb-alien:define-alien-routine dlerror sb-alien:c-string)
125
126 ;;; Ensure that we've opened our own binary so we can dynamically resolve 
127 ;;; symbols in the C runtime.  
128
129 ;;; Old comment: This used to happen only in
130 ;;; GET-DYNAMIC-FOREIGN-SYMBOL-ADDRESS, and only if no libraries were
131 ;;; dlopen()ed already, but that didn't work if something was
132 ;;; dlopen()ed before any problem global vars were used.  So now we do
133 ;;; this in any function that can add to the *HANDLES-FROM-DLOPEN*, as
134 ;;; well as in GET-DYNAMIC-FOREIGN-SYMBOL-ADDRESS.
135
136 ;;; FIXME: It would work just as well to do it once at startup, actually.
137 ;;; Then at least we know it's done.    -dan 2001.05.10
138
139 (defun ensure-runtime-symbol-table-opened ()
140   (unless *handles-from-dlopen*
141     ;; Prevent recursive call if dlopen() isn't defined.
142     (setf *handles-from-dlopen* (int-sap 0))
143     (setf *handles-from-dlopen* (list (dlopen nil rtld-lazy)))
144     (when (zerop (sb-sys:sap-int (first *handles-from-dlopen*)))
145       (error "can't open our own binary's symbol table: ~S" (dlerror)))))
146
147 (defun load-1-foreign (file)
148   "the primitive upon which the more general LOAD-FOREIGN is built: load
149   a single foreign object file
150
151   To use LOAD-1-FOREIGN, at the Unix command line do this:
152     echo 'int summish(int x, int y) { return 1 + x + y; }' > /tmp/ffi-test.c
153     make /tmp/ffi-test.o # i.e. cc -c -o /tmp/ffi-test.o /tmp/ffi-test.c
154     ld -shared -o /tmp/ffi-test.so /tmp/ffi-test.o
155   then in SBCL do this:
156     (LOAD-1-FOREIGN \"/tmp/ffi-test.so\")
157     (DEFINE-ALIEN-ROUTINE SUMMISH INT (X INT) (Y INT))
158   Now running (SUMMISH 10 20) should return 31.
159 "
160   (ensure-runtime-symbol-table-opened)
161   ;; Note: We use RTLD-GLOBAL so that it can find all the symbols
162   ;; previously loaded. We use RTLD-NOW so that dlopen() will fail if
163   ;; not all symbols are defined.
164   (let* ((real-file (or (unix-namestring file) file))
165          (sap (dlopen real-file (logior rtld-now rtld-global))))
166        (if (zerop (sap-int sap))
167            (error "can't open object ~S: ~S" real-file (dlerror))
168            (pushnew sap *handles-from-dlopen* :test #'sap=)))
169   (values))
170
171 (defun get-dynamic-foreign-symbol-address (symbol)
172   (ensure-runtime-symbol-table-opened)
173   ;; Find the symbol in any of the loaded object files. Search in
174   ;; reverse order of loading, so that later loadings take precedence.
175   ;;
176   ;; FIXME: The way that we use PUSHNEW SAP in LOAD-1-FOREIGN means
177   ;; that the list isn't guaranteed to be in reverse order of loading,
178   ;; at least not if a file is loaded more than once. Is this the
179   ;; right thing? (In what cases does it matter?)
180   (dolist (handle *handles-from-dlopen*)
181     ;; KLUDGE: We implicitly exclude the possibility that the variable
182     ;; could actually be NULL, but the man page for dlsym(3) 
183     ;; recommends doing a more careful test. -- WHN 20000825
184     (let ((possible-result (sap-int (dlsym handle symbol))))
185       (unless (zerop possible-result)
186         (return possible-result)))))
187
188 (defun load-foreign (files
189                      &key
190                      (libraries '("-lc"))
191                      ;; FIXME: The old documentation said
192                      ;;   The BASE-FILE argument is used to specify a
193                      ;;   file to use as the starting place for
194                      ;;   defined symbols. The default is the C start
195                      ;;   up code for Lisp.
196                      ;; But the code ignored the BASE-FILE argument.
197                      ;; The comment above
198                      ;;   (DECLARE (IGNORE BASE-FILE))
199                      ;; said
200                      ;;   dlopen() remembers the name of an object,
201                      ;;   when dlopen()ing the same name twice, the
202                      ;;   old object is reused.
203                      ;; So I deleted all reference to BASE-FILE,
204                      ;; including the now-bogus reference to the
205                      ;; BASE-FILE argument in the documentation. But
206                      ;; are there any other subtleties of the new code
207                      ;; which need to be documented in its place?
208                      (env nil env-p)
209                      (environment (if env-p
210                                       (unix-environment-sbcl-from-cmu env)
211                                       (posix-environ))
212                                   environment-p))
213   #+sb-doc
214   "LOAD-FOREIGN loads a list of C object files into a running Lisp. The FILES
215   argument should be a single file or a list of files. The files may be
216   specified as namestrings or as pathnames. The libraries argument should be a
217   list of library files as would be specified to ld. They will be searched in
218   the order given. The default is just \"-lc\", i.e., the C library. The
219   ENVIRONMENT argument is a list of SIMPLE-STRINGs corresponding to the Unix
220   environment (\"man environ\") definitions for the invocation of the linker.
221   The default is the environment that Lisp is itself running in. Instead of
222   using the ENVIRONMENT argument, it is also possible to use the ENV argument,
223   using the older, lossy CMU CL representation."
224   (when (and env-p environment-p)
225     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
226   (let ((output-file (pick-temporary-file-name
227                       (concatenate 'string "/tmp/~D~C" (string (gensym)))))
228         (error-output (make-string-output-stream)))
229
230     (/show "running" *dso-linker*)
231     (force-output)
232     (unwind-protect
233         (let ((proc (sb-ext:run-program
234                      *dso-linker*
235                      (append *dso-linker-options*
236                              (list output-file)
237                              (append (mapcar (lambda (name)
238                                                (unix-namestring name nil))
239                                              (if (atom files)
240                                                  (list files)
241                                                files))
242                                      libraries))
243                      :environment environment
244                      :input nil
245                      :output error-output
246                      :error :output)))
247           (unless proc
248             (error "could not run ~A" *dso-linker*))
249           (unless (zerop (sb-ext:process-exit-code proc))
250             (sb-sys:serve-all-events 0)
251             (error "~A failed:~%~A" *dso-linker*
252                    (get-output-stream-string error-output)))
253           (load-1-foreign output-file))
254       #-sb-show (sb-unix:unix-unlink output-file)
255       #+sb-show (/show "not unlinking" output-file)))) ; so we can look at it
256
257 ) ; PROGN