Release 980315
[wine/multimedia.git] / memory / heap.c
blobe657d384b5929a6c46b9cf787d492e88cd66ccc0
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 "debug.h"
19 /* Note: the heap data structures are based on what Pietrek describes in his
20 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
21 * the same, but could be easily adapted if it turns out some programs
22 * require it.
25 typedef struct tagARENA_INUSE
27 DWORD size; /* Block size; must be the first field */
28 WORD threadId; /* Allocating thread id */
29 WORD magic; /* Magic number */
30 DWORD callerEIP; /* EIP of caller upon allocation */
31 } ARENA_INUSE;
33 typedef struct tagARENA_FREE
35 DWORD size; /* Block size; must be the first field */
36 WORD threadId; /* Freeing thread id */
37 WORD magic; /* Magic number */
38 struct tagARENA_FREE *next; /* Next free arena */
39 struct tagARENA_FREE *prev; /* Prev free arena */
40 } ARENA_FREE;
42 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
43 #define ARENA_FLAG_PREV_FREE 0x00000002
44 #define ARENA_SIZE_MASK 0xfffffffc
45 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
46 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
48 #define ARENA_INUSE_FILLER 0x55
49 #define ARENA_FREE_FILLER 0xaa
51 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
53 /* Max size of the blocks on the free lists */
54 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
56 0x20, 0x80, 0x200, 0xffffffff
59 typedef struct
61 DWORD size;
62 ARENA_FREE arena;
63 } FREE_LIST_ENTRY;
65 struct tagHEAP;
67 typedef struct tagSUBHEAP
69 DWORD size; /* Size of the whole sub-heap */
70 DWORD commitSize; /* Committed size of the sub-heap */
71 DWORD headerSize; /* Size of the heap header */
72 struct tagSUBHEAP *next; /* Next sub-heap */
73 struct tagHEAP *heap; /* Main heap structure */
74 DWORD magic; /* Magic number */
75 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
76 } SUBHEAP;
78 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
80 typedef struct tagHEAP
82 SUBHEAP subheap; /* First sub-heap */
83 struct tagHEAP *next; /* Next heap for this process */
84 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
85 CRITICAL_SECTION critSection; /* Critical section for serialization */
86 DWORD flags; /* Heap flags */
87 DWORD magic; /* Magic number */
88 } HEAP;
90 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
92 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
93 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
95 HANDLE32 SystemHeap = 0;
96 HANDLE32 SegptrHeap = 0;
97 CRITICAL_SECTION *HEAP_SystemLock = NULL;
100 /***********************************************************************
101 * HEAP_Dump
103 void HEAP_Dump( HEAP *heap )
105 int i;
106 SUBHEAP *subheap;
107 char *ptr;
109 printf( "Heap: %08lx\n", (DWORD)heap );
110 printf( "Next: %08lx Sub-heaps: %08lx",
111 (DWORD)heap->next, (DWORD)&heap->subheap );
112 subheap = &heap->subheap;
113 while (subheap->next)
115 printf( " -> %08lx", (DWORD)subheap->next );
116 subheap = subheap->next;
119 printf( "\nFree lists:\n Block Stat Size Id\n" );
120 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
121 printf( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
122 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
123 heap->freeList[i].arena.threadId,
124 (DWORD)heap->freeList[i].arena.prev,
125 (DWORD)heap->freeList[i].arena.next );
127 subheap = &heap->subheap;
128 while (subheap)
130 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
131 printf( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
132 (DWORD)subheap, subheap->size, subheap->commitSize );
134 printf( "\n Block Stat Size Id\n" );
135 ptr = (char*)subheap + subheap->headerSize;
136 while (ptr < (char *)subheap + subheap->size)
138 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
140 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
141 printf( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
142 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
143 pArena->threadId, (DWORD)pArena->prev,
144 (DWORD)pArena->next);
145 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
146 arenaSize += sizeof(ARENA_FREE);
147 freeSize += pArena->size & ARENA_SIZE_MASK;
149 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
151 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
152 printf( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
153 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
154 pArena->threadId, *((DWORD *)pArena - 1),
155 pArena->callerEIP );
156 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
157 arenaSize += sizeof(ARENA_INUSE);
158 usedSize += pArena->size & ARENA_SIZE_MASK;
160 else
162 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
163 printf( "%08lx used %08lx %04x EIP=%08lx\n",
164 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
165 pArena->threadId, pArena->callerEIP );
166 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
167 arenaSize += sizeof(ARENA_INUSE);
168 usedSize += pArena->size & ARENA_SIZE_MASK;
171 printf( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
172 subheap->size, subheap->commitSize, freeSize, usedSize,
173 arenaSize, (arenaSize * 100) / subheap->size );
174 subheap = subheap->next;
179 /***********************************************************************
180 * HEAP_GetPtr
182 static HEAP *HEAP_GetPtr( HANDLE32 heap )
184 HEAP *heapPtr = (HEAP *)heap;
185 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
187 fprintf( stderr, "Invalid heap %08x!\n", heap );
188 SetLastError( ERROR_INVALID_HANDLE );
189 return NULL;
191 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
193 HEAP_Dump( heapPtr );
194 assert( FALSE );
195 SetLastError( ERROR_INVALID_HANDLE );
196 return NULL;
198 return heapPtr;
202 /***********************************************************************
203 * HEAP_InsertFreeBlock
205 * Insert a free block into the free list.
207 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
209 FREE_LIST_ENTRY *pEntry = heap->freeList;
210 while (pEntry->size < pArena->size) pEntry++;
211 pArena->size |= ARENA_FLAG_FREE;
212 pArena->next = pEntry->arena.next;
213 pArena->next->prev = pArena;
214 pArena->prev = &pEntry->arena;
215 pEntry->arena.next = pArena;
219 /***********************************************************************
220 * HEAP_FindSubHeap
222 * Find the sub-heap containing a given address.
224 static SUBHEAP *HEAP_FindSubHeap( HEAP *heap, LPCVOID ptr )
226 SUBHEAP *sub = &heap->subheap;
227 while (sub)
229 if (((char *)ptr >= (char *)sub) &&
230 ((char *)ptr < (char *)sub + sub->size)) return sub;
231 sub = sub->next;
233 return NULL;
237 /***********************************************************************
238 * HEAP_Commit
240 * Make sure the heap storage is committed up to (not including) ptr.
242 static BOOL32 HEAP_Commit( SUBHEAP *subheap, void *ptr )
244 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
245 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
246 if (size > subheap->size) size = subheap->size;
247 if (size <= subheap->commitSize) return TRUE;
248 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
249 size - subheap->commitSize, MEM_COMMIT,
250 PAGE_EXECUTE_READWRITE))
252 fprintf( stderr, "HEAP_Commit: could not commit %08lx bytes at %08lx for heap %08lx\n",
253 size - subheap->commitSize,
254 (DWORD)((char *)subheap + subheap->commitSize),
255 (DWORD)subheap->heap );
256 return FALSE;
258 subheap->commitSize = size;
259 return TRUE;
263 /***********************************************************************
264 * HEAP_Decommit
266 * If possible, decommit the heap storage from (including) 'ptr'.
268 static BOOL32 HEAP_Decommit( SUBHEAP *subheap, void *ptr )
270 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
271 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
272 if (size >= subheap->commitSize) return TRUE;
273 if (!VirtualFree( (char *)subheap + size,
274 subheap->commitSize - size, MEM_DECOMMIT ))
276 fprintf( stderr, "HEAP_Decommit: could not decommit %08lx bytes at %08lx for heap %08lx\n",
277 subheap->commitSize - size,
278 (DWORD)((char *)subheap + size),
279 (DWORD)subheap->heap );
280 return FALSE;
282 subheap->commitSize = size;
283 return TRUE;
287 /***********************************************************************
288 * HEAP_CreateFreeBlock
290 * Create a free block at a specified address. 'size' is the size of the
291 * whole block, including the new arena.
293 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
295 ARENA_FREE *pFree;
297 /* Create a free arena */
299 pFree = (ARENA_FREE *)ptr;
300 pFree->threadId = GetCurrentTask();
301 pFree->magic = ARENA_FREE_MAGIC;
303 /* If debugging, erase the freed block content */
305 if (TRACE_ON(heap))
307 char *pEnd = (char *)ptr + size;
308 if (pEnd > (char *)subheap + subheap->commitSize)
309 pEnd = (char *)subheap + subheap->commitSize;
310 if (pEnd > (char *)(pFree + 1))
311 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
314 /* Check if next block is free also */
316 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
317 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
319 /* Remove the next arena from the free list */
320 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
321 pNext->next->prev = pNext->prev;
322 pNext->prev->next = pNext->next;
323 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
324 if (TRACE_ON(heap))
325 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
328 /* Set the next block PREV_FREE flag and pointer */
330 if ((char *)ptr + size < (char *)subheap + subheap->size)
332 DWORD *pNext = (DWORD *)((char *)ptr + size);
333 *pNext |= ARENA_FLAG_PREV_FREE;
334 *(ARENA_FREE **)(pNext - 1) = pFree;
337 /* Last, insert the new block into the free list */
339 pFree->size = size - sizeof(*pFree);
340 HEAP_InsertFreeBlock( subheap->heap, pFree );
344 /***********************************************************************
345 * HEAP_MakeInUseBlockFree
347 * Turn an in-use block into a free block. Can also decommit the end of
348 * the heap, and possibly even free the sub-heap altogether.
350 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
352 ARENA_FREE *pFree;
353 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
355 /* Check if we can merge with previous block */
357 if (pArena->size & ARENA_FLAG_PREV_FREE)
359 pFree = *((ARENA_FREE **)pArena - 1);
360 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
361 /* Remove it from the free list */
362 pFree->next->prev = pFree->prev;
363 pFree->prev->next = pFree->next;
365 else pFree = (ARENA_FREE *)pArena;
367 /* Create a free block */
369 HEAP_CreateFreeBlock( subheap, pFree, size );
370 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
371 if ((char *)pFree + size < (char *)subheap + subheap->size)
372 return; /* Not the last block, so nothing more to do */
374 /* Free the whole sub-heap if it's empty and not the original one */
376 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
377 (subheap != &subheap->heap->subheap))
379 SUBHEAP *pPrev = &subheap->heap->subheap;
380 /* Remove the free block from the list */
381 pFree->next->prev = pFree->prev;
382 pFree->prev->next = pFree->next;
383 /* Remove the subheap from the list */
384 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
385 if (pPrev) pPrev->next = subheap->next;
386 /* Free the memory */
387 subheap->magic = 0;
388 if (subheap->selector) FreeSelector( subheap->selector );
389 VirtualFree( subheap, 0, MEM_RELEASE );
390 return;
393 /* Decommit the end of the heap */
395 HEAP_Decommit( subheap, pFree + 1 );
399 /***********************************************************************
400 * HEAP_ShrinkBlock
402 * Shrink an in-use block.
404 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
406 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
408 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
409 (pArena->size & ARENA_SIZE_MASK) - size );
410 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
412 else
414 /* Turn off PREV_FREE flag in next block */
415 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
416 if (pNext < (char *)subheap + subheap->size)
417 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
422 /***********************************************************************
423 * HEAP_CreateSubHeap
425 * Create a sub-heap of the given size.
427 static SUBHEAP *HEAP_CreateSubHeap( DWORD flags, DWORD commitSize,
428 DWORD totalSize )
430 SUBHEAP *subheap;
431 WORD selector = 0;
433 /* Round-up sizes on a 64K boundary */
435 if (flags & HEAP_WINE_SEGPTR)
437 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
439 else
441 totalSize = (totalSize + 0xffff) & 0xffff0000;
442 commitSize = (commitSize + 0xffff) & 0xffff0000;
443 if (!commitSize) commitSize = 0x10000;
444 if (totalSize < commitSize) totalSize = commitSize;
447 /* Allocate the memory block */
449 if (!(subheap = VirtualAlloc( NULL, totalSize,
450 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
452 fprintf( stderr, "HEAP_CreateSubHeap: could not VirtualAlloc %08lx bytes\n",
453 totalSize );
454 return NULL;
456 if (!VirtualAlloc(subheap, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
458 fprintf( stderr, "HEAP_CreateSubHeap: could not commit %08lx bytes for sub-heap %08lx\n",
459 commitSize, (DWORD)subheap );
460 VirtualFree( subheap, 0, MEM_RELEASE );
461 return NULL;
464 /* Allocate a selector if needed */
466 if (flags & HEAP_WINE_SEGPTR)
468 selector = SELECTOR_AllocBlock( subheap, totalSize,
469 (flags & HEAP_WINE_CODESEG) ? SEGMENT_CODE : SEGMENT_DATA,
470 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
471 if (!selector)
473 fprintf( stderr, "HEAP_CreateSubHeap: could not allocate selector\n" );
474 VirtualFree( subheap, 0, MEM_RELEASE );
475 return NULL;
479 /* Fill the sub-heap structure */
481 subheap->size = totalSize;
482 subheap->commitSize = commitSize;
483 subheap->headerSize = sizeof(*subheap);
484 subheap->next = NULL;
485 subheap->heap = NULL;
486 subheap->magic = SUBHEAP_MAGIC;
487 subheap->selector = selector;
488 return subheap;
492 /***********************************************************************
493 * HEAP_FindFreeBlock
495 * Find a free block at least as large as the requested size, and make sure
496 * the requested size is committed.
498 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
499 SUBHEAP **ppSubHeap )
501 SUBHEAP *subheap;
502 ARENA_FREE *pArena;
503 FREE_LIST_ENTRY *pEntry = heap->freeList;
505 /* Find a suitable free list, and in it find a block large enough */
507 while (pEntry->size < size) pEntry++;
508 pArena = pEntry->arena.next;
509 while (pArena != &heap->freeList[0].arena)
511 if (pArena->size > size)
513 subheap = HEAP_FindSubHeap( heap, pArena );
514 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
515 + size + HEAP_MIN_BLOCK_SIZE))
516 return NULL;
517 *ppSubHeap = subheap;
518 return pArena;
521 pArena = pArena->next;
524 /* If no block was found, attempt to grow the heap */
526 if (!(heap->flags & HEAP_GROWABLE))
528 fprintf( stderr, "HEAP_FindFreeBlock: Not enough space in heap %08lx for %08lx bytes\n",
529 (DWORD)heap, size );
530 return NULL;
532 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
533 if (!(subheap = HEAP_CreateSubHeap( heap->flags, size,
534 MAX( HEAP_DEF_SIZE, size ) )))
535 return NULL;
537 /* Insert the new sub-heap in the list */
539 subheap->heap = heap;
540 subheap->next = heap->subheap.next;
541 heap->subheap.next = subheap;
542 size = subheap->size;
543 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
544 (DWORD)subheap, size, (DWORD)heap );
546 HEAP_CreateFreeBlock( subheap, subheap + 1, size - sizeof(*subheap) );
547 *ppSubHeap = subheap;
548 return (ARENA_FREE *)(subheap + 1);
552 /***********************************************************************
553 * HEAP_IsValidArenaPtr
555 * Check that the pointer is inside the range possible for arenas.
557 static BOOL32 HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
559 int i;
560 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
561 if (!subheap) return FALSE;
562 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
563 if (subheap != &heap->subheap) return FALSE;
564 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
565 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
566 return FALSE;
570 /***********************************************************************
571 * HEAP_ValidateFreeArena
573 static BOOL32 HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
575 char *heapEnd = (char *)subheap + subheap->size;
577 /* Check magic number */
578 if (pArena->magic != ARENA_FREE_MAGIC)
580 fprintf( stderr, "Heap %08lx: invalid free arena magic for %08lx\n",
581 (DWORD)subheap->heap, (DWORD)pArena );
582 return FALSE;
584 /* Check size flags */
585 if (!(pArena->size & ARENA_FLAG_FREE) ||
586 (pArena->size & ARENA_FLAG_PREV_FREE))
588 fprintf( stderr, "Heap %08lx: bad flags %lx for free arena %08lx\n",
589 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
591 /* Check arena size */
592 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
594 fprintf( stderr, "Heap %08lx: bad size %08lx for free arena %08lx\n",
595 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
596 return FALSE;
598 /* Check that next pointer is valid */
599 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
601 fprintf( stderr, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
602 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
603 return FALSE;
605 /* Check that next arena is free */
606 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
607 (pArena->next->magic != ARENA_FREE_MAGIC))
609 fprintf( stderr, "Heap %08lx: next arena %08lx invalid for %08lx\n",
610 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
611 return FALSE;
613 /* Check that prev pointer is valid */
614 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
616 fprintf( stderr, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
617 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
618 return FALSE;
620 /* Check that prev arena is free */
621 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
622 (pArena->prev->magic != ARENA_FREE_MAGIC))
624 fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
625 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
626 return FALSE;
628 /* Check that next block has PREV_FREE flag */
629 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
631 if (!(*(DWORD *)((char *)(pArena + 1) +
632 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
634 fprintf( stderr, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
635 (DWORD)subheap->heap, (DWORD)pArena );
636 return FALSE;
638 /* Check next block back pointer */
639 if (*((ARENA_FREE **)((char *)(pArena + 1) +
640 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
642 fprintf( stderr, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
643 (DWORD)subheap->heap, (DWORD)pArena,
644 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
645 return FALSE;
648 return TRUE;
652 /***********************************************************************
653 * HEAP_ValidateInUseArena
655 static BOOL32 HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
657 char *heapEnd = (char *)subheap + subheap->size;
659 /* Check magic number */
660 if (pArena->magic != ARENA_INUSE_MAGIC)
662 fprintf( stderr, "Heap %08lx: invalid in-use arena magic for %08lx\n",
663 (DWORD)subheap->heap, (DWORD)pArena );
664 return FALSE;
666 /* Check size flags */
667 if (pArena->size & ARENA_FLAG_FREE)
669 fprintf( stderr, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
670 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
672 /* Check arena size */
673 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
675 fprintf( stderr, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
676 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
677 return FALSE;
679 /* Check next arena PREV_FREE flag */
680 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
681 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
683 fprintf( stderr, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
684 (DWORD)subheap->heap, (DWORD)pArena );
685 return FALSE;
687 /* Check prev free arena */
688 if (pArena->size & ARENA_FLAG_PREV_FREE)
690 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
691 /* Check prev pointer */
692 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
694 fprintf(stderr, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
695 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
696 return FALSE;
698 /* Check that prev arena is free */
699 if (!(pPrev->size & ARENA_FLAG_FREE) ||
700 (pPrev->magic != ARENA_FREE_MAGIC))
702 fprintf( stderr, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
703 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
704 return FALSE;
706 /* Check that prev arena is really the previous block */
707 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
709 fprintf( stderr, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
710 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
711 return FALSE;
714 return TRUE;
718 /***********************************************************************
719 * HEAP_IsInsideHeap
721 * Check whether the pointer is to a block inside a given heap.
723 int HEAP_IsInsideHeap( HANDLE32 heap, DWORD flags, LPCVOID ptr )
725 HEAP *heapPtr = HEAP_GetPtr( heap );
726 SUBHEAP *subheap;
727 int ret;
729 /* Validate the parameters */
731 if (!heapPtr) return 0;
732 flags |= heapPtr->flags;
733 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
734 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
735 (((char *)ptr >= (char *)subheap + subheap->headerSize
736 + sizeof(ARENA_INUSE))));
737 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
738 return ret;
742 /***********************************************************************
743 * HEAP_GetSegptr
745 * Transform a linear pointer into a SEGPTR. The pointer must have been
746 * allocated from a HEAP_WINE_SEGPTR heap.
748 SEGPTR HEAP_GetSegptr( HANDLE32 heap, DWORD flags, LPCVOID ptr )
750 HEAP *heapPtr = HEAP_GetPtr( heap );
751 SUBHEAP *subheap;
752 SEGPTR ret;
754 /* Validate the parameters */
756 if (!heapPtr) return 0;
757 flags |= heapPtr->flags;
758 if (!(flags & HEAP_WINE_SEGPTR))
760 fprintf( stderr, "HEAP_GetSegptr: heap %08x is not a SEGPTR heap\n",
761 heap );
762 return 0;
764 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
766 /* Get the subheap */
768 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
770 fprintf( stderr, "HEAP_GetSegptr: %p is not inside heap %08x\n",
771 ptr, heap );
772 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
773 return 0;
776 /* Build the SEGPTR */
778 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
779 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
780 return ret;
784 /***********************************************************************
785 * HeapCreate (KERNEL32.336)
787 HANDLE32 WINAPI HeapCreate( DWORD flags, DWORD initialSize, DWORD maxSize )
789 int i;
790 HEAP *heap;
791 SUBHEAP *subheap;
792 FREE_LIST_ENTRY *pEntry;
794 /* Allocate the heap block */
796 if (!maxSize)
798 maxSize = HEAP_DEF_SIZE;
799 flags |= HEAP_GROWABLE;
801 if (!(subheap = HEAP_CreateSubHeap( flags, initialSize, maxSize )))
803 SetLastError( ERROR_OUTOFMEMORY );
804 return 0;
807 /* Fill the heap structure */
809 heap = (HEAP *)subheap;
810 subheap->heap = heap;
811 subheap->headerSize = sizeof(HEAP);
812 heap->next = NULL;
813 heap->flags = flags;
814 heap->magic = HEAP_MAGIC;
816 /* Build the free lists */
818 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
820 pEntry->size = HEAP_freeListSizes[i];
821 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
822 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
823 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
824 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
825 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
826 pEntry->arena.threadId = 0;
827 pEntry->arena.magic = ARENA_FREE_MAGIC;
830 /* Create the first free block */
832 HEAP_CreateFreeBlock( subheap, heap + 1, subheap->size - sizeof(*heap) );
834 /* Initialize critical section */
836 InitializeCriticalSection( &heap->critSection );
837 if (!SystemHeap) HEAP_SystemLock = &heap->critSection;
839 /* We are done */
841 return (HANDLE32)heap;
845 /***********************************************************************
846 * HeapDestroy (KERNEL32.337)
848 BOOL32 WINAPI HeapDestroy( HANDLE32 heap )
850 HEAP *heapPtr = HEAP_GetPtr( heap );
851 SUBHEAP *subheap;
853 TRACE(heap, "%08x\n", heap );
854 if (!heapPtr) return FALSE;
856 DeleteCriticalSection( &heapPtr->critSection );
857 subheap = &heapPtr->subheap;
858 while (subheap)
860 SUBHEAP *next = subheap->next;
861 if (subheap->selector) FreeSelector( subheap->selector );
862 VirtualFree( subheap, 0, MEM_RELEASE );
863 subheap = next;
865 return TRUE;
869 /***********************************************************************
870 * HeapAlloc (KERNEL32.334)
872 LPVOID WINAPI HeapAlloc( HANDLE32 heap, DWORD flags, DWORD size )
874 ARENA_FREE *pArena;
875 ARENA_INUSE *pInUse;
876 SUBHEAP *subheap;
877 HEAP *heapPtr = HEAP_GetPtr( heap );
879 /* Validate the parameters */
881 if (!heapPtr) return NULL;
882 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
883 flags |= heapPtr->flags;
884 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
885 size = (size + 3) & ~3;
886 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
888 /* Locate a suitable free block */
890 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
892 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
893 heap, flags, size );
894 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
895 SetLastError( ERROR_COMMITMENT_LIMIT );
896 return NULL;
899 /* Remove the arena from the free list */
901 pArena->next->prev = pArena->prev;
902 pArena->prev->next = pArena->next;
904 /* Build the in-use arena */
906 pInUse = (ARENA_INUSE *)pArena;
907 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
908 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
909 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
910 pInUse->threadId = GetCurrentTask();
911 pInUse->magic = ARENA_INUSE_MAGIC;
913 /* Shrink the block */
915 HEAP_ShrinkBlock( subheap, pInUse, size );
917 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
918 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
920 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
922 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
923 heap, flags, size, (DWORD)(pInUse + 1) );
924 return (LPVOID)(pInUse + 1);
928 /***********************************************************************
929 * HeapFree (KERNEL32.338)
931 BOOL32 WINAPI HeapFree( HANDLE32 heap, DWORD flags, LPVOID ptr )
933 ARENA_INUSE *pInUse;
934 SUBHEAP *subheap;
935 HEAP *heapPtr = HEAP_GetPtr( heap );
937 /* Validate the parameters */
939 if (!heapPtr) return FALSE;
940 flags &= HEAP_NO_SERIALIZE;
941 flags |= heapPtr->flags;
942 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
943 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
945 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
946 SetLastError( ERROR_INVALID_PARAMETER );
947 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
948 heap, flags, (DWORD)ptr );
949 return FALSE;
952 /* Turn the block into a free block */
954 pInUse = (ARENA_INUSE *)ptr - 1;
955 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
956 HEAP_MakeInUseBlockFree( subheap, pInUse );
958 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
959 /* SetLastError( 0 ); */
961 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
962 heap, flags, (DWORD)ptr );
963 return TRUE;
967 /***********************************************************************
968 * HeapReAlloc (KERNEL32.340)
970 LPVOID WINAPI HeapReAlloc( HANDLE32 heap, DWORD flags, LPVOID ptr, DWORD size )
972 ARENA_INUSE *pArena;
973 DWORD oldSize;
974 HEAP *heapPtr;
975 SUBHEAP *subheap;
977 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
978 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
980 /* Validate the parameters */
982 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
983 HEAP_REALLOC_IN_PLACE_ONLY;
984 flags |= heapPtr->flags;
985 size = (size + 3) & ~3;
986 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
988 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
989 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
991 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
992 SetLastError( ERROR_INVALID_PARAMETER );
993 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
994 heap, flags, (DWORD)ptr, size );
995 return NULL;
998 /* Check if we need to grow the block */
1000 pArena = (ARENA_INUSE *)ptr - 1;
1001 pArena->threadId = GetCurrentTask();
1002 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1003 oldSize = (pArena->size & ARENA_SIZE_MASK);
1004 if (size > oldSize)
1006 char *pNext = (char *)(pArena + 1) + oldSize;
1007 if ((pNext < (char *)subheap + subheap->size) &&
1008 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1009 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1011 /* The next block is free and large enough */
1012 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1013 pFree->next->prev = pFree->prev;
1014 pFree->prev->next = pFree->next;
1015 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1016 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1017 + size + HEAP_MIN_BLOCK_SIZE))
1019 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1020 SetLastError( ERROR_OUTOFMEMORY );
1021 return NULL;
1023 HEAP_ShrinkBlock( subheap, pArena, size );
1025 else /* Do it the hard way */
1027 ARENA_FREE *pNew;
1028 ARENA_INUSE *pInUse;
1029 SUBHEAP *newsubheap;
1031 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1032 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1034 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1035 SetLastError( ERROR_OUTOFMEMORY );
1036 return NULL;
1039 /* Build the in-use arena */
1041 pNew->next->prev = pNew->prev;
1042 pNew->prev->next = pNew->next;
1043 pInUse = (ARENA_INUSE *)pNew;
1044 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1045 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1046 pInUse->threadId = GetCurrentTask();
1047 pInUse->magic = ARENA_INUSE_MAGIC;
1048 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1049 memcpy( pInUse + 1, pArena + 1, oldSize );
1051 /* Free the previous block */
1053 HEAP_MakeInUseBlockFree( subheap, pArena );
1054 subheap = newsubheap;
1055 pArena = pInUse;
1058 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1060 /* Clear the extra bytes if needed */
1062 if (size > oldSize)
1064 if (flags & HEAP_ZERO_MEMORY)
1065 memset( (char *)(pArena + 1) + oldSize, 0,
1066 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1067 else if (TRACE_ON(heap))
1068 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1069 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1072 /* Return the new arena */
1074 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1075 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1077 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1078 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1079 return (LPVOID)(pArena + 1);
1083 /***********************************************************************
1084 * HeapCompact (KERNEL32.335)
1086 DWORD WINAPI HeapCompact( HANDLE32 heap, DWORD flags )
1088 return 0;
1092 /***********************************************************************
1093 * HeapLock (KERNEL32.339)
1095 BOOL32 WINAPI HeapLock( HANDLE32 heap )
1097 HEAP *heapPtr = HEAP_GetPtr( heap );
1098 if (!heapPtr) return FALSE;
1099 EnterCriticalSection( &heapPtr->critSection );
1100 return TRUE;
1104 /***********************************************************************
1105 * HeapUnlock (KERNEL32.342)
1107 BOOL32 WINAPI HeapUnlock( HANDLE32 heap )
1109 HEAP *heapPtr = HEAP_GetPtr( heap );
1110 if (!heapPtr) return FALSE;
1111 LeaveCriticalSection( &heapPtr->critSection );
1112 return TRUE;
1116 /***********************************************************************
1117 * HeapSize (KERNEL32.341)
1119 DWORD WINAPI HeapSize( HANDLE32 heap, DWORD flags, LPVOID ptr )
1121 DWORD ret;
1122 HEAP *heapPtr = HEAP_GetPtr( heap );
1124 if (!heapPtr) return FALSE;
1125 flags &= HEAP_NO_SERIALIZE;
1126 flags |= heapPtr->flags;
1127 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1128 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1130 SetLastError( ERROR_INVALID_PARAMETER );
1131 ret = 0xffffffff;
1133 else
1135 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1136 ret = pArena->size & ARENA_SIZE_MASK;
1138 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1140 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1141 heap, flags, (DWORD)ptr, ret );
1142 return ret;
1146 /***********************************************************************
1147 * HeapValidate (KERNEL32.343)
1149 BOOL32 WINAPI HeapValidate( HANDLE32 heap, DWORD flags, LPCVOID block )
1151 SUBHEAP *subheap;
1152 HEAP *heapPtr = (HEAP *)heap;
1154 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1156 fprintf( stderr, "Invalid heap %08x!\n", heap );
1157 return FALSE;
1160 if (block)
1162 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1163 ((char *)block < (char *)subheap + subheap->headerSize
1164 + sizeof(ARENA_INUSE)))
1166 fprintf( stderr, "Heap %08lx: block %08lx is not inside heap\n",
1167 (DWORD)heap, (DWORD)block );
1168 return FALSE;
1170 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1173 subheap = &heapPtr->subheap;
1174 while (subheap)
1176 char *ptr = (char *)subheap + subheap->headerSize;
1177 while (ptr < (char *)subheap + subheap->size)
1179 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1181 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1182 return FALSE;
1183 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1185 else
1187 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1188 return FALSE;
1189 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1192 subheap = subheap->next;
1194 return TRUE;
1198 /***********************************************************************
1199 * HeapWalk (KERNEL32.344)
1201 BOOL32 WINAPI HeapWalk( HANDLE32 heap, void *entry )
1203 fprintf( stderr, "HeapWalk(%08x): not implemented\n", heap );
1204 return FALSE;
1208 /***********************************************************************
1209 * HEAP_xalloc
1211 * Same as HeapAlloc(), but die on failure.
1213 LPVOID HEAP_xalloc( HANDLE32 heap, DWORD flags, DWORD size )
1215 LPVOID p = HeapAlloc( heap, flags, size );
1216 if (!p)
1218 fprintf( stderr, "Virtual memory exhausted.\n" );
1219 exit(1);
1221 return p;
1225 /***********************************************************************
1226 * HEAP_strdupA
1228 LPSTR HEAP_strdupA( HANDLE32 heap, DWORD flags, LPCSTR str )
1230 LPSTR p = HEAP_xalloc( heap, flags, lstrlen32A(str) + 1 );
1231 lstrcpy32A( p, str );
1232 return p;
1236 /***********************************************************************
1237 * HEAP_strdupW
1239 LPWSTR HEAP_strdupW( HANDLE32 heap, DWORD flags, LPCWSTR str )
1241 INT32 len = lstrlen32W(str) + 1;
1242 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1243 lstrcpy32W( p, str );
1244 return p;
1248 /***********************************************************************
1249 * HEAP_strdupAtoW
1251 LPWSTR HEAP_strdupAtoW( HANDLE32 heap, DWORD flags, LPCSTR str )
1253 LPWSTR ret;
1255 if (!str) return NULL;
1256 ret = HEAP_xalloc( heap, flags, (lstrlen32A(str)+1) * sizeof(WCHAR) );
1257 lstrcpyAtoW( ret, str );
1258 return ret;
1262 /***********************************************************************
1263 * HEAP_strdupWtoA
1265 LPSTR HEAP_strdupWtoA( HANDLE32 heap, DWORD flags, LPCWSTR str )
1267 LPSTR ret;
1269 if (!str) return NULL;
1270 ret = HEAP_xalloc( heap, flags, lstrlen32W(str) + 1 );
1271 lstrcpyWtoA( ret, str );
1272 return ret;