diff options
author | Jason Macnak <natsu@google.com> | 2021-08-30 14:36:24 -0700 |
---|---|---|
committer | Jason Macnak <natsu@google.com> | 2021-08-30 14:36:42 -0700 |
commit | 682d05061553cd377c2a87e53cf1f8c84c553e14 (patch) | |
tree | abec969f7659391ae4fe2bbbe5821f9decc6bad7 | |
parent | 078d3cf09ef52d01204066346aff69f049b238e6 (diff) | |
download | shared_library-682d05061553cd377c2a87e53cf1f8c84c553e14.tar.gz |
Import shared_library rust crate
Bug: b/189133061
Test: cd external/rush/crates/shared_library && mm
Change-Id: Ia68e3d776dcef821b1aee02ac2e82a1a1ddd2957
-rw-r--r-- | Android.bp | 48 | ||||
-rw-r--r-- | Cargo.toml | 24 | ||||
-rw-r--r-- | Cargo.toml.orig | 11 | ||||
l--------- | LICENSE | 1 | ||||
-rw-r--r-- | LICENSE-APACHE | 201 | ||||
-rw-r--r-- | LICENSE-MIT | 25 | ||||
-rw-r--r-- | METADATA | 20 | ||||
-rw-r--r-- | MODULE_LICENSE_APACHE2 | 0 | ||||
-rw-r--r-- | OWNERS | 1 | ||||
-rw-r--r-- | src/dynamic_library.rs | 410 | ||||
-rw-r--r-- | src/lib.rs | 175 |
11 files changed, 916 insertions, 0 deletions
diff --git a/Android.bp b/Android.bp new file mode 100644 index 0000000..13cc0cc --- /dev/null +++ b/Android.bp @@ -0,0 +1,48 @@ +// This file is generated by cargo2android.py --run --device --dependencies --tests. +// Do not modify this file as changes will be overridden on upgrade. + + + +rust_library { + name: "libshared_library", + host_supported: true, + crate_name: "shared_library", + cargo_env_compat: true, + cargo_pkg_version: "0.1.9", + srcs: ["src/lib.rs"], + edition: "2015", + rustlibs: [ + "liblazy_static", + "liblibc", + ], + apex_available: [ + "//apex_available:platform", + "com.android.virt", + ], +} + +rust_defaults { + name: "shared_library_test_defaults", + crate_name: "shared_library", + srcs: ["src/lib.rs"], + test_suites: ["general-tests"], + auto_gen_config: true, + edition: "2015", + rustlibs: [ + "liblazy_static", + "liblibc", + ], +} + +rust_test_host { + name: "shared_library_host_test_src_lib", + defaults: ["shared_library_test_defaults"], + test_options: { + unit_test: true, + }, +} + +rust_test { + name: "shared_library_device_test_src_lib", + defaults: ["shared_library_test_defaults"], +} diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1d7d58b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "shared_library" +version = "0.1.9" +authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"] +description = "Easily bind to and load shared libraries" +license = "Apache-2.0/MIT" +repository = "https://github.com/tomaka/shared_library/" +[dependencies.lazy_static] +version = "1" + +[dependencies.libc] +version = "0.2" diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..be74698 --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,11 @@ +[package] +name = "shared_library" +version = "0.1.9" +authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"] +description = "Easily bind to and load shared libraries" +license = "Apache-2.0/MIT" +repository = "https://github.com/tomaka/shared_library/" + +[dependencies] +libc = "0.2" +lazy_static = "1" @@ -0,0 +1 @@ +LICENSE-APACHE
\ No newline at end of file diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..1b22bef --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License.
\ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..4f2b149 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Pierre Krieger + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE.
\ No newline at end of file diff --git a/METADATA b/METADATA new file mode 100644 index 0000000..0b6518d --- /dev/null +++ b/METADATA @@ -0,0 +1,20 @@ +name: "shared_library" +description: "Easily bind to and load shared libraries" +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/shared_library" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/shared_library/shared_library-0.1.9.crate" + } + version: "0.1.9" + # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same. + license_type: NOTICE + last_upgrade_date { + year: 2021 + month: 8 + day: 30 + } +} diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_APACHE2 @@ -0,0 +1 @@ +include platform/prebuilts/rust:master:/OWNERS diff --git a/src/dynamic_library.rs b/src/dynamic_library.rs new file mode 100644 index 0000000..753b632 --- /dev/null +++ b/src/dynamic_library.rs @@ -0,0 +1,410 @@ +// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Dynamic library facilities. +//! +//! A simple wrapper over the platform's dynamic library facilities + +#![allow(missing_docs)] + +use std::env; +use std::ffi::{CString, OsString}; +use std::mem; +use std::path::{Path, PathBuf}; +use libc; + +pub struct DynamicLibrary { + handle: *mut u8 +} + +unsafe impl Send for DynamicLibrary {} +unsafe impl Sync for DynamicLibrary {} + +impl Drop for DynamicLibrary { + fn drop(&mut self) { + if let Err(str) = dl::check_for_errors_in(|| unsafe { + dl::close(self.handle) + }) { + panic!("{}", str) + } + } +} + +/// Special handles to be used with the `symbol_special` function. These are +/// provided by a GNU only extension and are not included as part of the POSIX +/// standard. +/// +/// See https://linux.die.net/man/3/dlsym for their behaviour. +#[cfg(target_os = "linux")] +pub enum SpecialHandles { + Next, + Default, +} + +impl DynamicLibrary { + // FIXME (#12938): Until DST lands, we cannot decompose &str into + // & and str, so we cannot usefully take ToCStr arguments by + // reference (without forcing an additional & around &str). So we + // are instead temporarily adding an instance for &Path, so that + // we can take ToCStr as owned. When DST lands, the &Path instance + // should be removed, and arguments bound by ToCStr should be + // passed by reference. (Here: in the `open` method.) + + /// Lazily loads the dynamic library named `filename` into memory and + /// then returns an opaque "handle" for that dynamic library. + /// + /// Returns a handle to the calling process when passed `None`. + pub fn open(filename: Option<&Path>) -> Result<Self, String> { + // The dynamic library must not be constructed if there is + // an error opening the library so the destructor does not + // run. + dl::open(filename.map(|path| path.as_os_str())) + .map(|handle| DynamicLibrary { handle }) + } + + /// Prepends a path to this process's search path for dynamic libraries + pub fn prepend_search_path(path: &Path) { + let mut search_path = Self::search_path(); + search_path.insert(0, path.to_path_buf()); + env::set_var(Self::envvar(), &Self::create_path(&search_path)); + } + + /// From a slice of paths, create a new vector which is suitable to be an + /// environment variable for this platforms dylib search path. + pub fn create_path(path: &[PathBuf]) -> OsString { + let mut newvar = OsString::new(); + for (i, path) in path.iter().enumerate() { + if i > 0 { newvar.push(Self::separator()); } + newvar.push(path); + } + newvar + } + + /// Returns the environment variable for this process's dynamic library + /// search path + pub fn envvar() -> &'static str { + if cfg!(windows) { + "PATH" + } else if cfg!(target_os = "macos") { + "DYLD_LIBRARY_PATH" + } else { + "LD_LIBRARY_PATH" + } + } + + //TODO: turn this and `envvar` into associated constants + fn separator() -> &'static str { + if cfg!(windows) { ";" } else { ":" } + } + + /// Returns the current search path for dynamic libraries being used by this + /// process + pub fn search_path() -> Vec<PathBuf> { + match env::var_os(Self::envvar()) { + Some(var) => env::split_paths(&var).collect(), + None => Vec::new(), + } + } + + /// Returns the address of where symbol `symbol` was loaded into memory. + /// + /// In POSIX compliant systems, we return 'Err' if the symbol was not found, + /// in this library or any of the libraries that were automatically loaded + /// when this library was loaded. + pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { + // This function should have a lifetime constraint of 'a on + // T but that feature is still unimplemented + + let raw_string = CString::new(symbol).unwrap(); + // The value must not be constructed if there is an error so + // the destructor does not run. + dl::check_for_errors_in(|| { + dl::symbol(self.handle as *mut libc::c_void, raw_string.as_ptr() as *const _) + }) + .map(|sym| mem::transmute(sym)) + } + + /// Returns the address of the first occurance of symbol `symbol` using the + /// default library search order if you use `SpecialHandles::Default`. + /// + /// Returns the address of the next occurance of symbol `symbol` after the + /// current library in the default library search order if you use + /// `SpecialHandles::Next`. + #[cfg(target_os = "linux")] + pub unsafe fn symbol_special<T>(handle: SpecialHandles, symbol: &str) -> Result<*mut T, String> { + // This function should have a lifetime constraint of 'a on + // T but that feature is still unimplemented + + let handle = match handle { + SpecialHandles::Next => mem::transmute::<libc::c_long, _>(-1), + SpecialHandles::Default => ::std::ptr::null_mut(), + }; + + let raw_string = CString::new(symbol).unwrap(); + // The value must not be constructed if there is an error so + // the destructor does not run. + dl::check_for_errors_in(|| { + dl::symbol(handle, raw_string.as_ptr() as *const _) + }) + .map(|sym| mem::transmute(sym)) + } +} + +#[cfg(all(test, not(target_os = "ios")))] +mod test { + use super::*; + use std::mem; + use std::path::Path; + + #[test] + #[cfg_attr(any(windows, target_os = "android"), ignore)] // FIXME #8818, #10379 + fn test_loading_cosine() { + // The math library does not need to be loaded since it is already + // statically linked in + let libm = match DynamicLibrary::open(None) { + Err(error) => panic!("Could not load self as module: {}", error), + Ok(libm) => libm + }; + + let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { + match libm.symbol("cos") { + Err(error) => panic!("Could not load function cos: {}", error), + Ok(cosine) => mem::transmute::<*mut u8, _>(cosine) + } + }; + + let argument = 0.0; + let expected_result = 1.0; + let result = cosine(argument); + if result != expected_result { + panic!("cos({}) != {} but equaled {} instead", argument, + expected_result, result) + } + } + + #[test] + #[cfg(any(target_os = "linux", + target_os = "macos", + target_os = "freebsd", + target_os = "fuchsia", + target_os = "netbsd", + target_os = "dragonfly", + target_os = "bitrig", + target_os = "openbsd", + target_os = "solaris"))] + fn test_errors_do_not_crash() { + // Open /dev/null as a library to get an error, and make sure + // that only causes an error, and not a crash. + let path = Path::new("/dev/null"); + match DynamicLibrary::open(Some(&path)) { + Err(_) => {} + Ok(_) => panic!("Successfully opened the empty library.") + } + } +} + +//TODO: use `unix` shortcut? +#[cfg(any(target_os = "linux", + target_os = "android", + target_os = "macos", + target_os = "ios", + target_os = "fuchsia", + target_os = "freebsd", + target_os = "netbsd", + target_os = "dragonfly", + target_os = "bitrig", + target_os = "openbsd", + target_os = "solaris", + target_os = "emscripten"))] +mod dl { + use std::ffi::{CString, CStr, OsStr}; + use std::os::unix::ffi::OsStrExt; + use std::str; + use libc; + use std::ptr; + use std::sync::Mutex; + + lazy_static! { + static ref LOCK: Mutex<()> = Mutex::new(()); + } + + pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { + check_for_errors_in(|| unsafe { + match filename { + Some(filename) => open_external(filename), + None => open_internal(), + } + }) + } + + const LAZY: libc::c_int = 1; + + unsafe fn open_external(filename: &OsStr) -> *mut u8 { + let s = CString::new(filename.as_bytes().to_vec()).unwrap(); + dlopen(s.as_ptr() as *const _, LAZY) as *mut u8 + } + + unsafe fn open_internal() -> *mut u8 { + dlopen(ptr::null(), LAZY) as *mut u8 + } + + pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where + F: FnOnce() -> T, + { + unsafe { + // dlerror isn't thread safe, so we need to lock around this entire + // sequence + let _guard = LOCK.lock(); + let _old_error = dlerror(); + + let result = f(); + + let last_error = dlerror() as *const _; + let ret = if ptr::null() == last_error { + Ok(result) + } else { + let s = CStr::from_ptr(last_error).to_bytes(); + Err(str::from_utf8(s).unwrap().to_string()) + }; + + ret + } + } + + pub unsafe fn symbol( + handle: *mut libc::c_void, + symbol: *const libc::c_char, + ) -> *mut u8 { + dlsym(handle, symbol) as *mut u8 + } + + pub unsafe fn close(handle: *mut u8) { + dlclose(handle as *mut libc::c_void); () + } + + extern { + fn dlopen( + filename: *const libc::c_char, + flag: libc::c_int, + ) -> *mut libc::c_void; + fn dlerror() -> *mut libc::c_char; + fn dlsym( + handle: *mut libc::c_void, + symbol: *const libc::c_char, + ) -> *mut libc::c_void; + fn dlclose( + handle: *mut libc::c_void, + ) -> libc::c_int; + } +} + +#[cfg(target_os = "windows")] +mod dl { + use std::ffi::OsStr; + use std::iter::Iterator; + use libc; + use std::ops::FnOnce; + use std::io::Error as IoError; + use std::os::windows::prelude::*; + use std::option::Option::{self, Some, None}; + use std::ptr; + use std::result::Result; + use std::result::Result::{Ok, Err}; + use std::string::String; + use std::vec::Vec; + + pub fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> { + // disable "dll load failed" error dialog. + let prev_error_mode = unsafe { + // SEM_FAILCRITICALERRORS 0x01 + let new_error_mode = 1; + SetErrorMode(new_error_mode) + }; + + unsafe { + SetLastError(0); + } + + let result = match filename { + Some(filename) => { + let filename_str: Vec<_> = + filename.encode_wide().chain(Some(0).into_iter()).collect(); + let result = unsafe { + LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) + }; + // beware: Vec/String may change errno during drop! + // so we get error here. + if result == ptr::null_mut() { + Err(format!("{}", IoError::last_os_error())) + } else { + Ok(result as *mut u8) + } + } + None => { + let mut handle = ptr::null_mut(); + let succeeded = unsafe { + GetModuleHandleExW(0, ptr::null(), &mut handle) + }; + if succeeded == 0 { + Err(format!("{}", IoError::last_os_error())) + } else { + Ok(handle as *mut u8) + } + } + }; + + unsafe { + SetErrorMode(prev_error_mode); + } + + result + } + + pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where + F: FnOnce() -> T, + { + unsafe { + SetLastError(0); + + let result = f(); + + let error = IoError::last_os_error(); + if 0 == error.raw_os_error().unwrap() { + Ok(result) + } else { + Err(format!("{}", error)) + } + } + } + + pub unsafe fn symbol(handle: *mut libc::c_void, symbol: *const libc::c_char) -> *mut u8 { + GetProcAddress(handle, symbol) as *mut u8 + } + pub unsafe fn close(handle: *mut u8) { + FreeLibrary(handle as *mut libc::c_void); () + } + + #[allow(non_snake_case)] + extern "system" { + fn SetLastError(error: libc::size_t); + fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void; + fn GetModuleHandleExW( + dwFlags: u32, + name: *const u16, + handle: *mut *mut libc::c_void, + ) -> i32; + fn GetProcAddress( + handle: *mut libc::c_void, + name: *const libc::c_char, + ) -> *mut libc::c_void; + fn FreeLibrary(handle: *mut libc::c_void); + fn SetErrorMode(uMode: libc::c_uint) -> libc::c_uint; + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..e698a47 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,175 @@ +extern crate libc; + +#[macro_use] +extern crate lazy_static; + +pub mod dynamic_library; + +/// Error that can happen while loading the shared library. +#[derive(Debug, Clone)] +pub enum LoadingError { + /// + LibraryNotFound { + descr: String, + }, + + /// One of the symbols could not be found in the library. + SymbolNotFound { + /// The symbol. + symbol: &'static str, + } +} + +#[macro_export] +macro_rules! shared_library { + ($struct_name:ident, pub $($rest:tt)+) => { + shared_library!(__impl $struct_name [] [] [] pub $($rest)+); + }; + + ($struct_name:ident, fn $($rest:tt)+) => { + shared_library!(__impl $struct_name [] [] [] fn $($rest)+); + }; + + ($struct_name:ident, static $($rest:tt)+) => { + shared_library!(__impl $struct_name [] [] [] static $($rest)+); + }; + + ($struct_name:ident, $def_path:expr, $($rest:tt)+) => { + shared_library!(__impl $struct_name [] [$def_path] [] $($rest)+); + }; + + (__impl $struct_name:ident + [$($p1:tt)*] [$($p2:tt)*] [$($p3:tt)*] + , $($rest:tt)* + ) => { + shared_library!(__impl $struct_name [$($p1)*] [$($p2)*] [$($p3)*] $($rest)*); + }; + + (__impl $struct_name:ident + [$($p1:tt)*] [$($p2:tt)*] [$($p3:tt)*] + pub $($rest:tt)* + ) => { + shared_library!(__impl $struct_name + [$($p1)*] [$($p2)*] [$($p3)* pub] $($rest)*); + }; + + (__impl $struct_name:ident + [$($p1:tt)*] [$($p2:tt)*] [$($p3:tt)*] + fn $name:ident($($p:ident:$ty:ty),*) -> $ret:ty, $($rest:tt)* + ) => { + shared_library!(__impl $struct_name + [$($p1)*, $name:unsafe extern fn($($p:$ty),*) -> $ret] + [$($p2)*] + [$($p3)* + unsafe fn $name($($p:$ty),*) -> $ret { + #![allow(dead_code)] + ($struct_name::get_static_ref().$name)($($p),*) + } + ] $($rest)*); + }; + + (__impl $struct_name:ident + [$($p1:tt)*] [$($p2:tt)*] [$($p3:tt)*] + static $name:ident:$ty:ty, $($rest:tt)* + ) => { + shared_library!(__impl $struct_name + [$($p1)*, $name: $ty] + [$($p2)*] + [$($p3)*] $($rest)*); + }; + + (__impl $struct_name:ident + [$($p1:tt)*] [$($p2:tt)*] [$($p3:tt)*] + fn $name:ident($($p:ident:$ty:ty),*), $($rest:tt)* + ) => { + shared_library!(__impl $struct_name + [$($p1)*] [$($p2)*] [$($p3)*] + fn $name($($p:$ty),*) -> (), $($rest)*); + }; + + (__impl $struct_name:ident [$(,$mem_n:ident:$mem_t:ty)+] [$($p2:tt)*] [$($p3:tt)*]) => { + /// Symbols loaded from a shared library. + #[allow(non_snake_case)] + pub struct $struct_name { + _library_guard: $crate::dynamic_library::DynamicLibrary, + $( + pub $mem_n: $mem_t, + )+ + } + + impl $struct_name { + /// Tries to open the dynamic library. + #[allow(non_snake_case)] + pub fn open(path: &::std::path::Path) -> Result<$struct_name, $crate::LoadingError> { + use std::mem; + + let dylib = match $crate::dynamic_library::DynamicLibrary::open(Some(path)) { + Ok(l) => l, + Err(reason) => return Err($crate::LoadingError::LibraryNotFound { descr: reason }) + }; + + $( + let $mem_n: *mut () = match unsafe { dylib.symbol(stringify!($mem_n)) } { + Ok(s) => s, + Err(_) => return Err($crate::LoadingError::SymbolNotFound { symbol: stringify!($mem_n) }), + }; + )+ + + Ok($struct_name { + _library_guard: dylib, + $( + $mem_n: unsafe { mem::transmute($mem_n) }, + )+ + }) + } + } + + shared_library!(__write_static_fns $struct_name [] [$($p2)*] [$($p3)*]); + }; + + (__write_static_fns $struct_name:ident [$($p1:tt)*] [] [$($p3:tt)*]) => { + }; + + (__write_static_fns $struct_name:ident [$($p1:tt)*] [$defpath:expr] [$($standalones:item)+]) => { + impl $struct_name { + /// This function is used by the regular functions. + fn get_static_ref() -> &'static $struct_name { + $struct_name::try_loading().ok() + .expect(concat!("Could not open dynamic \ + library `", stringify!($struct_name), + "`")) + } + + /// Try loading the static symbols linked to this library. + pub fn try_loading() -> Result<&'static $struct_name, $crate::LoadingError> { + use std::sync::{Mutex, Once, ONCE_INIT}; + use std::mem; + + unsafe { + static mut DATA: *const Mutex<Option<$struct_name>> = 0 as *const _; + + static mut INIT: Once = ONCE_INIT; + INIT.call_once(|| { + let data = Box::new(Mutex::new(None)); + DATA = &*data; + mem::forget(data); + }); + + let data: &Mutex<Option<$struct_name>> = &*DATA; + let mut data = data.lock().unwrap(); + + if let Some(ref data) = *data { + return Ok(mem::transmute(data)); + } + + let path = ::std::path::Path::new($defpath); + let result = try!($struct_name::open(path)); + *data = Some(result); + Ok(mem::transmute(data.as_ref().unwrap())) + } + } + } + + $($standalones)+ + }; +} |