Initial revision
[wine/multimedia.git] / memory / heap.c
blob05dc8facfc7dbb500a0a50ab42864003d4dd7d56
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
6 */
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include "windows.h"
12 #include "selectors.h"
13 #include "global.h"
14 #include "winbase.h"
15 #include "winerror.h"
16 #include "winnt.h"
17 #include "heap.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 DUMP( "Heap: %08lx\n", (DWORD)heap );
111 DUMP( "Next: %08lx Sub-heaps: %08lx",
112 (DWORD)heap->next, (DWORD)&heap->subheap );
113 subheap = &heap->subheap;
114 while (subheap->next)
116 DUMP( " -> %08lx", (DWORD)subheap->next );
117 subheap = subheap->next;
120 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
121 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
122 DUMP( "%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 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
133 (DWORD)subheap, subheap->size, subheap->commitSize );
135 DUMP( "\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 DUMP( "%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 DUMP( "%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 DUMP( "%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 DUMP( "\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
182 * RETURNS
183 * Pointer to the heap
184 * NULL: Failure
186 static HEAP *HEAP_GetPtr(
187 HANDLE32 heap /* [in] Handle to the heap */
189 HEAP *heapPtr = (HEAP *)heap;
190 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
192 WARN(heap, "Invalid heap %08x!\n", heap );
193 SetLastError( ERROR_INVALID_HANDLE );
194 return NULL;
196 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
198 HEAP_Dump( heapPtr );
199 assert( FALSE );
200 SetLastError( ERROR_INVALID_HANDLE );
201 return NULL;
203 return heapPtr;
207 /***********************************************************************
208 * HEAP_InsertFreeBlock
210 * Insert a free block into the free list.
212 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
214 FREE_LIST_ENTRY *pEntry = heap->freeList;
215 while (pEntry->size < pArena->size) pEntry++;
216 pArena->size |= ARENA_FLAG_FREE;
217 pArena->next = pEntry->arena.next;
218 pArena->next->prev = pArena;
219 pArena->prev = &pEntry->arena;
220 pEntry->arena.next = pArena;
224 /***********************************************************************
225 * HEAP_FindSubHeap
226 * Find the sub-heap containing a given address.
228 * RETURNS
229 * Pointer: Success
230 * NULL: Failure
232 static SUBHEAP *HEAP_FindSubHeap(
233 HEAP *heap, /* [in] Heap pointer */
234 LPCVOID ptr /* [in] Address */
236 SUBHEAP *sub = &heap->subheap;
237 while (sub)
239 if (((char *)ptr >= (char *)sub) &&
240 ((char *)ptr < (char *)sub + sub->size)) return sub;
241 sub = sub->next;
243 return NULL;
247 /***********************************************************************
248 * HEAP_Commit
250 * Make sure the heap storage is committed up to (not including) ptr.
252 static BOOL32 HEAP_Commit( SUBHEAP *subheap, void *ptr )
254 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
255 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
256 if (size > subheap->size) size = subheap->size;
257 if (size <= subheap->commitSize) return TRUE;
258 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
259 size - subheap->commitSize, MEM_COMMIT,
260 PAGE_EXECUTE_READWRITE))
262 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
263 size - subheap->commitSize,
264 (DWORD)((char *)subheap + subheap->commitSize),
265 (DWORD)subheap->heap );
266 return FALSE;
268 subheap->commitSize = size;
269 return TRUE;
273 /***********************************************************************
274 * HEAP_Decommit
276 * If possible, decommit the heap storage from (including) 'ptr'.
278 static BOOL32 HEAP_Decommit( SUBHEAP *subheap, void *ptr )
280 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
281 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
282 if (size >= subheap->commitSize) return TRUE;
283 if (!VirtualFree( (char *)subheap + size,
284 subheap->commitSize - size, MEM_DECOMMIT ))
286 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
287 subheap->commitSize - size,
288 (DWORD)((char *)subheap + size),
289 (DWORD)subheap->heap );
290 return FALSE;
292 subheap->commitSize = size;
293 return TRUE;
297 /***********************************************************************
298 * HEAP_CreateFreeBlock
300 * Create a free block at a specified address. 'size' is the size of the
301 * whole block, including the new arena.
303 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
305 ARENA_FREE *pFree;
307 /* Create a free arena */
309 pFree = (ARENA_FREE *)ptr;
310 pFree->threadId = GetCurrentTask();
311 pFree->magic = ARENA_FREE_MAGIC;
313 /* If debugging, erase the freed block content */
315 if (TRACE_ON(heap))
317 char *pEnd = (char *)ptr + size;
318 if (pEnd > (char *)subheap + subheap->commitSize)
319 pEnd = (char *)subheap + subheap->commitSize;
320 if (pEnd > (char *)(pFree + 1))
321 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
324 /* Check if next block is free also */
326 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
327 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
329 /* Remove the next arena from the free list */
330 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
331 pNext->next->prev = pNext->prev;
332 pNext->prev->next = pNext->next;
333 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
334 if (TRACE_ON(heap))
335 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
338 /* Set the next block PREV_FREE flag and pointer */
340 if ((char *)ptr + size < (char *)subheap + subheap->size)
342 DWORD *pNext = (DWORD *)((char *)ptr + size);
343 *pNext |= ARENA_FLAG_PREV_FREE;
344 *(ARENA_FREE **)(pNext - 1) = pFree;
347 /* Last, insert the new block into the free list */
349 pFree->size = size - sizeof(*pFree);
350 HEAP_InsertFreeBlock( subheap->heap, pFree );
354 /***********************************************************************
355 * HEAP_MakeInUseBlockFree
357 * Turn an in-use block into a free block. Can also decommit the end of
358 * the heap, and possibly even free the sub-heap altogether.
360 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
362 ARENA_FREE *pFree;
363 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
365 /* Check if we can merge with previous block */
367 if (pArena->size & ARENA_FLAG_PREV_FREE)
369 pFree = *((ARENA_FREE **)pArena - 1);
370 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
371 /* Remove it from the free list */
372 pFree->next->prev = pFree->prev;
373 pFree->prev->next = pFree->next;
375 else pFree = (ARENA_FREE *)pArena;
377 /* Create a free block */
379 HEAP_CreateFreeBlock( subheap, pFree, size );
380 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
381 if ((char *)pFree + size < (char *)subheap + subheap->size)
382 return; /* Not the last block, so nothing more to do */
384 /* Free the whole sub-heap if it's empty and not the original one */
386 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
387 (subheap != &subheap->heap->subheap))
389 SUBHEAP *pPrev = &subheap->heap->subheap;
390 /* Remove the free block from the list */
391 pFree->next->prev = pFree->prev;
392 pFree->prev->next = pFree->next;
393 /* Remove the subheap from the list */
394 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
395 if (pPrev) pPrev->next = subheap->next;
396 /* Free the memory */
397 subheap->magic = 0;
398 if (subheap->selector) FreeSelector( subheap->selector );
399 VirtualFree( subheap, 0, MEM_RELEASE );
400 return;
403 /* Decommit the end of the heap */
405 HEAP_Decommit( subheap, pFree + 1 );
409 /***********************************************************************
410 * HEAP_ShrinkBlock
412 * Shrink an in-use block.
414 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
416 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
418 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
419 (pArena->size & ARENA_SIZE_MASK) - size );
420 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
422 else
424 /* Turn off PREV_FREE flag in next block */
425 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
426 if (pNext < (char *)subheap + subheap->size)
427 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
431 /***********************************************************************
432 * HEAP_InitSubHeap
434 static BOOL32 HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
435 DWORD commitSize, DWORD totalSize )
437 SUBHEAP *subheap = (SUBHEAP *)address;
438 WORD selector = 0;
439 FREE_LIST_ENTRY *pEntry;
440 int i;
442 /* Commit memory */
444 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
446 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
447 commitSize, (DWORD)address );
448 return FALSE;
451 /* Allocate a selector if needed */
453 if (flags & HEAP_WINE_SEGPTR)
455 selector = SELECTOR_AllocBlock( address, totalSize,
456 (flags & HEAP_WINE_CODESEG) ? SEGMENT_CODE : SEGMENT_DATA,
457 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
458 if (!selector)
460 WARN(heap, "Could not allocate selector\n" );
461 return FALSE;
465 /* Fill the sub-heap structure */
467 subheap->heap = heap;
468 subheap->selector = selector;
469 subheap->size = totalSize;
470 subheap->commitSize = commitSize;
471 subheap->magic = SUBHEAP_MAGIC;
473 if ( subheap != (SUBHEAP *)heap )
475 /* If this is a secondary subheap, insert it into list */
477 subheap->headerSize = sizeof(SUBHEAP);
478 subheap->next = heap->subheap.next;
479 heap->subheap.next = subheap;
481 else
483 /* If this is a primary subheap, initialize main heap */
485 subheap->headerSize = sizeof(HEAP);
486 subheap->next = NULL;
487 heap->next = NULL;
488 heap->flags = flags;
489 heap->magic = HEAP_MAGIC;
491 /* Build the free lists */
493 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
495 pEntry->size = HEAP_freeListSizes[i];
496 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
497 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
498 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
499 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
500 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
501 pEntry->arena.threadId = 0;
502 pEntry->arena.magic = ARENA_FREE_MAGIC;
505 /* Initialize critical section */
507 InitializeCriticalSection( &heap->critSection );
508 if (!SystemHeap) HEAP_SystemLock = &heap->critSection;
511 /* Create the first free block */
513 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
514 subheap->size - subheap->headerSize );
516 return TRUE;
519 /***********************************************************************
520 * HEAP_CreateSubHeap
522 * Create a sub-heap of the given size.
523 * If heap == NULL, creates a main heap.
525 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
526 DWORD commitSize, DWORD totalSize )
528 LPVOID address;
530 /* Round-up sizes on a 64K boundary */
532 if (flags & HEAP_WINE_SEGPTR)
534 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
536 else
538 totalSize = (totalSize + 0xffff) & 0xffff0000;
539 commitSize = (commitSize + 0xffff) & 0xffff0000;
540 if (!commitSize) commitSize = 0x10000;
541 if (totalSize < commitSize) totalSize = commitSize;
544 /* Allocate the memory block */
546 if (!(address = VirtualAlloc( NULL, totalSize,
547 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
549 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
550 totalSize );
551 return NULL;
554 /* Initialize subheap */
556 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
557 address, flags, commitSize, totalSize ))
559 VirtualFree( address, 0, MEM_RELEASE );
560 return NULL;
563 return (SUBHEAP *)address;
567 /***********************************************************************
568 * HEAP_FindFreeBlock
570 * Find a free block at least as large as the requested size, and make sure
571 * the requested size is committed.
573 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
574 SUBHEAP **ppSubHeap )
576 SUBHEAP *subheap;
577 ARENA_FREE *pArena;
578 FREE_LIST_ENTRY *pEntry = heap->freeList;
580 /* Find a suitable free list, and in it find a block large enough */
582 while (pEntry->size < size) pEntry++;
583 pArena = pEntry->arena.next;
584 while (pArena != &heap->freeList[0].arena)
586 if (pArena->size > size)
588 subheap = HEAP_FindSubHeap( heap, pArena );
589 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
590 + size + HEAP_MIN_BLOCK_SIZE))
591 return NULL;
592 *ppSubHeap = subheap;
593 return pArena;
596 pArena = pArena->next;
599 /* If no block was found, attempt to grow the heap */
601 if (!(heap->flags & HEAP_GROWABLE))
603 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
604 (DWORD)heap, size );
605 return NULL;
607 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
608 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
609 MAX( HEAP_DEF_SIZE, size ) )))
610 return NULL;
612 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
613 (DWORD)subheap, size, (DWORD)heap );
615 *ppSubHeap = subheap;
616 return (ARENA_FREE *)(subheap + 1);
620 /***********************************************************************
621 * HEAP_IsValidArenaPtr
623 * Check that the pointer is inside the range possible for arenas.
625 static BOOL32 HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
627 int i;
628 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
629 if (!subheap) return FALSE;
630 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
631 if (subheap != &heap->subheap) return FALSE;
632 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
633 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
634 return FALSE;
638 /***********************************************************************
639 * HEAP_ValidateFreeArena
641 static BOOL32 HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
643 char *heapEnd = (char *)subheap + subheap->size;
645 /* Check magic number */
646 if (pArena->magic != ARENA_FREE_MAGIC)
648 WARN(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
649 (DWORD)subheap->heap, (DWORD)pArena );
650 return FALSE;
652 /* Check size flags */
653 if (!(pArena->size & ARENA_FLAG_FREE) ||
654 (pArena->size & ARENA_FLAG_PREV_FREE))
656 WARN(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
657 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
659 /* Check arena size */
660 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
662 WARN(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
663 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
664 return FALSE;
666 /* Check that next pointer is valid */
667 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
669 WARN(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
670 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
671 return FALSE;
673 /* Check that next arena is free */
674 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
675 (pArena->next->magic != ARENA_FREE_MAGIC))
677 WARN(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
678 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
679 return FALSE;
681 /* Check that prev pointer is valid */
682 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
684 WARN(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
685 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
686 return FALSE;
688 /* Check that prev arena is free */
689 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
690 (pArena->prev->magic != ARENA_FREE_MAGIC))
692 WARN(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
693 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
694 return FALSE;
696 /* Check that next block has PREV_FREE flag */
697 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
699 if (!(*(DWORD *)((char *)(pArena + 1) +
700 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
702 WARN(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
703 (DWORD)subheap->heap, (DWORD)pArena );
704 return FALSE;
706 /* Check next block back pointer */
707 if (*((ARENA_FREE **)((char *)(pArena + 1) +
708 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
710 WARN(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
711 (DWORD)subheap->heap, (DWORD)pArena,
712 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
713 return FALSE;
716 return TRUE;
720 /***********************************************************************
721 * HEAP_ValidateInUseArena
723 static BOOL32 HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
725 char *heapEnd = (char *)subheap + subheap->size;
727 /* Check magic number */
728 if (pArena->magic != ARENA_INUSE_MAGIC)
730 WARN(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
731 (DWORD)subheap->heap, (DWORD)pArena );
732 return FALSE;
734 /* Check size flags */
735 if (pArena->size & ARENA_FLAG_FREE)
737 WARN(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
738 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
740 /* Check arena size */
741 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
743 WARN(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
744 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
745 return FALSE;
747 /* Check next arena PREV_FREE flag */
748 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
749 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
751 WARN(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
752 (DWORD)subheap->heap, (DWORD)pArena );
753 return FALSE;
755 /* Check prev free arena */
756 if (pArena->size & ARENA_FLAG_PREV_FREE)
758 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
759 /* Check prev pointer */
760 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
762 WARN(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
763 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
764 return FALSE;
766 /* Check that prev arena is free */
767 if (!(pPrev->size & ARENA_FLAG_FREE) ||
768 (pPrev->magic != ARENA_FREE_MAGIC))
770 WARN(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
771 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
772 return FALSE;
774 /* Check that prev arena is really the previous block */
775 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
777 WARN(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
778 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
779 return FALSE;
782 return TRUE;
786 /***********************************************************************
787 * HEAP_IsInsideHeap
788 * Checks whether the pointer points to a block inside a given heap.
790 * NOTES
791 * Should this return BOOL32?
793 * RETURNS
794 * !0: Success
795 * 0: Failure
797 int HEAP_IsInsideHeap(
798 HANDLE32 heap, /* [in] Heap */
799 DWORD flags, /* [in] Flags */
800 LPCVOID ptr /* [in] Pointer */
802 HEAP *heapPtr = HEAP_GetPtr( heap );
803 SUBHEAP *subheap;
804 int ret;
806 /* Validate the parameters */
808 if (!heapPtr) return 0;
809 flags |= heapPtr->flags;
810 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
811 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
812 (((char *)ptr >= (char *)subheap + subheap->headerSize
813 + sizeof(ARENA_INUSE))));
814 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
815 return ret;
819 /***********************************************************************
820 * HEAP_GetSegptr
822 * Transform a linear pointer into a SEGPTR. The pointer must have been
823 * allocated from a HEAP_WINE_SEGPTR heap.
825 SEGPTR HEAP_GetSegptr( HANDLE32 heap, DWORD flags, LPCVOID ptr )
827 HEAP *heapPtr = HEAP_GetPtr( heap );
828 SUBHEAP *subheap;
829 SEGPTR ret;
831 /* Validate the parameters */
833 if (!heapPtr) return 0;
834 flags |= heapPtr->flags;
835 if (!(flags & HEAP_WINE_SEGPTR))
837 WARN(heap, "Heap %08x is not a SEGPTR heap\n",
838 heap );
839 return 0;
841 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
843 /* Get the subheap */
845 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
847 WARN(heap, "%p is not inside heap %08x\n",
848 ptr, heap );
849 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
850 return 0;
853 /* Build the SEGPTR */
855 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
856 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
857 return ret;
861 /***********************************************************************
862 * HeapCreate (KERNEL32.336)
863 * RETURNS
864 * Handle of heap: Success
865 * NULL: Failure
867 HANDLE32 WINAPI HeapCreate(
868 DWORD flags, /* [in] Heap allocation flag */
869 DWORD initialSize, /* [in] Initial heap size */
870 DWORD maxSize /* [in] Maximum heap size */
872 SUBHEAP *subheap;
874 /* Allocate the heap block */
876 if (!maxSize)
878 maxSize = HEAP_DEF_SIZE;
879 flags |= HEAP_GROWABLE;
881 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
883 SetLastError( ERROR_OUTOFMEMORY );
884 return 0;
887 return (HANDLE32)subheap;
890 /***********************************************************************
891 * HeapDestroy (KERNEL32.337)
892 * RETURNS
893 * TRUE: Success
894 * FALSE: Failure
896 BOOL32 WINAPI HeapDestroy(
897 HANDLE32 heap /* [in] Handle of heap */
899 HEAP *heapPtr = HEAP_GetPtr( heap );
900 SUBHEAP *subheap;
902 TRACE(heap, "%08x\n", heap );
903 if (!heapPtr) return FALSE;
905 DeleteCriticalSection( &heapPtr->critSection );
906 subheap = &heapPtr->subheap;
907 while (subheap)
909 SUBHEAP *next = subheap->next;
910 if (subheap->selector) FreeSelector( subheap->selector );
911 VirtualFree( subheap, 0, MEM_RELEASE );
912 subheap = next;
914 return TRUE;
918 /***********************************************************************
919 * HeapAlloc (KERNEL32.334)
920 * RETURNS
921 * Pointer to allocated memory block
922 * NULL: Failure
924 LPVOID WINAPI HeapAlloc(
925 HANDLE32 heap, /* [in] Handle of private heap block */
926 DWORD flags, /* [in] Heap allocation control flags */
927 DWORD size /* [in] Number of bytes to allocate */
929 ARENA_FREE *pArena;
930 ARENA_INUSE *pInUse;
931 SUBHEAP *subheap;
932 HEAP *heapPtr = HEAP_GetPtr( heap );
934 /* Validate the parameters */
936 if (!heapPtr) return NULL;
937 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
938 flags |= heapPtr->flags;
939 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
940 size = (size + 3) & ~3;
941 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
943 /* Locate a suitable free block */
945 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
947 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
948 heap, flags, size );
949 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
950 SetLastError( ERROR_COMMITMENT_LIMIT );
951 return NULL;
954 /* Remove the arena from the free list */
956 pArena->next->prev = pArena->prev;
957 pArena->prev->next = pArena->next;
959 /* Build the in-use arena */
961 pInUse = (ARENA_INUSE *)pArena;
962 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
963 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
964 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
965 pInUse->threadId = GetCurrentTask();
966 pInUse->magic = ARENA_INUSE_MAGIC;
968 /* Shrink the block */
970 HEAP_ShrinkBlock( subheap, pInUse, size );
972 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
973 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
975 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
977 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
978 heap, flags, size, (DWORD)(pInUse + 1) );
979 return (LPVOID)(pInUse + 1);
983 /***********************************************************************
984 * HeapFree (KERNEL32.338)
985 * RETURNS
986 * TRUE: Success
987 * FALSE: Failure
989 BOOL32 WINAPI HeapFree(
990 HANDLE32 heap, /* [in] Handle of heap */
991 DWORD flags, /* [in] Heap freeing flags */
992 LPVOID ptr /* [in] Address of memory to free */
994 ARENA_INUSE *pInUse;
995 SUBHEAP *subheap;
996 HEAP *heapPtr = HEAP_GetPtr( heap );
998 /* Validate the parameters */
1000 if (!heapPtr) return FALSE;
1001 flags &= HEAP_NO_SERIALIZE;
1002 flags |= heapPtr->flags;
1003 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1004 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1006 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1007 SetLastError( ERROR_INVALID_PARAMETER );
1008 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1009 heap, flags, (DWORD)ptr );
1010 return FALSE;
1013 /* Turn the block into a free block */
1015 pInUse = (ARENA_INUSE *)ptr - 1;
1016 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1017 HEAP_MakeInUseBlockFree( subheap, pInUse );
1019 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1020 /* SetLastError( 0 ); */
1022 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1023 heap, flags, (DWORD)ptr );
1024 return TRUE;
1028 /***********************************************************************
1029 * HeapReAlloc (KERNEL32.340)
1030 * RETURNS
1031 * Pointer to reallocated memory block
1032 * NULL: Failure
1034 LPVOID WINAPI HeapReAlloc(
1035 HANDLE32 heap, /* [in] Handle of heap block */
1036 DWORD flags, /* [in] Heap reallocation flags */
1037 LPVOID ptr, /* [in] Address of memory to reallocate */
1038 DWORD size /* [in] Number of bytes to reallocate */
1040 ARENA_INUSE *pArena;
1041 DWORD oldSize;
1042 HEAP *heapPtr;
1043 SUBHEAP *subheap;
1045 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1046 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1048 /* Validate the parameters */
1050 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1051 HEAP_REALLOC_IN_PLACE_ONLY;
1052 flags |= heapPtr->flags;
1053 size = (size + 3) & ~3;
1054 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1056 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1057 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1059 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1060 SetLastError( ERROR_INVALID_PARAMETER );
1061 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1062 heap, flags, (DWORD)ptr, size );
1063 return NULL;
1066 /* Check if we need to grow the block */
1068 pArena = (ARENA_INUSE *)ptr - 1;
1069 pArena->threadId = GetCurrentTask();
1070 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1071 oldSize = (pArena->size & ARENA_SIZE_MASK);
1072 if (size > oldSize)
1074 char *pNext = (char *)(pArena + 1) + oldSize;
1075 if ((pNext < (char *)subheap + subheap->size) &&
1076 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1077 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1079 /* The next block is free and large enough */
1080 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1081 pFree->next->prev = pFree->prev;
1082 pFree->prev->next = pFree->next;
1083 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1084 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1085 + size + HEAP_MIN_BLOCK_SIZE))
1087 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1088 SetLastError( ERROR_OUTOFMEMORY );
1089 return NULL;
1091 HEAP_ShrinkBlock( subheap, pArena, size );
1093 else /* Do it the hard way */
1095 ARENA_FREE *pNew;
1096 ARENA_INUSE *pInUse;
1097 SUBHEAP *newsubheap;
1099 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1100 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1102 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1103 SetLastError( ERROR_OUTOFMEMORY );
1104 return NULL;
1107 /* Build the in-use arena */
1109 pNew->next->prev = pNew->prev;
1110 pNew->prev->next = pNew->next;
1111 pInUse = (ARENA_INUSE *)pNew;
1112 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1113 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1114 pInUse->threadId = GetCurrentTask();
1115 pInUse->magic = ARENA_INUSE_MAGIC;
1116 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1117 memcpy( pInUse + 1, pArena + 1, oldSize );
1119 /* Free the previous block */
1121 HEAP_MakeInUseBlockFree( subheap, pArena );
1122 subheap = newsubheap;
1123 pArena = pInUse;
1126 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1128 /* Clear the extra bytes if needed */
1130 if (size > oldSize)
1132 if (flags & HEAP_ZERO_MEMORY)
1133 memset( (char *)(pArena + 1) + oldSize, 0,
1134 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1135 else if (TRACE_ON(heap))
1136 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1137 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1140 /* Return the new arena */
1142 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1143 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1145 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1146 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1147 return (LPVOID)(pArena + 1);
1151 /***********************************************************************
1152 * HeapCompact (KERNEL32.335)
1154 DWORD WINAPI HeapCompact( HANDLE32 heap, DWORD flags )
1156 return 0;
1160 /***********************************************************************
1161 * HeapLock (KERNEL32.339)
1162 * Attempts to acquire the critical section object for a specified heap.
1164 * RETURNS
1165 * TRUE: Success
1166 * FALSE: Failure
1168 BOOL32 WINAPI HeapLock(
1169 HANDLE32 heap /* [in] Handle of heap to lock for exclusive access */
1171 HEAP *heapPtr = HEAP_GetPtr( heap );
1172 if (!heapPtr) return FALSE;
1173 EnterCriticalSection( &heapPtr->critSection );
1174 return TRUE;
1178 /***********************************************************************
1179 * HeapUnlock (KERNEL32.342)
1180 * Releases ownership of the critical section object.
1182 * RETURNS
1183 * TRUE: Success
1184 * FALSE: Failure
1186 BOOL32 WINAPI HeapUnlock(
1187 HANDLE32 heap /* [in] Handle to the heap to unlock */
1189 HEAP *heapPtr = HEAP_GetPtr( heap );
1190 if (!heapPtr) return FALSE;
1191 LeaveCriticalSection( &heapPtr->critSection );
1192 return TRUE;
1196 /***********************************************************************
1197 * HeapSize (KERNEL32.341)
1198 * RETURNS
1199 * Size in bytes of allocated memory
1200 * 0: Failure
1202 DWORD WINAPI HeapSize(
1203 HANDLE32 heap, /* [in] Handle of heap */
1204 DWORD flags, /* [in] Heap size control flags */
1205 LPVOID ptr /* [in] Address of memory to return size for */
1207 DWORD ret;
1208 HEAP *heapPtr = HEAP_GetPtr( heap );
1210 if (!heapPtr) return FALSE;
1211 flags &= HEAP_NO_SERIALIZE;
1212 flags |= heapPtr->flags;
1213 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1214 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1216 SetLastError( ERROR_INVALID_PARAMETER );
1217 ret = 0xffffffff;
1219 else
1221 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1222 ret = pArena->size & ARENA_SIZE_MASK;
1224 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1226 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1227 heap, flags, (DWORD)ptr, ret );
1228 return ret;
1232 /***********************************************************************
1233 * HeapValidate (KERNEL32.343)
1234 * Validates a specified heap.
1236 * NOTES
1237 * Flags is ignored.
1239 * RETURNS
1240 * TRUE: Success
1241 * FALSE: Failure
1243 BOOL32 WINAPI HeapValidate(
1244 HANDLE32 heap, /* [in] Handle to the heap */
1245 DWORD flags, /* [in] Bit flags that control access during operation */
1246 LPCVOID block /* [in] Optional pointer to memory block to validate */
1248 SUBHEAP *subheap;
1249 HEAP *heapPtr = (HEAP *)(heap);
1251 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1253 WARN(heap, "Invalid heap %08x!\n", heap );
1254 return FALSE;
1257 if (block)
1259 /* Only check this single memory block */
1260 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1261 ((char *)block < (char *)subheap + subheap->headerSize
1262 + sizeof(ARENA_INUSE)))
1264 WARN(heap, "Heap %08lx: block %08lx is not inside heap\n",
1265 (DWORD)heap, (DWORD)block );
1266 return FALSE;
1268 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1271 subheap = &heapPtr->subheap;
1272 while (subheap)
1274 char *ptr = (char *)subheap + subheap->headerSize;
1275 while (ptr < (char *)subheap + subheap->size)
1277 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1279 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1280 return FALSE;
1281 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1283 else
1285 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1286 return FALSE;
1287 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1290 subheap = subheap->next;
1292 return TRUE;
1296 /***********************************************************************
1297 * HeapWalk (KERNEL32.344)
1298 * Enumerates the memory blocks in a specified heap.
1300 * RETURNS
1301 * TRUE: Success
1302 * FALSE: Failure
1304 BOOL32 WINAPI HeapWalk(
1305 HANDLE32 heap, /* [in] Handle to heap to enumerate */
1306 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1308 FIXME(heap, "(%08x): stub.\n", heap );
1309 return FALSE;
1313 /***********************************************************************
1314 * HEAP_xalloc
1316 * Same as HeapAlloc(), but die on failure.
1318 LPVOID HEAP_xalloc( HANDLE32 heap, DWORD flags, DWORD size )
1320 LPVOID p = HeapAlloc( heap, flags, size );
1321 if (!p)
1323 MSG("Virtual memory exhausted.\n" );
1324 exit(1);
1326 return p;
1330 /***********************************************************************
1331 * HEAP_strdupA
1333 LPSTR HEAP_strdupA( HANDLE32 heap, DWORD flags, LPCSTR str )
1335 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1336 strcpy( p, str );
1337 return p;
1341 /***********************************************************************
1342 * HEAP_strdupW
1344 LPWSTR HEAP_strdupW( HANDLE32 heap, DWORD flags, LPCWSTR str )
1346 INT32 len = lstrlen32W(str) + 1;
1347 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1348 lstrcpy32W( p, str );
1349 return p;
1353 /***********************************************************************
1354 * HEAP_strdupAtoW
1356 LPWSTR HEAP_strdupAtoW( HANDLE32 heap, DWORD flags, LPCSTR str )
1358 LPWSTR ret;
1360 if (!str) return NULL;
1361 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1362 lstrcpyAtoW( ret, str );
1363 return ret;
1367 /***********************************************************************
1368 * HEAP_strdupWtoA
1370 LPSTR HEAP_strdupWtoA( HANDLE32 heap, DWORD flags, LPCWSTR str )
1372 LPSTR ret;
1374 if (!str) return NULL;
1375 ret = HEAP_xalloc( heap, flags, lstrlen32W(str) + 1 );
1376 lstrcpyWtoA( ret, str );
1377 return ret;
1382 /***********************************************************************
1383 * 32-bit local heap functions (Win95; undocumented)
1386 #define HTABLE_SIZE 0x10000
1387 #define HTABLE_PAGESIZE 0x1000
1388 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1390 #pragma pack(1)
1391 typedef struct _LOCAL32HEADER
1393 WORD freeListFirst[HTABLE_NPAGES];
1394 WORD freeListSize[HTABLE_NPAGES];
1395 WORD freeListLast[HTABLE_NPAGES];
1397 DWORD selectorTableOffset;
1398 WORD selectorTableSize;
1399 WORD selectorDelta;
1401 DWORD segment;
1402 LPBYTE base;
1404 DWORD limit;
1405 DWORD flags;
1407 DWORD magic;
1408 HANDLE32 heap;
1410 } LOCAL32HEADER;
1411 #pragma pack(4)
1413 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1415 /***********************************************************************
1416 * Local32Init (KERNEL.208)
1418 HANDLE32 WINAPI Local32Init( WORD segment, DWORD tableSize,
1419 DWORD heapSize, DWORD flags )
1421 DWORD totSize, segSize = 0;
1422 LPBYTE base;
1423 LOCAL32HEADER *header;
1424 HEAP *heap;
1425 WORD *selectorTable;
1426 WORD selectorEven, selectorOdd;
1427 int i, nrBlocks;
1429 /* Determine new heap size */
1431 if ( segment )
1432 if ( (segSize = GetSelectorLimit( segment )) == 0 )
1433 return 0;
1434 else
1435 segSize++;
1437 if ( heapSize == -1L )
1438 heapSize = 1024L*1024L; /* FIXME */
1440 heapSize = (heapSize + 0xffff) & 0xffff0000;
1441 segSize = (segSize + 0x0fff) & 0xfffff000;
1442 totSize = segSize + HTABLE_SIZE + heapSize;
1445 /* Allocate memory and initialize heap */
1447 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1448 return 0;
1450 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1451 MEM_COMMIT, PAGE_READWRITE ) )
1453 VirtualFree( base, 0, MEM_RELEASE );
1454 return 0;
1457 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1458 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1460 VirtualFree( base, 0, MEM_RELEASE );
1461 return 0;
1465 /* Set up header and handle table */
1467 header = (LOCAL32HEADER *)(base + segSize);
1468 header->base = base;
1469 header->limit = HTABLE_PAGESIZE-1;
1470 header->flags = 0;
1471 header->magic = LOCAL32_MAGIC;
1472 header->heap = (HANDLE32)heap;
1474 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1475 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1476 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1478 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1479 *(DWORD *)((LPBYTE)header + i) = i+4;
1481 header->freeListFirst[1] = 0xffff;
1484 /* Set up selector table */
1486 nrBlocks = (totSize + 0x7fff) >> 15;
1487 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1488 selectorEven = SELECTOR_AllocBlock( base, totSize,
1489 SEGMENT_DATA, FALSE, FALSE );
1490 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1491 SEGMENT_DATA, FALSE, FALSE );
1493 if ( !selectorTable || !selectorEven || !selectorOdd )
1495 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1496 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1497 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1498 HeapDestroy( header->heap );
1499 VirtualFree( base, 0, MEM_RELEASE );
1500 return 0;
1503 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1504 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1505 header->selectorDelta = selectorEven - selectorOdd;
1506 header->segment = segment? segment : selectorEven;
1508 for (i = 0; i < nrBlocks; i++)
1509 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1510 : selectorEven + ((i >> 1) << __AHSHIFT);
1512 /* Move old segment */
1514 if ( segment )
1516 /* FIXME: This is somewhat ugly and relies on implementation
1517 details about 16-bit global memory handles ... */
1519 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1520 memcpy( base, oldBase, segSize );
1521 GLOBAL_MoveBlock( segment, base, totSize );
1522 HeapFree( SystemHeap, 0, oldBase );
1525 return (HANDLE32)header;
1528 /***********************************************************************
1529 * Local32_SearchHandle
1531 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1533 LPDWORD handle;
1535 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1536 handle < (LPDWORD)((LPBYTE)header + header->limit);
1537 handle++)
1539 if (*handle == addr)
1540 return handle;
1543 return NULL;
1546 /***********************************************************************
1547 * Local32_ToHandle
1549 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1550 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1552 *handle = NULL;
1553 *ptr = NULL;
1555 switch (type)
1557 case -2: /* 16:16 pointer, no handles */
1558 *ptr = PTR_SEG_TO_LIN( addr );
1559 *handle = (LPDWORD)*ptr;
1560 break;
1562 case -1: /* 32-bit offset, no handles */
1563 *ptr = header->base + addr;
1564 *handle = (LPDWORD)*ptr;
1565 break;
1567 case 0: /* handle */
1568 if ( addr >= sizeof(LOCAL32HEADER)
1569 && addr < header->limit && !(addr & 3)
1570 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1572 *handle = (LPDWORD)((LPBYTE)header + addr);
1573 *ptr = header->base + **handle;
1575 break;
1577 case 1: /* 16:16 pointer */
1578 *ptr = PTR_SEG_TO_LIN( addr );
1579 *handle = Local32_SearchHandle( header, *ptr - header->base );
1580 break;
1582 case 2: /* 32-bit offset */
1583 *ptr = header->base + addr;
1584 *handle = Local32_SearchHandle( header, *ptr - header->base );
1585 break;
1589 /***********************************************************************
1590 * Local32_FromHandle
1592 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1593 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1595 switch (type)
1597 case -2: /* 16:16 pointer */
1598 case 1:
1600 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1601 DWORD offset = (LPBYTE)ptr - header->base;
1602 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1604 break;
1606 case -1: /* 32-bit offset */
1607 case 2:
1608 *addr = ptr - header->base;
1609 break;
1611 case 0: /* handle */
1612 *addr = (LPBYTE)handle - (LPBYTE)header;
1613 break;
1617 /***********************************************************************
1618 * Local32Alloc (KERNEL.209)
1620 DWORD WINAPI Local32Alloc( HANDLE32 heap, DWORD size, INT16 type, DWORD flags )
1622 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1623 LPDWORD handle;
1624 LPBYTE ptr;
1625 DWORD addr;
1627 /* Allocate memory */
1628 ptr = HeapAlloc( header->heap,
1629 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1630 if (!ptr) return 0;
1633 /* Allocate handle if requested */
1634 if (type >= 0)
1636 int page, i;
1638 /* Find first page of handle table with free slots */
1639 for (page = 0; page < HTABLE_NPAGES; page++)
1640 if (header->freeListFirst[page] != 0)
1641 break;
1642 if (page == HTABLE_NPAGES)
1644 WARN( heap, "Out of handles!\n" );
1645 HeapFree( header->heap, 0, ptr );
1646 return 0;
1649 /* If virgin page, initialize it */
1650 if (header->freeListFirst[page] == 0xffff)
1652 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1653 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1655 WARN( heap, "Cannot grow handle table!\n" );
1656 HeapFree( header->heap, 0, ptr );
1657 return 0;
1660 header->limit += HTABLE_PAGESIZE;
1662 header->freeListFirst[page] = 0;
1663 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1664 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1666 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1667 *(DWORD *)((LPBYTE)header + i) = i+4;
1669 if (page < 31)
1670 header->freeListFirst[page+1] = 0xffff;
1673 /* Allocate handle slot from page */
1674 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1675 if (--header->freeListSize[page] == 0)
1676 header->freeListFirst[page] = header->freeListLast[page] = 0;
1677 else
1678 header->freeListFirst[page] = *handle;
1680 /* Store 32-bit offset in handle slot */
1681 *handle = ptr - header->base;
1683 else
1685 handle = (LPDWORD)ptr;
1686 header->flags |= 1;
1690 /* Convert handle to requested output type */
1691 Local32_FromHandle( header, type, &addr, handle, ptr );
1692 return addr;
1695 /***********************************************************************
1696 * Local32ReAlloc (KERNEL.210)
1698 DWORD WINAPI Local32ReAlloc( HANDLE32 heap, DWORD addr, INT16 type,
1699 DWORD size, DWORD flags )
1701 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1702 LPDWORD handle;
1703 LPBYTE ptr;
1705 if (!addr)
1706 return Local32Alloc( heap, size, type, flags );
1708 /* Retrieve handle and pointer */
1709 Local32_ToHandle( header, type, addr, &handle, &ptr );
1710 if (!handle) return FALSE;
1712 /* Reallocate memory block */
1713 ptr = HeapReAlloc( header->heap,
1714 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1715 ptr, size );
1716 if (!ptr) return 0;
1718 /* Modify handle */
1719 if (type >= 0)
1720 *handle = ptr - header->base;
1721 else
1722 handle = (LPDWORD)ptr;
1724 /* Convert handle to requested output type */
1725 Local32_FromHandle( header, type, &addr, handle, ptr );
1726 return addr;
1729 /***********************************************************************
1730 * Local32Free (KERNEL.211)
1732 BOOL32 WINAPI Local32Free( HANDLE32 heap, DWORD addr, INT16 type )
1734 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1735 LPDWORD handle;
1736 LPBYTE ptr;
1738 /* Retrieve handle and pointer */
1739 Local32_ToHandle( header, type, addr, &handle, &ptr );
1740 if (!handle) return FALSE;
1742 /* Free handle if necessary */
1743 if (type >= 0)
1745 int offset = (LPBYTE)handle - (LPBYTE)header;
1746 int page = offset >> 12;
1748 /* Return handle slot to page free list */
1749 if (header->freeListSize[page]++ == 0)
1750 header->freeListFirst[page] = header->freeListLast[page] = offset;
1751 else
1752 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1753 header->freeListLast[page] = *handle;
1755 *handle = 0;
1757 /* Shrink handle table when possible */
1758 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1760 if ( VirtualFree( (LPBYTE)header +
1761 (header->limit & ~(HTABLE_PAGESIZE-1)),
1762 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1763 break;
1765 header->limit -= HTABLE_PAGESIZE;
1766 header->freeListFirst[page] = -1;
1767 page--;
1771 /* Free memory */
1772 return HeapFree( header->heap, 0, ptr );
1775 /***********************************************************************
1776 * Local32Translate (KERNEL.213)
1778 DWORD WINAPI Local32Translate( HANDLE32 heap, DWORD addr, INT16 type1, INT16 type2 )
1780 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1781 LPDWORD handle;
1782 LPBYTE ptr;
1784 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1785 if (!handle) return 0;
1787 Local32_FromHandle( header, type2, &addr, handle, ptr );
1788 return addr;
1791 /***********************************************************************
1792 * Local32Size (KERNEL.214)
1794 DWORD WINAPI Local32Size( HANDLE32 heap, DWORD addr, INT16 type )
1796 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1797 LPDWORD handle;
1798 LPBYTE ptr;
1800 Local32_ToHandle( header, type, addr, &handle, &ptr );
1801 if (!handle) return 0;
1803 return HeapSize( header->heap, 0, ptr );
1806 /***********************************************************************
1807 * Local32ValidHandle (KERNEL.215)
1809 BOOL32 WINAPI Local32ValidHandle( HANDLE32 heap, WORD addr )
1811 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1812 LPDWORD handle;
1813 LPBYTE ptr;
1815 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1816 return handle != NULL;
1819 /***********************************************************************
1820 * Local32GetSegment (KERNEL.229)
1822 WORD WINAPI Local32GetSegment( HANDLE32 heap )
1824 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1825 return header->segment;