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));
171 return m_pmalloc(size);
175 void* VMem::Realloc(void* pMem, size_t size)
177 #ifdef _USE_LINKED_LIST
187 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
189 ptr = (PMEMORY_BLOCK_HEADER)m_prealloc(ptr, size+sizeof(MEMORY_BLOCK_HEADER));
195 return m_prealloc(pMem, size);
199 void VMem::Free(void* pMem)
201 #ifdef _USE_LINKED_LIST
203 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
204 if (ptr->owner != this) {
209 Perl_warn(aTHX_ "Free to wrong pool %p not %p",this,ptr->owner);
210 *nowhere = 0; /* this segfault is deliberate,
211 so you can see the stack trace */
213 ptr->owner->Free(pMem);
229 void VMem::GetLock(void)
231 EnterCriticalSection(&m_cs);
234 void VMem::FreeLock(void)
236 LeaveCriticalSection(&m_cs);
239 int VMem::IsLocked(void)
242 /* XXX TryEnterCriticalSection() is not available in some versions
243 * of Windows 95. Since this code is not used anywhere yet, we
244 * skirt the issue for now. */
245 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
247 LeaveCriticalSection(&m_cs);
251 ASSERT(0); /* alarm bells for when somebody calls this */
256 long VMem::Release(void)
258 long lCount = InterlockedDecrement(&m_lRefCount);
264 long VMem::AddRef(void)
266 long lCount = InterlockedIncrement(&m_lRefCount);
270 #else /* _USE_MSVCRT_MEM_ALLOC */
273 * Knuth's boundary tag algorithm Vol #1, Page 440.
275 * Each block in the heap has tag words before and after it,
279 * The size is stored in these tags as a long word, and includes the 8 bytes
280 * of overhead that the boundary tags consume. Blocks are allocated on long
281 * word boundaries, so the size is always multiples of long words. When the
282 * block is allocated, bit 0, (the tag bit), of the size is set to 1. When
283 * a block is freed, it is merged with adjacent free blocks, and the tag bit
286 * A linked list is used to manage the free list. The first two long words of
287 * the block contain double links. These links are only valid when the block
288 * is freed, therefore space needs to be reserved for them. Thus, the minimum
289 * block size (not counting the tags) is 8 bytes.
291 * Since memory allocation may occur on a single threaded, explict locks are not
296 const long lAllocStart = 0x00020000; /* start at 128K */
297 const long minBlockSize = sizeof(void*)*2;
298 const long sizeofTag = sizeof(long);
299 const long blockOverhead = sizeofTag*2;
300 const long minAllocSize = minBlockSize+blockOverhead;
301 #ifdef _USE_BUDDY_BLOCKS
302 const long lSmallBlockSize = 1024;
303 const size_t nListEntries = ((lSmallBlockSize-minAllocSize)/sizeof(long));
305 inline size_t CalcEntry(size_t size)
307 ASSERT((size&(sizeof(long)-1)) == 0);
308 return ((size - minAllocSize) / sizeof(long));
312 typedef BYTE* PBLOCK; /* pointer to a memory block */
315 * Macros for accessing hidden fields in a memory block:
317 * SIZE size of this block (tag bit 0 is 1 if block is allocated)
318 * PSIZE size of previous physical block
321 #define SIZE(block) (*(ULONG*)(((PBLOCK)(block))-sizeofTag))
322 #define PSIZE(block) (*(ULONG*)(((PBLOCK)(block))-(blockOverhead)))
323 inline void SetTags(PBLOCK block, long size)
326 PSIZE(block+(size&~1)) = size;
331 * PREV pointer to previous block
332 * NEXT pointer to next block
335 #define PREV(block) (*(PBLOCK*)(block))
336 #define NEXT(block) (*(PBLOCK*)((block)+sizeof(PBLOCK)))
337 inline void SetLink(PBLOCK block, PBLOCK prev, PBLOCK next)
342 inline void Unlink(PBLOCK p)
344 PBLOCK next = NEXT(p);
345 PBLOCK prev = PREV(p);
349 #ifndef _USE_BUDDY_BLOCKS
350 inline void AddToFreeList(PBLOCK block, PBLOCK pInList)
352 PBLOCK next = NEXT(pInList);
353 NEXT(pInList) = block;
354 SetLink(block, pInList, next);
359 /* Macro for rounding up to the next sizeof(long) */
360 #define ROUND_UP(n) (((ULONG)(n)+sizeof(long)-1)&~(sizeof(long)-1))
361 #define ROUND_UP64K(n) (((ULONG)(n)+0x10000-1)&~(0x10000-1))
362 #define ROUND_DOWN(n) ((ULONG)(n)&~(sizeof(long)-1))
365 * HeapRec - a list of all non-contiguous heap areas
367 * Each record in this array contains information about a non-contiguous heap area.
370 const int maxHeaps = 32; /* 64 was overkill */
371 const long lAllocMax = 0x80000000; /* max size of allocation */
373 #ifdef _USE_BUDDY_BLOCKS
374 typedef struct _FreeListEntry
376 BYTE Dummy[minAllocSize]; // dummy free block
377 } FREE_LIST_ENTRY, *PFREE_LIST_ENTRY;
380 #ifndef _USE_BUDDY_BLOCKS
381 #define USE_BIGBLOCK_ALLOC
385 * Use VirtualAlloc() for blocks bigger than nMaxHeapAllocSize since
386 * Windows 95/98/Me have heap managers that are designed for memory
387 * blocks smaller than four megabytes.
390 #ifdef USE_BIGBLOCK_ALLOC
391 const int nMaxHeapAllocSize = (1024*512); /* don't allocate anything larger than this from the heap */
394 typedef struct _HeapRec
396 PBLOCK base; /* base of heap area */
397 ULONG len; /* size of heap area */
398 #ifdef USE_BIGBLOCK_ALLOC
399 BOOL bBigBlock; /* was allocate using VirtualAlloc */
408 virtual void* Malloc(size_t size);
409 virtual void* Realloc(void* pMem, size_t size);
410 virtual void Free(void* pMem);
411 virtual void GetLock(void);
412 virtual void FreeLock(void);
413 virtual int IsLocked(void);
414 virtual long Release(void);
415 virtual long AddRef(void);
417 inline BOOL CreateOk(void)
419 #ifdef _USE_BUDDY_BLOCKS
422 return m_hHeap != NULL;
430 int Getmem(size_t size);
432 int HeapAdd(void* ptr, size_t size
433 #ifdef USE_BIGBLOCK_ALLOC
438 void* Expand(void* block, size_t size);
440 #ifdef _USE_BUDDY_BLOCKS
441 inline PBLOCK GetFreeListLink(int index)
443 if (index >= nListEntries)
444 index = nListEntries-1;
445 return &m_FreeList[index].Dummy[sizeofTag];
447 inline PBLOCK GetOverSizeFreeList(void)
449 return &m_FreeList[nListEntries-1].Dummy[sizeofTag];
451 inline PBLOCK GetEOLFreeList(void)
453 return &m_FreeList[nListEntries].Dummy[sizeofTag];
456 void AddToFreeList(PBLOCK block, size_t size)
458 PBLOCK pFreeList = GetFreeListLink(CalcEntry(size));
459 PBLOCK next = NEXT(pFreeList);
460 NEXT(pFreeList) = block;
461 SetLink(block, pFreeList, next);
465 inline size_t CalcAllocSize(size_t size)
468 * Adjust the real size of the block to be a multiple of sizeof(long), and add
469 * the overhead for the boundary tags. Disallow negative or zero sizes.
471 return (size < minBlockSize) ? minAllocSize : (size_t)ROUND_UP(size) + blockOverhead;
474 #ifdef _USE_BUDDY_BLOCKS
475 FREE_LIST_ENTRY m_FreeList[nListEntries+1]; // free list with dummy end of list entry as well
477 HANDLE m_hHeap; // memory heap for this script
478 char m_FreeDummy[minAllocSize]; // dummy free block
479 PBLOCK m_pFreeList; // pointer to first block on free list
481 PBLOCK m_pRover; // roving pointer into the free list
482 HeapRec m_heaps[maxHeaps]; // list of all non-contiguous heap areas
483 int m_nHeaps; // no. of heaps in m_heaps
484 long m_lAllocSize; // current alloc size
485 long m_lRefCount; // number of current users
486 CRITICAL_SECTION m_cs; // access lock
489 void WalkHeap(int complete);
490 void MemoryUsageMessage(char *str, long x, long y, int c);
498 #ifndef _USE_BUDDY_BLOCKS
499 BOOL bRet = (NULL != (m_hHeap = HeapCreate(HEAP_NO_SERIALIZE,
500 lAllocStart, /* initial size of heap */
501 0))); /* no upper limit on size of heap */
505 InitializeCriticalSection(&m_cs);
515 #ifndef _USE_BUDDY_BLOCKS
516 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, NULL));
520 DeleteCriticalSection(&m_cs);
521 #ifdef _USE_BUDDY_BLOCKS
522 for(int index = 0; index < m_nHeaps; ++index) {
523 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
525 #else /* !_USE_BUDDY_BLOCKS */
526 #ifdef USE_BIGBLOCK_ALLOC
527 for(int index = 0; index < m_nHeaps; ++index) {
528 if (m_heaps[index].bBigBlock) {
529 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
533 BOOL bRet = HeapDestroy(m_hHeap);
535 #endif /* _USE_BUDDY_BLOCKS */
538 void VMem::ReInit(void)
540 for(int index = 0; index < m_nHeaps; ++index) {
541 #ifdef _USE_BUDDY_BLOCKS
542 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
544 #ifdef USE_BIGBLOCK_ALLOC
545 if (m_heaps[index].bBigBlock) {
546 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
550 HeapFree(m_hHeap, HEAP_NO_SERIALIZE, m_heaps[index].base);
551 #endif /* _USE_BUDDY_BLOCKS */
557 void VMem::Init(void)
559 #ifdef _USE_BUDDY_BLOCKS
562 * Initialize the free list by placing a dummy zero-length block on it.
563 * Set the end of list marker.
564 * Set the number of non-contiguous heaps to zero.
565 * Set the next allocation size.
567 for (int index = 0; index < nListEntries; ++index) {
568 pFreeList = GetFreeListLink(index);
569 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
570 PREV(pFreeList) = NEXT(pFreeList) = pFreeList;
572 pFreeList = GetEOLFreeList();
573 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
574 PREV(pFreeList) = NEXT(pFreeList) = NULL;
575 m_pRover = GetOverSizeFreeList();
578 * Initialize the free list by placing a dummy zero-length block on it.
579 * Set the number of non-contiguous heaps to zero.
581 m_pFreeList = m_pRover = (PBLOCK)(&m_FreeDummy[sizeofTag]);
582 PSIZE(m_pFreeList+minAllocSize) = SIZE(m_pFreeList) = 0;
583 PREV(m_pFreeList) = NEXT(m_pFreeList) = m_pFreeList;
587 m_lAllocSize = lAllocStart;
590 void* VMem::Malloc(size_t size)
597 * Disallow negative or zero sizes.
599 size_t realsize = CalcAllocSize(size);
600 if((int)realsize < minAllocSize || size == 0)
603 #ifdef _USE_BUDDY_BLOCKS
605 * Check the free list of small blocks if this is free use it
606 * Otherwise check the rover if it has no blocks then
607 * Scan the free list entries use the first free block
608 * split the block if needed, stop at end of list marker
611 int index = CalcEntry(realsize);
612 if (index < nListEntries-1) {
613 ptr = GetFreeListLink(index);
615 if (lsize >= realsize) {
616 rem = lsize - realsize;
617 if(rem < minAllocSize) {
618 /* Unlink the block from the free list. */
624 * The remainder is big enough to split off into a new block.
625 * Use the end of the block, resize the beginning of the block
626 * no need to change the free list.
632 SetTags(ptr, lsize | 1);
637 if (lsize >= realsize) {
638 rem = lsize - realsize;
639 if(rem < minAllocSize) {
640 /* Unlink the block from the free list. */
646 * The remainder is big enough to split off into a new block.
647 * Use the end of the block, resize the beginning of the block
648 * no need to change the free list.
654 SetTags(ptr, lsize | 1);
657 ptr = GetFreeListLink(index+1);
660 if (lsize >= realsize) {
661 size_t rem = lsize - realsize;
662 if(rem < minAllocSize) {
663 /* Unlink the block from the free list. */
669 * The remainder is big enough to split off into a new block.
670 * Use the end of the block, resize the beginning of the block
671 * no need to change the free list.
677 SetTags(ptr, lsize | 1);
680 ptr += sizeof(FREE_LIST_ENTRY);
687 * Start searching the free list at the rover. If we arrive back at rover without
688 * finding anything, allocate some memory from the heap and try again.
690 ptr = m_pRover; /* start searching at rover */
691 int loops = 2; /* allow two times through the loop */
694 ASSERT((lsize&1)==0);
695 /* is block big enough? */
696 if(lsize >= realsize) {
697 /* if the remainder is too small, don't bother splitting the block. */
698 rem = lsize - realsize;
699 if(rem < minAllocSize) {
701 m_pRover = NEXT(ptr);
703 /* Unlink the block from the free list. */
709 * The remainder is big enough to split off into a new block.
710 * Use the end of the block, resize the beginning of the block
711 * no need to change the free list.
717 /* Set the boundary tags to mark it as allocated. */
718 SetTags(ptr, lsize | 1);
719 return ((void *)ptr);
723 * This block was unsuitable. If we've gone through this list once already without
724 * finding anything, allocate some new memory from the heap and try again.
727 if(ptr == m_pRover) {
728 if(!(loops-- && Getmem(realsize))) {
736 void* VMem::Realloc(void* block, size_t size)
740 /* if size is zero, free the block. */
746 /* if block pointer is NULL, do a Malloc(). */
751 * Grow or shrink the block in place.
752 * if the block grows then the next block will be used if free
754 if(Expand(block, size) != NULL)
757 size_t realsize = CalcAllocSize(size);
758 if((int)realsize < minAllocSize)
762 * see if the previous block is free, and is it big enough to cover the new size
763 * if merged with the current block.
765 PBLOCK ptr = (PBLOCK)block;
766 size_t cursize = SIZE(ptr) & ~1;
767 size_t psize = PSIZE(ptr);
768 if((psize&1) == 0 && (psize + cursize) >= realsize) {
769 PBLOCK prev = ptr - psize;
771 m_pRover = NEXT(prev);
773 /* Unlink the next block from the free list. */
776 /* Copy contents of old block to new location, make it the current block. */
777 memmove(prev, ptr, cursize);
778 cursize += psize; /* combine sizes */
781 size_t rem = cursize - realsize;
782 if(rem >= minAllocSize) {
784 * The remainder is big enough to be a new block. Set boundary
785 * tags for the resized block and the new block.
787 prev = ptr + realsize;
789 * add the new block to the free list.
790 * next block cannot be free
793 #ifdef _USE_BUDDY_BLOCKS
794 AddToFreeList(prev, rem);
796 AddToFreeList(prev, m_pFreeList);
800 /* Set the boundary tags to mark it as allocated. */
801 SetTags(ptr, cursize | 1);
802 return ((void *)ptr);
805 /* Allocate a new block, copy the old to the new, and free the old. */
806 if((ptr = (PBLOCK)Malloc(size)) != NULL) {
807 memmove(ptr, block, cursize-blockOverhead);
810 return ((void *)ptr);
813 void VMem::Free(void* p)
817 /* Ignore null pointer. */
821 PBLOCK ptr = (PBLOCK)p;
823 /* Check for attempt to free a block that's already free. */
824 size_t size = SIZE(ptr);
826 MEMODSlx("Attempt to free previously freed block", (long)p);
829 size &= ~1; /* remove allocated tag */
831 /* if previous block is free, add this block to it. */
832 #ifndef _USE_BUDDY_BLOCKS
835 size_t psize = PSIZE(ptr);
837 ptr -= psize; /* point to previous block */
838 size += psize; /* merge the sizes of the two blocks */
839 #ifdef _USE_BUDDY_BLOCKS
842 linked = TRUE; /* it's already on the free list */
846 /* if the next physical block is free, merge it with this block. */
847 PBLOCK next = ptr + size; /* point to next physical block */
848 size_t nsize = SIZE(next);
850 /* block is free move rover if needed */
852 m_pRover = NEXT(next);
854 /* unlink the next block from the free list. */
857 /* merge the sizes of this block and the next block. */
861 /* Set the boundary tags for the block; */
864 /* Link the block to the head of the free list. */
865 #ifdef _USE_BUDDY_BLOCKS
866 AddToFreeList(ptr, size);
869 AddToFreeList(ptr, m_pFreeList);
874 void VMem::GetLock(void)
876 EnterCriticalSection(&m_cs);
879 void VMem::FreeLock(void)
881 LeaveCriticalSection(&m_cs);
884 int VMem::IsLocked(void)
887 /* XXX TryEnterCriticalSection() is not available in some versions
888 * of Windows 95. Since this code is not used anywhere yet, we
889 * skirt the issue for now. */
890 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
892 LeaveCriticalSection(&m_cs);
896 ASSERT(0); /* alarm bells for when somebody calls this */
902 long VMem::Release(void)
904 long lCount = InterlockedDecrement(&m_lRefCount);
910 long VMem::AddRef(void)
912 long lCount = InterlockedIncrement(&m_lRefCount);
917 int VMem::Getmem(size_t requestSize)
918 { /* returns -1 is successful 0 if not */
919 #ifdef USE_BIGBLOCK_ALLOC
924 /* Round up size to next multiple of 64K. */
925 size_t size = (size_t)ROUND_UP64K(requestSize);
928 * if the size requested is smaller than our current allocation size
931 if(size < (unsigned long)m_lAllocSize)
934 /* Update the size to allocate on the next request */
935 if(m_lAllocSize != lAllocMax)
938 #ifndef _USE_BUDDY_BLOCKS
940 #ifdef USE_BIGBLOCK_ALLOC
941 && !m_heaps[m_nHeaps-1].bBigBlock
944 /* Expand the last allocated heap */
945 ptr = HeapReAlloc(m_hHeap, HEAP_REALLOC_IN_PLACE_ONLY|HEAP_NO_SERIALIZE,
946 m_heaps[m_nHeaps-1].base,
947 m_heaps[m_nHeaps-1].len + size);
949 HeapAdd(((char*)ptr) + m_heaps[m_nHeaps-1].len, size
950 #ifdef USE_BIGBLOCK_ALLOC
957 #endif /* _USE_BUDDY_BLOCKS */
960 * if we didn't expand a block to cover the requested size
961 * allocate a new Heap
962 * the size of this block must include the additional dummy tags at either end
963 * the above ROUND_UP64K may not have added any memory to include this.
965 if(size == requestSize)
966 size = (size_t)ROUND_UP64K(requestSize+(blockOverhead));
969 #ifdef _USE_BUDDY_BLOCKS
970 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
972 #ifdef USE_BIGBLOCK_ALLOC
974 if (size >= nMaxHeapAllocSize) {
976 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
980 ptr = HeapAlloc(m_hHeap, HEAP_NO_SERIALIZE, size);
981 #endif /* _USE_BUDDY_BLOCKS */
984 /* try to allocate a smaller chunk */
986 if(size > requestSize)
991 MEMODSlx("HeapAlloc failed on size!!!", size);
995 #ifdef _USE_BUDDY_BLOCKS
996 if (HeapAdd(ptr, size)) {
997 VirtualFree(ptr, 0, MEM_RELEASE);
1001 #ifdef USE_BIGBLOCK_ALLOC
1002 if (HeapAdd(ptr, size, bBigBlock)) {
1004 VirtualFree(ptr, 0, MEM_RELEASE);
1010 #endif /* _USE_BUDDY_BLOCKS */
1014 int VMem::HeapAdd(void* p, size_t size
1015 #ifdef USE_BIGBLOCK_ALLOC
1019 { /* if the block can be succesfully added to the heap, returns 0; otherwise -1. */
1022 /* Check size, then round size down to next long word boundary. */
1023 if(size < minAllocSize)
1026 size = (size_t)ROUND_DOWN(size);
1027 PBLOCK ptr = (PBLOCK)p;
1029 #ifdef USE_BIGBLOCK_ALLOC
1033 * Search for another heap area that's contiguous with the bottom of this new area.
1034 * (It should be extremely unusual to find one that's contiguous with the top).
1036 for(index = 0; index < m_nHeaps; ++index) {
1037 if(ptr == m_heaps[index].base + (int)m_heaps[index].len) {
1039 * The new block is contiguous with a previously allocated heap area. Add its
1040 * length to that of the previous heap. Merge it with the dummy end-of-heap
1041 * area marker of the previous heap.
1043 m_heaps[index].len += size;
1047 #ifdef USE_BIGBLOCK_ALLOC
1054 if(index == m_nHeaps) {
1055 /* The new block is not contiguous, or is BigBlock. Add it to the heap list. */
1056 if(m_nHeaps == maxHeaps) {
1057 return -1; /* too many non-contiguous heaps */
1059 m_heaps[m_nHeaps].base = ptr;
1060 m_heaps[m_nHeaps].len = size;
1061 #ifdef USE_BIGBLOCK_ALLOC
1062 m_heaps[m_nHeaps].bBigBlock = bBigBlock;
1067 * Reserve the first LONG in the block for the ending boundary tag of a dummy
1068 * block at the start of the heap area.
1070 size -= blockOverhead;
1071 ptr += blockOverhead;
1072 PSIZE(ptr) = 1; /* mark the dummy previous block as allocated */
1076 * Convert the heap to one large block. Set up its boundary tags, and those of
1077 * marker block after it. The marker block before the heap will already have
1078 * been set up if this heap is not contiguous with the end of another heap.
1080 SetTags(ptr, size | 1);
1081 PBLOCK next = ptr + size; /* point to dummy end block */
1082 SIZE(next) = 1; /* mark the dummy end block as allocated */
1085 * Link the block to the start of the free list by calling free().
1086 * This will merge the block with any adjacent free blocks.
1093 void* VMem::Expand(void* block, size_t size)
1096 * Disallow negative or zero sizes.
1098 size_t realsize = CalcAllocSize(size);
1099 if((int)realsize < minAllocSize || size == 0)
1102 PBLOCK ptr = (PBLOCK)block;
1104 /* if the current size is the same as requested, do nothing. */
1105 size_t cursize = SIZE(ptr) & ~1;
1106 if(cursize == realsize) {
1110 /* if the block is being shrunk, convert the remainder of the block into a new free block. */
1111 if(realsize <= cursize) {
1112 size_t nextsize = cursize - realsize; /* size of new remainder block */
1113 if(nextsize >= minAllocSize) {
1116 * Set boundary tags for the resized block and the new block.
1118 SetTags(ptr, realsize | 1);
1122 * add the new block to the free list.
1123 * call Free to merge this block with next block if free
1125 SetTags(ptr, nextsize | 1);
1132 PBLOCK next = ptr + cursize;
1133 size_t nextsize = SIZE(next);
1135 /* Check the next block for consistency.*/
1136 if((nextsize&1) == 0 && (nextsize + cursize) >= realsize) {
1138 * The next block is free and big enough. Add the part that's needed
1139 * to our block, and split the remainder off into a new block.
1141 if(m_pRover == next)
1142 m_pRover = NEXT(next);
1144 /* Unlink the next block from the free list. */
1146 cursize += nextsize; /* combine sizes */
1148 size_t rem = cursize - realsize; /* size of remainder */
1149 if(rem >= minAllocSize) {
1151 * The remainder is big enough to be a new block.
1152 * Set boundary tags for the resized block and the new block.
1154 next = ptr + realsize;
1156 * add the new block to the free list.
1157 * next block cannot be free
1160 #ifdef _USE_BUDDY_BLOCKS
1161 AddToFreeList(next, rem);
1163 AddToFreeList(next, m_pFreeList);
1167 /* Set the boundary tags to mark it as allocated. */
1168 SetTags(ptr, cursize | 1);
1169 return ((void *)ptr);
1175 #define LOG_FILENAME ".\\MemLog.txt"
1177 void VMem::MemoryUsageMessage(char *str, long x, long y, int c)
1182 m_pLog = fopen(LOG_FILENAME, "w");
1183 sprintf(szBuffer, str, x, y, c);
1184 fputs(szBuffer, m_pLog);
1195 void VMem::WalkHeap(int complete)
1198 MemoryUsageMessage(NULL, 0, 0, 0);
1200 for(int i = 0; i < m_nHeaps; ++i) {
1201 total += m_heaps[i].len;
1203 MemoryUsageMessage("VMem heaps used %d. Total memory %08x\n", m_nHeaps, total, 0);
1205 /* Walk all the heaps - verify structures */
1206 for(int index = 0; index < m_nHeaps; ++index) {
1207 PBLOCK ptr = m_heaps[index].base;
1208 size_t size = m_heaps[index].len;
1209 #ifndef _USE_BUDDY_BLOCKS
1210 #ifdef USE_BIGBLOCK_ALLOC
1211 if (!m_heaps[m_nHeaps].bBigBlock)
1213 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, ptr));
1216 /* set over reserved header block */
1217 size -= blockOverhead;
1218 ptr += blockOverhead;
1219 PBLOCK pLast = ptr + size;
1220 ASSERT(PSIZE(ptr) == 1); /* dummy previous block is allocated */
1221 ASSERT(SIZE(pLast) == 1); /* dummy next block is allocated */
1222 while(ptr < pLast) {
1223 ASSERT(ptr > m_heaps[index].base);
1224 size_t cursize = SIZE(ptr) & ~1;
1225 ASSERT((PSIZE(ptr+cursize) & ~1) == cursize);
1226 MemoryUsageMessage("Memory Block %08x: Size %08x %c\n", (long)ptr, cursize, (SIZE(ptr)&1) ? 'x' : ' ');
1227 if(!(SIZE(ptr)&1)) {
1228 /* this block is on the free list */
1229 PBLOCK tmp = NEXT(ptr);
1231 ASSERT((SIZE(tmp)&1)==0);
1232 if(tmp == m_pFreeList)
1238 MemoryUsageMessage("Memory Block %08x: Size %08x free but not in free list\n", (long)ptr, cursize, 0);
1244 MemoryUsageMessage(NULL, 0, 0, 0);
1247 #endif /* _DEBUG_MEM */
1249 #endif /* _USE_MSVCRT_MEM_ALLOC */
1251 #endif /* ___VMEM_H_INC___ */