[BSOD]driver_unloaded_without_cancelling_pending_operations

Rainie
職場學習筆記
Published in
Jan 27, 2021

前陣子公司的 driver 在 win7 上碰到了 BSOD,error message 表示driver 在 unload 時資源沒有釋放,底下提供幾個 API 組合是當你的 driver 有 call 到這些 API 時,driver unload 一定要 call 相對應的釋放 API 去清除資源。

Communication Port

FltCreateCommunicationPort
FltCloseCommunicationPort

Process Notify Routine

PsSetCreateProcesNotifyRoutineEx(_, false)
PsSetCreateProcesNotifyRoutineEx(_, true)

Thread Notify Routine

PsSetCreateThreadNotifyRoutine
PsRemoveCreateThreadNotifyRoutine

Image Load Notify Routine

PsSetLoadImageNotifyRoutine
PsRemoveLoadImageNotifyRoutine

Create System Thread

PsCreateSystemThread
PsTerminateSystemThread

這次踩到的坑的就是這個!我們的 code 的確有在 unload 的時候 call psTermincateSystemThread 去釋放資源,但是系統仍然 BSOD !

後來參考微軟提供的 driver sample code,用到 system thread 的話除了 PsTermicateSystemThread 還必須把 thread handle 轉換成 thread pointer,在 unload 的時候 call ObDereferenceObject 把資源釋放。

底下僅列出跟 thread 有關的 context :

完整的 driver sample code : https://github.com/microsoft/Windows-driver-samples/blob/master/general/cancel/sys/cancel.c

還有很多成對的 API 沒辦法一一條列,避免方式是當使用到一個新的 API 時就去把官方文件詳細看過,特別是 Remarks 的部分!需要呼叫釋放的 API 時這裡一定會註明,根據文件的規範設計才不會出一些奇怪的 Bug。

--

--