-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathUIforETWDlg.cpp
2538 lines (2272 loc) · 88 KB
/
UIforETWDlg.cpp
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 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "UIforETW.h"
#include "UIforETWDlg.h"
#include "About.h"
#include "ChildProcess.h"
#include "Settings.h"
#include "Utility.h"
#include "WorkingSet.h"
#include "Version.h"
#include "TraceLoggingSupport.h"
#include <algorithm>
#include <direct.h>
#include <ETWProviders\etwprof.h>
#include <vector>
#include <map>
#include <ShlObj.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
const int kRecordTraceHotKey = 1234;
const int kTimerID = 5678;
// This static pointer to the main window is used by the global
// outputPrintf function.
static CUIforETWDlg* pMainWindow;
// This convenient hack function is so that the ChildProcess code can
// print to the main output window. This function can only be called
// from the main thread.
void outputPrintf(_Printf_format_string_ const wchar_t* pFormat, ...)
{
va_list args;
va_start(args, pFormat);
pMainWindow->vprintf(pFormat, args);
va_end(args);
}
void CUIforETWDlg::vprintf(const wchar_t* pFormat, va_list args)
{
wchar_t buffer[5000];
_vsnwprintf_s(buffer, _TRUNCATE, pFormat, args);
auto converted = ConvertToCRLF(buffer);
// Don't add a line separator at the very beginning.
if (output_.empty() && converted.substr(0, 2) == L"\r\n")
converted = converted.substr(2);
output_ += converted;
SetDlgItemText(IDC_OUTPUT, output_.c_str());
// Make sure the end of the data is visible.
btOutput_.SetSel(0, -1);
btOutput_.SetSel(-1, -1);
// Display the results immediately.
UpdateWindow();
// Fake out the Windows hang detection since otherwise on long-running
// child-processes such as processing Chrome symbols we will get
// frosted, a ghost window will be displayed, and none of our updates
// will be visible.
MSG msg;
PeekMessage(&msg, *this, 0, 0, PM_NOREMOVE);
}
static std::wstring TranslateTraceLoggingProvider(const std::wstring& provider)
{
std::wstring providerOptions;
std::wstring justProviderName(provider);
const auto endOfProvider = justProviderName.find(L':');
if (endOfProvider != std::wstring::npos)
{
providerOptions = justProviderName.substr(endOfProvider);
justProviderName.resize(endOfProvider);
}
std::wstring providerGUID = TraceLoggingProviderNameToGUID(justProviderName);
providerGUID += providerOptions;
return providerGUID;
}
static std::wstring TranslateUserModeProviders(const std::wstring& providers)
{
std::wstring translatedProviders;
translatedProviders.reserve(providers.size());
for (const auto& provider : split(providers, '+'))
{
if (provider.empty())
{
continue;
}
translatedProviders += '+';
if (provider.front() != '*')
{
translatedProviders += provider;
continue;
}
// if the provider name begins with a *, it follows the EventSource / TraceLogging
// convention and must be translated to a GUID.
// remove the leading '*' before calling the function
translatedProviders += TranslateTraceLoggingProvider(provider.substr(1));
}
return translatedProviders;
}
CUIforETWDlg::CUIforETWDlg(CWnd* pParent /*=NULL*/) noexcept
: CDialog(CUIforETWDlg::IDD, pParent)
, monitorThread_(this)
{
pMainWindow = this;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
TransferSettings(false);
}
CUIforETWDlg::~CUIforETWDlg()
{
// Shut down key logging. Ideally this would be managed by an object so
// that CUIforETWDlg didn't have to do this, as the other threads are.
SetKeyloggingState(kKeyLoggerOff);
// Save settings.
TransferSettings(true);
}
// Shutdown tasks that must be completed before the dialog
// closes should go here.
void CUIforETWDlg::ShutdownTasks()
{
if (bShutdownCompleted_)
return;
bShutdownCompleted_ = true;
// Save any in-progress trace-notes edits.
SaveNotesIfNeeded();
// Stop ETW tracing when we shut down.
if (bIsTracing_)
{
StopTracingAndMaybeRecord(false);
}
// Forcibly clear the heap tracing registry keys.
SetHeapTracing(true);
// Make sure the sampling speed is set to normal on the way out.
// Don't change bFastSampling because it needs to get saved.
if (bFastSampling_)
{
bFastSampling_ = false;
SetSamplingSpeed();
bFastSampling_ = true;
}
}
void CUIforETWDlg::OnCancel()
{
ShutdownTasks();
CDialog::OnCancel();
}
void CUIforETWDlg::OnClose()
{
ShutdownTasks();
CDialog::OnClose();
}
void CUIforETWDlg::OnOK()
{
ShutdownTasks();
CDialog::OnOK();
}
// Hook up dialog controls to classes that represent them,
// for easier manipulation of those controls.
void CUIforETWDlg::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_STARTTRACING, btStartTracing_);
DDX_Control(pDX, IDC_SAVETRACEBUFFERS, btSaveTraceBuffers_);
DDX_Control(pDX, IDC_STOPTRACING, btStopTracing_);
DDX_Control(pDX, IDC_COMPRESSTRACE, btCompress_);
DDX_Control(pDX, IDC_CPUSAMPLINGCALLSTACKS, btSampledStacks_);
DDX_Control(pDX, IDC_CONTEXTSWITCHCALLSTACKS, btCswitchStacks_);
DDX_Control(pDX, IDC_FASTSAMPLING, btFastSampling_);
DDX_Control(pDX, IDC_GPUTRACING, btGPUTracing_);
DDX_Control(pDX, IDC_CLRTRACING, btCLRTracing_);
DDX_Control(pDX, IDC_SHOWCOMMANDS, btShowCommands_);
DDX_Control(pDX, IDC_INPUTTRACING, btInputTracing_);
DDX_Control(pDX, IDC_INPUTTRACING_LABEL, btInputTracingLabel_);
DDX_Control(pDX, IDC_TRACINGMODE, btTracingMode_);
DDX_Control(pDX, IDC_TRACELIST, btTraces_);
DDX_Control(pDX, IDC_TRACENOTES, btTraceNotes_);
DDX_Control(pDX, IDC_OUTPUT, btOutput_);
DDX_Control(pDX, IDC_TRACENAMEEDIT, btTraceNameEdit_);
CDialog::DoDataExchange(pDX);
}
// Hook up functions to messages from buttons, menus, etc.
BEGIN_MESSAGE_MAP(CUIforETWDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_STARTTRACING, &CUIforETWDlg::OnBnClickedStarttracing)
ON_BN_CLICKED(IDC_STOPTRACING, &CUIforETWDlg::OnBnClickedStoptracing)
ON_BN_CLICKED(IDC_COMPRESSTRACE, &CUIforETWDlg::OnBnClickedCompresstrace)
ON_BN_CLICKED(IDC_CPUSAMPLINGCALLSTACKS, &CUIforETWDlg::OnBnClickedCpusamplingcallstacks)
ON_BN_CLICKED(IDC_CONTEXTSWITCHCALLSTACKS, &CUIforETWDlg::OnBnClickedContextswitchcallstacks)
ON_BN_CLICKED(IDC_SHOWCOMMANDS, &CUIforETWDlg::OnBnClickedShowcommands)
ON_BN_CLICKED(IDC_FASTSAMPLING, &CUIforETWDlg::OnBnClickedFastsampling)
ON_CBN_SELCHANGE(IDC_INPUTTRACING, &CUIforETWDlg::OnCbnSelchangeInputtracing)
ON_MESSAGE(WM_UPDATETRACELIST, &CUIforETWDlg::UpdateTraceListHandler)
ON_MESSAGE(WM_NEWVERSIONAVAILABLE, &CUIforETWDlg::NewVersionAvailable)
ON_LBN_DBLCLK(IDC_TRACELIST, &CUIforETWDlg::OnLbnDblclkTracelist)
ON_WM_GETMINMAXINFO()
ON_WM_SIZE()
ON_LBN_SELCHANGE(IDC_TRACELIST, &CUIforETWDlg::OnLbnSelchangeTracelist)
ON_BN_CLICKED(IDC_ABOUT, &CUIforETWDlg::OnBnClickedAbout)
ON_BN_CLICKED(IDC_SAVETRACEBUFFERS, &CUIforETWDlg::OnBnClickedSavetracebuffers)
ON_MESSAGE(WM_HOTKEY, &CUIforETWDlg::OnHotKey)
ON_WM_CLOSE()
ON_CBN_SELCHANGE(IDC_TRACINGMODE, &CUIforETWDlg::OnCbnSelchangeTracingmode)
ON_BN_CLICKED(IDC_SETTINGS, &CUIforETWDlg::OnBnClickedSettings)
ON_WM_CONTEXTMENU()
ON_BN_CLICKED(ID_TRACES_OPENTRACEIN10WPA, &CUIforETWDlg::OnOpenTrace10WPA)
ON_BN_CLICKED(ID_TRACES_OPENTRACEINGPUVIEW, &CUIforETWDlg::OnOpenTraceGPUView)
ON_BN_CLICKED(ID_RENAME, &CUIforETWDlg::OnRenameKey)
ON_BN_CLICKED(ID_RENAMEFULL, &CUIforETWDlg::OnFullRenameKey)
ON_EN_KILLFOCUS(IDC_TRACENAMEEDIT, &CUIforETWDlg::FinishTraceRename)
ON_BN_CLICKED(ID_ENDRENAME, &CUIforETWDlg::FinishTraceRename)
ON_BN_CLICKED(ID_ESCKEY, &CUIforETWDlg::CancelTraceRename)
ON_BN_CLICKED(IDC_GPUTRACING, &CUIforETWDlg::OnBnClickedGPUtracing)
ON_BN_CLICKED(ID_COPYTRACENAME, &CUIforETWDlg::CopyTraceName)
ON_BN_CLICKED(ID_DELETETRACE, &CUIforETWDlg::DeleteTrace)
ON_BN_CLICKED(ID_SELECTALL, &CUIforETWDlg::NotesSelectAll)
ON_BN_CLICKED(ID_PASTEOVERRIDE, &CUIforETWDlg::NotesPaste)
ON_WM_ACTIVATE()
ON_WM_TIMER()
ON_BN_CLICKED(IDC_CLRTRACING, &CUIforETWDlg::OnBnClickedClrtracing)
END_MESSAGE_MAP()
void CUIforETWDlg::SetSymbolPath()
{
// Make sure that the symbol paths are set.
if (bManageSymbolPath_ || GetEnvironmentVariableString(L"_NT_SYMBOL_PATH").empty())
{
bManageSymbolPath_ = true;
std::string symbolPath = "SRV*" + systemDrive_ + "symbols*https://msdl.microsoft.com/download/symbols";
if (bChromeDeveloper_)
symbolPath = "SRV*" + systemDrive_ + "symbols*https://msdl.microsoft.com/download/symbols;SRV*" + systemDrive_ + "symbols*https://chromium-browser-symsrv.commondatastorage.googleapis.com";
(void)_putenv(("_NT_SYMBOL_PATH=" + symbolPath).c_str());
outputPrintf(L"\nSetting _NT_SYMBOL_PATH=%s (Microsoft%s). "
L"Set _NT_SYMBOL_PATH yourself or toggle 'Chrome developer' if you want different defaults.\n",
AnsiToUnicode(symbolPath).c_str(), bChromeDeveloper_ ? L" plus Chrome" : L"");
}
const std::wstring symCachePath = GetEnvironmentVariableString(L"_NT_SYMCACHE_PATH");
if (symCachePath.empty())
(void)_putenv(("_NT_SYMCACHE_PATH=" + systemDrive_ + "symcache").c_str());
}
void CUIforETWDlg::CheckSymbolDLLs()
{
// Starting with the 10.0.14393.33 (Windows 10 Anniversary) edition of
// WPT the latest version of symsrv.dll *must* be used. So, old copies
// in the WPT directory have to be deleted. Failing to do this will cause
// heap corruption and other crashes because WPT expects a thread-safe
// symsrv.dll, and the old versions aren't. Also, dbghelp.dll is rarely
// needed so it is deleted at the same time.
// Previously the old copies were used to handle these issues:
// https://randomascii.wordpress.com/2012/10/04/xperf-symbol-loading-pitfalls/
const wchar_t* const fileNames[] =
{
L"dbghelp.dll",
L"symsrv.dll",
};
std::vector<std::wstring> filePaths;
for (size_t i = 0; i < ARRAYSIZE(fileNames); ++i)
{
std::wstring filepath = wpt10Dir_ + fileNames[i];
if (PathFileExists(filepath.c_str()))
filePaths.push_back(std::move(filepath));
}
if (!filePaths.empty())
DeleteFiles(*this, filePaths);
#if defined(_WIN64)
const std::wstring symsrv_path = CanonicalizePath(wpt10Dir_ + L"..\\Debuggers\\x64\\symsrv.dll");
#else
const std::wstring symsrv_path = CanonicalizePath(wpt10Dir_ + L"..\\Debuggers\\x86\\symsrv.dll");
#endif
if (!PathFileExists(symsrv_path.c_str()))
{
AfxMessageBox((L"symsrv.dll (" + symsrv_path +
L") not found. Be sure to install the Windows 10 Anniversary Edition Debuggers "
L"or else symbol servers will not work.").c_str());
}
// Previous versions of symsrv.dll may not be multithreading safe and therefore can't
// be used with the latest WPA.
const int64_t requiredSymsrvVersion = (10llu << 48) + 0 + (14321llu << 16) + (1024llu << 0);
const auto symsrvVersion = GetFileVersion(symsrv_path);
if (symsrvVersion < requiredSymsrvVersion)
{
AfxMessageBox((L"symsrv.dll (" + symsrv_path +
L") is not the required version (10.0.14321.1024 or higher). "
L"Be sure to install the Windows 10 Anniversary Edition Debuggers "
L"or else symbol servers will not work.").c_str());
}
}
BOOL CUIforETWDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Load the F2 (rename) and ESC (silently swallow ESC) accelerators
hAccelTable_ = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATORS));
// Load the Enter accelerator for exiting renaming.
hRenameAccelTable_ = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_RENAMEACCELERATORS));
// Load the accelerators for when editing trace notes.
hNotesAccelTable_ = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_NOTESACCELERATORS));
// Load the accelerators for when the trace list is active.
hTracesAccelTable_ = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_TRACESACCELERATORS));
CRect windowRect;
GetWindowRect(&windowRect);
initialWidth_ = minWidth_ = lastWidth_ = windowRect.Width();
initialHeight_ = minHeight_ = lastHeight_ = windowRect.Height();
// Ensure previousWidth_ and previousHeight_ are valid
if (previousWidth_ < initialWidth_)
{
previousWidth_ = initialWidth_;
}
if (previousHeight_ < initialHeight_)
{
previousHeight_ = initialHeight_;
}
// Win+Ctrl+R is used to trigger recording of traces. This is compatible with
// wprui. If this is changed then be sure to change the text on *both* buttons
// in the main window.
// It used to be Win+Ctrl+C but the Fall Creators [sic] Update stole that
// shortcut, globally, which I think is a really rude thing to do.
if (!RegisterHotKey(*this, kRecordTraceHotKey, MOD_WIN + MOD_CONTROL, 'R'))
{
AfxMessageBox(L"Couldn't register hot key.");
btSaveTraceBuffers_.SetWindowTextW(L"Sa&ve Trace Buffers");
btStartTracing_.SetWindowTextW(L"Start &Tracing");
}
// Add "About..." menu item to system menu.
static_assert((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX, "IDM_ABOUTBOX must be in the system command range!");
static_assert(IDM_ABOUTBOX < 0xF000, "IDM_ABOUTBOX must be in the system command range!");
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu)
{
CString strAboutMenu;
const BOOL bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
UIETWASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
if (IsWindowsXPOrLesser())
{
AfxMessageBox(L"ETW tracing requires Windows Vista or above.");
exit(10);
}
wchar_t* windowsDir = nullptr;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Windows, 0, NULL, &windowsDir)))
std::terminate();
windowsDir_ = windowsDir;
windowsDir_ += '\\';
CoTaskMemFree(windowsDir);
// ANSI string, not unicode.
systemDrive_ = static_cast<char>(windowsDir_[0]);
systemDrive_ += ":\\";
// The WPT installer is always a 32-bit installer, so we look for it in
// ProgramFilesX86 / WOW6432Node, on 32-bit and 64-bit operating systems.
wpt10Dir_ = ReadRegistryString(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v10.0", L"InstallationFolder", true);
if (!wpt10Dir_.empty())
{
EnsureEndsWithDirSeparator(wpt10Dir_);
wpt10Dir_ += L"Windows Performance Toolkit\\";
}
// If the registry entries were unavailable, fall back to assuming their installation directory.
if (wpt10Dir_.empty())
{
wchar_t* progFilesx86Dir = nullptr;
if (!SUCCEEDED(SHGetKnownFolderPath(FOLDERID_ProgramFilesX86, 0, nullptr, &progFilesx86Dir)))
std::terminate();
std::wstring windowsKitsDir = progFilesx86Dir;
CoTaskMemFree(progFilesx86Dir);
windowsKitsDir += L"\\Windows Kits\\";
if (wpt10Dir_.empty())
{
wpt10Dir_ = windowsKitsDir + L"10\\Windows Performance Toolkit\\";
}
}
auto xperfVersion = GetFileVersion(GetXperfPath());
const int64_t requiredXperfVersion = (10llu << 48) + 0 + (10586llu << 16) + (15llu << 0);
// Windows 10 spring 2019 version, 10.0.18362.1 - requires Windows 8 or higher?
const int64_t preferredXperfVersion = (10llu << 48) + 0 + (18362llu << 16) + (1llu << 0);
wchar_t systemDir[MAX_PATH];
systemDir[0] = 0;
GetSystemDirectory(systemDir, ARRAYSIZE(systemDir));
std::wstring msiExecPath = systemDir + std::wstring(L"\\msiexec.exe");
if (Is64BitWindows() && PathFileExists(msiExecPath.c_str()))
{
// The installers are available as part of etwpackage.zip on
// https://github.com/google/UIforETW/releases
if (IsWindowsSevenOrLesser())
{
// The newest (Anniversary Edition or beyond) WPT doesn't work on Windows 7.
// Install the older 64-bit WPT 10 if needed and if available.
if (xperfVersion < requiredXperfVersion)
{
const std::wstring installPathOld10 = CanonicalizePath(GetExeDir() + L"..\\third_party\\oldwpt10\\WPTx64-x86_en-us.msi");
if (PathFileExists(installPathOld10.c_str()))
{
ChildProcess child(msiExecPath);
std::wstring args = L" /i \"" + installPathOld10 + L"\"";
child.Run(true, L"msiexec.exe" + args);
const DWORD installResult10 = child.GetExitCode();
if (!installResult10)
{
outputPrintf(L"WPT version 10.0.10586 was installed.\n");
}
else
{
outputPrintf(L"Failure code %u while installing WPT 10.\n", installResult10);
}
}
}
}
else
{
// Install 64-bit WPT 10 if needed and if available.
if (xperfVersion < preferredXperfVersion)
{
const std::wstring installPath10 = CanonicalizePath(GetExeDir() + L"..\\third_party\\wpt10\\WPTx64-x86_en-us.msi");
if (PathFileExists(installPath10.c_str()))
{
ChildProcess child(msiExecPath);
std::wstring args = L" /i \"" + installPath10 + L"\"";
child.Run(true, L"msiexec.exe" + args);
const DWORD installResult10 = child.GetExitCode();
if (!installResult10)
{
xperfVersion = GetFileVersion(GetXperfPath());
outputPrintf(L"WPT version %llu.%llu.%llu.%llu was installed.\n",
xperfVersion >> 48, (xperfVersion >> 32) & 0xFFFF,
(xperfVersion >> 16) & 0xFFFF, xperfVersion & 0xFFFF);
}
else
{
outputPrintf(L"Failure code %u while installing WPT 10.\n", installResult10);
}
}
}
xperfVersion = GetFileVersion(GetXperfPath());
}
}
// Because of bugs in the initial WPT 10 we require the TH2 version.
if (xperfVersion < requiredXperfVersion)
{
if (Is64BitWindows())
{
if (xperfVersion)
AfxMessageBox((GetXperfPath() + L" must be version 10.0.10586.15 or higher. If you run UIforETW from etwpackage.zip\n"
L"from https://github.com/google/UIforETW/releases\n"
L"then WPT will be automatically installed. Exiting.").c_str());
else
AfxMessageBox((GetXperfPath() + L" does not exist. If you run UIforETW from etwpackage.zip\n"
L"from https://github.com/google/UIforETW/releases\n"
L"then WPT will be automatically installed. Exiting.").c_str());
}
else
{
if (xperfVersion)
AfxMessageBox((GetXperfPath() + L" must be version 10.0.10586.15 or higher. You'll need to find the installer in the "
L"Windows 10 SDK or you can xcopy install it. Exiting.").c_str());
else
AfxMessageBox((GetXperfPath() + L" does not exist. You'll need to find the installer in the "
L"Windows 10 SDK or you can xcopy install it. Exiting.").c_str());
}
exit(10);
}
if (xperfVersion >= preferredXperfVersion)
{
if (IsWindowsSevenOrLesser())
{
AfxMessageBox(L"The installed version of Windows Performance Toolkit is not compatible with Windows 7. "
L"Please uninstall it and run UIforETW again.");
}
else
{
CheckSymbolDLLs();
}
}
gpuViewPath_ = wpt10Dir_ + L"gpuview\\gpuview.exe";
wpa10Path_ = wpt10Dir_ + L"wpa.exe";
// When WPT has just been installed it will not be in the path, which means
// that Python scripts which rely on xperf.exe being in the path will fail.
// This adds the WPT10 directory to the path. We could just do this when WPT
// has been freshly installed but this seems cleaner.
auto path = GetEnvironmentVariableString(L"path");
path += L';' + wpt10Dir_;
SetEnvironmentVariable(L"path", path.c_str());
// The Media Experience Analyzer is a 64-bit installer, so we look for it in
// ProgramFiles.
wchar_t* progFilesDir = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_ProgramFiles, 0, NULL, &progFilesDir)))
{
mxaPath_ = progFilesDir;
mxaPath_ += L"\\Media eXperience Analyzer\\XA.exe";
}
wchar_t documents[MAX_PATH];
const BOOL getMyDocsResult = SHGetSpecialFolderPath(*this, documents, CSIDL_MYDOCUMENTS, TRUE);
UIETWASSERT(getMyDocsResult);
if (!getMyDocsResult)
{
#ifdef OUTPUT_DEBUG_STRINGS
OutputDebugStringA("Failed to find My Documents directory.\r\n");
#endif
exit(10);
}
std::wstring defaultTraceDir = documents + std::wstring(L"\\etwtraces\\");
traceDir_ = GetDirectory(L"etwtracedir", defaultTraceDir);
// Copy over the startup profiles if they currently don't exist.
CopyStartupProfiles(GetExeDir(), false);
tempTraceDir_ = GetDirectory(L"temp", traceDir_);
SetSymbolPath();
btTraceNameEdit_.GetWindowRect(&traceNameEditRect_);
ScreenToClient(&traceNameEditRect_);
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
if (IsWindowsSevenOrLesser())
{
bCompress_ = false; // ETW trace compression requires Windows 8.0
SmartEnableWindow(btCompress_.m_hWnd, false);
}
CheckDlgButton(IDC_COMPRESSTRACE, bCompress_);
CheckDlgButton(IDC_CONTEXTSWITCHCALLSTACKS, bCswitchStacks_);
CheckDlgButton(IDC_CPUSAMPLINGCALLSTACKS, bSampledStacks_);
CheckDlgButton(IDC_FASTSAMPLING, bFastSampling_);
CheckDlgButton(IDC_GPUTRACING, bGPUTracing_);
CheckDlgButton(IDC_CLRTRACING, bCLRTracing_);
CheckDlgButton(IDC_SHOWCOMMANDS, bShowCommands_);
// If a fast sampling speed is requested then set it now. Note that
// this assumes that the speed will otherwise be normal.
if (bFastSampling_)
SetSamplingSpeed();
btInputTracing_.AddString(L"Off");
btInputTracing_.AddString(L"Private");
btInputTracing_.AddString(L"Full");
btInputTracing_.SetCurSel(InputTracing_);
btTracingMode_.AddString(L"Circular buffer tracing");
btTracingMode_.AddString(L"Tracing to file");
btTracingMode_.AddString(L"Heap tracing to file");
btTracingMode_.SetCurSel(tracingMode_);
UpdateEnabling();
SmartEnableWindow(btTraceNotes_, false); // This window always starts out disabled.
// Don't change traceDir_ because the monitor thread has a pointer to it.
monitorThread_.StartThread(&traceDir_);
// Configure the working set monitor.
workingSetThread_.SetProcessFilter(WSMonitoredProcesses_, bExpensiveWSMonitoring_);
DisablePagingExecutive();
// Fill in the traces list.
UpdateTraceList();
const int numTraces = btTraces_.GetCount();
if (numTraces > 0)
{
// Select the most recent trace.
btTraces_.SetCurSel(numTraces - 1);
UpdateNotesState();
}
if (toolTip_.Create(this))
{
toolTip_.SetMaxTipWidth(400);
toolTip_.Activate(TRUE);
toolTip_.AddTool(&btStartTracing_, L"Start ETW tracing.");
toolTip_.AddTool(&btCompress_, L"Only uncheck this if you record traces on Windows 8 and above and want to analyze "
L"them on Windows 7 and below.\n"
L"Enable ETW trace compression. On Windows 8 and above this compresses traces "
L"as they are saved, making them 5-10x smaller. However compressed traces cannot be loaded on "
L"Windows 7 or earlier. On Windows 7 this setting has no effect.");
toolTip_.AddTool(&btCswitchStacks_, L"This enables recording of call stacks on context switches, from both "
L"the thread being switched in and the readying thread. This should only be disabled if the performance "
L"of functions like WaitForSingleObject and SetEvent appears to be distorted, which can happen when the "
L"context-switch rate is very high.");
toolTip_.AddTool(&btSampledStacks_, L"This enables recording of call stacks on CPU sampling events, which "
L"by default happen at 1 KHz. This should rarely be disabled.");
toolTip_.AddTool(&btFastSampling_, L"Checking this changes the CPU sampling frequency from the default of "
L"~1 KHz to the maximum speed of ~8 KHz. This increases the data rate and thus the size of traces "
L"but can make investigating brief CPU-bound performance problems (such as a single long frame) "
L"more practical.");
toolTip_.AddTool(&btGPUTracing_, L"Check this to allow seeing GPU usage "
L"in WPA, and more data in GPUView.");
toolTip_.AddTool(&btCLRTracing_, L"Check this to record CLR call stacks" );
toolTip_.AddTool(&btShowCommands_, L"This tells UIforETW to display the commands being "
L"executed. This can be helpful for diagnostic purposes but is not normally needed.");
const TCHAR* pInputTip = L"Input tracing inserts custom ETW events into traces which can be helpful when "
L"investigating performance problems that are correlated with user input. The default setting of "
L"'private' records alphabetic keys as 'A' and numeric keys as '0'. The 'full' setting records "
L"alphanumeric details. Both 'private' and 'full' record mouse movement and button clicks. The "
L"'off' setting records no input.";
toolTip_.AddTool(&btInputTracingLabel_, pInputTip);
toolTip_.AddTool(&btInputTracing_, pInputTip);
toolTip_.AddTool(&btTracingMode_, L"Select whether to trace straight to disk or to in-memory circular buffers.");
toolTip_.AddTool(&btTraces_, L"This is a list of all traces found in %etwtracedir%, which defaults to "
L"documents\\etwtraces.");
toolTip_.AddTool(&btTraceNotes_, L"Trace notes are intended for recording information about ETW traces, such "
L"as an analysis of what was discovered in the trace. Trace notes are auto-saved to a parallel text "
L"file - just type your analysis. The notes files will be renamed when you rename traces "
L"through the trace-list context menu.");
}
SetHeapTracing(false);
CheckProcesses();
if (bVersionChecks_)
versionCheckerThread_.StartVersionCheckerThread(this);
const UINT flags = SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOACTIVATE;
// Resize our window per the previous dimensions if we have them
SetWindowPos(nullptr, 0, 0, previousWidth_, previousHeight_, flags);
return TRUE; // return TRUE unless you set the focus to a control
}
std::wstring CUIforETWDlg::wpaDefaultPath() const
{
return wpa10Path_;
}
std::wstring CUIforETWDlg::GetDirectory(PCWSTR env, const std::wstring& defaultDir)
{
// Get a directory (from an environment variable, if set) and make sure it exists.
std::wstring result = defaultDir;
const std::wstring traceDir = GetEnvironmentVariableString(env);
if (!traceDir.empty())
{
result = traceDir;
}
// Make sure the name ends with a backslash.
if (!result.empty() && result[result.size() - 1] != '\\')
result += '\\';
if (!PathFileExists(result.c_str()))
{
(void)_wmkdir(result.c_str());
}
if (!PathIsDirectory(result.c_str()))
{
AfxMessageBox((result + L" is not a directory. Exiting.").c_str());
exit(10);
}
return result;
}
void CUIforETWDlg::RegisterProviders()
{
outputPrintf(L"\n");
// Assume failure. This assures that when we say
// "Chrome providers will not be recorded." it will actually be true.
useChromeProviders_ = false;
std::wstring dllSource = GetExeDir();
// Be sure to register the version of the DLLs that we are actually using.
// This is important when adding new provider tasks, but should not otherwise
// matter.
#ifdef _M_ARM64
dllSource += L"ETWProvidersARM64.dll";
#elif _M_X64
dllSource += L"ETWProviders64.dll";
#elif _M_IX86
dllSource += L"ETWProviders.dll";
#else
#error Unknown CPU type
#endif
const std::wstring temp = GetEnvironmentVariableString(L"temp");
if (temp.empty())
return;
std::wstring dllDest = temp;
dllDest += L"\\ETWProviders.dll";
if (!CopyFile(dllSource.c_str(), dllDest.c_str(), FALSE))
{
outputPrintf(L"Registering of ETW providers failed due to copy error.\n");
return;
}
wchar_t systemDir[MAX_PATH];
systemDir[0] = 0;
GetSystemDirectory(systemDir, ARRAYSIZE(systemDir));
std::wstring wevtPath = systemDir + std::wstring(L"\\wevtutil.exe");
// Register ETWProviders.dll
for (int pass = 0; pass < 2; ++pass)
{
ChildProcess child(wevtPath);
std::wstring args = pass ? L" im" : L" um";
args += L" \"" + GetExeDir() + L"etwproviders.man\"";
if (pass)
{
args += L" /mf:\"" + dllDest + L"\" /rf:\"" + dllDest + L"\"";
}
child.Run(bShowCommands_, L"wevtutil.exe" + args);
}
// Register chrome.dll if some chrome keywords are selected to be recorded.
if (chromeKeywords_ != 0)
{
std::wstring manifestPath = GetExeDir() + L"chrome_events_win.man";
std::wstring dllSuffix = L"chrome.dll";
// DummyChrome.dll has the Chrome manifest compiled into it which is all that
// is actually needed.
std::wstring chromeDllFullPath = GetExeDir() + L"DummyChrome.dll";
if (!PathFileExists(chromeDllFullPath.c_str()))
{
outputPrintf(L"Couldn't find %s.\n", chromeDllFullPath.c_str());
outputPrintf(L"Chrome providers will not be recorded.\n");
return;
}
for (int pass = 0; pass < 2; ++pass)
{
ChildProcess child(wevtPath);
std::wstring args = pass ? L" im" : L" um";
args += L" \"" + manifestPath + L"\"";
if (pass)
{
args += L" \"/mf:" + chromeDllFullPath + L"\" \"/rf:" + chromeDllFullPath + L"\"";
}
child.Run(bShowCommands_, L"wevtutil.exe" + args);
if (pass)
{
const DWORD exitCode = child.GetExitCode();
if (!exitCode)
{
useChromeProviders_ = true;
outputPrintf(L"Chrome providers registered. Chrome providers will be recorded.\n");
}
}
}
}
}
// Tell Windows to keep 64-bit kernel metadata in memory so that
// stack walking will work. Just do it -- don't ask.
void CUIforETWDlg::DisablePagingExecutive()
{
if (Is64BitWindows())
{
const wchar_t* keyName = L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management";
SetRegistryDWORD(HKEY_LOCAL_MACHINE, keyName, L"DisablePagingExecutive", 1);
}
}
void CUIforETWDlg::UpdateEnabling() noexcept
{
SmartEnableWindow(btStartTracing_.m_hWnd, !bIsTracing_);
SmartEnableWindow(btSaveTraceBuffers_.m_hWnd, bIsTracing_);
SmartEnableWindow(btStopTracing_.m_hWnd, bIsTracing_);
SmartEnableWindow(btTracingMode_.m_hWnd, !bIsTracing_);
SmartEnableWindow(btSampledStacks_.m_hWnd, !bIsTracing_);
SmartEnableWindow(btCswitchStacks_.m_hWnd, !bIsTracing_);
SmartEnableWindow(btGPUTracing_.m_hWnd, !bIsTracing_);
SmartEnableWindow(btCLRTracing_.m_hWnd, !bIsTracing_);
}
void CUIforETWDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CATLAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CUIforETWDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
const int cxIcon = GetSystemMetrics(SM_CXICON);
const int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
const int x = (rect.Width() - cxIcon + 1) / 2;
const int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CUIforETWDlg::OnQueryDragIcon() noexcept
{
// HCURSOR and HICON are the same type, so no cast is needed.
return m_hIcon;
}
std::wstring CUIforETWDlg::GetExeDir() const
{
wchar_t exePath[MAX_PATH];
if (GetModuleFileName(0, exePath, ARRAYSIZE(exePath)))
{
wchar_t* lastSlash = wcsrchr(exePath, '\\');
if (lastSlash)
{
lastSlash[1] = 0;
return exePath;
}
}
exit(10);
}
std::wstring CUIforETWDlg::GenerateResultFilename() const
{
std::wstring traceDir = GetTraceDir();
char time[10];
_strtime_s(time);
char date[10];
_strdate_s(date);
int hour, min, sec;
int year, month, day;
const std::wstring username = GetEnvironmentVariableString(L"USERNAME");
wchar_t fileName[MAX_PATH];
// Hilarious /analyze warning on this line from bug in _strtime_s annotation!
// warning C6054: String 'time' might not be zero-terminated.
#pragma warning(suppress : 6054)
if (3 == sscanf_s(time, "%d:%d:%d", &hour, &min, &sec) &&
3 == sscanf_s(date, "%d/%d/%d", &month, &day, &year))
{
// The filenames are chosen to sort by date, with username as the LSB.
swprintf_s(fileName, L"%04d-%02d-%02d_%02d-%02d-%02d_%s", year + 2000, month, day, hour, min, sec, username.c_str());
}
else
{
wcscpy_s(fileName, L"UIforETW");
}
std::wstring filePart = fileName;
if (tracingMode_ == kHeapTracingToFile)
{
for (const auto& tracingName : split(heapTracingExes_, ';'))
filePart += L"_" + CrackFilePart(tracingName);
filePart += L"_heap";
}
return GetTraceDir() + filePart + L".etl";
}
void CUIforETWDlg::StartEventThreads()
{
// Start the input logging thread with the current settings.
SetKeyloggingState(InputTracing_);
// Send occasional timer messages so that we can check for tracing to file
// that has run "too long". Checking every thirty seconds should be fine.
SetTimer(kTimerID, 30000, nullptr);
if (bBackgroundMonitoring_)
{
CPUFrequencyMonitor_.StartThreads();
workingSetThread_.StartThreads();
}
PowerMonitor_.SetPerfCounters(perfCounters_);
PowerMonitor_.StartThreads(bBackgroundMonitoring_ ?
CPowerStatusMonitor::MonitorType::HeavyLoad :
CPowerStatusMonitor::MonitorType::LightLoad);
}
void CUIforETWDlg::StopEventThreads()
{
// Stop the input logging thread.
SetKeyloggingState(kKeyLoggerOff);
KillTimer(kTimerID);
CPUFrequencyMonitor_.StopThreads();
PowerMonitor_.StopThreads();
workingSetThread_.StopThreads();
}
void CUIforETWDlg::OnBnClickedStarttracing()
{
RegisterProviders();
if (tracingMode_ == kTracingToMemory)
outputPrintf(L"\nStarting tracing to in-memory circular buffers...\n");
else if (tracingMode_ == kTracingToFile)
outputPrintf(L"\nStarting tracing to disk...\n");
else if (tracingMode_ == kHeapTracingToFile)
{
auto heapSettings = ParseHeapTracingSettings(heapTracingExes_);
if (heapSettings.pathName.size())
{
outputPrintf(L"");
// Launch and heap-profile the specified process, handy for heap-profiling
// the browser process from startup.
outputPrintf(L"\nLaunching and heap tracing to disk %s...\n", heapSettings.pathName.c_str());
}
else if (heapSettings.processIDs.size())
{
// Heap profile the processes specified by the PIDs (maximum of two).
outputPrintf(L"\nStarting heap tracing to disk of PIDs %s...\n", heapSettings.processIDs.c_str());
}
else