diff --git a/cryptoki/src/context/mod.rs b/cryptoki/src/context/mod.rs index 4d526053..60f4681a 100644 --- a/cryptoki/src/context/mod.rs +++ b/cryptoki/src/context/mod.rs @@ -94,21 +94,37 @@ impl Pkcs11 { unsafe { let pkcs11_lib = cryptoki_sys::Pkcs11::new(filename.as_ref()).map_err(Error::LibraryLoading)?; - let mut list = mem::MaybeUninit::uninit(); + Self::_new(pkcs11_lib) + } + } + + /// Instantiate a new context from current executable, the PKCS11 implementation is contained in the current executable + pub fn new_from_self() -> Result { + unsafe { + #[cfg(not(windows))] + let this_lib = libloading::os::unix::Library::this(); + #[cfg(windows)] + let this_lib = libloading::os::windows::Library::this()?; + let pkcs11_lib = cryptoki_sys::Pkcs11::from_library(this_lib)?; + Self::_new(pkcs11_lib) + } + } - Rv::from(pkcs11_lib.C_GetFunctionList(list.as_mut_ptr())) - .into_result(Function::GetFunctionList)?; + unsafe fn _new(pkcs11_lib: cryptoki_sys::Pkcs11) -> Result { + let mut list = mem::MaybeUninit::uninit(); - let list_ptr = *list.as_ptr(); + Rv::from(pkcs11_lib.C_GetFunctionList(list.as_mut_ptr())) + .into_result(Function::GetFunctionList)?; - Ok(Pkcs11 { - impl_: Arc::new(Pkcs11Impl { - _pkcs11_lib: pkcs11_lib, - function_list: *list_ptr, - }), - initialized: Arc::new(RwLock::new(false)), - }) - } + let list_ptr = *list.as_ptr(); + + Ok(Pkcs11 { + impl_: Arc::new(Pkcs11Impl { + _pkcs11_lib: pkcs11_lib, + function_list: *list_ptr, + }), + initialized: Arc::new(RwLock::new(false)), + }) } /// Initialize the PKCS11 library