从服务 returns 调用的 VirtualProtectEx false 但 GetLastError 为 0(成功)

VirtualProtectEx called from service returns false but GetLastError is 0 (success)

为什么从服务应用程序调用时 VirtualProtectEx 函数失败?已经从一个简单的应用程序执行,一切正常。

那么,有没有可能让这个功能也能从服务中工作?

这是我的代码:

void WriteProcMem(HANDLE hProcess, VOID *pAddr)
{
    DWORD oldProtection;
    DWORD bytesWritten = 0;
    BYTE data[] = { 0x90, 0x90, 0x90, 0x90, 0x90 }; // Only a example of assembly data

    if (!VirtualProtectEx(hProcess, (LPVOID)pAddr, sizeof(DWORD), PAGE_EXECUTE_READWRITE, &oldProtection)) {
        printf("\n VirtualProtectEx() error - %d\n", GetLastError());

        //=============== To debug from service application ===================

        FILE * pFile;
        pFile = fopen("C:\myfile.txt", "w");
        if (pFile != NULL)
        {

            char * str = new char[100];
            sprintf(str, "%d", GetLastError());

            fputs(str, pFile);
            fclose(pFile);
        }

        //======================================================================

        return;
    }

    if (WriteProcessMemory(hProcess, (LPVOID)pAddr, &data, sizeof(data), &bytesWritten)) {

        printf("\n Data written success! \n");

        if (!VirtualProtectEx(hProcess, (LPVOID)pAddr, sizeof(DWORD), oldProtection, &oldProtection))
            printf("\n VirtualProtectEx() [2] error - %d \n", GetLastError());
    }

}

The service executes a child process in debug mode and with SYSTEM account, these data should be written on "child.exe".


版本:

@S.M 回答后。 GetLastError() 返回的实际值是:

ERROR_INVALID_HANDLE: 6 (0x6) - The handle is invalid.

但是正如我已经说过的,当不作为服务执行时,一切正常。为什么会这样?

这就是你标题上的答案。

pFile = fopen("C:\myfile.txt", "w"); 调用 Windows API 函数并可能重置最后一个错误代码。因此,正确处理最后一个错误代码是在有趣的 API 调用后立即将其保存到变量中。试试下面的代码,你应该在 VirtualProtectEx 调用后得到真正的错误代码。

if (!VirtualProtectEx(hProcess, (LPVOID)pAddr, sizeof(DWORD), PAGE_EXECUTE_READWRITE, &oldProtection)) {
    int err_code = GetLastError();
    printf("\n VirtualProtectEx() error - %d\n", err_code):

    //=============== To debug from service application ===================

    FILE * pFile = fopen("C:\myfile.txt", "w");
    if (pFile != NULL)
    {
        fprintf(pFile, "%d\n", err_code);
        fclose(pFile);
    }
    ...