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 
52 using namespace ::com::sun::star;
53 
54 static OUString toUNOname(OUString const& rRTTIname) throw()
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 
70 static OUString toRTTIname(OUString const& rUNOname) throw()
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(rUNOname.subView(n + 1, nPos - n - 1));
79  aRet.append('@');
80  nPos = n;
81  }
82  aRet.append('@');
83  return aRet.makeStringAndClear();
84 }
85 
87 
88 ExceptionTypeInfoWrapper* RTTInfos::getInfo(OUString const& rUNOname) throw()
89 {
91  t_string2PtrMap::const_iterator const iFind(m_allRTTI.find(rUNOname));
92 
93  if (iFind != m_allRTTI.end())
94  pRTTI = static_cast<ExceptionTypeInfoWrapper*>(iFind->second);
95  else
96  {
97  OString aRawName(OUStringToOString(toRTTIname(rUNOname), RTL_TEXTENCODING_ASCII_US));
98  // Wrap new ExceptionTypeInfo in ExceptionTypeInfoWrapper to preserve length info
99  pRTTI = new (std::malloc(sizeof(ExceptionTypeInfoWrapper) + aRawName.getLength()))
100  ExceptionTypeInfoWrapper(nullptr, aRawName.getStr());
101 
102  std::pair<t_string2PtrMap::iterator, bool> insertion(
103  m_allRTTI.insert(t_string2PtrMap::value_type(rUNOname, pRTTI)));
104  assert(insertion.second && "### rtti insertion failed?!");
105  }
106 
107  return pRTTI;
108 }
109 
110 type_info* RTTInfos::get(OUString const& rUNOname, int* len) throw()
111 {
112  static RTTInfos* s_pRTTIs = new RTTInfos();
113 
114  static_assert(sizeof(ExceptionTypeInfo) == sizeof(std::type_info),
115  "### type info structure size differ!");
116 
117  osl::MutexGuard aGuard(s_pRTTIs->m_aMutex);
118  ExceptionTypeInfoWrapper* pETIW = s_pRTTIs->getInfo(rUNOname);
119  if (len)
120  *len = pETIW->get_type_info_size();
121  return pETIW->get_type_info();
122 }
123 
124 RTTInfos::RTTInfos() throw() {}
125 
127 
129 
131 {
132  SAL_INFO("bridges", "> freeing exception infos... <");
133 
134  osl::MutexGuard aGuard(m_aMutex);
135  for (auto& rEntry : m_allRaiseInfos)
136  delete static_cast<RaiseInfo*>(rEntry.second);
137 }
138 
140 {
141  static ExceptionInfos* s_pInfos = []() {
142 #if defined _M_AMD64 || defined _M_ARM64
143  SYSTEM_INFO systemInfo;
144  GetSystemInfo(&systemInfo);
145  allocationGranularity = systemInfo.dwAllocationGranularity;
146 #endif
147  return new ExceptionInfos();
148  }();
149 
150  assert(pTD
151  && (pTD->eTypeClass == typelib_TypeClass_STRUCT
152  || pTD->eTypeClass == typelib_TypeClass_EXCEPTION));
153 
154  RaiseInfo* pRaiseInfo;
155 
156  OUString const& rTypeName = OUString::unacquired(&pTD->pTypeName);
157  osl::MutexGuard aGuard(s_pInfos->m_aMutex);
158  t_string2PtrMap::const_iterator const iFind(s_pInfos->m_allRaiseInfos.find(rTypeName));
159  if (iFind != s_pInfos->m_allRaiseInfos.end())
160  pRaiseInfo = static_cast<RaiseInfo*>(iFind->second);
161  else
162  {
163  pRaiseInfo = new RaiseInfo(pTD);
164 
165  std::pair<t_string2PtrMap::iterator, bool> insertion(s_pInfos->m_allRaiseInfos.insert(
166  t_string2PtrMap::value_type(rTypeName, static_cast<void*>(pRaiseInfo))));
167  assert(insertion.second && "### raise info insertion failed?!");
168  }
169 
170  return pRaiseInfo;
171 }
172 
173 void msvc_raiseException(uno_Any* pUnoExc, uno_Mapping* pUno2Cpp)
174 {
175  // no ctor/dtor in here: this leads to dtors called twice upon RaiseException()!
176  // thus this obj file will be compiled without opt, so no inlining of
177  // ExceptionInfos::getRaiseInfo()
178 
179  // construct cpp exception object
180  typelib_TypeDescription* pTD = nullptr;
181  TYPELIB_DANGER_GET(&pTD, pUnoExc->pType);
182 
183  void* pCppExc = alloca(pTD->nSize);
184  ::uno_copyAndConvertData(pCppExc, pUnoExc->pData, pTD, pUno2Cpp);
185 
186  ULONG_PTR arFilterArgs[MSVC_EH_PARAMETERS];
187  arFilterArgs[0] = MSVC_EH_MAGIC_PARAM;
188  arFilterArgs[1] = reinterpret_cast<ULONG_PTR>(pCppExc);
189  arFilterArgs[2] = reinterpret_cast<ULONG_PTR>(ExceptionInfos::getRaiseInfo(pTD));
190 #if MSVC_EH_PARAMETERS == 4
191  arFilterArgs[3] = reinterpret_cast<RaiseInfo*>(arFilterArgs[2])->_codeBase;
192 #endif
193 
194  // Destruct uno exception
195  ::uno_any_destruct(pUnoExc, nullptr);
196  TYPELIB_DANGER_RELEASE(pTD);
197 
198  // last point to release anything not affected by stack unwinding
199  RaiseException(MSVC_EH_MAGIC_CODE, EXCEPTION_NONCONTINUABLE, MSVC_EH_PARAMETERS, arFilterArgs);
200 }
201 
202 // This function does the same check as __CxxDetectRethrow from msvcrt (see its
203 // crt/src/vcruntime/mgdframe.cpp). But it does not alter the global state, i.e. it does not
204 // increment __ProcessingThrow, and so does not break following exception handling. We rely on the
205 // definition of EHExceptionRecord, PER_IS_MSVC_EH and PER_PTHROW, that are current as of msvcrt
206 // 2017 (14.14.26428).
207 static bool DetectRethrow(void* ppExcept)
208 {
209  struct EHExceptionRecord
210  {
211  DWORD ExceptionCode;
212  DWORD ExceptionFlags;
213  struct _EXCEPTION_RECORD* ExceptionRecord;
214  PVOID ExceptionAddress;
215  DWORD NumberParameters;
216 #if MSVC_EH_PARAMETERS == 3
217  struct EHParameters
218 #else
219  struct alignas(8)
220 #endif
221  {
222  DWORD magicNumber;
223  PVOID pExceptionObject;
224  PVOID pThrowInfo;
225 #if MSVC_EH_PARAMETERS == 4
226  PVOID pThrowImageBase;
227 #endif
228  } params;
229  };
230 
231  constexpr auto PER_IS_MSVC_EH = [](EHExceptionRecord* p) {
232  return p->ExceptionCode == MSVC_EH_MAGIC_CODE && p->NumberParameters == MSVC_EH_PARAMETERS
233  && (p->params.magicNumber == MSVC_EH_MAGIC_PARAM
234  || p->params.magicNumber == MSVC_EH_MAGIC_PARAM + 1
235  || p->params.magicNumber == MSVC_EH_MAGIC_PARAM + 2);
236  };
237 
238  constexpr auto PER_PTHROW = [](EHExceptionRecord* p) { return p->params.pThrowInfo; };
239 
240  EHExceptionRecord* pExcept;
241  if (!ppExcept)
242  return false;
243  pExcept = *static_cast<EHExceptionRecord**>(ppExcept);
244  if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr)
245  return true;
246  return false;
247 }
248 
249 int msvc_filterCppException(EXCEPTION_POINTERS* pPointers, uno_Any* pUnoExc, uno_Mapping* pCpp2Uno)
250 {
251  if (pPointers == nullptr)
252  return EXCEPTION_CONTINUE_SEARCH;
253 
254  EXCEPTION_RECORD* pRecord = pPointers->ExceptionRecord;
255 
256  // Handle only C++ exceptions:
257  if (pRecord == nullptr || pRecord->ExceptionCode != MSVC_EH_MAGIC_CODE)
258  return EXCEPTION_CONTINUE_SEARCH;
259 
260  const bool rethrow = DetectRethrow(&pRecord);
261  assert(pRecord == pPointers->ExceptionRecord);
262 
263  if (rethrow && pRecord == pPointers->ExceptionRecord)
264  pRecord = *reinterpret_cast<EXCEPTION_RECORD**>(__current_exception());
265 
266  // Rethrow: handle only C++ exceptions:
267  if (pRecord == nullptr || pRecord->ExceptionCode != MSVC_EH_MAGIC_CODE)
268  return EXCEPTION_CONTINUE_SEARCH;
269 
270  if (pRecord->NumberParameters == MSVC_EH_PARAMETERS
271 #if MSVC_EH_PARAMETERS == 4
272  && pRecord->ExceptionInformation[0] == MSVC_EH_MAGIC_PARAM
273 #endif
274  && pRecord->ExceptionInformation[1] != 0 && pRecord->ExceptionInformation[2] != 0
275 #if MSVC_EH_PARAMETERS == 4
276  && pRecord->ExceptionInformation[3] != 0
277 #endif
278  )
279  {
280  // ExceptionInformation[1] is the address of the thrown object
281  // (or the address of a pointer to it, in most cases when it
282  // is a C++ class, obviously).
283 
284  // [2] is the pThrowInfo pointer
285  RaiseInfo* pInfo = reinterpret_cast<RaiseInfo*>(pRecord->ExceptionInformation[2]);
286 
287 #if MSVC_EH_PARAMETERS == 3
288  ULONG_PTR base = 0;
289  DWORD* types = reinterpret_cast<DWORD*>(pInfo->_types);
290 #else
291  // [3] is the image base address which is added the 32-bit
292  // rva_t fields in throwinfo to get actual 64-bit addresses
293  ULONG_PTR base = pRecord->ExceptionInformation[3];
294  DWORD* types = reinterpret_cast<DWORD*>(base + pInfo->_types);
295 #endif
296  if (types != nullptr && types[0] != 0 && types[1] != 0)
297  {
298  ExceptionType* et = reinterpret_cast<ExceptionType*>(base + types[1]);
299  if (et->_pTypeInfo != 0)
300  {
301  OUString aRTTIname(OStringToOUString(
302  reinterpret_cast<ExceptionTypeInfo*>(base + et->_pTypeInfo)->m_d_name,
303  RTL_TEXTENCODING_ASCII_US));
304  OUString aUNOname(toUNOname(aRTTIname));
305 
306  typelib_TypeDescription* pExcTD = nullptr;
307  typelib_typedescription_getByName(&pExcTD, aUNOname.pData);
308  if (pExcTD == nullptr)
309  {
310  OUString sMsg = "[mscx_uno bridge error] UNO type of C++ exception unknown: \""
311  + aUNOname + "\", RTTI-name=\"" + aRTTIname + "\"!";
312 
313  uno::RuntimeException exc(sMsg);
315  pUnoExc, &exc, cppu::UnoType<decltype(exc)>::get().getTypeLibType(),
316  pCpp2Uno);
317  }
318  else
319  {
320  // construct uno exception any
322  pUnoExc, reinterpret_cast<void*>(pRecord->ExceptionInformation[1]), pExcTD,
323  pCpp2Uno);
325  }
326 
327  return EXCEPTION_EXECUTE_HANDLER;
328  }
329  }
330  }
331 
332  // though this unknown exception leaks now, no user-defined exception
333  // is ever thrown through the binary C-UNO dispatcher call stack.
334  uno::RuntimeException exc("[mscx_uno bridge error] unexpected C++ exception occurred!");
336  pUnoExc, &exc, cppu::UnoType<decltype(exc)>::get().getTypeLibType(), pCpp2Uno);
337  return EXCEPTION_EXECUTE_HANDLER;
338 }
339 
340 #pragma pack(pop)
static DWORD allocationGranularity
type_info * get_type_info()
Definition: msvc/except.hxx:84
void ** __current_exception()
struct _uno_Mapping uno_Mapping
Definition: msvc/except.hxx:32
sal_Int64 n
int msvc_filterCppException(EXCEPTION_POINTERS *pPointers, uno_Any *pUnoExc, uno_Mapping *pCpp2Uno)
sal_uInt32 _types
Definition: amd64.hxx:47
ExceptionTypeInfoWrapper * getInfo(OUString const &rUNOname)
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)
sal_uInt32 _pTypeInfo
Definition: amd64.hxx:29
const BorderLinePrimitive2D *pCandidateB assert(pCandidateA)
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
struct _uno_Any uno_Any
Definition: msvc/except.hxx:31
void msvc_raiseException(uno_Any *pUnoExc, uno_Mapping *pUno2Cpp)
static OUString toUNOname(OUString const &rRTTIname)
osl::Mutex m_aMutex
Definition: msvc/except.hxx:90
void const * base
constexpr DWORD MSVC_EH_MAGIC_CODE
Definition: msvc/except.hxx:39
struct _typelib_TypeDescription typelib_TypeDescription
Definition: msvc/except.hxx:52
osl::Mutex m_aMutex
void SAL_CALL typelib_typedescription_release(typelib_TypeDescription *pTD) SAL_THROW_EXTERN_C()
static OUString toRTTIname(OUString const &rUNOname)
void SAL_CALL typelib_typedescription_getByName(typelib_TypeDescription **ppRet, rtl_uString *pName) SAL_THROW_EXTERN_C()
t_string2PtrMap m_allRaiseInfos
static bool DetectRethrow(void *ppExcept)
#define SAL_INFO(area, stream)
void * p
static type_info * get(OUString const &rUNOname, int *len=nullptr)
constexpr DWORD MSVC_EH_MAGIC_PARAM
Definition: msvc/except.hxx:37
aStr
sal_uInt16 nPos
typedef void(CALLTYPE *GetFuncDataPtr)(sal_uInt16 &nNo