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