static void HRESULT_ToString()

in src/ctest_windows.c [34:106]


static void HRESULT_ToString(char* string, size_t bufferSize, HRESULT hr)
{
    /*see if the "system" can provide the code*/
    if (FormatMessageA(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        hr,
        0, /*if you pass in zero, FormatMessage looks for a message for LANGIDs in the following order...*/
        (LPVOID)string, (DWORD)bufferSize, NULL) != 0)
    {
        /*success, SYSTEM was able to find the message*/
        /*return as is*/
        goto allok;
    }
    else
    {
        /*then maaaaaybe one of the other modules provides it*/

        HANDLE currentProcess = GetCurrentProcess();
        /*apparently this cannot fail and returns somewhat of a "pseudo handle"*/

        HMODULE hModules[N_MAX_MODULES];
        DWORD enumModulesUsedBytes;
        if (EnumProcessModules(currentProcess, hModules, sizeof(hModules), &enumModulesUsedBytes) == 0)
        {
            // no modules
        }
        else
        {
            size_t iModule;
            for (iModule = 0; iModule < (enumModulesUsedBytes / sizeof(HMODULE)); iModule++)
            {
                char fileName[MAX_PATH];
                if (GetModuleFileNameA(hModules[iModule], fileName, sizeof(fileName) / sizeof(fileName[0])) == 0)
                {
                    iModule = enumModulesUsedBytes / sizeof(HMODULE);
                    break;
                }
                else
                {
                    /*see if this module */
                    if (FormatMessageA(
                        FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS,
                        hModules[iModule],
                        hr,
                        0,
                        (LPVOID)string, (DWORD)bufferSize, NULL) != 0)
                    {
                        break;
                    }
                    else
                    {
                        /*this module does not have it...*/
                    }
                }
            }

            if (iModule == (enumModulesUsedBytes / sizeof(HMODULE)))
            {
                // not found
            }
            else
            {
                goto allok;
            }
        }
    }

    // on error print the value as is
    (void)snprintf(string, bufferSize, "0x%08lx", hr);

allok:;
}