Release 980104
[wine/multimedia.git] / memory / heap.c
blob9904b3da86e7b46ce31bfe60f4318ba28194f0de
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include "windows.h"
12 #include "selectors.h"
13 #include "winbase.h"
14 #include "winerror.h"
15 #include "winnt.h"
16 #include "heap.h"
17 #include "stddebug.h"
18 #include "debug.h"
20 /* Note: the heap data structures are based on what Pietrek describes in his
21 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
22 * the same, but could be easily adapted if it turns out some programs
23 * require it.
26 typedef struct tagARENA_INUSE
28 DWORD size; /* Block size; must be the first field */
29 WORD threadId; /* Allocating thread id */
30 WORD magic; /* Magic number */
31 DWORD callerEIP; /* EIP of caller upon allocation */
32 } ARENA_INUSE;
34 typedef struct tagARENA_FREE
36 DWORD size; /* Block size; must be the first field */
37 WORD threadId; /* Freeing thread id */
38 WORD magic; /* Magic number */
39 struct tagARENA_FREE *next; /* Next free arena */
40 struct tagARENA_FREE *prev; /* Prev free arena */
41 } ARENA_FREE;
43 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
44 #define ARENA_FLAG_PREV_FREE 0x00000002
45 #define ARENA_SIZE_MASK 0xfffffffc
46 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
47 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
49 #define ARENA_INUSE_FILLER 0x55
50 #define ARENA_FREE_FILLER 0xaa
52 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
54 /* Max size of the blocks on the free lists */
55 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
57 0x20, 0x80, 0x200, 0xffffffff
60 typedef struct
62 DWORD size;
63 ARENA_FREE arena;
64 } FREE_LIST_ENTRY;
66 struct tagHEAP;
68 typedef struct tagSUBHEAP
70 DWORD size; /* Size of the whole sub-heap */
71 DWORD commitSize; /* Committed size of the sub-heap */
72 DWORD headerSize; /* Size of the heap header */
73 struct tagSUBHEAP *next; /* Next sub-heap */
74 struct tagHEAP *heap; /* Main heap structure */
75 DWORD magic; /* Magic number */
76 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
77 } SUBHEAP;
79 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
81 typedef struct tagHEAP
83 SUBHEAP subheap; /* First sub-heap */
84 struct tagHEAP *next; /* Next heap for this process */
85 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
86 CRITICAL_SECTION critSection; /* Critical section for serialization */
87 DWORD flags; /* Heap flags */
88 DWORD magic; /* Magic number */
89 } HEAP;
91 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
93 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
94 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
96 HANDLE32 SystemHeap = 0;
97 HANDLE32 SegptrHeap = 0;
98 CRITICAL_SECTION *HEAP_SystemLock = NULL;
101 /***********************************************************************
102 * HEAP_Dump
104 void HEAP_Dump( HEAP *heap )
106 int i;
107 SUBHEAP *subheap;
108 char *ptr;
110 printf( "Heap: %08lx\n", (DWORD)heap );
111 printf( "Next: %08lx Sub-heaps: %08lx",
112 (DWORD)heap->next, (DWORD)&heap->subheap );
113 subheap = &heap->subheap;
114 while (subheap->next)
116 printf( " -> %08lx", (DWORD)subheap->next );
117 subheap = subheap->next;
120 printf( "\nFree lists:\n Block Stat Size Id\n" );
121 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
122 printf( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
123 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
124 heap->freeList[i].arena.threadId,
125 (DWORD)heap->freeList[i].arena.prev,
126 (DWORD)heap->freeList[i].arena.next );
128 subheap = &heap->subheap;
129 while (subheap)
131 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
132 printf( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
133 (DWORD)subheap, subheap->size, subheap->commitSize );
135 printf( "\n Block Stat Size Id\n" );
136 ptr = (char*)subheap + subheap->headerSize;
137 while (ptr < (char *)subheap + subheap->size)
139 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
141 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
142 printf( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
143 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
144 pArena->threadId, (DWORD)pArena->prev,
145 (DWORD)pArena->next);
146 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
147 arenaSize += sizeof(ARENA_FREE);
148 freeSize += pArena->size & ARENA_SIZE_MASK;
150 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
152 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
153 printf( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
154 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
155 pArena->threadId, *((DWORD *)pArena - 1),
156 pArena->callerEIP );
157 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
158 arenaSize += sizeof(ARENA_INUSE);
159 usedSize += pArena->size & ARENA_SIZE_MASK;
161 else
163 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
164 printf( "%08lx used %08lx %04x EIP=%08lx\n",
165 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
166 pArena->threadId, pArena->callerEIP );
167 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
168 arenaSize += sizeof(ARENA_INUSE);
169 usedSize += pArena->size & ARENA_SIZE_MASK;
172 printf( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
173 subheap->size, subheap->commitSize, freeSize, usedSize,
174 arenaSize, (arenaSize * 100) / subheap->size );
175 subheap = subheap->next;
180 /***********************************************************************
181 * HEAP_GetPtr
183 static HEAP *HEAP_GetPtr( HANDLE32 heap )
185 HEAP *heapPtr = (HEAP *)heap;
186 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
188 fprintf( stderr, "Invalid heap %08x!\n", heap );
189 SetLastError( ERROR_INVALID_HANDLE );
190 return NULL;
192 if (debugging_heap && !HeapValidate( heap, 0, NULL ))
194 HEAP_Dump( heapPtr );
195 assert( FALSE );
196 SetLastError( ERROR_INVALID_HANDLE );
197 return NULL;
199 return heapPtr;
203 /***********************************************************************
204 * HEAP_InsertFreeBlock
206 * Insert a free block into the free list.
208 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
210 FREE_LIST_ENTRY *pEntry = heap->freeList;
211 while (pEntry->size < pArena->size) pEntry++;
212 pArena->size |= ARENA_FLAG_FREE;
213 pArena->next = pEntry->arena.next;
214 pArena->next->prev = pArena;
215 pArena->prev = &pEntry->arena;
216 pEntry->arena.next = pArena;
220 /***********************************************************************
221 * HEAP_FindSubHeap
223 * Find the sub-heap containing a given address.
225 static SUBHEAP *HEAP_FindSubHeap( HEAP *heap, LPCVOID ptr )
227 SUBHEAP *sub = &heap->subheap;
228 while (sub)
230 if (((char *)ptr >= (char *)sub) &&
231 ((char *)ptr < (char *)sub + sub->size)) return sub;
232 sub = sub->next;
234 return NULL;
238 /***********************************************************************
239 * HEAP_Commit
241 * Make sure the heap storage is committed up to (not including) ptr.
243 static BOOL32 HEAP_Commit( SUBHEAP *subheap, void *ptr )
245 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
246 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
247 if (size > subheap->size) size = subheap->size;
248 if (size <= subheap->commitSize) return TRUE;
249 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
250 size - subheap->commitSize, MEM_COMMIT,
251 PAGE_EXECUTE_READWRITE))
253 fprintf( stderr, "HEAP_Commit: could not commit %08lx bytes at %08lx for heap %08lx\n",
254 size - subheap->commitSize,
255 (DWORD)((char *)subheap + subheap->commitSize),
256 (DWORD)subheap->heap );
257 return FALSE;
259 subheap->commitSize = size;
260 return TRUE;
264 /***********************************************************************
265 * HEAP_Decommit
267 * If possible, decommit the heap storage from (including) 'ptr'.
269 static BOOL32 HEAP_Decommit( SUBHEAP *subheap, void *ptr )
271 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
272 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
273 if (size >= subheap->commitSize) return TRUE;
274 if (!VirtualFree( (char *)subheap + size,
275 subheap->commitSize - size, MEM_DECOMMIT ))
277 fprintf( stderr, "HEAP_Decommit: could not decommit %08lx bytes at %08lx for heap %08lx\n",
278 subheap->commitSize - size,
279 (DWORD)((char *)subheap + size),
280 (DWORD)subheap->heap );
281 return FALSE;
283 subheap->commitSize = size;
284 return TRUE;
288 /***********************************************************************
289 * HEAP_CreateFreeBlock
291 * Create a free block at a specified address. 'size' is the size of the
292 * whole block, including the new arena.
294 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
296 ARENA_FREE *pFree;
298 /* Create a free arena */
300 pFree = (ARENA_FREE *)ptr;
301 pFree->threadId = GetCurrentTask();
302 pFree->magic = ARENA_FREE_MAGIC;
304 /* If debugging, erase the freed block content */
306 if (debugging_heap)
308 char *pEnd = (char *)ptr + size;
309 if (pEnd > (char *)subheap + subheap->commitSize)
310 pEnd = (char *)subheap + subheap->commitSize;
311 if (pEnd > (char *)(pFree + 1))
312 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
315 /* Check if next block is free also */
317 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
318 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
320 /* Remove the next arena from the free list */
321 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
322 pNext->next->prev = pNext->prev;
323 pNext->prev->next = pNext->next;
324 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
325 if (debugging_heap)
326 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
329 /* Set the next block PREV_FREE flag and pointer */
331 if ((char *)ptr + size < (char *)subheap + subheap->size)
333 DWORD *pNext = (DWORD *)((char *)ptr + size);
334 *pNext |= ARENA_FLAG_PREV_FREE;
335 *(ARENA_FREE **)(pNext - 1) = pFree;
338 /* Last, insert the new block into the free list */
340 pFree->size = size - sizeof(*pFree);
341 HEAP_InsertFreeBlock( subheap->heap, pFree );
345 /***********************************************************************
346 * HEAP_MakeInUseBlockFree
348 * Turn an in-use block into a free block. Can also decommit the end of
349 * the heap, and possibly even free the sub-heap altogether.
351 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
353 ARENA_FREE *pFree;
354 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
356 /* Check if we can merge with previous block */
358 if (pArena->size & ARENA_FLAG_PREV_FREE)
360 pFree = *((ARENA_FREE **)pArena - 1);
361 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
362 /* Remove it from the free list */
363 pFree->next->prev = pFree->prev;
364 pFree->prev->next = pFree->next;
366 else pFree = (ARENA_FREE *)pArena;
368 /* Create a free block */
370 HEAP_CreateFreeBlock( subheap, pFree, size );
371 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
372 if ((char *)pFree + size < (char *)subheap + subheap->size)
373 return; /* Not the last block, so nothing more to do */
375 /* Free the whole sub-heap if it's empty and not the original one */
377 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
378 (subheap != &subheap->heap->subheap))
380 SUBHEAP *pPrev = &subheap->heap->subheap;
381 /* Remove the free block from the list */
382 pFree->next->prev = pFree->prev;
383 pFree->prev->next = pFree->next;
384 /* Remove the subheap from the list */
385 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
386 if (pPrev) pPrev->next = subheap->next;
387 /* Free the memory */
388 subheap->magic = 0;
389 if (subheap->selector) FreeSelector( subheap->selector );
390 VirtualFree( subheap, 0, MEM_RELEASE );
391 return;
394 /* Decommit the end of the heap */
396 HEAP_Decommit( subheap, pFree + 1 );
400 /***********************************************************************
401 * HEAP_ShrinkBlock
403 * Shrink an in-use block.
405 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
407 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
409 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
410 (pArena->size & ARENA_SIZE_MASK) - size );
411 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
413 else
415 /* Turn off PREV_FREE flag in next block */
416 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
417 if (pNext < (char *)subheap + subheap->size)
418 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
423 /***********************************************************************
424 * HEAP_CreateSubHeap
426 * Create a sub-heap of the given size.
428 static SUBHEAP *HEAP_CreateSubHeap( DWORD flags, DWORD commitSize,
429 DWORD totalSize )
431 SUBHEAP *subheap;
432 WORD selector = 0;
434 /* Round-up sizes on a 64K boundary */
436 if (flags & HEAP_WINE_SEGPTR)
438 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
440 else
442 totalSize = (totalSize + 0xffff) & 0xffff0000;
443 commitSize = (commitSize + 0xffff) & 0xffff0000;
444 if (!commitSize) commitSize = 0x10000;
445 if (totalSize < commitSize) totalSize = commitSize;
448 /* Allocate the memory block */
450 if (!(subheap = VirtualAlloc( NULL, totalSize,
451 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
453 fprintf( stderr, "HEAP_CreateSubHeap: could not VirtualAlloc %08lx bytes\n",
454 totalSize );
455 return NULL;
457 if (!VirtualAlloc(subheap, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
459 fprintf( stderr, "HEAP_CreateSubHeap: could not commit %08lx bytes for sub-heap %08lx\n",
460 commitSize, (DWORD)subheap );
461 VirtualFree( subheap, 0, MEM_RELEASE );
462 return NULL;
465 /* Allocate a selector if needed */
467 if (flags & HEAP_WINE_SEGPTR)
469 selector = SELECTOR_AllocBlock( subheap, totalSize,
470 (flags & HEAP_WINE_CODESEG) ? SEGMENT_CODE : SEGMENT_DATA,
471 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
472 if (!selector)
474 fprintf( stderr, "HEAP_CreateSubHeap: could not allocate selector\n" );
475 VirtualFree( subheap, 0, MEM_RELEASE );
476 return NULL;
480 /* Fill the sub-heap structure */
482 subheap->size = totalSize;
483 subheap->commitSize = commitSize;
484 subheap->headerSize = sizeof(*subheap);
485 subheap->next = NULL;
486 subheap->heap = NULL;
487 subheap->magic = SUBHEAP_MAGIC;
488 subheap->selector = selector;
489 return subheap;
493 /***********************************************************************
494 * HEAP_FindFreeBlock
496 * Find a free block at least as large as the requested size, and make sure
497 * the requested size is committed.
499 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
500 SUBHEAP **ppSubHeap )
502 SUBHEAP *subheap;
503 ARENA_FREE *pArena;
504 FREE_LIST_ENTRY *pEntry = heap->freeList;
506 /* Find a suitable free list, and in it find a block large enough */
508 while (pEntry->size < size) pEntry++;
509 pArena = pEntry->arena.next;
510 while (pArena != &heap->freeList[0].arena)
512 if (pArena->size > size)
514 subheap = HEAP_FindSubHeap( heap, pArena );
515 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
516 + size + HEAP_MIN_BLOCK_SIZE))
517 return NULL;
518 *ppSubHeap = subheap;
519 return pArena;
522 pArena = pArena->next;
525 /* If no block was found, attempt to grow the heap */
527 if (!(heap->flags & HEAP_GROWABLE))
529 fprintf( stderr, "HEAP_FindFreeBlock: Not enough space in heap %08lx for %08lx bytes\n",
530 (DWORD)heap, size );
531 return NULL;
533 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
534 if (!(subheap = HEAP_CreateSubHeap( heap->flags, size,
535 MAX( HEAP_DEF_SIZE, size ) )))
536 return NULL;
538 /* Insert the new sub-heap in the list */
540 subheap->heap = heap;
541 subheap->next = heap->subheap.next;
542 heap->subheap.next = subheap;
543 size = subheap->size;
544 dprintf_heap( stddeb, "HEAP_FindFreeBlock: created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
545 (DWORD)subheap, size, (DWORD)heap );
547 HEAP_CreateFreeBlock( subheap, subheap + 1, size - sizeof(*subheap) );
548 *ppSubHeap = subheap;
549 return (ARENA_FREE *)(subheap + 1);
553 /***********************************************************************
554 * HEAP_IsValidArenaPtr
556 * Check that the pointer is inside the range possible for arenas.
558 static BOOL32 HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
560 int i;
561 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
562 if (!subheap) return FALSE;
563 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
564 if (subheap != &heap->subheap) return FALSE;
565 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
566 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
567 return FALSE;
571 /***********************************************************************
572 * HEAP_ValidateFreeArena
574 static BOOL32 HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
576 char *heapEnd = (char *)subheap + subheap->size;
578 /* Check magic number */
579 if (pArena->magic != ARENA_FREE_MAGIC)
581 fprintf( stderr, "Heap %08lx: invalid free arena magic for %08lx\n",
582 (DWORD)subheap->heap, (DWORD)pArena );
583 return FALSE;
585 /* Check size flags */
586 if (!(pArena->size & ARENA_FLAG_FREE) ||
587 (pArena->size & ARENA_FLAG_PREV_FREE))
589 fprintf( stderr, "Heap %08lx: bad flags %lx for free arena %08lx\n",
590 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
592 /* Check arena size */
593 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
595 fprintf( stderr, "Heap %08lx: bad size %08lx for free arena %08lx\n",
596 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
597 return FALSE;
599 /* Check that next pointer is valid */
600 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
602 fprintf( stderr, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
603 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
604 return FALSE;
606 /* Check that next arena is free */
607 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
608 (pArena->next->magic != ARENA_FREE_MAGIC))
610 fprintf( stderr, "Heap %08lx: next arena %08lx invalid for %08lx\n",
611 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
612 return FALSE;
614 /* Check that prev pointer is valid */
615 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
617 fprintf( stderr, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
618 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
619 return FALSE;
621 /* Check that prev arena is free */
622 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
623 (pArena->prev->magic != ARENA_FREE_MAGIC))
625 fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
626 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
627 return FALSE;
629 /* Check that next block has PREV_FREE flag */
630 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
632 if (!(*(DWORD *)((char *)(pArena + 1) +
633 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
635 fprintf( stderr, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
636 (DWORD)subheap->heap, (DWORD)pArena );
637 return FALSE;
639 /* Check next block back pointer */
640 if (*((ARENA_FREE **)((char *)(pArena + 1) +
641 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
643 fprintf( stderr, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
644 (DWORD)subheap->heap, (DWORD)pArena,
645 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
646 return FALSE;
649 return TRUE;
653 /***********************************************************************
654 * HEAP_ValidateInUseArena
656 static BOOL32 HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
658 char *heapEnd = (char *)subheap + subheap->size;
660 /* Check magic number */
661 if (pArena->magic != ARENA_INUSE_MAGIC)
663 fprintf( stderr, "Heap %08lx: invalid in-use arena magic for %08lx\n",
664 (DWORD)subheap->heap, (DWORD)pArena );
665 return FALSE;
667 /* Check size flags */
668 if (pArena->size & ARENA_FLAG_FREE)
670 fprintf( stderr, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
671 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
673 /* Check arena size */
674 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
676 fprintf( stderr, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
677 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
678 return FALSE;
680 /* Check next arena PREV_FREE flag */
681 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
682 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
684 fprintf( stderr, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
685 (DWORD)subheap->heap, (DWORD)pArena );
686 return FALSE;
688 /* Check prev free arena */
689 if (pArena->size & ARENA_FLAG_PREV_FREE)
691 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
692 /* Check prev pointer */
693 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
695 fprintf(stderr, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
696 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
697 return FALSE;
699 /* Check that prev arena is free */
700 if (!(pPrev->size & ARENA_FLAG_FREE) ||
701 (pPrev->magic != ARENA_FREE_MAGIC))
703 fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
704 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
705 return FALSE;
707 /* Check that prev arena is really the previous block */
708 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
710 fprintf( stderr, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
711 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
712 return FALSE;
715 return TRUE;
719 /***********************************************************************
720 * HEAP_IsInsideHeap
722 * Check whether the pointer is to a block inside a given heap.
724 int HEAP_IsInsideHeap( HANDLE32 heap, DWORD flags, LPCVOID ptr )
726 HEAP *heapPtr = HEAP_GetPtr( heap );
727 SUBHEAP *subheap;
728 int ret;
730 /* Validate the parameters */
732 if (!heapPtr) return 0;
733 flags |= heapPtr->flags;
734 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
735 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
736 (((char *)ptr >= (char *)subheap + subheap->headerSize
737 + sizeof(ARENA_INUSE))));
738 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
739 return ret;
743 /***********************************************************************
744 * HEAP_GetSegptr
746 * Transform a linear pointer into a SEGPTR. The pointer must have been
747 * allocated from a HEAP_WINE_SEGPTR heap.
749 SEGPTR HEAP_GetSegptr( HANDLE32 heap, DWORD flags, LPCVOID ptr )
751 HEAP *heapPtr = HEAP_GetPtr( heap );
752 SUBHEAP *subheap;
753 SEGPTR ret;
755 /* Validate the parameters */
757 if (!heapPtr) return 0;
758 flags |= heapPtr->flags;
759 if (!(flags & HEAP_WINE_SEGPTR))
761 fprintf( stderr, "HEAP_GetSegptr: heap %08x is not a SEGPTR heap\n",
762 heap );
763 return 0;
765 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
767 /* Get the subheap */
769 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
771 fprintf( stderr, "HEAP_GetSegptr: %p is not inside heap %08x\n",
772 ptr, heap );
773 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
774 return 0;
777 /* Build the SEGPTR */
779 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
780 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
781 return ret;
785 /***********************************************************************
786 * HeapCreate (KERNEL32.336)
788 HANDLE32 WINAPI HeapCreate( DWORD flags, DWORD initialSize, DWORD maxSize )
790 int i;
791 HEAP *heap;
792 SUBHEAP *subheap;
793 FREE_LIST_ENTRY *pEntry;
795 /* Allocate the heap block */
797 if (!maxSize)
799 maxSize = HEAP_DEF_SIZE;
800 flags |= HEAP_GROWABLE;
802 if (!(subheap = HEAP_CreateSubHeap( flags, initialSize, maxSize )))
804 SetLastError( ERROR_OUTOFMEMORY );
805 return 0;
808 /* Fill the heap structure */
810 heap = (HEAP *)subheap;
811 subheap->heap = heap;
812 subheap->headerSize = sizeof(HEAP);
813 heap->next = NULL;
814 heap->flags = flags;
815 heap->magic = HEAP_MAGIC;
817 /* Build the free lists */
819 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
821 pEntry->size = HEAP_freeListSizes[i];
822 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
823 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
824 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
825 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
826 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
827 pEntry->arena.threadId = 0;
828 pEntry->arena.magic = ARENA_FREE_MAGIC;
831 /* Create the first free block */
833 HEAP_CreateFreeBlock( subheap, heap + 1, subheap->size - sizeof(*heap) );
835 /* Initialize critical section */
837 InitializeCriticalSection( &heap->critSection );
838 if (!SystemHeap) HEAP_SystemLock = &heap->critSection;
840 /* We are done */
842 return (HANDLE32)heap;
846 /***********************************************************************
847 * HeapDestroy (KERNEL32.337)
849 BOOL32 WINAPI HeapDestroy( HANDLE32 heap )
851 HEAP *heapPtr = HEAP_GetPtr( heap );
852 SUBHEAP *subheap;
854 dprintf_heap( stddeb, "HeapDestroy: %08x\n", heap );
855 if (!heapPtr) return FALSE;
857 DeleteCriticalSection( &heapPtr->critSection );
858 subheap = &heapPtr->subheap;
859 while (subheap)
861 SUBHEAP *next = subheap->next;
862 if (subheap->selector) FreeSelector( subheap->selector );
863 VirtualFree( subheap, 0, MEM_RELEASE );
864 subheap = next;
866 return TRUE;
870 /***********************************************************************
871 * HeapAlloc (KERNEL32.334)
873 LPVOID WINAPI HeapAlloc( HANDLE32 heap, DWORD flags, DWORD size )
875 ARENA_FREE *pArena;
876 ARENA_INUSE *pInUse;
877 SUBHEAP *subheap;
878 HEAP *heapPtr = HEAP_GetPtr( heap );
880 /* Validate the parameters */
882 if (!heapPtr) return NULL;
883 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
884 flags |= heapPtr->flags;
885 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
886 size = (size + 3) & ~3;
887 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
889 /* Locate a suitable free block */
891 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
893 dprintf_heap( stddeb, "HeapAlloc(%08x,%08lx,%08lx): returning NULL\n",
894 heap, flags, size );
895 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
896 SetLastError( ERROR_COMMITMENT_LIMIT );
897 return NULL;
900 /* Remove the arena from the free list */
902 pArena->next->prev = pArena->prev;
903 pArena->prev->next = pArena->next;
905 /* Build the in-use arena */
907 pInUse = (ARENA_INUSE *)pArena;
908 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
909 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
910 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
911 pInUse->threadId = GetCurrentTask();
912 pInUse->magic = ARENA_INUSE_MAGIC;
914 /* Shrink the block */
916 HEAP_ShrinkBlock( subheap, pInUse, size );
918 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
919 else if (debugging_heap) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
921 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
923 dprintf_heap( stddeb, "HeapAlloc(%08x,%08lx,%08lx): returning %08lx\n",
924 heap, flags, size, (DWORD)(pInUse + 1) );
925 return (LPVOID)(pInUse + 1);
929 /***********************************************************************
930 * HeapFree (KERNEL32.338)
932 BOOL32 WINAPI HeapFree( HANDLE32 heap, DWORD flags, LPVOID ptr )
934 ARENA_INUSE *pInUse;
935 SUBHEAP *subheap;
936 HEAP *heapPtr = HEAP_GetPtr( heap );
938 /* Validate the parameters */
940 if (!heapPtr) return FALSE;
941 flags &= HEAP_NO_SERIALIZE;
942 flags |= heapPtr->flags;
943 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
944 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
946 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
947 SetLastError( ERROR_INVALID_PARAMETER );
948 dprintf_heap( stddeb, "HeapFree(%08x,%08lx,%08lx): returning FALSE\n",
949 heap, flags, (DWORD)ptr );
950 return FALSE;
953 /* Turn the block into a free block */
955 pInUse = (ARENA_INUSE *)ptr - 1;
956 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
957 HEAP_MakeInUseBlockFree( subheap, pInUse );
959 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
960 /* SetLastError( 0 ); */
962 dprintf_heap( stddeb, "HeapFree(%08x,%08lx,%08lx): returning TRUE\n",
963 heap, flags, (DWORD)ptr );
964 return TRUE;
968 /***********************************************************************
969 * HeapReAlloc (KERNEL32.340)
971 LPVOID WINAPI HeapReAlloc( HANDLE32 heap, DWORD flags, LPVOID ptr, DWORD size )
973 ARENA_INUSE *pArena;
974 DWORD oldSize;
975 HEAP *heapPtr;
976 SUBHEAP *subheap;
978 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
979 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
981 /* Validate the parameters */
983 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
984 HEAP_REALLOC_IN_PLACE_ONLY;
985 flags |= heapPtr->flags;
986 size = (size + 3) & ~3;
987 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
989 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
990 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
992 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
993 SetLastError( ERROR_INVALID_PARAMETER );
994 dprintf_heap( stddeb, "HeapReAlloc(%08x,%08lx,%08lx,%08lx): returning NULL\n",
995 heap, flags, (DWORD)ptr, size );
996 return NULL;
999 /* Check if we need to grow the block */
1001 pArena = (ARENA_INUSE *)ptr - 1;
1002 pArena->threadId = GetCurrentTask();
1003 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1004 oldSize = (pArena->size & ARENA_SIZE_MASK);
1005 if (size > oldSize)
1007 char *pNext = (char *)(pArena + 1) + oldSize;
1008 if ((pNext < (char *)subheap + subheap->size) &&
1009 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1010 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1012 /* The next block is free and large enough */
1013 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1014 pFree->next->prev = pFree->prev;
1015 pFree->prev->next = pFree->next;
1016 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1017 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1018 + size + HEAP_MIN_BLOCK_SIZE))
1020 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1021 SetLastError( ERROR_OUTOFMEMORY );
1022 return NULL;
1024 HEAP_ShrinkBlock( subheap, pArena, size );
1026 else /* Do it the hard way */
1028 ARENA_FREE *pNew;
1029 ARENA_INUSE *pInUse;
1030 SUBHEAP *newsubheap;
1032 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1033 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1035 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1036 SetLastError( ERROR_OUTOFMEMORY );
1037 return NULL;
1040 /* Build the in-use arena */
1042 pNew->next->prev = pNew->prev;
1043 pNew->prev->next = pNew->next;
1044 pInUse = (ARENA_INUSE *)pNew;
1045 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1046 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1047 pInUse->threadId = GetCurrentTask();
1048 pInUse->magic = ARENA_INUSE_MAGIC;
1049 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1050 memcpy( pInUse + 1, pArena + 1, oldSize );
1052 /* Free the previous block */
1054 HEAP_MakeInUseBlockFree( subheap, pArena );
1055 subheap = newsubheap;
1056 pArena = pInUse;
1059 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1061 /* Clear the extra bytes if needed */
1063 if (size > oldSize)
1065 if (flags & HEAP_ZERO_MEMORY)
1066 memset( (char *)(pArena + 1) + oldSize, 0,
1067 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1068 else if (debugging_heap)
1069 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1070 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1073 /* Return the new arena */
1075 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1076 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1078 dprintf_heap( stddeb, "HeapReAlloc(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1079 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1080 return (LPVOID)(pArena + 1);
1084 /***********************************************************************
1085 * HeapCompact (KERNEL32.335)
1087 DWORD WINAPI HeapCompact( HANDLE32 heap, DWORD flags )
1089 return 0;
1093 /***********************************************************************
1094 * HeapLock (KERNEL32.339)
1096 BOOL32 WINAPI HeapLock( HANDLE32 heap )
1098 HEAP *heapPtr = HEAP_GetPtr( heap );
1099 if (!heapPtr) return FALSE;
1100 EnterCriticalSection( &heapPtr->critSection );
1101 return TRUE;
1105 /***********************************************************************
1106 * HeapUnlock (KERNEL32.342)
1108 BOOL32 WINAPI HeapUnlock( HANDLE32 heap )
1110 HEAP *heapPtr = HEAP_GetPtr( heap );
1111 if (!heapPtr) return FALSE;
1112 LeaveCriticalSection( &heapPtr->critSection );
1113 return TRUE;
1117 /***********************************************************************
1118 * HeapSize (KERNEL32.341)
1120 DWORD WINAPI HeapSize( HANDLE32 heap, DWORD flags, LPVOID ptr )
1122 DWORD ret;
1123 HEAP *heapPtr = HEAP_GetPtr( heap );
1125 if (!heapPtr) return FALSE;
1126 flags &= HEAP_NO_SERIALIZE;
1127 flags |= heapPtr->flags;
1128 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1129 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1131 SetLastError( ERROR_INVALID_PARAMETER );
1132 ret = 0xffffffff;
1134 else
1136 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1137 ret = pArena->size & ARENA_SIZE_MASK;
1139 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1141 dprintf_heap( stddeb, "HeapSize(%08x,%08lx,%08lx): returning %08lx\n",
1142 heap, flags, (DWORD)ptr, ret );
1143 return ret;
1147 /***********************************************************************
1148 * HeapValidate (KERNEL32.343)
1150 BOOL32 WINAPI HeapValidate( HANDLE32 heap, DWORD flags, LPCVOID block )
1152 SUBHEAP *subheap;
1153 HEAP *heapPtr = (HEAP *)heap;
1155 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1157 fprintf( stderr, "Invalid heap %08x!\n", heap );
1158 return FALSE;
1161 if (block)
1163 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1164 ((char *)block < (char *)subheap + subheap->headerSize
1165 + sizeof(ARENA_INUSE)))
1167 fprintf( stderr, "Heap %08lx: block %08lx is not inside heap\n",
1168 (DWORD)heap, (DWORD)block );
1169 return FALSE;
1171 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1174 subheap = &heapPtr->subheap;
1175 while (subheap)
1177 char *ptr = (char *)subheap + subheap->headerSize;
1178 while (ptr < (char *)subheap + subheap->size)
1180 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1182 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1183 return FALSE;
1184 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1186 else
1188 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1189 return FALSE;
1190 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1193 subheap = subheap->next;
1195 return TRUE;
1199 /***********************************************************************
1200 * HeapWalk (KERNEL32.344)
1202 BOOL32 WINAPI HeapWalk( HANDLE32 heap, void *entry )
1204 fprintf( stderr, "HeapWalk(%08x): not implemented\n", heap );
1205 return FALSE;
1209 /***********************************************************************
1210 * HEAP_xalloc
1212 * Same as HeapAlloc(), but die on failure.
1214 LPVOID HEAP_xalloc( HANDLE32 heap, DWORD flags, DWORD size )
1216 LPVOID p = HeapAlloc( heap, flags, size );
1217 if (!p)
1219 fprintf( stderr, "Virtual memory exhausted.\n" );
1220 exit(1);
1222 return p;
1226 /***********************************************************************
1227 * HEAP_strdupA
1229 LPSTR HEAP_strdupA( HANDLE32 heap, DWORD flags, LPCSTR str )
1231 LPSTR p = HEAP_xalloc( heap, flags, lstrlen32A(str) + 1 );
1232 lstrcpy32A( p, str );
1233 return p;
1237 /***********************************************************************
1238 * HEAP_strdupW
1240 LPWSTR HEAP_strdupW( HANDLE32 heap, DWORD flags, LPCWSTR str )
1242 INT32 len = lstrlen32W(str) + 1;
1243 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1244 lstrcpy32W( p, str );
1245 return p;
1249 /***********************************************************************
1250 * HEAP_strdupAtoW
1252 LPWSTR HEAP_strdupAtoW( HANDLE32 heap, DWORD flags, LPCSTR str )
1254 LPWSTR ret;
1256 if (!str) return NULL;
1257 ret = HEAP_xalloc( heap, flags, (lstrlen32A(str)+1) * sizeof(WCHAR) );
1258 lstrcpyAtoW( ret, str );
1259 return ret;
1263 /***********************************************************************
1264 * HEAP_strdupWtoA
1266 LPSTR HEAP_strdupWtoA( HANDLE32 heap, DWORD flags, LPCWSTR str )
1268 LPSTR ret;
1270 if (!str) return NULL;
1271 ret = HEAP_xalloc( heap, flags, lstrlen32W(str) + 1 );
1272 lstrcpyWtoA( ret, str );
1273 return ret;