-
Notifications
You must be signed in to change notification settings - Fork 11
/
memwatch.c
2673 lines (2357 loc) · 74.3 KB
/
memwatch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** MEMWATCH.C
** Nonintrusive ANSI C memory leak / overwrite detection
** Copyright (C) 1992-2003 Johan Lindh
** All rights reserved.
** Version 2.71
This file is part of MEMWATCH.
MEMWATCH is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
MEMWATCH 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with MEMWATCH; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**
** 920810 JLI [1.00]
** 920830 JLI [1.10 double-free detection]
** 920912 JLI [1.15 mwPuts, mwGrab/Drop, mwLimit]
** 921022 JLI [1.20 ASSERT and VERIFY]
** 921105 JLI [1.30 C++ support and TRACE]
** 921116 JLI [1.40 mwSetOutFunc]
** 930215 JLI [1.50 modified ASSERT/VERIFY]
** 930327 JLI [1.51 better auto-init & PC-lint support]
** 930506 JLI [1.55 MemWatch class, improved C++ support]
** 930507 JLI [1.60 mwTest & CHECK()]
** 930809 JLI [1.65 Abort/Retry/Ignore]
** 930820 JLI [1.70 data dump when unfreed]
** 931016 JLI [1.72 modified C++ new/delete handling]
** 931108 JLI [1.77 mwSetAssertAction() & some small changes]
** 940110 JLI [1.80 no-mans-land alloc/checking]
** 940328 JLI [2.00 version 2.0 rewrite]
** Improved NML (no-mans-land) support.
** Improved performance (especially for free()ing!).
** Support for 'read-only' buffers (checksums)
** ^^ NOTE: I never did this... maybe I should?
** FBI (free'd block info) tagged before freed blocks
** Exporting of the mwCounter variable
** mwBreakOut() localizes debugger support
** Allocation statistics (global, per-module, per-line)
** Self-repair ability with relinking
** 950913 JLI [2.10 improved garbage handling]
** 951201 JLI [2.11 improved auto-free in emergencies]
** 960125 JLI [X.01 implemented auto-checking using mwAutoCheck()]
** 960514 JLI [2.12 undefining of existing macros]
** 960515 JLI [2.13 possibility to use default new() & delete()]
** 960516 JLI [2.20 suppression of file flushing on unfreed msgs]
** 960516 JLI [2.21 better support for using MEMWATCH with DLL's]
** 960710 JLI [X.02 multiple logs and mwFlushNow()]
** 960801 JLI [2.22 merged X.01 version with current]
** 960805 JLI [2.30 mwIsXXXXAddr() to avoid unneeded GP's]
** 960805 JLI [2.31 merged X.02 version with current]
** 961002 JLI [2.32 support for realloc() + fixed STDERR bug]
** 961222 JLI [2.40 added mwMark() & mwUnmark()]
** 970101 JLI [2.41 added over/underflow checking after failed ASSERT/VERIFY]
** 970113 JLI [2.42 added support for PC-Lint 7.00g]
** 970207 JLI [2.43 added support for strdup()]
** 970209 JLI [2.44 changed default filename to lowercase]
** 970405 JLI [2.45 fixed bug related with atexit() and some C++ compilers]
** 970723 JLI [2.46 added MW_ARI_NULLREAD flag]
** 970813 JLI [2.47 stabilized marker handling]
** 980317 JLI [2.48 ripped out C++ support; wasn't working good anyway]
** 980318 JLI [2.50 improved self-repair facilities & SIGSEGV support]
** 980417 JLI [2.51 more checks for invalid addresses]
** 980512 JLI [2.52 moved MW_ARI_NULLREAD to occur before aborting]
** 990112 JLI [2.53 added check for empty heap to mwIsOwned]
** 990217 JLI [2.55 improved the emergency repairs diagnostics and NML]
** 990224 JLI [2.56 changed ordering of members in structures]
** 990303 JLI [2.57 first maybe-fixit-for-hpux test]
** 990516 JLI [2.58 added 'static' to the definition of mwAutoInit]
** 990517 JLI [2.59 fixed some high-sensitivity warnings]
** 990610 JLI [2.60 fixed some more high-sensitivity warnings]
** 990715 JLI [2.61 changed TRACE/ASSERT/VERIFY macro names]
** 991001 JLI [2.62 added CHECK_BUFFER() and mwTestBuffer()]
** 991007 JLI [2.63 first shot at a 64-bit compatible version]
** 991009 JLI [2.64 undef's strdup() if defined, mwStrdup made const]
** 000704 JLI [2.65 added some more detection for 64-bits]
** 010502 JLI [2.66 incorporated some user fixes]
** [mwRelink() could print out garbage pointer (thanks [email protected])]
** [added array destructor for C++ (thanks [email protected])]
** [added mutex support (thanks [email protected])]
** 010531 JLI [2.67 fix: mwMutexXXX() was declared even if MW_HAVE_MUTEX was not defined]
** 010619 JLI [2.68 fix: mwRealloc() could leave the mutex locked]
** 020918 JLI [2.69 changed to GPL, added C++ array allocation by Howard Cohen]
** 030212 JLI [2.70 mwMalloc() bug for very large allocations (4GB on 32bits)]
** 030520 JLI [2.71 added ULONG_LONG_MAX as a 64-bit detector (thanks Sami Salonen)]
*/
#define __MEMWATCH_C 1
#ifdef MW_NOCPP
#define MEMWATCH_NOCPP
#endif
#ifdef MW_STDIO
#define MEMWATCH_STDIO
#endif
/***********************************************************************
** Include files
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#include <setjmp.h>
#include <time.h>
#include <limits.h>
#include "memwatch.h"
#ifndef toupper
#include <ctype.h>
#endif
#if defined(WIN32) || defined(__WIN32__)
#define MW_HAVE_MUTEX 1
#include <windows.h>
#endif
#if defined(MW_PTHREADS) || defined(HAVE_PTHREAD_H)
#define MW_HAVE_MUTEX 1
#include <pthread.h>
#endif
/***********************************************************************
** Defines & other weird stuff
***********************************************************************/
/*lint -save -e767 */
#define VERSION "2.71" /* the current version number */
#define CHKVAL(mw) (0xFE0180L^(long)mw->count^(long)mw->size^(long)mw->line)
#define FLUSH() mwFlush()
#define TESTS(f,l) if(mwTestAlways) (void)mwTestNow(f,l,1)
#define PRECHK 0x01234567L
#define POSTCHK 0x76543210L
#define mwBUFFER_TO_MW(p) ( (mwData*) (void*) ( ((char*)p)-mwDataSize-mwOverflowZoneSize ) )
/*lint -restore */
#define MW_NML 0x0001
#ifdef _MSC_VER
#define COMMIT "c" /* Microsoft C requires the 'c' to perform as desired */
#else
#define COMMIT "" /* Normal ANSI */
#endif /* _MSC_VER */
#ifdef __cplusplus
#define CPPTEXT "++"
#else
#define CPPTEXT ""
#endif /* __cplusplus */
#ifdef MEMWATCH_STDIO
#define mwSTDERR stderr
#else
#define mwSTDERR mwLog
#endif
#ifdef MW_HAVE_MUTEX
#define MW_MUTEX_INIT() mwMutexInit()
#define MW_MUTEX_TERM() mwMutexTerm()
#define MW_MUTEX_LOCK() mwMutexLock()
#define MW_MUTEX_UNLOCK() mwMutexUnlock()
#else
#define MW_MUTEX_INIT()
#define MW_MUTEX_TERM()
#define MW_MUTEX_LOCK()
#define MW_MUTEX_UNLOCK()
#endif
/***********************************************************************
** If you really, really know what you're doing,
** you can predefine these things yourself.
***********************************************************************/
#ifndef mwBYTE_DEFINED
# if CHAR_BIT != 8
# error need CHAR_BIT to be 8!
# else
typedef unsigned char mwBYTE;
# define mwBYTE_DEFINED 1
# endif
#endif
#if defined(ULONGLONG_MAX) || defined(ULLONG_MAX) || defined(_UI64_MAX) || defined(ULONG_LONG_MAX)
# define mw64BIT 1
# define mwROUNDALLOC_DEFAULT 8
#else
# if UINT_MAX <= 0xFFFFUL
# define mw16BIT 1
# define mwROUNDALLOC_DEFAULT 2
# else
# if ULONG_MAX > 0xFFFFFFFFUL
# define mw64BIT 1
# define mwROUNDALLOC_DEFAULT 8
# else
# define mw32BIT 1
# define mwROUNDALLOC_DEFAULT 4
# endif
# endif
#endif
/* mwROUNDALLOC is the number of bytes to */
/* round up to, to ensure that the end of */
/* the buffer is suitable for storage of */
/* any kind of object */
#ifndef mwROUNDALLOC
# define mwROUNDALLOC mwROUNDALLOC_DEFAULT
#endif
#ifndef mwDWORD_DEFINED
#if ULONG_MAX == 0xFFFFFFFFUL
typedef unsigned long mwDWORD;
#define mwDWORD_DEFINED "unsigned long"
#endif
#endif
#ifndef mwDWORD_DEFINED
#if UINT_MAX == 0xFFFFFFFFUL
typedef unsigned int mwDWORD;
#define mwDWORD_DEFINED "unsigned int"
#endif
#endif
#ifndef mwDWORD_DEFINED
#if USHRT_MAX == 0xFFFFFFFFUL
typedef unsigned short mwDWORD;
#define mwDWORD_DEFINED "unsigned short"
#endif
#endif
#ifndef mwBYTE_DEFINED
#error "can't find out the correct type for a 8 bit scalar"
#endif
#ifndef mwDWORD_DEFINED
#error "can't find out the correct type for a 32 bit scalar"
#endif
/***********************************************************************
** Typedefs & structures
***********************************************************************/
/* main data holding area, precedes actual allocation */
typedef struct mwData_ mwData;
struct mwData_ {
mwData* prev; /* previous allocation in chain */
mwData* next; /* next allocation in chain */
const char* file; /* file name where allocated */
long count; /* action count */
long check; /* integrity check value */
#if 0
long crc; /* data crc value */
#endif
size_t size; /* size of allocation */
int line; /* line number where allocated */
unsigned flag; /* flag word */
};
/* statistics structure */
typedef struct mwStat_ mwStat;
struct mwStat_ {
mwStat* next; /* next statistic buffer */
const char* file;
long total; /* total bytes allocated */
long num; /* total number of allocations */
long max; /* max allocated at one time */
long curr; /* current allocations */
int line;
};
/* grabbing structure, 1K in size */
typedef struct mwGrabData_ mwGrabData;
struct mwGrabData_ {
mwGrabData* next;
int type;
char blob[ 1024 - sizeof(mwGrabData*) - sizeof(int) ];
};
typedef struct mwMarker_ mwMarker;
struct mwMarker_ {
void *host;
char *text;
mwMarker *next;
int level;
};
#if defined(WIN32) || defined(__WIN32__)
typedef HANDLE mwMutex;
#endif
#if defined(MW_PTHREADS) || defined(HAVE_PTHREAD_H)
typedef pthread_mutex_t mwMutex;
#endif
/***********************************************************************
** Static variables
***********************************************************************/
static int mwInited = 0;
static int mwInfoWritten = 0;
static int mwUseAtexit = 0;
static FILE* mwLog = NULL;
static int mwFlushing = 0;
static int mwStatLevel = MW_STAT_DEFAULT;
static int mwNML = MW_NML_DEFAULT;
static int mwFBI = 0;
static long mwAllocLimit = 0L;
static int mwUseLimit = 0;
static long mwNumCurAlloc = 0L;
static mwData* mwHead = NULL;
static mwData* mwTail = NULL;
static int mwDataSize = 0;
static unsigned char mwOverflowZoneTemplate[] = "mEmwAtch";
static int mwOverflowZoneSize = mwROUNDALLOC;
static void (*mwOutFunction)(int) = NULL;
static int (*mwAriFunction)(const char*) = NULL;
static int mwAriAction = MW_ARI_ABORT;
static char mwPrintBuf[MW_TRACE_BUFFER+8];
static unsigned long mwCounter = 0L;
static long mwErrors = 0L;
static int mwTestFlags = 0;
static int mwTestAlways = 0;
static FILE* mwLogB1 = NULL;
static int mwFlushingB1 = 0;
static mwStat* mwStatList = NULL;
static long mwStatTotAlloc = 0L;
static long mwStatMaxAlloc = 0L;
static long mwStatNumAlloc = 0L;
static long mwStatCurAlloc = 0L;
static long mwNmlNumAlloc = 0L;
static long mwNmlCurAlloc = 0L;
static mwGrabData* mwGrabList = NULL;
static long mwGrabSize = 0L;
static void * mwLastFree[MW_FREE_LIST];
static const char *mwLFfile[MW_FREE_LIST];
static int mwLFline[MW_FREE_LIST];
static int mwLFcur = 0;
static mwMarker* mwFirstMark = NULL;
static FILE* mwLogB2 = NULL;
static int mwFlushingB2 = 0;
#ifdef MW_HAVE_MUTEX
static mwMutex mwGlobalMutex;
#endif
/***********************************************************************
** Static function declarations
***********************************************************************/
static void mwAutoInit( void );
static FILE* mwLogR( void );
static void mwLogW( FILE* );
static int mwFlushR( void );
static void mwFlushW( int );
static void mwFlush( void );
static void mwIncErr( void );
static void mwUnlink( mwData*, const char* file, int line );
static int mwRelink( mwData*, const char* file, int line );
static int mwIsHeapOK( mwData *mw );
static int mwIsOwned( mwData* mw, const char* file, int line );
static int mwTestBuf( mwData* mw, const char* file, int line );
static void mwDefaultOutFunc( int );
static void mwWrite( const char* format, ... );
static void mwLogFile( const char* name );
static size_t mwFreeUp( size_t, int );
static const void *mwTestMem( const void *, unsigned, int );
static int mwStrCmpI( const char *s1, const char *s2 );
static int mwTestNow( const char *file, int line, int always_invoked );
static void mwDropAll( void );
static const char *mwGrabType( int type );
static unsigned mwGrab_( unsigned kb, int type, int silent );
static unsigned mwDrop_( unsigned kb, int type, int silent );
static int mwARI( const char* text );
static void mwStatReport( void );
static mwStat* mwStatGet( const char*, int, int );
static void mwStatAlloc( size_t, const char*, int );
static void mwStatFree( size_t, const char*, int );
static int mwCheckOF( const void * p );
static void mwWriteOF( void * p );
static char mwDummy( char c );
#ifdef MW_HAVE_MUTEX
static void mwMutexInit( void );
static void mwMutexTerm( void );
static void mwMutexLock( void );
static void mwMutexUnlock( void );
#endif
extern int gargc;
extern char** gargv;
/***********************************************************************
** System functions
***********************************************************************/
void mwInit( void ) {
time_t tid;
if( mwInited++ > 0 ) return;
MW_MUTEX_INIT();
/* start a log if none is running */
if( mwLogR() == NULL ) mwLogFile( "memwatch.log" );
if( mwLogR() == NULL ) {
int i;
char buf[32];
/* oops, could not open it! */
/* probably because it's already open */
/* so we try some other names */
for( i=1; i<100; i++ ) {
sprintf( buf, "memwat%02d.log", i );
mwLogFile( buf );
if( mwLogR() != NULL ) break;
}
}
/* initialize the statistics */
mwStatList = NULL;
mwStatTotAlloc = 0L;
mwStatCurAlloc = 0L;
mwStatMaxAlloc = 0L;
mwStatNumAlloc = 0L;
mwNmlCurAlloc = 0L;
mwNmlNumAlloc = 0L;
/* calculate the buffer size to use for a mwData */
mwDataSize = sizeof(mwData);
while( mwDataSize % mwROUNDALLOC ) mwDataSize ++;
/* write informational header if needed */
if( !mwInfoWritten ) {
int i;
mwInfoWritten = 1;
(void) time( &tid );
mwWrite(
"\n============="
" MEMWATCH " VERSION " Copyright (C) 1992-1999 Johan Lindh "
"=============\n");
mwWrite( "\nStarted at %s\n", ctime( &tid ) );
mwWrite( "Command line: ");
for (i=1; i<gargc; i++) {
mwWrite( "%s ", gargv[i]);
}
mwWrite( "\n");
/**************************************************************** Generic */
mwWrite( "Modes: " );
#ifdef mwNew
mwWrite( "C++ " );
#endif /* mwNew */
#ifdef __STDC__
mwWrite( "__STDC__ " );
#endif /* __STDC__ */
#ifdef mw16BIT
mwWrite( "16-bit " );
#endif
#ifdef mw32BIT
mwWrite( "32-bit " );
#endif
#ifdef mw64BIT
mwWrite( "64-bit " );
#endif
mwWrite( "mwDWORD==(" mwDWORD_DEFINED ")\n" );
mwWrite( "mwROUNDALLOC==%d sizeof(mwData)==%d mwDataSize==%d\n",
mwROUNDALLOC, sizeof(mwData), mwDataSize );
/**************************************************************** Generic */
/************************************************************ Microsoft C */
#ifdef _MSC_VER
mwWrite( "Compiled using Microsoft C" CPPTEXT
" %d.%02d\n", _MSC_VER / 100, _MSC_VER % 100 );
#endif /* _MSC_VER */
/************************************************************ Microsoft C */
/************************************************************** Borland C */
#ifdef __BORLANDC__
mwWrite( "Compiled using Borland C"
#ifdef __cplusplus
"++ %d.%01d\n", __BCPLUSPLUS__/0x100, (__BCPLUSPLUS__%0x100)/0x10 );
#else
" %d.%01d\n", __BORLANDC__/0x100, (__BORLANDC__%0x100)/0x10 );
#endif /* __cplusplus */
#endif /* __BORLANDC__ */
/************************************************************** Borland C */
/************************************************************** Watcom C */
#ifdef __WATCOMC__
mwWrite( "Compiled using Watcom C %d.%02d ",
__WATCOMC__/100, __WATCOMC__%100 );
#ifdef __FLAT__
mwWrite( "(32-bit flat model)" );
#endif /* __FLAT__ */
mwWrite( "\n" );
#endif /* __WATCOMC__ */
/************************************************************** Watcom C */
mwWrite( "\n" );
FLUSH();
}
if( mwUseAtexit ) (void) atexit( mwAbort );
return;
}
void mwAbort( void ) {
mwData *mw;
mwMarker *mrk;
char *data;
time_t tid;
int c, i, j;
int errors;
tid = time( NULL );
mwWrite( "\nStopped at %s\n", ctime( &tid) );
if( !mwInited )
mwWrite( "internal: mwAbort(): MEMWATCH not initialized!\n" );
/* release the grab list */
mwDropAll();
/* report mwMarked items */
while( mwFirstMark ) {
mrk = mwFirstMark->next;
mwWrite( "mark: %p: %s\n", mwFirstMark->host, mwFirstMark->text );
free( mwFirstMark->text );
free( mwFirstMark );
mwFirstMark = mrk;
mwErrors ++;
}
/* release all still allocated memory */
errors = 0;
while( mwHead != NULL && errors < 3 ) {
if( !mwIsOwned(mwHead, __FILE__, __LINE__ ) ) {
if( errors < 3 )
{
errors ++;
mwWrite( "internal: NML/unfreed scan restarting\n" );
FLUSH();
mwHead = mwHead;
continue;
}
mwWrite( "internal: NML/unfreed scan aborted, heap too damaged\n" );
FLUSH();
break;
}
mwFlushW(0);
if( !(mwHead->flag & MW_NML) ) {
mwErrors++;
data = ((char*)mwHead)+mwDataSize;
mwWrite( "unfreed: <%ld> %s(%d), %ld bytes at %p ",
mwHead->count, mwHead->file, mwHead->line, (long)mwHead->size, data+mwOverflowZoneSize );
if( mwCheckOF( data ) ) {
mwWrite( "[underflowed] ");
FLUSH();
}
if( mwCheckOF( (data+mwOverflowZoneSize+mwHead->size) ) ) {
mwWrite( "[overflowed] ");
FLUSH();
}
mwWrite( " \t{" );
j = 16; if( mwHead->size < 16 ) j = (int) mwHead->size;
for( i=0;i<16;i++ ) {
if( i<j ) mwWrite( "%02X ",
(unsigned char) *(data+mwOverflowZoneSize+i) );
else mwWrite( ".. " );
}
for( i=0;i<j;i++ ) {
c = *(data+mwOverflowZoneSize+i);
if( c < 32 || c > 126 ) c = '.';
mwWrite( "%c", c );
}
mwWrite( "}\n" );
mw = mwHead;
mwUnlink( mw, __FILE__, __LINE__ );
free( mw );
}
else {
data = ((char*)mwHead) + mwDataSize + mwOverflowZoneSize;
if( mwTestMem( data, mwHead->size, MW_VAL_NML ) ) {
mwErrors++;
mwWrite( "wild pointer: <%ld> NoMansLand %p alloc'd at %s(%d)\n",
mwHead->count, data + mwOverflowZoneSize, mwHead->file, mwHead->line );
FLUSH();
}
mwNmlNumAlloc --;
mwNmlCurAlloc -= mwHead->size;
mw = mwHead;
mwUnlink( mw, __FILE__, __LINE__ );
free( mw );
}
}
if( mwNmlNumAlloc ) mwWrite("internal: NoMansLand block counter %ld, not zero\n", mwNmlNumAlloc );
if( mwNmlCurAlloc ) mwWrite("internal: NoMansLand byte counter %ld, not zero\n", mwNmlCurAlloc );
/* report statistics */
mwStatReport();
FLUSH();
mwInited = 0;
mwHead = mwTail = NULL;
if( mwErrors )
fprintf(mwSTDERR,"MEMWATCH detected %ld anomalies\n",mwErrors);
mwLogFile( NULL );
mwErrors = 0;
MW_MUTEX_TERM();
}
void mwTerm( void ) {
if( mwInited == 1 )
{
mwAbort();
return;
}
if( !mwInited )
mwWrite("internal: mwTerm(): MEMWATCH has not been started!\n");
else
mwInited --;
}
void mwStatistics( int level )
{
mwAutoInit();
if( level<0 ) level=0;
if( mwStatLevel != level )
{
mwWrite( "statistics: now collecting on a %s basis\n",
level<1?"global":(level<2?"module":"line") );
mwStatLevel = level;
}
}
void mwAutoCheck( int onoff ) {
mwAutoInit();
mwTestAlways = onoff;
if( onoff ) mwTestFlags = MW_TEST_ALL;
}
void mwSetOutFunc( void (*func)(int) ) {
mwAutoInit();
mwOutFunction = func;
}
static void mwWriteOF( void *p )
{
int i;
unsigned char *ptr;
ptr = (unsigned char*) p;
for( i=0; i<mwOverflowZoneSize; i++ )
{
*(ptr+i) = mwOverflowZoneTemplate[i%8];
}
return;
}
static int mwCheckOF( const void *p )
{
int i;
const unsigned char *ptr;
ptr = (const unsigned char *) p;
for( i=0; i<mwOverflowZoneSize; i++ )
{
if( *(ptr+i) != mwOverflowZoneTemplate[i%8] )
return 1; /* errors found */
}
return 0; /* no errors */
}
int mwTest( const char *file, int line, int items ) {
mwAutoInit();
mwTestFlags = items;
return mwTestNow( file, line, 0 );
}
/*
** Returns zero if there are no errors.
** Returns nonzero if there are errors.
*/
int mwTestBuffer( const char *file, int line, void *p ) {
mwData* mw;
mwAutoInit();
/* do the quick ownership test */
mw = (mwData*) mwBUFFER_TO_MW( p );
if( mwIsOwned( mw, file, line ) ) {
return mwTestBuf( mw, file, line );
}
return 1;
}
void mwBreakOut( const char* cause ) {
fprintf(mwSTDERR, "breakout: %s\n", cause);
mwWrite("breakout: %s\n", cause );
return;
}
/*
** 981217 JLI: is it possible that ->next is not always set?
*/
void * mwMark( void *p, const char *desc, const char *file, unsigned line ) {
mwMarker *mrk;
unsigned n, isnew;
char *buf;
int tot, oflow = 0;
char wherebuf[128];
mwAutoInit();
TESTS(NULL,0);
if( desc == NULL ) desc = "unknown";
if( file == NULL ) file = "unknown";
tot = sprintf( wherebuf, "%.48s called from %s(%d)", desc, file, line );
if( tot >= (int)sizeof(wherebuf) ) { wherebuf[sizeof(wherebuf)-1] = 0; oflow = 1; }
if( p == NULL ) {
mwWrite("mark: %s(%d), no mark for NULL:'%s' may be set\n", file, line, desc );
return p;
}
if( mwFirstMark != NULL && !mwIsReadAddr( mwFirstMark, sizeof( mwMarker ) ) )
{
mwWrite("mark: %s(%d), mwFirstMark (%p) is trashed, can't mark for %s\n",
file, line, mwFirstMark, desc );
return p;
}
for( mrk=mwFirstMark; mrk; mrk=mrk->next )
{
if( mrk->next != NULL && !mwIsReadAddr( mrk->next, sizeof( mwMarker ) ) )
{
mwWrite("mark: %s(%d), mark(%p)->next(%p) is trashed, can't mark for %s\n",
file, line, mrk, mrk->next, desc );
return p;
}
if( mrk->host == p ) break;
}
if( mrk == NULL ) {
isnew = 1;
mrk = (mwMarker*) malloc( sizeof( mwMarker ) );
if( mrk == NULL ) {
mwWrite("mark: %s(%d), no mark for %p:'%s', out of memory\n", file, line, p, desc );
return p;
}
mrk->next = NULL;
n = 0;
}
else {
isnew = 0;
n = strlen( mrk->text );
}
n += strlen( wherebuf );
buf = (char*) malloc( n+3 );
if( buf == NULL ) {
if( isnew ) free( mrk );
mwWrite("mark: %s(%d), no mark for %p:'%s', out of memory\n", file, line, p, desc );
return p;
}
if( isnew ) {
memcpy( buf, wherebuf, n+1 );
mrk->next = mwFirstMark;
mrk->host = p;
mrk->text = buf;
mrk->level = 1;
mwFirstMark = mrk;
}
else {
strcpy( buf, mrk->text );
strcat( buf, ", " );
strcat( buf, wherebuf );
free( mrk->text );
mrk->text = buf;
mrk->level ++;
}
if( oflow ) {
mwIncErr();
mwTrace( " [WARNING: OUTPUT BUFFER OVERFLOW - SYSTEM UNSTABLE]\n" );
}
return p;
}
void* mwUnmark( void *p, const char *file, unsigned line ) {
mwMarker *mrk, *prv;
mrk = mwFirstMark;
prv = NULL;
while( mrk ) {
if( mrk->host == p ) {
if( mrk->level < 2 ) {
if( prv ) prv->next = mrk->next;
else mwFirstMark = mrk->next;
free( mrk->text );
free( mrk );
return p;
}
mrk->level --;
return p;
}
prv = mrk;
mrk = mrk->next;
}
mwWrite("mark: %s(%d), no mark found for %p\n", file, line, p );
return p;
}
/***********************************************************************
** Abort/Retry/Ignore handlers
***********************************************************************/
static int mwARI( const char *estr ) {
char inbuf[81];
int c;
fprintf(mwSTDERR, "\n%s\nMEMWATCH: Abort, Retry or Ignore? ", estr);
(void) fgets(inbuf,sizeof(inbuf),stdin);
for( c=0; inbuf[c] && inbuf[c] <= ' '; c++ ) ;
c = inbuf[c];
if( c == 'R' || c == 'r' ) {
mwBreakOut( estr );
return MW_ARI_RETRY;
}
if( c == 'I' || c == 'i' ) return MW_ARI_IGNORE;
return MW_ARI_ABORT;
}
/* standard ARI handler (exported) */
int mwAriHandler( const char *estr ) {
mwAutoInit();
return mwARI( estr );
}
/* used to set the ARI function */
void mwSetAriFunc( int (*func)(const char *) ) {
mwAutoInit();
mwAriFunction = func;
}
/***********************************************************************
** Allocation handlers
***********************************************************************/
void* mwMalloc( size_t size, const char* file, int line) {
size_t needed;
mwData *mw;
char *ptr;
void *p;
mwAutoInit();
MW_MUTEX_LOCK();
TESTS(file,line);
mwCounter ++;
needed = mwDataSize + mwOverflowZoneSize*2 + size;
if( needed < size )
{
/* theoretical case: req size + mw overhead exceeded size_t limits */
return NULL;
}
/* if this allocation would violate the limit, fail it */
if( mwUseLimit && ((long)size + mwStatCurAlloc > mwAllocLimit) ) {
mwWrite( "limit fail: <%ld> %s(%d), %ld wanted %ld available\n",
mwCounter, file, line, (long)size, mwAllocLimit - mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
mw = (mwData*) malloc( needed );
if( mw == NULL ) {
if( mwFreeUp(needed,0) >= needed ) {
mw = (mwData*) malloc(needed);
if( mw == NULL ) {
mwWrite( "internal: mwFreeUp(%u) reported success, but malloc() fails\n", needed );
mwIncErr();
FLUSH();
}
}
if( mw == NULL ) {
mwWrite( "fail: <%ld> %s(%d), %ld wanted %ld allocated\n",
mwCounter, file, line, (long)size, mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
}
mw->count = mwCounter;
mw->prev = NULL;
mw->next = mwHead;
mw->file = file;
mw->size = size;
mw->line = line;
mw->flag = 0;
mw->check = CHKVAL(mw);
if( mwHead ) mwHead->prev = mw;
mwHead = mw;
if( mwTail == NULL ) mwTail = mw;
ptr = ((char*)mw) + mwDataSize;
mwWriteOF( ptr ); /* '*(long*)ptr = PRECHK;' */
ptr += mwOverflowZoneSize;
p = ptr;
memset( ptr, MW_VAL_NEW, size );
ptr += size;
mwWriteOF( ptr ); /* '*(long*)ptr = POSTCHK;' */
mwNumCurAlloc ++;
mwStatCurAlloc += (long) size;
mwStatTotAlloc += (long) size;
if( mwStatCurAlloc > mwStatMaxAlloc )
mwStatMaxAlloc = mwStatCurAlloc;
mwStatNumAlloc ++;
if( mwStatLevel ) mwStatAlloc( size, file, line );
MW_MUTEX_UNLOCK();
return p;
}
void* mwRealloc( void *p, size_t size, const char* file, int line) {
int oldUseLimit, i;
mwData *mw;
char *ptr;
mwAutoInit();
if( p == NULL ) return mwMalloc( size, file, line );
if( size == 0 ) { mwFree( p, file, line ); return NULL; }
MW_MUTEX_LOCK();
/* do the quick ownership test */
mw = (mwData*) mwBUFFER_TO_MW( p );
if( mwIsOwned( mw, file, line ) ) {
/* if the buffer is an NML, treat this as a double-free */
if( mw->flag & MW_NML )
{
mwIncErr();
if( *((unsigned char*)(mw)+mwDataSize+mwOverflowZoneSize) != MW_VAL_NML )
{
mwWrite( "internal: <%ld> %s(%d), no-mans-land MW-%p is corrupted\n",
mwCounter, file, line, mw );
}
goto check_dbl_free;
}
/* if this allocation would violate the limit, fail it */
if( mwUseLimit && ((long)size + mwStatCurAlloc - (long)mw->size > mwAllocLimit) ) {
TESTS(file,line);
mwCounter ++;
mwWrite( "limit fail: <%ld> %s(%d), %ld wanted %ld available\n",
mwCounter, file, line, (unsigned long)size - mw->size, mwAllocLimit - mwStatCurAlloc );
mwIncErr();
FLUSH();
MW_MUTEX_UNLOCK();
return NULL;
}
/* fake realloc operation */
oldUseLimit = mwUseLimit;
mwUseLimit = 0;
ptr = (char*) mwMalloc( size, file, line );
if( ptr != NULL ) {