result.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. //*********************************************************
  2. //
  3. // Copyright (c) Microsoft. All rights reserved.
  4. // This code is licensed under the MIT License.
  5. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
  6. // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  7. // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  8. // PARTICULAR PURPOSE AND NONINFRINGEMENT.
  9. //
  10. //*********************************************************
  11. #ifndef __WIL_RESULT_INCLUDED
  12. #define __WIL_RESULT_INCLUDED
  13. // Most functionality is picked up from result_macros.h. This file specifically provides higher level processing of errors when
  14. // they are encountered by the underlying macros.
  15. #include "result_macros.h"
  16. // Note that we avoid pulling in STL's memory header from Result.h through Resource.h as we have
  17. // Result.h customers who are still on older versions of STL (without std::shared_ptr<>).
  18. #ifndef RESOURCE_SUPPRESS_STL
  19. #define RESOURCE_SUPPRESS_STL
  20. #include "resource.h"
  21. #undef RESOURCE_SUPPRESS_STL
  22. #else
  23. #include "resource.h"
  24. #endif
  25. #ifdef WIL_KERNEL_MODE
  26. #error This header is not supported in kernel-mode.
  27. #endif
  28. // The updated behavior of running init-list ctors during placement new is proper & correct, disable the warning that requests developers verify they want it
  29. #pragma warning(push)
  30. #pragma warning(disable : 4351)
  31. namespace wil
  32. {
  33. // WARNING: EVERYTHING in this namespace must be handled WITH CARE as the entities defined within
  34. // are used as an in-proc ABI contract between binaries that utilize WIL. Making changes
  35. // that add v-tables or change the storage semantics of anything herein needs to be done
  36. // with care and respect to versioning.
  37. ///@cond
  38. namespace details_abi
  39. {
  40. #define __WI_SEMAHPORE_VERSION L"_p0"
  41. // This class uses named semaphores to be able to stash a numeric value (including a pointer
  42. // for retrieval from within any module in a process). This is a very specific need of a
  43. // header-based library that should not be generally used.
  44. //
  45. // Notes for use:
  46. // * Data members must be stable unless __WI_SEMAHPORE_VERSION is changed
  47. // * The class must not reference module code (v-table, function pointers, etc)
  48. // * Use of this class REQUIRES that there be a MUTEX held around the semaphore manipulation
  49. // and tests as it doesn't attempt to handle thread contention on the semaphore while manipulating
  50. // the count.
  51. // * This class supports storing a 31-bit number of a single semaphore or a 62-bit number across
  52. // two semaphores and directly supports pointers.
  53. class SemaphoreValue
  54. {
  55. public:
  56. SemaphoreValue() = default;
  57. SemaphoreValue(const SemaphoreValue&) = delete;
  58. SemaphoreValue& operator=(const SemaphoreValue&) = delete;
  59. SemaphoreValue(SemaphoreValue&& other) WI_NOEXCEPT :
  60. m_semaphore(wistd::move(other.m_semaphore)),
  61. m_semaphoreHigh(wistd::move(other.m_semaphoreHigh))
  62. {
  63. static_assert(sizeof(m_semaphore) == sizeof(HANDLE), "unique_any must be a direct representation of the HANDLE to be used across module");
  64. }
  65. void Destroy()
  66. {
  67. m_semaphore.reset();
  68. m_semaphoreHigh.reset();
  69. }
  70. template <typename T>
  71. HRESULT CreateFromValue(PCWSTR name, T value)
  72. {
  73. return CreateFromValueInternal(name, (sizeof(value) > sizeof(unsigned long)), static_cast<unsigned __int64>(value));
  74. }
  75. HRESULT CreateFromPointer(PCWSTR name, void* pointer)
  76. {
  77. ULONG_PTR value = reinterpret_cast<ULONG_PTR>(pointer);
  78. FAIL_FAST_IMMEDIATE_IF(WI_IsAnyFlagSet(value, 0x3));
  79. return CreateFromValue(name, value >> 2);
  80. }
  81. template <typename T>
  82. static HRESULT TryGetValue(PCWSTR name, _Out_ T* value, _Out_opt_ bool *retrieved = nullptr)
  83. {
  84. *value = static_cast<T>(0);
  85. unsigned __int64 value64 = 0;
  86. __WIL_PRIVATE_RETURN_IF_FAILED(TryGetValueInternal(name, (sizeof(T) > sizeof(unsigned long)), &value64, retrieved));
  87. *value = static_cast<T>(value64);
  88. return S_OK;
  89. }
  90. static HRESULT TryGetPointer(PCWSTR name, _Outptr_result_maybenull_ void** pointer)
  91. {
  92. *pointer = nullptr;
  93. ULONG_PTR value = 0;
  94. __WIL_PRIVATE_RETURN_IF_FAILED(TryGetValue(name, &value));
  95. *pointer = reinterpret_cast<void*>(value << 2);
  96. return S_OK;
  97. }
  98. private:
  99. HRESULT CreateFromValueInternal(PCWSTR name, bool is64Bit, unsigned __int64 value)
  100. {
  101. WI_ASSERT(!m_semaphore && !m_semaphoreHigh); // call Destroy first
  102. // This routine only supports 31 bits when semahporeHigh is not supplied or 62 bits when the value
  103. // is supplied. It's a programming error to use it when either of these conditions are not true.
  104. FAIL_FAST_IMMEDIATE_IF((!is64Bit && WI_IsAnyFlagSet(value, 0xFFFFFFFF80000000)) ||
  105. (is64Bit && WI_IsAnyFlagSet(value, 0xC000000000000000)));
  106. wchar_t localName[MAX_PATH];
  107. WI_VERIFY_SUCCEEDED(StringCchCopyW(localName, ARRAYSIZE(localName), name));
  108. WI_VERIFY_SUCCEEDED(StringCchCatW(localName, ARRAYSIZE(localName), __WI_SEMAHPORE_VERSION));
  109. const unsigned long highPart = static_cast<unsigned long>(value >> 31);
  110. const unsigned long lowPart = static_cast<unsigned long>(value & 0x000000007FFFFFFF);
  111. // We set the count of the semaphore equal to the max (the value we're storing). The only exception to that
  112. // is ZERO, where you can't create a semaphore of value ZERO, where we push the max to one and use a count of ZERO.
  113. __WIL_PRIVATE_RETURN_IF_FAILED(m_semaphore.create(static_cast<LONG>(lowPart), static_cast<LONG>((lowPart > 0) ? lowPart : 1), localName));
  114. if (is64Bit)
  115. {
  116. WI_VERIFY_SUCCEEDED(StringCchCatW(localName, ARRAYSIZE(localName), L"h"));
  117. __WIL_PRIVATE_RETURN_IF_FAILED(m_semaphoreHigh.create(static_cast<LONG>(highPart), static_cast<LONG>((highPart > 0) ? highPart : 1), localName));
  118. }
  119. return S_OK;
  120. }
  121. static HRESULT GetValueFromSemaphore(HANDLE semaphore, _Out_ LONG* count)
  122. {
  123. // First we consume a single count from the semaphore. This will work in all cases other
  124. // than the case where the count we've recorded is ZERO which will TIMEOUT.
  125. DWORD result = ::WaitForSingleObject(semaphore, 0);
  126. __WIL_PRIVATE_RETURN_LAST_ERROR_IF(result == WAIT_FAILED);
  127. __WIL_PRIVATE_RETURN_HR_IF(E_UNEXPECTED, !((result == WAIT_OBJECT_0) || (result == WAIT_TIMEOUT)));
  128. LONG value = 0;
  129. if (result == WAIT_OBJECT_0)
  130. {
  131. // We were able to wait. To establish our count, all we have to do is release that count
  132. // back to the semaphore and observe the value that we released.
  133. __WIL_PRIVATE_RETURN_IF_WIN32_BOOL_FALSE(::ReleaseSemaphore(semaphore, 1, &value));
  134. value++; // we waited first, so our actual value is one more than the old value
  135. // Make sure the value is correct by validating that we have no more posts.
  136. BOOL expectedFailure = ::ReleaseSemaphore(semaphore, 1, nullptr);
  137. __WIL_PRIVATE_RETURN_HR_IF(E_UNEXPECTED, expectedFailure || (::GetLastError() != ERROR_TOO_MANY_POSTS));
  138. }
  139. else
  140. {
  141. WI_ASSERT(result == WAIT_TIMEOUT);
  142. // We know at this point that the value is ZERO. We'll do some verification to ensure that
  143. // this address is right by validating that we have one and only one more post that we could use.
  144. LONG expected = 0;
  145. __WIL_PRIVATE_RETURN_IF_WIN32_BOOL_FALSE(::ReleaseSemaphore(semaphore, 1, &expected));
  146. __WIL_PRIVATE_RETURN_HR_IF(E_UNEXPECTED, expected != 0);
  147. const BOOL expectedFailure = ::ReleaseSemaphore(semaphore, 1, nullptr);
  148. __WIL_PRIVATE_RETURN_HR_IF(E_UNEXPECTED, expectedFailure || (::GetLastError() != ERROR_TOO_MANY_POSTS));
  149. result = ::WaitForSingleObject(semaphore, 0);
  150. __WIL_PRIVATE_RETURN_LAST_ERROR_IF(result == WAIT_FAILED);
  151. __WIL_PRIVATE_RETURN_HR_IF(E_UNEXPECTED, result != WAIT_OBJECT_0);
  152. }
  153. *count = value;
  154. return S_OK;
  155. }
  156. static HRESULT TryGetValueInternal(PCWSTR name, bool is64Bit, _Out_ unsigned __int64* value, _Out_opt_ bool* retrieved)
  157. {
  158. assign_to_opt_param(retrieved, false);
  159. *value = 0;
  160. wchar_t localName[MAX_PATH];
  161. WI_VERIFY_SUCCEEDED(StringCchCopyW(localName, ARRAYSIZE(localName), name));
  162. WI_VERIFY_SUCCEEDED(StringCchCatW(localName, ARRAYSIZE(localName), __WI_SEMAHPORE_VERSION));
  163. wil::unique_semaphore_nothrow semaphoreLow(::OpenSemaphoreW(SEMAPHORE_ALL_ACCESS, FALSE, localName));
  164. if (!semaphoreLow)
  165. {
  166. __WIL_PRIVATE_RETURN_HR_IF(S_OK, (::GetLastError() == ERROR_FILE_NOT_FOUND));
  167. __WIL_PRIVATE_RETURN_LAST_ERROR();
  168. }
  169. LONG countLow = 0;
  170. LONG countHigh = 0;
  171. __WIL_PRIVATE_RETURN_IF_FAILED(GetValueFromSemaphore(semaphoreLow.get(), &countLow));
  172. if (is64Bit)
  173. {
  174. WI_VERIFY_SUCCEEDED(StringCchCatW(localName, ARRAYSIZE(localName), L"h"));
  175. wil::unique_semaphore_nothrow semaphoreHigh(::OpenSemaphoreW(SEMAPHORE_ALL_ACCESS, FALSE, localName));
  176. __WIL_PRIVATE_RETURN_LAST_ERROR_IF_NULL(semaphoreHigh);
  177. __WIL_PRIVATE_RETURN_IF_FAILED(GetValueFromSemaphore(semaphoreHigh.get(), &countHigh));
  178. }
  179. WI_ASSERT((countLow >= 0) && (countHigh >= 0));
  180. const unsigned __int64 newValueHigh = (static_cast<unsigned __int64>(countHigh) << 31);
  181. const unsigned __int64 newValueLow = static_cast<unsigned __int64>(countLow);
  182. assign_to_opt_param(retrieved, true);
  183. *value = (newValueHigh | newValueLow);
  184. return S_OK;
  185. }
  186. wil::unique_semaphore_nothrow m_semaphore;
  187. wil::unique_semaphore_nothrow m_semaphoreHigh;
  188. };
  189. template <typename T>
  190. class ProcessLocalStorageData
  191. {
  192. public:
  193. ProcessLocalStorageData(unique_mutex_nothrow&& mutex, SemaphoreValue&& value) :
  194. m_mutex(wistd::move(mutex)),
  195. m_value(wistd::move(value)),
  196. m_data()
  197. {
  198. static_assert(sizeof(m_mutex) == sizeof(HANDLE), "unique_any must be equivalent to the handle size to safely use across module");
  199. }
  200. T* GetData()
  201. {
  202. WI_ASSERT(m_mutex);
  203. return &m_data;
  204. }
  205. void Release()
  206. {
  207. if (ProcessShutdownInProgress())
  208. {
  209. // There are no other threads to contend with.
  210. m_refCount = m_refCount - 1;
  211. if (m_refCount == 0)
  212. {
  213. m_data.ProcessShutdown();
  214. }
  215. }
  216. else
  217. {
  218. auto lock = m_mutex.acquire();
  219. m_refCount = m_refCount - 1;
  220. if (m_refCount == 0)
  221. {
  222. // We must explicitly destroy our semaphores while holding the mutex
  223. m_value.Destroy();
  224. lock.reset();
  225. this->~ProcessLocalStorageData();
  226. ::HeapFree(::GetProcessHeap(), 0, this);
  227. }
  228. }
  229. }
  230. static HRESULT Acquire(PCSTR staticNameWithVersion, _Outptr_result_nullonfailure_ ProcessLocalStorageData<T>** data)
  231. {
  232. *data = nullptr;
  233. // NOTE: the '0' in SM0 below is intended as the VERSION number. Changes to this class require
  234. // that this value be revised.
  235. const DWORD size = static_cast<DWORD>(sizeof(ProcessLocalStorageData<T>));
  236. wchar_t name[MAX_PATH];
  237. WI_VERIFY(SUCCEEDED(StringCchPrintfW(name, ARRAYSIZE(name), L"Local\\SM0:%lu:%lu:%hs", ::GetCurrentProcessId(), size, staticNameWithVersion)));
  238. unique_mutex_nothrow mutex;
  239. mutex.reset(::CreateMutexExW(nullptr, name, 0, MUTEX_ALL_ACCESS));
  240. // This will fail in some environments and will be fixed with deliverable 12394134
  241. RETURN_LAST_ERROR_IF_EXPECTED(!mutex);
  242. auto lock = mutex.acquire();
  243. void* pointer = nullptr;
  244. __WIL_PRIVATE_RETURN_IF_FAILED(SemaphoreValue::TryGetPointer(name, &pointer));
  245. if (pointer)
  246. {
  247. *data = reinterpret_cast<ProcessLocalStorageData<T>*>(pointer);
  248. (*data)->m_refCount = (*data)->m_refCount + 1;
  249. }
  250. else
  251. {
  252. __WIL_PRIVATE_RETURN_IF_FAILED(MakeAndInitialize(name, wistd::move(mutex), data)); // Assumes mutex handle ownership on success ('lock' will still be released)
  253. }
  254. return S_OK;
  255. }
  256. private:
  257. volatile long m_refCount = 1;
  258. unique_mutex_nothrow m_mutex;
  259. SemaphoreValue m_value;
  260. T m_data;
  261. static HRESULT MakeAndInitialize(PCWSTR name, unique_mutex_nothrow&& mutex, _Outptr_result_nullonfailure_ ProcessLocalStorageData<T>** data)
  262. {
  263. *data = nullptr;
  264. const DWORD size = static_cast<DWORD>(sizeof(ProcessLocalStorageData<T>));
  265. unique_process_heap_ptr<ProcessLocalStorageData<T>> dataAlloc(static_cast<ProcessLocalStorageData<T>*>(details::ProcessHeapAlloc(HEAP_ZERO_MEMORY, size)));
  266. __WIL_PRIVATE_RETURN_IF_NULL_ALLOC(dataAlloc);
  267. SemaphoreValue semaphoreValue;
  268. __WIL_PRIVATE_RETURN_IF_FAILED(semaphoreValue.CreateFromPointer(name, dataAlloc.get()));
  269. new(dataAlloc.get()) ProcessLocalStorageData<T>(wistd::move(mutex), wistd::move(semaphoreValue));
  270. *data = dataAlloc.release();
  271. return S_OK;
  272. }
  273. };
  274. template <typename T>
  275. class ProcessLocalStorage
  276. {
  277. public:
  278. ProcessLocalStorage(PCSTR staticNameWithVersion) WI_NOEXCEPT :
  279. m_staticNameWithVersion(staticNameWithVersion)
  280. {
  281. }
  282. ~ProcessLocalStorage() WI_NOEXCEPT
  283. {
  284. if (m_data)
  285. {
  286. m_data->Release();
  287. }
  288. }
  289. T* GetShared() WI_NOEXCEPT
  290. {
  291. if (!m_data)
  292. {
  293. ProcessLocalStorageData<T>* localTemp = nullptr;
  294. if (SUCCEEDED(ProcessLocalStorageData<T>::Acquire(m_staticNameWithVersion, &localTemp)) && !m_data)
  295. {
  296. m_data = localTemp;
  297. }
  298. }
  299. return m_data ? m_data->GetData() : nullptr;
  300. }
  301. private:
  302. PCSTR m_staticNameWithVersion = nullptr;
  303. ProcessLocalStorageData<T>* m_data = nullptr;
  304. };
  305. template <typename T>
  306. class ThreadLocalStorage
  307. {
  308. public:
  309. ThreadLocalStorage(const ThreadLocalStorage&) = delete;
  310. ThreadLocalStorage& operator=(const ThreadLocalStorage&) = delete;
  311. ThreadLocalStorage() = default;
  312. ~ThreadLocalStorage() WI_NOEXCEPT
  313. {
  314. for (auto &entry : m_hashArray)
  315. {
  316. Node *pNode = entry;
  317. while (pNode != nullptr)
  318. {
  319. auto pCurrent = pNode;
  320. pNode = pNode->pNext;
  321. pCurrent->~Node();
  322. ::HeapFree(::GetProcessHeap(), 0, pCurrent);
  323. }
  324. entry = nullptr;
  325. }
  326. }
  327. // Note: Can return nullptr even when (shouldAllocate == true) upon allocation failure
  328. T* GetLocal(bool shouldAllocate = false) WI_NOEXCEPT
  329. {
  330. DWORD const threadId = ::GetCurrentThreadId();
  331. size_t const index = (threadId % ARRAYSIZE(m_hashArray));
  332. for (auto pNode = m_hashArray[index]; pNode != nullptr; pNode = pNode->pNext)
  333. {
  334. if (pNode->threadId == threadId)
  335. {
  336. return &pNode->value;
  337. }
  338. }
  339. if (shouldAllocate)
  340. {
  341. if (auto pNewRaw = details::ProcessHeapAlloc(0, sizeof(Node)))
  342. {
  343. auto pNew = new (pNewRaw) Node{ threadId };
  344. Node *pFirst;
  345. do
  346. {
  347. pFirst = m_hashArray[index];
  348. pNew->pNext = pFirst;
  349. } while (::InterlockedCompareExchangePointer(reinterpret_cast<PVOID volatile *>(m_hashArray + index), pNew, pFirst) != pFirst);
  350. return &pNew->value;
  351. }
  352. }
  353. return nullptr;
  354. }
  355. private:
  356. struct Node
  357. {
  358. DWORD threadId = ULONG_MAX;
  359. Node* pNext = nullptr;
  360. T value{};
  361. };
  362. Node * volatile m_hashArray[10]{};
  363. };
  364. struct ThreadLocalFailureInfo
  365. {
  366. // ABI contract (carry size to facilitate additive change without re-versioning)
  367. unsigned short size;
  368. unsigned char reserved1[2]; // packing, reserved
  369. // When this failure was seen
  370. unsigned int sequenceId;
  371. // Information about the failure
  372. HRESULT hr;
  373. PCSTR fileName;
  374. unsigned short lineNumber;
  375. unsigned char failureType; // FailureType
  376. unsigned char reserved2; // packing, reserved
  377. PCSTR modulePath;
  378. void* returnAddress;
  379. void* callerReturnAddress;
  380. PCWSTR message;
  381. // The allocation (LocalAlloc) where structure strings point
  382. void* stringBuffer;
  383. size_t stringBufferSize;
  384. // NOTE: Externally Managed: Must not have constructor or destructor
  385. void Clear()
  386. {
  387. ::HeapFree(::GetProcessHeap(), 0, stringBuffer);
  388. stringBuffer = nullptr;
  389. stringBufferSize = 0;
  390. }
  391. void Set(const FailureInfo& info, unsigned int newSequenceId)
  392. {
  393. sequenceId = newSequenceId;
  394. hr = info.hr;
  395. fileName = nullptr;
  396. lineNumber = static_cast<unsigned short>(info.uLineNumber);
  397. failureType = static_cast<unsigned char>(info.type);
  398. modulePath = nullptr;
  399. returnAddress = info.returnAddress;
  400. callerReturnAddress = info.callerReturnAddress;
  401. message = nullptr;
  402. size_t neededSize = details::ResultStringSize(info.pszFile) +
  403. details::ResultStringSize(info.pszModule) +
  404. details::ResultStringSize(info.pszMessage);
  405. if (!stringBuffer || (stringBufferSize < neededSize))
  406. {
  407. auto newBuffer = details::ProcessHeapAlloc(HEAP_ZERO_MEMORY, neededSize);
  408. if (newBuffer)
  409. {
  410. ::HeapFree(::GetProcessHeap(), 0, stringBuffer);
  411. stringBuffer = newBuffer;
  412. stringBufferSize = neededSize;
  413. }
  414. }
  415. if (stringBuffer)
  416. {
  417. unsigned char *pBuffer = static_cast<unsigned char *>(stringBuffer);
  418. unsigned char *pBufferEnd = pBuffer + stringBufferSize;
  419. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszFile, &fileName);
  420. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszModule, &modulePath);
  421. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszMessage, &message);
  422. ZeroMemory(pBuffer, pBufferEnd - pBuffer);
  423. }
  424. }
  425. void Get(FailureInfo& info) const
  426. {
  427. ::ZeroMemory(&info, sizeof(info));
  428. info.failureId = sequenceId;
  429. info.hr = hr;
  430. info.pszFile = fileName;
  431. info.uLineNumber = lineNumber;
  432. info.type = static_cast<FailureType>(failureType);
  433. info.pszModule = modulePath;
  434. info.returnAddress = returnAddress;
  435. info.callerReturnAddress = callerReturnAddress;
  436. info.pszMessage = message;
  437. }
  438. };
  439. struct ThreadLocalData
  440. {
  441. // ABI contract (carry size to facilitate additive change without re-versioning)
  442. unsigned short size = sizeof(ThreadLocalData);
  443. // Subscription information
  444. unsigned int threadId = 0;
  445. volatile long* failureSequenceId = nullptr; // backpointer to the global ID
  446. // Information about thread errors
  447. unsigned int latestSubscribedFailureSequenceId = 0;
  448. // The last (N) observed errors
  449. ThreadLocalFailureInfo* errors = nullptr;
  450. unsigned short errorAllocCount = 0;
  451. unsigned short errorCurrentIndex = 0;
  452. // NOTE: Externally Managed: Must allow ZERO init construction
  453. ~ThreadLocalData()
  454. {
  455. Clear();
  456. }
  457. void Clear()
  458. {
  459. for (auto& error : make_range(errors, errorAllocCount))
  460. {
  461. error.Clear();
  462. }
  463. ::HeapFree(::GetProcessHeap(), 0, errors);
  464. errorAllocCount = 0;
  465. errorCurrentIndex = 0;
  466. errors = nullptr;
  467. }
  468. bool EnsureAllocated(bool create = true)
  469. {
  470. if (!errors && create)
  471. {
  472. const unsigned short errorCount = 5;
  473. errors = reinterpret_cast<ThreadLocalFailureInfo *>(details::ProcessHeapAlloc(HEAP_ZERO_MEMORY, errorCount * sizeof(ThreadLocalFailureInfo)));
  474. if (errors)
  475. {
  476. errorAllocCount = errorCount;
  477. errorCurrentIndex = 0;
  478. for (auto& error : make_range(errors, errorAllocCount))
  479. {
  480. error.size = sizeof(ThreadLocalFailureInfo);
  481. }
  482. }
  483. }
  484. return (errors != nullptr);
  485. }
  486. void SetLastError(const wil::FailureInfo& info)
  487. {
  488. const bool hasListener = (latestSubscribedFailureSequenceId > 0);
  489. if (!EnsureAllocated(hasListener))
  490. {
  491. // We either couldn't allocate or we haven't yet allocated and nobody
  492. // was listening, so we ignore.
  493. return;
  494. }
  495. if (hasListener)
  496. {
  497. // When we have listeners, we can throw away any updates to the last seen error
  498. // code within the same listening context presuming it's an update of the existing
  499. // error with the same code.
  500. for (auto& error : make_range(errors, errorAllocCount))
  501. {
  502. if ((error.sequenceId > latestSubscribedFailureSequenceId) && (error.hr == info.hr))
  503. {
  504. return;
  505. }
  506. }
  507. }
  508. // Otherwise we create a new failure...
  509. errorCurrentIndex = (errorCurrentIndex + 1) % errorAllocCount;
  510. errors[errorCurrentIndex].Set(info, ::InterlockedIncrementNoFence(failureSequenceId));
  511. }
  512. bool GetLastError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId, HRESULT matchRequirement) const
  513. {
  514. if (!errors)
  515. {
  516. return false;
  517. }
  518. // If the last error we saw doesn't meet the filter requirement or if the last error was never
  519. // set, then we couldn't return a result at all...
  520. auto& lastFailure = errors[errorCurrentIndex];
  521. if (minSequenceId >= lastFailure.sequenceId)
  522. {
  523. return false;
  524. }
  525. // With no result filter, we just go to the last error and report it
  526. if (matchRequirement == S_OK)
  527. {
  528. lastFailure.Get(info);
  529. return true;
  530. }
  531. // Find the oldest result matching matchRequirement and passing minSequenceId
  532. ThreadLocalFailureInfo* find = nullptr;
  533. for (auto& error : make_range(errors, errorAllocCount))
  534. {
  535. if ((error.hr == matchRequirement) && (error.sequenceId > minSequenceId))
  536. {
  537. if (!find || (error.sequenceId < find->sequenceId))
  538. {
  539. find = &error;
  540. }
  541. }
  542. }
  543. if (find)
  544. {
  545. find->Get(info);
  546. return true;
  547. }
  548. return false;
  549. }
  550. bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId, _In_opt_ const DiagnosticsInfo* diagnostics, HRESULT matchRequirement, void* returnAddress)
  551. {
  552. // First attempt to get the last error and then see if it matches the error returned from
  553. // the last caught exception. If it does, then we're good to go and we return that last error.
  554. FailureInfo last = {};
  555. if (GetLastError(last, minSequenceId, matchRequirement) && (last.hr == ResultFromCaughtException()))
  556. {
  557. info = last;
  558. return true;
  559. }
  560. // The last error didn't match or we never had one... we need to create one -- we do so by logging
  561. // our current request and then using the last error.
  562. DiagnosticsInfo source;
  563. if (diagnostics)
  564. {
  565. source = *diagnostics;
  566. }
  567. // NOTE: FailureType::Log as it's only informative (no action) and SupportedExceptions::All as it's not a barrier, only recognition.
  568. wchar_t message[2048];
  569. message[0] = L'\0';
  570. const HRESULT hr = details::ReportFailure_CaughtExceptionCommon<FailureType::Log>(__R_DIAGNOSTICS_RA(source, returnAddress), message, ARRAYSIZE(message), SupportedExceptions::All).hr;
  571. // Now that the exception was logged, we should be able to fetch it.
  572. return GetLastError(info, minSequenceId, hr);
  573. }
  574. };
  575. struct ProcessLocalData
  576. {
  577. // ABI contract (carry size to facilitate additive change without re-versioning)
  578. unsigned short size = sizeof(ProcessLocalData);
  579. // Failure Information
  580. volatile long failureSequenceId = 1; // process global variable
  581. ThreadLocalStorage<ThreadLocalData> threads; // list of allocated threads
  582. void ProcessShutdown() {}
  583. };
  584. __declspec(selectany) ProcessLocalStorage<ProcessLocalData>* g_pProcessLocalData = nullptr;
  585. __declspec(noinline) inline ThreadLocalData* GetThreadLocalDataCache(bool allocate = true)
  586. {
  587. ThreadLocalData* result = nullptr;
  588. if (g_pProcessLocalData)
  589. {
  590. auto processData = g_pProcessLocalData->GetShared();
  591. if (processData)
  592. {
  593. result = processData->threads.GetLocal(allocate);
  594. if (result && !result->failureSequenceId)
  595. {
  596. result->failureSequenceId = &(processData->failureSequenceId);
  597. }
  598. }
  599. }
  600. return result;
  601. }
  602. __forceinline ThreadLocalData* GetThreadLocalData(bool allocate = true)
  603. {
  604. return GetThreadLocalDataCache(allocate);
  605. }
  606. } // details_abi
  607. /// @endcond
  608. /** Returns a sequence token that can be used with wil::GetLastError to limit errors to those that occur after this token was retrieved.
  609. General usage pattern: use wil::GetCurrentErrorSequenceId to cache a token, execute your code, on failure use wil::GetLastError with the token
  610. to provide information on the error that occurred while executing your code. Prefer to use wil::ThreadErrorContext over this approach when
  611. possible. */
  612. inline long GetCurrentErrorSequenceId()
  613. {
  614. auto data = details_abi::GetThreadLocalData();
  615. if (data)
  616. {
  617. // someone is interested -- make sure we can store errors
  618. data->EnsureAllocated();
  619. return *data->failureSequenceId;
  620. }
  621. return 0;
  622. }
  623. /** Caches failure information for later retrieval from GetLastError.
  624. Most people will never need to do this explicitly as failure information is automatically made available per-thread across a process when
  625. errors are encountered naturally through the WIL macros. */
  626. inline void SetLastError(const wil::FailureInfo& info)
  627. {
  628. static volatile unsigned int lastThread = 0;
  629. auto threadId = ::GetCurrentThreadId();
  630. if (lastThread != threadId)
  631. {
  632. static volatile long depth = 0;
  633. if (::InterlockedIncrementNoFence(&depth) < 4)
  634. {
  635. lastThread = threadId;
  636. auto data = details_abi::GetThreadLocalData(false); // false = avoids allocation if not already present
  637. if (data)
  638. {
  639. data->SetLastError(info);
  640. }
  641. lastThread = 0;
  642. }
  643. ::InterlockedDecrementNoFence(&depth);
  644. }
  645. }
  646. /** Retrieves failure information for the current thread with the given filters.
  647. This API can be used to retrieve information about the last WIL failure that occurred on the current thread.
  648. This error crosses DLL boundaries as long as the error occurred in the current process. Passing a minSequenceId
  649. restricts the error returned to one that occurred after the given sequence ID. Passing matchRequirement also filters
  650. the returned result to the given error code. */
  651. inline bool GetLastError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId = 0, HRESULT matchRequirement = S_OK)
  652. {
  653. auto data = details_abi::GetThreadLocalData(false); // false = avoids allocation if not already present
  654. if (data)
  655. {
  656. return data->GetLastError(info, minSequenceId, matchRequirement);
  657. }
  658. return false;
  659. }
  660. /** Retrieves failure information when within a catch block for the current thread with the given filters.
  661. When unable to retrieve the exception information (when WIL hasn't yet seen it), this will attempt (best effort) to
  662. discover information about the exception and will attribute that information to the given DiagnosticsInfo position.
  663. See GetLastError for capabilities and filtering. */
  664. inline __declspec(noinline) bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId = 0, const DiagnosticsInfo* diagnostics = nullptr, HRESULT matchRequirement = S_OK)
  665. {
  666. auto data = details_abi::GetThreadLocalData();
  667. if (data)
  668. {
  669. return data->GetCaughtExceptionError(info, minSequenceId, diagnostics, matchRequirement, _ReturnAddress());
  670. }
  671. return false;
  672. }
  673. /** Use this class to manage retrieval of information about an error occurring in the requested code.
  674. Construction of this class sets a point in time after which you can use the GetLastError class method to retrieve
  675. the origination of the last error that occurred on this thread since the class was created. */
  676. class ThreadErrorContext
  677. {
  678. public:
  679. ThreadErrorContext() :
  680. m_data(details_abi::GetThreadLocalData())
  681. {
  682. if (m_data)
  683. {
  684. m_sequenceIdLast = m_data->latestSubscribedFailureSequenceId;
  685. m_sequenceIdStart = *m_data->failureSequenceId;
  686. m_data->latestSubscribedFailureSequenceId = m_sequenceIdStart;
  687. }
  688. }
  689. ~ThreadErrorContext()
  690. {
  691. if (m_data)
  692. {
  693. m_data->latestSubscribedFailureSequenceId = m_sequenceIdLast;
  694. }
  695. }
  696. /** Retrieves the origination of the last error that occurred since this class was constructed.
  697. The optional parameter allows the failure information returned to be filtered to a specific
  698. result. */
  699. inline bool GetLastError(FailureInfo& info, HRESULT matchRequirement = S_OK)
  700. {
  701. if (m_data)
  702. {
  703. return m_data->GetLastError(info, m_sequenceIdStart, matchRequirement);
  704. }
  705. return false;
  706. }
  707. /** Retrieves the origin of the current exception (within a catch block) since this class was constructed.
  708. See @ref GetCaughtExceptionError for more information */
  709. inline __declspec(noinline) bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, const DiagnosticsInfo* diagnostics = nullptr, HRESULT matchRequirement = S_OK)
  710. {
  711. if (m_data)
  712. {
  713. return m_data->GetCaughtExceptionError(info, m_sequenceIdStart, diagnostics, matchRequirement, _ReturnAddress());
  714. }
  715. return false;
  716. }
  717. private:
  718. details_abi::ThreadLocalData* m_data;
  719. unsigned long m_sequenceIdStart{};
  720. unsigned long m_sequenceIdLast{};
  721. };
  722. enum class WilInitializeCommand
  723. {
  724. Create,
  725. Destroy,
  726. };
  727. /// @cond
  728. namespace details
  729. {
  730. struct IFailureCallback
  731. {
  732. virtual bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT = 0;
  733. };
  734. class ThreadFailureCallbackHolder;
  735. __declspec(selectany) details_abi::ThreadLocalStorage<ThreadFailureCallbackHolder*>* g_pThreadFailureCallbacks = nullptr;
  736. class ThreadFailureCallbackHolder
  737. {
  738. public:
  739. ThreadFailureCallbackHolder(_In_ IFailureCallback *pCallbackParam, _In_opt_ CallContextInfo *pCallContext = nullptr, bool watchNow = true) WI_NOEXCEPT :
  740. m_ppThreadList(nullptr),
  741. m_pCallback(pCallbackParam),
  742. m_pNext(nullptr),
  743. m_threadId(0),
  744. m_pCallContext(pCallContext)
  745. {
  746. if (watchNow)
  747. {
  748. StartWatching();
  749. }
  750. }
  751. ThreadFailureCallbackHolder(ThreadFailureCallbackHolder &&other) WI_NOEXCEPT :
  752. m_ppThreadList(nullptr),
  753. m_pCallback(other.m_pCallback),
  754. m_pNext(nullptr),
  755. m_threadId(0),
  756. m_pCallContext(other.m_pCallContext)
  757. {
  758. if (other.m_threadId != 0)
  759. {
  760. other.StopWatching();
  761. StartWatching();
  762. }
  763. }
  764. ~ThreadFailureCallbackHolder() WI_NOEXCEPT
  765. {
  766. if (m_threadId != 0)
  767. {
  768. StopWatching();
  769. }
  770. }
  771. void SetCallContext(_In_opt_ CallContextInfo *pCallContext)
  772. {
  773. m_pCallContext = pCallContext;
  774. }
  775. CallContextInfo *CallContextInfo()
  776. {
  777. return m_pCallContext;
  778. }
  779. void StartWatching()
  780. {
  781. // out-of balance Start/Stop calls?
  782. __FAIL_FAST_IMMEDIATE_ASSERT__(m_threadId == 0);
  783. m_ppThreadList = g_pThreadFailureCallbacks ? g_pThreadFailureCallbacks->GetLocal(true) : nullptr; // true = allocate thread list if missing
  784. if (m_ppThreadList)
  785. {
  786. m_pNext = *m_ppThreadList;
  787. *m_ppThreadList = this;
  788. m_threadId = ::GetCurrentThreadId();
  789. }
  790. }
  791. void StopWatching()
  792. {
  793. if (m_threadId != ::GetCurrentThreadId())
  794. {
  795. // The thread-specific failure holder cannot be stopped on a different thread than it was started on or the
  796. // internal book-keeping list will be corrupted. To fix this change the telemetry pattern in the calling code
  797. // to match one of the patterns available here:
  798. // https://microsoft.sharepoint.com/teams/osg_development/Shared%20Documents/Windows%20TraceLogging%20Helpers.docx
  799. WI_USAGE_ERROR("MEMORY CORRUPTION: Calling code is leaking an activity thread-watcher and releasing it on another thread");
  800. }
  801. m_threadId = 0;
  802. while (*m_ppThreadList != nullptr)
  803. {
  804. if (*m_ppThreadList == this)
  805. {
  806. *m_ppThreadList = m_pNext;
  807. break;
  808. }
  809. m_ppThreadList = &((*m_ppThreadList)->m_pNext);
  810. }
  811. m_ppThreadList = nullptr;
  812. }
  813. bool IsWatching() const
  814. {
  815. return (m_threadId != 0);
  816. }
  817. void SetWatching(bool shouldWatch)
  818. {
  819. if (shouldWatch && !IsWatching())
  820. {
  821. StartWatching();
  822. }
  823. else if (!shouldWatch && IsWatching())
  824. {
  825. StopWatching();
  826. }
  827. }
  828. static bool GetThreadContext(_Inout_ FailureInfo *pFailure, _In_opt_ ThreadFailureCallbackHolder *pCallback, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength)
  829. {
  830. *callContextString = '\0';
  831. bool foundContext = false;
  832. if (pCallback != nullptr)
  833. {
  834. foundContext = GetThreadContext(pFailure, pCallback->m_pNext, callContextString, callContextStringLength);
  835. if (pCallback->m_pCallContext != nullptr)
  836. {
  837. auto &context = *pCallback->m_pCallContext;
  838. // We generate the next telemetry ID only when we've found an error (avoid always incrementing)
  839. if (context.contextId == 0)
  840. {
  841. context.contextId = ::InterlockedIncrementNoFence(&s_telemetryId);
  842. }
  843. if (pFailure->callContextOriginating.contextId == 0)
  844. {
  845. pFailure->callContextOriginating = context;
  846. }
  847. pFailure->callContextCurrent = context;
  848. auto callContextStringEnd = callContextString + callContextStringLength;
  849. callContextString += strlen(callContextString);
  850. if ((callContextStringEnd - callContextString) > 2) // room for at least the slash + null
  851. {
  852. *callContextString++ = '\\';
  853. auto nameSizeBytes = strlen(context.contextName) + 1;
  854. size_t remainingBytes = static_cast<size_t>(callContextStringEnd - callContextString);
  855. auto copyBytes = (nameSizeBytes < remainingBytes) ? nameSizeBytes : remainingBytes;
  856. memcpy_s(callContextString, remainingBytes, context.contextName, copyBytes);
  857. *(callContextString + (copyBytes - 1)) = '\0';
  858. }
  859. return true;
  860. }
  861. }
  862. return foundContext;
  863. }
  864. static void GetContextAndNotifyFailure(_Inout_ FailureInfo *pFailure, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT
  865. {
  866. *callContextString = '\0';
  867. bool reportedTelemetry = false;
  868. ThreadFailureCallbackHolder **ppListeners = g_pThreadFailureCallbacks ? g_pThreadFailureCallbacks->GetLocal() : nullptr;
  869. if ((ppListeners != nullptr) && (*ppListeners != nullptr))
  870. {
  871. callContextString[0] = '\0';
  872. if (GetThreadContext(pFailure, *ppListeners, callContextString, callContextStringLength))
  873. {
  874. pFailure->pszCallContext = callContextString;
  875. }
  876. auto pNode = *ppListeners;
  877. do
  878. {
  879. reportedTelemetry |= pNode->m_pCallback->NotifyFailure(*pFailure);
  880. pNode = pNode->m_pNext;
  881. }
  882. while (pNode != nullptr);
  883. }
  884. if (g_pfnTelemetryCallback != nullptr)
  885. {
  886. // If the telemetry was requested to be suppressed,
  887. // pretend like it has already been reported to the fallback callback
  888. g_pfnTelemetryCallback(reportedTelemetry || WI_IsFlagSet(pFailure->flags, FailureFlags::RequestSuppressTelemetry), *pFailure);
  889. }
  890. }
  891. ThreadFailureCallbackHolder(ThreadFailureCallbackHolder const &) = delete;
  892. ThreadFailureCallbackHolder& operator=(ThreadFailureCallbackHolder const &) = delete;
  893. private:
  894. static long volatile s_telemetryId;
  895. ThreadFailureCallbackHolder **m_ppThreadList;
  896. IFailureCallback *m_pCallback;
  897. ThreadFailureCallbackHolder *m_pNext;
  898. DWORD m_threadId;
  899. wil::CallContextInfo *m_pCallContext;
  900. };
  901. __declspec(selectany) long volatile ThreadFailureCallbackHolder::s_telemetryId = 1;
  902. template <typename TLambda>
  903. class ThreadFailureCallbackFn final : public IFailureCallback
  904. {
  905. public:
  906. explicit ThreadFailureCallbackFn(_In_opt_ CallContextInfo *pContext, _Inout_ TLambda &&errorFunction) WI_NOEXCEPT :
  907. m_errorFunction(wistd::move(errorFunction)),
  908. m_callbackHolder(this, pContext)
  909. {
  910. }
  911. ThreadFailureCallbackFn(_Inout_ ThreadFailureCallbackFn && other) WI_NOEXCEPT :
  912. m_errorFunction(wistd::move(other.m_errorFunction)),
  913. m_callbackHolder(this, other.m_callbackHolder.CallContextInfo())
  914. {
  915. }
  916. bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT override
  917. {
  918. return m_errorFunction(failure);
  919. }
  920. private:
  921. ThreadFailureCallbackFn(_In_ ThreadFailureCallbackFn const &);
  922. ThreadFailureCallbackFn & operator=(_In_ ThreadFailureCallbackFn const &);
  923. TLambda m_errorFunction;
  924. ThreadFailureCallbackHolder m_callbackHolder;
  925. };
  926. // returns true if telemetry was reported for this error
  927. inline void __stdcall GetContextAndNotifyFailure(_Inout_ FailureInfo *pFailure, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT
  928. {
  929. ThreadFailureCallbackHolder::GetContextAndNotifyFailure(pFailure, callContextString, callContextStringLength);
  930. // Update the process-wide failure cache
  931. wil::SetLastError(*pFailure);
  932. }
  933. template<typename T, typename... TCtorArgs> void InitGlobalWithStorage(WilInitializeCommand state, void* storage, T*& global, TCtorArgs&&... args)
  934. {
  935. if ((state == WilInitializeCommand::Create) && !global)
  936. {
  937. global = ::new (storage) T(wistd::forward<TCtorArgs>(args)...);
  938. }
  939. else if ((state == WilInitializeCommand::Destroy) && global)
  940. {
  941. global->~T();
  942. global = nullptr;
  943. }
  944. }
  945. }
  946. /// @endcond
  947. /** Modules that cannot use CRT-based static initialization may call this method from their entrypoint
  948. instead. Disable the use of CRT-based initializers by defining RESULT_SUPPRESS_STATIC_INITIALIZERS
  949. while compiling this header. Linking together libraries that disagree on this setting and calling
  950. this method will behave correctly. It may be necessary to recompile all statically linked libraries
  951. with the RESULT_SUPPRESS_... setting to eliminate all "LNK4201 - CRT section exists, but..." errors.
  952. */
  953. inline void WilInitialize_Result(WilInitializeCommand state)
  954. {
  955. static unsigned char s_processLocalData[sizeof(*details_abi::g_pProcessLocalData)];
  956. static unsigned char s_threadFailureCallbacks[sizeof(*details::g_pThreadFailureCallbacks)];
  957. details::InitGlobalWithStorage(state, s_processLocalData, details_abi::g_pProcessLocalData, "WilError_03");
  958. details::InitGlobalWithStorage(state, s_threadFailureCallbacks, details::g_pThreadFailureCallbacks);
  959. if (state == WilInitializeCommand::Create)
  960. {
  961. details::g_pfnGetContextAndNotifyFailure = details::GetContextAndNotifyFailure;
  962. }
  963. }
  964. /// @cond
  965. namespace details
  966. {
  967. #ifndef RESULT_SUPPRESS_STATIC_INITIALIZERS
  968. __declspec(selectany) ::wil::details_abi::ProcessLocalStorage<::wil::details_abi::ProcessLocalData> g_processLocalData("WilError_03");
  969. __declspec(selectany) ::wil::details_abi::ThreadLocalStorage<ThreadFailureCallbackHolder*> g_threadFailureCallbacks;
  970. WI_HEADER_INITITALIZATION_FUNCTION(InitializeResultHeader, []
  971. {
  972. g_pfnGetContextAndNotifyFailure = GetContextAndNotifyFailure;
  973. ::wil::details_abi::g_pProcessLocalData = &g_processLocalData;
  974. g_pThreadFailureCallbacks = &g_threadFailureCallbacks;
  975. return 1;
  976. });
  977. #endif
  978. }
  979. /// @endcond
  980. // This helper functions much like scope_exit -- give it a lambda and get back a local object that can be used to
  981. // catch all errors happening in your module through all WIL error handling mechanisms. The lambda will be called
  982. // once for each error throw, error return, or error catch that is handled while the returned object is still in
  983. // scope. Usage:
  984. //
  985. // auto monitor = wil::ThreadFailureCallback([](wil::FailureInfo const &failure)
  986. // {
  987. // // Write your code that logs or cares about failure details here...
  988. // // It has access to HRESULT, filename, line number, etc through the failure param.
  989. // });
  990. //
  991. // As long as the returned 'monitor' object remains in scope, the lambda will continue to receive callbacks for any
  992. // failures that occur in this module on the calling thread. Note that this will guarantee that the lambda will run
  993. // for any failure that is through any of the WIL macros (THROW_XXX, RETURN_XXX, LOG_XXX, etc).
  994. template <typename TLambda>
  995. inline wil::details::ThreadFailureCallbackFn<TLambda> ThreadFailureCallback(_Inout_ TLambda &&fnAtExit) WI_NOEXCEPT
  996. {
  997. return wil::details::ThreadFailureCallbackFn<TLambda>(nullptr, wistd::forward<TLambda>(fnAtExit));
  998. }
  999. // Much like ThreadFailureCallback, this class will receive WIL failure notifications from the time it's instantiated
  1000. // until the time that it's destroyed. At any point during that time you can ask for the last failure that was seen
  1001. // by any of the WIL macros (RETURN_XXX, THROW_XXX, LOG_XXX, etc) on the current thread.
  1002. //
  1003. // This class is most useful when utilized as a member of an RAII class that's dedicated to providing logging or
  1004. // telemetry. In the destructor of that class, if the operation had not been completed successfully (it goes out of
  1005. // scope due to early return or exception unwind before success is acknowledged) then details about the last failure
  1006. // can be retrieved and appropriately logged.
  1007. //
  1008. // Usage:
  1009. //
  1010. // class MyLogger
  1011. // {
  1012. // public:
  1013. // MyLogger() : m_fComplete(false) {}
  1014. // ~MyLogger()
  1015. // {
  1016. // if (!m_fComplete)
  1017. // {
  1018. // FailureInfo *pFailure = m_cache.GetFailure();
  1019. // if (pFailure != nullptr)
  1020. // {
  1021. // // Log information about pFailure (pFileure->hr, pFailure->pszFile, pFailure->uLineNumber, etc)
  1022. // }
  1023. // else
  1024. // {
  1025. // // It's possible that you get stack unwind from an exception that did NOT come through WIL
  1026. // // like (std::bad_alloc from the STL). Use a reasonable default like: HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION).
  1027. // }
  1028. // }
  1029. // }
  1030. // void Complete() { m_fComplete = true; }
  1031. // private:
  1032. // bool m_fComplete;
  1033. // ThreadFailureCache m_cache;
  1034. // };
  1035. class ThreadFailureCache final :
  1036. public details::IFailureCallback
  1037. {
  1038. public:
  1039. ThreadFailureCache() :
  1040. m_callbackHolder(this)
  1041. {
  1042. }
  1043. ThreadFailureCache(ThreadFailureCache && rhs) WI_NOEXCEPT :
  1044. m_failure(wistd::move(rhs.m_failure)),
  1045. m_callbackHolder(this)
  1046. {
  1047. }
  1048. ThreadFailureCache& operator=(ThreadFailureCache && rhs) WI_NOEXCEPT
  1049. {
  1050. m_failure = wistd::move(rhs.m_failure);
  1051. return *this;
  1052. }
  1053. void WatchCurrentThread()
  1054. {
  1055. m_callbackHolder.StartWatching();
  1056. }
  1057. void IgnoreCurrentThread()
  1058. {
  1059. m_callbackHolder.StopWatching();
  1060. }
  1061. FailureInfo const *GetFailure()
  1062. {
  1063. return (FAILED(m_failure.GetFailureInfo().hr) ? &(m_failure.GetFailureInfo()) : nullptr);
  1064. }
  1065. bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT override
  1066. {
  1067. // When we "cache" a failure, we bias towards trying to find the origin of the last HRESULT
  1068. // generated, so we ignore subsequent failures on the same error code (assuming propagation).
  1069. if (failure.hr != m_failure.GetFailureInfo().hr)
  1070. {
  1071. m_failure.SetFailureInfo(failure);
  1072. }
  1073. return false;
  1074. }
  1075. private:
  1076. StoredFailureInfo m_failure;
  1077. details::ThreadFailureCallbackHolder m_callbackHolder;
  1078. };
  1079. } // wil
  1080. #pragma warning(pop)
  1081. #endif