3 * (c) 1999 Microsoft Corporation. All rights reserved.
4 * Portions (c) 1999 ActiveState Tool Corp, http://www.ActiveState.com/
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
11 * Defining _USE_MSVCRT_MEM_ALLOC will cause all memory allocations
12 * to be forwarded to MSVCRT.DLL. Defining _USE_LINKED_LIST as well will
13 * track all allocations in a doubly linked list, so that the host can
14 * free all memory allocated when it goes away.
15 * If _USE_MSVCRT_MEM_ALLOC is not defined then Knuth's boundary tag algorithm
16 * is used; defining _USE_BUDDY_BLOCKS will use Knuth's algorithm R
17 * (Buddy system reservation)
21 #ifndef ___VMEM_H_INC___
22 #define ___VMEM_H_INC___
25 #define _USE_MSVCRT_MEM_ALLOC
27 #define _USE_LINKED_LIST
29 // #define _USE_BUDDY_BLOCKS
33 #define ASSERT(f) if(!(f)) DebugBreak();
35 inline void MEMODS(char *str)
37 OutputDebugString(str);
38 OutputDebugString("\n");
41 inline void MEMODSlx(char *str, long x)
44 sprintf(szBuffer, "%s %lx\n", str, x);
45 OutputDebugString(szBuffer);
48 #define WALKHEAP() WalkHeap(0)
49 #define WALKHEAPTRACE() WalkHeap(1)
55 #define MEMODSlx(x, y)
57 #define WALKHEAPTRACE()
61 #ifdef _USE_MSVCRT_MEM_ALLOC
63 #ifndef _USE_LINKED_LIST
64 // #define _USE_LINKED_LIST
68 * Pass all memory requests throught to msvcrt.dll
69 * optionaly track by using a doubly linked header
72 typedef void (*LPFREE)(void *block);
73 typedef void* (*LPMALLOC)(size_t size);
74 typedef void* (*LPREALLOC)(void *block, size_t size);
75 #ifdef _USE_LINKED_LIST
77 typedef struct _MemoryBlockHeader* PMEMORY_BLOCK_HEADER;
78 typedef struct _MemoryBlockHeader {
79 PMEMORY_BLOCK_HEADER pNext;
80 PMEMORY_BLOCK_HEADER pPrev;
82 } MEMORY_BLOCK_HEADER, *PMEMORY_BLOCK_HEADER;
90 virtual void* Malloc(size_t size);
91 virtual void* Realloc(void* pMem, size_t size);
92 virtual void Free(void* pMem);
93 virtual void GetLock(void);
94 virtual void FreeLock(void);
95 virtual int IsLocked(void);
96 virtual long Release(void);
97 virtual long AddRef(void);
99 inline BOOL CreateOk(void)
105 #ifdef _USE_LINKED_LIST
106 void LinkBlock(PMEMORY_BLOCK_HEADER ptr)
108 PMEMORY_BLOCK_HEADER next = m_Dummy.pNext;
110 ptr->pPrev = &m_Dummy;
115 void UnlinkBlock(PMEMORY_BLOCK_HEADER ptr)
117 PMEMORY_BLOCK_HEADER next = ptr->pNext;
118 PMEMORY_BLOCK_HEADER prev = ptr->pPrev;
123 MEMORY_BLOCK_HEADER m_Dummy;
126 long m_lRefCount; // number of current users
127 CRITICAL_SECTION m_cs; // access lock
131 LPREALLOC m_prealloc;
137 InitializeCriticalSection(&m_cs);
138 #ifdef _USE_LINKED_LIST
139 m_Dummy.pNext = m_Dummy.pPrev = &m_Dummy;
140 m_Dummy.owner = this;
142 m_hLib = LoadLibrary("msvcrt.dll");
144 m_pfree = (LPFREE)GetProcAddress(m_hLib, "free");
145 m_pmalloc = (LPMALLOC)GetProcAddress(m_hLib, "malloc");
146 m_prealloc = (LPREALLOC)GetProcAddress(m_hLib, "realloc");
152 #ifdef _USE_LINKED_LIST
153 while (m_Dummy.pNext != &m_Dummy) {
154 Free(m_Dummy.pNext+1);
159 DeleteCriticalSection(&m_cs);
162 void* VMem::Malloc(size_t size)
164 #ifdef _USE_LINKED_LIST
166 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)m_pmalloc(size+sizeof(MEMORY_BLOCK_HEADER));
175 return m_pmalloc(size);
179 void* VMem::Realloc(void* pMem, size_t size)
181 #ifdef _USE_LINKED_LIST
191 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
193 ptr = (PMEMORY_BLOCK_HEADER)m_prealloc(ptr, size+sizeof(MEMORY_BLOCK_HEADER));
203 return m_prealloc(pMem, size);
207 void VMem::Free(void* pMem)
209 #ifdef _USE_LINKED_LIST
211 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
212 if (ptr->owner != this) {
217 Perl_warn(aTHX_ "Free to wrong pool %p not %p",this,ptr->owner);
218 *nowhere = 0; /* this segfault is deliberate,
219 so you can see the stack trace */
221 ptr->owner->Free(pMem);
237 void VMem::GetLock(void)
239 EnterCriticalSection(&m_cs);
242 void VMem::FreeLock(void)
244 LeaveCriticalSection(&m_cs);
247 int VMem::IsLocked(void)
250 /* XXX TryEnterCriticalSection() is not available in some versions
251 * of Windows 95. Since this code is not used anywhere yet, we
252 * skirt the issue for now. */
253 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
255 LeaveCriticalSection(&m_cs);
259 ASSERT(0); /* alarm bells for when somebody calls this */
264 long VMem::Release(void)
266 long lCount = InterlockedDecrement(&m_lRefCount);
272 long VMem::AddRef(void)
274 long lCount = InterlockedIncrement(&m_lRefCount);
278 #else /* _USE_MSVCRT_MEM_ALLOC */
281 * Knuth's boundary tag algorithm Vol #1, Page 440.
283 * Each block in the heap has tag words before and after it,
287 * The size is stored in these tags as a long word, and includes the 8 bytes
288 * of overhead that the boundary tags consume. Blocks are allocated on long
289 * word boundaries, so the size is always multiples of long words. When the
290 * block is allocated, bit 0, (the tag bit), of the size is set to 1. When
291 * a block is freed, it is merged with adjacent free blocks, and the tag bit
294 * A linked list is used to manage the free list. The first two long words of
295 * the block contain double links. These links are only valid when the block
296 * is freed, therefore space needs to be reserved for them. Thus, the minimum
297 * block size (not counting the tags) is 8 bytes.
299 * Since memory allocation may occur on a single threaded, explict locks are not
304 const long lAllocStart = 0x00020000; /* start at 128K */
305 const long minBlockSize = sizeof(void*)*2;
306 const long sizeofTag = sizeof(long);
307 const long blockOverhead = sizeofTag*2;
308 const long minAllocSize = minBlockSize+blockOverhead;
309 #ifdef _USE_BUDDY_BLOCKS
310 const long lSmallBlockSize = 1024;
311 const size_t nListEntries = ((lSmallBlockSize-minAllocSize)/sizeof(long));
313 inline size_t CalcEntry(size_t size)
315 ASSERT((size&(sizeof(long)-1)) == 0);
316 return ((size - minAllocSize) / sizeof(long));
320 typedef BYTE* PBLOCK; /* pointer to a memory block */
323 * Macros for accessing hidden fields in a memory block:
325 * SIZE size of this block (tag bit 0 is 1 if block is allocated)
326 * PSIZE size of previous physical block
329 #define SIZE(block) (*(ULONG*)(((PBLOCK)(block))-sizeofTag))
330 #define PSIZE(block) (*(ULONG*)(((PBLOCK)(block))-(blockOverhead)))
331 inline void SetTags(PBLOCK block, long size)
334 PSIZE(block+(size&~1)) = size;
339 * PREV pointer to previous block
340 * NEXT pointer to next block
343 #define PREV(block) (*(PBLOCK*)(block))
344 #define NEXT(block) (*(PBLOCK*)((block)+sizeof(PBLOCK)))
345 inline void SetLink(PBLOCK block, PBLOCK prev, PBLOCK next)
350 inline void Unlink(PBLOCK p)
352 PBLOCK next = NEXT(p);
353 PBLOCK prev = PREV(p);
357 #ifndef _USE_BUDDY_BLOCKS
358 inline void AddToFreeList(PBLOCK block, PBLOCK pInList)
360 PBLOCK next = NEXT(pInList);
361 NEXT(pInList) = block;
362 SetLink(block, pInList, next);
367 /* Macro for rounding up to the next sizeof(long) */
368 #define ROUND_UP(n) (((ULONG)(n)+sizeof(long)-1)&~(sizeof(long)-1))
369 #define ROUND_UP64K(n) (((ULONG)(n)+0x10000-1)&~(0x10000-1))
370 #define ROUND_DOWN(n) ((ULONG)(n)&~(sizeof(long)-1))
373 * HeapRec - a list of all non-contiguous heap areas
375 * Each record in this array contains information about a non-contiguous heap area.
378 const int maxHeaps = 32; /* 64 was overkill */
379 const long lAllocMax = 0x80000000; /* max size of allocation */
381 #ifdef _USE_BUDDY_BLOCKS
382 typedef struct _FreeListEntry
384 BYTE Dummy[minAllocSize]; // dummy free block
385 } FREE_LIST_ENTRY, *PFREE_LIST_ENTRY;
388 #ifndef _USE_BUDDY_BLOCKS
389 #define USE_BIGBLOCK_ALLOC
393 * Use VirtualAlloc() for blocks bigger than nMaxHeapAllocSize since
394 * Windows 95/98/Me have heap managers that are designed for memory
395 * blocks smaller than four megabytes.
398 #ifdef USE_BIGBLOCK_ALLOC
399 const int nMaxHeapAllocSize = (1024*512); /* don't allocate anything larger than this from the heap */
402 typedef struct _HeapRec
404 PBLOCK base; /* base of heap area */
405 ULONG len; /* size of heap area */
406 #ifdef USE_BIGBLOCK_ALLOC
407 BOOL bBigBlock; /* was allocate using VirtualAlloc */
416 virtual void* Malloc(size_t size);
417 virtual void* Realloc(void* pMem, size_t size);
418 virtual void Free(void* pMem);
419 virtual void GetLock(void);
420 virtual void FreeLock(void);
421 virtual int IsLocked(void);
422 virtual long Release(void);
423 virtual long AddRef(void);
425 inline BOOL CreateOk(void)
427 #ifdef _USE_BUDDY_BLOCKS
430 return m_hHeap != NULL;
438 int Getmem(size_t size);
440 int HeapAdd(void* ptr, size_t size
441 #ifdef USE_BIGBLOCK_ALLOC
446 void* Expand(void* block, size_t size);
448 #ifdef _USE_BUDDY_BLOCKS
449 inline PBLOCK GetFreeListLink(int index)
451 if (index >= nListEntries)
452 index = nListEntries-1;
453 return &m_FreeList[index].Dummy[sizeofTag];
455 inline PBLOCK GetOverSizeFreeList(void)
457 return &m_FreeList[nListEntries-1].Dummy[sizeofTag];
459 inline PBLOCK GetEOLFreeList(void)
461 return &m_FreeList[nListEntries].Dummy[sizeofTag];
464 void AddToFreeList(PBLOCK block, size_t size)
466 PBLOCK pFreeList = GetFreeListLink(CalcEntry(size));
467 PBLOCK next = NEXT(pFreeList);
468 NEXT(pFreeList) = block;
469 SetLink(block, pFreeList, next);
473 inline size_t CalcAllocSize(size_t size)
476 * Adjust the real size of the block to be a multiple of sizeof(long), and add
477 * the overhead for the boundary tags. Disallow negative or zero sizes.
479 return (size < minBlockSize) ? minAllocSize : (size_t)ROUND_UP(size) + blockOverhead;
482 #ifdef _USE_BUDDY_BLOCKS
483 FREE_LIST_ENTRY m_FreeList[nListEntries+1]; // free list with dummy end of list entry as well
485 HANDLE m_hHeap; // memory heap for this script
486 char m_FreeDummy[minAllocSize]; // dummy free block
487 PBLOCK m_pFreeList; // pointer to first block on free list
489 PBLOCK m_pRover; // roving pointer into the free list
490 HeapRec m_heaps[maxHeaps]; // list of all non-contiguous heap areas
491 int m_nHeaps; // no. of heaps in m_heaps
492 long m_lAllocSize; // current alloc size
493 long m_lRefCount; // number of current users
494 CRITICAL_SECTION m_cs; // access lock
497 void WalkHeap(int complete);
498 void MemoryUsageMessage(char *str, long x, long y, int c);
506 #ifndef _USE_BUDDY_BLOCKS
507 BOOL bRet = (NULL != (m_hHeap = HeapCreate(HEAP_NO_SERIALIZE,
508 lAllocStart, /* initial size of heap */
509 0))); /* no upper limit on size of heap */
513 InitializeCriticalSection(&m_cs);
523 #ifndef _USE_BUDDY_BLOCKS
524 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, NULL));
528 DeleteCriticalSection(&m_cs);
529 #ifdef _USE_BUDDY_BLOCKS
530 for(int index = 0; index < m_nHeaps; ++index) {
531 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
533 #else /* !_USE_BUDDY_BLOCKS */
534 #ifdef USE_BIGBLOCK_ALLOC
535 for(int index = 0; index < m_nHeaps; ++index) {
536 if (m_heaps[index].bBigBlock) {
537 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
541 BOOL bRet = HeapDestroy(m_hHeap);
543 #endif /* _USE_BUDDY_BLOCKS */
546 void VMem::ReInit(void)
548 for(int index = 0; index < m_nHeaps; ++index) {
549 #ifdef _USE_BUDDY_BLOCKS
550 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
552 #ifdef USE_BIGBLOCK_ALLOC
553 if (m_heaps[index].bBigBlock) {
554 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
558 HeapFree(m_hHeap, HEAP_NO_SERIALIZE, m_heaps[index].base);
559 #endif /* _USE_BUDDY_BLOCKS */
565 void VMem::Init(void)
567 #ifdef _USE_BUDDY_BLOCKS
570 * Initialize the free list by placing a dummy zero-length block on it.
571 * Set the end of list marker.
572 * Set the number of non-contiguous heaps to zero.
573 * Set the next allocation size.
575 for (int index = 0; index < nListEntries; ++index) {
576 pFreeList = GetFreeListLink(index);
577 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
578 PREV(pFreeList) = NEXT(pFreeList) = pFreeList;
580 pFreeList = GetEOLFreeList();
581 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
582 PREV(pFreeList) = NEXT(pFreeList) = NULL;
583 m_pRover = GetOverSizeFreeList();
586 * Initialize the free list by placing a dummy zero-length block on it.
587 * Set the number of non-contiguous heaps to zero.
589 m_pFreeList = m_pRover = (PBLOCK)(&m_FreeDummy[sizeofTag]);
590 PSIZE(m_pFreeList+minAllocSize) = SIZE(m_pFreeList) = 0;
591 PREV(m_pFreeList) = NEXT(m_pFreeList) = m_pFreeList;
595 m_lAllocSize = lAllocStart;
598 void* VMem::Malloc(size_t size)
605 * Disallow negative or zero sizes.
607 size_t realsize = CalcAllocSize(size);
608 if((int)realsize < minAllocSize || size == 0)
611 #ifdef _USE_BUDDY_BLOCKS
613 * Check the free list of small blocks if this is free use it
614 * Otherwise check the rover if it has no blocks then
615 * Scan the free list entries use the first free block
616 * split the block if needed, stop at end of list marker
619 int index = CalcEntry(realsize);
620 if (index < nListEntries-1) {
621 ptr = GetFreeListLink(index);
623 if (lsize >= realsize) {
624 rem = lsize - realsize;
625 if(rem < minAllocSize) {
626 /* Unlink the block from the free list. */
632 * The remainder is big enough to split off into a new block.
633 * Use the end of the block, resize the beginning of the block
634 * no need to change the free list.
640 SetTags(ptr, lsize | 1);
645 if (lsize >= realsize) {
646 rem = lsize - realsize;
647 if(rem < minAllocSize) {
648 /* Unlink the block from the free list. */
654 * The remainder is big enough to split off into a new block.
655 * Use the end of the block, resize the beginning of the block
656 * no need to change the free list.
662 SetTags(ptr, lsize | 1);
665 ptr = GetFreeListLink(index+1);
668 if (lsize >= realsize) {
669 size_t rem = lsize - realsize;
670 if(rem < minAllocSize) {
671 /* Unlink the block from the free list. */
677 * The remainder is big enough to split off into a new block.
678 * Use the end of the block, resize the beginning of the block
679 * no need to change the free list.
685 SetTags(ptr, lsize | 1);
688 ptr += sizeof(FREE_LIST_ENTRY);
695 * Start searching the free list at the rover. If we arrive back at rover without
696 * finding anything, allocate some memory from the heap and try again.
698 ptr = m_pRover; /* start searching at rover */
699 int loops = 2; /* allow two times through the loop */
702 ASSERT((lsize&1)==0);
703 /* is block big enough? */
704 if(lsize >= realsize) {
705 /* if the remainder is too small, don't bother splitting the block. */
706 rem = lsize - realsize;
707 if(rem < minAllocSize) {
709 m_pRover = NEXT(ptr);
711 /* Unlink the block from the free list. */
717 * The remainder is big enough to split off into a new block.
718 * Use the end of the block, resize the beginning of the block
719 * no need to change the free list.
725 /* Set the boundary tags to mark it as allocated. */
726 SetTags(ptr, lsize | 1);
727 return ((void *)ptr);
731 * This block was unsuitable. If we've gone through this list once already without
732 * finding anything, allocate some new memory from the heap and try again.
735 if(ptr == m_pRover) {
736 if(!(loops-- && Getmem(realsize))) {
744 void* VMem::Realloc(void* block, size_t size)
748 /* if size is zero, free the block. */
754 /* if block pointer is NULL, do a Malloc(). */
759 * Grow or shrink the block in place.
760 * if the block grows then the next block will be used if free
762 if(Expand(block, size) != NULL)
765 size_t realsize = CalcAllocSize(size);
766 if((int)realsize < minAllocSize)
770 * see if the previous block is free, and is it big enough to cover the new size
771 * if merged with the current block.
773 PBLOCK ptr = (PBLOCK)block;
774 size_t cursize = SIZE(ptr) & ~1;
775 size_t psize = PSIZE(ptr);
776 if((psize&1) == 0 && (psize + cursize) >= realsize) {
777 PBLOCK prev = ptr - psize;
779 m_pRover = NEXT(prev);
781 /* Unlink the next block from the free list. */
784 /* Copy contents of old block to new location, make it the current block. */
785 memmove(prev, ptr, cursize);
786 cursize += psize; /* combine sizes */
789 size_t rem = cursize - realsize;
790 if(rem >= minAllocSize) {
792 * The remainder is big enough to be a new block. Set boundary
793 * tags for the resized block and the new block.
795 prev = ptr + realsize;
797 * add the new block to the free list.
798 * next block cannot be free
801 #ifdef _USE_BUDDY_BLOCKS
802 AddToFreeList(prev, rem);
804 AddToFreeList(prev, m_pFreeList);
808 /* Set the boundary tags to mark it as allocated. */
809 SetTags(ptr, cursize | 1);
810 return ((void *)ptr);
813 /* Allocate a new block, copy the old to the new, and free the old. */
814 if((ptr = (PBLOCK)Malloc(size)) != NULL) {
815 memmove(ptr, block, cursize-blockOverhead);
818 return ((void *)ptr);
821 void VMem::Free(void* p)
825 /* Ignore null pointer. */
829 PBLOCK ptr = (PBLOCK)p;
831 /* Check for attempt to free a block that's already free. */
832 size_t size = SIZE(ptr);
834 MEMODSlx("Attempt to free previously freed block", (long)p);
837 size &= ~1; /* remove allocated tag */
839 /* if previous block is free, add this block to it. */
840 #ifndef _USE_BUDDY_BLOCKS
843 size_t psize = PSIZE(ptr);
845 ptr -= psize; /* point to previous block */
846 size += psize; /* merge the sizes of the two blocks */
847 #ifdef _USE_BUDDY_BLOCKS
850 linked = TRUE; /* it's already on the free list */
854 /* if the next physical block is free, merge it with this block. */
855 PBLOCK next = ptr + size; /* point to next physical block */
856 size_t nsize = SIZE(next);
858 /* block is free move rover if needed */
860 m_pRover = NEXT(next);
862 /* unlink the next block from the free list. */
865 /* merge the sizes of this block and the next block. */
869 /* Set the boundary tags for the block; */
872 /* Link the block to the head of the free list. */
873 #ifdef _USE_BUDDY_BLOCKS
874 AddToFreeList(ptr, size);
877 AddToFreeList(ptr, m_pFreeList);
882 void VMem::GetLock(void)
884 EnterCriticalSection(&m_cs);
887 void VMem::FreeLock(void)
889 LeaveCriticalSection(&m_cs);
892 int VMem::IsLocked(void)
895 /* XXX TryEnterCriticalSection() is not available in some versions
896 * of Windows 95. Since this code is not used anywhere yet, we
897 * skirt the issue for now. */
898 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
900 LeaveCriticalSection(&m_cs);
904 ASSERT(0); /* alarm bells for when somebody calls this */
910 long VMem::Release(void)
912 long lCount = InterlockedDecrement(&m_lRefCount);
918 long VMem::AddRef(void)
920 long lCount = InterlockedIncrement(&m_lRefCount);
925 int VMem::Getmem(size_t requestSize)
926 { /* returns -1 is successful 0 if not */
927 #ifdef USE_BIGBLOCK_ALLOC
932 /* Round up size to next multiple of 64K. */
933 size_t size = (size_t)ROUND_UP64K(requestSize);
936 * if the size requested is smaller than our current allocation size
939 if(size < (unsigned long)m_lAllocSize)
942 /* Update the size to allocate on the next request */
943 if(m_lAllocSize != lAllocMax)
946 #ifndef _USE_BUDDY_BLOCKS
948 #ifdef USE_BIGBLOCK_ALLOC
949 && !m_heaps[m_nHeaps-1].bBigBlock
952 /* Expand the last allocated heap */
953 ptr = HeapReAlloc(m_hHeap, HEAP_REALLOC_IN_PLACE_ONLY|HEAP_NO_SERIALIZE,
954 m_heaps[m_nHeaps-1].base,
955 m_heaps[m_nHeaps-1].len + size);
957 HeapAdd(((char*)ptr) + m_heaps[m_nHeaps-1].len, size
958 #ifdef USE_BIGBLOCK_ALLOC
965 #endif /* _USE_BUDDY_BLOCKS */
968 * if we didn't expand a block to cover the requested size
969 * allocate a new Heap
970 * the size of this block must include the additional dummy tags at either end
971 * the above ROUND_UP64K may not have added any memory to include this.
973 if(size == requestSize)
974 size = (size_t)ROUND_UP64K(requestSize+(blockOverhead));
977 #ifdef _USE_BUDDY_BLOCKS
978 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
980 #ifdef USE_BIGBLOCK_ALLOC
982 if (size >= nMaxHeapAllocSize) {
984 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
988 ptr = HeapAlloc(m_hHeap, HEAP_NO_SERIALIZE, size);
989 #endif /* _USE_BUDDY_BLOCKS */
992 /* try to allocate a smaller chunk */
994 if(size > requestSize)
999 MEMODSlx("HeapAlloc failed on size!!!", size);
1003 #ifdef _USE_BUDDY_BLOCKS
1004 if (HeapAdd(ptr, size)) {
1005 VirtualFree(ptr, 0, MEM_RELEASE);
1009 #ifdef USE_BIGBLOCK_ALLOC
1010 if (HeapAdd(ptr, size, bBigBlock)) {
1012 VirtualFree(ptr, 0, MEM_RELEASE);
1018 #endif /* _USE_BUDDY_BLOCKS */
1022 int VMem::HeapAdd(void* p, size_t size
1023 #ifdef USE_BIGBLOCK_ALLOC
1027 { /* if the block can be succesfully added to the heap, returns 0; otherwise -1. */
1030 /* Check size, then round size down to next long word boundary. */
1031 if(size < minAllocSize)
1034 size = (size_t)ROUND_DOWN(size);
1035 PBLOCK ptr = (PBLOCK)p;
1037 #ifdef USE_BIGBLOCK_ALLOC
1041 * Search for another heap area that's contiguous with the bottom of this new area.
1042 * (It should be extremely unusual to find one that's contiguous with the top).
1044 for(index = 0; index < m_nHeaps; ++index) {
1045 if(ptr == m_heaps[index].base + (int)m_heaps[index].len) {
1047 * The new block is contiguous with a previously allocated heap area. Add its
1048 * length to that of the previous heap. Merge it with the dummy end-of-heap
1049 * area marker of the previous heap.
1051 m_heaps[index].len += size;
1055 #ifdef USE_BIGBLOCK_ALLOC
1062 if(index == m_nHeaps) {
1063 /* The new block is not contiguous, or is BigBlock. Add it to the heap list. */
1064 if(m_nHeaps == maxHeaps) {
1065 return -1; /* too many non-contiguous heaps */
1067 m_heaps[m_nHeaps].base = ptr;
1068 m_heaps[m_nHeaps].len = size;
1069 #ifdef USE_BIGBLOCK_ALLOC
1070 m_heaps[m_nHeaps].bBigBlock = bBigBlock;
1075 * Reserve the first LONG in the block for the ending boundary tag of a dummy
1076 * block at the start of the heap area.
1078 size -= blockOverhead;
1079 ptr += blockOverhead;
1080 PSIZE(ptr) = 1; /* mark the dummy previous block as allocated */
1084 * Convert the heap to one large block. Set up its boundary tags, and those of
1085 * marker block after it. The marker block before the heap will already have
1086 * been set up if this heap is not contiguous with the end of another heap.
1088 SetTags(ptr, size | 1);
1089 PBLOCK next = ptr + size; /* point to dummy end block */
1090 SIZE(next) = 1; /* mark the dummy end block as allocated */
1093 * Link the block to the start of the free list by calling free().
1094 * This will merge the block with any adjacent free blocks.
1101 void* VMem::Expand(void* block, size_t size)
1104 * Disallow negative or zero sizes.
1106 size_t realsize = CalcAllocSize(size);
1107 if((int)realsize < minAllocSize || size == 0)
1110 PBLOCK ptr = (PBLOCK)block;
1112 /* if the current size is the same as requested, do nothing. */
1113 size_t cursize = SIZE(ptr) & ~1;
1114 if(cursize == realsize) {
1118 /* if the block is being shrunk, convert the remainder of the block into a new free block. */
1119 if(realsize <= cursize) {
1120 size_t nextsize = cursize - realsize; /* size of new remainder block */
1121 if(nextsize >= minAllocSize) {
1124 * Set boundary tags for the resized block and the new block.
1126 SetTags(ptr, realsize | 1);
1130 * add the new block to the free list.
1131 * call Free to merge this block with next block if free
1133 SetTags(ptr, nextsize | 1);
1140 PBLOCK next = ptr + cursize;
1141 size_t nextsize = SIZE(next);
1143 /* Check the next block for consistency.*/
1144 if((nextsize&1) == 0 && (nextsize + cursize) >= realsize) {
1146 * The next block is free and big enough. Add the part that's needed
1147 * to our block, and split the remainder off into a new block.
1149 if(m_pRover == next)
1150 m_pRover = NEXT(next);
1152 /* Unlink the next block from the free list. */
1154 cursize += nextsize; /* combine sizes */
1156 size_t rem = cursize - realsize; /* size of remainder */
1157 if(rem >= minAllocSize) {
1159 * The remainder is big enough to be a new block.
1160 * Set boundary tags for the resized block and the new block.
1162 next = ptr + realsize;
1164 * add the new block to the free list.
1165 * next block cannot be free
1168 #ifdef _USE_BUDDY_BLOCKS
1169 AddToFreeList(next, rem);
1171 AddToFreeList(next, m_pFreeList);
1175 /* Set the boundary tags to mark it as allocated. */
1176 SetTags(ptr, cursize | 1);
1177 return ((void *)ptr);
1183 #define LOG_FILENAME ".\\MemLog.txt"
1185 void VMem::MemoryUsageMessage(char *str, long x, long y, int c)
1190 m_pLog = fopen(LOG_FILENAME, "w");
1191 sprintf(szBuffer, str, x, y, c);
1192 fputs(szBuffer, m_pLog);
1203 void VMem::WalkHeap(int complete)
1206 MemoryUsageMessage(NULL, 0, 0, 0);
1208 for(int i = 0; i < m_nHeaps; ++i) {
1209 total += m_heaps[i].len;
1211 MemoryUsageMessage("VMem heaps used %d. Total memory %08x\n", m_nHeaps, total, 0);
1213 /* Walk all the heaps - verify structures */
1214 for(int index = 0; index < m_nHeaps; ++index) {
1215 PBLOCK ptr = m_heaps[index].base;
1216 size_t size = m_heaps[index].len;
1217 #ifndef _USE_BUDDY_BLOCKS
1218 #ifdef USE_BIGBLOCK_ALLOC
1219 if (!m_heaps[m_nHeaps].bBigBlock)
1221 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, ptr));
1224 /* set over reserved header block */
1225 size -= blockOverhead;
1226 ptr += blockOverhead;
1227 PBLOCK pLast = ptr + size;
1228 ASSERT(PSIZE(ptr) == 1); /* dummy previous block is allocated */
1229 ASSERT(SIZE(pLast) == 1); /* dummy next block is allocated */
1230 while(ptr < pLast) {
1231 ASSERT(ptr > m_heaps[index].base);
1232 size_t cursize = SIZE(ptr) & ~1;
1233 ASSERT((PSIZE(ptr+cursize) & ~1) == cursize);
1234 MemoryUsageMessage("Memory Block %08x: Size %08x %c\n", (long)ptr, cursize, (SIZE(ptr)&1) ? 'x' : ' ');
1235 if(!(SIZE(ptr)&1)) {
1236 /* this block is on the free list */
1237 PBLOCK tmp = NEXT(ptr);
1239 ASSERT((SIZE(tmp)&1)==0);
1240 if(tmp == m_pFreeList)
1246 MemoryUsageMessage("Memory Block %08x: Size %08x free but not in free list\n", (long)ptr, cursize, 0);
1252 MemoryUsageMessage(NULL, 0, 0, 0);
1255 #endif /* _DEBUG_MEM */
1257 #endif /* _USE_MSVCRT_MEM_ALLOC */
1259 #endif /* ___VMEM_H_INC___ */