From ed5640d8b587fbcfed7dd7967f3de04b37a76f26 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:06:44 +0200 Subject: Adding upstream version 4:7.4.7. Signed-off-by: Daniel Baumann --- include/comphelper/windowserrorstring.hxx | 68 +++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 include/comphelper/windowserrorstring.hxx (limited to 'include/comphelper/windowserrorstring.hxx') diff --git a/include/comphelper/windowserrorstring.hxx b/include/comphelper/windowserrorstring.hxx new file mode 100644 index 000000000..1b50f1ead --- /dev/null +++ b/include/comphelper/windowserrorstring.hxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#ifndef INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX +#define INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX + +#include +#include +#include +#include + +namespace { + +inline OUString WindowsErrorString(DWORD nErrorCode) +{ + LPWSTR pMsgBuf; + + if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + nErrorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast(&pMsgBuf), + 0, + nullptr) == 0) + return OUString::number(nErrorCode, 16); + + OUString result(o3tl::toU(pMsgBuf)); + result.endsWith("\r\n", &result); + + HeapFree(GetProcessHeap(), 0, pMsgBuf); + + return result; +} + +inline OUString WindowsErrorStringFromHRESULT(HRESULT hr) +{ + // See https://blogs.msdn.microsoft.com/oldnewthing/20061103-07/?p=29133 + // Also https://social.msdn.microsoft.com/Forums/vstudio/en-US/c33d9a4a-1077-4efd-99e8-0c222743d2f8 + // (which refers to https://msdn.microsoft.com/en-us/library/aa382475) + // explains why can't we just reinterpret_cast HRESULT to DWORD Win32 error: + // we might actually have a Win32 error code converted using HRESULT_FROM_WIN32 macro + + DWORD nErrorCode = DWORD(hr); + if (HRESULT(hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0) || hr == S_OK) + { + nErrorCode = HRESULT_CODE(hr); + // https://msdn.microsoft.com/en-us/library/ms679360 mentions that the codes might have + // high word bits set (e.g., bit 29 could be set if error comes from a 3rd-party library). + // So try to restore the original error code to avoid wrong error messages + DWORD nLastError = GetLastError(); + if ((nLastError & 0xFFFF) == nErrorCode) + nErrorCode = nLastError; + } + + return WindowsErrorString(nErrorCode); +} + +} // anonymous namespace + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ -- cgit v1.2.3