xz: Add a function to print Windows specific error messages.

Native Windows C API functions do not use errno, but instead have to
call GetLastError(). There is not an easy way to convert this error
code into a helpful message, so this creates a wrapper around the
slightly complicated FormatMessage() function.

The new message_windows_error() function calls message_error() under the
hood, so it will set the exit status to 1.
This commit is contained in:
Jia Tan 2023-10-21 20:32:05 +08:00
parent b43c3e48bf
commit d6d1e40f19
2 changed files with 36 additions and 0 deletions

View File

@ -806,6 +806,28 @@ message_signal_handler(void)
} }
#ifdef _MSC_VER
extern void
message_windows_error(const char* message, DWORD error_code)
{
char *error_message;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&error_message, 0, NULL)) {
message_error("%s: %s", message, error_message);
}
else {
message_error("%s\n", message);
}
LocalFree(error_message);
}
#endif
extern const char * extern const char *
message_strm(lzma_ret code) message_strm(lzma_ret code)
{ {

View File

@ -84,6 +84,20 @@ tuklib_attr_noreturn
extern void message_signal_handler(void); extern void message_signal_handler(void);
#ifdef _MSC_VER
/// \brief Print an error message using a Windows specific error code
///
/// The function uses message_error() internally, so it will set the
/// exit code to 1 after printing.
///
/// \param message Message describing where the error occurred
/// \param error_code Error number from GetLastError()
extern void
message_windows_error(const char* message, DWORD error_code);
#endif
/// Convert lzma_ret to a string. /// Convert lzma_ret to a string.
extern const char *message_strm(lzma_ret code); extern const char *message_strm(lzma_ret code);