-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprofiler.c
2047 lines (1632 loc) · 85 KB
/
profiler.c
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) 2023 Pascal Beyer
//
// 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.
//
//
// This is a fairly simple sampling profiler based on the Event Tracing for Windows (ETW)
// and DbgHelp APIs. The basic idea is to use ETW to generate stack trace samples,
// symbolize these stack traces using DbgHelp and build a profile tree.
// These profile trees are displayed using the GDI (essentially FillRect + TextOut).
//
// The command-line usage is as follows:
//
// profiler <command> <arg1> <arg2>...
//
// The profiler will get the raw command line and strip everything until the first space
// and then execute the rest using 'CreateProcess'. For this reason <command> cannot be
// a batch script.
//
// As ETW is intended to be used as a whole system profiler (including kernel) the API
// is sort of awkward and you need administrator privileges (or at least the
// 'SeSystemProfilePrivilege') to use it. For this reason it is advantageous to embed
// a 'requireAdministrator' Manifest into the application. The build command for this is
//
// cl /O2 profiler.c /link /MANIFESTUAC:level='requireAdministrator' /MANIFEST:EMBED
//
// Otherwise, the build command is simply
//
// cl /O2 profiler.c
//
// This build command has to be executed from an x64 Native Tools Command Prompt:
//
// https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line
//
// The code works as follows:
//
// * main() sets up the ETW trace.
//
// * main() starts the command as 'CREATE_SUSPENDED' which already gives us the PID,
// but does not actually run the application until we call 'ResumeThread'.
//
// * ETW requires a _event record_ callback, which has to run inside a processing thread.
// This thread is created by main(). main() then calls ResumeThread to start the target process.
//
// * The processing thread (EventRecordCallback()) filters for events with the correct PID,
// which are either module loads/unloads or stack walk events.
//
// * During this time the main thread waits for the target process to exit.
// Once it does, it stops the tracing, causing the event trace thread to exit.
//
// * Now we have collected stack trace samples, the main thread opens a window and
// creates a background thread.
//
// * The background thread symbolizes the stack traces and builds profiling trees.
//
// * The main thread renders the profiling trees and handles input events.
//
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#include <Tchar.h>
#include <windows.h>
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Gdi32.lib")
#include <dbghelp.h>
#pragma comment(lib, "Dbghelp.lib")
#define INITGUID
#include <evntrace.h>
#include <evntcons.h>
#include <evntprov.h>
DEFINE_GUID(/* ce1dbfb4-137e-4da6-87b0-3f59aa102cbc */ PerfInfoGuid, 0xce1dbfb4, 0x137e, 0x4da6, 0x87, 0xb0, 0x3f, 0x59, 0xaa, 0x10, 0x2c, 0xbc);
DEFINE_GUID(/* 2cb15d1d-5fc1-11d2-abe1-00a0c911f518 */ ImageLoadGuid, 0x2cb15d1d, 0x5fc1, 0x11d2, 0xab, 0xe1, 0x00, 0xa0, 0xc9, 0x11, 0xf5, 0x18);
DEFINE_GUID(/* def2fe46-7bd6-4b80-bd94-f57fe20d0ce3 */ StackWalkGuid, 0xdef2fe46, 0x7bd6, 0x4b80, 0xbd, 0x94, 0xf5, 0x7f, 0xe2, 0x0d, 0x0c, 0xe3);
#pragma comment(lib, "Advapi32.lib")
//
// Always flush after printing!
//
void print(char *format, ...){
va_list va;
va_start(va, format);
int ret = vprintf(format, va);
va_end(va);
fflush(0);
}
//_____________________________________________________________________________________________________________________
// Pool Allocator
typedef struct _POOL_ALLOCATOR{
PCHAR Base;
SIZE_T Used;
SIZE_T Committed;
SIZE_T Reserved;
} POOL_ALLOCATOR, *PPOOL_ALLOCATOR;
//
// Pool allocator for fast allocations.
//
// Does not return aligned memory, but it's fine, it's x64.
//
void *PoolAllocate(PPOOL_ALLOCATOR Pool, SIZE_T Size){
if(Pool->Used + Size > Pool->Committed){
if(!Pool->Base){
//
// If we do not have a base, the Pool is not initialized yet.
// Initialize it by reserving 64 GiB of memory.
// ... that should be enough for anybody.
//
SIZE_T ReserveSize = 64ull * 1024ull * 1024ull * 1024ull;
Pool->Base = VirtualAlloc(NULL, ReserveSize, MEM_RESERVE, PAGE_READWRITE);
Pool->Reserved = ReserveSize;
}
//
// Usually, allocate memory from the system in 10 MiB chunks.
//
ULONG AllocationSize = 10 * 1024 * 1024;
//
// Ensure we allocate enough for 'Size'.
//
if(Size > AllocationSize) AllocationSize = (Size + 0xfff) & ~0xfff;
if(Pool->Committed + AllocationSize > Pool->Reserved){
print("Out of memory.\n");
_exit(1);
}
PVOID Check = VirtualAlloc(Pool->Base + Pool->Committed, AllocationSize, MEM_COMMIT, PAGE_READWRITE);
if(!Check){
print("Out of memory.\n");
_exit(1);
}
Pool->Committed += AllocationSize;
}
void *Ret = Pool->Base + Pool->Used;
Pool->Used += Size;
memset(Ret, 0, Size);
return Ret;
}
//_____________________________________________________________________________________________________________________
// Event Trace processing structures
typedef enum _ENTRY_TRACE_ENTRY_TYPE{
EVENT_TRACE_ENTRY_TYPE_NONE,
EVENT_TRACE_ENTRY_TYPE_LOAD_MODULE,
EVENT_TRACE_ENTRY_TYPE_UNLOAD_MODULE,
EVENT_TRACE_ENTRY_TYPE_STACK_TRACE_SAMPLE,
EVENT_TRACE_ENTRY_TYPE_COUNT,
} EVENT_TRACE_ENTRY_TYPE;
typedef struct _EVENT_TRACE_ENTRY_HEADER{
EVENT_TRACE_ENTRY_TYPE EntryType;
ULONG EntryLength;
} EVENT_TRACE_ENTRY_HEADER, *PEVENT_TRACE_ENTRY_HEADER;
struct StackWalk_Event{
uint64_t EventTimeStamp;
uint32_t StackProcess;
uint32_t StackThread;
uint64_t Stack[];
};
typedef struct _EVENT_RECORD_CALLBACK_CONTEXT{
ULONG TargetProcessId;
POOL_ALLOCATOR EventTrace;
} EVENT_RECORD_CALLBACK_CONTEXT, *PEVENT_RECORD_CALLBACK_CONTEXT;
void EventRecordCallback(PEVENT_RECORD EventRecord){
PEVENT_RECORD_CALLBACK_CONTEXT Context = EventRecord->UserContext;
ULONG TargetProcessId = Context->TargetProcessId;
GUID ProviderId = EventRecord->EventHeader.ProviderId;
UCHAR Opcode = EventRecord->EventHeader.EventDescriptor.Opcode;
EVENT_TRACE_ENTRY_TYPE EntryType = EVENT_TRACE_ENTRY_TYPE_NONE;
if(memcmp(&ProviderId, &PerfInfoGuid, sizeof(ProviderId)) == 0){
//
// @cleanup: Understand this... Did we not switch on StackTracing for these?
//
// if(EventRecord->EventHeader.EventDescriptor.Opcode == /*SampledProfile*/46) return;
return;
}else if(memcmp(&ProviderId, &StackWalkGuid, sizeof(ProviderId)) == 0){
//
// Technically, a StackWalk event is only a StackWalk_Event event if it has Opcode 32.
// This seems to be always the case though from my limited testing.
//
if(Opcode != /*Stack tracing event*/32) return;
//
// "Parse" the user data.
//
struct StackWalk_Event *StackWalk_Event = EventRecord->UserData;
uint64_t StackWalkEventSize = EventRecord->UserDataLength;
uint64_t AmountOfStacks = (StackWalkEventSize - sizeof(*StackWalk_Event))/8;
if(StackWalkEventSize < sizeof(*StackWalk_Event)) return;
//
// Filter by the ProcessId we actually care about.
//
if(StackWalk_Event->StackProcess != TargetProcessId) return;
//
// For some reason, even though we specify 'ExcludeKernelStack'
// we still get some _small_ kernel stack events.
// Filter these by checking if the high bits are set.
//
if((int64_t)StackWalk_Event->Stack[0] < 0) return;
EntryType = EVENT_TRACE_ENTRY_TYPE_STACK_TRACE_SAMPLE;
}else if(memcmp(&ProviderId, &ImageLoadGuid, sizeof(ProviderId)) == 0){
struct{
uint64_t ImageBase;
uint64_t ImageSize;
uint32_t ProcessId;
uint32_t ImageCheckSum;
uint32_t TimeDateStamp;
uint32_t Reserved0;
uint64_t DefaultBase;
uint32_t Reserved1;
uint32_t Reserved2;
uint32_t Reserved3;
uint32_t Reserved4;
WCHAR FileName[];
} *Image_Load = EventRecord->UserData;
if(EventRecord->UserDataLength < sizeof(*Image_Load)) return;
if(Image_Load->ProcessId != TargetProcessId) return;
if(Opcode == EVENT_TRACE_TYPE_LOAD/* || Opcode == EVENT_TRACE_TYPE_DC_START*/) EntryType = EVENT_TRACE_ENTRY_TYPE_LOAD_MODULE;
if(Opcode == EVENT_TRACE_TYPE_END/* || Opcode == EVENT_TRACE_TYPE_DC_END*/) EntryType = EVENT_TRACE_ENTRY_TYPE_UNLOAD_MODULE;
}else{
#if 0
print("Unhandled {%.8x-%.4x-%.4x-%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x}\n",
ProviderId.Data1, ProviderId.Data2, ProviderId.Data3,
ProviderId.Data4[0], ProviderId.Data4[1], ProviderId.Data4[2], ProviderId.Data4[3],
ProviderId.Data4[4], ProviderId.Data4[5], ProviderId.Data4[6], ProviderId.Data4[7]);
#endif
return;
}
//
// If we did not return, Copy the event to the 'EventTrace'.
//
EVENT_TRACE_ENTRY_HEADER EventTraceEntryHeader = {
.EntryType = EntryType,
.EntryLength = EventRecord->UserDataLength,
};
PCHAR EventMemory = PoolAllocate(&Context->EventTrace, sizeof(EventTraceEntryHeader) + EventRecord->UserDataLength);
memcpy(EventMemory, &EventTraceEntryHeader, sizeof(EventTraceEntryHeader));
memcpy(EventMemory + sizeof(EventTraceEntryHeader), EventRecord->UserData, EventRecord->UserDataLength);
}
int ProcessTraceThreadStartRoutine(void *Parameter){
PTRACEHANDLE ProcessTraceHandle = Parameter;
ProcessTrace(ProcessTraceHandle, /*HandleCount*/1, /*StartTime*/0, /*EndTime*/0);
return 1;
}
//_____________________________________________________________________________________________________________________
// Profiling Tree information
typedef enum _PROFILE_TREE_KIND{
PROFILE_TREE_TOP_DOWN,
PROFILE_TREE_BOTTOM_UP,
PROFILE_TREE_TOP_FUNCTIONS_UP,
PROFILE_TREE_TOP_FUNCTIONS_DOWN,
PROFILE_TREE_KIND_COUNT,
} PROFILE_TREE_KIND, *PPROFILE_TREE_KIND;
typedef struct _FILE_AND_LINE{
PCHAR FileName;
ULONG FileNameLength;
ULONG LineNumber;
ULONG Samples;
} FILE_AND_LINE, *PFILE_AND_LINE;
typedef struct _PROFILE_TREE_NODE{
ULONG AmountOfChildren;
ULONG MaxAmountOfChildren;
struct _PROFILE_TREE_NODE **Children;
PFILE_AND_LINE FileAndLineNumbers;
ULONG AmountOfFileAndLineNumbers;
ULONG MaxAmountOfFileAndLineNumbers;
ULONG IsExpanded;
ULONG Depth;
ULONG Samples;
ULONG NameLength;
CHAR Name[];
} PROFILE_TREE_NODE, *PPROFILE_TREE_NODE;
typedef struct _LOADED_MODULE{
struct _LOADED_MODULE *Next;
DWORD64 ImageBase;
DWORD64 ImageSize;
ULONG FileNameLength;
CHAR FileName[];
} LOADED_MODULE, *PLOADED_MODULE;
typedef struct _ADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY{
uint64_t Address;
PCHAR FileName;
PCHAR SymbolName;
ULONG SymbolNameLength;
ULONG FileNameLength;
ULONG LineNumber;
} ADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY, *PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY;
typedef struct _PROFILE_TREE_GENERATING_THREAD_CONTEXT{
// The window handle to refresh the window.
HWND WindowHandle;
volatile uint64_t *SelectedStartTimeStamp;
volatile uint64_t *SelectedEndTimeStamp;
// The event trace to be processed.
PCHAR EventTraceBase;
SIZE_T EventTraceSize;
HANDLE TreeUpdateEvent;
// The destination of where to put the generated profile trees.
volatile PPROFILE_TREE_NODE (*CachedProfileTrees)[PROFILE_TREE_KIND_COUNT];
struct{
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY *Entries;
ULONG Size;
ULONG Capacity;
} AddressToSymbolHashTable;
} PROFILE_TREE_GENERATING_THREAD_CONTEXT, *PPROFILE_TREE_GENERATING_THREAD_CONTEXT;
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY LookupSymbolForAddress(PPROFILE_TREE_GENERATING_THREAD_CONTEXT Context, uint64_t Address){
for(ULONG TableIndex = 0; TableIndex < Context->AddressToSymbolHashTable.Capacity; TableIndex++){
ULONG Index = ((Address % 1337133713371337) + TableIndex) & (Context->AddressToSymbolHashTable.Capacity - 1);
if(!Context->AddressToSymbolHashTable.Entries[Index]) return 0;
if(Context->AddressToSymbolHashTable.Entries[Index]->Address == Address){
return Context->AddressToSymbolHashTable.Entries[Index];
}
}
return 0;
}
//
// Compare functions for 'qsort'.
//
int CompareProfileTreeNodes(const void *First, const void *Second){
PPROFILE_TREE_NODE FirstNode = *(PPROFILE_TREE_NODE *)First;
PPROFILE_TREE_NODE SecondNode = *(PPROFILE_TREE_NODE *)Second;
return SecondNode->Samples - FirstNode->Samples;
}
int CompareFileAndLineNumbers(const void *First, const void *Second){
PFILE_AND_LINE FirstLine = (PFILE_AND_LINE)First;
PFILE_AND_LINE SecondLine = (PFILE_AND_LINE)Second;
return SecondLine->Samples - FirstLine->Samples;
}
void GenerateProfileTree(PPROFILE_TREE_GENERATING_THREAD_CONTEXT Context, PPOOL_ALLOCATOR ProfileTreePool, HANDLE DbgHelpHandle, PLOADED_MODULE LoadedModules, PROFILE_TREE_KIND ProfileTreeKind){
uint64_t SelectedStartTimeStamp = *Context->SelectedStartTimeStamp;
uint64_t SelectedEndTimeStamp = *Context->SelectedEndTimeStamp;
//
// Allocate the 'RootNode'. This node does not correspond to any function.
//
PPROFILE_TREE_NODE RootNode = PoolAllocate(ProfileTreePool, sizeof(*RootNode));
SIZE_T EventTraceSize = Context->EventTraceSize;
for(SIZE_T EventTraceAt = 0; EventTraceAt < EventTraceSize; ){
PEVENT_TRACE_ENTRY_HEADER EventTraceEntryHeader = (PEVENT_TRACE_ENTRY_HEADER)(Context->EventTraceBase + EventTraceAt);
if(EventTraceEntryHeader->EntryType != EVENT_TRACE_ENTRY_TYPE_STACK_TRACE_SAMPLE){
EventTraceAt += EventTraceEntryHeader->EntryLength + sizeof(*EventTraceEntryHeader);
continue;
}
struct StackWalk_Event *StackWalk_Event = (PVOID)(EventTraceEntryHeader + 1);
if(!(SelectedStartTimeStamp <= StackWalk_Event->EventTimeStamp && StackWalk_Event->EventTimeStamp <= SelectedEndTimeStamp)){
//
// If the time stamp is not in the selected range, we ignore the event.
//
EventTraceAt += EventTraceEntryHeader->EntryLength + sizeof(*EventTraceEntryHeader);
continue;
}
//
// Save the total amount of samples in the 'RootNode->Samples'.
//
RootNode->Samples += 1;
uint64_t AmountOfStacks = (EventTraceEntryHeader->EntryLength - sizeof(*StackWalk_Event))/8;
int64_t TopFunctionIteratorStart = 0;
if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP || ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_DOWN){
TopFunctionIteratorStart = AmountOfStacks - 1;
}
//
// For "Top-Functions" we lookup the symbols prior to entering the loop,
// as they will be processed more then once.
// This allocation should be on a _scratch_ arena, but I did not care for now.
//
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY *TopFunctionStackNodes = 0;
if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP || ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_DOWN){
TopFunctionStackNodes = PoolAllocate(ProfileTreePool, AmountOfStacks * sizeof(*TopFunctionStackNodes));
for(uint64_t StackIndex = 0; StackIndex < AmountOfStacks; StackIndex++){
TopFunctionStackNodes[StackIndex] = LookupSymbolForAddress(Context, StackWalk_Event->Stack[StackIndex]);
}
}
for(int64_t TopFunctionIterator = TopFunctionIteratorStart; TopFunctionIterator >= 0; TopFunctionIterator--){
PPROFILE_TREE_NODE CurrentNode = RootNode;
int64_t StackIndexStart = 0;
int64_t StackIndexEnd = 0;
BOOL IterateBackwards = 0;
if(ProfileTreeKind == PROFILE_TREE_TOP_DOWN){
//
// Top Down means we start at the highest stack frame (index 0 of stacks)
// and iterate until we are back at the root stack frame,
// i.e the main() or whatever.
//
StackIndexStart = 0;
StackIndexEnd = AmountOfStacks;
IterateBackwards = FALSE;
}else if(ProfileTreeKind == PROFILE_TREE_BOTTOM_UP){
//
// Bottom up means we start at the root stack frame,
// i.e main() or whatever and iterate till the top of the stack.
//
StackIndexStart = AmountOfStacks-1;
StackIndexEnd = -1;
IterateBackwards = TRUE;
}else if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP){
//
// Top functions up means we iterate in the same way as 'bottom up'
// but re-start at every stack frame along the way.
//
StackIndexStart = TopFunctionIterator;
StackIndexEnd = -1;
IterateBackwards = TRUE;
}else if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_DOWN){
//
// Top functions down means we iterate in the same way as 'top down'
// but re-start at every stack frame along the way.
//
StackIndexStart = TopFunctionIterator;
StackIndexEnd = AmountOfStacks;
IterateBackwards = FALSE;
}
if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_DOWN || ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP){
//
// If the same function was already hit by a _previous_ node, we want to skip this 'Entry'.
// This prevents double counting for recursive functions.
//
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY Entry = TopFunctionStackNodes[StackIndexStart];
BOOL ShouldSkip = 0;
if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP){
for(int64_t PriorIndex = StackIndexStart + 1; PriorIndex < AmountOfStacks; PriorIndex++){
if(Entry->SymbolNameLength != TopFunctionStackNodes[PriorIndex]->SymbolNameLength) continue;
if(memcmp(Entry->SymbolName, TopFunctionStackNodes[PriorIndex]->SymbolName, Entry->SymbolNameLength) == 0){
ShouldSkip = 1;
break;
}
}
}else{
for(int64_t PriorIndex = StackIndexStart - 1; PriorIndex >= 0; PriorIndex--){
if(Entry->SymbolNameLength != TopFunctionStackNodes[PriorIndex]->SymbolNameLength) continue;
if(memcmp(Entry->SymbolName, TopFunctionStackNodes[PriorIndex]->SymbolName, Entry->SymbolNameLength) == 0){
ShouldSkip = 1;
break;
}
}
}
if(ShouldSkip) continue;
}
ULONG Depth = 0;
for(int64_t StackIndex = StackIndexStart; StackIndex != StackIndexEnd; StackIndex = IterateBackwards ? (StackIndex - 1) : (StackIndex + 1)){
uint64_t Stack = StackWalk_Event->Stack[StackIndex];
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY Entry = NULL;
if(ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_DOWN || ProfileTreeKind == PROFILE_TREE_TOP_FUNCTIONS_UP){
Entry = TopFunctionStackNodes[StackIndex];
}else{
Entry = LookupSymbolForAddress(Context, Stack);
}
ULONG NameLength = Entry->SymbolNameLength;
PCHAR SymbolName = Entry->SymbolName;
ULONG LineNumber = Entry->LineNumber;
PCHAR FileName = Entry->FileName;
ULONG FileNameLength = Entry->FileNameLength;
PPROFILE_TREE_NODE TreeNode = NULL;
for(ULONG ChildIndex = 0; ChildIndex < CurrentNode->AmountOfChildren; ChildIndex++){
PPROFILE_TREE_NODE Iterator = CurrentNode->Children[ChildIndex];
if(Iterator->NameLength == NameLength && strcmp(Iterator->Name, SymbolName) == 0){
//
// We found an existing node.
//
TreeNode = Iterator;
break;
}
}
if(!TreeNode){
//
// If we could not find the node, allocate a new one.
//
TreeNode = PoolAllocate(ProfileTreePool, sizeof(*TreeNode) + NameLength + 1);
TreeNode->NameLength = NameLength;
memcpy(TreeNode->Name, SymbolName, NameLength);
TreeNode->Name[TreeNode->NameLength] = 0;
TreeNode->Depth = Depth;
//
// Append the 'TreeNode' as a child of 'CurrentNode'.
//
if(CurrentNode->AmountOfChildren + 1 >= CurrentNode->MaxAmountOfChildren){
ULONG NewMax = CurrentNode->MaxAmountOfChildren ? 2 * CurrentNode->MaxAmountOfChildren : 8;
PPROFILE_TREE_NODE *NewChildren = PoolAllocate(ProfileTreePool, NewMax * sizeof(*CurrentNode->Children));
memcpy(NewChildren, CurrentNode->Children, CurrentNode->MaxAmountOfChildren * sizeof(*CurrentNode->Children));
CurrentNode->MaxAmountOfChildren = NewMax;
CurrentNode->Children = NewChildren;
}
CurrentNode->Children[CurrentNode->AmountOfChildren++] = TreeNode;
}
//
// Remember that we hit this node!
//
TreeNode->Samples += 1;
if(FileNameLength != 0){
PFILE_AND_LINE Found = NULL;
for(ULONG Index = 0; Index < TreeNode->AmountOfFileAndLineNumbers; Index++){
PFILE_AND_LINE FileAndLine = TreeNode->FileAndLineNumbers + Index;
if(FileAndLine->LineNumber == LineNumber && FileAndLine->FileNameLength == FileNameLength && strcmp(FileAndLine->FileName, FileName) == 0){
Found = FileAndLine;
break;
}
}
if(!Found){
if(TreeNode->AmountOfFileAndLineNumbers + 1 >= TreeNode->MaxAmountOfFileAndLineNumbers){
ULONG NewMax = TreeNode->MaxAmountOfFileAndLineNumbers ? 2 * TreeNode->MaxAmountOfFileAndLineNumbers : 8;
PFILE_AND_LINE NewLines = PoolAllocate(ProfileTreePool, NewMax * sizeof(*TreeNode->FileAndLineNumbers));
memcpy(NewLines, TreeNode->FileAndLineNumbers, TreeNode->MaxAmountOfFileAndLineNumbers * sizeof(*TreeNode->FileAndLineNumbers));
TreeNode->MaxAmountOfFileAndLineNumbers = NewMax;
TreeNode->FileAndLineNumbers = NewLines;
}
PFILE_AND_LINE NewLine = &TreeNode->FileAndLineNumbers[TreeNode->AmountOfFileAndLineNumbers++];
NewLine->LineNumber = LineNumber;
NewLine->FileName = FileName;
NewLine->FileNameLength = FileNameLength;
Found = NewLine;
}
Found->Samples++;
}
//
// Iterate down the tree.
//
Depth += 1;
CurrentNode = TreeNode;
}
}
EventTraceAt += EventTraceEntryHeader->EntryLength + sizeof(*EventTraceEntryHeader);
}
{
//
// Sort all the tree nodes:
//
struct {
PPROFILE_TREE_NODE TreeNode;
ULONG ChildIndex;
} Stack[0x100] = {
{RootNode, 0}
};
LONG StackAt = 0;
while(StackAt >= 0){
PPROFILE_TREE_NODE ParentNode = Stack[StackAt].TreeNode;
ULONG ChildIndex = Stack[StackAt].ChildIndex++;
if(ChildIndex == ParentNode->AmountOfChildren){
//
// Pop the StackNode, if this is past the last child.
//
StackAt--;
continue;
}
//
// If we are on the first child, _first_ sort the whole array.
//
if(ChildIndex == 0){
qsort(ParentNode->Children, ParentNode->AmountOfChildren, sizeof(*ParentNode->Children), CompareProfileTreeNodes);
}
//
// Add the Child to the Stack.
//
PPROFILE_TREE_NODE ChildNode = ParentNode->Children[ChildIndex];
//
// Sort the file and line numbers of the Child node.
//
if(ChildNode->AmountOfFileAndLineNumbers){
qsort(ChildNode->FileAndLineNumbers, ChildNode->AmountOfFileAndLineNumbers, sizeof(*ChildNode->FileAndLineNumbers), CompareFileAndLineNumbers);
}
if(StackAt + 1 < ARRAYSIZE(Stack)){
ULONG Index = ++StackAt;
Stack[Index].TreeNode = ChildNode;
Stack[Index].ChildIndex = 0;
}
}
}
(*Context->CachedProfileTrees)[ProfileTreeKind] = RootNode;
//
// Redraw the entire window just in case the Window thread is waiting on us.
//
RedrawWindow(Context->WindowHandle, NULL, NULL, RDW_INVALIDATE);
}
int ProfileTreeGeneratorThreadStartRoutine(void *parameter){
PPROFILE_TREE_GENERATING_THREAD_CONTEXT Context = parameter;
//
// Setup the 'DbgHelp' state.
//
// "A handle that identifies the caller. This value should be unique and nonzero,
// but need not be a process handle."
HANDLE DbgHelpHandle = (HANDLE)1337;
BOOL SymInitializeSuccess = SymInitialize(DbgHelpHandle, /*UserSearchPath*/NULL, /*fInvaldeProcess*/FALSE);
if(!SymInitializeSuccess){
print("Failed to initialize DbgHelp with error %d\n", GetLastError());
return 1;
}
//
// Set the Search Path to the microsoft symbol server.
//
BOOL SymSetSearchPathSuccess = SymSetSearchPath(DbgHelpHandle, TEXT("srv**symbols*http://msdl.microsoft.com/download/symbols"));
if(!SymSetSearchPathSuccess){
print("Failed to SymSetSearchPath.\n");
return 1;
}
//
// Load line number information.
//
SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES);
PLOADED_MODULE LoadedModules = NULL;
POOL_ALLOCATOR DbgHelpPool = {0};
//
// Load all the modules into 'DbgHelp' and populate the symbol hash table.
//
PCHAR EventTraceBase = Context->EventTraceBase;
SIZE_T EventTraceSize = Context->EventTraceSize;
for(SIZE_T EventTraceAt = 0; EventTraceAt < EventTraceSize; ){
PEVENT_TRACE_ENTRY_HEADER EventTraceEntryHeader = (PEVENT_TRACE_ENTRY_HEADER)(EventTraceBase + EventTraceAt);
switch(EventTraceEntryHeader->EntryType){
case EVENT_TRACE_ENTRY_TYPE_LOAD_MODULE:
case EVENT_TRACE_ENTRY_TYPE_UNLOAD_MODULE:{
struct{
uint64_t ImageBase;
uint64_t ImageSize;
uint32_t ProcessId;
uint32_t ImageCheckSum;
uint32_t TimeDateStamp;
uint32_t Reserved0;
uint64_t DefaultBase;
uint32_t Reserved1;
uint32_t Reserved2;
uint32_t Reserved3;
uint32_t Reserved4;
WCHAR FileName[];
} *Image_Load = (PVOID)(EventTraceEntryHeader + 1);
WCHAR FileNameBuffer[0x100];
_snwprintf(FileNameBuffer, sizeof(FileNameBuffer), L"\\\\.\\GLOBALROOT%ws", Image_Load->FileName);
if(EventTraceEntryHeader->EntryType == EVENT_TRACE_ENTRY_TYPE_LOAD_MODULE){
DWORD64 BaseAddress = SymLoadModuleExW(DbgHelpHandle, NULL, FileNameBuffer, NULL, Image_Load->ImageBase, Image_Load->ImageSize, NULL, 0);
if(BaseAddress == 0 || BaseAddress != Image_Load->ImageBase){
print("Failed to SymLoadModuleExW for %ws with error %d\n", FileNameBuffer, GetLastError());
}
// "If 'wcstombs' successfully converts the multi-byte string,
// it returns the number of bytes written into the output string,
// excluding the terminating NULL (if any). If the destination parameter
// is NULL, 'wcstombs' returns the required size in bytes of the destination
// string. If 'wcstombs' encounters a wide character it can't convert to
// a multi-byte character, it returns '-1'.
size_t size_or_error = wcstombs(NULL, Image_Load->FileName, 0);
if(size_or_error == (size_t)-1) continue;
PLOADED_MODULE Module = PoolAllocate(&DbgHelpPool, sizeof(LOADED_MODULE) + size_or_error + 1);
Module->ImageBase = Image_Load->ImageBase;
Module->ImageSize = Image_Load->ImageSize;
Module->FileNameLength = size_or_error;
wcstombs(Module->FileName, Image_Load->FileName, size_or_error + 1);
Module->Next = LoadedModules;
LoadedModules = Module;
}
}break;
case EVENT_TRACE_ENTRY_TYPE_STACK_TRACE_SAMPLE:{
struct StackWalk_Event *StackWalk_Event = (PVOID)(EventTraceEntryHeader + 1);
uint64_t AmountOfStacks = (EventTraceEntryHeader->EntryLength - sizeof(*StackWalk_Event))/8;
for(int64_t StackIndex = 0; StackIndex < AmountOfStacks; StackIndex++){
uint64_t Stack = StackWalk_Event->Stack[StackIndex];
//
// Only symbolize 'Stack', if we don't already have it.
//
if(LookupSymbolForAddress(Context, Stack)) continue;
PCHAR SymbolName = NULL;
ULONG NameLength = 0;
PCHAR FileName = NULL;
ULONG FileNameLength = 0;
ULONG LineNumber = 0;
if((int64_t)Stack < 0){
static CHAR Kernel[] = "Kernel";
SymbolName = Kernel;
NameLength = sizeof(Kernel) - 1;
}else{
//
// Get the 'SymbolName' either from 'SymFromAddr' or if that fails by iterating the modules.
//
union{
union{ SYMBOL_INFO; SYMBOL_INFO Base; };
CHAR buffer[0x100];
} SymbolInfo = {
//
// "Note that the total size of the data is the SizeOfStruct + (MaxNameLen - 1) * sizeof(TCHAR)."
// The reason to subtract one is that the first character in the name is accounted for in the size of the structure."
//
.SizeOfStruct = sizeof(SYMBOL_INFO),
.MaxNameLen = (sizeof(SymbolInfo) - sizeof(SYMBOL_INFO))/sizeof(TCHAR),
};
DWORD64 Displacement;
BOOL SymFromAddrSuccess = SymFromAddr(DbgHelpHandle, Stack, &Displacement, &SymbolInfo.Base);
if(SymFromAddrSuccess){
SymbolName = PoolAllocate(&DbgHelpPool, SymbolInfo.NameLen + 1);
memcpy(SymbolName, SymbolInfo.Name, SymbolInfo.NameLen);
NameLength = SymbolInfo.NameLen;
}else{
//
// This happens for modules which don't have loaded symbols.
//
int found = 0;
for(PLOADED_MODULE Iterator = LoadedModules; Iterator; Iterator = Iterator->Next){
if(Iterator->ImageBase <= Stack && Stack <= Iterator->ImageBase + Iterator->ImageSize){
SymbolName = Iterator->FileName;
NameLength = Iterator->FileNameLength;
found = 1;
break;
}
}
if(!found){
//
// This might happen for JIT-code or something.
// It also randomly happens sometimes, not sure why.
//
static CHAR Unknown[] = "Unknown";
SymbolName = Unknown;
NameLength = sizeof(Unknown) - 1;
}
}
if(SymFromAddrSuccess){
//
// Get the file/line which was hit and store it in the node.
//
IMAGEHLP_LINE64 Line = { .SizeOfStruct = sizeof(Line) };
DWORD LineDisplacement = 0;
BOOL SymGetLineFromAddr64Success = SymGetLineFromAddr64(DbgHelpHandle, Stack, &LineDisplacement, &Line);
if(SymGetLineFromAddr64Success){
FileNameLength = strlen(Line.FileName);
PCHAR CopiedFileName = PoolAllocate(&DbgHelpPool, FileNameLength + 1);
memcpy(CopiedFileName, Line.FileName, FileNameLength);
CopiedFileName[FileNameLength] = 0;
FileName = CopiedFileName;
LineNumber = Line.LineNumber;
}
}
}
//
// Potentially grow the hash table.
//
if(2 * (Context->AddressToSymbolHashTable.Size + 1) > Context->AddressToSymbolHashTable.Capacity){
ULONG NewCapacity = Context->AddressToSymbolHashTable.Capacity ? 2 * Context->AddressToSymbolHashTable.Capacity : 128;
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY *NewEntries = PoolAllocate(&DbgHelpPool, sizeof(*NewEntries) * NewCapacity);
for(ULONG OldTableIndex = 0; OldTableIndex < Context->AddressToSymbolHashTable.Capacity; OldTableIndex++){
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY OldEntry = Context->AddressToSymbolHashTable.Entries[OldTableIndex];
if(!OldEntry) continue;
for(ULONG NewTableIndex = 0; NewTableIndex < NewCapacity; NewTableIndex++){
ULONG Index = ((OldEntry->Address % 1337133713371337) + NewTableIndex) & (NewCapacity - 1);
if(!NewEntries[Index]){
NewEntries[Index] = OldEntry;
break;
}
}
}
Context->AddressToSymbolHashTable.Capacity = NewCapacity;
Context->AddressToSymbolHashTable.Entries = NewEntries;
}
//
// Insert 'Stack -> SymbolName, SymbolLength, PFILE_AND_LINE' into the hash table.
//
PADDRESS_TO_SYMBOL_HASH_TABLE_ENTRY Entry = PoolAllocate(&DbgHelpPool, sizeof(*Entry));
Entry->FileName = FileName;
Entry->FileNameLength = FileNameLength;
Entry->SymbolName = SymbolName;
Entry->SymbolNameLength = NameLength;
Entry->LineNumber = LineNumber;
Entry->Address = Stack;
for(ULONG TableIndex = 0; TableIndex < Context->AddressToSymbolHashTable.Capacity; TableIndex++){
ULONG Index = ((Stack % 1337133713371337) + TableIndex) & (Context->AddressToSymbolHashTable.Capacity - 1);
// @note: We checked in the beginning that it is not contained in the table already.
if(!Context->AddressToSymbolHashTable.Entries[Index]){
Context->AddressToSymbolHashTable.Entries[Index] = Entry;
break;
}
}
Context->AddressToSymbolHashTable.Size += 1;
}
}break;
}
EventTraceAt += EventTraceEntryHeader->EntryLength + sizeof(*EventTraceEntryHeader);
}
POOL_ALLOCATOR ProfileTreePool = {0};
while(1){
ProfileTreePool.Used = 0; // Reset the profile trees.
//
// Generate all the Profile trees one by one.
// We could make this even more parallel, but DbgHelp is single threaded.
// (The single threaded is now okay, because of the AddressToSymbolHashTable).
//
GenerateProfileTree(Context, &ProfileTreePool, DbgHelpHandle, LoadedModules, PROFILE_TREE_BOTTOM_UP);
GenerateProfileTree(Context, &ProfileTreePool, DbgHelpHandle, LoadedModules, PROFILE_TREE_TOP_FUNCTIONS_DOWN);
GenerateProfileTree(Context, &ProfileTreePool, DbgHelpHandle, LoadedModules, PROFILE_TREE_TOP_DOWN);
GenerateProfileTree(Context, &ProfileTreePool, DbgHelpHandle, LoadedModules, PROFILE_TREE_TOP_FUNCTIONS_UP);
WaitForSingleObject(Context->TreeUpdateEvent, INFINITE);
}
return 0;
}
//_____________________________________________________________________________________________________________________
// Timeline rendering thread.
#define TIMELINE_PADDING 10
#define TIMELINE_HEIGHT 100
typedef struct _TIMELINE_RENDER_CONTEXT{
// The event trace to be processed.
PCHAR EventTraceBase;
SIZE_T EventTraceSize;
uint64_t MinimumTimeStamp;
uint64_t MaximumTimeStamp;
// Window handle to get the dimensions.
HWND WindowHandle;
// Used to redraw the timeline after the window has been resized.
HANDLE ResizeEvent;
// Output Bitmap.
volatile HBITMAP *OutTimelineBitmap;