/
Tracelogging.h
6697 lines (6301 loc) · 300 KB
/
Tracelogging.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
#pragma once
//*********************************************************
//
// 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
//! Defines a series of macros and types that simplify authoring and consumption of tracelogging, telemetry, and activities.
#ifndef __WIL_TRACELOGGING_H_INCLUDED
/// @cond
#define __WIL_TRACELOGGING_H_INCLUDED
/// @endcond
#ifdef _KERNEL_MODE
#error This header is not supported in kernel-mode.
#endif
// Note that we avoid pulling in STL's memory header from TraceLogging.h through Resource.h as we have
// TraceLogging customers who are still on older versions of STL (without std::shared_ptr<>).
/// @cond
#define RESOURCE_SUPPRESS_STL
/// @endcond
#ifndef __WIL_RESULT_INCLUDED
#include <wil/result.h>
#endif
#undef RESOURCE_SUPPRESS_STL
#include <winmeta.h>
#include <TraceLoggingProvider.h>
#include <TraceLoggingActivity.h>
#ifndef __WIL_TRACELOGGING_CONFIG_H
#include <wil/traceloggingconfig.h>
#endif
#ifndef TRACELOGGING_SUPPRESS_NEW
#include <new>
#endif
#pragma warning(push)
#pragma warning(disable : 26135) // Missing locking annotation, Caller failing to hold lock
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmicrosoft-template-shadow"
#endif
/// @cond
#ifndef __TRACELOGGING_TEST_HOOK_ERROR
#define __TRACELOGGING_TEST_HOOK_ERROR(failure)
#define __TRACELOGGING_TEST_HOOK_ACTIVITY_ERROR(failure)
#define __TRACELOGGING_TEST_HOOK_CALLCONTEXT_ERROR(pFailure, hr)
#define __TRACELOGGING_TEST_HOOK_ACTIVITY_START()
#define __TRACELOGGING_TEST_HOOK_ACTIVITY_STOP(pFailure, hr)
#define __TRACELOGGING_TEST_HOOK_SET_ENABLED false
#define __TRACELOGGING_TEST_HOOK_VERIFY_API_TELEMETRY(nameSpace, apiList, specializationList, countArray, numCounters)
#define __TRACELOGGING_TEST_HOOK_API_TELEMETRY_EVENT_DELAY_MS 5000
#endif
// For use only within wil/TraceLogging.h:
#define _wiltlg_STRINGIZE(x) _wiltlg_STRINGIZE_imp(x)
#define _wiltlg_STRINGIZE_imp(x) #x
#define _wiltlg_LSTRINGIZE(x) _wiltlg_LSTRINGIZE_imp1(x)
#define _wiltlg_LSTRINGIZE_imp1(x) _wiltlg_LSTRINGIZE_imp2(#x)
#define _wiltlg_LSTRINGIZE_imp2(s) L##s
/*
Macro __TRACELOGGING_DEFINE_PROVIDER_STORAGE_LINK(name1, name2):
This macro defines a storage link association between two names for use by the
TlgReflector static analysis tool.
*/
#define __TRACELOGGING_DEFINE_PROVIDER_STORAGE_LINK(name1, name2) \
__annotation(L"_TlgProviderLink:|" _wiltlg_LSTRINGIZE(__LINE__) L"|Key|" _wiltlg_LSTRINGIZE(name1) L"=" _wiltlg_LSTRINGIZE(name2))
// Utility macro for writing relevant fields from a wil::FailureInfo structure into a TraceLoggingWrite
// statement. Most fields are relevant for telemetry or for simple ETW, but there are a few additional
// fields reported via ETW.
#define __RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure) \
TraceLoggingUInt32((failure).hr, "hresult", "Failure error code"), \
TraceLoggingString((failure).pszFile, "fileName", "Source code file name where the error occurred"), \
TraceLoggingUInt32((failure).uLineNumber, "lineNumber", "Line number within the source code file where the error occurred"), \
TraceLoggingString((failure).pszModule, "module", "Name of the binary where the error occurred"), \
TraceLoggingUInt32( \
static_cast<DWORD>((failure).type), \
"failureType", \
"Indicates what type of failure was observed (exception, returned error, logged error or fail fast"), \
TraceLoggingWideString((failure).pszMessage, "message", "Custom message associated with the failure (if any)"), \
TraceLoggingUInt32((failure).threadId, "threadId", "Identifier of the thread the error occurred on"), \
TraceLoggingString((failure).pszCallContext, "callContext", "List of telemetry activities containing this error"), \
TraceLoggingUInt32( \
(failure).callContextOriginating.contextId, \
"originatingContextId", \
"Identifier for the oldest telemetry activity containing this error"), \
TraceLoggingString( \
(failure).callContextOriginating.contextName, \
"originatingContextName", \
"Name of the oldest telemetry activity containing this error"), \
TraceLoggingWideString( \
(failure).callContextOriginating.contextMessage, \
"originatingContextMessage", \
"Custom message associated with the oldest telemetry activity containing this error (if any)"), \
TraceLoggingUInt32( \
(failure).callContextCurrent.contextId, "currentContextId", "Identifier for the newest telemetry activity containing this error"), \
TraceLoggingString( \
(failure).callContextCurrent.contextName, "currentContextName", "Name of the newest telemetry activity containing this error"), \
TraceLoggingWideString( \
(failure).callContextCurrent.contextMessage, \
"currentContextMessage", \
"Custom message associated with the newest telemetry activity containing this error (if any)")
#define __RESULT_TRACELOGGING_COMMON_FAILURE_PARAMS(failure) \
__RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure), \
TraceLoggingUInt32(static_cast<DWORD>((failure).failureId), "failureId", "Identifier assigned to this failure"), \
TraceLoggingUInt32( \
static_cast<DWORD>((failure).cFailureCount), "failureCount", "Number of failures seen within the binary where the error occurred"), \
TraceLoggingString((failure).pszFunction, "function", "Name of the function where the error occurred")
// Activity Start Event (ALL)
#define __ACTIVITY_START_PARAMS() \
TraceLoggingStruct(1, "wilActivity"), \
TraceLoggingUInt32(::GetCurrentThreadId(), "threadId", "Identifier of the thread the activity was run on")
// Activity Stop Event (SUCCESSFUL or those WITHOUT full failure info -- just hr)
// Also utilized for intermediate stop events (a successful call to 'Stop()' from a Split activity
#define __ACTIVITY_STOP_PARAMS(hr) \
TraceLoggingStruct(2, "wilActivity"), TraceLoggingUInt32(hr, "hresult", "Failure error code"), \
TraceLoggingUInt32(::GetCurrentThreadId(), "threadId", "Identifier of the thread the activity was run on")
// Activity Stop Event (FAILED with full failure info)
#define __ACTIVITY_STOP_TELEMETRY_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(14, "wilActivity"), \
__RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure)
#define __ACTIVITY_STOP_TRACELOGGING_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(17, "wilActivity"), \
__RESULT_TRACELOGGING_COMMON_FAILURE_PARAMS(failure)
// "ActivityError" tagged event (all distinct FAILURES occurring within the outer activity scope)
#define __ACTIVITY_ERROR_TELEMETRY_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(14, "wilActivity"), \
__RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure)
#define __ACTIVITY_ERROR_TRACELOGGING_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(17, "wilActivity"), \
__RESULT_TRACELOGGING_COMMON_FAILURE_PARAMS(failure)
// "ActivityFailure" tagged event (only comes through on TELEMETRY for CallContext activities that have FAILED)
#define __ACTIVITY_FAILURE_TELEMETRY_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(14, "wilActivity"), \
__RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure)
#define __ACTIVITY_FAILURE_TELEMETRY_PARAMS(hr, contextName, contextMessage) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(4, "wilActivity"), \
TraceLoggingUInt32(hr, "hresult", "Failure error code"), \
TraceLoggingUInt32(::GetCurrentThreadId(), "threadId", "Identifier of the thread the activity was run on"), \
TraceLoggingString(contextName, "currentContextName", "Name of the activity containing this error"), \
TraceLoggingWideString(contextMessage, "currentContextMessage", "Custom message for the activity containing this error (if any)")
// "FallbackError" events (all FAILURE events happening outside of ANY activity context)
#define __RESULT_TELEMETRY_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(14, "wilResult"), \
__RESULT_TELEMETRY_COMMON_FAILURE_PARAMS(failure)
#define __RESULT_TRACELOGGING_FAILURE_PARAMS(failure) \
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance), TraceLoggingStruct(17, "wilResult"), \
__RESULT_TRACELOGGING_COMMON_FAILURE_PARAMS(failure)
/// @endcond
namespace wil
{
enum class ActivityOptions
{
None = 0,
TelemetryOnFailure = 0x1,
TraceLoggingOnFailure = 0x2
};
DEFINE_ENUM_FLAG_OPERATORS(ActivityOptions)
template <typename ActivityTraceLoggingType, ActivityOptions options, UINT64 keyword, UINT8 level, UINT64 privacyTag, typename TlgReflectorTag>
class ActivityBase;
/// @cond
namespace details
{
// Lazy static initialization helper for holding a singleton telemetry class to maintain
// the provider handle.
template <class T>
class static_lazy
{
public:
void __cdecl cleanup() WI_NOEXCEPT
{
void* pVoid;
BOOL pending;
// If object is being constructed on another thread, wait until construction completes.
// Need a memory barrier here (see get() and ~Completer below) so use the result that we
// get from InitOnceBeginInitialize(..., &pVoid, ...)
if (::InitOnceBeginInitialize(&m_initOnce, INIT_ONCE_CHECK_ONLY, &pending, &pVoid) && !pending)
{
static_cast<T*>(pVoid)->~T();
}
}
T* get(void(__cdecl* cleanupFunc)(void)) WI_NOEXCEPT
{
void* pVoid{};
BOOL pending;
if (::InitOnceBeginInitialize(&m_initOnce, 0, &pending, &pVoid) && pending)
{
// Don't do anything non-trivial from DllMain, fail fast.
// Some 3rd party code in IE calls shell functions this way, so we can only enforce
// this in DEBUG.
#ifdef DEBUG
FAIL_FAST_IMMEDIATE_IF_IN_LOADER_CALLOUT();
#endif
Completer completer(this);
pVoid = &m_storage;
::new (pVoid) T();
atexit(cleanupFunc); // ignore failure (that's what the C runtime does, too)
completer.Succeed();
}
return static_cast<T*>(pVoid);
}
private:
INIT_ONCE m_initOnce;
alignas(T) BYTE m_storage[sizeof(T)];
struct Completer
{
static_lazy* m_pSelf;
DWORD m_flags;
explicit Completer(static_lazy* pSelf) WI_NOEXCEPT : m_pSelf(pSelf), m_flags(INIT_ONCE_INIT_FAILED)
{
}
void Succeed() WI_NOEXCEPT
{
m_flags = 0;
}
~Completer() WI_NOEXCEPT
{
if (m_flags == 0)
{
reinterpret_cast<T*>(&m_pSelf->m_storage)->Create();
}
::InitOnceComplete(&m_pSelf->m_initOnce, m_flags, &m_pSelf->m_storage);
}
};
};
// This class serves as a simple RAII wrapper around CallContextInfo. It presumes that
// the contextName parameter is always a static string, but copies or allocates the
// contextMessage as needed.
class StoredCallContextInfo : public wil::CallContextInfo
{
public:
StoredCallContextInfo() WI_NOEXCEPT
{
::ZeroMemory(this, sizeof(*this));
}
StoredCallContextInfo(StoredCallContextInfo&& other) WI_NOEXCEPT : StoredCallContextInfo()
{
operator=(wistd::move(other));
}
StoredCallContextInfo& operator=(StoredCallContextInfo&& other) WI_NOEXCEPT
{
contextId = other.contextId;
contextName = other.contextName;
ClearMessage();
contextMessage = other.contextMessage;
other.contextMessage = nullptr;
m_ownsMessage = other.m_ownsMessage;
other.m_ownsMessage = false;
return *this;
}
StoredCallContextInfo(StoredCallContextInfo const& other) WI_NOEXCEPT : m_ownsMessage(false)
{
contextId = other.contextId;
contextName = other.contextName;
if (other.m_ownsMessage)
{
AssignMessage(other.contextMessage);
}
else
{
contextMessage = other.contextMessage;
}
}
StoredCallContextInfo(_In_opt_ PCSTR staticContextName) WI_NOEXCEPT : m_ownsMessage(false)
{
contextId = 0;
contextName = staticContextName;
contextMessage = nullptr;
}
StoredCallContextInfo(PCSTR staticContextName, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT
: StoredCallContextInfo(staticContextName)
{
SetMessage(formatString, argList);
}
void SetMessage(_Printf_format_string_ PCSTR formatString, va_list argList)
{
wchar_t loggingMessage[2048];
PrintLoggingMessage(loggingMessage, ARRAYSIZE(loggingMessage), formatString, argList);
ClearMessage();
AssignMessage(loggingMessage);
}
void SetMessage(_In_opt_ PCWSTR message)
{
ClearMessage();
contextMessage = message;
}
void SetMessageCopy(_In_opt_ PCWSTR message)
{
ClearMessage();
if (message != nullptr)
{
AssignMessage(message);
}
}
void ClearMessage()
{
if (m_ownsMessage)
{
WIL_FreeMemory(const_cast<PWSTR>(contextMessage));
m_ownsMessage = false;
}
contextMessage = nullptr;
}
~StoredCallContextInfo()
{
ClearMessage();
}
StoredCallContextInfo& operator=(StoredCallContextInfo const&) = delete;
private:
void AssignMessage(PCWSTR message)
{
auto length = wcslen(message);
if (length > 0)
{
auto sizeBytes = (length + 1) * sizeof(wchar_t);
contextMessage = static_cast<PCWSTR>(WIL_AllocateMemory(sizeBytes));
if (contextMessage != nullptr)
{
m_ownsMessage = true;
memcpy_s(const_cast<PWSTR>(contextMessage), sizeBytes, message, sizeBytes);
}
}
}
bool m_ownsMessage;
};
template <typename TActivity>
void SetRelatedActivityId(TActivity&)
{
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
template <typename ActivityTraceLoggingType, ActivityOptions options, UINT64 keyword, UINT8 level, UINT64 privacyTag, typename TlgReflectorTag>
void SetRelatedActivityId(wil::ActivityBase<ActivityTraceLoggingType, options, keyword, level, privacyTag, TlgReflectorTag>& activity)
{
GUID capturedRelatedId;
EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, &capturedRelatedId);
activity.SetRelatedActivityId(capturedRelatedId);
}
#endif
typedef wistd::integral_constant<char, 0> tag_start;
typedef wistd::integral_constant<char, 1> tag_start_cv;
} // namespace details
/// @endcond
// This class acts as a simple RAII class returned by a call to ContinueOnCurrentThread() for an activity
// or by a call to WatchCurrentThread() on a provider. The result is meant to be a stack local variable
// whose scope controls the lifetime of an error watcher on the given thread. That error watcher re-directs
// errors occurrent within the object's lifetime to the associated provider or activity.
class ActivityThreadWatcher
{
public:
ActivityThreadWatcher() WI_NOEXCEPT : m_callbackHolder(nullptr, nullptr, false)
{
}
ActivityThreadWatcher(_In_ details::IFailureCallback* pCallback, PCSTR staticContextName) WI_NOEXCEPT
: m_callContext(staticContextName),
m_callbackHolder(pCallback, &m_callContext)
{
}
ActivityThreadWatcher(
_In_ details::IFailureCallback* pCallback, PCSTR staticContextName, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT
: ActivityThreadWatcher(pCallback, staticContextName)
{
m_callContext.SetMessage(formatString, argList);
}
// Uses the supplied StoredCallContextInfo rather than producing one itself
ActivityThreadWatcher(_In_ details::IFailureCallback* pCallback, _In_ details::StoredCallContextInfo const& callContext) WI_NOEXCEPT
: m_callContext(callContext),
m_callbackHolder(pCallback, &m_callContext)
{
}
ActivityThreadWatcher(ActivityThreadWatcher&& other) WI_NOEXCEPT : m_callContext(wistd::move(other.m_callContext)),
m_callbackHolder(wistd::move(other.m_callbackHolder))
{
m_callbackHolder.SetCallContext(&m_callContext);
}
ActivityThreadWatcher(ActivityThreadWatcher const&) = delete;
ActivityThreadWatcher& operator=(ActivityThreadWatcher const&) = delete;
void SetMessage(_Printf_format_string_ PCSTR formatString, ...)
{
va_list argList;
va_start(argList, formatString);
m_callContext.SetMessage(formatString, argList);
va_end(argList);
}
void SetMessage(_In_opt_ PCWSTR message)
{
m_callContext.SetMessage(message);
}
void SetMessageCopy(_In_opt_ PCWSTR message)
{
m_callContext.SetMessageCopy(message);
}
private:
details::StoredCallContextInfo m_callContext;
details::ThreadFailureCallbackHolder m_callbackHolder;
};
// This is the base-class implementation of a TraceLogging class. TraceLogging classes are defined with
// BEGIN_TRACELOGGING_CLASS and automatically derive from this class
enum class ErrorReportingType
{
None = 0,
Telemetry,
TraceLogging
};
class TraceLoggingProvider : public details::IFailureCallback
{
public:
// Only one instance of each of these derived classes should be created
TraceLoggingProvider(_In_ TraceLoggingProvider const&) = delete;
TraceLoggingProvider& operator=(TraceLoggingProvider const&) = delete;
void* operator new(size_t) = delete;
void* operator new[](size_t) = delete;
protected:
// This can be overridden to provide specific initialization code for any individual provider.
// It will be ran once when the single static singleton instance of this class is created.
virtual void Initialize() WI_NOEXCEPT
{
}
// This method can be overridden by a provider to more tightly control what happens in the event
// of a failure in a CallContext activity, WatchCurrentThread() object, or attributed to a specific failure.
virtual void OnErrorReported(bool alreadyReported, FailureInfo const& failure) WI_NOEXCEPT
{
if (!alreadyReported && WI_IsFlagClear(failure.flags, FailureFlags::RequestSuppressTelemetry))
{
if (m_errorReportingType == ErrorReportingType::Telemetry)
{
ReportTelemetryFailure(failure);
}
else if (m_errorReportingType == ErrorReportingType::TraceLogging)
{
ReportTraceLoggingFailure(failure);
}
}
}
public:
WI_NODISCARD TraceLoggingHProvider Provider_() const WI_NOEXCEPT
{
return m_providerHandle;
}
protected:
TraceLoggingProvider() WI_NOEXCEPT
{
}
virtual ~TraceLoggingProvider() WI_NOEXCEPT
{
if (m_ownsProviderHandle)
{
TraceLoggingUnregister(m_providerHandle);
}
}
WI_NODISCARD bool IsEnabled_(
UCHAR eventLevel /* WINEVENT_LEVEL_XXX, e.g. WINEVENT_LEVEL_VERBOSE */,
ULONGLONG eventKeywords /* MICROSOFT_KEYWORD_XXX */) const WI_NOEXCEPT
{
return ((m_providerHandle != nullptr) && TraceLoggingProviderEnabled(m_providerHandle, eventLevel, eventKeywords)) ||
__TRACELOGGING_TEST_HOOK_SET_ENABLED;
}
void SetErrorReportingType_(ErrorReportingType type)
{
m_errorReportingType = type;
}
static bool WasAlreadyReportedToTelemetry(long failureId) WI_NOEXCEPT
{
static long volatile s_lastFailureSeen = -1;
auto wasSeen = (s_lastFailureSeen == failureId);
s_lastFailureSeen = failureId;
return wasSeen;
}
void ReportTelemetryFailure(FailureInfo const& failure) WI_NOEXCEPT
{
__TRACELOGGING_TEST_HOOK_ERROR(failure);
TraceLoggingWrite(
m_providerHandle,
"FallbackError",
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance),
TraceLoggingKeyword(MICROSOFT_KEYWORD_TELEMETRY),
TraceLoggingLevel(WINEVENT_LEVEL_ERROR),
__RESULT_TELEMETRY_FAILURE_PARAMS(failure));
}
void ReportTraceLoggingFailure(FailureInfo const& failure) WI_NOEXCEPT
{
TraceLoggingWrite(
m_providerHandle, "FallbackError", TraceLoggingLevel(WINEVENT_LEVEL_ERROR), __RESULT_TRACELOGGING_FAILURE_PARAMS(failure));
}
// Helper function for TraceLoggingError.
// It prints out a trace message for debug purposes. The message does not go into the telemetry.
void ReportTraceLoggingError(_In_ _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT
{
if (IsEnabled_(WINEVENT_LEVEL_ERROR, 0))
{
wchar_t loggingMessage[2048];
details::PrintLoggingMessage(loggingMessage, ARRAYSIZE(loggingMessage), formatString, argList);
TraceLoggingWrite(
m_providerHandle,
"TraceLoggingError",
TraceLoggingLevel(WINEVENT_LEVEL_ERROR),
TraceLoggingWideString(loggingMessage, "traceLoggingMessage"));
}
}
// Helper function for TraceLoggingInfo.
// It prints out a trace message for debug purposes. The message does not go into the telemetry.
void ReportTraceLoggingMessage(_In_ _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT
{
if (IsEnabled_(WINEVENT_LEVEL_VERBOSE, 0))
{
wchar_t loggingMessage[2048];
details::PrintLoggingMessage(loggingMessage, ARRAYSIZE(loggingMessage), formatString, argList);
TraceLoggingWrite(
m_providerHandle,
"TraceLoggingInfo",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingWideString(loggingMessage, "traceLoggingMessage"));
}
}
void Register(TraceLoggingHProvider const providerHandle, TLG_PENABLECALLBACK callback = nullptr) WI_NOEXCEPT
{
// taking over the lifetime and management of providerHandle
m_providerHandle = providerHandle;
m_ownsProviderHandle = true;
TraceLoggingRegisterEx(providerHandle, callback, nullptr);
InternalInitialize();
}
void AttachProvider(TraceLoggingHProvider const providerHandle) WI_NOEXCEPT
{
m_providerHandle = providerHandle;
m_ownsProviderHandle = false;
InternalInitialize();
}
private:
// IFailureCallback
bool NotifyFailure(FailureInfo const& failure) WI_NOEXCEPT override
{
if (!WasAlreadyReportedToTelemetry(failure.failureId))
{
OnErrorReported(false, failure);
}
return true;
}
void InternalInitialize()
{
m_errorReportingType = ErrorReportingType::Telemetry;
Initialize();
}
TraceLoggingHProvider m_providerHandle{};
bool m_ownsProviderHandle{};
ErrorReportingType m_errorReportingType{};
};
template <
typename TraceLoggingType,
UINT64 keyword = 0,
UINT8 level = WINEVENT_LEVEL_VERBOSE,
typename TlgReflectorTag = _TlgReflectorTag_Param0IsProviderType> // helps TlgReflector understand that this is a wrapper type
class BasicActivity : public _TlgActivityBase<BasicActivity<TraceLoggingType, keyword, level, TlgReflectorTag>, keyword, level>
{
using BaseTy = _TlgActivityBase<BasicActivity<TraceLoggingType, keyword, level, TlgReflectorTag>, keyword, level>;
friend BaseTy;
void OnStarted()
{
}
void OnStopped()
{
}
public:
BasicActivity()
{
}
BasicActivity(BasicActivity&& rhs) : BaseTy(wistd::move(rhs))
{
}
BasicActivity& operator=(BasicActivity&& rhs)
{
BaseTy::operator=(wistd::move(rhs));
return *this;
}
/*
Returns a handle to the TraceLogging provider associated with this activity.
*/
WI_NODISCARD TraceLoggingHProvider Provider() const
{
return TraceLoggingType::Provider();
}
/*
Sets the related (parent) activity.
May only be called once. If used, must be called before starting the activity.
*/
template <typename ActivityTy>
void SetRelatedActivity(_In_ const ActivityTy& relatedActivity)
{
this->SetRelatedId(*relatedActivity.Id());
}
/*
Sets the related (parent) activity.
May only be called once. If used, must be called before starting the activity.
*/
void SetRelatedActivityId(_In_ const GUID& relatedActivityId)
{
this->SetRelatedId(relatedActivityId);
}
/*
Sets the related (parent) activity.
May only be called once. If used, must be called before starting the activity.
*/
void SetRelatedActivityId(_In_ const GUID* relatedActivityId)
{
__FAIL_FAST_IMMEDIATE_ASSERT__(relatedActivityId != NULL);
this->SetRelatedId(*relatedActivityId);
}
};
template <
typename TraceLoggingType,
UINT64 keyword = 0,
UINT8 level = WINEVENT_LEVEL_VERBOSE,
typename TlgReflectorTag = _TlgReflectorTag_Param0IsProviderType> // helps TlgReflector understand that this is a wrapper type
class BasicThreadActivity
: public _TlgActivityBase<BasicThreadActivity<TraceLoggingType, keyword, level, TlgReflectorTag>, keyword, level>
{
using BaseTy = _TlgActivityBase<BasicThreadActivity<TraceLoggingType, keyword, level, TlgReflectorTag>, keyword, level>;
friend BaseTy;
void OnStarted()
{
this->PushThreadActivityId();
}
void OnStopped()
{
this->PopThreadActivityId();
}
public:
BasicThreadActivity()
{
}
BasicThreadActivity(BasicThreadActivity&& rhs) : BaseTy(wistd::move(rhs))
{
}
BasicThreadActivity& operator=(BasicThreadActivity&& rhs)
{
BaseTy::operator=(wistd::move(rhs));
return *this;
}
/*
Returns a handle to the TraceLogging provider associated with this activity.
*/
WI_NODISCARD TraceLoggingHProvider Provider() const
{
return TraceLoggingType::Provider();
}
};
/// @cond
#define __WI_TraceLoggingWriteTagged(activity, name, ...) \
__pragma(warning(push)) __pragma(warning(disable : 4127)) do \
{ \
_tlgActivityDecl(activity) \
TraceLoggingWriteActivity(TraceLoggingType::Provider(), (name), _tlgActivityRef(activity).Id(), NULL, __VA_ARGS__); \
} \
while (0) \
__pragma(warning(pop)) /// @endcond
// This is the ultimate base class implementation for all activities. Activity classes are defined with
// DEFINE_TRACELOGGING_ACTIVITY, DEFINE_CALLCONTEXT_ACTIVITY, DEFINE_TELEMETRY_ACTIVITY and others
template <typename ActivityTraceLoggingType, ActivityOptions options = ActivityOptions::None, UINT64 keyword = 0, UINT8 level = WINEVENT_LEVEL_VERBOSE, UINT64 privacyTag = 0, typename TlgReflectorTag = _TlgReflectorTag_Param0IsProviderType>
class ActivityBase : public details::IFailureCallback
{
public:
typedef ActivityTraceLoggingType TraceLoggingType;
static UINT64 const Keyword = keyword;
static UINT8 const Level = level;
static UINT64 const PrivacyTag = privacyTag;
ActivityBase(PCSTR contextName, bool shouldWatchErrors = false) WI_NOEXCEPT
: m_activityData(contextName),
m_pActivityData(&m_activityData),
m_callbackHolder(this, m_activityData.GetCallContext(), shouldWatchErrors)
{
}
ActivityBase(ActivityBase&& other, bool shouldWatchErrors) WI_NOEXCEPT
: m_activityData(wistd::move(other.m_activityData)),
m_sharedActivityData(wistd::move(other.m_sharedActivityData)),
m_callbackHolder(this, nullptr, shouldWatchErrors)
{
m_pActivityData = m_sharedActivityData ? m_sharedActivityData.get() : &m_activityData;
m_callbackHolder.SetCallContext(m_pActivityData->GetCallContext());
other.m_pActivityData = &other.m_activityData;
if (other.m_callbackHolder.IsWatching())
{
other.m_callbackHolder.StopWatching();
}
}
ActivityBase(ActivityBase&& other) WI_NOEXCEPT : ActivityBase(wistd::move(other), other.m_callbackHolder.IsWatching())
{
}
ActivityBase(ActivityBase const& other) WI_NOEXCEPT
: m_activityData(),
m_pActivityData(&m_activityData),
m_callbackHolder(this, nullptr, false) // false = do not automatically watch for failures
{
operator=(other);
}
ActivityBase& operator=(ActivityBase&& other) WI_NOEXCEPT
{
m_activityData = wistd::move(other.m_activityData);
m_sharedActivityData = wistd::move(other.m_sharedActivityData);
m_pActivityData = m_sharedActivityData ? m_sharedActivityData.get() : &m_activityData;
m_callbackHolder.SetCallContext(m_pActivityData->GetCallContext());
m_callbackHolder.SetWatching(other.m_callbackHolder.IsWatching());
other.m_pActivityData = &other.m_activityData;
if (other.m_callbackHolder.IsWatching())
{
other.m_callbackHolder.StopWatching();
}
return *this;
}
ActivityBase& operator=(ActivityBase const& other) WI_NOEXCEPT
{
if (m_callbackHolder.IsWatching())
{
m_callbackHolder.StopWatching();
}
if (other.m_sharedActivityData)
{
m_pActivityData = other.m_pActivityData;
m_sharedActivityData = other.m_sharedActivityData;
}
else if (m_sharedActivityData.create(wistd::move(other.m_activityData)))
{
// Locking should not be required as the first copy should always take place on the owning
// thread...
m_pActivityData = m_sharedActivityData.get();
other.m_sharedActivityData = m_sharedActivityData;
other.m_pActivityData = m_pActivityData;
other.m_callbackHolder.SetCallContext(m_pActivityData->GetCallContext());
}
m_callbackHolder.SetCallContext(m_pActivityData->GetCallContext());
return *this;
}
// These calls all result in setting a message to associate with any failures that might occur while
// running the activity. For example, you could associate a filename with a call context activity
// so that the file name is only reported if the activity fails with the failure.
void SetMessage(_In_ _Printf_format_string_ PCSTR formatString, ...)
{
va_list argList;
va_start(argList, formatString);
auto lock = LockExclusive();
GetCallContext()->SetMessage(formatString, argList);
va_end(argList);
}
void SetMessage(_In_opt_ PCWSTR message)
{
auto lock = LockExclusive();
GetCallContext()->SetMessage(message);
}
void SetMessageCopy(_In_opt_ PCWSTR message)
{
auto lock = LockExclusive();
GetCallContext()->SetMessageCopy(message);
}
// This call stops watching for errors on the thread that the activity was originally
// created on. Use it when moving the activity into a thread-agnostic class or moving
// an activity across threads.
void IgnoreCurrentThread() WI_NOEXCEPT
{
if (m_callbackHolder.IsWatching())
{
m_callbackHolder.StopWatching();
}
}
// Call this API to retrieve an RAII object to watch events on the current thread. The returned
// object should only be used on the stack.
WI_NODISCARD ActivityThreadWatcher ContinueOnCurrentThread() WI_NOEXCEPT
{
if (IsRunning())
{
return ActivityThreadWatcher(this, *m_pActivityData->GetCallContext());
}
return ActivityThreadWatcher();
}
// This is the 'default' Stop routine that accepts an HRESULT and completes the activity...
void Stop(HRESULT hr = S_OK) WI_NOEXCEPT
{
bool stopActivity;
HRESULT hrLocal;
{
auto lock = LockExclusive();
stopActivity = m_pActivityData->SetStopResult(hr, &hrLocal);
}
if (stopActivity)
{
ReportStopActivity(hrLocal);
}
else
{
__WI_TraceLoggingWriteTagged(
*this,
"ActivityIntermediateStop",
TraceLoggingKeyword(Keyword),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance),
__ACTIVITY_STOP_PARAMS(hr));
}
IgnoreCurrentThread();
}
// IFailureCallback
bool NotifyFailure(FailureInfo const& failure) WI_NOEXCEPT override
{
// We always report errors to the ETW stream, but we hold-back the telemetry keyword if we've already reported this error
// to this particular telemetry provider.
__TRACELOGGING_TEST_HOOK_ACTIVITY_ERROR(failure);
if (WI_IsFlagClear(failure.flags, FailureFlags::RequestSuppressTelemetry))
{
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
#endif
#pragma warning(push)
#pragma warning(disable : 6319)
if (false, WI_IsFlagSet(options, ActivityOptions::TelemetryOnFailure) && !WasAlreadyReportedToTelemetry(failure.failureId))
{
__WI_TraceLoggingWriteTagged(
*this,
"ActivityError",
TraceLoggingKeyword(Keyword | MICROSOFT_KEYWORD_TELEMETRY),
TraceLoggingLevel(WINEVENT_LEVEL_ERROR),
__ACTIVITY_ERROR_TELEMETRY_FAILURE_PARAMS(failure));
}
else if (false, WI_IsFlagSet(options, ActivityOptions::TraceLoggingOnFailure))
{
__WI_TraceLoggingWriteTagged(
*this,
"ActivityError",
TraceLoggingKeyword(0),
TraceLoggingLevel(WINEVENT_LEVEL_ERROR),
__ACTIVITY_ERROR_TRACELOGGING_FAILURE_PARAMS(failure));
}
else
{
__WI_TraceLoggingWriteTagged(
*this,
"ActivityError",
TraceLoggingKeyword(Keyword),
TraceLoggingLevel(WINEVENT_LEVEL_ERROR),
__ACTIVITY_ERROR_TRACELOGGING_FAILURE_PARAMS(failure));
}
#pragma warning(pop)
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
auto lock = LockExclusive();
m_pActivityData->NotifyFailure(failure);
return true;
}
// This is the base TraceLoggingActivity<> contract... we implement it so that this class
// can be used by all of the activity macros and we re-route the request as needed.
//
// The contract required by the TraceLogging Activity macros is:
// - activity.Keyword // compile-time constant
// - activity.Level // compile-time constant
// - activity.PrivacyTag // compile-time constant
// - activity.Provider()
// - activity.Id()
// - activity.zInternalRelatedId()
// - activity.zInternalStart()
// - activity.zInternalStop()
// In addition, for TlgReflector to work correctly, it must be possible for
// TlgReflector to statically map from typeof(activity) to hProvider.
WI_NODISCARD GUID const* zInternalRelatedId() const WI_NOEXCEPT
{
return m_pActivityData->zInternalRelatedId();
}
void zInternalStart() WI_NOEXCEPT
{
auto lock = LockExclusive();
m_pActivityData->zInternalStart();
}
void zInternalStop() WI_NOEXCEPT
{
auto lock = LockExclusive();
m_pActivityData->zInternalStop();
}
static TraceLoggingHProvider Provider() WI_NOEXCEPT
{