You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1276 lines
52KB

  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. if (--m_refCount == 0)
  211. {
  212. m_data.ProcessShutdown();
  213. }
  214. }
  215. else
  216. {
  217. auto lock = m_mutex.acquire();
  218. if (--m_refCount == 0)
  219. {
  220. // We must explicitly destroy our semaphores while holding the mutex
  221. m_value.Destroy();
  222. lock.reset();
  223. this->~ProcessLocalStorageData();
  224. ::HeapFree(::GetProcessHeap(), 0, this);
  225. }
  226. }
  227. }
  228. static HRESULT Acquire(PCSTR staticNameWithVersion, _Outptr_result_nullonfailure_ ProcessLocalStorageData<T>** data)
  229. {
  230. *data = nullptr;
  231. // NOTE: the '0' in SM0 below is intended as the VERSION number. Changes to this class require
  232. // that this value be revised.
  233. const DWORD size = static_cast<DWORD>(sizeof(ProcessLocalStorageData<T>));
  234. wchar_t name[MAX_PATH];
  235. WI_VERIFY(SUCCEEDED(StringCchPrintfW(name, ARRAYSIZE(name), L"Local\\SM0:%d:%d:%hs", ::GetCurrentProcessId(), size, staticNameWithVersion)));
  236. unique_mutex_nothrow mutex;
  237. mutex.reset(::CreateMutexExW(nullptr, name, 0, MUTEX_ALL_ACCESS));
  238. // This will fail in some environments and will be fixed with deliverable 12394134
  239. RETURN_LAST_ERROR_IF_EXPECTED(!mutex);
  240. auto lock = mutex.acquire();
  241. void* pointer = nullptr;
  242. __WIL_PRIVATE_RETURN_IF_FAILED(SemaphoreValue::TryGetPointer(name, &pointer));
  243. if (pointer)
  244. {
  245. *data = reinterpret_cast<ProcessLocalStorageData<T>*>(pointer);
  246. (*data)->m_refCount++;
  247. }
  248. else
  249. {
  250. __WIL_PRIVATE_RETURN_IF_FAILED(MakeAndInitialize(name, wistd::move(mutex), data)); // Assumes mutex handle ownership on success ('lock' will still be released)
  251. }
  252. return S_OK;
  253. }
  254. private:
  255. volatile long m_refCount = 1;
  256. unique_mutex_nothrow m_mutex;
  257. SemaphoreValue m_value;
  258. T m_data;
  259. static HRESULT MakeAndInitialize(PCWSTR name, unique_mutex_nothrow&& mutex, ProcessLocalStorageData<T>** data)
  260. {
  261. *data = nullptr;
  262. const DWORD size = static_cast<DWORD>(sizeof(ProcessLocalStorageData<T>));
  263. unique_process_heap_ptr<ProcessLocalStorageData<T>> dataAlloc(static_cast<ProcessLocalStorageData<T>*>(::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, size)));
  264. __WIL_PRIVATE_RETURN_IF_NULL_ALLOC(dataAlloc);
  265. SemaphoreValue semaphoreValue;
  266. __WIL_PRIVATE_RETURN_IF_FAILED(semaphoreValue.CreateFromPointer(name, dataAlloc.get()));
  267. new(dataAlloc.get()) ProcessLocalStorageData<T>(wistd::move(mutex), wistd::move(semaphoreValue));
  268. *data = dataAlloc.release();
  269. return S_OK;
  270. }
  271. };
  272. template <typename T>
  273. class ProcessLocalStorage
  274. {
  275. public:
  276. ProcessLocalStorage(PCSTR staticNameWithVersion) WI_NOEXCEPT :
  277. m_staticNameWithVersion(staticNameWithVersion)
  278. {
  279. }
  280. ~ProcessLocalStorage() WI_NOEXCEPT
  281. {
  282. if (m_data)
  283. {
  284. m_data->Release();
  285. }
  286. }
  287. T* GetShared() WI_NOEXCEPT
  288. {
  289. if (!m_data)
  290. {
  291. ProcessLocalStorageData<T>* localTemp = nullptr;
  292. if (SUCCEEDED(ProcessLocalStorageData<T>::Acquire(m_staticNameWithVersion, &localTemp)) && !m_data)
  293. {
  294. m_data = localTemp;
  295. }
  296. }
  297. return m_data ? m_data->GetData() : nullptr;
  298. }
  299. private:
  300. PCSTR m_staticNameWithVersion = nullptr;
  301. ProcessLocalStorageData<T>* m_data = nullptr;
  302. };
  303. template <typename T>
  304. class ThreadLocalStorage
  305. {
  306. public:
  307. ThreadLocalStorage(const ThreadLocalStorage&) = delete;
  308. ThreadLocalStorage& operator=(const ThreadLocalStorage&) = delete;
  309. ThreadLocalStorage() = default;
  310. ~ThreadLocalStorage() WI_NOEXCEPT
  311. {
  312. for (auto &entry : m_hashArray)
  313. {
  314. Node *pNode = entry;
  315. while (pNode != nullptr)
  316. {
  317. auto pCurrent = pNode;
  318. pNode = pNode->pNext;
  319. pCurrent->~Node();
  320. ::HeapFree(::GetProcessHeap(), 0, pCurrent);
  321. }
  322. entry = nullptr;
  323. }
  324. }
  325. // Note: Can return nullptr even when (shouldAllocate == true) upon allocation failure
  326. T* GetLocal(bool shouldAllocate = false) WI_NOEXCEPT
  327. {
  328. DWORD const threadId = ::GetCurrentThreadId();
  329. size_t const index = (threadId % ARRAYSIZE(m_hashArray));
  330. for (auto pNode = m_hashArray[index]; pNode != nullptr; pNode = pNode->pNext)
  331. {
  332. if (pNode->threadId == threadId)
  333. {
  334. return &pNode->value;
  335. }
  336. }
  337. if (shouldAllocate)
  338. {
  339. Node *pNew = reinterpret_cast<Node *>(::HeapAlloc(::GetProcessHeap(), 0, sizeof(Node)));
  340. if (pNew != nullptr)
  341. {
  342. new(pNew)Node{ threadId };
  343. Node *pFirst;
  344. do
  345. {
  346. pFirst = m_hashArray[index];
  347. pNew->pNext = pFirst;
  348. } while (::InterlockedCompareExchangePointer(reinterpret_cast<PVOID volatile *>(m_hashArray + index), pNew, pFirst) != pFirst);
  349. return &pNew->value;
  350. }
  351. }
  352. return nullptr;
  353. }
  354. private:
  355. struct Node
  356. {
  357. DWORD threadId;
  358. Node* pNext = nullptr;
  359. T value{};
  360. };
  361. Node * volatile m_hashArray[10]{};
  362. };
  363. struct ThreadLocalFailureInfo
  364. {
  365. // ABI contract (carry size to facilitate additive change without re-versioning)
  366. unsigned short size;
  367. unsigned char reserved1[2]; // packing, reserved
  368. // When this failure was seen
  369. unsigned int sequenceId;
  370. // Information about the failure
  371. HRESULT hr;
  372. PCSTR fileName;
  373. unsigned short lineNumber;
  374. unsigned char failureType; // FailureType
  375. unsigned char reserved2; // packing, reserved
  376. PCSTR modulePath;
  377. void* returnAddress;
  378. void* callerReturnAddress;
  379. PCWSTR message;
  380. // The allocation (LocalAlloc) where structure strings point
  381. void* stringBuffer;
  382. size_t stringBufferSize;
  383. // NOTE: Externally Managed: Must not have constructor or destructor
  384. void Clear()
  385. {
  386. ::HeapFree(::GetProcessHeap(), 0, stringBuffer);
  387. stringBuffer = nullptr;
  388. stringBufferSize = 0;
  389. }
  390. void Set(const FailureInfo& info, unsigned int newSequenceId)
  391. {
  392. sequenceId = newSequenceId;
  393. hr = info.hr;
  394. fileName = nullptr;
  395. lineNumber = static_cast<unsigned short>(info.uLineNumber);
  396. failureType = static_cast<unsigned char>(info.type);
  397. modulePath = nullptr;
  398. returnAddress = info.returnAddress;
  399. callerReturnAddress = info.callerReturnAddress;
  400. message = nullptr;
  401. size_t neededSize = details::ResultStringSize(info.pszFile) +
  402. details::ResultStringSize(info.pszModule) +
  403. details::ResultStringSize(info.pszMessage);
  404. if (!stringBuffer || (stringBufferSize < neededSize))
  405. {
  406. auto newBuffer = ::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, neededSize);
  407. if (newBuffer)
  408. {
  409. ::HeapFree(::GetProcessHeap(), 0, stringBuffer);
  410. stringBuffer = newBuffer;
  411. stringBufferSize = neededSize;
  412. }
  413. }
  414. if (stringBuffer)
  415. {
  416. unsigned char *pBuffer = static_cast<unsigned char *>(stringBuffer);
  417. unsigned char *pBufferEnd = pBuffer + stringBufferSize;
  418. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszFile, &fileName);
  419. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszModule, &modulePath);
  420. pBuffer = details::WriteResultString(pBuffer, pBufferEnd, info.pszMessage, &message);
  421. ZeroMemory(pBuffer, pBufferEnd - pBuffer);
  422. }
  423. }
  424. void Get(FailureInfo& info)
  425. {
  426. ::ZeroMemory(&info, sizeof(info));
  427. info.failureId = sequenceId;
  428. info.hr = hr;
  429. info.pszFile = fileName;
  430. info.uLineNumber = lineNumber;
  431. info.type = static_cast<FailureType>(failureType);
  432. info.pszModule = modulePath;
  433. info.returnAddress = returnAddress;
  434. info.callerReturnAddress = callerReturnAddress;
  435. info.pszMessage = message;
  436. }
  437. };
  438. struct ThreadLocalData
  439. {
  440. // ABI contract (carry size to facilitate additive change without re-versioning)
  441. unsigned short size = sizeof(ThreadLocalData);
  442. // Subscription information
  443. unsigned int threadId = 0;
  444. volatile long* failureSequenceId = nullptr; // backpointer to the global ID
  445. // Information about thread errors
  446. unsigned int latestSubscribedFailureSequenceId = 0;
  447. // The last (N) observed errors
  448. ThreadLocalFailureInfo* errors = nullptr;
  449. unsigned short errorAllocCount = 0;
  450. unsigned short errorCurrentIndex = 0;
  451. // NOTE: Externally Managed: Must allow ZERO init construction
  452. ~ThreadLocalData()
  453. {
  454. Clear();
  455. }
  456. void Clear()
  457. {
  458. for (auto& error : make_range(errors, errorAllocCount))
  459. {
  460. error.Clear();
  461. }
  462. ::HeapFree(::GetProcessHeap(), 0, errors);
  463. errorAllocCount = 0;
  464. errorCurrentIndex = 0;
  465. errors = nullptr;
  466. }
  467. bool EnsureAllocated(bool create = true)
  468. {
  469. if (!errors && create)
  470. {
  471. const unsigned short errorCount = 5;
  472. errors = reinterpret_cast<ThreadLocalFailureInfo *>(::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, errorCount * sizeof(ThreadLocalFailureInfo)));
  473. if (errors)
  474. {
  475. errorAllocCount = errorCount;
  476. errorCurrentIndex = 0;
  477. for (auto& error : make_range(errors, errorAllocCount))
  478. {
  479. error.size = sizeof(ThreadLocalFailureInfo);
  480. }
  481. }
  482. }
  483. return (errors != nullptr);
  484. }
  485. void SetLastError(const wil::FailureInfo& info)
  486. {
  487. const bool hasListener = (latestSubscribedFailureSequenceId > 0);
  488. if (!EnsureAllocated(hasListener))
  489. {
  490. // We either couldn't allocate or we haven't yet allocated and nobody
  491. // was listening, so we ignore.
  492. return;
  493. }
  494. if (hasListener)
  495. {
  496. // When we have listeners, we can throw away any updates to the last seen error
  497. // code within the same listening context presuming it's an update of the existing
  498. // error with the same code.
  499. for (auto& error : make_range(errors, errorAllocCount))
  500. {
  501. if ((error.sequenceId > latestSubscribedFailureSequenceId) && (error.hr == info.hr))
  502. {
  503. return;
  504. }
  505. }
  506. }
  507. // Otherwise we create a new failure...
  508. errorCurrentIndex = (errorCurrentIndex + 1) % errorAllocCount;
  509. errors[errorCurrentIndex].Set(info, ::InterlockedIncrementNoFence(failureSequenceId));
  510. }
  511. bool GetLastError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId, HRESULT matchRequirement)
  512. {
  513. if (!errors)
  514. {
  515. return false;
  516. }
  517. // If the last error we saw doesn't meet the filter requirement or if the last error was never
  518. // set, then we couldn't return a result at all...
  519. auto& lastFailure = errors[errorCurrentIndex];
  520. if (minSequenceId >= lastFailure.sequenceId)
  521. {
  522. return false;
  523. }
  524. // With no result filter, we just go to the last error and report it
  525. if (matchRequirement == S_OK)
  526. {
  527. lastFailure.Get(info);
  528. return true;
  529. }
  530. // Find the oldest result matching matchRequirement and passing minSequenceId
  531. ThreadLocalFailureInfo* find = nullptr;
  532. for (auto& error : make_range(errors, errorAllocCount))
  533. {
  534. if ((error.hr == matchRequirement) && (error.sequenceId > minSequenceId))
  535. {
  536. if (!find || (error.sequenceId < find->sequenceId))
  537. {
  538. find = &error;
  539. }
  540. }
  541. }
  542. if (find)
  543. {
  544. find->Get(info);
  545. return true;
  546. }
  547. return false;
  548. }
  549. bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId, _In_opt_ const DiagnosticsInfo* diagnostics, HRESULT matchRequirement, void* returnAddress)
  550. {
  551. // First attempt to get the last error and then see if it matches the error returned from
  552. // the last caught exception. If it does, then we're good to go and we return that last error.
  553. FailureInfo last = {};
  554. if (GetLastError(last, minSequenceId, matchRequirement) && (last.hr == ResultFromCaughtException()))
  555. {
  556. info = last;
  557. return true;
  558. }
  559. // The last error didn't match or we never had one... we need to create one -- we do so by logging
  560. // our current request and then using the last error.
  561. DiagnosticsInfo source;
  562. if (diagnostics)
  563. {
  564. source = *diagnostics;
  565. }
  566. // NOTE: FailureType::Log as it's only informative (no action) and SupportedExceptions::All as it's not a barrier, only recognition.
  567. wchar_t message[2048];
  568. message[0] = L'\0';
  569. const HRESULT hr = details::ReportFailure_CaughtExceptionCommon<FailureType::Log>(__R_DIAGNOSTICS_RA(source, returnAddress), message, ARRAYSIZE(message), SupportedExceptions::All);
  570. // Now that the exception was logged, we should be able to fetch it.
  571. return GetLastError(info, minSequenceId, hr);
  572. }
  573. };
  574. struct ProcessLocalData
  575. {
  576. // ABI contract (carry size to facilitate additive change without re-versioning)
  577. unsigned short size = sizeof(ProcessLocalData);
  578. // Failure Information
  579. volatile long failureSequenceId = 1; // process global variable
  580. ThreadLocalStorage<ThreadLocalData> threads; // list of allocated threads
  581. void ProcessShutdown() {}
  582. };
  583. __declspec(selectany) ProcessLocalStorage<ProcessLocalData>* g_pProcessLocalData = nullptr;
  584. __declspec(noinline) inline ThreadLocalData* GetThreadLocalDataCache(bool allocate = true)
  585. {
  586. ThreadLocalData* result = nullptr;
  587. if (g_pProcessLocalData)
  588. {
  589. auto processData = g_pProcessLocalData->GetShared();
  590. if (processData)
  591. {
  592. result = processData->threads.GetLocal(allocate);
  593. if (result && !result->failureSequenceId)
  594. {
  595. result->failureSequenceId = &(processData->failureSequenceId);
  596. }
  597. }
  598. }
  599. return result;
  600. }
  601. __forceinline ThreadLocalData* GetThreadLocalData(bool allocate = true)
  602. {
  603. return GetThreadLocalDataCache(allocate);
  604. }
  605. } // details_abi
  606. /// @endcond
  607. /** Returns a sequence token that can be used with wil::GetLastError to limit errors to those that occur after this token was retrieved.
  608. General usage pattern: use wil::GetCurrentErrorSequenceId to cache a token, execute your code, on failure use wil::GetLastError with the token
  609. to provide information on the error that occurred while executing your code. Prefer to use wil::ThreadErrorContext over this approach when
  610. possible. */
  611. inline long GetCurrentErrorSequenceId()
  612. {
  613. auto data = details_abi::GetThreadLocalData();
  614. if (data)
  615. {
  616. // someone is interested -- make sure we can store errors
  617. data->EnsureAllocated();
  618. return *data->failureSequenceId;
  619. }
  620. return 0;
  621. }
  622. /** Caches failure information for later retrieval from GetLastError.
  623. Most people will never need to do this explicitly as failure information is automatically made available per-thread across a process when
  624. errors are encountered naturally through the WIL macros. */
  625. inline void SetLastError(const wil::FailureInfo& info)
  626. {
  627. static volatile unsigned int lastThread = 0;
  628. auto threadId = ::GetCurrentThreadId();
  629. if (lastThread != threadId)
  630. {
  631. static volatile long depth = 0;
  632. if (::InterlockedIncrementNoFence(&depth) < 4)
  633. {
  634. lastThread = threadId;
  635. auto data = details_abi::GetThreadLocalData(false); // false = avoids allocation if not already present
  636. if (data)
  637. {
  638. data->SetLastError(info);
  639. }
  640. lastThread = 0;
  641. }
  642. ::InterlockedDecrementNoFence(&depth);
  643. }
  644. }
  645. /** Retrieves failure information for the current thread with the given filters.
  646. This API can be used to retrieve information about the last WIL failure that occurred on the current thread.
  647. This error crosses DLL boundaries as long as the error occurred in the current process. Passing a minSequenceId
  648. restricts the error returned to one that occurred after the given sequence ID. Passing matchRequirement also filters
  649. the returned result to the given error code. */
  650. inline bool GetLastError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId = 0, HRESULT matchRequirement = S_OK)
  651. {
  652. auto data = details_abi::GetThreadLocalData(false); // false = avoids allocation if not already present
  653. if (data)
  654. {
  655. return data->GetLastError(info, minSequenceId, matchRequirement);
  656. }
  657. return false;
  658. }
  659. /** Retrieves failure information when within a catch block for the current thread with the given filters.
  660. When unable to retrieve the exception information (when WIL hasn't yet seen it), this will attempt (best effort) to
  661. discover information about the exception and will attribute that information to the given DiagnosticsInfo position.
  662. See GetLastError for capabilities and filtering. */
  663. inline __declspec(noinline) bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, unsigned int minSequenceId = 0, const DiagnosticsInfo* diagnostics = nullptr, HRESULT matchRequirement = S_OK)
  664. {
  665. auto data = details_abi::GetThreadLocalData();
  666. if (data)
  667. {
  668. return data->GetCaughtExceptionError(info, minSequenceId, diagnostics, matchRequirement, _ReturnAddress());
  669. }
  670. return false;
  671. }
  672. /** Use this class to manage retrieval of information about an error occurring in the requested code.
  673. Construction of this class sets a point in time after which you can use the GetLastError class method to retrieve
  674. the origination of the last error that occurred on this thread since the class was created. */
  675. class ThreadErrorContext
  676. {
  677. public:
  678. ThreadErrorContext() :
  679. m_data(details_abi::GetThreadLocalData())
  680. {
  681. if (m_data)
  682. {
  683. m_sequenceIdLast = m_data->latestSubscribedFailureSequenceId;
  684. m_sequenceIdStart = *m_data->failureSequenceId;
  685. m_data->latestSubscribedFailureSequenceId = m_sequenceIdStart;
  686. }
  687. }
  688. ~ThreadErrorContext()
  689. {
  690. if (m_data)
  691. {
  692. m_data->latestSubscribedFailureSequenceId = m_sequenceIdLast;
  693. }
  694. }
  695. /** Retrieves the origination of the last error that occurred since this class was constructed.
  696. The optional parameter allows the failure information returned to be filtered to a specific
  697. result. */
  698. inline bool GetLastError(FailureInfo& info, HRESULT matchRequirement = S_OK)
  699. {
  700. if (m_data)
  701. {
  702. return m_data->GetLastError(info, m_sequenceIdStart, matchRequirement);
  703. }
  704. return false;
  705. }
  706. /** Retrieves the origin of the current exception (within a catch block) since this class was constructed.
  707. See @ref GetCaughtExceptionError for more information */
  708. inline __declspec(noinline) bool GetCaughtExceptionError(_Inout_ wil::FailureInfo& info, const DiagnosticsInfo* diagnostics = nullptr, HRESULT matchRequirement = S_OK)
  709. {
  710. if (m_data)
  711. {
  712. return m_data->GetCaughtExceptionError(info, m_sequenceIdStart, diagnostics, matchRequirement, _ReturnAddress());
  713. }
  714. return false;
  715. }
  716. private:
  717. details_abi::ThreadLocalData* m_data;
  718. unsigned long m_sequenceIdStart{};
  719. unsigned long m_sequenceIdLast{};
  720. };
  721. enum class WilInitializeCommand
  722. {
  723. Create,
  724. Destroy,
  725. };
  726. /// @cond
  727. namespace details
  728. {
  729. struct IFailureCallback
  730. {
  731. virtual bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT = 0;
  732. };
  733. class ThreadFailureCallbackHolder;
  734. __declspec(selectany) details_abi::ThreadLocalStorage<ThreadFailureCallbackHolder*>* g_pThreadFailureCallbacks = nullptr;
  735. class ThreadFailureCallbackHolder
  736. {
  737. public:
  738. ThreadFailureCallbackHolder(_In_ IFailureCallback *pCallbackParam, _In_opt_ CallContextInfo *pCallContext = nullptr, bool watchNow = true) WI_NOEXCEPT :
  739. m_ppThreadList(nullptr),
  740. m_pCallback(pCallbackParam),
  741. m_pNext(nullptr),
  742. m_threadId(0),
  743. m_pCallContext(pCallContext)
  744. {
  745. if (watchNow)
  746. {
  747. StartWatching();
  748. }
  749. }
  750. ThreadFailureCallbackHolder(ThreadFailureCallbackHolder &&other) WI_NOEXCEPT :
  751. m_ppThreadList(nullptr),
  752. m_pCallback(other.m_pCallback),
  753. m_pNext(nullptr),
  754. m_threadId(0),
  755. m_pCallContext(other.m_pCallContext)
  756. {
  757. if (other.m_threadId != 0)
  758. {
  759. other.StopWatching();
  760. StartWatching();
  761. }
  762. }
  763. ~ThreadFailureCallbackHolder() WI_NOEXCEPT
  764. {
  765. if (m_threadId != 0)
  766. {
  767. StopWatching();
  768. }
  769. }
  770. void SetCallContext(_In_opt_ CallContextInfo *pCallContext)
  771. {
  772. m_pCallContext = pCallContext;
  773. }
  774. CallContextInfo *CallContextInfo()
  775. {
  776. return m_pCallContext;
  777. }
  778. void StartWatching()
  779. {
  780. // out-of balance Start/Stop calls?
  781. __FAIL_FAST_IMMEDIATE_ASSERT__(m_threadId == 0);
  782. m_ppThreadList = g_pThreadFailureCallbacks ? g_pThreadFailureCallbacks->GetLocal(true) : nullptr; // true = allocate thread list if missing
  783. if (m_ppThreadList)
  784. {
  785. m_pNext = *m_ppThreadList;
  786. *m_ppThreadList = this;
  787. m_threadId = ::GetCurrentThreadId();
  788. }
  789. }
  790. void StopWatching()
  791. {
  792. if (m_threadId != ::GetCurrentThreadId())
  793. {
  794. // The thread-specific failure holder cannot be stopped on a different thread than it was started on or the
  795. // internal book-keeping list will be corrupted. To fix this change the telemetry pattern in the calling code
  796. // to match one of the patterns available here:
  797. // https://microsoft.sharepoint.com/teams/osg_development/Shared%20Documents/Windows%20TraceLogging%20Helpers.docx
  798. WI_USAGE_ERROR("MEMORY CORRUPTION: Calling code is leaking an activity thread-watcher and releasing it on another thread");
  799. }
  800. m_threadId = 0;
  801. while (*m_ppThreadList != nullptr)
  802. {
  803. if (*m_ppThreadList == this)
  804. {
  805. *m_ppThreadList = m_pNext;
  806. break;
  807. }
  808. m_ppThreadList = &((*m_ppThreadList)->m_pNext);
  809. }
  810. m_ppThreadList = nullptr;
  811. }
  812. bool IsWatching()
  813. {
  814. return (m_threadId != 0);
  815. }
  816. void SetWatching(bool shouldWatch)
  817. {
  818. if (shouldWatch && !IsWatching())
  819. {
  820. StartWatching();
  821. }
  822. else if (!shouldWatch && IsWatching())
  823. {
  824. StopWatching();
  825. }
  826. }
  827. static bool GetThreadContext(_Inout_ FailureInfo *pFailure, _In_opt_ ThreadFailureCallbackHolder *pCallback, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength)
  828. {
  829. *callContextString = '\0';
  830. bool foundContext = false;
  831. if (pCallback != nullptr)
  832. {
  833. foundContext = GetThreadContext(pFailure, pCallback->m_pNext, callContextString, callContextStringLength);
  834. if (pCallback->m_pCallContext != nullptr)
  835. {
  836. auto &context = *pCallback->m_pCallContext;
  837. // We generate the next telemetry ID only when we've found an error (avoid always incrementing)
  838. if (context.contextId == 0)
  839. {
  840. context.contextId = ::InterlockedIncrementNoFence(&s_telemetryId);
  841. }
  842. if (pFailure->callContextOriginating.contextId == 0)
  843. {
  844. pFailure->callContextOriginating = context;
  845. }
  846. pFailure->callContextCurrent = context;
  847. auto callContextStringEnd = callContextString + callContextStringLength;
  848. callContextString += strlen(callContextString);
  849. if ((callContextStringEnd - callContextString) > 2) // room for at least the slash + null
  850. {
  851. *callContextString++ = '\\';
  852. auto nameSizeBytes = strlen(context.contextName) + 1;
  853. size_t remainingBytes = static_cast<size_t>(callContextStringEnd - callContextString);
  854. auto copyBytes = (nameSizeBytes < remainingBytes) ? nameSizeBytes : remainingBytes;
  855. memcpy_s(callContextString, remainingBytes, context.contextName, copyBytes);
  856. *(callContextString + (copyBytes - 1)) = '\0';
  857. }
  858. return true;
  859. }
  860. }
  861. return foundContext;
  862. }
  863. static void GetContextAndNotifyFailure(_Inout_ FailureInfo *pFailure, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT
  864. {
  865. *callContextString = '\0';
  866. bool reportedTelemetry = false;
  867. ThreadFailureCallbackHolder **ppListeners = g_pThreadFailureCallbacks ? g_pThreadFailureCallbacks->GetLocal() : nullptr;
  868. if ((ppListeners != nullptr) && (*ppListeners != nullptr))
  869. {
  870. callContextString[0] = '\0';
  871. if (GetThreadContext(pFailure, *ppListeners, callContextString, callContextStringLength))
  872. {
  873. pFailure->pszCallContext = callContextString;
  874. }
  875. auto pNode = *ppListeners;
  876. do
  877. {
  878. reportedTelemetry |= pNode->m_pCallback->NotifyFailure(*pFailure);
  879. pNode = pNode->m_pNext;
  880. }
  881. while (pNode != nullptr);
  882. }
  883. if (g_pfnTelemetryCallback != nullptr)
  884. {
  885. g_pfnTelemetryCallback(reportedTelemetry, *pFailure);
  886. }
  887. }
  888. ThreadFailureCallbackHolder(ThreadFailureCallbackHolder const &) = delete;
  889. ThreadFailureCallbackHolder& operator=(ThreadFailureCallbackHolder const &) = delete;
  890. private:
  891. static long volatile s_telemetryId;
  892. ThreadFailureCallbackHolder **m_ppThreadList;
  893. IFailureCallback *m_pCallback;
  894. ThreadFailureCallbackHolder *m_pNext;
  895. DWORD m_threadId;
  896. wil::CallContextInfo *m_pCallContext;
  897. };
  898. __declspec(selectany) long volatile ThreadFailureCallbackHolder::s_telemetryId = 1;
  899. template <typename TLambda>
  900. class ThreadFailureCallbackFn final : public IFailureCallback
  901. {
  902. public:
  903. explicit ThreadFailureCallbackFn(_In_opt_ CallContextInfo *pContext, _Inout_ TLambda &&errorFunction) WI_NOEXCEPT :
  904. m_errorFunction(wistd::move(errorFunction)),
  905. m_callbackHolder(this, pContext)
  906. {
  907. }
  908. ThreadFailureCallbackFn(_Inout_ ThreadFailureCallbackFn && other) WI_NOEXCEPT :
  909. m_errorFunction(wistd::move(other.m_errorFunction)),
  910. m_callbackHolder(this, other.m_callbackHolder.CallContextInfo())
  911. {
  912. }
  913. bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT
  914. {
  915. return m_errorFunction(failure);
  916. }
  917. private:
  918. ThreadFailureCallbackFn(_In_ ThreadFailureCallbackFn const &);
  919. ThreadFailureCallbackFn & operator=(_In_ ThreadFailureCallbackFn const &);
  920. TLambda m_errorFunction;
  921. ThreadFailureCallbackHolder m_callbackHolder;
  922. };
  923. // returns true if telemetry was reported for this error
  924. inline void __stdcall GetContextAndNotifyFailure(_Inout_ FailureInfo *pFailure, _Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString, _Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT
  925. {
  926. ThreadFailureCallbackHolder::GetContextAndNotifyFailure(pFailure, callContextString, callContextStringLength);
  927. // Update the process-wide failure cache
  928. wil::SetLastError(*pFailure);
  929. }
  930. template<typename T, typename... TCtorArgs> void InitGlobalWithStorage(WilInitializeCommand state, void* storage, T*& global, TCtorArgs&&... args)
  931. {
  932. if ((state == WilInitializeCommand::Create) && !global)
  933. {
  934. global = ::new (storage) T(wistd::forward<TCtorArgs>(args)...);
  935. }
  936. else if ((state == WilInitializeCommand::Destroy) && global)
  937. {
  938. global->~T();
  939. global = nullptr;
  940. }
  941. }
  942. }
  943. /// @endcond
  944. /** Modules that cannot use CRT-based static initialization may call this method from their entrypoint
  945. instead. Disable the use of CRT-based initializers by defining RESULT_SUPPRESS_STATIC_INITIALIZERS
  946. while compiling this header. Linking together libraries that disagree on this setting and calling
  947. this method will behave correctly. It may be necessary to recompile all statically linked libraries
  948. with the RESULT_SUPPRESS_... setting to eliminate all "LNK4201 - CRT section exists, but..." errors.
  949. */
  950. inline void WilInitialize_Result(WilInitializeCommand state)
  951. {
  952. static unsigned char s_processLocalData[sizeof(*details_abi::g_pProcessLocalData)];
  953. static unsigned char s_threadFailureCallbacks[sizeof(*details::g_pThreadFailureCallbacks)];
  954. details::InitGlobalWithStorage(state, s_processLocalData, details_abi::g_pProcessLocalData, "WilError_03");
  955. details::InitGlobalWithStorage(state, s_threadFailureCallbacks, details::g_pThreadFailureCallbacks);
  956. if (state == WilInitializeCommand::Create)
  957. {
  958. details::g_pfnGetContextAndNotifyFailure = details::GetContextAndNotifyFailure;
  959. }
  960. }
  961. /// @cond
  962. namespace details
  963. {
  964. #ifndef RESULT_SUPPRESS_STATIC_INITIALIZERS
  965. __declspec(selectany) ::wil::details_abi::ProcessLocalStorage<::wil::details_abi::ProcessLocalData> g_processLocalData("WilError_03");
  966. __declspec(selectany) ::wil::details_abi::ThreadLocalStorage<ThreadFailureCallbackHolder*> g_threadFailureCallbacks;
  967. WI_HEADER_INITITALIZATION_FUNCTION(InitializeResultHeader, []
  968. {
  969. g_pfnGetContextAndNotifyFailure = GetContextAndNotifyFailure;
  970. ::wil::details_abi::g_pProcessLocalData = &g_processLocalData;
  971. g_pThreadFailureCallbacks = &g_threadFailureCallbacks;
  972. return 1;
  973. });
  974. #endif
  975. }
  976. /// @endcond
  977. // This helper functions much like scope_exit -- give it a lambda and get back a local object that can be used to
  978. // catch all errors happening in your module through all WIL error handling mechanisms. The lambda will be called
  979. // once for each error throw, error return, or error catch that is handled while the returned object is still in
  980. // scope. Usage:
  981. //
  982. // auto monitor = wil::ThreadFailureCallback([](wil::FailureInfo const &failure)
  983. // {
  984. // // Write your code that logs or cares about failure details here...
  985. // // It has access to HRESULT, filename, line number, etc through the failure param.
  986. // });
  987. //
  988. // As long as the returned 'monitor' object remains in scope, the lambda will continue to receive callbacks for any
  989. // failures that occur in this module on the calling thread. Note that this will guarantee that the lambda will run
  990. // for any failure that is through any of the WIL macros (THROW_XXX, RETURN_XXX, LOG_XXX, etc).
  991. template <typename TLambda>
  992. inline wil::details::ThreadFailureCallbackFn<TLambda> ThreadFailureCallback(_Inout_ TLambda &&fnAtExit) WI_NOEXCEPT
  993. {
  994. return wil::details::ThreadFailureCallbackFn<TLambda>(nullptr, wistd::forward<TLambda>(fnAtExit));
  995. }
  996. // Much like ThreadFailureCallback, this class will receive WIL failure notifications from the time it's instantiated
  997. // until the time that it's destroyed. At any point during that time you can ask for the last failure that was seen
  998. // by any of the WIL macros (RETURN_XXX, THROW_XXX, LOG_XXX, etc) on the current thread.
  999. //
  1000. // This class is most useful when utilized as a member of an RAII class that's dedicated to providing logging or
  1001. // telemetry. In the destructor of that class, if the operation had not been completed successfully (it goes out of
  1002. // scope due to early return or exception unwind before success is acknowledged) then details about the last failure
  1003. // can be retrieved and appropriately logged.
  1004. //
  1005. // Usage:
  1006. //
  1007. // class MyLogger
  1008. // {
  1009. // public:
  1010. // MyLogger() : m_fComplete(false) {}
  1011. // ~MyLogger()
  1012. // {
  1013. // if (!m_fComplete)
  1014. // {
  1015. // FailureInfo *pFailure = m_cache.GetFailure();
  1016. // if (pFailure != nullptr)
  1017. // {
  1018. // // Log information about pFailure (pFileure->hr, pFailure->pszFile, pFailure->uLineNumber, etc)
  1019. // }
  1020. // else
  1021. // {
  1022. // // It's possible that you get stack unwind from an exception that did NOT come through WIL
  1023. // // like (std::bad_alloc from the STL). Use a reasonable default like: HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION).
  1024. // }
  1025. // }
  1026. // }
  1027. // void Complete() { m_fComplete = true; }
  1028. // private:
  1029. // bool m_fComplete;
  1030. // ThreadFailureCache m_cache;
  1031. // };
  1032. class ThreadFailureCache final :
  1033. public details::IFailureCallback
  1034. {
  1035. public:
  1036. ThreadFailureCache() :
  1037. m_callbackHolder(this)
  1038. {
  1039. }
  1040. ThreadFailureCache(ThreadFailureCache && rhs) WI_NOEXCEPT :
  1041. m_failure(wistd::move(rhs.m_failure)),
  1042. m_callbackHolder(this)
  1043. {
  1044. }
  1045. ThreadFailureCache& operator=(ThreadFailureCache && rhs) WI_NOEXCEPT
  1046. {
  1047. m_failure = wistd::move(rhs.m_failure);
  1048. return *this;
  1049. }
  1050. void WatchCurrentThread()
  1051. {
  1052. m_callbackHolder.StartWatching();
  1053. }
  1054. void IgnoreCurrentThread()
  1055. {
  1056. m_callbackHolder.StopWatching();
  1057. }
  1058. FailureInfo const *GetFailure()
  1059. {
  1060. return (FAILED(m_failure.GetFailureInfo().hr) ? &(m_failure.GetFailureInfo()) : nullptr);
  1061. }
  1062. bool NotifyFailure(FailureInfo const &failure) WI_NOEXCEPT
  1063. {
  1064. // When we "cache" a failure, we bias towards trying to find the origin of the last HRESULT
  1065. // generated, so we ignore subsequent failures on the same error code (assuming propagation).
  1066. if (failure.hr != m_failure.GetFailureInfo().hr)
  1067. {
  1068. m_failure.SetFailureInfo(failure);
  1069. }
  1070. return false;
  1071. }
  1072. private:
  1073. StoredFailureInfo m_failure;
  1074. details::ThreadFailureCallbackHolder m_callbackHolder;
  1075. };
  1076. } // wil
  1077. #pragma warning(pop)
  1078. #endif