1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! A Rust idiomatic Windows Kernel Driver KMUTEX type which protects the inner type T
use ;
use println;
use ;
use crateDriverMutexError;
/// A thread safe mutex implemented through acquiring a KMUTEX in the Windows kernel.
///
/// The type `Kmutex<T>` provides mutually exclusive access to the inner type T allocated through
/// this crate in the non-paged pool. All data required to initialise the KMutex is allocated in the
/// non-paged pool and as such is safe to pass stack data into the type as it will not go out of scope.
///
/// `KMutex` holds an inner value which is a pointer to a `KMutexInner` type which is the actual type
/// allocated in the non-paged pool, and this holds information relating to the mutex.
///
/// Access to the `T` within the `KMutex` can be done through calling [`Self::lock`].
///
/// To receive debug messages when the IRQL is too high for an operation, enable the feature flag `debug`.
///
/// # Lifetimes
///
/// As the `KMutex` is designed to be used in the Windows Kernel, with the Windows `wdk` crate, the lifetimes of
/// the `KMutex` must be considered by the caller. See examples below for usage.
///
/// The KMutex can exist in a locally scoped function with little additional configuration. To use the mutex across
/// thread boundaries, or to use it in callback functions, the recommended course of action is to utilise either a
/// globally accessible `static AtomicPtr<KMutex<T>>`; or to utilise a
/// [Device Extension](https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/device-extensions)
/// provided in the wdk.
///
/// <section class="warning">
/// If you use a `static AtomicPtr<KMutex<T>>` you MUST ensure that the memory is cleaned up when you exit the driver
/// otherwise you cause a memory leak.
///
/// A future addition is planned which will make the API more flexible for dynamically managing globally available
/// mutexes to somewhat reduce the overhead required to use this crate.
/// </section>
///
/// # Deallocation
///
/// KMutex handles the deallocation of resources at the point the KMutex is dropped.
///
/// # Examples
///
/// ## Locally scoped mutex:
///
/// ```
/// {
/// let mtx = KMutex::new(0u32).unwrap();
/// let lock = mtx.lock().unwrap();
///
/// // If T implements display, you do not need to dereference the lock to print.
/// println!("The value is: {}", lock);
/// } // Mutex will become unlocked as it is managed via RAII
/// ```
///
/// ## Global scope via static pointer:
///
/// A future release is planned to make this process more ergonomic.
///
/// ```
/// pub static HEAP_MTX_PTR: AtomicPtr<KMutex<u32>> = AtomicPtr::new(null_mut());
///
/// fn my_fn() {
/// let heap_mtx = Box::new(KMutex::new(0u32).unwrap());
/// let heap_mtx_ptr = Box::into_raw(heap_mtx);
/// HEAP_MTX_PTR.store(heap_mtx_ptr, Ordering::SeqCst);
///
/// // spawn some system threads
/// r _ in 0..3 {
/// let mut thread_handle: HANDLE = null_mut();
/// let status = unsafe {
/// PsCreateSystemThread(
/// &mut thread_handle,
/// 0,
/// null_mut::<OBJECT_ATTRIBUTES>(),
/// null_mut(),
/// null_mut::<CLIENT_ID>(),
/// Some(callback_fn),
/// null_mut(),
/// )
/// };
/// println!("[i] Thread status: {status}");
/// }
/// }
///
/// unsafe extern "C" fn callback_fn(_: *mut c_void) {
/// for _ in 0..50 {
/// let p = HEAP_MTX_PTR.load(Ordering::SeqCst);
/// if !p.is_null() {
/// let p = unsafe { &*p };
/// let mut lock = p.lock().unwrap();
/// println!("Got the lock before change! {}", *lock);
/// *lock += 1;
/// println!("After the change: {}", *lock);
/// }
/// }
/// }
///
/// // IMPORTANT ensure the KMutex in the static is properly dropped to clean memory
/// extern "C" fn driver_exit(driver: *mut DRIVER_OBJECT) {
/// let ptr: *mut KMutex<u32> = HEAP_MTX_PTR.load(Ordering::SeqCst);
/// if !ptr.is_null() {
/// unsafe {
/// // RAII will kick in here to deallocate our memory
/// let _ = Box::from_raw(ptr);
/// }
/// }
/// }
/// ```
/// The underlying data which is non-page pool allocated which is pointed to by the `KMutex`.
unsafe
/// A RAII scoped guard for the inner data protected by the mutex. Once this guard is given out, the protected data
/// may be safely mutated by the caller as we guarantee exclusive access via Windows Kernel Mutex primitives.
///
/// When this structure is dropped (falls out of scope), the lock will be unlocked.
///
/// # IRQL
///
/// Access to the data within this guard must be done at <= APC_LEVEL if a non-alertable lock was acquired, or <=
/// DISPATCH_LEVEL if an alertable lock was acquired. It is the callers responsible to manage APC levels whilst
/// using the KMutex.
///
/// If you wish to manually drop the lock with a safety check, call the function [`Self::drop_safe`].
///
/// # Kernel panic
///
/// Raising the IRQL above safe limits whilst using the mutex will cause a Kernel Panic if not appropriately handled.
/// When RAII drops this type, the mutex is released, if the mutex goes out of scope whilst you hold an IRQL that
/// is too high, you will receive a kernel panic.
///