Search code examples
c++windowswinapi

Which API returns the message for NTSTATUS?


Is there a Windows API returning the message text for NTSTATUS codes?

i.e. something similar to WinAPI: FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, ....)

FormatMessage doesn't work - neither on the ntstatus code, nor on HRESULT_FROM_NT(ntstatus).


Solution

  • According to this MS KB article, FormatMessage API can be used to convert NTSTATUS code to text.
    The article above contains a complete usage example.

    Important notes for the usage:

    1. dwFlags (the 1st param) should include:
      FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE
      
    2. lpSource (the 2nd param) should be the HMODULE of "NTDLL.DLL" (can be acquired via LoadLibrary("NTDLL.DLL")).

    Another alernative if you are using C++, is to use std::system_category (available since C++ 11).

    #include <system_error>  // required for std::system_category
    #include <iostream>
    
    // ...
    
    std::string message1 = std::system_category().message(STATUS_TIMEOUT);
    std::cout << message1 << std::endl;
    

    Output:

    The wait operation timed out.
    

    Note: not all NTSTATUS values are supported by std::system_category(), for some you will get "unknown error".