From d6d1e40f195440b198e6c57d5283b63037dcee92 Mon Sep 17 00:00:00 2001 From: Jia Tan Date: Sat, 21 Oct 2023 20:32:05 +0800 Subject: [PATCH] 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. --- src/xz/message.c | 22 ++++++++++++++++++++++ src/xz/message.h | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/xz/message.c b/src/xz/message.c index 7756b5b2..0aabbadf 100644 --- a/src/xz/message.c +++ b/src/xz/message.c @@ -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 * message_strm(lzma_ret code) { diff --git a/src/xz/message.h b/src/xz/message.h index 20381705..a60d9693 100644 --- a/src/xz/message.h +++ b/src/xz/message.h @@ -84,6 +84,20 @@ tuklib_attr_noreturn 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. extern const char *message_strm(lzma_ret code);