1 // Copyright 2013 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
24 use path::GenericPath;
29 pub struct DynamicLibrary { handle: *u8}
31 impl Drop for DynamicLibrary {
33 match dl::check_for_errors_in(|| {
35 dl::close(self.handle)
39 Err(str) => fail!("{}", str)
45 /// Lazily open a dynamic library. When passed None it gives a
46 /// handle to the calling process
47 pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> {
49 let maybe_library = dl::check_for_errors_in(|| {
51 Some(name) => dl::open_external(name),
52 None => dl::open_internal()
56 // The dynamic library must not be constructed if there is
57 // an error opening the library so the destructor does not
61 Ok(handle) => Ok(DynamicLibrary { handle: handle })
66 /// Appends a path to the system search path for dynamic libraries
67 pub fn add_search_path(path: &path::Path) {
68 let (envvar, sep) = if cfg!(windows) {
70 } else if cfg!(target_os = "macos") {
71 ("DYLD_LIBRARY_PATH", ':' as u8)
73 ("LD_LIBRARY_PATH", ':' as u8)
75 let newenv = os::getenv_as_bytes(envvar).unwrap_or(~[]);
76 let newenv = newenv + &[sep] + path.as_vec();
77 os::setenv(envvar, str::from_utf8(newenv).unwrap());
80 /// Access the value at the symbol of the dynamic library
81 pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, ~str> {
82 // This function should have a lifetime constraint of 'a on
83 // T but that feature is still unimplemented
85 let maybe_symbol_value = dl::check_for_errors_in(|| {
86 symbol.with_c_str(|raw_string| {
87 dl::symbol(self.handle, raw_string)
91 // The value must not be constructed if there is an error so
92 // the destructor does not run.
93 match maybe_symbol_value {
95 Ok(symbol_value) => Ok(cast::transmute(symbol_value))
107 #[ignore(cfg(windows))] // FIXME #8818
108 #[ignore(cfg(target_os="android"))] // FIXME(#10379)
109 fn test_loading_cosine() {
110 // The math library does not need to be loaded since it is already
111 // statically linked in
112 let libm = match DynamicLibrary::open(None) {
113 Err(error) => fail!("Could not load self as module: {}", error),
117 let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
118 match libm.symbol("cos") {
119 Err(error) => fail!("Could not load function cos: {}", error),
125 let expected_result = 1.0;
126 let result = cosine(argument);
127 if result != expected_result {
128 fail!("cos({:?}) != {:?} but equaled {:?} instead", argument,
129 expected_result, result)
134 #[cfg(target_os = "linux")]
135 #[cfg(target_os = "macos")]
136 #[cfg(target_os = "freebsd")]
137 fn test_errors_do_not_crash() {
138 // Open /dev/null as a library to get an error, and make sure
139 // that only causes an error, and not a crash.
140 let path = GenericPath::new("/dev/null");
141 match DynamicLibrary::open(Some(&path)) {
143 Ok(_) => fail!("Successfully opened the empty library.")
148 #[cfg(target_os = "linux")]
149 #[cfg(target_os = "android")]
150 #[cfg(target_os = "macos")]
151 #[cfg(target_os = "freebsd")]
160 pub unsafe fn open_external(filename: &path::Path) -> *u8 {
161 filename.with_c_str(|raw_name| {
162 dlopen(raw_name, Lazy as libc::c_int) as *u8
166 pub unsafe fn open_internal() -> *u8 {
167 dlopen(ptr::null(), Lazy as libc::c_int) as *u8
170 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> {
171 use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
172 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
174 // dlerror isn't thread safe, so we need to lock around this entire
176 let _guard = lock.lock();
177 let _old_error = dlerror();
181 let last_error = dlerror();
182 let ret = if ptr::null() == last_error {
185 Err(str::raw::from_c_str(last_error))
192 pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
193 dlsym(handle as *libc::c_void, symbol) as *u8
195 pub unsafe fn close(handle: *u8) {
196 dlclose(handle as *libc::c_void); ()
208 fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void;
209 fn dlerror() -> *libc::c_char;
210 fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void;
211 fn dlclose(handle: *libc::c_void) -> libc::c_int;
215 #[cfg(target_os = "win32")]
219 use path::GenericPath;
222 use result::{Ok, Err, Result};
224 pub unsafe fn open_external(filename: &path::Path) -> *u8 {
225 os::win32::as_utf16_p(filename.as_str().unwrap(), |raw_name| {
226 LoadLibraryW(raw_name as *libc::c_void) as *u8
230 pub unsafe fn open_internal() -> *u8 {
231 let handle = ptr::null();
232 GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void);
236 pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> {
242 let error = os::errno();
246 Err(format!("Error code {}", error))
251 pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 {
252 GetProcAddress(handle as *libc::c_void, symbol) as *u8
254 pub unsafe fn close(handle: *u8) {
255 FreeLibrary(handle as *libc::c_void); ()
259 fn SetLastError(error: libc::size_t);
260 fn LoadLibraryW(name: *libc::c_void) -> *libc::c_void;
261 fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16,
262 handle: **libc::c_void) -> *libc::c_void;
263 fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void;
264 fn FreeLibrary(handle: *libc::c_void);