1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 Dynamic library facilities.
15 A simple wrapper over the platform's dynamic library facilities
20 #![allow(missing_doc)]
29 use path::{Path,GenericPath};
31 use slice::{Vector,ImmutableVector};
36 pub struct DynamicLibrary { handle: *u8}
38 impl Drop for DynamicLibrary {
40 match dl::check_for_errors_in(|| {
42 dl::close(self.handle)
46 Err(str) => fail!("{}", str)
52 // FIXME (#12938): Until DST lands, we cannot decompose &str into
53 // & and str, so we cannot usefully take ToCStr arguments by
54 // reference (without forcing an additional & around &str). So we
55 // are instead temporarily adding an instance for &Path, so that
56 // we can take ToCStr as owned. When DST lands, the &Path instance
57 // should be removed, and arguments bound by ToCStr should be
58 // passed by reference. (Here: in the `open` method.)
60 /// Lazily open a dynamic library. When passed None it gives a
61 /// handle to the calling process
62 pub fn open<T: ToCStr>(filename: Option<T>)
63 -> Result<DynamicLibrary, String> {
65 let mut filename = filename;
66 let maybe_library = dl::check_for_errors_in(|| {
67 match filename.take() {
68 Some(name) => dl::open_external(name),
69 None => dl::open_internal()
73 // The dynamic library must not be constructed if there is
74 // an error opening the library so the destructor does not
78 Ok(handle) => Ok(DynamicLibrary { handle: handle })
83 /// Prepends a path to this process's search path for dynamic libraries
84 pub fn prepend_search_path(path: &Path) {
85 let mut search_path = DynamicLibrary::search_path();
86 search_path.insert(0, path.clone());
87 let newval = DynamicLibrary::create_path(search_path.as_slice());
88 os::setenv(DynamicLibrary::envvar(),
89 str::from_utf8(newval.as_slice()).unwrap());
92 /// From a slice of paths, create a new vector which is suitable to be an
93 /// environment variable for this platforms dylib search path.
94 pub fn create_path(path: &[Path]) -> Vec<u8> {
95 let mut newvar = Vec::new();
96 for (i, path) in path.iter().enumerate() {
97 if i > 0 { newvar.push(DynamicLibrary::separator()); }
98 newvar.push_all(path.as_vec());
103 /// Returns the environment variable for this process's dynamic library
105 pub fn envvar() -> &'static str {
108 } else if cfg!(target_os = "macos") {
115 fn separator() -> u8 {
116 if cfg!(windows) {';' as u8} else {':' as u8}
119 /// Returns the current search path for dynamic libraries being used by this
121 pub fn search_path() -> Vec<Path> {
122 let mut ret = Vec::new();
123 match os::getenv_as_bytes(DynamicLibrary::envvar()) {
127 .split(|a| *a == DynamicLibrary::separator()) {
128 ret.push(Path::new(portion));
136 /// Access the value at the symbol of the dynamic library
137 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*T, String> {
138 // This function should have a lifetime constraint of 'a on
139 // T but that feature is still unimplemented
141 let maybe_symbol_value = dl::check_for_errors_in(|| {
142 symbol.with_c_str(|raw_string| {
143 dl::symbol(self.handle, raw_string)
147 // The value must not be constructed if there is an error so
148 // the destructor does not run.
149 match maybe_symbol_value {
150 Err(err) => Err(err),
151 Ok(symbol_value) => Ok(mem::transmute(symbol_value))
156 #[cfg(test, not(target_os = "ios"))]
164 #[ignore(cfg(windows))] // FIXME #8818
165 #[ignore(cfg(target_os="android"))] // FIXME(#10379)
166 fn test_loading_cosine() {
167 // The math library does not need to be loaded since it is already
168 // statically linked in
169 let none: Option<Path> = None; // appease the typechecker
170 let libm = match DynamicLibrary::open(none) {
171 Err(error) => fail!("Could not load self as module: {}", error),
175 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
176 match libm.symbol("cos") {
177 Err(error) => fail!("Could not load function cos: {}", error),
178 Ok(cosine) => mem::transmute::<*u8, _>(cosine)
183 let expected_result = 1.0;
184 let result = cosine(argument);
185 if result != expected_result {
186 fail!("cos({:?}) != {:?} but equaled {:?} instead", argument,
187 expected_result, result)
192 #[cfg(target_os = "linux")]
193 #[cfg(target_os = "macos")]
194 #[cfg(target_os = "freebsd")]
195 fn test_errors_do_not_crash() {
196 // Open /dev/null as a library to get an error, and make sure
197 // that only causes an error, and not a crash.
198 let path = Path::new("/dev/null");
199 match DynamicLibrary::open(Some(&path)) {
201 Ok(_) => fail!("Successfully opened the empty library.")
206 #[cfg(target_os = "linux")]
207 #[cfg(target_os = "android")]
208 #[cfg(target_os = "macos")]
209 #[cfg(target_os = "ios")]
210 #[cfg(target_os = "freebsd")]
214 use c_str::{CString, ToCStr};
218 use str::StrAllocating;
221 pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 {
222 filename.with_c_str(|raw_name| {
223 dlopen(raw_name, Lazy as libc::c_int) as *u8
227 pub unsafe fn open_internal() -> *u8 {
228 dlopen(ptr::null(), Lazy as libc::c_int) as *u8
231 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
232 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
233 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
235 // dlerror isn't thread safe, so we need to lock around this entire
237 let _guard = lock.lock();
238 let _old_error = dlerror();
242 let last_error = dlerror();
243 let ret = if ptr::null() == last_error {
246 Err(CString::new(last_error, false).as_str()
255 pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
256 dlsym(handle as *libc::c_void, symbol) as *u8
258 pub unsafe fn close(handle: *u8) {
259 dlclose(handle as *libc::c_void); ()
271 fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void;
272 fn dlerror() -> *libc::c_char;
273 fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void;
274 fn dlclose(handle: *libc::c_void) -> libc::c_int;
278 #[cfg(target_os = "win32")]
284 use result::{Ok, Err, Result};
285 use str::StrAllocating;
289 pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 {
290 // Windows expects Unicode data
291 let filename_cstr = filename.to_c_str();
292 let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap();
293 let filename_str = filename_str.to_utf16().append_one(0);
294 LoadLibraryW(filename_str.as_ptr() as *libc::c_void) as *u8
297 pub unsafe fn open_internal() -> *u8 {
298 let handle = ptr::null();
299 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void);
303 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
309 let error = os::errno();
313 Err(format!("Error code {}", error))
318 pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
319 GetProcAddress(handle as *libc::c_void, symbol) as *u8
321 pub unsafe fn close(handle: *u8) {
322 FreeLibrary(handle as *libc::c_void); ()
325 #[allow(non_snake_case_functions)]
327 fn SetLastError(error: libc::size_t);
328 fn LoadLibraryW(name: *libc::c_void) -> *libc::c_void;
329 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
330 handle: **libc::c_void) -> *libc::c_void;
331 fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
332 fn FreeLibrary(handle: *libc::c_void);