1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  */
9 
10 #ifndef INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX
11 #define INCLUDED_COMPHELPER_WINDOWSERRORSTRING_HXX
12 
13 #include <prewin.h>
14 #include <postwin.h>
15 #include <rtl/ustring.hxx>
16 #include <o3tl/char16_t2wchar_t.hxx>
17 
18 namespace {
19 
WindowsErrorString(DWORD nErrorCode)20 inline OUString WindowsErrorString(DWORD nErrorCode)
21 {
22     LPWSTR pMsgBuf;
23 
24     if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
25                        nullptr,
26                        nErrorCode,
27                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
28                        reinterpret_cast<LPWSTR>(&pMsgBuf),
29                        0,
30                        nullptr) == 0)
31         return OUString::number(nErrorCode, 16);
32 
33     OUString result(o3tl::toU(pMsgBuf));
34     result.endsWith("\r\n", &result);
35 
36     HeapFree(GetProcessHeap(), 0, pMsgBuf);
37 
38     return result;
39 }
40 
WindowsErrorStringFromHRESULT(HRESULT hr)41 inline OUString WindowsErrorStringFromHRESULT(HRESULT hr)
42 {
43     // See https://blogs.msdn.microsoft.com/oldnewthing/20061103-07/?p=29133
44     // Also https://social.msdn.microsoft.com/Forums/vstudio/en-US/c33d9a4a-1077-4efd-99e8-0c222743d2f8
45     // (which refers to https://msdn.microsoft.com/en-us/library/aa382475)
46     // explains why can't we just reinterpret_cast HRESULT to DWORD Win32 error:
47     // we might actually have a Win32 error code converted using HRESULT_FROM_WIN32 macro
48 
49     DWORD nErrorCode = DWORD(hr);
50     if (HRESULT(hr & 0xFFFF0000) == MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, 0) || hr == S_OK)
51     {
52         nErrorCode = HRESULT_CODE(hr);
53         // https://msdn.microsoft.com/en-us/library/ms679360 mentions that the codes might have
54         // high word bits set (e.g., bit 29 could be set if error comes from a 3rd-party library).
55         // So try to restore the original error code to avoid wrong error messages
56         DWORD nLastError = GetLastError();
57         if ((nLastError & 0xFFFF) == nErrorCode)
58             nErrorCode = nLastError;
59     }
60 
61     return WindowsErrorString(nErrorCode);
62 }
63 
64 } // anonymous namespace
65 
66 #endif
67 
68 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
69