Windows 驅動:向 DbgPrintf 一樣將調試資訊輸出到檔案

來源:互聯網
上載者:User

運用的技術跟應用程式層大體一致,倒是互斥的問題幹擾我很久。已開始使用的是 FastMutex,但是它會提升 IRQL 到 APC_LEVEL,顯然寫檔案的服務函數都只能跑在 PASSIVE_LEVEL 下,最後只好使用了 Event 。

範例程式碼說明:

GetCurrentTimeString() 詳見前文:Windows 驅動中擷取系統目前時間,產生格式字串

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;
  NTSTATUS status;
  HANDLE FileHandle;
  UNICODE_STRING fileName;
  static WCHAR s_szLogFile[] = L"//??//C://KeLog.log";
  LPCWSTR lpszLogFile = s_szLogFile;

  PAGED_CODE();
  if (lpszLogFile == NULL)
   lpszLogFile = s_szLogFile;

  //get a handle to the log file object
  fileName.Buffer = NULL;
  fileName.Length = 0;
  fileName.MaximumLength = (wcslen(lpszLogFile) + 1) * sizeof(WCHAR);
  fileName.Buffer = ExAllocatePool(PagedPool, fileName.MaximumLength);
  if (!fileName.Buffer)
  {
   ReleaseWriteMutex();
   TOKdPrint(("TKeHook: KeLog: ExAllocatePool Failed.../n"));
   return FALSE;
  }
  RtlZeroMemory(fileName.Buffer, fileName.MaximumLength);
  status = RtlAppendUnicodeToString(&fileName, (PWSTR)lpszLogFile);

  InitializeObjectAttributes (&objectAttributes,
         (PUNICODE_STRING)&fileName,
         OBJ_CASE_INSENSITIVE,
         NULL,
         NULL );

  status = ZwCreateFile(&FileHandle,
        FILE_APPEND_DATA,
        &objectAttributes,
        &IoStatus,
        0,
        FILE_ATTRIBUTE_NORMAL,
        FILE_SHARE_WRITE,
        FILE_OPEN_IF,
        FILE_SYNCHRONOUS_IO_NONALERT,
        NULL,    
        0
        );

  if(NT_SUCCESS(status))
  {
   static CHAR szBuffer[1024];
   PCHAR  pszBuffer = szBuffer;
   ULONG  ulBufSize;
   int   nSize;
   va_list  pArglist;

   // add process name and time string
   sprintf(szBuffer, "[%s][%16s:%d] "
    , GetCurrentTimeString()
    , GetCurrentProcessName()
    , (ULONG)PsGetCurrentProcessId()
    );
   pszBuffer = szBuffer + strlen(szBuffer);
   
   va_start(pArglist, lpszLog);  
   // The last argument to wvsprintf points to the arguments  
   nSize = _vsnprintf( pszBuffer, 1024 - 32, lpszLog, pArglist);  
   // The va_end macro just zeroes out pArgList for no good reason  
   va_end(pArglist);
   if (nSize > 0)
   {
    //
    pszBuffer[nSize] = 0;
   }
   else
   {
    pszBuffer[0] = 0;
   }

   ulBufSize = strlen(szBuffer);
   ZwWriteFile(FileHandle,
       NULL,
       NULL,
       NULL,
       &IoStatus,
       szBuffer,
       ulBufSize,
       NULL,
       NULL
       );
   ZwClose(FileHandle);
  }
  if (fileName.Buffer)
   ExFreePool (fileName.Buffer);

  ReleaseWriteMutex();
  return TRUE;
 }
 __except(EXCEPTION_EXECUTE_HANDLER)
 {
  ReleaseWriteMutex();
  TOKdPrint(("TKeHook: DbgKeLog() except: %0xd !!/n", GetExceptionCode()));
  return FALSE;
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.