Erik Swansson
Erik Swansson

Reputation: 157

Can't get thread context from a Windows 64 bit process

Hello so I'm trying to get the thread context of a 64bit process on the system. I've tried using both a 32 bit and a 64 bit solution with the correct functions. But I always end up with the error '0x57', Invalid parameter. A short sample from the 64bit code.

// open a handle to the thread
HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | 
THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, FALSE,
        atoi(argv[1]));
if(hThread  == NULL) {
    printf("Error opening thread handle.. 0x%08x\n", GetLastError());
    return 0;
}

// suspend the thread
if(Wow64SuspendThread(hThread ) == -1) {
    printf("Error suspending thread.. 0x%08x\n", GetLastError());
    CloseHandle(hThread );
    return 0;
}

// get the thread context
WOW64_CONTEXT orig_ctx = {WOW64_CONTEXT_FULL };
if(GetThreadContext(hThread , &orig_ctx) == FALSE) {
    printf("Error  0x%08x\n", GetLastError());
    CloseHandle(hThread );
    return 0;
}

I doubt the handle is wrong, the code worked correctly on 32bit processes. I would greatly appreciate any help or advice. Thanks in advance!

Upvotes: 3

Views: 6812

Answers (1)

jcopenha
jcopenha

Reputation: 3975

The following code when compiled as a 64-bit application successfully retrieves the thread context of a 64-bit thread.

// threadcontext.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>


int _tmain(int argc, _TCHAR* argv[])
{
    // open a handle to the thread
    HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | 
    THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, FALSE, _ttoi(argv[1]));

    if(hThread  == NULL) {
        printf("Error opening thread handle.. 0x%08x\n", GetLastError());
        return 0;
    }   

    // suspend the thread
    if(SuspendThread(hThread ) == -1) {
        printf("Error suspending thread.. 0x%08x\n", GetLastError());
        CloseHandle(hThread );
        return 0;
    }

    // get the thread context
    CONTEXT orig_ctx = { 0 };
    orig_ctx.ContextFlags = CONTEXT_FULL;
    if(GetThreadContext(hThread , &orig_ctx) == FALSE) {
        printf("Error  0x%08x\n", GetLastError());
        CloseHandle(hThread );
        return 0;
    }

    return 0;
}

One thing to notice is that there is no mixing of regular calls and Wow64 calls. The Wow64 calls are for getting the information about 32-bit process running on a 64-bit system.

The other correction is the setting of the ContextFlags member. You were trying to set it during initialization but the ContextFlags member is not the first member in the structure.

Upvotes: 2

Related Questions