-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
optick_core.win.h
1737 lines (1502 loc) · 56.7 KB
/
optick_core.win.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
// The MIT License(MIT)
//
// Copyright(c) 2019 Vadim Slyusarev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// 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.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#if defined(_MSC_VER)
#include "optick.config.h"
#if USE_OPTICK
#include "optick_core.platform.h"
namespace Optick
{
const char* Platform::GetName()
{
#if OPTICK_PC
return "Windows";
#else
return "XBox";
#endif
}
ThreadID Platform::GetThreadID()
{
return GetCurrentThreadId();
}
ProcessID Platform::GetProcessID()
{
return GetCurrentProcessId();
}
int64 Platform::GetFrequency()
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}
int64 Platform::GetTime()
{
LARGE_INTEGER largeInteger;
QueryPerformanceCounter(&largeInteger);
return largeInteger.QuadPart;
}
}
#if OPTICK_ENABLE_TRACING
#include <psapi.h>
#include "optick_core.h"
/*
Event Tracing Functions - API
https://msdn.microsoft.com/en-us/library/windows/desktop/aa363795(v=vs.85).aspx
*/
#define DECLARE_ETW (!OPTICK_PC)
#if DECLARE_ETW
// Copied from Windows SDK
#ifndef WMIAPI
#ifndef MIDL_PASS
#ifdef _WMI_SOURCE_
#define WMIAPI __stdcall
#else
#define WMIAPI DECLSPEC_IMPORT __stdcall
#endif // _WMI_SOURCE
#endif // MIDL_PASS
#endif // WMIAPI
#define INITGUID
#include <guiddef.h>
#if defined(_NTDDK_) || defined(_NTIFS_) || defined(_WMIKM_)
#define _EVNTRACE_KERNEL_MODE
#endif
#if !defined(_EVNTRACE_KERNEL_MODE)
#include <wmistr.h>
#endif
#if _MSC_VER <= 1600
#define EVENT_DESCRIPTOR_DEF
#define EVENT_HEADER_DEF
#define EVENT_HEADER_EXTENDED_DATA_ITEM_DEF
#define EVENT_RECORD_DEF
#endif
#ifndef _TRACEHANDLE_DEFINED
#define _TRACEHANDLE_DEFINED
typedef ULONG64 TRACEHANDLE, *PTRACEHANDLE;
#endif
//
// EventTraceGuid is used to identify a event tracing session
//
DEFINE_GUID( /* 68fdd900-4a3e-11d1-84f4-0000f80464e3 */
EventTraceGuid,
0x68fdd900,
0x4a3e,
0x11d1,
0x84, 0xf4, 0x00, 0x00, 0xf8, 0x04, 0x64, 0xe3
);
//
// SystemTraceControlGuid. Used to specify event tracing for kernel
//
DEFINE_GUID( /* 9e814aad-3204-11d2-9a82-006008a86939 */
SystemTraceControlGuid,
0x9e814aad,
0x3204,
0x11d2,
0x9a, 0x82, 0x00, 0x60, 0x08, 0xa8, 0x69, 0x39
);
//
// EventTraceConfigGuid. Used to report system configuration records
//
DEFINE_GUID( /* 01853a65-418f-4f36-aefc-dc0f1d2fd235 */
EventTraceConfigGuid,
0x01853a65,
0x418f,
0x4f36,
0xae, 0xfc, 0xdc, 0x0f, 0x1d, 0x2f, 0xd2, 0x35
);
//
// DefaultTraceSecurityGuid. Specifies the default event tracing security
//
DEFINE_GUID( /* 0811c1af-7a07-4a06-82ed-869455cdf713 */
DefaultTraceSecurityGuid,
0x0811c1af,
0x7a07,
0x4a06,
0x82, 0xed, 0x86, 0x94, 0x55, 0xcd, 0xf7, 0x13
);
///////////////////////////////////////////////////////////////////////////////
#define PROCESS_TRACE_MODE_REAL_TIME 0x00000100
#define PROCESS_TRACE_MODE_RAW_TIMESTAMP 0x00001000
#define PROCESS_TRACE_MODE_EVENT_RECORD 0x10000000
///////////////////////////////////////////////////////////////////////////////
#define EVENT_HEADER_FLAG_EXTENDED_INFO 0x0001
#define EVENT_HEADER_FLAG_PRIVATE_SESSION 0x0002
#define EVENT_HEADER_FLAG_STRING_ONLY 0x0004
#define EVENT_HEADER_FLAG_TRACE_MESSAGE 0x0008
#define EVENT_HEADER_FLAG_NO_CPUTIME 0x0010
#define EVENT_HEADER_FLAG_32_BIT_HEADER 0x0020
#define EVENT_HEADER_FLAG_64_BIT_HEADER 0x0040
#define EVENT_HEADER_FLAG_CLASSIC_HEADER 0x0100
#define EVENT_HEADER_FLAG_PROCESSOR_INDEX 0x0200
///////////////////////////////////////////////////////////////////////////////
#define KERNEL_LOGGER_NAMEW L"NT Kernel Logger"
///////////////////////////////////////////////////////////////////////////////
#define EVENT_TRACE_REAL_TIME_MODE 0x00000100 // Real time mode on
///////////////////////////////////////////////////////////////////////////////
#define EVENT_TRACE_CONTROL_STOP 1
///////////////////////////////////////////////////////////////////////////////
//
// Enable flags for Kernel Events
//
#define EVENT_TRACE_FLAG_PROCESS 0x00000001 // process start & end
#define EVENT_TRACE_FLAG_THREAD 0x00000002 // thread start & end
#define EVENT_TRACE_FLAG_IMAGE_LOAD 0x00000004 // image load
#define EVENT_TRACE_FLAG_DISK_IO 0x00000100 // physical disk IO
#define EVENT_TRACE_FLAG_DISK_FILE_IO 0x00000200 // requires disk IO
#define EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS 0x00001000 // all page faults
#define EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS 0x00002000 // hard faults only
#define EVENT_TRACE_FLAG_NETWORK_TCPIP 0x00010000 // tcpip send & receive
#define EVENT_TRACE_FLAG_REGISTRY 0x00020000 // registry calls
#define EVENT_TRACE_FLAG_DBGPRINT 0x00040000 // DbgPrint(ex) Calls
//
// Enable flags for Kernel Events on Vista and above
//
#define EVENT_TRACE_FLAG_PROCESS_COUNTERS 0x00000008 // process perf counters
#define EVENT_TRACE_FLAG_CSWITCH 0x00000010 // context switches
#define EVENT_TRACE_FLAG_DPC 0x00000020 // deffered procedure calls
#define EVENT_TRACE_FLAG_INTERRUPT 0x00000040 // interrupts
#define EVENT_TRACE_FLAG_SYSTEMCALL 0x00000080 // system calls
#define EVENT_TRACE_FLAG_DISK_IO_INIT 0x00000400 // physical disk IO initiation
#define EVENT_TRACE_FLAG_ALPC 0x00100000 // ALPC traces
#define EVENT_TRACE_FLAG_SPLIT_IO 0x00200000 // split io traces (VolumeManager)
#define EVENT_TRACE_FLAG_DRIVER 0x00800000 // driver delays
#define EVENT_TRACE_FLAG_PROFILE 0x01000000 // sample based profiling
#define EVENT_TRACE_FLAG_FILE_IO 0x02000000 // file IO
#define EVENT_TRACE_FLAG_FILE_IO_INIT 0x04000000 // file IO initiation
#define EVENT_TRACE_FLAG_PMC_PROFILE 0x80000000 // sample based profiling (PMC) - NOT CONFIRMED!
//
// Enable flags for Kernel Events on Win7 and above
//
#define EVENT_TRACE_FLAG_DISPATCHER 0x00000800 // scheduler (ReadyThread)
#define EVENT_TRACE_FLAG_VIRTUAL_ALLOC 0x00004000 // VM operations
//
// Enable flags for Kernel Events on Win8 and above
//
#define EVENT_TRACE_FLAG_VAMAP 0x00008000 // map/unmap (excluding images)
#define EVENT_TRACE_FLAG_NO_SYSCONFIG 0x10000000 // Do not do sys config rundown
///////////////////////////////////////////////////////////////////////////////
#pragma warning(push)
#pragma warning (disable:4201)
#ifndef EVENT_DESCRIPTOR_DEF
#define EVENT_DESCRIPTOR_DEF
typedef struct _EVENT_DESCRIPTOR {
USHORT Id;
UCHAR Version;
UCHAR Channel;
UCHAR Level;
UCHAR Opcode;
USHORT Task;
ULONGLONG Keyword;
} EVENT_DESCRIPTOR, *PEVENT_DESCRIPTOR;
typedef const EVENT_DESCRIPTOR *PCEVENT_DESCRIPTOR;
#endif
///////////////////////////////////////////////////////////////////////////////
#ifndef EVENT_HEADER_DEF
#define EVENT_HEADER_DEF
typedef struct _EVENT_HEADER {
USHORT Size;
USHORT HeaderType;
USHORT Flags;
USHORT EventProperty;
ULONG ThreadId;
ULONG ProcessId;
LARGE_INTEGER TimeStamp;
GUID ProviderId;
EVENT_DESCRIPTOR EventDescriptor;
union {
struct {
ULONG KernelTime;
ULONG UserTime;
} DUMMYSTRUCTNAME;
ULONG64 ProcessorTime;
} DUMMYUNIONNAME;
GUID ActivityId;
} EVENT_HEADER, *PEVENT_HEADER;
#endif
///////////////////////////////////////////////////////////////////////////////
#ifndef EVENT_HEADER_EXTENDED_DATA_ITEM_DEF
#define EVENT_HEADER_EXTENDED_DATA_ITEM_DEF
typedef struct _EVENT_HEADER_EXTENDED_DATA_ITEM {
USHORT Reserved1; // Reserved for internal use
USHORT ExtType; // Extended info type
struct {
USHORT Linkage : 1; // Indicates additional extended
// data item
USHORT Reserved2 : 15;
};
USHORT DataSize; // Size of extended info data
ULONGLONG DataPtr; // Pointer to extended info data
} EVENT_HEADER_EXTENDED_DATA_ITEM, *PEVENT_HEADER_EXTENDED_DATA_ITEM;
#endif
///////////////////////////////////////////////////////////////////////////////
#ifndef ETW_BUFFER_CONTEXT_DEF
#define ETW_BUFFER_CONTEXT_DEF
typedef struct _ETW_BUFFER_CONTEXT {
union {
struct {
UCHAR ProcessorNumber;
UCHAR Alignment;
} DUMMYSTRUCTNAME;
USHORT ProcessorIndex;
} DUMMYUNIONNAME;
USHORT LoggerId;
} ETW_BUFFER_CONTEXT, *PETW_BUFFER_CONTEXT;
#endif
///////////////////////////////////////////////////////////////////////////////
#ifndef EVENT_RECORD_DEF
#define EVENT_RECORD_DEF
typedef struct _EVENT_RECORD {
EVENT_HEADER EventHeader;
ETW_BUFFER_CONTEXT BufferContext;
USHORT ExtendedDataCount;
USHORT UserDataLength;
PEVENT_HEADER_EXTENDED_DATA_ITEM ExtendedData;
PVOID UserData;
PVOID UserContext;
} EVENT_RECORD, *PEVENT_RECORD;
#endif
///////////////////////////////////////////////////////////////////////////////
typedef struct _EVENT_TRACE_PROPERTIES {
WNODE_HEADER Wnode;
//
// data provided by caller
ULONG BufferSize; // buffer size for logging (kbytes)
ULONG MinimumBuffers; // minimum to preallocate
ULONG MaximumBuffers; // maximum buffers allowed
ULONG MaximumFileSize; // maximum logfile size (in MBytes)
ULONG LogFileMode; // sequential, circular
ULONG FlushTimer; // buffer flush timer, in seconds
ULONG EnableFlags; // trace enable flags
union {
LONG AgeLimit; // unused
LONG FlushThreshold; // Number of buffers to fill before flushing
} DUMMYUNIONNAME;
// data returned to caller
ULONG NumberOfBuffers; // no of buffers in use
ULONG FreeBuffers; // no of buffers free
ULONG EventsLost; // event records lost
ULONG BuffersWritten; // no of buffers written to file
ULONG LogBuffersLost; // no of logfile write failures
ULONG RealTimeBuffersLost; // no of rt delivery failures
HANDLE LoggerThreadId; // thread id of Logger
ULONG LogFileNameOffset; // Offset to LogFileName
ULONG LoggerNameOffset; // Offset to LoggerName
} EVENT_TRACE_PROPERTIES, *PEVENT_TRACE_PROPERTIES;
typedef struct _EVENT_TRACE_HEADER { // overlays WNODE_HEADER
USHORT Size; // Size of entire record
union {
USHORT FieldTypeFlags; // Indicates valid fields
struct {
UCHAR HeaderType; // Header type - internal use only
UCHAR MarkerFlags; // Marker - internal use only
} DUMMYSTRUCTNAME;
} DUMMYUNIONNAME;
union {
ULONG Version;
struct {
UCHAR Type; // event type
UCHAR Level; // trace instrumentation level
USHORT Version; // version of trace record
} Class;
} DUMMYUNIONNAME2;
ULONG ThreadId; // Thread Id
ULONG ProcessId; // Process Id
LARGE_INTEGER TimeStamp; // time when event happens
union {
GUID Guid; // Guid that identifies event
ULONGLONG GuidPtr; // use with WNODE_FLAG_USE_GUID_PTR
} DUMMYUNIONNAME3;
union {
struct {
ULONG KernelTime; // Kernel Mode CPU ticks
ULONG UserTime; // User mode CPU ticks
} DUMMYSTRUCTNAME;
ULONG64 ProcessorTime; // Processor Clock
struct {
ULONG ClientContext; // Reserved
ULONG Flags; // Event Flags
} DUMMYSTRUCTNAME2;
} DUMMYUNIONNAME4;
} EVENT_TRACE_HEADER, *PEVENT_TRACE_HEADER;
typedef struct _EVENT_TRACE {
EVENT_TRACE_HEADER Header; // Event trace header
ULONG InstanceId; // Instance Id of this event
ULONG ParentInstanceId; // Parent Instance Id.
GUID ParentGuid; // Parent Guid;
PVOID MofData; // Pointer to Variable Data
ULONG MofLength; // Variable Datablock Length
union {
ULONG ClientContext;
ETW_BUFFER_CONTEXT BufferContext;
} DUMMYUNIONNAME;
} EVENT_TRACE, *PEVENT_TRACE;
typedef struct _TRACE_LOGFILE_HEADER {
ULONG BufferSize; // Logger buffer size in Kbytes
union {
ULONG Version; // Logger version
struct {
UCHAR MajorVersion;
UCHAR MinorVersion;
UCHAR SubVersion;
UCHAR SubMinorVersion;
} VersionDetail;
} DUMMYUNIONNAME;
ULONG ProviderVersion; // defaults to NT version
ULONG NumberOfProcessors; // Number of Processors
LARGE_INTEGER EndTime; // Time when logger stops
ULONG TimerResolution; // assumes timer is constant!!!
ULONG MaximumFileSize; // Maximum in Mbytes
ULONG LogFileMode; // specify logfile mode
ULONG BuffersWritten; // used to file start of Circular File
union {
GUID LogInstanceGuid; // For RealTime Buffer Delivery
struct {
ULONG StartBuffers; // Count of buffers written at start.
ULONG PointerSize; // Size of pointer type in bits
ULONG EventsLost; // Events losts during log session
ULONG CpuSpeedInMHz; // Cpu Speed in MHz
} DUMMYSTRUCTNAME;
} DUMMYUNIONNAME2;
#if defined(_WMIKM_)
PWCHAR LoggerName;
PWCHAR LogFileName;
RTL_TIME_ZONE_INFORMATION TimeZone;
#else
LPWSTR LoggerName;
LPWSTR LogFileName;
TIME_ZONE_INFORMATION TimeZone;
#endif
LARGE_INTEGER BootTime;
LARGE_INTEGER PerfFreq; // Reserved
LARGE_INTEGER StartTime; // Reserved
ULONG ReservedFlags; // ClockType
ULONG BuffersLost;
} TRACE_LOGFILE_HEADER, *PTRACE_LOGFILE_HEADER;
typedef enum _TRACE_QUERY_INFO_CLASS {
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo, // Win7
TraceSystemTraceEnableFlagsInfo,
TraceSampledProfileIntervalInfo,
TraceProfileSourceConfigInfo,
TraceProfileSourceListInfo,
TracePmcEventListInfo,
TracePmcCounterListInfo,
MaxTraceSetInfoClass
} TRACE_QUERY_INFO_CLASS, TRACE_INFO_CLASS;
typedef struct _CLASSIC_EVENT_ID {
GUID EventGuid;
UCHAR Type;
UCHAR Reserved[7];
} CLASSIC_EVENT_ID, *PCLASSIC_EVENT_ID;
typedef struct _TRACE_PROFILE_INTERVAL {
ULONG Source;
ULONG Interval;
} TRACE_PROFILE_INTERVAL, *PTRACE_PROFILE_INTERVAL;
typedef struct _EVENT_TRACE_LOGFILEW
EVENT_TRACE_LOGFILEW, *PEVENT_TRACE_LOGFILEW;
typedef ULONG(WINAPI * PEVENT_TRACE_BUFFER_CALLBACKW)
(PEVENT_TRACE_LOGFILEW Logfile);
typedef VOID(WINAPI *PEVENT_CALLBACK)(PEVENT_TRACE pEvent);
typedef struct _EVENT_RECORD
EVENT_RECORD, *PEVENT_RECORD;
typedef VOID(WINAPI *PEVENT_RECORD_CALLBACK) (PEVENT_RECORD EventRecord);
struct _EVENT_TRACE_LOGFILEW {
LPWSTR LogFileName; // Logfile Name
LPWSTR LoggerName; // LoggerName
LONGLONG CurrentTime; // timestamp of last event
ULONG BuffersRead; // buffers read to date
union {
// Mode of the logfile
ULONG LogFileMode;
// Processing flags used on Vista and above
ULONG ProcessTraceMode;
} DUMMYUNIONNAME;
EVENT_TRACE CurrentEvent; // Current Event from this stream.
TRACE_LOGFILE_HEADER LogfileHeader; // logfile header structure
PEVENT_TRACE_BUFFER_CALLBACKW // callback before each buffer
BufferCallback; // is read
//
// following variables are filled for BufferCallback.
//
ULONG BufferSize;
ULONG Filled;
ULONG EventsLost;
//
// following needs to be propaged to each buffer
//
union {
// Callback with EVENT_TRACE
PEVENT_CALLBACK EventCallback;
// Callback with EVENT_RECORD on Vista and above
PEVENT_RECORD_CALLBACK EventRecordCallback;
} DUMMYUNIONNAME2;
ULONG IsKernelTrace; // TRUE for kernel logfile
PVOID Context; // reserved for internal use
};
#pragma warning(pop)
#define PEVENT_TRACE_BUFFER_CALLBACK PEVENT_TRACE_BUFFER_CALLBACKW
#define EVENT_TRACE_LOGFILE EVENT_TRACE_LOGFILEW
#define PEVENT_TRACE_LOGFILE PEVENT_TRACE_LOGFILEW
#define KERNEL_LOGGER_NAME KERNEL_LOGGER_NAMEW
#define GLOBAL_LOGGER_NAME GLOBAL_LOGGER_NAMEW
#define EVENT_LOGGER_NAME EVENT_LOGGER_NAMEW
EXTERN_C
ULONG
WMIAPI
ProcessTrace(
_In_reads_(HandleCount) PTRACEHANDLE HandleArray,
_In_ ULONG HandleCount,
_In_opt_ LPFILETIME StartTime,
_In_opt_ LPFILETIME EndTime
);
EXTERN_C
ULONG
WMIAPI
StartTraceW(
_Out_ PTRACEHANDLE TraceHandle,
_In_ LPCWSTR InstanceName,
_Inout_ PEVENT_TRACE_PROPERTIES Properties
);
EXTERN_C
ULONG
WMIAPI
ControlTraceW(
_In_ TRACEHANDLE TraceHandle,
_In_opt_ LPCWSTR InstanceName,
_Inout_ PEVENT_TRACE_PROPERTIES Properties,
_In_ ULONG ControlCode
);
EXTERN_C
TRACEHANDLE
WMIAPI
OpenTraceW(
_Inout_ PEVENT_TRACE_LOGFILEW Logfile
);
EXTERN_C
ULONG
WMIAPI
CloseTrace(
_In_ TRACEHANDLE TraceHandle
);
EXTERN_C
ULONG
WMIAPI
TraceSetInformation(
_In_ TRACEHANDLE SessionHandle,
_In_ TRACE_INFO_CLASS InformationClass,
_In_reads_bytes_(InformationLength) PVOID TraceInformation,
_In_ ULONG InformationLength
);
EXTERN_C
ULONG
WMIAPI
TraceQueryInformation(
_In_ TRACEHANDLE SessionHandle,
_In_ TRACE_INFO_CLASS InformationClass,
_Out_writes_bytes_(InformationLength) PVOID TraceInformation,
_In_ ULONG InformationLength,
_Out_opt_ PULONG ReturnLength
);
//////////////////////////////////////////////////////////////////////////
#define RegisterTraceGuids RegisterTraceGuidsW
#define StartTrace StartTraceW
#define ControlTrace ControlTraceW
#define StopTrace StopTraceW
#define QueryTrace QueryTraceW
#define UpdateTrace UpdateTraceW
#define FlushTrace FlushTraceW
#define QueryAllTraces QueryAllTracesW
#define OpenTrace OpenTraceW
//////////////////////////////////////////////////////////////////////////
#else
#define INITGUID // Causes definition of SystemTraceControlGuid in evntrace.h.
#include <wmistr.h>
#include <evntrace.h>
#include <strsafe.h>
#include <evntcons.h>
#endif //DECLARE_ETW
namespace Optick
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const int MAX_CPU_CORES = 256;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct ETWRuntime
{
array<ThreadID, MAX_CPU_CORES> activeCores;
vector<std::pair<uint8_t, SysCallData*>> activeSyscalls;
unordered_set<uint64> activeThreadsIDs;
ProcessID currentProcessId;
ETWRuntime()
{
Reset();
}
void Reset()
{
currentProcessId = INVALID_PROCESS_ID;
activeCores.fill(INVALID_THREAD_ID);
activeSyscalls.resize(0);
activeThreadsIDs.clear();
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class ETW : public Trace
{
static const int ETW_BUFFER_SIZE = 1024 << 10; // 1Mb
static const int ETW_BUFFER_COUNT = 32;
static const int ETW_MAXIMUM_SESSION_NAME = 1024;
EVENT_TRACE_PROPERTIES *traceProperties;
EVENT_TRACE_LOGFILE logFile;
TRACEHANDLE traceSessionHandle;
TRACEHANDLE openedHandle;
HANDLE processThreadHandle;
DWORD currentProcessId;
bool isActive;
static DWORD WINAPI RunProcessTraceThreadFunction(LPVOID parameter);
static void AdjustPrivileges();
unordered_map<uint64_t, const EventDescription*> syscallDescriptions;
public:
ETWRuntime runtime;
ETW();
~ETW();
virtual CaptureStatus::Type Start(Mode::Type mode, int frequency, const ThreadList& threads) override;
virtual bool Stop() override;
DWORD GetProcessID() const { return currentProcessId; }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct CSwitch
{
// New thread ID after the switch.
uint32 NewThreadId;
// Previous thread ID.
uint32 OldThreadId;
// Thread priority of the new thread.
int8 NewThreadPriority;
// Thread priority of the previous thread.
int8 OldThreadPriority;
//The index of the C-state that was last used by the processor. A value of 0 represents the lightest idle state with higher values representing deeper C-states.
uint8 PreviousCState;
// Not used.
int8 SpareByte;
// Wait reason for the previous thread. The following are the possible values:
// 0 Executive
// 1 FreePage
// 2 PageIn
// 3 PoolAllocation
// 4 DelayExecution
// 5 Suspended
// 6 UserRequest
// 7 WrExecutive
// 8 WrFreePage
// 9 WrPageIn
// 10 WrPoolAllocation
// 11 WrDelayExecution
// 12 WrSuspended
// 13 WrUserRequest
// 14 WrEventPair
// 15 WrQueue
// 16 WrLpcReceive
// 17 WrLpcReply
// 18 WrVirtualMemory
// 19 WrPageOut
// 20 WrRendezvous
// 21 WrKeyedEvent
// 22 WrTerminated
// 23 WrProcessInSwap
// 24 WrCpuRateControl
// 25 WrCalloutStack
// 26 WrKernel
// 27 WrResource
// 28 WrPushLock
// 29 WrMutex
// 30 WrQuantumEnd
// 31 WrDispatchInt
// 32 WrPreempted
// 33 WrYieldExecution
// 34 WrFastMutex
// 35 WrGuardedMutex
// 36 WrRundown
// 37 MaximumWaitReason
int8 OldThreadWaitReason;
// Wait mode for the previous thread. The following are the possible values:
// 0 KernelMode
// 1 UserMode
int8 OldThreadWaitMode;
// State of the previous thread. The following are the possible state values:
// 0 Initialized
// 1 Ready
// 2 Running
// 3 Standby
// 4 Terminated
// 5 Waiting
// 6 Transition
// 7 DeferredReady (added for Windows Server 2003)
int8 OldThreadState;
// Ideal wait time of the previous thread.
int8 OldThreadWaitIdealProcessor;
// Wait time for the new thread.
uint32 NewThreadWaitTime;
// Reserved.
uint32 Reserved;
static const byte OPCODE = 36;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct StackWalk_Event
{
// Original event time stamp from the event header
uint64 EventTimeStamp;
// The process identifier of the original event
uint32 StackProcess;
// The thread identifier of the original event
uint32 StackThread;
// Callstack head
uint64 Stack0;
static const byte OPCODE = 32;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Thread_TypeGroup1
{
// Process identifier of the thread involved in the event.
uint32 ProcessId;
// Thread identifier of the thread involved in the event.
uint32 TThreadId;
// Base address of the thread's stack.
uint64 StackBase;
// Limit of the thread's stack.
uint64 StackLimit;
// Base address of the thread's user-mode stack.
uint64 UserStackBase;
// Limit of the thread's user-mode stack.
uint64 UserStackLimit;
// The set of processors on which the thread is allowed to run.
uint32 Affinity;
// Starting address of the function to be executed by this thread.
uint64 Win32StartAddr;
// Thread environment block base address.
uint64 TebBase;
// Identifies the service if the thread is owned by a service; otherwise, zero.
uint32 SubProcessTag;
// The scheduler priority of the thread
uint8 BasePriority;
// A memory page priority hint for memory pages accessed by the thread.
uint8 PagePriority;
// An IO priority hint for scheduling IOs generated by the thread.
uint8 IoPriority;
// Not used.
uint8 ThreadFlags;
enum Opcode : uint8
{
Start = 1,
End = 2,
DCStart = 3,
DCEnd = 4,
};
};
size_t GetSIDSize(uint8* ptr)
{
size_t result = 0;
int sid = *((int*)ptr);
if (sid != 0)
{
size_t tokenSize = 16;
ptr += tokenSize;
result += tokenSize;
result += 8 + (4 * ((SID*)ptr)->SubAuthorityCount);
}
else
{
result = 4;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// https://github.com/Microsoft/perfview/blob/688a8564062d51321bbab53cd71d9e174a77d2ce/src/TraceEvent/TraceEvent.cs
struct Process_TypeGroup1
{
// The address of the process object in the kernel.
uint64 UniqueProcessKey;
// Global process identifier that you can use to identify a process.
uint32 ProcessId;
// Unique identifier of the process that creates this process.
uint32 ParentId;
// Unique identifier that an operating system generates when it creates a new session.
uint32 SessionId;
// Exit status of the stopped process.
int32 ExitStatus;
// The physical address of the page table of the process.
uint64 DirectoryTableBase;
// (?) uint8 Flags;
// object UserSID;
// string ImageFileName;
// wstring CommandLine;
static size_t GetSIDOffset(PEVENT_RECORD pEvent)
{
if (pEvent->EventHeader.EventDescriptor.Version >= 4)
return 36;
if (pEvent->EventHeader.EventDescriptor.Version == 3)
return 32;
return 24;
}
const char* GetProcessName(PEVENT_RECORD pEvent) const
{
OPTICK_ASSERT((pEvent->EventHeader.Flags & EVENT_HEADER_FLAG_64_BIT_HEADER) != 0, "32-bit is not supported! Disable OPTICK_ENABLE_TRACING on 32-bit platform if needed!");
size_t sidOffset = GetSIDOffset(pEvent);
size_t sidSize = GetSIDSize((uint8*)this + sidOffset);
return (char*)this + sidOffset + sidSize;
}
enum Opcode
{
Start = 1,
End = 2,
DCStart = 3,
DCEnd = 4,
Defunct = 39,
};
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct SampledProfile
{
uint32 InstructionPointer;
uint32 ThreadId;
uint32 Count;
static const byte OPCODE = 46;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct SysCallEnter
{
uintptr_t SysCallAddress;
static const byte OPCODE = 51;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct SysCallExit
{
uint32 SysCallNtStatus;
static const byte OPCODE = 52;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
constexpr uint32 GuidHash(uint32 u0, uint32 u1, uint32 u2, uint32 u3)
{
return u0 ^ u1 ^ u2 ^ u3;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
uint32 GuidHash(GUID guid)
{
return GuidHash(guid.Data1, (guid.Data3 << 16) | guid.Data2, ((uint32*)guid.Data4)[0], ((uint32*)guid.Data4)[1]);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define ETW_GUID(NAME, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) DEFINE_GUID(NAME, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8); \
const uint32 NAME##Hash = GuidHash((uint32)l, (uint32)((w2 << 16) | w1), (uint32)((b4 << 24) | (b3 << 16) | (b2 << 8) | b1), (uint32)((b8 << 24) | (b7 << 16) | (b6 << 8) | b5));
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ce1dbfb4-137e-4da6-87b0-3f59aa102cbc
ETW_GUID(SampledProfileGuid, 0xce1dbfb4, 0x137e, 0x4da6, 0x87, 0xb0, 0x3f, 0x59, 0xaa, 0x10, 0x2c, 0xbc);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c
// https://docs.microsoft.com/en-us/windows/desktop/etw/thread
ETW_GUID(ThreadGuid, 0x3d6fa8d1, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 3d6fa8d0-fe05-11d0-9dda-00c04fd7ba7c
// https://docs.microsoft.com/en-us/windows/desktop/etw/process
ETW_GUID(ProcessGuid, 0x3d6fa8d0, 0xfe05, 0x11d0, 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// def2fe46-7bd6-4b80-bd94-f57fe20d0ce3
// https://docs.microsoft.com/en-us/windows/win32/etw/stackwalk
ETW_GUID(StackWalkGuid, 0xdef2fe46, 0x7bd6, 0x4b80, 0xbd, 0x94, 0xf5, 0x7f, 0xe2, 0x0d, 0x0c, 0xe3);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// https://docs.microsoft.com/en-us/windows/win32/etw/perfinfo
// ce1dbfb4-137e-4da6-87b0-3f59aa102cbc
ETW_GUID(PerfInfoGuid, 0xce1dbfb4, 0x137e, 0x4da6, 0x87, 0xb0, 0x3f, 0x59, 0xaa, 0x10, 0x2c, 0xbc);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ETW* g_ETW;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void OnThreadEvent(PEVENT_RECORD eventRecord)
{
ETWRuntime& runtime = g_ETW->runtime;
switch (eventRecord->EventHeader.EventDescriptor.Opcode)
{
case CSwitch::OPCODE:
if (sizeof(CSwitch) == eventRecord->UserDataLength)
{
CSwitch* pSwitchEvent = (CSwitch*)eventRecord->UserData;
SwitchContextDesc desc;
desc.reason = pSwitchEvent->OldThreadWaitReason;
desc.cpuId = eventRecord->BufferContext.ProcessorNumber;
desc.oldThreadId = (uint64)pSwitchEvent->OldThreadId;
desc.newThreadId = (uint64)pSwitchEvent->NewThreadId;
desc.timestamp = eventRecord->EventHeader.TimeStamp.QuadPart;
Core::Get().ReportSwitchContext(desc);
// Assign ThreadID to the cores
if (runtime.activeThreadsIDs.find(desc.newThreadId) != runtime.activeThreadsIDs.end())
{
runtime.activeCores[desc.cpuId] = desc.newThreadId;
}
else if (runtime.activeThreadsIDs.find(desc.oldThreadId) != runtime.activeThreadsIDs.end())
{
runtime.activeCores[desc.cpuId] = INVALID_THREAD_ID;
}
}
break;
case Thread_TypeGroup1::Start:
case Thread_TypeGroup1::DCStart:
if (eventRecord->UserDataLength >= sizeof(Thread_TypeGroup1))
{
const Thread_TypeGroup1* pThreadEvent = (const Thread_TypeGroup1*)eventRecord->UserData;
Core::Get().RegisterThreadDescription(ThreadDescription("", pThreadEvent->TThreadId, pThreadEvent->ProcessId, 1, pThreadEvent->BasePriority));
if (pThreadEvent->ProcessId == runtime.currentProcessId)
runtime.activeThreadsIDs.insert(pThreadEvent->TThreadId);
}
break;
default:
break;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////