使用windbg 来启动exe,然后添加断点来查看相关的变量值,我们使用的是Windbg Preview。
首先需要加载exe 文件到windbg 上面,我们的exe 名称是ConsoleApplication3.exe
设置符号表路劲和源码路径,详细设置如下图
测试代码结构如下:
ConsoleApplication3.cpp的代码如下:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include"Test.h"
VOID SimulateMemoryCorruption();
Test test1;
int __cdecl main(int argv,wchar_t * pArgs[])
{
// std::cout << "Hello World!\n";
wint_t iChar = 0;
test1.g_AppInfo = new CAppInfo(const_cast <LPWSTR>(L"Memory Corruption Sample"), const_cast <LPWSTR>(L"1.0"));
if (!test1.g_AppInfo)
{
return 1;
}
wprintf(L"Press: \n");
wprintf(L" 1 To display application information\n");
wprintf(L" 2 To simulated memory corruption\n");
wprintf(L" 3 To exit\n\n\n>");
while ((iChar = _getwche()) != '3')
{
switch (iChar)
{
case '1':
test1.g_AppInfo->PrintAppInfo();
break;
case '2':
SimulateMemoryCorruption();
wprintf(L"\nMemory Corruption completed\n");
break;
default:
wprintf(L"\nInvalid option\n");
}
wprintf(L"\n\n> ");
}
return 0;
}
VOID SimulateMemoryCorruption()
{
const char* pszWrite ="Corrupt";
BYTE* p = (BYTE*)test1.g_AppInfo;
CopyMemory(p, pszWrite, strlen(pszWrite));
}
Test.h 代码如下:
#pragma once
#include"CAppInfoT.h"
class Test
{
public:
Test();
CAppInfo* g_AppInfo;
};
Test.cpp 代码如下:
#include "Test.h"
Test::Test()
{
}
CAppInfoT.h代码如下:
#pragma once
#include <stdio.h>
#include <windows.h>
class CAppInfo
{
public:
CAppInfo(LPWSTR wszAppName, LPWSTR wszVersion);
VOID PrintAppInfo();
private:
LPWSTR m_wszAppName;
LPWSTR m_wszVersion;
};
CAppInfoT.cpp 代码如下:
#include "CAppInfoT.h"
CAppInfo::CAppInfo(LPWSTR wszAppName, LPWSTR wszVersion)
{
m_wszAppName = wszAppName;
m_wszVersion = wszVersion;
}
VOID CAppInfo::PrintAppInfo()
{
wprintf(L"\nFull application Name: %s\n", m_wszAppName);
wprintf(L"Version: %s\n", m_wszVersion);
}
下面开始通过Windbg 来运行exe:
我们在命令输入行输入设置的断点:bp ConsoleApplication3!CAppInfo::PrintAppInfo
断点设置在code,CAppInfo::PrintAppInfo() 函数处。
VOID CAppInfo::PrintAppInfo()
{
wprintf(L"\nFull application Name: %s\n", m_wszAppName);
wprintf(L"Version: %s\n", m_wszVersion);
}
断点设置好后可以开始运行程序,命令输入行中输入g或者点击任务栏中的go按钮。
ConsoleApplication3.exe开始运行,我们输入1
windbg 中显示断点被触发
下面可以使用指令来查看变量:
从中可以看到下面的代码处有问题:
[+0x000] m_wszAppName : 0x74707572726f43 : "--- memory read error at address 0x00747075`72726f43 ---" [Type: wchar_t *]
查看内存地址的数据,发现是Corrupt
查看源码,下面将g_AppInfo 的内存地址处用“Corrupt”覆盖。
VOID SimulateMemoryCorruption()
{
const char* pszWrite ="Corrupt";
BYTE* p = (BYTE*)test1.g_AppInfo;
CopyMemory(p, pszWrite, strlen(pszWrite));
}