Debian Codegraph @

generic/tclAlloc.c

raw
1 /*
2 * tclAlloc.c --
3 *
4 * This is a very fast storage allocator. It allocates blocks of a small
5 * number of different sizes, and keeps free lists of each size. Blocks
6 * that don't exactly fit are passed up to the next larger size. Blocks
7 * over a certain size are directly allocated from the system.
8 *
9 * Copyright (c) 1983 Regents of the University of California.
10 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
11 * Copyright (c) 1998-1999 Scriptics Corporation.
12 *
13 * Portions contributed by Chris Kingsley, Jack Jansen and Ray Johnson.
14 *
15 * See the file "license.terms" for information on usage and redistribution of
16 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
17 */
18
19 /*
20 * Windows and Unix use an alternative allocator when building with threads
21 * that has significantly reduced lock contention.
22 */
23
24 #include "tclInt.h"
25 #if !defined(TCL_THREADS) || !defined(USE_THREAD_ALLOC)
26
27 #if defined(USE_TCLALLOC) && USE_TCLALLOC
28
29 /*
30 * We should really make use of AC_CHECK_TYPE(caddr_t) here, but it can wait
31 * until Tcl uses config.h properly.
32 */
33
34 #if defined(_MSC_VER) || defined(__MSVCRT__) || defined(__BORLANDC__)
35 typedef unsigned long caddr_t;
36 #endif
37
38 /*
39 * The overhead on a block is at least 8 bytes. When free, this space contains
40 * a pointer to the next free block, and the bottom two bits must be zero.
41 * When in use, the first byte is set to MAGIC, and the second byte is the
42 * size index. The remaining bytes are for alignment. If range checking is
43 * enabled then a second word holds the size of the requested block, less 1,
44 * rounded up to a multiple of sizeof(RMAGIC). The order of elements is
45 * critical: ov.magic must overlay the low order bits of ov.next, and ov.magic
46 * can not be a valid ov.next bit pattern.
47 */
48
49 union overhead {
50 union overhead *next; /* when free */
51 unsigned char padding[TCL_ALLOCALIGN]; /* align struct to TCL_ALLOCALIGN bytes */
52 struct {
53 unsigned char magic0; /* magic number */
54 unsigned char index; /* bucket # */
55 unsigned char unused; /* unused */
56 unsigned char magic1; /* other magic number */
57 #ifndef NDEBUG
58 unsigned short rmagic; /* range magic number */
59 unsigned long size; /* actual block size */
60 unsigned short unused2; /* padding to 8-byte align */
61 #endif
62 } ovu;
63 #define overMagic0 ovu.magic0
64 #define overMagic1 ovu.magic1
65 #define bucketIndex ovu.index
66 #define rangeCheckMagic ovu.rmagic
67 #define realBlockSize ovu.size
68 };
69
70
71 #define MAGIC 0xEF /* magic # on accounting info */
72 #define RMAGIC 0x5555 /* magic # on range info */
73
74 #ifndef NDEBUG
75 #define RSLOP sizeof(unsigned short)
76 #else
77 #define RSLOP 0
78 #endif
79
80 #define OVERHEAD (sizeof(union overhead) + RSLOP)
81
82 /*
83 * Macro to make it easier to refer to the end-of-block guard magic.
84 */
85
86 #define BLOCK_END(overPtr) \
87 (*(unsigned short *)((caddr_t)((overPtr) + 1) + (overPtr)->realBlockSize))
88
89 /*
90 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
91 * smallest allocatable block is MINBLOCK bytes. The overhead information
92 * precedes the data area returned to the user.
93 */
94
95 #define MINBLOCK ((sizeof(union overhead) + (TCL_ALLOCALIGN-1)) & ~(TCL_ALLOCALIGN-1))
96 #define NBUCKETS (13 - (MINBLOCK >> 4))
97 #define MAXMALLOC (1<<(NBUCKETS+2))
98 static union overhead *nextf[NBUCKETS];
99
100 /*
101 * The following structure is used to keep track of all system memory
102 * currently owned by Tcl. When finalizing, all this memory will be returned
103 * to the system.
104 */
105
106 struct block {
107 struct block *nextPtr; /* Linked list. */
108 struct block *prevPtr; /* Linked list for big blocks, ensures 8-byte
109 * alignment for suballocated blocks. */
110 };
111
112 static struct block *blockList; /* Tracks the suballocated blocks. */
113 static struct block bigBlocks={ /* Big blocks aren't suballocated. */
114 &bigBlocks, &bigBlocks
115 };
116
117 /*
118 * The allocator is protected by a special mutex that must be explicitly
119 * initialized. Furthermore, because Tcl_Alloc may be used before anything else
120 * in Tcl, we make this module self-initializing after all with the allocInit
121 * variable.
122 */
123
124 #ifdef TCL_THREADS
125 static Tcl_Mutex *allocMutexPtr;
126 #endif
127 static int allocInit = 0;
128
129 #ifdef MSTATS
130
131 /*
132 * numMallocs[i] is the difference between the number of mallocs and frees for
133 * a given block size.
134 */
135
136 static unsigned int numMallocs[NBUCKETS+1];
137 #endif
138
139 #if !defined(NDEBUG)
140 #define ASSERT(p) if (!(p)) Tcl_Panic(# p)
141 #define RANGE_ASSERT(p) if (!(p)) Tcl_Panic(# p)
142 #else
143 #define ASSERT(p)
144 #define RANGE_ASSERT(p)
145 #endif
146
147 /*
148 * Prototypes for functions used only in this file.
149 */
150
151 static void MoreCore(int bucket);
152
153 /*
154 *-------------------------------------------------------------------------
155 *
156 * TclInitAlloc --
157 *
158 * Initialize the memory system.
159 *
160 * Results:
161 * None.
162 *
163 * Side effects:
164 * Initialize the mutex used to serialize allocations.
165 *
166 *-------------------------------------------------------------------------
167 */
168
169 void
170 TclInitAlloc(void)
171 {
172 if (!allocInit) {
173 allocInit = 1;
174 #ifdef TCL_THREADS
175 allocMutexPtr = Tcl_GetAllocMutex();
176 #endif
177 }
178 }
179
180 /*
181 *-------------------------------------------------------------------------
182 *
183 * TclFinalizeAllocSubsystem --
184 *
185 * Release all resources being used by this subsystem, including
186 * aggressively freeing all memory allocated by TclpAlloc() that has not
187 * yet been released with TclpFree().
188 *
189 * After this function is called, all memory allocated with TclpAlloc()
190 * should be considered unusable.
191 *
192 * Results:
193 * None.
194 *
195 * Side effects:
196 * This subsystem is self-initializing, since memory can be allocated
197 * before Tcl is formally initialized. After this call, this subsystem
198 * has been reset to its initial state and is usable again.
199 *
200 *-------------------------------------------------------------------------
201 */
202
203 void
204 TclFinalizeAllocSubsystem(void)
205 {
206 unsigned int i;
207 struct block *blockPtr, *nextPtr;
208
209 Tcl_MutexLock(allocMutexPtr);
210 for (blockPtr = blockList; blockPtr != NULL; blockPtr = nextPtr) {
211 nextPtr = blockPtr->nextPtr;
212 TclpSysFree(blockPtr);
213 }
214 blockList = NULL;
215
216 for (blockPtr = bigBlocks.nextPtr; blockPtr != &bigBlocks; ) {
217 nextPtr = blockPtr->nextPtr;
218 TclpSysFree(blockPtr);
219 blockPtr = nextPtr;
220 }
221 bigBlocks.nextPtr = &bigBlocks;
222 bigBlocks.prevPtr = &bigBlocks;
223
224 for (i=0 ; i<NBUCKETS ; i++) {
225 nextf[i] = NULL;
226 #ifdef MSTATS
227 numMallocs[i] = 0;
228 #endif
229 }
230 #ifdef MSTATS
231 numMallocs[i] = 0;
232 #endif
233 Tcl_MutexUnlock(allocMutexPtr);
234 }
235
236 /*
237 *----------------------------------------------------------------------
238 *
239 * TclpAlloc --
240 *
241 * Allocate more memory.
242 *
243 * Results:
244 * None.
245 *
246 * Side effects:
247 * None.
248 *
249 *----------------------------------------------------------------------
250 */
251
252 char *
253 TclpAlloc(
254 unsigned int numBytes) /* Number of bytes to allocate. */
255 {
256 union overhead *overPtr;
257 long bucket;
258 unsigned amount;
259 struct block *bigBlockPtr = NULL;
260
261 if (!allocInit) {
262 /*
263 * We have to make the "self initializing" because Tcl_Alloc may be
264 * used before any other part of Tcl. E.g., see main() for tclsh!
265 */
266
267 TclInitAlloc();
268 }
269 Tcl_MutexLock(allocMutexPtr);
270
271 /*
272 * First the simple case: we simple allocate big blocks directly.
273 */
274
275 if (numBytes >= MAXMALLOC - OVERHEAD) {
276 if (numBytes <= UINT_MAX - OVERHEAD -sizeof(struct block)) {
277 bigBlockPtr = (struct block *) TclpSysAlloc(
278 sizeof(struct block) + OVERHEAD + numBytes, 0);
279 }
280 if (bigBlockPtr == NULL) {
281 Tcl_MutexUnlock(allocMutexPtr);
282 return NULL;
283 }
284 bigBlockPtr->nextPtr = bigBlocks.nextPtr;
285 bigBlocks.nextPtr = bigBlockPtr;
286 bigBlockPtr->prevPtr = &bigBlocks;
287 bigBlockPtr->nextPtr->prevPtr = bigBlockPtr;
288
289 overPtr = (union overhead *) (bigBlockPtr + 1);
290 overPtr->overMagic0 = overPtr->overMagic1 = MAGIC;
291 overPtr->bucketIndex = 0xFF;
292 #ifdef MSTATS
293 numMallocs[NBUCKETS]++;
294 #endif
295
296 #ifndef NDEBUG
297 /*
298 * Record allocated size of block and bound space with magic numbers.
299 */
300
301 overPtr->realBlockSize = (numBytes + RSLOP - 1) & ~(RSLOP - 1);
302 overPtr->rangeCheckMagic = RMAGIC;
303 BLOCK_END(overPtr) = RMAGIC;
304 #endif
305
306 Tcl_MutexUnlock(allocMutexPtr);
307 return (void *)(overPtr+1);
308 }
309
310 /*
311 * Convert amount of memory requested into closest block size stored in
312 * hash buckets which satisfies request. Account for space used per block
313 * for accounting.
314 */
315
316 amount = MINBLOCK; /* size of first bucket */
317 bucket = MINBLOCK >> 4;
318
319 while (numBytes + OVERHEAD > amount) {
320 amount <<= 1;
321 if (amount == 0) {
322 Tcl_MutexUnlock(allocMutexPtr);
323 return NULL;
324 }
325 bucket++;
326 }
327 ASSERT(bucket < NBUCKETS);
328
329 /*
330 * If nothing in hash bucket right now, request more memory from the
331 * system.
332 */
333
334 if ((overPtr = nextf[bucket]) == NULL) {
335 MoreCore(bucket);
336 if ((overPtr = nextf[bucket]) == NULL) {
337 Tcl_MutexUnlock(allocMutexPtr);
338 return NULL;
339 }
340 }
341
342 /*
343 * Remove from linked list
344 */
345
346 nextf[bucket] = overPtr->next;
347 overPtr->overMagic0 = overPtr->overMagic1 = MAGIC;
348 overPtr->bucketIndex = UCHAR(bucket);
349
350 #ifdef MSTATS
351 numMallocs[bucket]++;
352 #endif
353
354 #ifndef NDEBUG
355 /*
356 * Record allocated size of block and bound space with magic numbers.
357 */
358
359 overPtr->realBlockSize = (numBytes + RSLOP - 1) & ~(RSLOP - 1);
360 overPtr->rangeCheckMagic = RMAGIC;
361 BLOCK_END(overPtr) = RMAGIC;
362 #endif
363
364 Tcl_MutexUnlock(allocMutexPtr);
365 return ((char *)(overPtr + 1));
366 }
367
368 /*
369 *----------------------------------------------------------------------
370 *
371 * MoreCore --
372 *
373 * Allocate more memory to the indicated bucket.
374 *
375 * Assumes Mutex is already held.
376 *
377 * Results:
378 * None.
379 *
380 * Side effects:
381 * Attempts to get more memory from the system.
382 *
383 *----------------------------------------------------------------------
384 */
385
386 static void
387 MoreCore(
388 int bucket) /* Bucket to allocate to. */
389 {
390 union overhead *overPtr;
391 long size; /* size of desired block */
392 long amount; /* amount to allocate */
393 int numBlocks; /* how many blocks we get */
394 struct block *blockPtr;
395
396 /*
397 * sbrk_size <= 0 only for big, FLUFFY, requests (about 2^30 bytes on a
398 * VAX, I think) or for a negative arg.
399 */
400
401 size = 1 << (bucket + 3);
402 ASSERT(size > 0);
403
404 amount = MAXMALLOC;
405 numBlocks = amount / size;
406 ASSERT(numBlocks*size == amount);
407
408 blockPtr = (struct block *) TclpSysAlloc(
409 (sizeof(struct block) + amount), 1);
410 /* no more room! */
411 if (blockPtr == NULL) {
412 return;
413 }
414 blockPtr->nextPtr = blockList;
415 blockList = blockPtr;
416
417 overPtr = (union overhead *) (blockPtr + 1);
418
419 /*
420 * Add new memory allocated to that on free list for this hash bucket.
421 */
422
423 nextf[bucket] = overPtr;
424 while (--numBlocks > 0) {
425 overPtr->next = (union overhead *)((caddr_t)overPtr + size);
426 overPtr = (union overhead *)((caddr_t)overPtr + size);
427 }
428 overPtr->next = NULL;
429 }
430
431 /*
432 *----------------------------------------------------------------------
433 *
434 * TclpFree --
435 *
436 * Free memory.
437 *
438 * Results:
439 * None.
440 *
441 * Side effects:
442 * None.
443 *
444 *----------------------------------------------------------------------
445 */
446
447 void
448 TclpFree(
449 char *oldPtr) /* Pointer to memory to free. */
450 {
451 long size;
452 union overhead *overPtr;
453 struct block *bigBlockPtr;
454
455 if (oldPtr == NULL) {
456 return;
457 }
458
459 Tcl_MutexLock(allocMutexPtr);
460 overPtr = (union overhead *)((caddr_t)oldPtr - sizeof(union overhead));
461
462 ASSERT(overPtr->overMagic0 == MAGIC); /* make sure it was in use */
463 ASSERT(overPtr->overMagic1 == MAGIC);
464 if (overPtr->overMagic0 != MAGIC || overPtr->overMagic1 != MAGIC) {
465 Tcl_MutexUnlock(allocMutexPtr);
466 return;
467 }
468
469 RANGE_ASSERT(overPtr->rangeCheckMagic == RMAGIC);
470 RANGE_ASSERT(BLOCK_END(overPtr) == RMAGIC);
471 size = overPtr->bucketIndex;
472 if (size == 0xFF) {
473 #ifdef MSTATS
474 numMallocs[NBUCKETS]--;
475 #endif
476
477 bigBlockPtr = (struct block *) overPtr - 1;
478 bigBlockPtr->prevPtr->nextPtr = bigBlockPtr->nextPtr;
479 bigBlockPtr->nextPtr->prevPtr = bigBlockPtr->prevPtr;
480 TclpSysFree(bigBlockPtr);
481
482 Tcl_MutexUnlock(allocMutexPtr);
483 return;
484 }
485 ASSERT(size < NBUCKETS);
486 overPtr->next = nextf[size]; /* also clobbers overMagic */
487 nextf[size] = overPtr;
488
489 #ifdef MSTATS
490 numMallocs[size]--;
491 #endif
492
493 Tcl_MutexUnlock(allocMutexPtr);
494 }
495
496 /*
497 *----------------------------------------------------------------------
498 *
499 * TclpRealloc --
500 *
501 * Reallocate memory.
502 *
503 * Results:
504 * None.
505 *
506 * Side effects:
507 * None.
508 *
509 *----------------------------------------------------------------------
510 */
511
512 char *
513 TclpRealloc(
514 char *oldPtr, /* Pointer to alloc'ed block. */
515 unsigned int numBytes) /* New size of memory. */
516 {
517 int i;
518 union overhead *overPtr;
519 struct block *bigBlockPtr;
520 int expensive;
521 unsigned long maxSize;
522
523 if (oldPtr == NULL) {
524 return TclpAlloc(numBytes);
525 }
526
527 Tcl_MutexLock(allocMutexPtr);
528
529 overPtr = (union overhead *)((caddr_t)oldPtr - sizeof(union overhead));
530
531 ASSERT(overPtr->overMagic0 == MAGIC); /* make sure it was in use */
532 ASSERT(overPtr->overMagic1 == MAGIC);
533 if (overPtr->overMagic0 != MAGIC || overPtr->overMagic1 != MAGIC) {
534 Tcl_MutexUnlock(allocMutexPtr);
535 return NULL;
536 }
537
538 RANGE_ASSERT(overPtr->rangeCheckMagic == RMAGIC);
539 RANGE_ASSERT(BLOCK_END(overPtr) == RMAGIC);
540 i = overPtr->bucketIndex;
541
542 /*
543 * If the block isn't in a bin, just realloc it.
544 */
545
546 if (i == 0xFF) {
547 struct block *prevPtr, *nextPtr;
548 bigBlockPtr = (struct block *) overPtr - 1;
549 prevPtr = bigBlockPtr->prevPtr;
550 nextPtr = bigBlockPtr->nextPtr;
551 bigBlockPtr = (struct block *) TclpSysRealloc(bigBlockPtr,
552 sizeof(struct block) + OVERHEAD + numBytes);
553 if (bigBlockPtr == NULL) {
554 Tcl_MutexUnlock(allocMutexPtr);
555 return NULL;
556 }
557
558 if (prevPtr->nextPtr != bigBlockPtr) {
559 /*
560 * If the block has moved, splice the new block into the list
561 * where the old block used to be.
562 */
563
564 prevPtr->nextPtr = bigBlockPtr;
565 nextPtr->prevPtr = bigBlockPtr;
566 }
567
568 overPtr = (union overhead *) (bigBlockPtr + 1);
569
570 #ifdef MSTATS
571 numMallocs[NBUCKETS]++;
572 #endif
573
574 #ifndef NDEBUG
575 /*
576 * Record allocated size of block and update magic number bounds.
577 */
578
579 overPtr->realBlockSize = (numBytes + RSLOP - 1) & ~(RSLOP - 1);
580 BLOCK_END(overPtr) = RMAGIC;
581 #endif
582
583 Tcl_MutexUnlock(allocMutexPtr);
584 return (char *)(overPtr+1);
585 }
586 maxSize = 1 << (i+3);
587 expensive = 0;
588 if (numBytes+OVERHEAD > maxSize) {
589 expensive = 1;
590 } else if (i>0 && numBytes+OVERHEAD < maxSize/2) {
591 expensive = 1;
592 }
593
594 if (expensive) {
595 void *newPtr;
596
597 Tcl_MutexUnlock(allocMutexPtr);
598
599 newPtr = TclpAlloc(numBytes);
600 if (newPtr == NULL) {
601 return NULL;
602 }
603 maxSize -= OVERHEAD;
604 if (maxSize < numBytes) {
605 numBytes = maxSize;
606 }
607 memcpy(newPtr, oldPtr, numBytes);
608 TclpFree(oldPtr);
609 return newPtr;
610 }
611
612 /*
613 * No need to copy. It fits as-is.
614 */
615
616 #ifndef NDEBUG
617 overPtr->realBlockSize = (numBytes + RSLOP - 1) & ~(RSLOP - 1);
618 BLOCK_END(overPtr) = RMAGIC;
619 #endif
620
621 Tcl_MutexUnlock(allocMutexPtr);
622 return(oldPtr);
623 }
624
625 /*
626 *----------------------------------------------------------------------
627 *
628 * mstats --
629 *
630 * Prints two lines of numbers, one showing the length of the free list
631 * for each size category, the second showing the number of mallocs -
632 * frees for each size category.
633 *
634 * Results:
635 * None.
636 *
637 * Side effects:
638 * None.
639 *
640 *----------------------------------------------------------------------
641 */
642
643 #ifdef MSTATS
644 void
645 mstats(
646 char *s) /* Where to write info. */
647 {
648 int i, j;
649 union overhead *overPtr;
650 int totalFree = 0, totalUsed = 0;
651
652 Tcl_MutexLock(allocMutexPtr);
653
654 fprintf(stderr, "Memory allocation statistics %s\nTclpFree:\t", s);
655 for (i = 0; i < NBUCKETS; i++) {
656 for (j=0, overPtr=nextf[i]; overPtr; overPtr=overPtr->next, j++) {
657 fprintf(stderr, " %d", j);
658 }
659 totalFree += j * (1 << (i + 3));
660 }
661
662 fprintf(stderr, "\nused:\t");
663 for (i = 0; i < NBUCKETS; i++) {
664 fprintf(stderr, " %d", numMallocs[i]);
665 totalUsed += numMallocs[i] * (1 << (i + 3));
666 }
667
668 fprintf(stderr, "\n\tTotal small in use: %d, total free: %d\n",
669 totalUsed, totalFree);
670 fprintf(stderr, "\n\tNumber of big (>%d) blocks in use: %d\n",
671 MAXMALLOC, numMallocs[NBUCKETS]);
672
673 Tcl_MutexUnlock(allocMutexPtr);
674 }
675 #endif
676
677 #else /* !USE_TCLALLOC */
678
679 /*
680 *----------------------------------------------------------------------
681 *
682 * TclpAlloc --
683 *
684 * Allocate more memory.
685 *
686 * Results:
687 * None.
688 *
689 * Side effects:
690 * None.
691 *
692 *----------------------------------------------------------------------
693 */
694
695 char *
696 TclpAlloc(
697 unsigned int numBytes) /* Number of bytes to allocate. */
698 {
699 return (char *) malloc(numBytes);
700 }
701
702 /*
703 *----------------------------------------------------------------------
704 *
705 * TclpFree --
706 *
707 * Free memory.
708 *
709 * Results:
710 * None.
711 *
712 * Side effects:
713 * None.
714 *
715 *----------------------------------------------------------------------
716 */
717
718 void
719 TclpFree(
720 char *oldPtr) /* Pointer to memory to free. */
721 {
722 free(oldPtr);
723 return;
724 }
725
726 /*
727 *----------------------------------------------------------------------
728 *
729 * TclpRealloc --
730 *
731 * Reallocate memory.
732 *
733 * Results:
734 * None.
735 *
736 * Side effects:
737 * None.
738 *
739 *----------------------------------------------------------------------
740 */
741
742 char *
743 TclpRealloc(
744 char *oldPtr, /* Pointer to alloced block. */
745 unsigned int numBytes) /* New size of memory. */
746 {
747 return (char *) realloc(oldPtr, numBytes);
748 }
749
750 #endif /* !USE_TCLALLOC */
751 #else
752 TCL_MAC_EMPTY_FILE(generic_tclAlloc_c)
753 #endif /* !TCL_THREADS */
754
755 /*
756 * Local Variables:
757 * mode: c
758 * c-basic-offset: 4
759 * fill-column: 78
760 * End:
761 */