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