運用的技術跟應用層大體一致,倒是互斥的問題干擾我很久。已開始使用的是 FastMutex,但是它會提升 IRQL 到 APC_LEVEL,顯然寫文件的服務函數都只能跑在 PASSIVE_LEVEL 下,最後只好使用了 Event 。
示例代碼說明:
GetCurrentTimeString() 詳見前文:
GetCurrentProcessName() 詳見前文:Windows 驅動:獲取當前進程名
示例代碼:
#include <stdarg.h>
//
// Enable log event: for synchronization
//
static KEVENT gs_eventEnableKeLog;
//----------------------------------------------------------------------
//
// initialization interface
//
//----------------------------------------------------------------------
//
// initialize the global data structures, when the driver is loading.
// (Call in DriverEntry())
//
NTSTATUS
Dbg_LoadInit()
{
// Initialize the event
KeInitializeEvent(&gs_eventEnableKeLog, SynchronizationEvent, TRUE);
return STATUS_SUCCESS;
}
static void WaitForWriteMutex()
{
// Wait for enable log event
KeWaitForSingleObject(&gs_eventEnableKeLog, Executive, KernelMode, TRUE, 0);
KeClearEvent(&gs_eventEnableKeLog);
}
static void ReleaseWriteMutex()
{
// Set enable log event
KeSetEvent(&gs_eventEnableKeLog, 0, FALSE);
}
//----------------------------------------------------------------------
//
// DbgKeLog
//
// Trace to file.
//
//----------------------------------------------------------------------
BOOLEAN
DbgKeLog(LPCSTR lpszLog, ...)
{
if (KeGetCurrentIrql() > PASSIVE_LEVEL)
{
TOKdPrint(("TKeHook: KeLog: IRQL too hight...\n"));
return FALSE;
}
WaitForWriteMutex();
__try
{
IO_STATUS_BLOCK iOStatus;
OBJECT_ATTRIBUTES objectAttributes;