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___
24 #define _USE_MSVCRT_MEM_ALLOC
25 #define _USE_LINKED_LIST
27 // #define _USE_BUDDY_BLOCKS
31 #define ASSERT(f) if(!(f)) DebugBreak();
33 inline void MEMODS(char *str)
35 OutputDebugString(str);
36 OutputDebugString("\n");
39 inline void MEMODSlx(char *str, long x)
42 sprintf(szBuffer, "%s %lx\n", str, x);
43 OutputDebugString(szBuffer);
46 #define WALKHEAP() WalkHeap(0)
47 #define WALKHEAPTRACE() WalkHeap(1)
53 #define MEMODSlx(x, y)
55 #define WALKHEAPTRACE()
59 #ifdef _USE_MSVCRT_MEM_ALLOC
61 #ifndef _USE_LINKED_LIST
62 // #define _USE_LINKED_LIST
66 * Pass all memory requests throught to msvcrt.dll
67 * optionaly track by using a doubly linked header
70 typedef void (*LPFREE)(void *block);
71 typedef void* (*LPMALLOC)(size_t size);
72 typedef void* (*LPREALLOC)(void *block, size_t size);
73 #ifdef _USE_LINKED_LIST
75 typedef struct _MemoryBlockHeader* PMEMORY_BLOCK_HEADER;
76 typedef struct _MemoryBlockHeader {
77 PMEMORY_BLOCK_HEADER pNext;
78 PMEMORY_BLOCK_HEADER pPrev;
80 } MEMORY_BLOCK_HEADER, *PMEMORY_BLOCK_HEADER;
88 virtual void* Malloc(size_t size);
89 virtual void* Realloc(void* pMem, size_t size);
90 virtual void Free(void* pMem);
91 virtual void GetLock(void);
92 virtual void FreeLock(void);
93 virtual int IsLocked(void);
94 virtual long Release(void);
95 virtual long AddRef(void);
97 inline BOOL CreateOk(void)
103 #ifdef _USE_LINKED_LIST
104 void LinkBlock(PMEMORY_BLOCK_HEADER ptr)
106 PMEMORY_BLOCK_HEADER next = m_Dummy.pNext;
108 ptr->pPrev = &m_Dummy;
113 void UnlinkBlock(PMEMORY_BLOCK_HEADER ptr)
115 PMEMORY_BLOCK_HEADER next = ptr->pNext;
116 PMEMORY_BLOCK_HEADER prev = ptr->pPrev;
121 MEMORY_BLOCK_HEADER m_Dummy;
124 long m_lRefCount; // number of current users
125 CRITICAL_SECTION m_cs; // access lock
129 LPREALLOC m_prealloc;
135 InitializeCriticalSection(&m_cs);
136 #ifdef _USE_LINKED_LIST
137 m_Dummy.pNext = m_Dummy.pPrev = &m_Dummy;
138 m_Dummy.owner = this;
140 m_hLib = LoadLibrary("msvcrt.dll");
142 m_pfree = (LPFREE)GetProcAddress(m_hLib, "free");
143 m_pmalloc = (LPMALLOC)GetProcAddress(m_hLib, "malloc");
144 m_prealloc = (LPREALLOC)GetProcAddress(m_hLib, "realloc");
150 #ifdef _USE_LINKED_LIST
151 while (m_Dummy.pNext != &m_Dummy) {
152 Free(m_Dummy.pNext+1);
157 DeleteCriticalSection(&m_cs);
160 void* VMem::Malloc(size_t size)
162 #ifdef _USE_LINKED_LIST
164 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)m_pmalloc(size+sizeof(MEMORY_BLOCK_HEADER));
169 return m_pmalloc(size);
173 void* VMem::Realloc(void* pMem, size_t size)
175 #ifdef _USE_LINKED_LIST
185 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
187 ptr = (PMEMORY_BLOCK_HEADER)m_prealloc(ptr, size+sizeof(MEMORY_BLOCK_HEADER));
193 return m_prealloc(pMem, size);
197 void VMem::Free(void* pMem)
199 #ifdef _USE_LINKED_LIST
201 PMEMORY_BLOCK_HEADER ptr = (PMEMORY_BLOCK_HEADER)(((char*)pMem)-sizeof(MEMORY_BLOCK_HEADER));
202 if (ptr->owner != this) {
207 Perl_warn(aTHX_ "Free to wrong pool %p not %p",this,ptr->owner);
210 ptr->owner->Free(pMem);
226 void VMem::GetLock(void)
228 EnterCriticalSection(&m_cs);
231 void VMem::FreeLock(void)
233 LeaveCriticalSection(&m_cs);
236 int VMem::IsLocked(void)
239 /* XXX TryEnterCriticalSection() is not available in some versions
240 * of Windows 95. Since this code is not used anywhere yet, we
241 * skirt the issue for now. */
242 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
244 LeaveCriticalSection(&m_cs);
248 ASSERT(0); /* alarm bells for when somebody calls this */
253 long VMem::Release(void)
255 long lCount = InterlockedDecrement(&m_lRefCount);
261 long VMem::AddRef(void)
263 long lCount = InterlockedIncrement(&m_lRefCount);
267 #else /* _USE_MSVCRT_MEM_ALLOC */
270 * Knuth's boundary tag algorithm Vol #1, Page 440.
272 * Each block in the heap has tag words before and after it,
276 * The size is stored in these tags as a long word, and includes the 8 bytes
277 * of overhead that the boundary tags consume. Blocks are allocated on long
278 * word boundaries, so the size is always multiples of long words. When the
279 * block is allocated, bit 0, (the tag bit), of the size is set to 1. When
280 * a block is freed, it is merged with adjacent free blocks, and the tag bit
283 * A linked list is used to manage the free list. The first two long words of
284 * the block contain double links. These links are only valid when the block
285 * is freed, therefore space needs to be reserved for them. Thus, the minimum
286 * block size (not counting the tags) is 8 bytes.
288 * Since memory allocation may occur on a single threaded, explict locks are not
293 const long lAllocStart = 0x00020000; /* start at 128K */
294 const long minBlockSize = sizeof(void*)*2;
295 const long sizeofTag = sizeof(long);
296 const long blockOverhead = sizeofTag*2;
297 const long minAllocSize = minBlockSize+blockOverhead;
298 #ifdef _USE_BUDDY_BLOCKS
299 const long lSmallBlockSize = 1024;
300 const size_t nListEntries = ((lSmallBlockSize-minAllocSize)/sizeof(long));
302 inline size_t CalcEntry(size_t size)
304 ASSERT((size&(sizeof(long)-1)) == 0);
305 return ((size - minAllocSize) / sizeof(long));
309 typedef BYTE* PBLOCK; /* pointer to a memory block */
312 * Macros for accessing hidden fields in a memory block:
314 * SIZE size of this block (tag bit 0 is 1 if block is allocated)
315 * PSIZE size of previous physical block
318 #define SIZE(block) (*(ULONG*)(((PBLOCK)(block))-sizeofTag))
319 #define PSIZE(block) (*(ULONG*)(((PBLOCK)(block))-(blockOverhead)))
320 inline void SetTags(PBLOCK block, long size)
323 PSIZE(block+(size&~1)) = size;
328 * PREV pointer to previous block
329 * NEXT pointer to next block
332 #define PREV(block) (*(PBLOCK*)(block))
333 #define NEXT(block) (*(PBLOCK*)((block)+sizeof(PBLOCK)))
334 inline void SetLink(PBLOCK block, PBLOCK prev, PBLOCK next)
339 inline void Unlink(PBLOCK p)
341 PBLOCK next = NEXT(p);
342 PBLOCK prev = PREV(p);
346 #ifndef _USE_BUDDY_BLOCKS
347 inline void AddToFreeList(PBLOCK block, PBLOCK pInList)
349 PBLOCK next = NEXT(pInList);
350 NEXT(pInList) = block;
351 SetLink(block, pInList, next);
356 /* Macro for rounding up to the next sizeof(long) */
357 #define ROUND_UP(n) (((ULONG)(n)+sizeof(long)-1)&~(sizeof(long)-1))
358 #define ROUND_UP64K(n) (((ULONG)(n)+0x10000-1)&~(0x10000-1))
359 #define ROUND_DOWN(n) ((ULONG)(n)&~(sizeof(long)-1))
362 * HeapRec - a list of all non-contiguous heap areas
364 * Each record in this array contains information about a non-contiguous heap area.
367 const int maxHeaps = 32; /* 64 was overkill */
368 const long lAllocMax = 0x80000000; /* max size of allocation */
370 #ifdef _USE_BUDDY_BLOCKS
371 typedef struct _FreeListEntry
373 BYTE Dummy[minAllocSize]; // dummy free block
374 } FREE_LIST_ENTRY, *PFREE_LIST_ENTRY;
377 #ifndef _USE_BUDDY_BLOCKS
378 #define USE_BIGBLOCK_ALLOC
382 * Use VirtualAlloc() for blocks bigger than nMaxHeapAllocSize since
383 * Windows 95/98/Me have heap managers that are designed for memory
384 * blocks smaller than four megabytes.
387 #ifdef USE_BIGBLOCK_ALLOC
388 const int nMaxHeapAllocSize = (1024*512); /* don't allocate anything larger than this from the heap */
391 typedef struct _HeapRec
393 PBLOCK base; /* base of heap area */
394 ULONG len; /* size of heap area */
395 #ifdef USE_BIGBLOCK_ALLOC
396 BOOL bBigBlock; /* was allocate using VirtualAlloc */
405 virtual void* Malloc(size_t size);
406 virtual void* Realloc(void* pMem, size_t size);
407 virtual void Free(void* pMem);
408 virtual void GetLock(void);
409 virtual void FreeLock(void);
410 virtual int IsLocked(void);
411 virtual long Release(void);
412 virtual long AddRef(void);
414 inline BOOL CreateOk(void)
416 #ifdef _USE_BUDDY_BLOCKS
419 return m_hHeap != NULL;
427 int Getmem(size_t size);
429 int HeapAdd(void* ptr, size_t size
430 #ifdef USE_BIGBLOCK_ALLOC
435 void* Expand(void* block, size_t size);
437 #ifdef _USE_BUDDY_BLOCKS
438 inline PBLOCK GetFreeListLink(int index)
440 if (index >= nListEntries)
441 index = nListEntries-1;
442 return &m_FreeList[index].Dummy[sizeofTag];
444 inline PBLOCK GetOverSizeFreeList(void)
446 return &m_FreeList[nListEntries-1].Dummy[sizeofTag];
448 inline PBLOCK GetEOLFreeList(void)
450 return &m_FreeList[nListEntries].Dummy[sizeofTag];
453 void AddToFreeList(PBLOCK block, size_t size)
455 PBLOCK pFreeList = GetFreeListLink(CalcEntry(size));
456 PBLOCK next = NEXT(pFreeList);
457 NEXT(pFreeList) = block;
458 SetLink(block, pFreeList, next);
462 inline size_t CalcAllocSize(size_t size)
465 * Adjust the real size of the block to be a multiple of sizeof(long), and add
466 * the overhead for the boundary tags. Disallow negative or zero sizes.
468 return (size < minBlockSize) ? minAllocSize : (size_t)ROUND_UP(size) + blockOverhead;
471 #ifdef _USE_BUDDY_BLOCKS
472 FREE_LIST_ENTRY m_FreeList[nListEntries+1]; // free list with dummy end of list entry as well
474 HANDLE m_hHeap; // memory heap for this script
475 char m_FreeDummy[minAllocSize]; // dummy free block
476 PBLOCK m_pFreeList; // pointer to first block on free list
478 PBLOCK m_pRover; // roving pointer into the free list
479 HeapRec m_heaps[maxHeaps]; // list of all non-contiguous heap areas
480 int m_nHeaps; // no. of heaps in m_heaps
481 long m_lAllocSize; // current alloc size
482 long m_lRefCount; // number of current users
483 CRITICAL_SECTION m_cs; // access lock
486 void WalkHeap(int complete);
487 void MemoryUsageMessage(char *str, long x, long y, int c);
495 #ifndef _USE_BUDDY_BLOCKS
496 BOOL bRet = (NULL != (m_hHeap = HeapCreate(HEAP_NO_SERIALIZE,
497 lAllocStart, /* initial size of heap */
498 0))); /* no upper limit on size of heap */
502 InitializeCriticalSection(&m_cs);
512 #ifndef _USE_BUDDY_BLOCKS
513 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, NULL));
517 DeleteCriticalSection(&m_cs);
518 #ifdef _USE_BUDDY_BLOCKS
519 for(int index = 0; index < m_nHeaps; ++index) {
520 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
522 #else /* !_USE_BUDDY_BLOCKS */
523 #ifdef USE_BIGBLOCK_ALLOC
524 for(int index = 0; index < m_nHeaps; ++index) {
525 if (m_heaps[index].bBigBlock) {
526 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
530 BOOL bRet = HeapDestroy(m_hHeap);
532 #endif /* _USE_BUDDY_BLOCKS */
535 void VMem::ReInit(void)
537 for(int index = 0; index < m_nHeaps; ++index) {
538 #ifdef _USE_BUDDY_BLOCKS
539 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
541 #ifdef USE_BIGBLOCK_ALLOC
542 if (m_heaps[index].bBigBlock) {
543 VirtualFree(m_heaps[index].base, 0, MEM_RELEASE);
547 HeapFree(m_hHeap, HEAP_NO_SERIALIZE, m_heaps[index].base);
548 #endif /* _USE_BUDDY_BLOCKS */
554 void VMem::Init(void)
556 #ifdef _USE_BUDDY_BLOCKS
559 * Initialize the free list by placing a dummy zero-length block on it.
560 * Set the end of list marker.
561 * Set the number of non-contiguous heaps to zero.
562 * Set the next allocation size.
564 for (int index = 0; index < nListEntries; ++index) {
565 pFreeList = GetFreeListLink(index);
566 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
567 PREV(pFreeList) = NEXT(pFreeList) = pFreeList;
569 pFreeList = GetEOLFreeList();
570 SIZE(pFreeList) = PSIZE(pFreeList+minAllocSize) = 0;
571 PREV(pFreeList) = NEXT(pFreeList) = NULL;
572 m_pRover = GetOverSizeFreeList();
575 * Initialize the free list by placing a dummy zero-length block on it.
576 * Set the number of non-contiguous heaps to zero.
578 m_pFreeList = m_pRover = (PBLOCK)(&m_FreeDummy[sizeofTag]);
579 PSIZE(m_pFreeList+minAllocSize) = SIZE(m_pFreeList) = 0;
580 PREV(m_pFreeList) = NEXT(m_pFreeList) = m_pFreeList;
584 m_lAllocSize = lAllocStart;
587 void* VMem::Malloc(size_t size)
594 * Disallow negative or zero sizes.
596 size_t realsize = CalcAllocSize(size);
597 if((int)realsize < minAllocSize || size == 0)
600 #ifdef _USE_BUDDY_BLOCKS
602 * Check the free list of small blocks if this is free use it
603 * Otherwise check the rover if it has no blocks then
604 * Scan the free list entries use the first free block
605 * split the block if needed, stop at end of list marker
608 int index = CalcEntry(realsize);
609 if (index < nListEntries-1) {
610 ptr = GetFreeListLink(index);
612 if (lsize >= realsize) {
613 rem = lsize - realsize;
614 if(rem < minAllocSize) {
615 /* Unlink the block from the free list. */
621 * The remainder is big enough to split off into a new block.
622 * Use the end of the block, resize the beginning of the block
623 * no need to change the free list.
629 SetTags(ptr, lsize | 1);
634 if (lsize >= realsize) {
635 rem = lsize - realsize;
636 if(rem < minAllocSize) {
637 /* Unlink the block from the free list. */
643 * The remainder is big enough to split off into a new block.
644 * Use the end of the block, resize the beginning of the block
645 * no need to change the free list.
651 SetTags(ptr, lsize | 1);
654 ptr = GetFreeListLink(index+1);
657 if (lsize >= realsize) {
658 size_t rem = lsize - realsize;
659 if(rem < minAllocSize) {
660 /* Unlink the block from the free list. */
666 * The remainder is big enough to split off into a new block.
667 * Use the end of the block, resize the beginning of the block
668 * no need to change the free list.
674 SetTags(ptr, lsize | 1);
677 ptr += sizeof(FREE_LIST_ENTRY);
684 * Start searching the free list at the rover. If we arrive back at rover without
685 * finding anything, allocate some memory from the heap and try again.
687 ptr = m_pRover; /* start searching at rover */
688 int loops = 2; /* allow two times through the loop */
691 ASSERT((lsize&1)==0);
692 /* is block big enough? */
693 if(lsize >= realsize) {
694 /* if the remainder is too small, don't bother splitting the block. */
695 rem = lsize - realsize;
696 if(rem < minAllocSize) {
698 m_pRover = NEXT(ptr);
700 /* Unlink the block from the free list. */
706 * The remainder is big enough to split off into a new block.
707 * Use the end of the block, resize the beginning of the block
708 * no need to change the free list.
714 /* Set the boundary tags to mark it as allocated. */
715 SetTags(ptr, lsize | 1);
716 return ((void *)ptr);
720 * This block was unsuitable. If we've gone through this list once already without
721 * finding anything, allocate some new memory from the heap and try again.
724 if(ptr == m_pRover) {
725 if(!(loops-- && Getmem(realsize))) {
733 void* VMem::Realloc(void* block, size_t size)
737 /* if size is zero, free the block. */
743 /* if block pointer is NULL, do a Malloc(). */
748 * Grow or shrink the block in place.
749 * if the block grows then the next block will be used if free
751 if(Expand(block, size) != NULL)
754 size_t realsize = CalcAllocSize(size);
755 if((int)realsize < minAllocSize)
759 * see if the previous block is free, and is it big enough to cover the new size
760 * if merged with the current block.
762 PBLOCK ptr = (PBLOCK)block;
763 size_t cursize = SIZE(ptr) & ~1;
764 size_t psize = PSIZE(ptr);
765 if((psize&1) == 0 && (psize + cursize) >= realsize) {
766 PBLOCK prev = ptr - psize;
768 m_pRover = NEXT(prev);
770 /* Unlink the next block from the free list. */
773 /* Copy contents of old block to new location, make it the current block. */
774 memmove(prev, ptr, cursize);
775 cursize += psize; /* combine sizes */
778 size_t rem = cursize - realsize;
779 if(rem >= minAllocSize) {
781 * The remainder is big enough to be a new block. Set boundary
782 * tags for the resized block and the new block.
784 prev = ptr + realsize;
786 * add the new block to the free list.
787 * next block cannot be free
790 #ifdef _USE_BUDDY_BLOCKS
791 AddToFreeList(prev, rem);
793 AddToFreeList(prev, m_pFreeList);
797 /* Set the boundary tags to mark it as allocated. */
798 SetTags(ptr, cursize | 1);
799 return ((void *)ptr);
802 /* Allocate a new block, copy the old to the new, and free the old. */
803 if((ptr = (PBLOCK)Malloc(size)) != NULL) {
804 memmove(ptr, block, cursize-blockOverhead);
807 return ((void *)ptr);
810 void VMem::Free(void* p)
814 /* Ignore null pointer. */
818 PBLOCK ptr = (PBLOCK)p;
820 /* Check for attempt to free a block that's already free. */
821 size_t size = SIZE(ptr);
823 MEMODSlx("Attempt to free previously freed block", (long)p);
826 size &= ~1; /* remove allocated tag */
828 /* if previous block is free, add this block to it. */
829 #ifndef _USE_BUDDY_BLOCKS
832 size_t psize = PSIZE(ptr);
834 ptr -= psize; /* point to previous block */
835 size += psize; /* merge the sizes of the two blocks */
836 #ifdef _USE_BUDDY_BLOCKS
839 linked = TRUE; /* it's already on the free list */
843 /* if the next physical block is free, merge it with this block. */
844 PBLOCK next = ptr + size; /* point to next physical block */
845 size_t nsize = SIZE(next);
847 /* block is free move rover if needed */
849 m_pRover = NEXT(next);
851 /* unlink the next block from the free list. */
854 /* merge the sizes of this block and the next block. */
858 /* Set the boundary tags for the block; */
861 /* Link the block to the head of the free list. */
862 #ifdef _USE_BUDDY_BLOCKS
863 AddToFreeList(ptr, size);
866 AddToFreeList(ptr, m_pFreeList);
871 void VMem::GetLock(void)
873 EnterCriticalSection(&m_cs);
876 void VMem::FreeLock(void)
878 LeaveCriticalSection(&m_cs);
881 int VMem::IsLocked(void)
884 /* XXX TryEnterCriticalSection() is not available in some versions
885 * of Windows 95. Since this code is not used anywhere yet, we
886 * skirt the issue for now. */
887 BOOL bAccessed = TryEnterCriticalSection(&m_cs);
889 LeaveCriticalSection(&m_cs);
893 ASSERT(0); /* alarm bells for when somebody calls this */
899 long VMem::Release(void)
901 long lCount = InterlockedDecrement(&m_lRefCount);
907 long VMem::AddRef(void)
909 long lCount = InterlockedIncrement(&m_lRefCount);
914 int VMem::Getmem(size_t requestSize)
915 { /* returns -1 is successful 0 if not */
916 #ifdef USE_BIGBLOCK_ALLOC
921 /* Round up size to next multiple of 64K. */
922 size_t size = (size_t)ROUND_UP64K(requestSize);
925 * if the size requested is smaller than our current allocation size
928 if(size < (unsigned long)m_lAllocSize)
931 /* Update the size to allocate on the next request */
932 if(m_lAllocSize != lAllocMax)
935 #ifndef _USE_BUDDY_BLOCKS
937 #ifdef USE_BIGBLOCK_ALLOC
938 && !m_heaps[m_nHeaps-1].bBigBlock
941 /* Expand the last allocated heap */
942 ptr = HeapReAlloc(m_hHeap, HEAP_REALLOC_IN_PLACE_ONLY|HEAP_NO_SERIALIZE,
943 m_heaps[m_nHeaps-1].base,
944 m_heaps[m_nHeaps-1].len + size);
946 HeapAdd(((char*)ptr) + m_heaps[m_nHeaps-1].len, size
947 #ifdef USE_BIGBLOCK_ALLOC
954 #endif /* _USE_BUDDY_BLOCKS */
957 * if we didn't expand a block to cover the requested size
958 * allocate a new Heap
959 * the size of this block must include the additional dummy tags at either end
960 * the above ROUND_UP64K may not have added any memory to include this.
962 if(size == requestSize)
963 size = (size_t)ROUND_UP64K(requestSize+(blockOverhead));
966 #ifdef _USE_BUDDY_BLOCKS
967 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
969 #ifdef USE_BIGBLOCK_ALLOC
971 if (size >= nMaxHeapAllocSize) {
973 ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);
977 ptr = HeapAlloc(m_hHeap, HEAP_NO_SERIALIZE, size);
978 #endif /* _USE_BUDDY_BLOCKS */
981 /* try to allocate a smaller chunk */
983 if(size > requestSize)
988 MEMODSlx("HeapAlloc failed on size!!!", size);
992 #ifdef _USE_BUDDY_BLOCKS
993 if (HeapAdd(ptr, size)) {
994 VirtualFree(ptr, 0, MEM_RELEASE);
998 #ifdef USE_BIGBLOCK_ALLOC
999 if (HeapAdd(ptr, size, bBigBlock)) {
1001 VirtualFree(ptr, 0, MEM_RELEASE);
1007 #endif /* _USE_BUDDY_BLOCKS */
1011 int VMem::HeapAdd(void* p, size_t size
1012 #ifdef USE_BIGBLOCK_ALLOC
1016 { /* if the block can be succesfully added to the heap, returns 0; otherwise -1. */
1019 /* Check size, then round size down to next long word boundary. */
1020 if(size < minAllocSize)
1023 size = (size_t)ROUND_DOWN(size);
1024 PBLOCK ptr = (PBLOCK)p;
1026 #ifdef USE_BIGBLOCK_ALLOC
1030 * Search for another heap area that's contiguous with the bottom of this new area.
1031 * (It should be extremely unusual to find one that's contiguous with the top).
1033 for(index = 0; index < m_nHeaps; ++index) {
1034 if(ptr == m_heaps[index].base + (int)m_heaps[index].len) {
1036 * The new block is contiguous with a previously allocated heap area. Add its
1037 * length to that of the previous heap. Merge it with the dummy end-of-heap
1038 * area marker of the previous heap.
1040 m_heaps[index].len += size;
1044 #ifdef USE_BIGBLOCK_ALLOC
1051 if(index == m_nHeaps) {
1052 /* The new block is not contiguous, or is BigBlock. Add it to the heap list. */
1053 if(m_nHeaps == maxHeaps) {
1054 return -1; /* too many non-contiguous heaps */
1056 m_heaps[m_nHeaps].base = ptr;
1057 m_heaps[m_nHeaps].len = size;
1058 #ifdef USE_BIGBLOCK_ALLOC
1059 m_heaps[m_nHeaps].bBigBlock = bBigBlock;
1064 * Reserve the first LONG in the block for the ending boundary tag of a dummy
1065 * block at the start of the heap area.
1067 size -= blockOverhead;
1068 ptr += blockOverhead;
1069 PSIZE(ptr) = 1; /* mark the dummy previous block as allocated */
1073 * Convert the heap to one large block. Set up its boundary tags, and those of
1074 * marker block after it. The marker block before the heap will already have
1075 * been set up if this heap is not contiguous with the end of another heap.
1077 SetTags(ptr, size | 1);
1078 PBLOCK next = ptr + size; /* point to dummy end block */
1079 SIZE(next) = 1; /* mark the dummy end block as allocated */
1082 * Link the block to the start of the free list by calling free().
1083 * This will merge the block with any adjacent free blocks.
1090 void* VMem::Expand(void* block, size_t size)
1093 * Disallow negative or zero sizes.
1095 size_t realsize = CalcAllocSize(size);
1096 if((int)realsize < minAllocSize || size == 0)
1099 PBLOCK ptr = (PBLOCK)block;
1101 /* if the current size is the same as requested, do nothing. */
1102 size_t cursize = SIZE(ptr) & ~1;
1103 if(cursize == realsize) {
1107 /* if the block is being shrunk, convert the remainder of the block into a new free block. */
1108 if(realsize <= cursize) {
1109 size_t nextsize = cursize - realsize; /* size of new remainder block */
1110 if(nextsize >= minAllocSize) {
1113 * Set boundary tags for the resized block and the new block.
1115 SetTags(ptr, realsize | 1);
1119 * add the new block to the free list.
1120 * call Free to merge this block with next block if free
1122 SetTags(ptr, nextsize | 1);
1129 PBLOCK next = ptr + cursize;
1130 size_t nextsize = SIZE(next);
1132 /* Check the next block for consistency.*/
1133 if((nextsize&1) == 0 && (nextsize + cursize) >= realsize) {
1135 * The next block is free and big enough. Add the part that's needed
1136 * to our block, and split the remainder off into a new block.
1138 if(m_pRover == next)
1139 m_pRover = NEXT(next);
1141 /* Unlink the next block from the free list. */
1143 cursize += nextsize; /* combine sizes */
1145 size_t rem = cursize - realsize; /* size of remainder */
1146 if(rem >= minAllocSize) {
1148 * The remainder is big enough to be a new block.
1149 * Set boundary tags for the resized block and the new block.
1151 next = ptr + realsize;
1153 * add the new block to the free list.
1154 * next block cannot be free
1157 #ifdef _USE_BUDDY_BLOCKS
1158 AddToFreeList(next, rem);
1160 AddToFreeList(next, m_pFreeList);
1164 /* Set the boundary tags to mark it as allocated. */
1165 SetTags(ptr, cursize | 1);
1166 return ((void *)ptr);
1172 #define LOG_FILENAME ".\\MemLog.txt"
1174 void VMem::MemoryUsageMessage(char *str, long x, long y, int c)
1179 m_pLog = fopen(LOG_FILENAME, "w");
1180 sprintf(szBuffer, str, x, y, c);
1181 fputs(szBuffer, m_pLog);
1192 void VMem::WalkHeap(int complete)
1195 MemoryUsageMessage(NULL, 0, 0, 0);
1197 for(int i = 0; i < m_nHeaps; ++i) {
1198 total += m_heaps[i].len;
1200 MemoryUsageMessage("VMem heaps used %d. Total memory %08x\n", m_nHeaps, total, 0);
1202 /* Walk all the heaps - verify structures */
1203 for(int index = 0; index < m_nHeaps; ++index) {
1204 PBLOCK ptr = m_heaps[index].base;
1205 size_t size = m_heaps[index].len;
1206 #ifndef _USE_BUDDY_BLOCKS
1207 #ifdef USE_BIGBLOCK_ALLOC
1208 if (!m_heaps[m_nHeaps].bBigBlock)
1210 ASSERT(HeapValidate(m_hHeap, HEAP_NO_SERIALIZE, ptr));
1213 /* set over reserved header block */
1214 size -= blockOverhead;
1215 ptr += blockOverhead;
1216 PBLOCK pLast = ptr + size;
1217 ASSERT(PSIZE(ptr) == 1); /* dummy previous block is allocated */
1218 ASSERT(SIZE(pLast) == 1); /* dummy next block is allocated */
1219 while(ptr < pLast) {
1220 ASSERT(ptr > m_heaps[index].base);
1221 size_t cursize = SIZE(ptr) & ~1;
1222 ASSERT((PSIZE(ptr+cursize) & ~1) == cursize);
1223 MemoryUsageMessage("Memory Block %08x: Size %08x %c\n", (long)ptr, cursize, (SIZE(ptr)&1) ? 'x' : ' ');
1224 if(!(SIZE(ptr)&1)) {
1225 /* this block is on the free list */
1226 PBLOCK tmp = NEXT(ptr);
1228 ASSERT((SIZE(tmp)&1)==0);
1229 if(tmp == m_pFreeList)
1235 MemoryUsageMessage("Memory Block %08x: Size %08x free but not in free list\n", (long)ptr, cursize, 0);
1241 MemoryUsageMessage(NULL, 0, 0, 0);
1244 #endif /* _DEBUG_MEM */
1246 #endif /* _USE_MSVCRT_MEM_ALLOC */
1248 #endif /* ___VMEM_H_INC___ */