Debian Codegraph @

generic/tclCkalloc.c

raw
1 /*
2 * tclCkalloc.c --
3 *
4 * Interface to malloc and free that provides support for debugging
5 * problems involving overwritten, double freeing memory and loss of
6 * memory.
7 *
8 * Copyright (c) 1991-1994 The Regents of the University of California.
9 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
10 * Copyright (c) 1998-1999 by Scriptics Corporation.
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 *
15 * This code contributed by Karl Lehenbauer and Mark Diekhans
16 */
17
18 #include "tclInt.h"
19
20 #define FALSE 0
21 #define TRUE 1
22
23 #undef Tcl_Alloc
24 #undef Tcl_Free
25 #undef Tcl_Realloc
26 #undef Tcl_AttemptAlloc
27 #undef Tcl_AttemptRealloc
28
29 #ifdef TCL_MEM_DEBUG
30
31 /*
32 * One of the following structures is allocated each time the
33 * "memory tag" command is invoked, to hold the current tag.
34 */
35
36 typedef struct MemTag {
37 int refCount; /* Number of mem_headers referencing this
38 * tag. */
39 char string[1]; /* Actual size of string will be as large as
40 * needed for actual tag. This must be the
41 * last field in the structure. */
42 } MemTag;
43
44 #define TAG_SIZE(bytesInString) ((unsigned) ((TclOffset(MemTag, string) + 1U) + (bytesInString)))
45
46 static MemTag *curTagPtr = NULL;/* Tag to use in all future mem_headers (set
47 * by "memory tag" command). */
48
49 /*
50 * One of the following structures is allocated just before each dynamically
51 * allocated chunk of memory, both to record information about the chunk and
52 * to help detect chunk under-runs.
53 */
54
55 #define LOW_GUARD_SIZE (8 + (32 - (sizeof(long) + sizeof(int)))%8)
56 struct mem_header {
57 struct mem_header *flink;
58 struct mem_header *blink;
59 MemTag *tagPtr; /* Tag from "memory tag" command; may be
60 * NULL. */
61 const char *file;
62 long length;
63 int line;
64 unsigned char low_guard[LOW_GUARD_SIZE];
65 /* Aligns body on 8-byte boundary, plus
66 * provides at least 8 additional guard bytes
67 * to detect underruns. */
68 char body[1]; /* First byte of client's space. Actual size
69 * of this field will be larger than one. */
70 };
71
72 static struct mem_header *allocHead = NULL; /* List of allocated structures */
73
74 #define GUARD_VALUE 0141
75
76 /*
77 * The following macro determines the amount of guard space *above* each chunk
78 * of memory.
79 */
80
81 #define HIGH_GUARD_SIZE 8
82
83 /*
84 * The following macro computes the offset of the "body" field within
85 * mem_header. It is used to get back to the header pointer from the body
86 * pointer that's used by clients.
87 */
88
89 #define BODY_OFFSET \
90 ((size_t) (&((struct mem_header *) 0)->body))
91
92 static int total_mallocs = 0;
93 static int total_frees = 0;
94 static size_t current_bytes_malloced = 0;
95 static size_t maximum_bytes_malloced = 0;
96 static int current_malloc_packets = 0;
97 static int maximum_malloc_packets = 0;
98 static int break_on_malloc = 0;
99 static int trace_on_at_malloc = 0;
100 static int alloc_tracing = FALSE;
101 static int init_malloced_bodies = TRUE;
102 #ifdef MEM_VALIDATE
103 static int validate_memory = TRUE;
104 #else
105 static int validate_memory = FALSE;
106 #endif
107
108 /*
109 * The following variable indicates to TclFinalizeMemorySubsystem() that it
110 * should dump out the state of memory before exiting. If the value is
111 * non-NULL, it gives the name of the file in which to dump memory usage
112 * information.
113 */
114
115 char *tclMemDumpFileName = NULL;
116
117 static char *onExitMemDumpFileName = NULL;
118 static char dumpFile[100]; /* Records where to dump memory allocation
119 * information. */
120
121 /*
122 * Mutex to serialize allocations. This is a low-level mutex that must be
123 * explicitly initialized. This is necessary because the self initializing
124 * mutexes use ckalloc...
125 */
126
127 static Tcl_Mutex *ckallocMutexPtr;
128 static int ckallocInit = 0;
129
130 /*
131 * Prototypes for procedures defined in this file:
132 */
133
134 static int CheckmemCmd(ClientData clientData, Tcl_Interp *interp,
135 int argc, const char *argv[]);
136 static int MemoryCmd(ClientData clientData, Tcl_Interp *interp,
137 int argc, const char *argv[]);
138 static void ValidateMemory(struct mem_header *memHeaderP,
139 const char *file, int line, int nukeGuards);
140
141 /*
142 *----------------------------------------------------------------------
143 *
144 * TclInitDbCkalloc --
145 *
146 * Initialize the locks used by the allocator. This is only appropriate
147 * to call in a single threaded environment, such as during
148 * TclInitSubsystems.
149 *
150 *----------------------------------------------------------------------
151 */
152
153 void
154 TclInitDbCkalloc(void)
155 {
156 if (!ckallocInit) {
157 ckallocInit = 1;
158 ckallocMutexPtr = Tcl_GetAllocMutex();
159 #ifndef TCL_THREADS
160 /* Silence compiler warning */
161 (void)ckallocMutexPtr;
162 #endif
163 }
164 }
165
166 /*
167 *----------------------------------------------------------------------
168 *
169 * TclDumpMemoryInfo --
170 *
171 * Display the global memory management statistics.
172 *
173 *----------------------------------------------------------------------
174 */
175
176 int
177 TclDumpMemoryInfo(
178 ClientData clientData,
179 int flags)
180 {
181 char buf[1024];
182
183 if (clientData == NULL) {
184 return 0;
185 }
186 snprintf(buf, sizeof(buf),
187 "total mallocs %10d\n"
188 "total frees %10d\n"
189 "current packets allocated %10d\n"
190 "current bytes allocated %10lu\n"
191 "maximum packets allocated %10d\n"
192 "maximum bytes allocated %10lu\n",
193 total_mallocs,
194 total_frees,
195 current_malloc_packets,
196 (unsigned long)current_bytes_malloced,
197 maximum_malloc_packets,
198 (unsigned long)maximum_bytes_malloced);
199 if (flags == 0) {
200 fprintf((FILE *)clientData, "%s", buf);
201 } else {
202 /* Assume objPtr to append to */
203 Tcl_AppendToObj((Tcl_Obj *) clientData, buf, -1);
204 }
205 return 1;
206 }
207
208 /*
209 *----------------------------------------------------------------------
210 *
211 * ValidateMemory --
212 *
213 * Validate memory guard zones for a particular chunk of allocated
214 * memory.
215 *
216 * Results:
217 * None.
218 *
219 * Side effects:
220 * Prints validation information about the allocated memory to stderr.
221 *
222 *----------------------------------------------------------------------
223 */
224
225 static void
226 ValidateMemory(
227 struct mem_header *memHeaderP,
228 /* Memory chunk to validate */
229 const char *file, /* File containing the call to
230 * Tcl_ValidateAllMemory */
231 int line, /* Line number of call to
232 * Tcl_ValidateAllMemory */
233 int nukeGuards) /* If non-zero, indicates that the memory
234 * guards are to be reset to 0 after they have
235 * been printed */
236 {
237 unsigned char *hiPtr;
238 size_t idx;
239 int guard_failed = FALSE;
240 int byte;
241
242 for (idx = 0; idx < LOW_GUARD_SIZE; idx++) {
243 byte = *(memHeaderP->low_guard + idx);
244 if (byte != GUARD_VALUE) {
245 guard_failed = TRUE;
246 fflush(stdout);
247 byte &= 0xFF;
248 fprintf(stderr, "low guard byte %d is 0x%x \t%c\n", (int)idx, byte,
249 (isprint(UCHAR(byte)) ? byte : ' ')); /* INTL: bytes */
250 }
251 }
252 if (guard_failed) {
253 TclDumpMemoryInfo((ClientData) stderr, 0);
254 fprintf(stderr, "low guard failed at %lx, %s %d\n",
255 (unsigned long)(size_t)memHeaderP->body, file, line);
256 fflush(stderr); /* In case name pointer is bad. */
257 fprintf(stderr, "%ld bytes allocated at (%s %d)\n", memHeaderP->length,
258 memHeaderP->file, memHeaderP->line);
259 Tcl_Panic("Memory validation failure");
260 }
261
262 hiPtr = (unsigned char *)memHeaderP->body + memHeaderP->length;
263 for (idx = 0; idx < HIGH_GUARD_SIZE; idx++) {
264 byte = *(hiPtr + idx);
265 if (byte != GUARD_VALUE) {
266 guard_failed = TRUE;
267 fflush(stdout);
268 byte &= 0xFF;
269 fprintf(stderr, "hi guard byte %d is 0x%x \t%c\n", (int)idx, byte,
270 (isprint(UCHAR(byte)) ? byte : ' ')); /* INTL: bytes */
271 }
272 }
273
274 if (guard_failed) {
275 TclDumpMemoryInfo((ClientData) stderr, 0);
276 fprintf(stderr, "high guard failed at %lx, %s %d\n",
277 (unsigned long)(size_t)memHeaderP->body, file, line);
278 fflush(stderr); /* In case name pointer is bad. */
279 fprintf(stderr, "%ld bytes allocated at (%s %d)\n",
280 memHeaderP->length, memHeaderP->file,
281 memHeaderP->line);
282 Tcl_Panic("Memory validation failure");
283 }
284
285 if (nukeGuards) {
286 memset(memHeaderP->low_guard, 0, LOW_GUARD_SIZE);
287 memset(hiPtr, 0, HIGH_GUARD_SIZE);
288 }
289
290 }
291
292 /*
293 *----------------------------------------------------------------------
294 *
295 * Tcl_ValidateAllMemory --
296 *
297 * Validate memory guard regions for all allocated memory.
298 *
299 * Results:
300 * None.
301 *
302 * Side effects:
303 * Displays memory validation information to stderr.
304 *
305 *----------------------------------------------------------------------
306 */
307
308 void
309 Tcl_ValidateAllMemory(
310 const char *file, /* File from which Tcl_ValidateAllMemory was
311 * called. */
312 int line) /* Line number of call to
313 * Tcl_ValidateAllMemory */
314 {
315 struct mem_header *memScanP;
316
317 if (!ckallocInit) {
318 TclInitDbCkalloc();
319 }
320 Tcl_MutexLock(ckallocMutexPtr);
321 for (memScanP = allocHead; memScanP != NULL; memScanP = memScanP->flink) {
322 ValidateMemory(memScanP, file, line, FALSE);
323 }
324 Tcl_MutexUnlock(ckallocMutexPtr);
325 }
326
327 /*
328 *----------------------------------------------------------------------
329 *
330 * Tcl_DumpActiveMemory --
331 *
332 * Displays all allocated memory to a file; if no filename is given,
333 * information will be written to stderr.
334 *
335 * Results:
336 * Return TCL_ERROR if an error accessing the file occurs, `errno' will
337 * have the file error number left in it.
338 *
339 *----------------------------------------------------------------------
340 */
341
342 int
343 Tcl_DumpActiveMemory(
344 const char *fileName) /* Name of the file to write info to */
345 {
346 FILE *fileP;
347 struct mem_header *memScanP;
348 char *address;
349
350 if (fileName == NULL) {
351 fileP = stderr;
352 } else {
353 fileP = fopen(fileName, "w");
354 if (fileP == NULL) {
355 return TCL_ERROR;
356 }
357 }
358
359 Tcl_MutexLock(ckallocMutexPtr);
360 for (memScanP = allocHead; memScanP != NULL; memScanP = memScanP->flink) {
361 address = &memScanP->body[0];
362 fprintf(fileP, "%8lx - %8lx %7ld @ %s %d %s",
363 (unsigned long)(size_t)address,
364 (unsigned long)(size_t)address + memScanP->length - 1,
365 memScanP->length, memScanP->file, memScanP->line,
366 (memScanP->tagPtr == NULL) ? "" : memScanP->tagPtr->string);
367 (void) fputc('\n', fileP);
368 }
369 Tcl_MutexUnlock(ckallocMutexPtr);
370
371 if (fileP != stderr) {
372 fclose(fileP);
373 }
374 return TCL_OK;
375 }
376
377 /*
378 *----------------------------------------------------------------------
379 *
380 * Tcl_DbCkalloc - debugging ckalloc
381 *
382 * Allocate the requested amount of space plus some extra for guard bands
383 * at both ends of the request, plus a size, panicking if there isn't
384 * enough space, then write in the guard bands and return the address of
385 * the space in the middle that the user asked for.
386 *
387 * The second and third arguments are file and line, these contain the
388 * filename and line number corresponding to the caller. These are sent
389 * by the ckalloc macro; it uses the preprocessor autodefines __FILE__
390 * and __LINE__.
391 *
392 *----------------------------------------------------------------------
393 */
394
395 char *
396 Tcl_DbCkalloc(
397 unsigned int size,
398 const char *file,
399 int line)
400 {
401 struct mem_header *result = NULL;
402
403 if (validate_memory) {
404 Tcl_ValidateAllMemory(file, line);
405 }
406
407 /* Don't let size argument to TclpAlloc overflow */
408 if (size <= UINT_MAX - HIGH_GUARD_SIZE -sizeof(struct mem_header)) {
409 result = (struct mem_header *) TclpAlloc(size +
410 sizeof(struct mem_header) + HIGH_GUARD_SIZE);
411 }
412 if (result == NULL) {
413 fflush(stdout);
414 TclDumpMemoryInfo((ClientData) stderr, 0);
415 Tcl_Panic("unable to alloc %u bytes, %s line %d", size, file, line);
416 }
417
418 /*
419 * Fill in guard zones and size. Also initialize the contents of the block
420 * with bogus bytes to detect uses of initialized data. Link into
421 * allocated list.
422 */
423
424 if (init_malloced_bodies) {
425 memset(result, GUARD_VALUE,
426 size + sizeof(struct mem_header) + HIGH_GUARD_SIZE);
427 } else {
428 memset(result->low_guard, GUARD_VALUE, LOW_GUARD_SIZE);
429 memset(result->body + size, GUARD_VALUE, HIGH_GUARD_SIZE);
430 }
431 if (!ckallocInit) {
432 TclInitDbCkalloc();
433 }
434 Tcl_MutexLock(ckallocMutexPtr);
435 result->length = size;
436 result->tagPtr = curTagPtr;
437 if (curTagPtr != NULL) {
438 curTagPtr->refCount++;
439 }
440 result->file = file;
441 result->line = line;
442 result->flink = allocHead;
443 result->blink = NULL;
444
445 if (allocHead != NULL) {
446 allocHead->blink = result;
447 }
448 allocHead = result;
449
450 total_mallocs++;
451 if (trace_on_at_malloc && (total_mallocs >= trace_on_at_malloc)) {
452 (void) fflush(stdout);
453 fprintf(stderr, "reached malloc trace enable point (%d)\n",
454 total_mallocs);
455 fflush(stderr);
456 alloc_tracing = TRUE;
457 trace_on_at_malloc = 0;
458 }
459
460 if (alloc_tracing) {
461 fprintf(stderr,"ckalloc %lx %u %s %d\n",
462 (unsigned long)(size_t)result->body, size, file, line);
463 }
464
465 if (break_on_malloc && (total_mallocs >= break_on_malloc)) {
466 break_on_malloc = 0;
467 (void) fflush(stdout);
468 Tcl_Panic("reached malloc break limit (%d)", total_mallocs);
469 }
470
471 current_malloc_packets++;
472 if (current_malloc_packets > maximum_malloc_packets) {
473 maximum_malloc_packets = current_malloc_packets;
474 }
475 current_bytes_malloced += size;
476 if (current_bytes_malloced > maximum_bytes_malloced) {
477 maximum_bytes_malloced = current_bytes_malloced;
478 }
479
480 Tcl_MutexUnlock(ckallocMutexPtr);
481
482 return result->body;
483 }
484
485 char *
486 Tcl_AttemptDbCkalloc(
487 unsigned int size,
488 const char *file,
489 int line)
490 {
491 struct mem_header *result = NULL;
492
493 if (validate_memory) {
494 Tcl_ValidateAllMemory(file, line);
495 }
496
497 /* Don't let size argument to TclpAlloc overflow */
498 if (size <= UINT_MAX - HIGH_GUARD_SIZE - sizeof(struct mem_header)) {
499 result = (struct mem_header *) TclpAlloc(size +
500 sizeof(struct mem_header) + HIGH_GUARD_SIZE);
501 }
502 if (result == NULL) {
503 fflush(stdout);
504 TclDumpMemoryInfo((ClientData) stderr, 0);
505 return NULL;
506 }
507
508 /*
509 * Fill in guard zones and size. Also initialize the contents of the block
510 * with bogus bytes to detect uses of initialized data. Link into
511 * allocated list.
512 */
513 if (init_malloced_bodies) {
514 memset(result, GUARD_VALUE,
515 size + sizeof(struct mem_header) + HIGH_GUARD_SIZE);
516 } else {
517 memset(result->low_guard, GUARD_VALUE, LOW_GUARD_SIZE);
518 memset(result->body + size, GUARD_VALUE, HIGH_GUARD_SIZE);
519 }
520 if (!ckallocInit) {
521 TclInitDbCkalloc();
522 }
523 Tcl_MutexLock(ckallocMutexPtr);
524 result->length = size;
525 result->tagPtr = curTagPtr;
526 if (curTagPtr != NULL) {
527 curTagPtr->refCount++;
528 }
529 result->file = file;
530 result->line = line;
531 result->flink = allocHead;
532 result->blink = NULL;
533
534 if (allocHead != NULL) {
535 allocHead->blink = result;
536 }
537 allocHead = result;
538
539 total_mallocs++;
540 if (trace_on_at_malloc && (total_mallocs >= trace_on_at_malloc)) {
541 (void) fflush(stdout);
542 fprintf(stderr, "reached malloc trace enable point (%d)\n",
543 total_mallocs);
544 fflush(stderr);
545 alloc_tracing = TRUE;
546 trace_on_at_malloc = 0;
547 }
548
549 if (alloc_tracing) {
550 fprintf(stderr,"ckalloc %lx %u %s %d\n",
551 (unsigned long)(size_t)result->body, size, file, line);
552 }
553
554 if (break_on_malloc && (total_mallocs >= break_on_malloc)) {
555 break_on_malloc = 0;
556 (void) fflush(stdout);
557 Tcl_Panic("reached malloc break limit (%d)", total_mallocs);
558 }
559
560 current_malloc_packets++;
561 if (current_malloc_packets > maximum_malloc_packets) {
562 maximum_malloc_packets = current_malloc_packets;
563 }
564 current_bytes_malloced += size;
565 if (current_bytes_malloced > maximum_bytes_malloced) {
566 maximum_bytes_malloced = current_bytes_malloced;
567 }
568
569 Tcl_MutexUnlock(ckallocMutexPtr);
570
571 return result->body;
572 }
573
574 /*
575 *----------------------------------------------------------------------
576 *
577 * Tcl_DbCkfree - debugging ckfree
578 *
579 * Verify that the low and high guards are intact, and if so then free
580 * the buffer else Tcl_Panic.
581 *
582 * The guards are erased after being checked to catch duplicate frees.
583 *
584 * The second and third arguments are file and line, these contain the
585 * filename and line number corresponding to the caller. These are sent
586 * by the ckfree macro; it uses the preprocessor autodefines __FILE__ and
587 * __LINE__.
588 *
589 *----------------------------------------------------------------------
590 */
591
592 void
593 Tcl_DbCkfree(
594 char *ptr,
595 const char *file,
596 int line)
597 {
598 struct mem_header *memp;
599
600 if (ptr == NULL) {
601 return;
602 }
603
604 /*
605 * The following cast is *very* tricky. Must convert the pointer to an
606 * integer before doing arithmetic on it, because otherwise the arithmetic
607 * will be done differently (and incorrectly) on word-addressed machines
608 * such as Crays (will subtract only bytes, even though BODY_OFFSET is in
609 * words on these machines).
610 */
611
612 memp = (struct mem_header *) (((size_t) ptr) - BODY_OFFSET);
613
614 if (alloc_tracing) {
615 fprintf(stderr, "ckfree %lx %ld %s %d\n",
616 (unsigned long)(size_t)memp->body, memp->length, file, line);
617 }
618
619 if (validate_memory) {
620 Tcl_ValidateAllMemory(file, line);
621 }
622
623 Tcl_MutexLock(ckallocMutexPtr);
624 ValidateMemory(memp, file, line, TRUE);
625 if (init_malloced_bodies) {
626 memset(ptr, GUARD_VALUE, memp->length);
627 }
628
629 total_frees++;
630 current_malloc_packets--;
631 current_bytes_malloced -= memp->length;
632
633 if (memp->tagPtr != NULL) {
634 memp->tagPtr->refCount--;
635 if ((memp->tagPtr->refCount == 0) && (curTagPtr != memp->tagPtr)) {
636 TclpFree((char *) memp->tagPtr);
637 }
638 }
639
640 /*
641 * Delink from allocated list
642 */
643
644 if (memp->flink != NULL) {
645 memp->flink->blink = memp->blink;
646 }
647 if (memp->blink != NULL) {
648 memp->blink->flink = memp->flink;
649 }
650 if (allocHead == memp) {
651 allocHead = memp->flink;
652 }
653 TclpFree((char *) memp);
654 Tcl_MutexUnlock(ckallocMutexPtr);
655 }
656
657 /*
658 *--------------------------------------------------------------------
659 *
660 * Tcl_DbCkrealloc - debugging ckrealloc
661 *
662 * Reallocate a chunk of memory by allocating a new one of the right
663 * size, copying the old data to the new location, and then freeing the
664 * old memory space, using all the memory checking features of this
665 * package.
666 *
667 *--------------------------------------------------------------------
668 */
669
670 char *
671 Tcl_DbCkrealloc(
672 char *ptr,
673 unsigned int size,
674 const char *file,
675 int line)
676 {
677 char *newPtr;
678 unsigned int copySize;
679 struct mem_header *memp;
680
681 if (ptr == NULL) {
682 return Tcl_DbCkalloc(size, file, line);
683 }
684
685 /*
686 * See comment from Tcl_DbCkfree before you change the following line.
687 */
688
689 memp = (struct mem_header *) (((size_t) ptr) - BODY_OFFSET);
690
691 copySize = size;
692 if (copySize > (unsigned int) memp->length) {
693 copySize = memp->length;
694 }
695 newPtr = Tcl_DbCkalloc(size, file, line);
696 memcpy(newPtr, ptr, copySize);
697 Tcl_DbCkfree(ptr, file, line);
698 return newPtr;
699 }
700
701 char *
702 Tcl_AttemptDbCkrealloc(
703 char *ptr,
704 unsigned int size,
705 const char *file,
706 int line)
707 {
708 char *newPtr;
709 unsigned int copySize;
710 struct mem_header *memp;
711
712 if (ptr == NULL) {
713 return Tcl_AttemptDbCkalloc(size, file, line);
714 }
715
716 /*
717 * See comment from Tcl_DbCkfree before you change the following line.
718 */
719
720 memp = (struct mem_header *) (((size_t) ptr) - BODY_OFFSET);
721
722 copySize = size;
723 if (copySize > (unsigned int) memp->length) {
724 copySize = memp->length;
725 }
726 newPtr = Tcl_AttemptDbCkalloc(size, file, line);
727 if (newPtr == NULL) {
728 return NULL;
729 }
730 memcpy(newPtr, ptr, copySize);
731 Tcl_DbCkfree(ptr, file, line);
732 return newPtr;
733 }
734
735
736 /*
737 *----------------------------------------------------------------------
738 *
739 * Tcl_Alloc, et al. --
740 *
741 * These functions are defined in terms of the debugging versions when
742 * TCL_MEM_DEBUG is set.
743 *
744 * Results:
745 * Same as the debug versions.
746 *
747 * Side effects:
748 * Same as the debug versions.
749 *
750 *----------------------------------------------------------------------
751 */
752
753 char *
754 Tcl_Alloc(
755 unsigned int size)
756 {
757 return Tcl_DbCkalloc(size, "unknown", 0);
758 }
759
760 char *
761 Tcl_AttemptAlloc(
762 unsigned int size)
763 {
764 return Tcl_AttemptDbCkalloc(size, "unknown", 0);
765 }
766
767 void
768 Tcl_Free(
769 char *ptr)
770 {
771 Tcl_DbCkfree(ptr, "unknown", 0);
772 }
773
774 char *
775 Tcl_Realloc(
776 char *ptr,
777 unsigned int size)
778 {
779 return Tcl_DbCkrealloc(ptr, size, "unknown", 0);
780 }
781 char *
782 Tcl_AttemptRealloc(
783 char *ptr,
784 unsigned int size)
785 {
786 return Tcl_AttemptDbCkrealloc(ptr, size, "unknown", 0);
787 }
788
789 /*
790 *----------------------------------------------------------------------
791 *
792 * MemoryCmd --
793 *
794 * Implements the Tcl "memory" command, which provides Tcl-level control
795 * of Tcl memory debugging information.
796 * memory active $file
797 * memory break_on_malloc $count
798 * memory info
799 * memory init on|off
800 * memory onexit $file
801 * memory tag $string
802 * memory trace on|off
803 * memory trace_on_at_malloc $count
804 * memory validate on|off
805 *
806 * Results:
807 * Standard TCL results.
808 *
809 *----------------------------------------------------------------------
810 */
811 /* ARGSUSED */
812 static int
813 MemoryCmd(
814 ClientData clientData,
815 Tcl_Interp *interp,
816 int argc,
817 const char *argv[])
818 {
819 const char *fileName;
820 FILE *fileP;
821 Tcl_DString buffer;
822 int result;
823 size_t len;
824
825 if (argc < 2) {
826 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
827 "wrong # args: should be \"%s option [args..]\"", argv[0]));
828 return TCL_ERROR;
829 }
830
831 if (strcmp(argv[1], "active") == 0 || strcmp(argv[1], "display") == 0) {
832 if (argc != 3) {
833 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
834 "wrong # args: should be \"%s %s file\"",
835 argv[0], argv[1]));
836 return TCL_ERROR;
837 }
838 fileName = Tcl_TranslateFileName(interp, argv[2], &buffer);
839 if (fileName == NULL) {
840 return TCL_ERROR;
841 }
842 result = Tcl_DumpActiveMemory(fileName);
843 Tcl_DStringFree(&buffer);
844 if (result != TCL_OK) {
845 Tcl_SetObjResult(interp, Tcl_ObjPrintf("error accessing %s: %s",
846 argv[2], Tcl_PosixError(interp)));
847 return TCL_ERROR;
848 }
849 return TCL_OK;
850 }
851 if (strcmp(argv[1],"break_on_malloc") == 0) {
852 if (argc != 3) {
853 goto argError;
854 }
855 if (Tcl_GetInt(interp, argv[2], &break_on_malloc) != TCL_OK) {
856 return TCL_ERROR;
857 }
858 return TCL_OK;
859 }
860 if (strcmp(argv[1],"info") == 0) {
861 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
862 "%-25s %10d\n%-25s %10d\n%-25s %10d\n%-25s %10lu\n%-25s %10d\n%-25s %10lu\n",
863 "total mallocs", total_mallocs, "total frees", total_frees,
864 "current packets allocated", current_malloc_packets,
865 "current bytes allocated", (unsigned long)current_bytes_malloced,
866 "maximum packets allocated", maximum_malloc_packets,
867 "maximum bytes allocated", (unsigned long)maximum_bytes_malloced));
868 return TCL_OK;
869 }
870 if (strcmp(argv[1], "init") == 0) {
871 if (argc != 3) {
872 goto bad_suboption;
873 }
874 init_malloced_bodies = (strcmp(argv[2],"on") == 0);
875 return TCL_OK;
876 }
877 if (strcmp(argv[1], "objs") == 0) {
878 if (argc != 3) {
879 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
880 "wrong # args: should be \"%s objs file\"", argv[0]));
881 return TCL_ERROR;
882 }
883 fileName = Tcl_TranslateFileName(interp, argv[2], &buffer);
884 if (fileName == NULL) {
885 return TCL_ERROR;
886 }
887 fileP = fopen(fileName, "w");
888 if (fileP == NULL) {
889 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
890 "cannot open output file: %s",
891 Tcl_PosixError(interp)));
892 return TCL_ERROR;
893 }
894 TclDbDumpActiveObjects(fileP);
895 fclose(fileP);
896 Tcl_DStringFree(&buffer);
897 return TCL_OK;
898 }
899 if (strcmp(argv[1],"onexit") == 0) {
900 if (argc != 3) {
901 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
902 "wrong # args: should be \"%s onexit file\"", argv[0]));
903 return TCL_ERROR;
904 }
905 fileName = Tcl_TranslateFileName(interp, argv[2], &buffer);
906 if (fileName == NULL) {
907 return TCL_ERROR;
908 }
909 onExitMemDumpFileName = dumpFile;
910 strcpy(onExitMemDumpFileName,fileName);
911 Tcl_DStringFree(&buffer);
912 return TCL_OK;
913 }
914 if (strcmp(argv[1],"tag") == 0) {
915 if (argc != 3) {
916 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
917 "wrong # args: should be \"%s tag string\"", argv[0]));
918 return TCL_ERROR;
919 }
920 if ((curTagPtr != NULL) && (curTagPtr->refCount == 0)) {
921 TclpFree((char *) curTagPtr);
922 }
923 len = strlen(argv[2]);
924 curTagPtr = (MemTag *) TclpAlloc(TAG_SIZE(len));
925 curTagPtr->refCount = 0;
926 memcpy(curTagPtr->string, argv[2], len + 1);
927 return TCL_OK;
928 }
929 if (strcmp(argv[1],"trace") == 0) {
930 if (argc != 3) {
931 goto bad_suboption;
932 }
933 alloc_tracing = (strcmp(argv[2],"on") == 0);
934 return TCL_OK;
935 }
936
937 if (strcmp(argv[1],"trace_on_at_malloc") == 0) {
938 if (argc != 3) {
939 goto argError;
940 }
941 if (Tcl_GetInt(interp, argv[2], &trace_on_at_malloc) != TCL_OK) {
942 return TCL_ERROR;
943 }
944 return TCL_OK;
945 }
946 if (strcmp(argv[1],"validate") == 0) {
947 if (argc != 3) {
948 goto bad_suboption;
949 }
950 validate_memory = (strcmp(argv[2],"on") == 0);
951 return TCL_OK;
952 }
953
954 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
955 "bad option \"%s\": should be active, break_on_malloc, info, "
956 "init, objs, onexit, tag, trace, trace_on_at_malloc, or validate",
957 argv[1]));
958 return TCL_ERROR;
959
960 argError:
961 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
962 "wrong # args: should be \"%s %s count\"", argv[0], argv[1]));
963 return TCL_ERROR;
964
965 bad_suboption:
966 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
967 "wrong # args: should be \"%s %s on|off\"", argv[0], argv[1]));
968 return TCL_ERROR;
969 }
970
971 /*
972 *----------------------------------------------------------------------
973 *
974 * CheckmemCmd --
975 *
976 * This is the command procedure for the "checkmem" command, which causes
977 * the application to exit after printing information about memory usage
978 * to the file passed to this command as its first argument.
979 *
980 * Results:
981 * Returns a standard Tcl completion code.
982 *
983 * Side effects:
984 * None.
985 *
986 *----------------------------------------------------------------------
987 */
988
989 static int
990 CheckmemCmd(
991 ClientData clientData, /* Not used. */
992 Tcl_Interp *interp, /* Interpreter for evaluation. */
993 int argc, /* Number of arguments. */
994 const char *argv[]) /* String values of arguments. */
995 {
996 if (argc != 2) {
997 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
998 "wrong # args: should be \"%s fileName\"", argv[0]));
999 return TCL_ERROR;
1000 }
1001 tclMemDumpFileName = dumpFile;
1002 strcpy(tclMemDumpFileName, argv[1]);
1003 return TCL_OK;
1004 }
1005
1006 /*
1007 *----------------------------------------------------------------------
1008 *
1009 * Tcl_InitMemory --
1010 *
1011 * Create the "memory" and "checkmem" commands in the given interpreter.
1012 *
1013 * Results:
1014 * None.
1015 *
1016 * Side effects:
1017 * New commands are added to the interpreter.
1018 *
1019 *----------------------------------------------------------------------
1020 */
1021
1022 void
1023 Tcl_InitMemory(
1024 Tcl_Interp *interp) /* Interpreter in which commands should be
1025 * added */
1026 {
1027 TclInitDbCkalloc();
1028 Tcl_CreateCommand(interp, "memory", MemoryCmd, NULL, NULL);
1029 Tcl_CreateCommand(interp, "checkmem", CheckmemCmd, NULL, NULL);
1030 }
1031
1032
1033 #else /* TCL_MEM_DEBUG */
1034
1035 /* This is the !TCL_MEM_DEBUG case */
1036
1037 #undef Tcl_InitMemory
1038 #undef Tcl_DumpActiveMemory
1039 #undef Tcl_ValidateAllMemory
1040
1041
1042 /*
1043 *----------------------------------------------------------------------
1044 *
1045 * Tcl_Alloc --
1046 *
1047 * Interface to TclpAlloc when TCL_MEM_DEBUG is disabled. It does check
1048 * that memory was actually allocated.
1049 *
1050 *----------------------------------------------------------------------
1051 */
1052
1053 char *
1054 Tcl_Alloc(
1055 unsigned int size)
1056 {
1057 char *result;
1058
1059 result = TclpAlloc(size);
1060
1061 /*
1062 * Most systems will not alloc(0), instead bumping it to one so that NULL
1063 * isn't returned. Some systems (AIX, Tru64) will alloc(0) by returning
1064 * NULL, so we have to check that the NULL we get is not in response to
1065 * alloc(0).
1066 *
1067 * The ANSI spec actually says that systems either return NULL *or* a
1068 * special pointer on failure, but we only check for NULL
1069 */
1070
1071 if ((result == NULL) && size) {
1072 Tcl_Panic("unable to alloc %u bytes", size);
1073 }
1074 return result;
1075 }
1076
1077 char *
1078 Tcl_DbCkalloc(
1079 unsigned int size,
1080 const char *file,
1081 int line)
1082 {
1083 char *result;
1084
1085 result = (char *) TclpAlloc(size);
1086
1087 if ((result == NULL) && size) {
1088 fflush(stdout);
1089 Tcl_Panic("unable to alloc %u bytes, %s line %d", size, file, line);
1090 }
1091 return result;
1092 }
1093
1094 /*
1095 *----------------------------------------------------------------------
1096 *
1097 * Tcl_AttemptAlloc --
1098 *
1099 * Interface to TclpAlloc when TCL_MEM_DEBUG is disabled. It does not
1100 * check that memory was actually allocated.
1101 *
1102 *----------------------------------------------------------------------
1103 */
1104
1105 char *
1106 Tcl_AttemptAlloc(
1107 unsigned int size)
1108 {
1109 char *result;
1110
1111 result = TclpAlloc(size);
1112 return result;
1113 }
1114
1115 char *
1116 Tcl_AttemptDbCkalloc(
1117 unsigned int size,
1118 const char *file,
1119 int line)
1120 {
1121 char *result;
1122 (void)file;
1123 (void)line;
1124
1125 result = (char *) TclpAlloc(size);
1126 return result;
1127 }
1128
1129 /*
1130 *----------------------------------------------------------------------
1131 *
1132 * Tcl_Realloc --
1133 *
1134 * Interface to TclpRealloc when TCL_MEM_DEBUG is disabled. It does check
1135 * that memory was actually allocated.
1136 *
1137 *----------------------------------------------------------------------
1138 */
1139
1140 char *
1141 Tcl_Realloc(
1142 char *ptr,
1143 unsigned int size)
1144 {
1145 char *result;
1146
1147 result = TclpRealloc(ptr, size);
1148
1149 if ((result == NULL) && size) {
1150 Tcl_Panic("unable to realloc %u bytes", size);
1151 }
1152 return result;
1153 }
1154
1155 char *
1156 Tcl_DbCkrealloc(
1157 char *ptr,
1158 unsigned int size,
1159 const char *file,
1160 int line)
1161 {
1162 char *result;
1163
1164 result = (char *) TclpRealloc(ptr, size);
1165
1166 if ((result == NULL) && size) {
1167 fflush(stdout);
1168 Tcl_Panic("unable to realloc %u bytes, %s line %d", size, file, line);
1169 }
1170 return result;
1171 }
1172
1173 /*
1174 *----------------------------------------------------------------------
1175 *
1176 * Tcl_AttemptRealloc --
1177 *
1178 * Interface to TclpRealloc when TCL_MEM_DEBUG is disabled. It does not
1179 * check that memory was actually allocated.
1180 *
1181 *----------------------------------------------------------------------
1182 */
1183
1184 char *
1185 Tcl_AttemptRealloc(
1186 char *ptr,
1187 unsigned int size)
1188 {
1189 char *result;
1190
1191 result = TclpRealloc(ptr, size);
1192 return result;
1193 }
1194
1195 char *
1196 Tcl_AttemptDbCkrealloc(
1197 char *ptr,
1198 unsigned int size,
1199 const char *file,
1200 int line)
1201 {
1202 char *result;
1203 (void)file;
1204 (void)line;
1205
1206 result = (char *) TclpRealloc(ptr, size);
1207 return result;
1208 }
1209
1210 /*
1211 *----------------------------------------------------------------------
1212 *
1213 * Tcl_Free --
1214 *
1215 * Interface to TclpFree when TCL_MEM_DEBUG is disabled. Done here rather
1216 * in the macro to keep some modules from being compiled with
1217 * TCL_MEM_DEBUG enabled and some with it disabled.
1218 *
1219 *----------------------------------------------------------------------
1220 */
1221
1222 void
1223 Tcl_Free(
1224 char *ptr)
1225 {
1226 TclpFree(ptr);
1227 }
1228
1229 void
1230 Tcl_DbCkfree(
1231 char *ptr,
1232 const char *file,
1233 int line)
1234 {
1235 (void)file;
1236 (void)line;
1237 TclpFree(ptr);
1238 }
1239
1240 /*
1241 *----------------------------------------------------------------------
1242 *
1243 * Tcl_InitMemory --
1244 *
1245 * Dummy initialization for memory command, which is only available if
1246 * TCL_MEM_DEBUG is on.
1247 *
1248 *----------------------------------------------------------------------
1249 */
1250 /* ARGSUSED */
1251 void
1252 Tcl_InitMemory(
1253 Tcl_Interp *interp)
1254 {
1255 (void)interp;
1256 }
1257
1258 int
1259 Tcl_DumpActiveMemory(
1260 const char *fileName)
1261 {
1262 (void)fileName;
1263 return TCL_OK;
1264 }
1265
1266 void
1267 Tcl_ValidateAllMemory(
1268 const char *file,
1269 int line)
1270 {
1271 (void)file;
1272 (void)line;
1273 }
1274
1275 int
1276 TclDumpMemoryInfo(
1277 ClientData clientData,
1278 int flags)
1279 {
1280 (void)clientData;
1281 (void)flags;
1282 return 1;
1283 }
1284
1285 #endif /* TCL_MEM_DEBUG */
1286
1287 /*
1288 *---------------------------------------------------------------------------
1289 *
1290 * TclFinalizeMemorySubsystem --
1291 *
1292 * This procedure is called to finalize all the structures that are used
1293 * by the memory allocator on a per-process basis.
1294 *
1295 * Results:
1296 * None.
1297 *
1298 * Side effects:
1299 * This subsystem is self-initializing, since memory can be allocated
1300 * before Tcl is formally initialized. After this call, this subsystem
1301 * has been reset to its initial state and is usable again.
1302 *
1303 *---------------------------------------------------------------------------
1304 */
1305
1306 void
1307 TclFinalizeMemorySubsystem(void)
1308 {
1309 #ifdef TCL_MEM_DEBUG
1310 if (tclMemDumpFileName != NULL) {
1311 Tcl_DumpActiveMemory(tclMemDumpFileName);
1312 } else if (onExitMemDumpFileName != NULL) {
1313 Tcl_DumpActiveMemory(onExitMemDumpFileName);
1314 }
1315
1316 Tcl_MutexLock(ckallocMutexPtr);
1317
1318 if (curTagPtr != NULL) {
1319 TclpFree((char *) curTagPtr);
1320 curTagPtr = NULL;
1321 }
1322 allocHead = NULL;
1323
1324 Tcl_MutexUnlock(ckallocMutexPtr);
1325 #endif
1326
1327 #if defined(USE_TCLALLOC) && USE_TCLALLOC
1328 TclFinalizeAllocSubsystem();
1329 #endif
1330 }
1331
1332 /*
1333 * Local Variables:
1334 * mode: c
1335 * c-basic-offset: 4
1336 * fill-column: 78
1337 * tab-width: 8
1338 * indent-tabs-mode: nil
1339 * End:
1340 */