-
Notifications
You must be signed in to change notification settings - Fork 402
/
vld.cpp
2726 lines (2464 loc) · 104 KB
/
vld.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
////////////////////////////////////////////////////////////////////////////////
//
// Visual Leak Detector - VisualLeakDetector Class Implementation
// Copyright (c) 2005-2009 Dan Moulding
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
#pragma comment(lib, "dbghelp.lib")
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <sys/stat.h>
#include <windows.h>
#ifndef __out_xcount
#define __out_xcount(x) // Workaround for the specstrings.h bug in the Platform SDK.
#endif
#define DBGHELP_TRANSLATE_TCHAR
#include <dbghelp.h> // Provides symbol handling services.
#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 "vldheap.h" // Provides internal new and delete operators.
#include "vldint.h" // Provides access to the Visual Leak Detector internals.
#define BLOCKMAPRESERVE 64 // This should strike a balance between memory use and a desire to minimize heap hits.
#define HEAPMAPRESERVE 2 // Usually there won't be more than a few heaps in the process, so this should be small.
#define MAXSYMBOLNAMELENGTH 256 // Maximum symbol name length that we will allow. Longer names will be truncated.
#define MODULESETRESERVE 16 // There are likely to be several modules loaded in the process.
// Imported global variables.
extern vldblockheader_t *vldblocklist;
extern HANDLE vldheap;
extern CRITICAL_SECTION vldheaplock;
// Global variables.
HANDLE currentprocess; // Pseudo-handle for the current process.
HANDLE currentthread; // Pseudo-handle for the current thread.
CRITICAL_SECTION imagelock; // Serializes calls to the Debug Help Library PE image access APIs.
HANDLE processheap; // Handle to the process's heap (COM allocations come from here).
CRITICAL_SECTION stackwalklock; // Serializes calls to StackWalk64 from the Debug Help Library.
CRITICAL_SECTION symbollock; // Serializes calls to the Debug Help Library symbols handling APIs.
// The one and only VisualLeakDetector object instance.
__declspec(dllexport) VisualLeakDetector vld;
// Global function pointers for explicit dynamic linking with functions listed
// in the import patch table. Using explicit dynamic linking minimizes VLD's
// footprint by loading only modules that are actually used. These pointers will
// be linked to the real functions the first time they are used.
// The import patch table: lists the heap-related API imports that VLD patches
// through to replacement functions provided by VLD. Having this table simply
// makes it more convenient to add additional IAT patches.
patchentry_t VisualLeakDetector::m_patchtable [] = {
// Win32 heap APIs.
"kernel32.dll", "GetProcAddress", 0x0, _GetProcAddress, // Not heap related, but can be used to obtain pointers to heap functions.
"kernel32.dll", "HeapAlloc", 0x0, _RtlAllocateHeap,
"kernel32.dll", "HeapCreate", 0x0, _HeapCreate,
"kernel32.dll", "HeapDestroy", 0x0, _HeapDestroy,
"kernel32.dll", "HeapFree", 0x0, _RtlFreeHeap,
"kernel32.dll", "HeapReAlloc", 0x0, _RtlReAllocateHeap,
// MFC new operators (exported by ordinal).
// XXX why are the vector new operators missing for mfc42d.dll?
"mfc42d.dll", (LPCSTR)711, 0x0, VS60::mfcd_scalar_new,
"mfc42d.dll", (LPCSTR)712, 0x0, VS60::mfcd__scalar_new_dbg_4p,
"mfc42d.dll", (LPCSTR)714, 0x0, VS60::mfcd__scalar_new_dbg_3p,
"mfc42ud.dll", (LPCSTR)711, 0x0, VS60::mfcud_scalar_new,
"mfc42ud.dll", (LPCSTR)712, 0x0, VS60::mfcud__scalar_new_dbg_4p,
"mfc42ud.dll", (LPCSTR)714, 0x0, VS60::mfcud__scalar_new_dbg_3p,
"mfc70d.dll", (LPCSTR)257, 0x0, VS70::mfcd_vector_new,
"mfc70d.dll", (LPCSTR)258, 0x0, VS70::mfcd__vector_new_dbg_4p,
"mfc70d.dll", (LPCSTR)259, 0x0, VS70::mfcd__vector_new_dbg_3p,
"mfc70d.dll", (LPCSTR)832, 0x0, VS70::mfcd_scalar_new,
"mfc70d.dll", (LPCSTR)833, 0x0, VS70::mfcd__scalar_new_dbg_4p,
"mfc70d.dll", (LPCSTR)834, 0x0, VS70::mfcd__scalar_new_dbg_3p,
"mfc70ud.dll", (LPCSTR)258, 0x0, VS70::mfcud_vector_new,
"mfc70ud.dll", (LPCSTR)259, 0x0, VS70::mfcud__vector_new_dbg_4p,
"mfc70ud.dll", (LPCSTR)260, 0x0, VS70::mfcud__vector_new_dbg_3p,
"mfc70ud.dll", (LPCSTR)833, 0x0, VS70::mfcud_scalar_new,
"mfc70ud.dll", (LPCSTR)834, 0x0, VS70::mfcud__scalar_new_dbg_4p,
"mfc70ud.dll", (LPCSTR)835, 0x0, VS70::mfcud__scalar_new_dbg_3p,
"mfc71d.dll", (LPCSTR)267, 0x0, VS71::mfcd_vector_new,
"mfc71d.dll", (LPCSTR)268, 0x0, VS71::mfcd__vector_new_dbg_4p,
"mfc71d.dll", (LPCSTR)269, 0x0, VS71::mfcd__vector_new_dbg_3p,
"mfc71d.dll", (LPCSTR)893, 0x0, VS71::mfcd_scalar_new,
"mfc71d.dll", (LPCSTR)894, 0x0, VS71::mfcd__scalar_new_dbg_4p,
"mfc71d.dll", (LPCSTR)895, 0x0, VS71::mfcd__scalar_new_dbg_3p,
"mfc71ud.dll", (LPCSTR)267, 0x0, VS71::mfcud_vector_new,
"mfc71ud.dll", (LPCSTR)268, 0x0, VS71::mfcud__vector_new_dbg_4p,
"mfc71ud.dll", (LPCSTR)269, 0x0, VS71::mfcud__vector_new_dbg_3p,
"mfc71ud.dll", (LPCSTR)893, 0x0, VS71::mfcud_scalar_new,
"mfc71ud.dll", (LPCSTR)894, 0x0, VS71::mfcud__scalar_new_dbg_4p,
"mfc71ud.dll", (LPCSTR)895, 0x0, VS71::mfcud__scalar_new_dbg_3p,
"mfc80d.dll", (LPCSTR)267, 0x0, VS80::mfcd_vector_new,
"mfc80d.dll", (LPCSTR)268, 0x0, VS80::mfcd__vector_new_dbg_4p,
"mfc80d.dll", (LPCSTR)269, 0x0, VS80::mfcd__vector_new_dbg_3p,
"mfc80d.dll", (LPCSTR)893, 0x0, VS80::mfcd_scalar_new,
"mfc80d.dll", (LPCSTR)894, 0x0, VS80::mfcd__scalar_new_dbg_4p,
"mfc80d.dll", (LPCSTR)895, 0x0, VS80::mfcd__scalar_new_dbg_3p,
"mfc80ud.dll", (LPCSTR)267, 0x0, VS80::mfcud_vector_new,
"mfc80ud.dll", (LPCSTR)268, 0x0, VS80::mfcud__vector_new_dbg_4p,
"mfc80ud.dll", (LPCSTR)269, 0x0, VS80::mfcud__vector_new_dbg_3p,
"mfc80ud.dll", (LPCSTR)893, 0x0, VS80::mfcud_scalar_new,
"mfc80ud.dll", (LPCSTR)894, 0x0, VS80::mfcud__scalar_new_dbg_4p,
"mfc80ud.dll", (LPCSTR)895, 0x0, VS80::mfcud__scalar_new_dbg_3p,
"mfc90d.dll", (LPCSTR)267, 0x0, VS90::mfcd_vector_new,
"mfc90d.dll", (LPCSTR)268, 0x0, VS90::mfcd__vector_new_dbg_4p,
"mfc90d.dll", (LPCSTR)269, 0x0, VS90::mfcd__vector_new_dbg_3p,
"mfc90d.dll", (LPCSTR)931, 0x0, VS90::mfcd_scalar_new,
"mfc90d.dll", (LPCSTR)932, 0x0, VS90::mfcd__scalar_new_dbg_4p,
"mfc90d.dll", (LPCSTR)933, 0x0, VS90::mfcd__scalar_new_dbg_3p,
"mfc90ud.dll", (LPCSTR)267, 0x0, VS90::mfcud_vector_new,
"mfc90ud.dll", (LPCSTR)268, 0x0, VS90::mfcud__vector_new_dbg_4p,
"mfc90ud.dll", (LPCSTR)269, 0x0, VS90::mfcud__vector_new_dbg_3p,
"mfc90ud.dll", (LPCSTR)935, 0x0, VS90::mfcud_scalar_new,
"mfc90ud.dll", (LPCSTR)936, 0x0, VS90::mfcud__scalar_new_dbg_4p,
"mfc90ud.dll", (LPCSTR)937, 0x0, VS90::mfcud__scalar_new_dbg_3p,
// CRT new operators and heap APIs.
"msvcrtd.dll", "_calloc_dbg", 0x0, VS60::crtd__calloc_dbg,
"msvcrtd.dll", "_malloc_dbg", 0x0, VS60::crtd__malloc_dbg,
"msvcrtd.dll", "_realloc_dbg", 0x0, VS60::crtd__realloc_dbg,
"msvcrtd.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS60::crtd__scalar_new_dbg,
// "msvcrtd.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS60::crtd__vector_new_dbg,
"msvcrtd.dll", "calloc", 0x0, VS60::crtd_calloc,
"msvcrtd.dll", "malloc", 0x0, VS60::crtd_malloc,
"msvcrtd.dll", "realloc", 0x0, VS60::crtd_realloc,
"msvcrtd.dll", "??2@YAPAXI@Z", 0x0, VS60::crtd_scalar_new,
// "msvcrtd.dll", "??_U@YAPAXI@Z", 0x0, VS60::crtd_vector_new,
"msvcr70d.dll", "_calloc_dbg", 0x0, VS70::crtd__calloc_dbg,
"msvcr70d.dll", "_malloc_dbg", 0x0, VS70::crtd__malloc_dbg,
"msvcr70d.dll", "_realloc_dbg", 0x0, VS70::crtd__realloc_dbg,
"msvcr70d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS70::crtd__scalar_new_dbg,
"msvcr70d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS70::crtd__vector_new_dbg,
"msvcr70d.dll", "calloc", 0x0, VS70::crtd_calloc,
"msvcr70d.dll", "malloc", 0x0, VS70::crtd_malloc,
"msvcr70d.dll", "realloc", 0x0, VS70::crtd_realloc,
"msvcr70d.dll", "??2@YAPAXI@Z", 0x0, VS70::crtd_scalar_new,
"msvcr70d.dll", "??_U@YAPAXI@Z", 0x0, VS70::crtd_vector_new,
"msvcr71d.dll", "_calloc_dbg", 0x0, VS71::crtd__calloc_dbg,
"msvcr71d.dll", "_malloc_dbg", 0x0, VS71::crtd__malloc_dbg,
"msvcr71d.dll", "_realloc_dbg", 0x0, VS71::crtd__realloc_dbg,
"msvcr71d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS71::crtd__scalar_new_dbg,
"msvcr71d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS71::crtd__vector_new_dbg,
"msvcr71d.dll", "calloc", 0x0, VS71::crtd_calloc,
"msvcr71d.dll", "malloc", 0x0, VS71::crtd_malloc,
"msvcr71d.dll", "realloc", 0x0, VS71::crtd_realloc,
"msvcr71d.dll", "??2@YAPAXI@Z", 0x0, VS71::crtd_scalar_new,
"msvcr71d.dll", "??_U@YAPAXI@Z", 0x0, VS71::crtd_vector_new,
"msvcr80d.dll", "_calloc_dbg", 0x0, VS80::crtd__calloc_dbg,
"msvcr80d.dll", "_malloc_dbg", 0x0, VS80::crtd__malloc_dbg,
"msvcr80d.dll", "_realloc_dbg", 0x0, VS80::crtd__realloc_dbg,
"msvcr80d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS80::crtd__scalar_new_dbg,
"msvcr80d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS80::crtd__vector_new_dbg,
"msvcr80d.dll", "calloc", 0x0, VS80::crtd_calloc,
"msvcr80d.dll", "malloc", 0x0, VS80::crtd_malloc,
"msvcr80d.dll", "realloc", 0x0, VS80::crtd_realloc,
"msvcr80d.dll", "??2@YAPAXI@Z", 0x0, VS80::crtd_scalar_new,
"msvcr80d.dll", "??_U@YAPAXI@Z", 0x0, VS80::crtd_vector_new,
"msvcr90d.dll", "_calloc_dbg", 0x0, VS90::crtd__calloc_dbg,
"msvcr90d.dll", "_malloc_dbg", 0x0, VS90::crtd__malloc_dbg,
"msvcr90d.dll", "_realloc_dbg", 0x0, VS90::crtd__realloc_dbg,
"msvcr90d.dll", "??2@YAPAXIHPBDH@Z", 0x0, VS90::crtd__scalar_new_dbg,
"msvcr90d.dll", "??_U@YAPAXIHPBDH@Z", 0x0, VS90::crtd__vector_new_dbg,
"msvcr90d.dll", "calloc", 0x0, VS90::crtd_calloc,
"msvcr90d.dll", "malloc", 0x0, VS90::crtd_malloc,
"msvcr90d.dll", "realloc", 0x0, VS90::crtd_realloc,
"msvcr90d.dll", "??2@YAPAXI@Z", 0x0, VS90::crtd_scalar_new,
"msvcr90d.dll", "??_U@YAPAXI@Z", 0x0, VS90::crtd_vector_new,
// NT APIs.
"ntdll.dll", "RtlAllocateHeap", 0x0, _RtlAllocateHeap,
"ntdll.dll", "RtlFreeHeap", 0x0, _RtlFreeHeap,
"ntdll.dll", "RtlReAllocateHeap", 0x0, _RtlReAllocateHeap,
// COM heap APIs.
"ole32.dll", "CoGetMalloc", 0x0, _CoGetMalloc,
"ole32.dll", "CoTaskMemAlloc", 0x0, _CoTaskMemAlloc,
"ole32.dll", "CoTaskMemRealloc", 0x0, _CoTaskMemRealloc
};
// Constructor - Initializes private data, loads configuration options, and
// attaches Visual Leak Detector to all other modules loaded into the current
// process.
//
VisualLeakDetector::VisualLeakDetector ()
{
WCHAR bom = BOM; // Unicode byte-order mark.
HMODULE kernel32;
ModuleSet *newmodules;
HMODULE ntdll;
LPWSTR symbolpath;
// 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;
// Load configuration options.
configure();
if (m_options & VLD_OPT_VLDOFF) {
report(L"Visual Leak Detector is turned off.\n");
return;
}
kernel32 = GetModuleHandle(L"kernel32.dll");
ntdll = GetModuleHandle(L"ntdll.dll");
// Initialize global variables.
currentprocess = GetCurrentProcess();
currentthread = GetCurrentThread();
InitializeCriticalSection(&imagelock);
LdrLoadDll = (LdrLoadDll_t)GetProcAddress(ntdll, "LdrLoadDll");
processheap = GetProcessHeap();
RtlAllocateHeap = (RtlAllocateHeap_t)GetProcAddress(ntdll, "RtlAllocateHeap");
RtlFreeHeap = (RtlFreeHeap_t)GetProcAddress(ntdll, "RtlFreeHeap");
RtlReAllocateHeap = (RtlReAllocateHeap_t)GetProcAddress(ntdll, "RtlReAllocateHeap");
InitializeCriticalSection(&stackwalklock);
InitializeCriticalSection(&symbollock);
vldheap = HeapCreate(0x0, 0, 0);
InitializeCriticalSection(&vldheaplock);
// Initialize remaining private data.
m_heapmap = new HeapMap;
m_heapmap->reserve(HEAPMAPRESERVE);
m_imalloc = NULL;
m_leaksfound = 0;
m_loadedmodules = NULL;
InitializeCriticalSection(&m_loaderlock);
InitializeCriticalSection(&m_maplock);
InitializeCriticalSection(&m_moduleslock);
m_selftestfile = __FILE__;
m_selftestline = 0;
m_tlsindex = TlsAlloc();
InitializeCriticalSection(&m_tlslock);
m_tlsset = new TlsSet;
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) {
// Reporting to file enabled.
if (m_options & VLD_OPT_UNICODE_REPORT) {
// Unicode data encoding has been enabled. Write the byte-order
// mark before anything else gets written to the file. Open the
// file for binary writing.
if (_wfopen_s(&m_reportfile, m_reportfilepath, L"wb") == EINVAL) {
// Couldn't open the file.
m_reportfile = NULL;
}
else {
fwrite(&bom, sizeof(WCHAR), 1, m_reportfile);
setreportencoding(unicode);
}
}
else {
// Open the file in text mode for ASCII output.
if (_wfopen_s(&m_reportfile, m_reportfilepath, L"w") == EINVAL) {
// Couldn't open the file.
m_reportfile = NULL;
}
else {
setreportencoding(ascii);
}
}
if (m_reportfile == NULL) {
report(L"WARNING: Visual Leak Detector: Couldn't open report file for writing: %s\n"
L" The report will be sent to the debugger instead.\n", m_reportfilepath);
}
else {
// Set the "report" function to write to the file.
setreportfile(m_reportfile, m_options & VLD_OPT_REPORT_TO_DEBUGGER);
}
}
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.
symbolpath = buildsymbolsearchpath();
SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);
if (!SymInitializeW(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;
// Patch into kernel32.dll's calls to LdrLoadDll so that VLD can
// dynamically attach to new modules loaded during runtime.
patchimport(kernel32, ntdll, "ntdll.dll", "LdrLoadDll", _LdrLoadDll);
// Attach Visual Leak Detector to every module loaded in the process.
newmodules = new ModuleSet;
newmodules->reserve(MODULESETRESERVE);
EnumerateLoadedModulesW64(currentprocess, addloadedmodule, newmodules);
attachtoloadedmodules(newmodules);
m_loadedmodules = newmodules;
m_status |= VLD_STATUS_INSTALLED;
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();
}
// Destructor - Detaches Visual Leak Detector from all modules loaded in the
// process, frees internally allocated resources, and generates the memory
// leak report.
//
VisualLeakDetector::~VisualLeakDetector ()
{
BlockMap::Iterator blockit;
BlockMap *blockmap;
size_t count;
vldblockheader_t *header;
HANDLE heap;
HeapMap::Iterator heapit;
SIZE_T internalleaks = 0;
const char *leakfile = NULL;
WCHAR leakfilew [MAX_PATH];
int leakline = 0;
ModuleSet::Iterator moduleit;
HANDLE thread;
BOOL threadsactive= FALSE;
TlsSet::Iterator tlsit;
DWORD dwCurProcessID;
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.
EnumerateLoadedModulesW64(currentprocess, detachfrommodule, NULL);
dwCurProcessID = GetCurrentProcessId();
// See if any threads that have ever entered VLD's code are still active.
EnterCriticalSection(&m_tlslock);
for (tlsit = m_tlsset->begin(); tlsit != m_tlsset->end(); ++tlsit) {
if ((*tlsit)->threadid == GetCurrentThreadId()) {
// Don't wait for the current thread to exit.
continue;
}
thread = OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, (*tlsit)->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;
}
while (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.
threadsactive = TRUE;
report(L"Visual Leak Detector: Waiting for threads to terminate...\n");
}
CloseHandle(thread);
}
LeaveCriticalSection(&m_tlslock);
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.
for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) {
heap = (*heapit).first;
reportleaks(heap);
}
// Show a summary.
if (m_leaksfound == 0) {
report(L"No memory leaks detected.\n");
}
else {
report(L"Visual Leak Detector detected %lu memory leak", m_leaksfound);
report((m_leaksfound > 1) ? L"s.\n" : L".\n");
}
}
// Free resources used by the symbol handler.
if (!SymCleanup(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.
for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) {
blockmap = &(*heapit).second->blockmap;
for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) {
delete (*blockit).second->callstack;
delete (*blockit).second;
}
delete blockmap;
}
delete m_heapmap;
// Free internally allocated resources used by the loaded module set.
for (moduleit = m_loadedmodules->begin(); moduleit != m_loadedmodules->end(); ++moduleit) {
delete (*moduleit).name;
delete (*moduleit).path;
}
delete m_loadedmodules;
// Free internally allocated resources used for thread local storage.
for (tlsit = m_tlsset->begin(); tlsit != m_tlsset->end(); ++tlsit) {
delete *tlsit;
}
delete m_tlsset;
// Do a memory leak self-check.
header = 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 %ld at " ADDRESSFORMAT L": %u 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");
}
}
if (threadsactive == TRUE) {
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");
}
else {
// VLD failed to load properly.
delete m_heapmap;
delete m_tlsset;
}
HeapDestroy(vldheap);
DeleteCriticalSection(&imagelock);
DeleteCriticalSection(&m_loaderlock);
DeleteCriticalSection(&m_maplock);
DeleteCriticalSection(&m_moduleslock);
DeleteCriticalSection(&stackwalklock);
DeleteCriticalSection(&symbollock);
DeleteCriticalSection(&vldheaplock);
if (m_tlsindex != TLS_OUT_OF_INDEXES) {
TlsFree(m_tlsindex);
}
if (m_reportfile != NULL) {
fclose(m_reportfile);
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Private Leak Detection Functions
//
////////////////////////////////////////////////////////////////////////////////
// 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)
{
size_t count;
DWORD64 modulebase;
UINT32 moduleflags;
IMAGEHLP_MODULE64 moduleimageinfo;
LPCSTR modulename;
#define MAXMODULENAME (_MAX_FNAME + _MAX_EXT)
WCHAR modulenamew [MAXMODULENAME];
LPCSTR modulepath;
DWORD modulesize;
ModuleSet::Iterator newit;
ModuleSet::Iterator oldit;
ModuleSet *oldmodules;
BOOL refresh;
UINT tablesize = sizeof(m_patchtable) / sizeof(patchentry_t);
ModuleSet::Muterator updateit;
// Iterate through the supplied set, until all modules have been attached.
for (newit = newmodules->begin(); newit != newmodules->end(); ++newit) {
modulebase = (DWORD64)(*newit).addrlow;
moduleflags = 0x0;
modulename = (*newit).name;
modulepath = (*newit).path;
modulesize = (DWORD)((*newit).addrhigh - (*newit).addrlow) + 1;
refresh = FALSE;
EnterCriticalSection(&m_moduleslock);
oldmodules = m_loadedmodules;
if (oldmodules != NULL) {
// This is not the first time we have been called to attach to the
// currently loaded modules.
oldit = oldmodules->find(*newit);
if (oldit != oldmodules->end()) {
// We've seen this "new" module loaded in the process before.
moduleflags = (*oldit).flags;
LeaveCriticalSection(&m_moduleslock);
if (moduleispatched((HMODULE)modulebase, m_patchtable, tablesize)) {
// This module is already attached. Just update the module's
// flags, nothing more.
updateit = newit;
(*updateit).flags = moduleflags;
continue;
}
else {
// 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.
refresh = TRUE;
}
}
else {
LeaveCriticalSection(&m_moduleslock);
}
}
else {
LeaveCriticalSection(&m_moduleslock);
}
EnterCriticalSection(&symbollock);
if ((refresh == TRUE) && (moduleflags & VLD_MODULE_SYMBOLSLOADED)) {
// Discard the previously loaded symbols, so we can refresh them.
if (SymUnloadModule64(currentprocess, modulebase) == 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.", 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.
moduleimageinfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if ((SymGetModuleInfoW64(currentprocess, (DWORD64)modulebase, &moduleimageinfo) == TRUE) ||
((SymLoadModule64(currentprocess, NULL, modulepath, NULL, modulebase, modulesize) == modulebase) &&
(SymGetModuleInfoW64(currentprocess, modulebase, &moduleimageinfo) == TRUE))) {
moduleflags |= VLD_MODULE_SYMBOLSLOADED;
}
LeaveCriticalSection(&symbollock);
if (_stricmp("vld.dll", 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;
}
mbstowcs_s(&count, modulenamew, MAXMODULENAME, modulename, _TRUNCATE);
if ((findimport((HMODULE)modulebase, m_vldbase, "vld.dll", "?vld@@3VVisualLeakDetector@@A") == FALSE) &&
(wcsstr(vld.m_forcedmodulelist, modulenamew) == NULL)) {
// This module does not import VLD. This means that none of the module's
// sources #included vld.h. Exclude this module from leak detection.
moduleflags |= VLD_MODULE_EXCLUDED;
}
else if (!(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.
updateit = newit;
(*updateit).flags = moduleflags;
// Attach to the module.
patchmodule((HMODULE)modulebase, m_patchtable, tablesize);
}
}
// 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 ()
{
WCHAR directory [_MAX_DIR];
WCHAR drive [_MAX_DRIVE];
LPWSTR env;
DWORD envlen;
SIZE_T index;
SIZE_T length;
HMODULE module;
LPWSTR path = new WCHAR [MAX_PATH];
SIZE_T pos = 0;
WCHAR system [MAX_PATH];
WCHAR windows [MAX_PATH];
// 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.
path[0] = L'\0';
module = GetModuleHandle(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);
strapp(&path, directory);
// When the symbol handler is given a custom symbol search path, it will no
// longer search the default directories (working directory, system root,
// 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.
strapp(&path, L";.\\");
// Append the Windows directory.
if (GetWindowsDirectory(windows, MAX_PATH) != 0) {
strapp(&path, L";");
strapp(&path, windows);
}
// Append the system directory.
if (GetSystemDirectory(system, MAX_PATH) != 0) {
strapp(&path, L";");
strapp(&path, system);
}
// Append %_NT_SYMBOL_PATH%.
envlen = GetEnvironmentVariable(L"_NT_SYMBOL_PATH", NULL, 0);
if (envlen != 0) {
env = new WCHAR [envlen];
if (GetEnvironmentVariable(L"_NT_SYMBOL_PATH", env, envlen) != 0) {
strapp(&path, L";");
strapp(&path, env);
}
delete [] env;
}
// Append %_NT_ALT_SYMBOL_PATH%.
envlen = GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", NULL, 0);
if (envlen != 0) {
env = new WCHAR [envlen];
if (GetEnvironmentVariable(L"_NT_ALT_SYMBOL_PATH", env, envlen) != 0) {
strapp(&path, L";");
strapp(&path, env);
}
delete [] env;
}
// Remove any quotes from the path. The symbol handler doesn't like them.
pos = 0;
length = wcslen(path);
while (pos < length) {
if (path[pos] == L'\"') {
for (index = pos; index < length; index++) {
path[index] = path[index + 1];
}
}
pos++;
}
return path;
}
// configure - Configures VLD using values read from the vld.ini file.
//
// Return Value:
//
// None.
//
VOID VisualLeakDetector::configure ()
{
#define BSIZE 64
WCHAR buffer [BSIZE];
WCHAR filename [MAX_PATH];
WCHAR inipath [MAX_PATH];
BOOL keyopen = FALSE;
DWORD length;
HKEY productkey;
LONG regstatus;
struct _stat s;
DWORD valuetype;
if (_wstat(L".\\vld.ini", &s) == 0) {
// Found a copy of vld.ini in the working directory. Use it.
wcsncpy_s(inipath, MAX_PATH, L".\\vld.ini", _TRUNCATE);
}
else {
// Get the location of the vld.ini file from the registry.
regstatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, VLDREGKEYPRODUCT, 0, KEY_QUERY_VALUE, &productkey);
if (regstatus == ERROR_SUCCESS) {
keyopen = TRUE;
regstatus = RegQueryValueEx(productkey, L"IniFile", NULL, &valuetype, (LPBYTE)&inipath, &length);
}
if (keyopen) {
RegCloseKey(productkey);
}
if ((regstatus != ERROR_SUCCESS) || (_wstat(inipath, &s) != 0)) {
// The location of vld.ini could not be read from the registry. As a
// last resort, look in the Windows directory.
wcsncpy_s(inipath, MAX_PATH, L"vld.ini", _TRUNCATE);
}
}
// Read the boolean options.
GetPrivateProfileString(L"Options", L"VLD", L"on", buffer, BSIZE, inipath);
if (strtobool(buffer) == FALSE) {
m_options |= VLD_OPT_VLDOFF;
return;
}
GetPrivateProfileString(L"Options", L"AggregateDuplicates", L"", buffer, BSIZE, inipath);
if (strtobool(buffer) == TRUE) {
m_options |= VLD_OPT_AGGREGATE_DUPLICATES;
}
GetPrivateProfileString(L"Options", L"SelfTest", L"", buffer, BSIZE, inipath);
if (strtobool(buffer) == TRUE) {
m_options |= VLD_OPT_SELF_TEST;
}
GetPrivateProfileString(L"Options", L"SlowDebuggerDump", L"", buffer, BSIZE, inipath);
if (strtobool(buffer) == TRUE) {
m_options |= VLD_OPT_SLOW_DEBUGGER_DUMP;
}
GetPrivateProfileString(L"Options", L"StartDisabled", L"", buffer, BSIZE, inipath);
if (strtobool(buffer) == TRUE) {
m_options |= VLD_OPT_START_DISABLED;
}
GetPrivateProfileString(L"Options", L"TraceInternalFrames", L"", buffer, BSIZE, inipath);
if (strtobool(buffer) == TRUE) {
m_options |= VLD_OPT_TRACE_INTERNAL_FRAMES;
}
// Read the integer configuration options.
m_maxdatadump = GetPrivateProfileInt(L"Options", L"MaxDataDump", VLD_DEFAULT_MAX_DATA_DUMP, inipath);
m_maxtraceframes = GetPrivateProfileInt(L"Options", L"MaxTraceFrames", VLD_DEFAULT_MAX_TRACE_FRAMES, inipath);
if (m_maxtraceframes < 1) {
m_maxtraceframes = VLD_DEFAULT_MAX_TRACE_FRAMES;
}
// Read the force-include module list.
GetPrivateProfileString(L"Options", L"ForceIncludeModules", L"", m_forcedmodulelist, MAXMODULELISTLENGTH, inipath);
_wcslwr_s(m_forcedmodulelist, MAXMODULELISTLENGTH);
// Read the report destination (debugger, file, or both).
GetPrivateProfileString(L"Options", L"ReportFile", L"", filename, MAX_PATH, inipath);
if (wcslen(filename) == 0) {
wcsncpy_s(filename, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE);
}
_wfullpath(m_reportfilepath, filename, MAX_PATH);
GetPrivateProfileString(L"Options", L"ReportTo", L"", buffer, BSIZE, inipath);
if (_wcsicmp(buffer, L"both") == 0) {
m_options |= (VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE);
}
else if (_wcsicmp(buffer, L"file") == 0) {
m_options |= VLD_OPT_REPORT_TO_FILE;
}
else {
m_options |= VLD_OPT_REPORT_TO_DEBUGGER;
}
// Read the report file encoding (ascii or unicode).
GetPrivateProfileString(L"Options", L"ReportEncoding", L"", buffer, BSIZE, inipath);
if (_wcsicmp(buffer, L"unicode") == 0) {
m_options |= VLD_OPT_UNICODE_REPORT;
}
if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) {
// If Unicode report encoding is enabled, then the report needs to be
// sent to a file because the debugger will not display Unicode
// characters, it will display question marks in their place instead.
m_options |= VLD_OPT_REPORT_TO_FILE;
m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE;
}
// Read the stack walking method.
GetPrivateProfileString(L"Options", L"StackWalkMethod", L"", buffer, BSIZE, inipath);
if (_wcsicmp(buffer, L"safe") == 0) {
m_options |= VLD_OPT_SAFE_STACK_WALK;
}
}
// enabled - Determines if memory leak detection is enabled for the current
// thread.
//
// Return Value:
//
// Returns true if Visual Leak Detector is enabled for the current thread.
// Otherwise, returns false.
//
BOOL VisualLeakDetector::enabled ()
{
tls_t *tls = vld.gettls();
if (!(m_status & VLD_STATUS_INSTALLED)) {
// Memory leak detection is not yet enabled because VLD is still
// initializing.
return FALSE;
}
if (!(tls->flags & VLD_TLS_DISABLED) && !(tls->flags & VLD_TLS_ENABLED)) {
// The enabled/disabled state for the current thread has not been
// initialized yet. Use the default state.
if (m_options & VLD_OPT_START_DISABLED) {
tls->flags |= VLD_TLS_DISABLED;
}
else {
tls->flags |= VLD_TLS_ENABLED;
}
}
return ((tls->flags & VLD_TLS_ENABLED) != 0);
}
// eraseduplicates - Erases, from the block maps, blocks that appear to be
// duplicate leaks of an already identified leak.
//
// - element (IN): BlockMap Iterator referencing the block of which to search
// for duplicates.
//
// Return Value:
//
// Returns the number of duplicate blocks erased from the block map.
//
SIZE_T VisualLeakDetector::eraseduplicates (const BlockMap::Iterator &element)
{
BlockMap::Iterator blockit;
BlockMap *blockmap;
blockinfo_t *elementinfo;
SIZE_T erased = 0;
HeapMap::Iterator heapit;
blockinfo_t *info;
BlockMap::Iterator previt;
elementinfo = (*element).second;
// Iteratate through all block maps, looking for blocks with the same size
// and callstack as the specified element.
for (heapit = m_heapmap->begin(); heapit != m_heapmap->end(); ++heapit) {
blockmap = &(*heapit).second->blockmap;
for (blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) {
if (blockit == element) {
// Don't delete the element of which we are searching for
// duplicates.
continue;
}
info = (*blockit).second;
if ((info->size == elementinfo->size) && (*(info->callstack) == *(elementinfo->callstack))) {
// Found a duplicate. Erase it.
delete info->callstack;
delete info;
previt = blockit - 1;
blockmap->erase(blockit);
blockit = previt;
erased++;
}
}
}
return erased;
}
// gettls - Obtains the thread local storage structure for the calling thread.
//
// Return Value:
//
// Returns a pointer to the thread local storage structure. (This function
// always succeeds).
//
tls_t* VisualLeakDetector::gettls ()
{
tls_t *tls;
// Get the pointer to this thread's thread local storage structure.
tls = (tls_t*)TlsGetValue(m_tlsindex);
assert(GetLastError() == ERROR_SUCCESS);
if (tls == NULL) {
// This thread's thread local storage structure has not been allocated.
tls = new tls_t;
TlsSetValue(m_tlsindex, tls);
tls->addrfp = 0x0;
tls->flags = 0x0;
tls->threadid = GetCurrentThreadId();
// Add this thread's TLS to the TlsSet.
EnterCriticalSection(&m_tlslock);
m_tlsset->insert(tls);
LeaveCriticalSection(&m_tlslock);