Skip to content

Commit f3144bc

Browse files
Add ManuallyDrop to avoid drop invocations
Signed-off-by: Alexandru Placinta <placintaalexandru1@gmail.com>
1 parent 0e0a4c9 commit f3144bc

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

cryptoki/src/context/locking.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use cryptoki_sys::{
99
};
1010

1111
use std::{
12+
mem::ManuallyDrop,
1213
os::raw::c_void,
1314
ptr::{self, NonNull},
1415
};
@@ -117,7 +118,12 @@ unsafe extern "C" fn create_mutex<M: MutexLifeCycle>(
117118
) -> CK_RV {
118119
match M::create() {
119120
Ok(mutex) => {
120-
*ptr_ptr = Box::into_raw(mutex) as *mut c_void;
121+
// SAFETY: This is called by the PKCS#11 library when it needs to
122+
// create a mutex so ptr_ptr contains the address of a valid pointer
123+
unsafe {
124+
*ptr_ptr = Box::into_raw(mutex) as *mut c_void;
125+
}
126+
121127
CKR_OK
122128
}
123129
Err(err) => err.into(),
@@ -128,6 +134,7 @@ unsafe extern "C" fn destroy_mutex<M: MutexLifeCycle>(
128134
mutex_ptr: *mut ::std::os::raw::c_void,
129135
) -> CK_RV {
130136
// SAFETY: This is invoked after create_mutex
137+
// Here we want to drop so ManuallyDrop is not necessary
131138
let mut mutex = unsafe { Box::<M>::from_raw(mutex_ptr as *mut M) };
132139

133140
match mutex.destroy() {
@@ -140,7 +147,9 @@ unsafe extern "C" fn lock_mutex<M: MutexLifeCycle>(
140147
mutex_ptr: *mut ::std::os::raw::c_void,
141148
) -> CK_RV {
142149
// SAFETY: This is invoked after create_mutex
143-
let mutex = unsafe { Box::<M>::from_raw(mutex_ptr as *mut M) };
150+
let boxed_mutex = unsafe { Box::<M>::from_raw(mutex_ptr as *mut M) };
151+
// Avoid the call of Box::drop at the end of the function
152+
let mutex = ManuallyDrop::new(boxed_mutex);
144153

145154
match mutex.lock() {
146155
Ok(_) => CKR_OK,
@@ -152,7 +161,10 @@ unsafe extern "C" fn unlock_mutex<M: MutexLifeCycle>(
152161
mutex_ptr: *mut ::std::os::raw::c_void,
153162
) -> CK_RV {
154163
// SAFETY: This is invoked after create_mutex
155-
let mutex = unsafe { Box::<M>::from_raw(mutex_ptr as *mut M) };
164+
let boxed_mutex = unsafe { Box::<M>::from_raw(mutex_ptr as *mut M) };
165+
// Avoid the call of Box::drop at the end of the function
166+
let mutex = ManuallyDrop::new(boxed_mutex);
167+
156168
match mutex.unlock() {
157169
Ok(_) => CKR_OK,
158170
Err(err) => err.into(),

0 commit comments

Comments
 (0)