forked from j256/dmalloc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdmalloc.info
More file actions
3033 lines (2408 loc) · 174 KB
/
dmalloc.info
File metadata and controls
3033 lines (2408 loc) · 174 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
This is dmalloc.info.t, produced by makeinfo version 4.8 from dmalloc.texi.
INFO-DIR-SECTION Libraries
START-INFO-DIR-ENTRY
* Dmalloc: (dmalloc). Malloc debug library.
END-INFO-DIR-ENTRY
This file is an introduction to the Dmalloc library which handles general memory heap management.
Copyright 1992 to 2007 by Gray Watson.
Permission is granted to make and distribute verbatim copies of this manual provided the
copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the
conditions for verbatim copying, provided also that the chapter entitled "Copying" are included
exactly as in the original, and provided that the entire resulting derived work is distributed under
the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language,
under the above conditions for modified versions, except that the chapter entitled "Copying" may be
included in a translation approved by the author instead of in the original English.
File: dmalloc.info.t, Node: Top, Next: Copying, Prev: (dir), Up: (dir)
Debug Malloc Library
********************
Version 5.5.2 - May 2007
The debug memory allocation or "dmalloc" library has been designed as a drop in replacement for the
system's `malloc', `realloc', `calloc', `free' and other memory management routines while providing
powerful debugging facilities configurable at runtime. These facilities include such things as
memory-leak tracking, fence-post write detection, file/line number reporting, and general logging of
statistics.
The library is reasonably portable having been run successfully on at least the following
operating systems: AIX, DGUX, Free/Net/OpenBSD, GNU/Hurd, HPUX, Irix, Linux, Mac OSX, NeXT,
OSF/DUX, SCO, Solaris, Ultrix, Unixware, MS Windows, and Unicos on a Cray T3E. It also provides
support for the debugging of threaded programs. *Note Using With Threads::.
The package includes the library, configuration scripts, debug utility application, test
program, and documentation. Online documentation as well as the full source is available at URL
`http://dmalloc.com/'. Details on the library's mailing list are available there as well.
Please use the forums at URL `http://dmalloc.com/' to discuss any problems or to request
features. If you are still having problems, the author can be reached via his home page at URL
`http://256.com/gray/' with questions or feedback. Please include the version number of the
library that you are using, your machine and operating system types, and the value of the
DMALLOC_OPTIONS environment variable.
Gray Watson.
* Menu:
* Copying:: Library copying and licensing conditions.
* Overview:: Description of features and how to get started.
* Programming:: How to program with the library.
* Dmalloc Program:: How to use the library's utility.
* Source Code:: Information on the source code.
* Troubleshooting:: Some solutions to common problems.
* Index of Concepts:: Index of concepts in the manual.
File: dmalloc.info.t, Node: Copying, Next: Overview, Prev: Top, Up: Top
1 Library Copying and Licensing Conditions
******************************************
Copyright 1992 to 2007 by Gray Watson.
Permission to use, copy, modify, and distribute this software for any purpose and without fee is
hereby granted, provided that the above copyright notice and this permission notice appear in all
copies, and that the name of Gray Watson not be used in advertising or publicity pertaining to
distribution of the document or software without specific, written prior permission.
Gray Watson makes no representations about the suitability of the software described herein for
any purpose. It is provided "as is" without express or implied warranty.
File: dmalloc.info.t, Node: Overview, Next: Programming, Prev: Copying, Up: Top
2 Description of Features and How to Get Started
************************************************
* Menu:
* Installation:: How to install the library.
* Getting Started:: Getting started with the library.
* Allocation Basics:: Basic description of terms and functions.
* Features:: General features of the library.
* How It Works:: How the library checks your program.
File: dmalloc.info.t, Node: Installation, Next: Getting Started, Prev: Overview, Up: Overview
2.1 How to Install the Library
==============================
To configure, compile, and install the library, follow these steps carefully.
1. Make sure you have downloaded the latest version of the library available from the home page
at URL `http://dmalloc.com/'.
2. The release files have a `.tgz' file extension which means that they are a tar'd gzip'd
directory of files. You will need to ungzip and then untar the release file into your source
work directory. You may have to rename the file to `.tar.gz' to get some old zip programs to
handle the file correctly.
3. You may want to edit or at least review the settings in `settings.dist' to tune specific
features of the library. The `configure' script will copy this file to `settings.h' which is
where you should be adding per-architecture settings.
4. Type `sh ./configure' to configure the library. You may want to first examine the
`config.help' file for some information about configure. You may want to use the
`--disable-cxx' option if you do not want the Makefile to build the C++ version of dmalloc.
You may want to use the `--enable-threads' option to build the threaded version of dmalloc.
You may want to use the `--enable-shlib' option to build the shared versions of the dmalloc
libraries. `sh ./configure --help' lists the available options to configure. Configure should
generate the `Makefile' and configuration files automatically.
5. You may want to examine the `Makefile' and `conf.h' files created by configure to make sure it
did its job correctly.
6. You might want to tune the settings in `settings.h' file to tune the library to the local
architecture. This file contains relevant settings if you are using pthreads or another
thread library. *Note Using With Threads::. The `configure' script created this file from
the `settings.dist' file. Any permanent changes to these settings should made to the
`settings.dist' file. You then can run `config.status' to re-create the `settings.h' file.
7. The `DMALLOC_SIZE' variable gets auto-configured in `dmalloc.h.2' but it may not generate
correct settings for all systems. You may have to alter the definitions in this file to get
things to stop complaining when you go to compile about the size arguments to malloc routines.
Comments on this please.
8. Typing `make' should be enough to build `libdmalloc.a', and `dmalloc' program. If it does not
work, please see if there are any notes in the contrib directory about your system-type. If
not and you figure your problem out, please send me some notes so future users can profit from
your experiences.
_NOTE_: You may experience some errors compiling some of the `return.h' assembly macros which
attempt to determine the callers address for logging purposes. *Note Portability::. You may
want to first try disabling any compiler optimization flags. If this doesn't work then you
may need to disable the `USE_RETURN_MACROS' variable in the `settings.h' file.
_NOTE_: The code is dependent on an ANSI-C compiler. If the configure script gives the
`WARNING' that you do not have an ANSI-C compiler, you may still be able to add some sort of
option to your compiler to make it ANSI. If there such is an option, please send it to the
author so it can be added to the configure script.
9. If you use threads and did not add the `--enable-threads' argument to configure, typing `make
threads' should be enough to build `libdmallocth.a' which is the threaded version of the
library. This may or may not work depending on the configuration scripts ability to detect
your local thread functionality. Feel free to send me mail with improvements.
See the section of the manual on threads for more information about the operation of the
library with your threaded program. *Note Using With Threads::.
10. If you have a C++ compiler installed, the library should have automatically built
`libdmallocxx.a' which is the C++ version of the library. If it was not done automatically,
you can build it by typing `make cxx'. You should link this library into your C++ programs
instead of `libdmalloc.a'. See the `dmallocc.cc' C++ file which contains basic code to
overload the `new', `new[]', `delete', and `delete[]' C++ operators. My apologies on the
minimal C++ support. I am still living in a mostly C world. Any help improving this
interface without sacrificing portability would be appreciated.
11. Typing `make light' should build and run the `dmalloc_t' test program through a set of light
trials. By default this will execute `dmalloc_t' 5 times - each time will execute 10,000
malloc operations in a very random manner. Anal folks can type `make heavy' to up the ante.
Use `dmalloc_t --usage' for the list of all `dmalloc_t' options.
12. Typing `make install' should install the `libdmalloc.a' library in `/usr/local/lib', the
`dmalloc.h' include file in `/usr/local/include', and the `dmalloc' utility in
`/usr/local/bin'. You may also want to type `make installth' to install the thread library
into place and/or `make installcc' to install the C++ library into place.
You may have specified a `--prefix=PATH' option to configure in which case `/usr/local' will
have been replaced with `PATH'.
See the "Getting Started" section to get up and running with the library. *Note Getting
Started::.
File: dmalloc.info.t, Node: Getting Started, Next: Allocation Basics, Prev: Installation, Up: Overview
2.2 Getting Started with the Library
====================================
This section should give you a quick idea on how to get going. Basically, you need to do the
following things to make use of the library:
1. Make sure you have downloaded the latest version of the library available from the home page
at URL `http://dmalloc.com/'.
2. Follow the installation instructions on how to configure, make, and install the library (i.e.
type: `make install'). *Note Installation::.
3. You need to make sure that the library configuration and build process above was able to
locate one of the `on_exit' function, `atexit' function, or had compiler destructor support.
If one of these functions or support is available then the dmalloc library should be able to
automatically shut itself down when the program exits. This causes the memory statistics and
unfreed information to be dumped to the log file. However, if your system has none of the
above, then you will need to call `dmalloc_shutdown' yourself before your program exits.
4. To get the dmalloc utility to work you need to add an alias for dmalloc to your shell's
runtime configuration file if supported. The idea is to have the shell capture the dmalloc
program's output and adjust the environment.
After you add the alias to the shell config file you need to log out and log back in to have
it take effect, or you can execute the appropriate command below on the command line directly.
After you setup the alias, if you enter `dmalloc runtime' and see any output with
DMALLOC_OPTIONS in it then the alias did not take effect.
Bash, ksh, and zsh (`http://www.zsh.org/') users should add the following to their `.bashrc',
`.profile', or `.zshrc' file respectively (notice the `-b' option for bourne shell output):
function dmalloc { eval `command dmalloc -b $*`; }
If your shell does not support the `command' function then try:
function dmalloc { eval `\dmalloc -b $*`; }
or
function dmalloc { eval `/usr/local/bin/dmalloc -b $*`; }
If you are still using csh or tcsh, you should add the following to your `.cshrc' file (notice
the `-C' option for c-shell output):
alias dmalloc 'eval `\dmalloc -C \!*`'
If you are using rc shell, you should add the following to your `.rcrc' file (notice the `-R'
option for rc-shell output):
fn dmalloc {eval `{/usr/local/bin/dmalloc $*}}
5. Although not necessary, you may want to include `dmalloc.h' in your C files and recompile.
This will allow the library to report the file/line numbers of calls that generate problems.
*Note Allocation Macros::. It should be inserted at the _bottom_ of your include files as to
not conflict with wother includes. You may want to ifdef it as well and compile with `cc
-DDMALLOC ...':
/* other includes above ^^^ */
#ifdef DMALLOC
#include "dmalloc.h"
#endif
6. Another optional task is to compile all of your source with the `dmalloc.h' with the
`DMALLOC_FUNC_CHECK' compilation flag. This willallow the library to check all of the
arguments of a number of common string and utility routines. *Note Argument Checking::.
cc -DDMALLOC -DDMALLOC_FUNC_CHECK file.c
7. Link the dmalloc library into your program. The dmalloc library should probably be placed at
or near the end of the library list.
8. Enable the debugging features by typing `dmalloc -l logfile -i 100 low' (for example). You
should not see any messages printed by the dmalloc utility (see NOTE below). This will:
* Set the malloc logfile name to `logfile' (`-l logfile'). For programs which change
directories, you may want to specify the full path to your logfile.
* Have the library check itself every 100 iterations (`-i 100'). This controls how fast
your program will run. Larger numbers check the heap less and so it will run faster.
Lower numbers will be more likely to catch memory problems.
* Enable a number of debug features (`low'). You can also try `runtime' for minimal
checking or `medium' or `high' for more extensive heap verification.
* By default, the low, medium, and high values enable the `error-abort' token which will
cause the library to abort and usually dump core immediately upon seeing an error. *Note
Dumping Core::. You can disable this feature by entering `dmalloc -m error-abort' (-m
for minus) to remove the `error-abort' token and your program will just log errors and
continue.
`dmalloc --usage' will provide verbose usage info for the dmalloc program. *Note Dmalloc
Program::.
You may also want to install the `dmallocrc' file in your home directory as `.dmallocrc'.
This allows you to add your own combination of debug tokens. *Note RC File::.
_NOTE_: The output from the dmalloc utility should be captured by your shell. If you see a
bunch of stuff which includes the string `DMALLOC_OPTIONS' then the alias you should have
created above is not working and he environmental variables are not being set. Make sure
you've logged out and back in to have the alias take effect.
9. Run your program, examine the logfile that should have been created by `dmalloc_shutdown', and
use its information to help debug your program.
File: dmalloc.info.t, Node: Allocation Basics, Next: Features, Prev: Getting Started, Up: Overview
2.3 Basic Description of Terms and Functions
============================================
* Menu:
* Basic Definitions:: General memory terms and concepts.
* Malloc Functions:: Functionality supported by all malloc libs.
File: dmalloc.info.t, Node: Basic Definitions, Next: Malloc Functions, Prev: Allocation Basics, Up: Allocation Basics
2.3.1 General Memory Terms and Concepts
---------------------------------------
Any program can be divided into 2 logical parts: text and data. Text is the actual program code in
machine-readable format and data is the information that the text operates on when it is executing.
The data, in turn, can be divided into 3 logical parts according to where it is stored: "static",
"stack", and "heap".
Static data is the information whose storage space is compiled into the program.
/* global variables are allocated as static data */
int numbers[10];
main()
{
...
}
Stack data is data allocated at runtime to hold information used inside of functions. This data
is managed by the system in the space called stack space.
void foo()
{
/* this local variable is stored on the stack */
float total;
...
}
main()
{
foo();
}
Heap data is also allocated at runtime and provides a programmer with dynamic memory
capabilities.
main()
{
/* the address is stored on the stack */
char * string;
...
/*
* Allocate a string of 10 bytes on the heap. Store the
* address in string which is on the stack.
*/
string = (char *)malloc(10);
...
/* de-allocate the heap memory now that we're done with it */
(void)free(string);
...
}
It is the heap data that is managed by this library.
Although the above is an example of how to use the malloc and free commands, it is not a good
example of why using the heap for runtime storage is useful.
Consider this: You write a program that reads a file into memory, processes it, and displays
results. You would like to handle files with arbitrary size (from 10 bytes to 1.2 megabytes and
more). One problem, however, is that the entire file must be in memory at one time to do the
calculations. You don't want to have to allocate 1.2 megabytes when you might only be reading in a
10 byte file because it is wasteful of system resources. Also, you are worried that your program
might have to handle files of more than 1.2 megabytes.
A solution: first check out the file's size and then, using the heap-allocation routines, get
enough storage to read the entire file into memory. The program will only be using the system
resources necessary for the job and you will be guaranteed that your program can handle any sized
file.
File: dmalloc.info.t, Node: Malloc Functions, Prev: Basic Definitions, Up: Allocation Basics
2.3.2 Functionality Supported by All Malloc Libraries
-----------------------------------------------------
All malloc libraries support 4 basic memory allocation commands. These include "malloc", "calloc",
"realloc", and "free". For more information about their capabilities, check your system's manual
pages - in unix, do a `man 3 malloc'.
-- Function: void *malloc ( unsigned int SIZE )
Usage: `pnt = (type *)malloc(size)'
The malloc routine is the basic memory allocation routine. It allocates an area of `size'
bytes. It will return a pointer to the space requested.
-- Function: void *calloc ( unsigned int NUMBER, unsigned intSIZE )
Usage: `pnt = (type *)calloc(number, size)'
The calloc routine allocates a certain `number' of items, each of `size' bytes, and returns a
pointer to the space. It is appropriate to pass in a `sizeof(type)' value as the size
argument.
Also, calloc nulls the space that it returns, assuring that the memory is all zeros.
-- Function: void *realloc ( void *OLD_PNT, unsigned int NEW_SIZE )
Usage: `new_pnt = (type *)realloc(old_pnt, new_size)'
The realloc function expands or shrinks the memory allocation in `old_pnt' to `new_size'
number of bytes. Realloc copies as much of the information from `old_pnt' as it can into the
`new_pnt' space it returns, up to `new_size' bytes. If there is a problem allocating this
memory, 0L will be returned.
If the `old_pnt' is 0L then realloc will do the equivalent of a `malloc(new_size)'. If
`new_size' is 0 and `old_pnt' is not 0L, then it will do the equivalent of `free(old_pnt)' and
will return 0L.
-- Function: void free ( void *PNT )
Usage: `free(pnt)'
The free routine releases allocation in `pnt' which was returned by malloc, calloc, or realloc
back to the heap. This allows other parts of the program to re-use memory that is not needed
anymore. It guarantees that the process does not grow too big and swallow a large portion of
the system resources.
_WARNING_: there is a quite common myth that all of the space that is returned by malloc
libraries has already been cleared. _Only_ the `calloc' routine will zero the memory space it
returns.
File: dmalloc.info.t, Node: Features, Next: How It Works, Prev: Allocation Basics, Up: Overview
2.4 General Features of the Library
===================================
The debugging features that are available in this debug malloc library can be divided into a couple
basic classifications:
file and line number information
One of the nice things about a good debugger is its ability to provide the file and line
number of an offending piece of code. This library attempts to give this functionality with
the help of "cpp", the C preprocessor. *Note Allocation Macros::.
return-address information
To debug calls to the library from external sources (i.e. those files that could not use the
allocation macros), some facilities have been provided to supply the caller's address. This
address, with the help of a debugger, can help you locate the source of a problem. *Note
Return Address::.
fence-post (i.e. bounds) checking
"Fence-post" memory is the area immediately above or below memory allocations. It is all too
easy to write code that accesses above or below an allocation - especially when dealing with
arrays or strings. The library can write special values in the areas around every allocation
so it will notice when these areas have been overwritten. *Note Fence-Post Overruns::.
_NOTE_: The library cannot notice when the program _reads_ from these areas, only when it
writes values. Also, fence-post checking will increase the amount of memory the program
allocates.
heap-constancy verification
The administration of the library is reasonably complex. If any of the heap-maintenance
information is corrupted, the program will either crash or give unpredictable results.
By enabling heap-consistency checking, the library will run through its administrative
structures to make sure all is in order. This will mean that problems will be caught faster
and diagnosed better.
The drawback of this is, of course, that the library often takes quite a long time to do this.
It is suitable to enable this only during development and debugging sessions.
_NOTE_: the heap checking routines cannot guarantee that the tests will not cause a
segmentation-fault if the heap administration structures are properly (or improperly if you
will) overwritten. In other words, the tests will verify that everything is okay but may not
inform the user of problems in a graceful manner.
logging statistics
One of the reasons why the debug malloc library was initially developed was to track programs'
memory usage - specifically to locate "memory leaks" which are places where allocated memory
is never getting freed. *Note Memory Leaks::.
The library has a number of logging capabilities that can track un-freed memory pointers as
well as runtime memory usage, memory transactions, administrative actions, and final
statistics.
examining freed memory
Another common problem happens when a program frees a memory pointer but goes on to use it
again by mistake. This can lead to mysterious crashes and unexplained problems.
To combat this, the library can write special values into a block of memory after it has been
freed. This serves two purposes: it will make sure that the program will get garbage data if
it trying to access the area again, and it will allow the library to verify the area later for
signs of overwriting.
If any of the above debugging features detect an error, the library will try to recover. If
logging is enabled then an error will be logged with as much information as possible.
The error messages that the library displays are designed to give the most information for
developers. If the error message is not understood, then it is most likely just trying to indicate
that a part of the heap has been corrupted.
The library can be configured to quit immediately when an error is detected and to dump a core
file or memory-image. This can be examined with a debugger to determine the source of the problem.
The library can either stop after dumping core or continue running. *Note Dumping Core::.
_NOTE_: do not be surprised if the library catches problems with your system's routines. It
took me hours to finally come to the conclusion that the localtime call, included in SunOS release
4.1, overwrites one of its fence-post markers.
File: dmalloc.info.t, Node: How It Works, Prev: Features, Up: Overview
2.5 How the Library Checks Your Program
=======================================
This is one of the newer sections of the library implying that it is incomplete. If you have any
questions or issues that you'd like to see handled here, please let me know.
The dmalloc library replaces the heap library calls normally found in your system libraries with
its own versions. When you make a call to malloc (for example), you are calling dmalloc's version
of the memory allocation function. When you allocate memory with these functions, the dmalloc
library keeps track of a number of pieces of debugging information about your pointer including:
where it was allocated, exactly how much memory was requested, when the call was made, etc.. This
information can then be verified when the pointer is freed or reallocated and the details can be
logged on any errors.
Whenever you reallocate or free a memory address, the dmalloc library always performs a number
of checks on the pointer to make sure that it is valid and has not been corrupted. You can
configure the library to perform additional checks such as detected fence-post writing. The
library can also be configured to overwrite memory with non-zeros (only if calloc is not called)
when it is allocated and erase the memory when the pointers are freed.
In addition to per-pointer checks, you can configure the library to perform complete heap
checks. These complete checks verify all internal heap structures and include walking all of the
known allocated pointers to verify each one in turn. You need this level of checking to find
random pointers in your program which got corrupted but that won't be freed for a while. To turn
on these checks, you will need to enable the `check-heap' debug token. *Note Debug Tokens::. By
default this will cause the heap to be fully checked each and every time dmalloc is called whether
it is a malloc, free, realloc, or another dmalloc overloaded function.
Performing a full heap check can take a good bit of CPU and it may be that you will want to run
it sporadically. This can be accomplished in a couple different ways including the '-i' interval
argument to the dmalloc utility. *Note Dmalloc Program::. This will cause the check to be run
every N-th time. For instance, 'dmalloc -i 3' will cause the heap to be checked before every 3rd
call to a memory function. Values of 100 or even 1000 for high memory usage programs are more
useful than smaller ones.
You can also cause the program to start doing detailed heap checking after a certain point. For
instance, with 'dmalloc -s 1000' option, you can tell the dmalloc library to enable the heap checks
after the 1000th memory call. Examine the dmalloc log file produced and use the iteration count if
you have `LOG_ITERATION_COUNT' enabled in your `settings.h' file.
The start option can also have the format `file:line'. For instance, if it is set to
`dmalloc_t.c:126', dmalloc will start checking the heap after it sees a dmalloc call from the
`dmalloc_t.c' file, line number 126. If you use `dmalloc_t.c:0', with a 0 line number, then
dmalloc will start checking the heap after it sees a call from anywhere in the `dmalloc_t.c' file.
File: dmalloc.info.t, Node: Programming, Next: Dmalloc Program, Prev: Overview, Up: Top
3 How to Program with the Library
*********************************
* Menu:
* Allocation Macros:: Macros providing file and line information.
* Return Address:: Getting caller address information.
* Argument Checking:: Checking of function arguments.
* Dumping Core:: Generating a core file on errors for debugging.
* Extensions:: Additional non-standard routines.
* Error Codes:: Description of the internal error numbers.
* Disabling the Library:: How to disable the library.
* Using With C++:: Using the library with C++.
* Using With a Debugger:: Using a debugger with the library.
* Using With Threads:: Using the library with a thread package.
* Using With Cygwin:: Using the library with Cygwin environment.
* Debugging A Server:: Debugging memory in a server or cgi-bin process.
* Logfile Details:: Explanation of the Logfile Output.
* Other Hints:: Various other hints that may help.
File: dmalloc.info.t, Node: Allocation Macros, Next: Return Address, Prev: Programming, Up: Programming
3.1 Macros Providing File and Line Information
==============================================
By including `dmalloc.h' in your C files, your calls to malloc, calloc, realloc, recalloc,
memalign, valloc, strdup, and free are replaced with calls to _dmalloc_malloc, _dmalloc_realloc, and
_dmalloc_free with various flags. Additionally the library replaces calls to xmalloc, xcalloc,
xrealloc, xrecalloc, xmemalign, xvalloc, xstrdup, and xfree with associated calls.
These macros use the c-preprocessor `__FILE__' and `__LINE__' macros which get replaced at
compilation time with the current file and line-number of the source code in question. The
routines use this information to produce verbose reports on memory problems.
not freed: '0x38410' (22 bytes) from 'dmalloc_t.c:92'
This line from a log file shows that memory was not freed from file `dmalloc_t.c' line 92.
*Note Memory Leaks::.
You may notice some non standard memory allocation functions in the above list. Recalloc is a
routine like realloc that reallocates previously allocated memory to a new size. If the new memory
size is larger than the old, recalloc initializes the new space to all zeros. This may or may not
be supported natively by your operating system. Memalign is like malloc but should insure that the
returned pointer is aligned to a certain number of specified bytes. Currently, the memalign
function is not supported by the library. It defaults to returning possibly non-aligned memory for
alignment values less than a block-size. Valloc is like malloc but insures that the returned
pointer will be aligned to a page boundary. This may or may not be supported natively by your
operating system but is fully supported by the library. Strdup is a string duplicating routine
which takes in a null terminated string pointer and returns an allocated copy of the string that
will need to be passed to free later to deallocate.
The X versions of the standard memory functions (xmalloc, xfree, etc.) will print out an error
message to standard error and will stop if the library is unable to allocate any additional memory.
It is useful to use these routines instead of checking everywhere in your program for allocation
routines returning NULL pointers.
_WARNING_: If you are including the `dmalloc.h' file in your sources, it is recommended that it
be at the end of your include file list because dmalloc uses macros and may try to change
declarations of the malloc functions if they come after it.
File: dmalloc.info.t, Node: Return Address, Next: Argument Checking, Prev: Allocation Macros, Up: Programming
3.2 Getting Caller Address Information
======================================
Even though the allocation macros can provide file/line information for some of your code, there
are still modules which either you can't include `dmalloc.h' (such as library routines) or you just
don't want to. You can still get information about the routines that call dmalloc function from
the return-address information. To accomplish this, you must be using this library on one of the
supported architecture/compilers. *Note Portability::.
The library attempts to use some assembly hacks to get the return-address or the address of the
line that called the dmalloc function. If you have unfreed memory that does not have associated
file and line information, you might see the following non-freed memory messages.
not freed: '0x38410' (22 bytes) from 'ra=0xdd2c'
not freed: '0x38600' (10232 bytes) from 'ra=0x10234d'
not freed: '0x38220' (137 bytes) from 'ra=0x82cc'
With the help of a debugger, these return-addresses (or ra) can then be identified. I've
provided a `ra_info.pl' perl script in the `contrib/' directory with the dmalloc sources which
seems to work well with gdb. You can also use manual methods for gdb to find the return-address
location. *Note Translate Return Addresses::.
File: dmalloc.info.t, Node: Argument Checking, Next: Dumping Core, Prev: Return Address, Up: Programming
3.3 Checking of Function Arguments
==================================
One potential problem with the library and its multitude of checks and diagnoses is that they only
get performed when a dmalloc function is called. One solution this is to include `dmalloc.h' and
compile your source code with the `DMALLOC_FUNC_CHECK' flag defined and enable the `check-funcs'
token. *Note Debug Tokens::.
cc -DDMALLOC -DDMALLOC_FUNC_CHECK file.c
_NOTE_: Once you have compiled your source with DMALLOC_FUNC_CHECK enabled, you will have to
recompile with it off to disconnect the library. *Note Disabling the Library::.
_WARNING_: You should be sure to have `dmalloc.h' included at the end of your include file list
because dmalloc uses macros and may try to change declarations of the checked functions if they
come after it.
When this is defined dmalloc will override a number of functions and will insert a routine which
knows how to check its own arguments and then call the real function. Dmalloc can check such
functions as `bcopy', `index', `strcat', and `strcasecmp'. For the full list see the end of
`dmalloc.h'.
When you call `strlen', for instance, dmalloc will make sure the string argument's fence-post
areas have not been overwritten, its file and line number locations are good, etc. With `bcopy',
dmalloc will make sure that the destination string has enough space to store the number of bytes
specified.
For all of the arguments checked, if the pointer is not in the heap then it is ignored since
dmalloc does not know anything about it.
File: dmalloc.info.t, Node: Dumping Core, Next: Extensions, Prev: Argument Checking, Up: Programming
3.4 Generating a Core File on Errors
====================================
If the `error-abort' debug token has been enabled, when the library detects any problems with the
heap memory, it will immediately attempt to dump a core file. *Note Debug Tokens::. Core files
are a complete copy of the program and it's state and can be used by a debugger to see specifically
what is going on when the error occurred. *Note Using With a Debugger::. By default, the low,
medium, and high arguments to the library utility enable the `error-abort' token. You can disable
this feature by entering `dmalloc -m error-abort' (-m for minus) to remove the `error-abort' token
and your program will just log errors and continue. You can also use the `error-dump' token which
tries to dump core when it sees an error but still continue running. *Note Debug Tokens::.
When a program dumps core, the system writes the program and all of its memory to a file on disk
usually named `core'. If your program is called `foo' then your system may dump core as
`foo.core'. If you are not getting a `core' file, make sure that your program has not changed to a
new directory meaning that it may have written the core file in a different location. Also insure
that your program has write privileges over the directory that it is in otherwise it will not be
able to dump a core file. Core dumps are often security problems since they contain all program
memory so systems often block their being produced. You will want to check your user and system's
core dump size ulimit settings.
The library by default uses the `abort' function to dump core which may or may not work
depending on your operating system. If the following program does not dump core then this may be
the problem. See `KILL_PROCESS' definition in `settings.dist'.
main()
{
abort();
}
If `abort' does work then you may want to try the following setting in `settings.dist'. This
code tries to generate a segmentation fault by dereferencing a `NULL' pointer.
#define KILL_PROCESS { int *_int_p = 0L; *_int_p = 1; }
File: dmalloc.info.t, Node: Extensions, Next: Error Codes, Prev: Dumping Core, Up: Programming
3.5 Additional Non-standard Routines
====================================
The library has a number of variables that are not a standard part of most malloc libraries:
-- Variable: int dmalloc_errno
This variable stores the internal dmalloc library error number like errno does for the system
calls. It can be passed to `dmalloc_strerror()' (see below) to get a string version of the
error. It will have a value of zero if the library has not detected any problems.
-- Variable: char* dmalloc_logpath
This variable can be used to set the dmalloc log filename. The env variable `DMALLOC_LOGFILE'
overrides this variable.
Additionally the library provides a number of non-standard malloc routines:
-- Function: void dmalloc_shutdown ( void )
This function shuts the library down and logs the final statistics and information especially
the non-freed memory pointers. The library has code to support auto-shutdown if your system
has the `on_exit()' call, `atexit()' call, or compiler destructor support (see `conf.h'). If
you do not have these, then `dmalloc_shutdown' should be called right before `exit()' or as
the last function in `main()'.
main()
{
...
dmalloc_shutdown();
exit(0);
}
-- Function: int dmalloc_verify ( char * PNT )
This function verifies individual memory pointers that are suspect of memory problems. To
check the entire heap pass in a NULL or 0 pointer. The routine returns DMALLOC_VERIFY_ERROR
or DMALLOC_VERIFY_NOERROR.
_NOTE_: `dmalloc_verify()' can only check the heap with the functions that have been enabled.
For example, if fence-post checking is not enabled, `dmalloc_verify()' cannot check the
fence-post areas in the heap.
-- Function: unsigned-int dmalloc_debug ( const unsigned int FLAGS )
This routine sets the debug functionality flags and returns the previous flag value. It is
helpful in server or cgi-bin programs where environmental variables cannot be used. *Note
Debugging A Server::. For instance, if debugging should never be enabled for a program, a
call to `dmalloc_debug(0)' as the first call in `main()' will disable all the memory debugging
from that point on.
_NOTE_: you cannot add or remove certain flags such as signal handlers since they are setup at
initialization time only.
_NOTE_: you can also use `dmalloc_debug_setup' below.
-- Function: unsigned-int dmalloc_debug_current ( void )
This routine returns the current debug functionality value value. This allows you to save a
copy of the debug dmalloc settings to be changed and then restored later.
-- Function: void dmalloc_debug_setup ( const char * OPTIONS_STR )
This routine sets the global debugging functionality as an option string. Normally this would
be passed in in the DMALLOC_OPTIONS environmental variable. This is here to override the env
or for circumstances where modifying the environment is not possible or does not apply such as
servers or cgi-bin programs. *Note Debugging A Server::.
Some examples:
/*
* debug tokens high, threaded lock-on at 20,
* log to dmalloc.%p (pid)
*/
dmalloc_debug_setup("debug=0x4f46d03,lockon=20,log=dmalloc.%p");
/*
* turn on some debug tokens directly and log to the
* file 'logfile'
*/
dmalloc_debug_setup(
"log-stats,log-non-free,check-fence,log=logfile");
-- Function: int dmalloc_examine ( const DMALLOC_PNT PNT, DMALLOC_SIZE * USER_SIZE_P, DMALLOC_SIZE
* TOTAL_SIZE_P, char ** FILE_P, int * LINE_P, DMALLOC_PNT * RET_ADDR_P, unsigned long *
USER_MARK_P, unsigned long * SEEN_P )
This function returns the size of a pointer's allocation as well as the total size given
including administrative overhead, file and line or the return-address from where it was
allocated, the last pointer when the pointer was "used", and the number of times the pointer
has been "seen". It will return DMALLOC_NOERROR or DMALLOC_ERROR depending on whether pnt is
good or not.
_NOTE_: This function is _certainly_ not provided by most if not all other malloc libraries.
-- Function: void dmalloc_track ( const dmalloc_track_t TRACK_FUNC )
Register an allocation tracking function which will be called each time an allocation occurs.
Pass in NULL to disable. To take a look at what information is provided, see the
dmalloc_track_t function typedef in dmalloc.h.
-- Function: unsigned-long dmalloc_mark ( void )
Return to the caller the current "mark" which can be used later to log the pointers which have
changed since this mark with the `dmalloc_log_changed' function. Multiple marks can be saved
and used.
This is very useful when using the library with a server which does not exit. You can then
save a mark before a transaction or event happens and then check to see what has changed using
the `dmalloc_log_changed' function below. *Note Debugging A Server::.
If you `LOG_ITERATION' enabled in your `settings.h' file then the entries in the log file will
be prepended with the number of memory transactions that the library has handled so far. You
can also enable `LOG_PNT_ITERATION' in `settings.h' to store the memory transaction number
with each pointer.
-- Function: unsigned-long dmalloc_memory_allocated ( void )
Return to the caller the total number of bytes that have been allocated by the library. This
is not the current in use but the total number of bytes returned by allocation functions.
-- Function: unsigned-int dmalloc_page_size ( void )
Return to the caller the memory page-size being used by the library. This should be the same
value as the one returned by the `getpagesize()' function, if available.
-- Function: unsigned-long dmalloc_count_changed ( const unsigned long MARK, const int
NOT_FREED_B, const int FREE_B )
Count the pointers that have changed since the mark which was returned by `dmalloc_mark'. If
`not_freed_b' is set to non-0 then count the pointers that have not been freed. If `free_b'
is set to non-0 then count the pointers that have been freed.
This can be used in conjunction with the `dmalloc_mark()' function to help servers which never
exit ensure that transactions or events are not leaking memory. *Note Debugging A Server::.
unsigned long mark = dmalloc_mark() ;
...
assert(dmalloc_count_changed(mark, 1, 0) == 0) ;
-- Function: void dmalloc_log_stats ( void )
This routine outputs the current dmalloc statistics to the log file.
-- Function: void dmalloc_log_unfreed ( void )
This function logs the unfreed-memory information to the log file. This is also useful to log
the currently allocated points to the log file to be compared against another dump later on.
-- Function: void dmalloc_log_changed ( const unsigned long MARK, const int NOT_FREED_B, const int
FREED_B, const int DETAILS_B )
Log the pointers that have changed since the mark which was returned by `dmalloc_mark'. If
`not_freed_b' is set to non-0 then log the pointers that have not been freed. If `free_b' is
set to non-0 then log the pointers that have been freed. If `details_b' set to non-0 then log
the individual pointers that have changed otherwise just log the summaries.
This can be used in conjunction with the `dmalloc_mark()' function to help servers which never
exit find transactions or events which are leaking memory. *Note Debugging A Server::.
-- Function: void dmalloc_vmessage ( const char * FORMAT, va_list ARGS )
Write a message into the dmalloc logfile using vprintf-like arguments.
-- Function: void dmalloc_message ( const char * FORMAT, ... )
Write a message into the dmalloc logfile using printf-like arguments.
-- Function: void dmalloc_get_stats ( DMALLOC_PNT * HEAP_LOW_P, DMALLOC_PNT * HEAP_HIGH_P,
unsigned long * TOTAL_SPACE_P, unsigned long * USER_SPACE_P, unsigned long *
CURRENT_ALLOCATED_P, unsigned long * CURRENT_PNT_NP, unsigned long * MAX_ALLOCATED_P,
unsigned long * MAX_PNT_NP, unsigned long * MAX_ONE_P)
This function return a number of statistics about the current heap. The pointers `heap_low_p'
and `heap_high_p' will be set to the low and high spots in the heap. `total_space_p' will be
set to the total space in the heap including user space, administrative space, and overhead.
`user_space_p' will be set to the space given to the user process (allocated and free space).
`current_allocated_p' will be set to the current allocated space given to the user process.
`current_pnt_np' will be set to the current number of pointers allocated by the user process.
`max_allocated_p' will be set to the maximum allocated space given to the user process.
`max_pnt_np' will be set to the maximum number of pointers allocated by the user process.
`max_on_p' will be set to the maximum space allocated with one call by the user process.
-- Function: const-char* dmalloc_strerror ( const int ERROR_NUMBER )
This function returns the string representation of the error value in `error_number' (which
probably should be dmalloc_errno). This allows the logging of more verbose memory error
messages.
You can also display the string representation of an error value by a call to the `dmalloc'
program with a `-e #' option. *Note Dmalloc Program::.
File: dmalloc.info.t, Node: Error Codes, Next: Disabling the Library, Prev: Extensions, Up: Programming
3.6 Description of the Internal Error Codes
===========================================
The following error codes are defined in `error_val.h'. They are used by the library to indicate a
detected problem. They can be caused by the user (`ERROR_TOO_BIG') or can indicate an internal
library problem (`ERROR_SLOT_CORRUPT'). The `dmalloc' utility can give you the string version of
the error with the `-e' argument:
$ dmalloc -e 60
dmalloc: dmalloc_errno value '60' =
'pointer is not on block boundary'
Here are the error codes set by the library. They are non contiguous on purpose because I add
and delete codes all of the time and there are sections for various error-code types.
`1 (ERROR_NONE) no error'
No error. It is good coding practice to set the no-error code to be non-0 value because it
forces you to set it explicitly.
`2 (INVALID_ERROR)'
Invalid error number. If the library outputs this error then your dmalloc utility may be out
of date with the library you linked against. This will be returned with all error codes not
listed here.
`10 (ERROR_BAD_SETUP) initialization and setup failed'
Bad setup value. This is currently unused but it is intended to report on invalid setup
configuration information.
`11 (ERROR_IN_TWICE) malloc library has gone recursive'
Library went recursive. This usually indicates that you are not using the threaded version of
the library. Or if you are then you are not using the `-o' "lock-on" option. *Note Using
With Threads::.
`13 (ERROR_LOCK_NOT_CONFIG) thread locking has not been configured'
Thread locking has not been configured. This indicates that you attempted to use the `-o'
"lock-on" option without linking with the thread version of the library. You should probably
be using `-ldmallocth' _not_ `-ldmalloc' when you are linking. Or you should include
`.../lib/libdmallocth.a' on your compilation line.
`20 (ERROR_IS_NULL) pointer is null'
Pointer is null. The program passed a NULL (0L) pointer to `free' and you have the
`error-free-null' token enabled.
`21 (ERROR_NOT_IN_HEAP) pointer is not pointing to heap data space'
Pointer is not pointing to heap data space. This means that the program passed an
out-of-bounds pointer to `free' or `realloc'. This could be someone trying to work with a
wild pointer or trying to free a pointer from a different source than `malloc'.
`22 (ERROR_NOT_FOUND) cannot locate pointer in heap'
Cannot locate pointer in heap. The user passed in a pointer which the heap did not know
about. Either this pointer was allocated by some other mechanism (like `mmap' or `sbrk'
directly) or it is a random invalid pointer.
In some rare circumstances, sometimes seen with shared libraries, there can be two separate
copies of the dmalloc library in a program. Each one does not know about the pointers
allocated by the other.
`23 (ERROR_IS_FOUND) found pointer the user was looking for'
This indicates that the pointer specified in the address part of the environmental variable
was discovered by the library. *Note Environment Variable::. This error is useful so you can
put a breakpoint in a debugger to find where a particular address was allocated. *Note Using
With a Debugger::.
`24 (ERROR_BAD_FILE) possibly bad .c filename pointer'
A possibly invalid filename was discovered in the dmalloc administrative sections. This could
indicate some corruption of the internal tables. It also could mean that you have a source
file whose name is longer than 100 characters. See `MAX_FILE_LENGTH' in the `settings.dist'
file.
`25 (ERROR_BAD_LINE) possibly bad .c file line-number'
A line-number was out-of-bounds in the dmalloc administrative sections. This could indicate
some corruption of the internal tables. It also could mean that you have a source file
containing more than `30000' lines of code. See `MAX_LINE_NUMBER' in the `settings.dist' file.
`26 (ERROR_UNDER_FENCE) failed UNDER picket-fence magic-number check'
This indicates that a pointer had its lower bound picket-fence magic number overwritten. If
the `check-fence' token is enabled, the library writes magic values above and below
allocations to protect against overflow. Most likely this is because a pointer below it went
past its allocate and wrote into the next pointer's space.
`27 (ERROR_OVER_FENCE) failed OVER picket-fence magic-number check'
This indicates that a pointer had its upper bound picket-fence magic space overwritten. If
the `check-fence' token is enabled, the library writes magic values above and below
allocations to protect against overflow. Most likely this is because an array or string
allocation wrote past the end of the allocation.
Check for improper usage of `strcat', `sprintf', `strcpy', and any other functions which work
with strings and do not protect themselves by tracking the size of the string. These