LibreOffice Module bridges (master) 1
msvc_shared/except.cxx
Go to the documentation of this file.
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 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20#include <sal/config.h>
21
22#include <memory>
23
24#include <malloc.h>
25#include <new.h>
26#include <typeinfo>
27#include <signal.h>
28
29#include <rtl/alloc.h>
30#include <rtl/strbuf.hxx>
31#include <rtl/ustrbuf.hxx>
32#include <sal/log.hxx>
33#include <osl/mutex.hxx>
34
35#include <com/sun/star/uno/Any.hxx>
36#include <unordered_map>
37#include <except.hxx>
38#include <msvc/except.hxx>
39
40#if defined(_M_IX86)
41#include <msvc/x86.hxx>
42#elif defined(_M_AMD64)
43#include <msvc/amd64.hxx>
44#elif defined(_M_ARM64)
45#include <msvc/arm64.hxx>
46#else
47#error "Unsupported machine type"
48#endif
49
50#pragma pack(push, 8)
51
52using namespace ::com::sun::star;
53
54static OUString toUNOname(OUString const& rRTTIname) noexcept
55{
56 OUStringBuffer aRet(64);
57 OUString aStr(rRTTIname.copy(4, rRTTIname.getLength() - 4 - 2)); // filter .?AUzzz@yyy@xxx@@
58 sal_Int32 nPos = aStr.getLength();
59 while (nPos > 0)
60 {
61 sal_Int32 n = aStr.lastIndexOf('@', nPos);
62 aRet.append(aStr.subView(n + 1, nPos - n - 1));
63 if (n >= 0)
64 aRet.append('.');
65 nPos = n;
66 }
67 return aRet.makeStringAndClear();
68}
69
70static OUString toRTTIname(OUString const& rUNOname) noexcept
71{
72 OUStringBuffer aRet(64);
73 aRet.append(".?AV"); // class ".?AV"; struct ".?AU"
74 sal_Int32 nPos = rUNOname.getLength();
75 while (nPos > 0)
76 {
77 sal_Int32 n = rUNOname.lastIndexOf('.', nPos);
78 aRet.append(OUString::Concat(rUNOname.subView(n + 1, nPos - n - 1)) + "@");
79 nPos = n;
80 }
81 aRet.append('@');
82 return aRet.makeStringAndClear();
83}
84
86
87ExceptionTypeInfoWrapper* RTTInfos::getInfo(OUString const& rUNOname) noexcept
88{
90 t_string2PtrMap::const_iterator const iFind(m_allRTTI.find(rUNOname));
91
92 if (iFind != m_allRTTI.end())
93 pRTTI = static_cast<ExceptionTypeInfoWrapper*>(iFind->second);
94 else
95 {
96 OString aRawName(OUStringToOString(toRTTIname(rUNOname), RTL_TEXTENCODING_ASCII_US));
97 // Wrap new ExceptionTypeInfo in ExceptionTypeInfoWrapper to preserve length info
98 pRTTI = new (std::malloc(sizeof(ExceptionTypeInfoWrapper) + aRawName.getLength()))
99 ExceptionTypeInfoWrapper(nullptr, aRawName.getStr());
100
101 std::pair<t_string2PtrMap::iterator, bool> insertion(
102 m_allRTTI.insert(t_string2PtrMap::value_type(rUNOname, pRTTI)));
103 assert(insertion.second && "### rtti insertion failed?!");
104 }
105
106 return pRTTI;
107}
108
109type_info* RTTInfos::get(OUString const& rUNOname, int* len) noexcept
110{
111 static RTTInfos* s_pRTTIs = new RTTInfos();
112
113 static_assert(sizeof(ExceptionTypeInfo) == sizeof(std::type_info),
114 "### type info structure size differ!");
115
116 osl::MutexGuard aGuard(s_pRTTIs->m_aMutex);
117 ExceptionTypeInfoWrapper* pETIW = s_pRTTIs->getInfo(rUNOname);
118 if (len)
119 *len = pETIW->get_type_info_size();
120 return pETIW->get_type_info();
121}
122
124
126
128
130{
131 SAL_INFO("bridges", "> freeing exception infos... <");
132
133 std::unique_lock aGuard(m_aMutex);
134 for (auto& rEntry : m_allRaiseInfos)
135 delete static_cast<RaiseInfo*>(rEntry.second);
136}
137
139{
140 static ExceptionInfos* s_pInfos = []() {
141#if defined _M_AMD64 || defined _M_ARM64
142 SYSTEM_INFO systemInfo;
143 GetSystemInfo(&systemInfo);
144 allocationGranularity = systemInfo.dwAllocationGranularity;
145#endif
146 return new ExceptionInfos();
147 }();
148
149 assert(pTD
150 && (pTD->eTypeClass == typelib_TypeClass_STRUCT
151 || pTD->eTypeClass == typelib_TypeClass_EXCEPTION));
152
153 RaiseInfo* pRaiseInfo;
154
155 OUString const& rTypeName = OUString::unacquired(&pTD->pTypeName);
156 std::unique_lock aGuard(s_pInfos->m_aMutex);
157 t_string2PtrMap::const_iterator const iFind(s_pInfos->m_allRaiseInfos.find(rTypeName));
158 if (iFind != s_pInfos->m_allRaiseInfos.end())
159 pRaiseInfo = static_cast<RaiseInfo*>(iFind->second);
160 else
161 {
162 pRaiseInfo = new RaiseInfo(pTD);
163
164 std::pair<t_string2PtrMap::iterator, bool> insertion(s_pInfos->m_allRaiseInfos.insert(
165 t_string2PtrMap::value_type(rTypeName, static_cast<void*>(pRaiseInfo))));
166 assert(insertion.second && "### raise info insertion failed?!");
167 }
168
169 return pRaiseInfo;
170}
171
172void msvc_raiseException(uno_Any* pUnoExc, uno_Mapping* pUno2Cpp)
173{
174 // no ctor/dtor in here: this leads to dtors called twice upon RaiseException()!
175 // thus this obj file will be compiled without opt, so no inlining of
176 // ExceptionInfos::getRaiseInfo()
177
178 // construct cpp exception object
179 typelib_TypeDescription* pTD = nullptr;
180 TYPELIB_DANGER_GET(&pTD, pUnoExc->pType);
181
182 void* pCppExc = alloca(pTD->nSize);
183 ::uno_copyAndConvertData(pCppExc, pUnoExc->pData, pTD, pUno2Cpp);
184
185 ULONG_PTR arFilterArgs[MSVC_EH_PARAMETERS];
186 arFilterArgs[0] = MSVC_EH_MAGIC_PARAM;
187 arFilterArgs[1] = reinterpret_cast<ULONG_PTR>(pCppExc);
188 arFilterArgs[2] = reinterpret_cast<ULONG_PTR>(ExceptionInfos::getRaiseInfo(pTD));
189#if MSVC_EH_PARAMETERS == 4
190 arFilterArgs[3] = reinterpret_cast<RaiseInfo*>(arFilterArgs[2])->_codeBase;
191#endif
192
193 // Destruct uno exception
194 ::uno_any_destruct(pUnoExc, nullptr);
195 TYPELIB_DANGER_RELEASE(pTD);
196
197 // last point to release anything not affected by stack unwinding
198 RaiseException(MSVC_EH_MAGIC_CODE, EXCEPTION_NONCONTINUABLE, MSVC_EH_PARAMETERS, arFilterArgs);
199}
200
201// This function does the same check as __CxxDetectRethrow from msvcrt (see its
202// crt/src/vcruntime/mgdframe.cpp). But it does not alter the global state, i.e. it does not
203// increment __ProcessingThrow, and so does not break following exception handling. We rely on the
204// definition of EHExceptionRecord, PER_IS_MSVC_EH and PER_PTHROW, that are current as of msvcrt
205// 2017 (14.14.26428).
206static bool DetectRethrow(void* ppExcept)
207{
208 struct EHExceptionRecord
209 {
210 DWORD ExceptionCode;
211 DWORD ExceptionFlags;
212 struct _EXCEPTION_RECORD* ExceptionRecord;
213 PVOID ExceptionAddress;
214 DWORD NumberParameters;
215#if MSVC_EH_PARAMETERS == 3
216 struct EHParameters
217#else
218 struct alignas(8)
219#endif
220 {
221 DWORD magicNumber;
222 PVOID pExceptionObject;
223 PVOID pThrowInfo;
224#if MSVC_EH_PARAMETERS == 4
225 PVOID pThrowImageBase;
226#endif
227 } params;
228 };
229
230 constexpr auto PER_IS_MSVC_EH = [](EHExceptionRecord* p) {
231 return p->ExceptionCode == MSVC_EH_MAGIC_CODE && p->NumberParameters == MSVC_EH_PARAMETERS
232 && (p->params.magicNumber == MSVC_EH_MAGIC_PARAM
233 || p->params.magicNumber == MSVC_EH_MAGIC_PARAM + 1
234 || p->params.magicNumber == MSVC_EH_MAGIC_PARAM + 2);
235 };
236
237 constexpr auto PER_PTHROW = [](EHExceptionRecord* p) { return p->params.pThrowInfo; };
238
239 EHExceptionRecord* pExcept;
240 if (!ppExcept)
241 return false;
242 pExcept = *static_cast<EHExceptionRecord**>(ppExcept);
243 if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr)
244 return true;
245 return false;
246}
247
248int msvc_filterCppException(EXCEPTION_POINTERS* pPointers, uno_Any* pUnoExc, uno_Mapping* pCpp2Uno)
249{
250 if (pPointers == nullptr)
251 return EXCEPTION_CONTINUE_SEARCH;
252
253 EXCEPTION_RECORD* pRecord = pPointers->ExceptionRecord;
254
255 // Handle only C++ exceptions:
256 if (pRecord == nullptr || pRecord->ExceptionCode != MSVC_EH_MAGIC_CODE)
257 return EXCEPTION_CONTINUE_SEARCH;
258
259 const bool rethrow = DetectRethrow(&pRecord);
260 assert(pRecord == pPointers->ExceptionRecord);
261
262 if (rethrow && pRecord == pPointers->ExceptionRecord)
263 pRecord = *reinterpret_cast<EXCEPTION_RECORD**>(__current_exception());
264
265 // Rethrow: handle only C++ exceptions:
266 if (pRecord == nullptr || pRecord->ExceptionCode != MSVC_EH_MAGIC_CODE)
267 return EXCEPTION_CONTINUE_SEARCH;
268
269 if (pRecord->NumberParameters == MSVC_EH_PARAMETERS
270#if MSVC_EH_PARAMETERS == 4
271 && pRecord->ExceptionInformation[0] == MSVC_EH_MAGIC_PARAM
272#endif
273 && pRecord->ExceptionInformation[1] != 0 && pRecord->ExceptionInformation[2] != 0
274#if MSVC_EH_PARAMETERS == 4
275 && pRecord->ExceptionInformation[3] != 0
276#endif
277 )
278 {
279 // ExceptionInformation[1] is the address of the thrown object
280 // (or the address of a pointer to it, in most cases when it
281 // is a C++ class, obviously).
282
283 // [2] is the pThrowInfo pointer
284 RaiseInfo* pInfo = reinterpret_cast<RaiseInfo*>(pRecord->ExceptionInformation[2]);
285
286#if MSVC_EH_PARAMETERS == 3
287 ULONG_PTR base = 0;
288 DWORD* types = reinterpret_cast<DWORD*>(pInfo->_types);
289#else
290 // [3] is the image base address which is added the 32-bit
291 // rva_t fields in throwinfo to get actual 64-bit addresses
292 ULONG_PTR base = pRecord->ExceptionInformation[3];
293 DWORD* types = reinterpret_cast<DWORD*>(base + pInfo->_types);
294#endif
295 if (types != nullptr && types[0] != 0 && types[1] != 0)
296 {
297 ExceptionType* et = reinterpret_cast<ExceptionType*>(base + types[1]);
298 if (et->_pTypeInfo != 0)
299 {
300 OUString aRTTIname(OStringToOUString(
301 reinterpret_cast<ExceptionTypeInfo*>(base + et->_pTypeInfo)->m_d_name,
302 RTL_TEXTENCODING_ASCII_US));
303 OUString aUNOname(toUNOname(aRTTIname));
304
305 typelib_TypeDescription* pExcTD = nullptr;
306 typelib_typedescription_getByName(&pExcTD, aUNOname.pData);
307 if (pExcTD == nullptr)
308 {
309 OUString sMsg = "[mscx_uno bridge error] UNO type of C++ exception unknown: \""
310 + aUNOname + "\", RTTI-name=\"" + aRTTIname + "\"!";
311
312 uno::RuntimeException exc(sMsg);
314 pUnoExc, &exc, cppu::UnoType<decltype(exc)>::get().getTypeLibType(),
315 pCpp2Uno);
316 }
317 else
318 {
319 // construct uno exception any
321 pUnoExc, reinterpret_cast<void*>(pRecord->ExceptionInformation[1]), pExcTD,
322 pCpp2Uno);
324 }
325
326 return EXCEPTION_EXECUTE_HANDLER;
327 }
328 }
329 }
330
331 // though this unknown exception leaks now, no user-defined exception
332 // is ever thrown through the binary C-UNO dispatcher call stack.
333 uno::RuntimeException exc("[mscx_uno bridge error] unexpected C++ exception occurred!");
335 pUnoExc, &exc, cppu::UnoType<decltype(exc)>::get().getTypeLibType(), pCpp2Uno);
336 return EXCEPTION_EXECUTE_HANDLER;
337}
338
339#pragma pack(pop)
void SAL_CALL uno_type_any_constructAndConvert(uno_Any *pDest, void *pSource, typelib_TypeDescriptionReference *pType, uno_Mapping *mapping) SAL_THROW_EXTERN_C()
void SAL_CALL uno_any_constructAndConvert(uno_Any *pDest, void *pSource, typelib_TypeDescription *pTypeDescr, uno_Mapping *mapping) SAL_THROW_EXTERN_C()
static RaiseInfo * getRaiseInfo(typelib_TypeDescription *pTD) noexcept
static DWORD allocationGranularity
~ExceptionInfos() noexcept
std::mutex m_aMutex
t_string2PtrMap m_allRaiseInfos
type_info * get_type_info()
Definition: msvc/except.hxx:85
virtual ~ExceptionTypeInfo() noexcept
ExceptionTypeInfoWrapper * getInfo(OUString const &rUNOname) noexcept
RTTInfos() noexcept
osl::Mutex m_aMutex
Definition: msvc/except.hxx:91
static type_info * get(OUString const &rUNOname, int *len=nullptr) noexcept
void ** __current_exception()
void const * base
void * p
sal_Int64 n
sal_uInt16 nPos
#define SAL_INFO(area, stream)
aStr
struct _uno_Mapping uno_Mapping
Definition: msvc/except.hxx:33
struct _typelib_TypeDescription typelib_TypeDescription
Definition: msvc/except.hxx:53
constexpr DWORD MSVC_EH_MAGIC_PARAM
Definition: msvc/except.hxx:38
constexpr DWORD MSVC_EH_MAGIC_CODE
Definition: msvc/except.hxx:40
struct _uno_Any uno_Any
Definition: msvc/except.hxx:32
int msvc_filterCppException(EXCEPTION_POINTERS *pPointers, uno_Any *pUnoExc, uno_Mapping *pCpp2Uno)
static OUString toUNOname(OUString const &rRTTIname) noexcept
static OUString toRTTIname(OUString const &rUNOname) noexcept
void msvc_raiseException(uno_Any *pUnoExc, uno_Mapping *pUno2Cpp)
static bool DetectRethrow(void *ppExcept)
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
sal_uInt32 _pTypeInfo
Definition: amd64.hxx:29
sal_uInt32 _types
Definition: amd64.hxx:47
void SAL_CALL typelib_typedescription_release(typelib_TypeDescription *pTD) SAL_THROW_EXTERN_C()
void SAL_CALL typelib_typedescription_getByName(typelib_TypeDescription **ppRet, rtl_uString *pName) SAL_THROW_EXTERN_C()