获取进程句柄名称

时间:2015-01-09 05:07:43

标签: c++ handle widechar

我正在尝试获取进程句柄的名称。我遍历所有句柄的列表,并尝试得到这样的名称:

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
}

当我到达WideToChar(objectName, nameInfo->Buffer);时,问题从while(Source[i] != '\0')开始。
然后我会收到以下错误

Unhandled exception at 0x00406CE5 in application.
exe: 0xC0000005: Access violation reading location 0xBAADF00D.

2 个答案:

答案 0 :(得分:1)

您为nameInfo变量分配内存,但不初始化它。因此,当您尝试使用它时,nameInfo->Buffer包含0xBAADF00D - 未初始化堆内存的Microsoft幻数。然后你得到访问冲突。您还应该使用WideCharToMultibyte函数进行字符串转换。

答案 1 :(得分:0)

涡卷

    while(Source[i] != '\0')
    {
        Dest[i] = (CHAR)Source[i];

        ++i;
    }

在if条件中:

if(Source != NULL){
}