forked from KindDragon/vld
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvld.cpp
More file actions
2996 lines (2647 loc) · 110 KB
/
vld.cpp
File metadata and controls
2996 lines (2647 loc) · 110 KB
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
////////////////////////////////////////////////////////////////////////////////
//
// Visual Leak Detector - VisualLeakDetector Class Implementation
// Copyright (c) 2005-2014 VLD Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// See COPYING.txt for the full terms of the GNU Lesser General Public License.
//
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#pragma comment(lib, "dbghelp.lib")
#include <sys/stat.h>
#define VLDBUILD // Declares that we are building Visual Leak Detector.
#include "callstack.h" // Provides a class for handling call stacks.
#include "crtmfcpatch.h" // Provides CRT and MFC patch functions.
#include "map.h" // Provides a lightweight STL-like map template.
#include "ntapi.h" // Provides access to NT APIs.
#include "set.h" // Provides a lightweight STL-like set template.
#include "utility.h" // Provides various utility functions.
#include "vldint.h" // Provides access to the Visual Leak Detector internals.
#include "loaderlock.h"
#include "tchar.h"
#define BLOCK_MAP_RESERVE 64 // This should strike a balance between memory use and a desire to minimize heap hits.
#define HEAP_MAP_RESERVE 2 // Usually there won't be more than a few heaps in the process, so this should be small.
#define MODULE_SET_RESERVE 16 // There are likely to be several modules loaded in the process.
// Imported global variables.
extern vldblockheader_t *g_vldBlockList;
extern HANDLE g_vldHeap;
extern CriticalSection g_vldHeapLock;
// Global variables.
HANDLE g_currentProcess; // Pseudo-handle for the current process.
HANDLE g_currentThread; // Pseudo-handle for the current thread.
HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here).
CriticalSection g_heapMapLock; // Serializes access to the heap and block maps.
ReportHookSet* g_pReportHooks;
DbgHelp g_DbgHelp;
ImageDirectoryEntries g_Ide;
LoadedModules g_LoadedModules;
// The one and only VisualLeakDetector object instance.
__declspec(dllexport) VisualLeakDetector g_vld;
// Patch only this entries in Kernel32.dll and KernelBase.dll
patchentry_t ldrLoadDllPatch [] = {
"LdrLoadDll", NULL, VisualLeakDetector::_LdrLoadDll,
"LdrGetDllHandle", NULL, VisualLeakDetector::_LdrGetDllHandle,
"LdrGetProcedureAddress", NULL, VisualLeakDetector::_LdrGetProcedureAddress,
"LdrLockLoaderLock", NULL, VisualLeakDetector::_LdrLockLoaderLock,
"LdrUnlockLoaderLock", NULL, VisualLeakDetector::_LdrUnlockLoaderLock,
NULL, NULL, NULL
};
moduleentry_t ntdllPatch [] = {
"ntdll.dll", FALSE, NULL, ldrLoadDllPatch,
};
/////////////////////////////////////////////////////////
// We provide our own DllEntryPoint in order to capture the ReturnAddress of the function calling our DllEntryPoint.
// Then we patch this function namely ntdll.dll!LdrpCallInitRoutine or any equivalent NT loader function by calling
// our LdrpCallInitRoutine where we RefreshModules before calling the EntryPoint in order to hook all functions required
// to properly capture all _CRT_INIT memory allocations which include internal CRT startup memory allocations and all
// global and static initializers.
//
// In getLeaksCount(), reportLeaks() and resolveStacks(), we take extra measures to identify and exclude debug and release
// internal CRT allocations from reporting as real memory leaks.
//
// Global and static initializers *might* be reported as memory leaks based on the order being unintialised by _CRT_INIT.
typedef BOOLEAN(NTAPI *PDLL_INIT_ROUTINE)(IN PVOID DllHandle, IN ULONG Reason, IN PCONTEXT Context OPTIONAL);
BOOLEAN WINAPI LdrpCallInitRoutine(IN PVOID BaseAddress, IN ULONG Reason, IN PVOID Context, IN PDLL_INIT_ROUTINE EntryPoint)
{
LoaderLock ll;
if (Reason == DLL_PROCESS_ATTACH) {
g_vld.RefreshModules();
}
return EntryPoint(BaseAddress, Reason, (PCONTEXT)Context);
}
PBYTE NtDllFindDetourAddress(const PBYTE pAddress, SIZE_T dwSize)
{
MEMORY_BASIC_INFORMATION meminfo = { 0 };
if (VirtualQuery(pAddress, &meminfo, sizeof(meminfo))) {
// Find spare bytes at the end of the memory region that are unused
// so we can jump to this address and set up the detour.
PBYTE end = (PBYTE)meminfo.BaseAddress + meminfo.RegionSize;
PBYTE begin = end;
while (((SIZE_T)(end - begin) < dwSize) && (begin != pAddress)) {
if (*(--begin) != 0x00)
end = begin;
}
if (begin != pAddress)
return begin;
}
return NULL;
}
PBYTE NtDllFindParamAddress(const PBYTE pAddress)
{
PBYTE ptr = pAddress;
// Test previous 32 bytes to find the begining address we need to patch
// for 32bit find => push [ebp][14h] => parameters are pushed to stack
// for 64bit find => mov r8,... => parameters are moved to registers r8, edx, rcx
while (pAddress - --ptr < 0x20) {
#ifdef _WIN64
if (((ptr[0] & 0x4D) >= 0x4C) && (ptr[1] == 0x8B) && ((ptr[2] & 0xC7) == ptr[2])) {
#else
if ((ptr[0] == 0xFF) && (ptr[1] == 0x75) && (ptr[2] == 0x14)) {
#endif
return ptr;
}
}
return NULL;
}
PBYTE NtDllFindCallAddress(const PBYTE pAddress)
{
PBYTE ptr = pAddress;
// Test previous 32 bytes to find the begining address we need to patch
// for 32bit find => call [ebp][08h]
// for 64bit find => call <register>
while (pAddress - --ptr < 0x20) {
#ifdef _WIN64
if ((ptr[0] == 0xFF) && ((ptr[1] & 0xD7) == ptr[1])) {
if ((*(ptr - 1) & 0x41) == *(ptr - 1)) {
--ptr;
}
#else
if ((ptr[0] == 0xFF) && (ptr[1] == 0x55) && (ptr[2] == 0x08)) {
#endif
return ptr;
}
}
return NULL;
}
typedef struct _NTDLL_LDR_PATCH {
PBYTE pPatchAddress;
SIZE_T nPatchSize;
BYTE pBackup[0x20];
PBYTE pDetourAddress;
SIZE_T nDetourSize;
BOOL bState;
} NTDLL_LDR_PATCH, *PNTDLL_LDR_PATCH;
NTDLL_LDR_PATCH patch;
BOOL NtDllPatch(const PBYTE pReturnAddress, NTDLL_LDR_PATCH &NtDllPatch)
{
if (NtDllPatch.bState == FALSE) {
#ifdef _WIN64
BYTE ptr[] = { '?', 0x8B, '?' }; // mov r9, r..
BYTE mov[] = { 0x48, 0xB8, '?', '?', '?', '?', '?', '?', '?', '?' }; // mov rax, 0x0000000000000000
BYTE call[] = { 0xFF, 0xD0 }; // call rax
#else
BYTE ptr[] = { 0xFF, 0x75, 0x08 }; // push [ebp][08h]
BYTE mov[] = { 0x90, 0xB8, '?', '?', '?', '?' }; // mov eax, 0x00000000
BYTE call[] = { 0xFF, 0xD0 }; // call eax
#endif
BYTE jmp[] = { 0xE9, '?', '?', '?', '?' }; // jmp 0x00000000
NtDllPatch.pPatchAddress = NtDllFindParamAddress(pReturnAddress);
PBYTE pCallAddress = NtDllFindCallAddress(pReturnAddress);
NtDllPatch.nPatchSize = pReturnAddress - NtDllPatch.pPatchAddress;
SIZE_T nParamSize = pCallAddress - NtDllPatch.pPatchAddress;
NtDllPatch.nDetourSize = _countof(ptr) + nParamSize + _countof(mov) + _countof(jmp);
NtDllPatch.pDetourAddress = NtDllFindDetourAddress(pReturnAddress, NtDllPatch.nDetourSize);
if (NtDllPatch.pPatchAddress && NtDllPatch.pDetourAddress && ((_countof(jmp) + _countof(call)) <= NtDllPatch.nPatchSize)) {
memcpy(NtDllPatch.pBackup, NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize);
DWORD dwProtect = 0;
if (VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, PAGE_EXECUTE_READWRITE, &dwProtect)) {
memset(NtDllPatch.pDetourAddress, 0x90, NtDllPatch.nDetourSize);
#ifdef _WIN64
// Copy original param instructions
memcpy(NtDllPatch.pDetourAddress, NtDllPatch.pPatchAddress, nParamSize);
BYTE reg = 0x00;
LPBYTE icall = NtDllPatch.pPatchAddress + nParamSize - (3 /*instruction size*/ + sizeof(DWORD));
if ((*(LPDWORD)icall & 0x000D8B4C) == 0x000D8B4C) {
// From Windows 10 (1607) calls to the EntryPoint are dispatched through
// __guard_dispatch_icall_fptr. In such case correct the relative address.
DWORD fptr = *(LPDWORD)(icall + 3) + (3 /*instruction size*/ + sizeof(DWORD)) - (DWORD)(NtDllPatch.pDetourAddress - NtDllPatch.pPatchAddress);
memcpy(NtDllPatch.pDetourAddress + nParamSize - sizeof(DWORD), &fptr, sizeof(DWORD));
// Additionally in such case the EntryPoint is held in another register
// that was moved to rax. In such case identify the correct register
// holding the EntryPoint
reg = ((*(icall - 3) & 0xF1) == 0x41 ? 0x08 : 0x00) + (*(icall - 1) & 0x07);
} else {
reg = ((pCallAddress[0] & 0xF1) == 0x41 ? 0x08 : 0x00) + (pCallAddress[pReturnAddress - pCallAddress - 1] & 0x07);
}
// Copy the register that holds the EntryPoint to r9
ptr[0] = 0x4C + ((reg & 0x08) ? 0x01 : 0x00);
ptr[2] = 0xC8 + (reg & 0x07);
memcpy(&NtDllPatch.pDetourAddress[nParamSize], &ptr, _countof(ptr));
#else
// Push EntryPoint as last parameter
memcpy(&NtDllPatch.pDetourAddress[0], &ptr, _countof(ptr));
// Copy original param instructions
memcpy(&NtDllPatch.pDetourAddress[_countof(ptr)], NtDllPatch.pPatchAddress, nParamSize);
#endif
// Move LdrpCallInitRoutine to eax/rax
*(PSIZE_T)(&mov[2]) = (SIZE_T)LdrpCallInitRoutine;
memcpy(&NtDllPatch.pDetourAddress[_countof(ptr) + nParamSize], &mov, _countof(mov));
// Jump to original function
*(DWORD*)(&jmp[1]) = (DWORD)(pReturnAddress - _countof(call) - (NtDllPatch.pDetourAddress + NtDllPatch.nDetourSize));
memcpy(&NtDllPatch.pDetourAddress[_countof(ptr) + nParamSize + _countof(mov)], &jmp, _countof(jmp));
VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, dwProtect, &dwProtect);
if (VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, PAGE_EXECUTE_READWRITE, &dwProtect)) {
memset(NtDllPatch.pPatchAddress, 0x90, NtDllPatch.nPatchSize);
// Jump to detour address
*(DWORD*)(&jmp[1]) = (DWORD)(NtDllPatch.pDetourAddress - (pReturnAddress - _countof(call)));
memcpy(pReturnAddress - _countof(call) - _countof(jmp), &jmp, _countof(jmp));
// Call LdrpCallInitRoutine from eax/rax
memcpy(pReturnAddress - _countof(call), &call, _countof(call));
VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, dwProtect, &dwProtect);
NtDllPatch.bState = TRUE;
}
}
}
}
return NtDllPatch.bState;
}
BOOL NtDllRestore(NTDLL_LDR_PATCH &NtDllPatch)
{
// Restore patched bytes
BOOL bResult = FALSE;
if (NtDllPatch.bState && NtDllPatch.nPatchSize && &NtDllPatch.pBackup[0]) {
DWORD dwProtect = 0;
if (VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, PAGE_EXECUTE_READWRITE, &dwProtect)) {
memcpy(NtDllPatch.pPatchAddress, NtDllPatch.pBackup, NtDllPatch.nPatchSize);
VirtualProtect(NtDllPatch.pPatchAddress, NtDllPatch.nPatchSize, dwProtect, &dwProtect);
if (VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, PAGE_EXECUTE_READWRITE, &dwProtect)) {
memset(NtDllPatch.pDetourAddress, 0x00, NtDllPatch.nDetourSize);
VirtualProtect(NtDllPatch.pDetourAddress, NtDllPatch.nDetourSize, dwProtect, &dwProtect);
bResult = TRUE;
}
}
}
return bResult;
}
#define _DECL_DLLMAIN // for _CRT_INIT
#include <process.h> // for _CRT_INIT
#pragma comment(linker, "/entry:DllEntryPoint")
__declspec(noinline)
BOOL WINAPI DllEntryPoint(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
// Patch/Restore ntdll address that calls the dll entry point
if (fdwReason == DLL_PROCESS_ATTACH) {
NtDllPatch((PBYTE)_ReturnAddress(), patch);
}
if (fdwReason == DLL_PROCESS_ATTACH || fdwReason == DLL_THREAD_ATTACH)
if (!_CRT_INIT(hinstDLL, fdwReason, lpReserved))
return(FALSE);
if (fdwReason == DLL_PROCESS_DETACH || fdwReason == DLL_THREAD_DETACH)
if (!_CRT_INIT(hinstDLL, fdwReason, lpReserved))
return(FALSE);
if (fdwReason == DLL_PROCESS_DETACH) {
NtDllRestore(patch);
}
return(TRUE);
}
/////////////////////////////////////////////////////////
bool IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0,{ 0 }, 0, 0 };
DWORDLONG const dwlConditionMask = VerSetConditionMask(
VerSetConditionMask(
VerSetConditionMask(
0, VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
osvi.dwMajorVersion = wMajorVersion;
osvi.dwMinorVersion = wMinorVersion;
osvi.wServicePackMajor = wServicePackMajor;
return !!VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask);
}
bool IsWindows7OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0);
}
#define _WIN32_WINNT_WIN8 0x0602
bool IsWindows8OrGreater()
{
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0);
}
// Constructor - Initializes private data, loads configuration options, and
// attaches Visual Leak Detector to all other modules loaded into the current
// process.
//
VisualLeakDetector::VisualLeakDetector ()
{
_set_error_mode(_OUT_TO_STDERR);
// Initialize configuration options and related private data.
_wcsnset_s(m_forcedModuleList, MAXMODULELISTLENGTH, '\0', _TRUNCATE);
m_maxDataDump = 0xffffffff;
m_maxTraceFrames = 0xffffffff;
m_options = 0x0;
m_reportFile = NULL;
wcsncpy_s(m_reportFilePath, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE);
m_status = 0x0;
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (ntdll)
{
if (!IsWindows8OrGreater())
{
LdrLoadDll = (LdrLoadDll_t)GetProcAddress(ntdll, "LdrLoadDll");
} else
{
LdrLoadDllWin8 = (LdrLoadDllWin8_t)GetProcAddress(ntdll, "LdrLoadDll");
ldrLoadDllPatch[0].replacement = _LdrLoadDllWin8;
}
RtlAllocateHeap = (RtlAllocateHeap_t)GetProcAddress(ntdll, "RtlAllocateHeap");
RtlFreeHeap = (RtlFreeHeap_t)GetProcAddress(ntdll, "RtlFreeHeap");
RtlReAllocateHeap = (RtlReAllocateHeap_t)GetProcAddress(ntdll, "RtlReAllocateHeap");
LdrGetDllHandle = (LdrGetDllHandle_t)GetProcAddress(ntdll, "LdrGetDllHandle");
LdrGetProcedureAddress = (LdrGetProcedureAddress_t)GetProcAddress(ntdll, "LdrGetProcedureAddress");
LdrUnloadDll = (LdrUnloadDll_t)GetProcAddress(ntdll, "LdrUnloadDll");
LdrLockLoaderLock = (LdrLockLoaderLock_t)GetProcAddress(ntdll, "LdrLockLoaderLock");
LdrUnlockLoaderLock = (LdrUnlockLoaderLock_t)GetProcAddress(ntdll, "LdrUnlockLoaderLock");
}
// Load configuration options.
configure();
if (m_options & VLD_OPT_VLDOFF) {
Report(L"Visual Leak Detector is turned off.\n");
return;
}
HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
HMODULE kernelBase = GetModuleHandleW(L"KernelBase.dll");
if (!IsWindows7OrGreater()) // kernel32.dll
{
if (kernel32)
m_GetProcAddress = (GetProcAddress_t) GetProcAddress(kernel32, "GetProcAddress");
}
else
{
if (kernelBase)
{
m_GetProcAddress = (GetProcAddress_t)GetProcAddress(kernelBase, "GetProcAddress");
m_GetProcAddressForCaller = (GetProcAddressForCaller_t)GetProcAddress(kernelBase, "GetProcAddressForCaller");
}
assert(m_patchTable[0].patchTable == m_kernelbasePatch);
m_patchTable[0].exportModuleName = "kernelbase.dll";
}
// Initialize global variables.
g_currentProcess = GetCurrentProcess();
g_currentThread = GetCurrentThread();
g_processHeap = GetProcessHeap();
LoaderLock ll;
g_heapMapLock.Initialize();
g_vldHeap = HeapCreate(0x0, 0, 0);
g_vldHeapLock.Initialize();
g_pReportHooks = new ReportHookSet;
// Initialize remaining private data.
m_heapMap = new HeapMap;
m_heapMap->reserve(HEAP_MAP_RESERVE);
m_iMalloc = NULL;
m_requestCurr = 1;
m_totalAlloc = 0;
m_curAlloc = 0;
m_maxAlloc = 0;
m_loadedModules = new ModuleSet();
m_optionsLock.Initialize();
m_modulesLock.Initialize();
m_selfTestFile = __FILE__;
m_selfTestLine = 0;
m_tlsIndex = TlsAlloc();
m_tlsLock.Initialize();
m_tlsMap = new TlsMap;
if (m_options & VLD_OPT_SELF_TEST) {
// Self-test mode has been enabled. Intentionally leak a small amount of
// memory so that memory leak self-checking can be verified.
if (m_options & VLD_OPT_UNICODE_REPORT) {
wcsncpy_s(new WCHAR [wcslen(SELFTESTTEXTW) + 1], wcslen(SELFTESTTEXTW) + 1, SELFTESTTEXTW, _TRUNCATE);
m_selfTestLine = __LINE__ - 1;
}
else {
strncpy_s(new CHAR [strlen(SELFTESTTEXTA) + 1], strlen(SELFTESTTEXTA) + 1, SELFTESTTEXTA, _TRUNCATE);
m_selfTestLine = __LINE__ - 1;
}
}
if (m_options & VLD_OPT_START_DISABLED) {
// Memory leak detection will initially be disabled.
m_status |= VLD_STATUS_NEVER_ENABLED;
}
if (m_options & VLD_OPT_REPORT_TO_FILE) {
setupReporting();
}
if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) {
// Insert a slight delay between messages sent to the debugger for
// output. (For working around a bug in VC6 where data sent to the
// debugger gets lost if it's sent too fast).
InsertReportDelay();
}
// This is highly unlikely to happen, but just in case, check to be sure
// we got a valid TLS index.
if (m_tlsIndex == TLS_OUT_OF_INDEXES) {
Report(L"ERROR: Visual Leak Detector could not be installed because thread local"
L" storage could not be allocated.");
return;
}
// Initialize the symbol handler. We use it for obtaining source file/line
// number information and function names for the memory leak report.
LPWSTR symbolpath = buildSymbolSearchPath();
#ifdef NOISY_DBGHELP_DIAGOSTICS
// From MSDN docs about SYMOPT_DEBUG:
/* To view all attempts to load symbols, call SymSetOptions with SYMOPT_DEBUG.
This causes DbgHelp to call the OutputDebugString function with detailed
information on symbol searches, such as the directories it is searching and and error messages.
In other words, this will really pollute the debug output window with extra messages.
To enable this debug output to be displayed to the console without changing your source code,
set the DBGHELP_DBGOUT environment variable to a non-NULL value before calling the SymInitialize function.
To log the information to a file, set the DBGHELP_LOG environment variable to the name of the log file to be used.
*/
g_DbgHelp.SymSetOptions(SYMOPT_DEBUG | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
#else
g_DbgHelp.SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
#endif
DbgTrace(L"dbghelp32.dll %i: SymInitializeW\n", GetCurrentThreadId());
if (!g_DbgHelp.SymInitializeW(g_currentProcess, symbolpath, FALSE)) {
Report(L"WARNING: Visual Leak Detector: The symbol handler failed to initialize (error=%lu).\n"
L" File and function names will probably not be available in call stacks.\n", GetLastError());
}
delete [] symbolpath;
ntdllPatch[0].moduleBase = (UINT_PTR)ntdll;
PatchImport(kernel32, ntdllPatch);
if (kernelBase != NULL)
PatchImport(kernelBase, ntdllPatch);
// Attach Visual Leak Detector to every module loaded in the process.
ModuleSet* newmodules = new ModuleSet();
newmodules->reserve(MODULE_SET_RESERVE);
DbgTrace(L"dbghelp32.dll %i: EnumerateLoadedModulesW64\n", GetCurrentThreadId());
g_LoadedModules.EnumerateLoadedModulesW64(g_currentProcess, addLoadedModule, newmodules);
attachToLoadedModules(newmodules);
ModuleSet* oldmodules = m_loadedModules;
m_loadedModules = newmodules;
delete oldmodules;
m_status |= VLD_STATUS_INSTALLED;
m_dbghlpBase = GetModuleHandleW(L"dbghelp.dll");
if (m_dbghlpBase)
ChangeModuleState(m_dbghlpBase, false);
Report(L"Visual Leak Detector Version " VLDVERSION L" installed.\n");
if (m_status & VLD_STATUS_FORCE_REPORT_TO_FILE) {
// The report is being forced to a file. Let the human know why.
Report(L"NOTE: Visual Leak Detector: Unicode-encoded reporting has been enabled, but the\n"
L" debugger is the only selected report destination. The debugger cannot display\n"
L" Unicode characters, so the report will also be sent to a file. If no file has\n"
L" been specified, the default file name is \"" VLD_DEFAULT_REPORT_FILE_NAME L"\".\n");
}
reportConfig();
}
bool VisualLeakDetector::waitForAllVLDThreads()
{
bool threadsactive = false;
DWORD dwCurProcessID = GetCurrentProcessId();
int waitcount = 0;
// See if any threads that have ever entered VLD's code are still active.
CriticalSectionLocker<> cs(m_tlsLock);
for (TlsMap::Iterator tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) {
if ((*tlsit).second->threadId == GetCurrentThreadId()) {
// Don't wait for the current thread to exit.
continue;
}
HANDLE thread = OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, (*tlsit).second->threadId);
if (thread == NULL) {
// Couldn't query this thread. We'll assume that it exited.
continue; // XXX should we check GetLastError()?
}
if (GetProcessIdOfThread(thread) != dwCurProcessID) {
//The thread ID has been recycled.
CloseHandle(thread);
continue;
}
if (WaitForSingleObject(thread, 10000) == WAIT_TIMEOUT) { // 10 seconds
// There is still at least one other thread running. The CRT
// will stomp it dead when it cleans up, which is not a
// graceful way for a thread to go down. Warn about this,
// and wait until the thread has exited so that we know it
// can't still be off running somewhere in VLD's code.
//
// Since we've been waiting a while, let the human know we are
// still here and alive.
waitcount++;
threadsactive = true;
if (waitcount >= 9) // 90 sec.
{
CloseHandle(thread);
return threadsactive;
}
Report(L"Visual Leak Detector: Waiting for threads to terminate...\n");
}
CloseHandle(thread);
}
return threadsactive;
}
void VisualLeakDetector::checkInternalMemoryLeaks()
{
const char* leakfile = NULL;
size_t count;
WCHAR leakfilew [MAX_PATH];
int leakline = 0;
// Do a memory leak self-check.
SIZE_T internalleaks = 0;
vldblockheader_t *header = g_vldBlockList;
while (header) {
// Doh! VLD still has an internally allocated block!
// This won't ever actually happen, right guys?... guys?
internalleaks++;
leakfile = header->file;
leakline = header->line;
mbstowcs_s(&count, leakfilew, MAX_PATH, leakfile, _TRUNCATE);
Report(L"ERROR: Visual Leak Detector: Detected a memory leak internal to Visual Leak Detector!!\n");
Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", header->serialNumber, VLDBLOCKDATA(header), header->size);
Report(L" Call Stack:\n");
Report(L" %s (%d): Full call stack not available.\n", leakfilew, leakline);
if (m_maxDataDump != 0) {
Report(L" Data:\n");
if (m_options & VLD_OPT_UNICODE_REPORT) {
DumpMemoryW(VLDBLOCKDATA(header), (m_maxDataDump < header->size) ? m_maxDataDump : header->size);
}
else {
DumpMemoryA(VLDBLOCKDATA(header), (m_maxDataDump < header->size) ? m_maxDataDump : header->size);
}
}
Report(L"\n");
header = header->next;
}
if (m_options & VLD_OPT_SELF_TEST) {
if ((internalleaks == 1) && (strcmp(leakfile, m_selfTestFile) == 0) && (leakline == m_selfTestLine)) {
Report(L"Visual Leak Detector passed the memory leak self-test.\n");
}
else {
Report(L"ERROR: Visual Leak Detector: Failed the memory leak self-test.\n");
}
}
}
// Destructor - Detaches Visual Leak Detector from all modules loaded in the
// process, frees internally allocated resources, and generates the memory
// leak report.
//
VisualLeakDetector::~VisualLeakDetector ()
{
LoaderLock ll;
if (m_options & VLD_OPT_VLDOFF) {
// VLD has been turned off.
return;
}
if (m_status & VLD_STATUS_INSTALLED) {
// Detach Visual Leak Detector from all previously attached modules.
DbgTrace(L"dbghelp32.dll %i: EnumerateLoadedModulesW64\n", GetCurrentThreadId());
g_LoadedModules.EnumerateLoadedModulesW64(g_currentProcess, detachFromModule, NULL);
HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
HMODULE kernelBase = GetModuleHandleW(L"KernelBase.dll");
RestoreImport(kernel32, ntdllPatch);
if (kernelBase != NULL)
RestoreImport(kernelBase, ntdllPatch);
BOOL threadsactive = waitForAllVLDThreads();
if (m_status & VLD_STATUS_NEVER_ENABLED) {
// Visual Leak Detector started with leak detection disabled and
// it was never enabled at runtime. A lot of good that does.
Report(L"WARNING: Visual Leak Detector: Memory leak detection was never enabled.\n");
}
else {
// Generate a memory leak report for each heap in the process.
SIZE_T leaks_count = ReportLeaks();
// Show a summary.
if (leaks_count == 0) {
Report(L"No memory leaks detected.\n");
}
else {
Report(L"Visual Leak Detector detected %Iu memory leak", leaks_count);
Report((leaks_count > 1) ? L"s (%Iu bytes).\n" : L" (%Iu bytes).\n", m_curAlloc);
Report(L"Largest number used: %Iu bytes.\n", m_maxAlloc);
Report(L"Total allocations: %Iu bytes.\n", m_totalAlloc);
}
}
// Free resources used by the symbol handler.
DbgTrace(L"dbghelp32.dll %i: SymCleanup\n", GetCurrentThreadId());
if (!g_DbgHelp.SymCleanup(g_currentProcess)) {
Report(L"WARNING: Visual Leak Detector: The symbol handler failed to deallocate resources (error=%lu).\n",
GetLastError());
}
{
// Free internally allocated resources used by the heapmap and blockmap.
CriticalSectionLocker<> cs(g_heapMapLock);
for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) {
BlockMap *blockmap = &(*heapit).second->blockMap;
for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) {
delete (*blockit).second;
}
delete blockmap;
}
delete m_heapMap;
}
delete m_loadedModules;
{
// Free internally allocated resources used for thread local storage.
CriticalSectionLocker<> cs(m_tlsLock);
for (TlsMap::Iterator tlsit = m_tlsMap->begin(); tlsit != m_tlsMap->end(); ++tlsit) {
delete (*tlsit).second;
}
delete m_tlsMap;
}
if (threadsactive) {
Report(L"WARNING: Visual Leak Detector: Some threads appear to have not terminated normally.\n"
L" This could cause inaccurate leak detection results, including false positives.\n");
}
Report(L"Visual Leak Detector is now exiting.\n");
delete g_pReportHooks;
g_pReportHooks = NULL;
checkInternalMemoryLeaks();
}
else {
// VLD failed to load properly.
delete m_heapMap;
delete m_tlsMap;
delete g_pReportHooks;
g_pReportHooks = NULL;
}
HeapDestroy(g_vldHeap);
m_optionsLock.Delete();
m_modulesLock.Delete();
m_tlsLock.Delete();
g_heapMapLock.Delete();
g_vldHeapLock.Delete();
if (m_tlsIndex != TLS_OUT_OF_INDEXES) {
TlsFree(m_tlsIndex);
}
if (m_reportFile != NULL) {
fclose(m_reportFile);
}
// Decrement the library reference count.
FreeLibrary(m_vldBase);
}
////////////////////////////////////////////////////////////////////////////////
//
// Private Leak Detection Functions
//
////////////////////////////////////////////////////////////////////////////////
UINT32 VisualLeakDetector::getModuleState(ModuleSet::Iterator& it, UINT32& moduleFlags)
{
const moduleinfo_t& moduleinfo = *it;
DWORD64 modulebase = (DWORD64) moduleinfo.addrLow;
moduleFlags = 0;
if (!GetCallingModule((UINT_PTR)modulebase)) // module unloaded
return 0;
{
CriticalSectionLocker<> cs(m_modulesLock);
ModuleSet* oldmodules = m_loadedModules;
ModuleSet::Iterator oldit = oldmodules->find(moduleinfo);
if (oldit != oldmodules->end()) // We've seen this "new" module loaded in the process before.
moduleFlags = (*oldit).flags;
else // This is new loaded module
return 1;
}
if (IsModulePatched((HMODULE) modulebase, m_patchTable, _countof(m_patchTable)))
{
// This module is already attached. Just update the module's
// flags, nothing more.
ModuleSet::Muterator updateit;
updateit = it;
(*updateit).flags = moduleFlags;
return 2;
}
// This module may have been attached before and has been
// detached. We'll need to try reattaching to it in case it
// was unloaded and then subsequently reloaded.
return 3;
}
// dbghelp32.dll should be updated in setup folder if you update dbghelp.h
static char dbghelp32_assert[sizeof(IMAGEHLP_MODULE64) == 3256 ? 1 : -1];
// attachtoloadedmodules - Attaches VLD to all modules contained in the provided
// ModuleSet. Not all modules are in the ModuleSet will actually be included
// in leak detection. Only modules that import the global VisualLeakDetector
// class object, or those that are otherwise explicitly included in leak
// detection, will be checked for memory leaks.
//
// When VLD attaches to a module, it means that any of the imports listed in
// the import patch table which are imported by the module, will be redirected
// to VLD's designated replacements.
//
// - newmodules (IN): Pointer to a ModuleSet containing information about any
// loaded modules that need to be attached.
//
// Return Value:
//
// None.
//
VOID VisualLeakDetector::attachToLoadedModules (ModuleSet *newmodules)
{
LoaderLock ll;
CriticalSectionLocker<DbgHelp> locker(g_DbgHelp);
// Iterate through the supplied set, until all modules have been attached.
for (ModuleSet::Iterator newit = newmodules->begin(); newit != newmodules->end(); ++newit)
{
UINT32 moduleFlags = 0x0;
UINT32 state = getModuleState(newit, moduleFlags);
if (state == 0 || state == 2)
continue;
DWORD64 modulebase = (DWORD64) (*newit).addrLow;
LPCWSTR modulename = (*newit).name.c_str();
LPCWSTR modulepath = (*newit).path.c_str();
DWORD modulesize = (DWORD)((*newit).addrHigh - (*newit).addrLow) + 1;
if ((state == 3) && (moduleFlags & VLD_MODULE_SYMBOLSLOADED)) {
// Discard the previously loaded symbols, so we can refresh them.
DbgTrace(L"dbghelp32.dll %i: SymUnloadModule64\n", GetCurrentThreadId());
if (g_DbgHelp.SymUnloadModule64(g_currentProcess, modulebase, locker) == false) {
Report(L"WARNING: Visual Leak Detector: Failed to unload the symbols for %s. Function names and line"
L" numbers shown in the memory leak report for %s may be inaccurate.\n", modulename, modulename);
}
}
// Try to load the module's symbols. This ensures that we have loaded
// the symbols for every module that has ever been loaded into the
// process, guaranteeing the symbols' availability when generating the
// leak report.
IMAGEHLP_MODULE64 moduleimageinfo;
moduleimageinfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
BOOL SymbolsLoaded = g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, modulebase, &moduleimageinfo, locker);
if (!SymbolsLoaded || moduleimageinfo.BaseOfImage != modulebase)
{
DbgTrace(L"dbghelp32.dll %i: SymLoadModuleEx\n", GetCurrentThreadId());
DWORD64 module = g_DbgHelp.SymLoadModuleExW(g_currentProcess, NULL, modulepath, NULL, modulebase, modulesize, NULL, 0, locker);
if (module == modulebase)
{
DbgTrace(L"dbghelp32.dll %i: SymGetModuleInfoW64\n", GetCurrentThreadId());
SymbolsLoaded = g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, modulebase, &moduleimageinfo, locker);
}
}
if (SymbolsLoaded)
moduleFlags |= VLD_MODULE_SYMBOLSLOADED;
if (_wcsicmp(TEXT(VLDDLL), modulename) == 0) {
// What happens when a module goes through it's own portal? Bad things.
// Like infinite recursion. And ugly bald men wearing dresses. VLD
// should not, therefore, attach to itself.
continue;
}
// increase reference count to module
HMODULE modulelocal = NULL;
if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR) modulebase, &modulelocal))
continue;
if (!FindImport(modulelocal, m_vldBase, VLDDLL, "?g_vld@@3VVisualLeakDetector@@A"))
{
// mfc dll's shouldn't be excluded, to have matched number of leaks
// from the statically linked MFC and dynamically
bool patchKnownModule = false;
LPSTR modulenamea;
ConvertModulePathToAscii(modulename, &modulenamea);
for (UINT index = 0; index < _countof(m_patchTable); index++) {
moduleentry_t *entry = &m_patchTable[index];
if (_stricmp(entry->exportModuleName, modulenamea) == 0) {
if (entry->reportLeaks != 0)
patchKnownModule = true;
break;
}
}
delete[] modulenamea;
if (!patchKnownModule)
{
// This module does not import VLD. This means that none of the module's
// sources #included vld.h.
if ((m_options & VLD_OPT_MODULE_LIST_INCLUDE) != 0)
{
if (wcsstr(m_forcedModuleList, modulename) == NULL) {
// Exclude this module from leak detection.
moduleFlags |= VLD_MODULE_EXCLUDED;
}
}
else
{
if (wcsstr(m_forcedModuleList, modulename) != NULL) {
// Exclude this module from leak detection.
moduleFlags |= VLD_MODULE_EXCLUDED;
}
}
}
}
if ((moduleFlags & VLD_MODULE_EXCLUDED) == 0 &&
!(moduleFlags & VLD_MODULE_SYMBOLSLOADED) || (moduleimageinfo.SymType == SymExport)) {
// This module is going to be included in leak detection, but complete
// symbols for this module couldn't be loaded. This means that any stack
// traces through this module may lack information, like line numbers
// and function names.
Report(L"WARNING: Visual Leak Detector: A module, %s, included in memory leak detection\n"
L" does not have any debugging symbols available, or they could not be located.\n"
L" Function names and/or line numbers for this module may not be available.\n", modulename);
}
// Update the module's flags in the "new modules" set.
ModuleSet::Muterator updateit;
updateit = newit;
(*updateit).flags = moduleFlags;
// Attach to the module.
PatchModule(modulelocal, m_patchTable, _countof(m_patchTable));
FreeLibrary(modulelocal);
}
}
// buildsymbolsearchpath - Builds the symbol search path for the symbol handler.
// This helps the symbol handler find the symbols for the application being
// debugged.
//
// Return Value:
//
// Returns a string containing the search path. The caller is responsible for
// freeing the string.
//
LPWSTR VisualLeakDetector::buildSymbolSearchPath ()
{
// Oddly, the symbol handler ignores the link to the PDB embedded in the
// executable image. So, we'll manually add the location of the executable
// to the search path since that is often where the PDB will be located.
WCHAR directory [_MAX_DIR] = {0};
WCHAR drive [_MAX_DRIVE] = {0};
LPWSTR path = new WCHAR [MAX_PATH * 4];
path[0] = L'\0';
HMODULE module = GetModuleHandleW(NULL);
GetModuleFileName(module, path, MAX_PATH);
_wsplitpath_s(path, drive, _MAX_DRIVE, directory, _MAX_DIR, NULL, 0, NULL, 0);
wcsncpy_s(path, MAX_PATH, drive, _TRUNCATE);
path = AppendString(path, directory);
path = AppendString(path, L";");
// When the symbol handler is given a custom symbol search path, it will no
// longer search the default directories (working directory, _NT_SYMBOL_PATH,
// etc...). But we'd like it to still search those directories, so we'll add
// them to our custom search path.
// Append the working directory.
path = AppendString(path, L".\\;");
// Append %_NT_SYMBOL_PATH%.
DWORD envlen = GetEnvironmentVariable(L"_NT_SYMBOL_PATH", NULL, 0);
if (envlen != 0) {
LPWSTR env = new WCHAR [envlen];
if (GetEnvironmentVariable(L"_NT_SYMBOL_PATH", env, envlen) != 0) {
path = AppendString(path, env);
path = AppendString(path, L";");
}
delete [] env;
}
// Append %_NT_ALT_SYMBOL_PATH%.
envlen = GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", NULL, 0);
if (envlen != 0) {
LPWSTR env = new WCHAR [envlen];
if (GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", env, envlen) != 0) {
path = AppendString(path, env);
path = AppendString(path, L";");
}
delete [] env;
}
// Append %_NT_ALTERNATE_SYMBOL_PATH%.
envlen = GetEnvironmentVariable(L"_NT_ALTERNATE_SYMBOL_PATH", NULL, 0);
if (envlen != 0) {
LPWSTR env = new WCHAR [envlen];
if (GetEnvironmentVariable(L"_NT_ALTERNATE_SYMBOL_PATH", env, envlen) != 0) {
path = AppendString(path, env);
path = AppendString(path, L";");
}
delete [] env;
}
#if _MSC_VER > 1900
#error Not supported VS
#endif
// Append Visual Studio 2015/2013/2012/2010/2008 symbols cache directory.
for (UINT n = 9; n <= 14; ++n) {
WCHAR debuggerpath[MAX_PATH] = { 0 };
swprintf(debuggerpath, _countof(debuggerpath), L"Software\\Microsoft\\VisualStudio\\%u.0\\Debugger", n);
HKEY debuggerkey;
WCHAR symbolCacheDir[MAX_PATH] = { 0 };
LSTATUS regstatus = RegOpenKeyExW(HKEY_CURRENT_USER, debuggerpath, 0, KEY_QUERY_VALUE, &debuggerkey);
if (regstatus == ERROR_SUCCESS) {
DWORD valuetype;
DWORD dirLength = MAX_PATH * sizeof(WCHAR);
regstatus = RegQueryValueExW(debuggerkey, L"SymbolCacheDir", NULL, &valuetype, (LPBYTE)&symbolCacheDir, &dirLength);
if (regstatus == ERROR_SUCCESS && valuetype == REG_SZ && symbolCacheDir[0] != NULL && !wcsstr(path, symbolCacheDir)) {
path = AppendString(path, symbolCacheDir);
path = AppendString(path, L"\\MicrosoftPublicSymbols;");
path = AppendString(path, symbolCacheDir);
path = AppendString(path, L";");
}
RegCloseKey(debuggerkey);
}
}
// Remove any quotes from the path. The symbol handler doesn't like them.