I am trying to get the names of a processes handle. I iterate trough a list of all handles and try to get the name like this:
void SystemHandle::GetHandleName()
{
HANDLE hFake;
char* objectName = NULL;
if (NT_SUCCESS(DuplicateHandle(this->process, this->GetNativeHandle(), GetCurrentProcess(), &hFake, 0, FALSE, DUPLICATE_SAME_ACCESS)))
{
POBJECT_TYPE_INFORMATION typeInfo = (POBJECT_TYPE_INFORMATION)new BYTE[0x1000];
PUNICODE_STRING nameInfo = (PUNICODE_STRING)new BYTE[0x1000];
DWORD read;
NTSTATUS status = NtQueryObject(hFake, ObjectTypeInformation, typeInfo, 0x1000, &read);
std::cout << "NtQueryObject: " << status << ", Success: " << NT_SUCCESS(status) << "\n";
objectName = new char[nameInfo->Length];
if (NT_SUCCESS(status) && nameInfo->Length > 0)
{
std::cout << "nameInfo length: " << nameInfo->Length << "\n";
std::cout << "objectName size: " << sizeof(objectName) << "\n";
std::cout << "nameInfo buffer: " << sizeof(nameInfo->Buffer) << "\n";
WideToChar(objectName, nameInfo->Buffer);
strcpy_s(this->handleName, objectName);
}
delete nameInfo;
delete typeInfo;
}
if (hFake) CloseHandle(hFake);
}
void WideToChar(char* Dest, const WCHAR* Source)
{
int i = 0;
// get each char from Source and put it in Dest
while(Source[i] != '\0')
{
Dest[i] = (CHAR)Source[i];
++i;
}
Dest[i] = '\0'; // create the end
}
My problem begins at WideToChar(objectName, nameInfo->Buffer);
when I get to while(Source[i] != '\0')
.
I will then get the following error :
Unhandled exception at 0x00406CE5 in application.
exe: 0xC0000005: Access violation reading location 0xBAADF00D.
You allocate memory for the nameInfo
variable, but do not initialize it. So when you try to use it, nameInfo->Buffer
contains 0xBAADF00D
- Microsoft magic number for uninitialized heap memory. Then you get access violation. You also should use WideCharToMultibyte
function for string conversion.