Added missing #include "config.h"
[wine/multimedia.git] / memory / heap.c
blobb73d1d05969841d2a4efdc38005f84ddf86138cd
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 ERR(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|HEAP_WINE_CODE16SEG))
457 ? SEGMENT_CODE : SEGMENT_DATA,
458 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
459 if (!selector)
461 ERR(heap, "Could not allocate selector\n" );
462 return FALSE;
466 /* Fill the sub-heap structure */
468 subheap->heap = heap;
469 subheap->selector = selector;
470 subheap->size = totalSize;
471 subheap->commitSize = commitSize;
472 subheap->magic = SUBHEAP_MAGIC;
474 if ( subheap != (SUBHEAP *)heap )
476 /* If this is a secondary subheap, insert it into list */
478 subheap->headerSize = sizeof(SUBHEAP);
479 subheap->next = heap->subheap.next;
480 heap->subheap.next = subheap;
482 else
484 /* If this is a primary subheap, initialize main heap */
486 subheap->headerSize = sizeof(HEAP);
487 subheap->next = NULL;
488 heap->next = NULL;
489 heap->flags = flags;
490 heap->magic = HEAP_MAGIC;
492 /* Build the free lists */
494 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
496 pEntry->size = HEAP_freeListSizes[i];
497 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
498 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
499 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
500 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
501 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
502 pEntry->arena.threadId = 0;
503 pEntry->arena.magic = ARENA_FREE_MAGIC;
506 /* Initialize critical section */
508 InitializeCriticalSection( &heap->critSection );
509 if (!SystemHeap) HEAP_SystemLock = &heap->critSection;
512 /* Create the first free block */
514 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
515 subheap->size - subheap->headerSize );
517 return TRUE;
520 /***********************************************************************
521 * HEAP_CreateSubHeap
523 * Create a sub-heap of the given size.
524 * If heap == NULL, creates a main heap.
526 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
527 DWORD commitSize, DWORD totalSize )
529 LPVOID address;
531 /* Round-up sizes on a 64K boundary */
533 if (flags & HEAP_WINE_SEGPTR)
535 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
537 else
539 totalSize = (totalSize + 0xffff) & 0xffff0000;
540 commitSize = (commitSize + 0xffff) & 0xffff0000;
541 if (!commitSize) commitSize = 0x10000;
542 if (totalSize < commitSize) totalSize = commitSize;
545 /* Allocate the memory block */
547 if (!(address = VirtualAlloc( NULL, totalSize,
548 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
550 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
551 totalSize );
552 return NULL;
555 /* Initialize subheap */
557 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
558 address, flags, commitSize, totalSize ))
560 VirtualFree( address, 0, MEM_RELEASE );
561 return NULL;
564 return (SUBHEAP *)address;
568 /***********************************************************************
569 * HEAP_FindFreeBlock
571 * Find a free block at least as large as the requested size, and make sure
572 * the requested size is committed.
574 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
575 SUBHEAP **ppSubHeap )
577 SUBHEAP *subheap;
578 ARENA_FREE *pArena;
579 FREE_LIST_ENTRY *pEntry = heap->freeList;
581 /* Find a suitable free list, and in it find a block large enough */
583 while (pEntry->size < size) pEntry++;
584 pArena = pEntry->arena.next;
585 while (pArena != &heap->freeList[0].arena)
587 if (pArena->size > size)
589 subheap = HEAP_FindSubHeap( heap, pArena );
590 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
591 + size + HEAP_MIN_BLOCK_SIZE))
592 return NULL;
593 *ppSubHeap = subheap;
594 return pArena;
597 pArena = pArena->next;
600 /* If no block was found, attempt to grow the heap */
602 if (!(heap->flags & HEAP_GROWABLE))
604 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
605 (DWORD)heap, size );
606 return NULL;
608 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
609 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
610 MAX( HEAP_DEF_SIZE, size ) )))
611 return NULL;
613 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
614 (DWORD)subheap, size, (DWORD)heap );
616 *ppSubHeap = subheap;
617 return (ARENA_FREE *)(subheap + 1);
621 /***********************************************************************
622 * HEAP_IsValidArenaPtr
624 * Check that the pointer is inside the range possible for arenas.
626 static BOOL32 HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
628 int i;
629 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
630 if (!subheap) return FALSE;
631 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
632 if (subheap != &heap->subheap) return FALSE;
633 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
634 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
635 return FALSE;
639 /***********************************************************************
640 * HEAP_ValidateFreeArena
642 static BOOL32 HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
644 char *heapEnd = (char *)subheap + subheap->size;
646 /* Check magic number */
647 if (pArena->magic != ARENA_FREE_MAGIC)
649 ERR(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
650 (DWORD)subheap->heap, (DWORD)pArena );
651 return FALSE;
653 /* Check size flags */
654 if (!(pArena->size & ARENA_FLAG_FREE) ||
655 (pArena->size & ARENA_FLAG_PREV_FREE))
657 ERR(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
658 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
660 /* Check arena size */
661 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
663 ERR(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
664 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
665 return FALSE;
667 /* Check that next pointer is valid */
668 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
670 ERR(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
671 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
672 return FALSE;
674 /* Check that next arena is free */
675 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
676 (pArena->next->magic != ARENA_FREE_MAGIC))
678 ERR(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
679 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
680 return FALSE;
682 /* Check that prev pointer is valid */
683 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
685 ERR(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
686 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
687 return FALSE;
689 /* Check that prev arena is free */
690 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
691 (pArena->prev->magic != ARENA_FREE_MAGIC))
693 ERR(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
694 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
695 return FALSE;
697 /* Check that next block has PREV_FREE flag */
698 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
700 if (!(*(DWORD *)((char *)(pArena + 1) +
701 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
703 ERR(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
704 (DWORD)subheap->heap, (DWORD)pArena );
705 return FALSE;
707 /* Check next block back pointer */
708 if (*((ARENA_FREE **)((char *)(pArena + 1) +
709 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
711 ERR(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
712 (DWORD)subheap->heap, (DWORD)pArena,
713 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
714 return FALSE;
717 return TRUE;
721 /***********************************************************************
722 * HEAP_ValidateInUseArena
724 static BOOL32 HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
726 char *heapEnd = (char *)subheap + subheap->size;
728 /* Check magic number */
729 if (pArena->magic != ARENA_INUSE_MAGIC)
731 ERR(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
732 (DWORD)subheap->heap, (DWORD)pArena );
733 return FALSE;
735 /* Check size flags */
736 if (pArena->size & ARENA_FLAG_FREE)
738 ERR(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
739 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
741 /* Check arena size */
742 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
744 ERR(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
745 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
746 return FALSE;
748 /* Check next arena PREV_FREE flag */
749 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
750 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
752 ERR(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
753 (DWORD)subheap->heap, (DWORD)pArena );
754 return FALSE;
756 /* Check prev free arena */
757 if (pArena->size & ARENA_FLAG_PREV_FREE)
759 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
760 /* Check prev pointer */
761 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
763 ERR(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
764 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
765 return FALSE;
767 /* Check that prev arena is free */
768 if (!(pPrev->size & ARENA_FLAG_FREE) ||
769 (pPrev->magic != ARENA_FREE_MAGIC))
771 ERR(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
772 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
773 return FALSE;
775 /* Check that prev arena is really the previous block */
776 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
778 ERR(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
779 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
780 return FALSE;
783 return TRUE;
787 /***********************************************************************
788 * HEAP_IsInsideHeap
789 * Checks whether the pointer points to a block inside a given heap.
791 * NOTES
792 * Should this return BOOL32?
794 * RETURNS
795 * !0: Success
796 * 0: Failure
798 int HEAP_IsInsideHeap(
799 HANDLE32 heap, /* [in] Heap */
800 DWORD flags, /* [in] Flags */
801 LPCVOID ptr /* [in] Pointer */
803 HEAP *heapPtr = HEAP_GetPtr( heap );
804 SUBHEAP *subheap;
805 int ret;
807 /* Validate the parameters */
809 if (!heapPtr) return 0;
810 flags |= heapPtr->flags;
811 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
812 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
813 (((char *)ptr >= (char *)subheap + subheap->headerSize
814 + sizeof(ARENA_INUSE))));
815 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
816 return ret;
820 /***********************************************************************
821 * HEAP_GetSegptr
823 * Transform a linear pointer into a SEGPTR. The pointer must have been
824 * allocated from a HEAP_WINE_SEGPTR heap.
826 SEGPTR HEAP_GetSegptr( HANDLE32 heap, DWORD flags, LPCVOID ptr )
828 HEAP *heapPtr = HEAP_GetPtr( heap );
829 SUBHEAP *subheap;
830 SEGPTR ret;
832 /* Validate the parameters */
834 if (!heapPtr) return 0;
835 flags |= heapPtr->flags;
836 if (!(flags & HEAP_WINE_SEGPTR))
838 ERR(heap, "Heap %08x is not a SEGPTR heap\n",
839 heap );
840 return 0;
842 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
844 /* Get the subheap */
846 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
848 ERR(heap, "%p is not inside heap %08x\n",
849 ptr, heap );
850 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
851 return 0;
854 /* Build the SEGPTR */
856 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
857 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
858 return ret;
862 /***********************************************************************
863 * HeapCreate (KERNEL32.336)
864 * RETURNS
865 * Handle of heap: Success
866 * NULL: Failure
868 HANDLE32 WINAPI HeapCreate(
869 DWORD flags, /* [in] Heap allocation flag */
870 DWORD initialSize, /* [in] Initial heap size */
871 DWORD maxSize /* [in] Maximum heap size */
873 SUBHEAP *subheap;
875 /* Allocate the heap block */
877 if (!maxSize)
879 maxSize = HEAP_DEF_SIZE;
880 flags |= HEAP_GROWABLE;
882 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
884 SetLastError( ERROR_OUTOFMEMORY );
885 return 0;
888 return (HANDLE32)subheap;
891 /***********************************************************************
892 * HeapDestroy (KERNEL32.337)
893 * RETURNS
894 * TRUE: Success
895 * FALSE: Failure
897 BOOL32 WINAPI HeapDestroy(
898 HANDLE32 heap /* [in] Handle of heap */
900 HEAP *heapPtr = HEAP_GetPtr( heap );
901 SUBHEAP *subheap;
903 TRACE(heap, "%08x\n", heap );
904 if (!heapPtr) return FALSE;
906 DeleteCriticalSection( &heapPtr->critSection );
907 subheap = &heapPtr->subheap;
908 while (subheap)
910 SUBHEAP *next = subheap->next;
911 if (subheap->selector) FreeSelector( subheap->selector );
912 VirtualFree( subheap, 0, MEM_RELEASE );
913 subheap = next;
915 return TRUE;
919 /***********************************************************************
920 * HeapAlloc (KERNEL32.334)
921 * RETURNS
922 * Pointer to allocated memory block
923 * NULL: Failure
925 LPVOID WINAPI HeapAlloc(
926 HANDLE32 heap, /* [in] Handle of private heap block */
927 DWORD flags, /* [in] Heap allocation control flags */
928 DWORD size /* [in] Number of bytes to allocate */
930 ARENA_FREE *pArena;
931 ARENA_INUSE *pInUse;
932 SUBHEAP *subheap;
933 HEAP *heapPtr = HEAP_GetPtr( heap );
935 /* Validate the parameters */
937 if (!heapPtr) return NULL;
938 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
939 flags |= heapPtr->flags;
940 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
941 size = (size + 3) & ~3;
942 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
944 /* Locate a suitable free block */
946 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
948 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
949 heap, flags, size );
950 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
951 SetLastError( ERROR_COMMITMENT_LIMIT );
952 return NULL;
955 /* Remove the arena from the free list */
957 pArena->next->prev = pArena->prev;
958 pArena->prev->next = pArena->next;
960 /* Build the in-use arena */
962 pInUse = (ARENA_INUSE *)pArena;
963 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
964 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
965 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
966 pInUse->threadId = GetCurrentTask();
967 pInUse->magic = ARENA_INUSE_MAGIC;
969 /* Shrink the block */
971 HEAP_ShrinkBlock( subheap, pInUse, size );
973 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
974 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
976 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
978 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
979 heap, flags, size, (DWORD)(pInUse + 1) );
980 return (LPVOID)(pInUse + 1);
984 /***********************************************************************
985 * HeapFree (KERNEL32.338)
986 * RETURNS
987 * TRUE: Success
988 * FALSE: Failure
990 BOOL32 WINAPI HeapFree(
991 HANDLE32 heap, /* [in] Handle of heap */
992 DWORD flags, /* [in] Heap freeing flags */
993 LPVOID ptr /* [in] Address of memory to free */
995 ARENA_INUSE *pInUse;
996 SUBHEAP *subheap;
997 HEAP *heapPtr = HEAP_GetPtr( heap );
999 /* Validate the parameters */
1001 if (!heapPtr) return FALSE;
1002 flags &= HEAP_NO_SERIALIZE;
1003 flags |= heapPtr->flags;
1004 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1005 if (!ptr)
1007 WARN(heap, "(%08x,%08lx,%08lx): asked to free NULL\n",
1008 heap, flags, (DWORD)ptr );
1010 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1012 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1013 SetLastError( ERROR_INVALID_PARAMETER );
1014 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1015 heap, flags, (DWORD)ptr );
1016 return FALSE;
1019 /* Turn the block into a free block */
1021 pInUse = (ARENA_INUSE *)ptr - 1;
1022 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1023 HEAP_MakeInUseBlockFree( subheap, pInUse );
1025 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1026 /* SetLastError( 0 ); */
1028 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1029 heap, flags, (DWORD)ptr );
1030 return TRUE;
1034 /***********************************************************************
1035 * HeapReAlloc (KERNEL32.340)
1036 * RETURNS
1037 * Pointer to reallocated memory block
1038 * NULL: Failure
1040 LPVOID WINAPI HeapReAlloc(
1041 HANDLE32 heap, /* [in] Handle of heap block */
1042 DWORD flags, /* [in] Heap reallocation flags */
1043 LPVOID ptr, /* [in] Address of memory to reallocate */
1044 DWORD size /* [in] Number of bytes to reallocate */
1046 ARENA_INUSE *pArena;
1047 DWORD oldSize;
1048 HEAP *heapPtr;
1049 SUBHEAP *subheap;
1051 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1052 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1054 /* Validate the parameters */
1056 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1057 HEAP_REALLOC_IN_PLACE_ONLY;
1058 flags |= heapPtr->flags;
1059 size = (size + 3) & ~3;
1060 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1062 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1063 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1065 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1066 SetLastError( ERROR_INVALID_PARAMETER );
1067 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1068 heap, flags, (DWORD)ptr, size );
1069 return NULL;
1072 /* Check if we need to grow the block */
1074 pArena = (ARENA_INUSE *)ptr - 1;
1075 pArena->threadId = GetCurrentTask();
1076 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1077 oldSize = (pArena->size & ARENA_SIZE_MASK);
1078 if (size > oldSize)
1080 char *pNext = (char *)(pArena + 1) + oldSize;
1081 if ((pNext < (char *)subheap + subheap->size) &&
1082 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1083 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1085 /* The next block is free and large enough */
1086 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1087 pFree->next->prev = pFree->prev;
1088 pFree->prev->next = pFree->next;
1089 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1090 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1091 + size + HEAP_MIN_BLOCK_SIZE))
1093 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1094 SetLastError( ERROR_OUTOFMEMORY );
1095 return NULL;
1097 HEAP_ShrinkBlock( subheap, pArena, size );
1099 else /* Do it the hard way */
1101 ARENA_FREE *pNew;
1102 ARENA_INUSE *pInUse;
1103 SUBHEAP *newsubheap;
1105 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1106 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1108 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1109 SetLastError( ERROR_OUTOFMEMORY );
1110 return NULL;
1113 /* Build the in-use arena */
1115 pNew->next->prev = pNew->prev;
1116 pNew->prev->next = pNew->next;
1117 pInUse = (ARENA_INUSE *)pNew;
1118 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1119 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1120 pInUse->threadId = GetCurrentTask();
1121 pInUse->magic = ARENA_INUSE_MAGIC;
1122 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1123 memcpy( pInUse + 1, pArena + 1, oldSize );
1125 /* Free the previous block */
1127 HEAP_MakeInUseBlockFree( subheap, pArena );
1128 subheap = newsubheap;
1129 pArena = pInUse;
1132 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1134 /* Clear the extra bytes if needed */
1136 if (size > oldSize)
1138 if (flags & HEAP_ZERO_MEMORY)
1139 memset( (char *)(pArena + 1) + oldSize, 0,
1140 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1141 else if (TRACE_ON(heap))
1142 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1143 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1146 /* Return the new arena */
1148 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1149 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1151 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1152 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1153 return (LPVOID)(pArena + 1);
1157 /***********************************************************************
1158 * HeapCompact (KERNEL32.335)
1160 DWORD WINAPI HeapCompact( HANDLE32 heap, DWORD flags )
1162 return 0;
1166 /***********************************************************************
1167 * HeapLock (KERNEL32.339)
1168 * Attempts to acquire the critical section object for a specified heap.
1170 * RETURNS
1171 * TRUE: Success
1172 * FALSE: Failure
1174 BOOL32 WINAPI HeapLock(
1175 HANDLE32 heap /* [in] Handle of heap to lock for exclusive access */
1177 HEAP *heapPtr = HEAP_GetPtr( heap );
1178 if (!heapPtr) return FALSE;
1179 EnterCriticalSection( &heapPtr->critSection );
1180 return TRUE;
1184 /***********************************************************************
1185 * HeapUnlock (KERNEL32.342)
1186 * Releases ownership of the critical section object.
1188 * RETURNS
1189 * TRUE: Success
1190 * FALSE: Failure
1192 BOOL32 WINAPI HeapUnlock(
1193 HANDLE32 heap /* [in] Handle to the heap to unlock */
1195 HEAP *heapPtr = HEAP_GetPtr( heap );
1196 if (!heapPtr) return FALSE;
1197 LeaveCriticalSection( &heapPtr->critSection );
1198 return TRUE;
1202 /***********************************************************************
1203 * HeapSize (KERNEL32.341)
1204 * RETURNS
1205 * Size in bytes of allocated memory
1206 * 0: Failure
1208 DWORD WINAPI HeapSize(
1209 HANDLE32 heap, /* [in] Handle of heap */
1210 DWORD flags, /* [in] Heap size control flags */
1211 LPVOID ptr /* [in] Address of memory to return size for */
1213 DWORD ret;
1214 HEAP *heapPtr = HEAP_GetPtr( heap );
1216 if (!heapPtr) return FALSE;
1217 flags &= HEAP_NO_SERIALIZE;
1218 flags |= heapPtr->flags;
1219 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1220 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1222 SetLastError( ERROR_INVALID_PARAMETER );
1223 ret = 0xffffffff;
1225 else
1227 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1228 ret = pArena->size & ARENA_SIZE_MASK;
1230 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1232 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1233 heap, flags, (DWORD)ptr, ret );
1234 return ret;
1238 /***********************************************************************
1239 * HeapValidate (KERNEL32.343)
1240 * Validates a specified heap.
1242 * NOTES
1243 * Flags is ignored.
1245 * RETURNS
1246 * TRUE: Success
1247 * FALSE: Failure
1249 BOOL32 WINAPI HeapValidate(
1250 HANDLE32 heap, /* [in] Handle to the heap */
1251 DWORD flags, /* [in] Bit flags that control access during operation */
1252 LPCVOID block /* [in] Optional pointer to memory block to validate */
1254 SUBHEAP *subheap;
1255 HEAP *heapPtr = (HEAP *)(heap);
1257 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1259 ERR(heap, "Invalid heap %08x!\n", heap );
1260 return FALSE;
1263 if (block)
1265 /* Only check this single memory block */
1266 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1267 ((char *)block < (char *)subheap + subheap->headerSize
1268 + sizeof(ARENA_INUSE)))
1270 ERR(heap, "Heap %08lx: block %08lx is not inside heap\n",
1271 (DWORD)heap, (DWORD)block );
1272 return FALSE;
1274 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1277 subheap = &heapPtr->subheap;
1278 while (subheap)
1280 char *ptr = (char *)subheap + subheap->headerSize;
1281 while (ptr < (char *)subheap + subheap->size)
1283 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1285 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1286 return FALSE;
1287 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1289 else
1291 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1292 return FALSE;
1293 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1296 subheap = subheap->next;
1298 return TRUE;
1302 /***********************************************************************
1303 * HeapWalk (KERNEL32.344)
1304 * Enumerates the memory blocks in a specified heap.
1306 * RETURNS
1307 * TRUE: Success
1308 * FALSE: Failure
1310 BOOL32 WINAPI HeapWalk(
1311 HANDLE32 heap, /* [in] Handle to heap to enumerate */
1312 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1314 FIXME(heap, "(%08x): stub.\n", heap );
1315 return FALSE;
1319 /***********************************************************************
1320 * HEAP_xalloc
1322 * Same as HeapAlloc(), but die on failure.
1324 LPVOID HEAP_xalloc( HANDLE32 heap, DWORD flags, DWORD size )
1326 LPVOID p = HeapAlloc( heap, flags, size );
1327 if (!p)
1329 MSG("Virtual memory exhausted.\n" );
1330 exit(1);
1332 return p;
1336 /***********************************************************************
1337 * HEAP_strdupA
1339 LPSTR HEAP_strdupA( HANDLE32 heap, DWORD flags, LPCSTR str )
1341 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1342 strcpy( p, str );
1343 return p;
1347 /***********************************************************************
1348 * HEAP_strdupW
1350 LPWSTR HEAP_strdupW( HANDLE32 heap, DWORD flags, LPCWSTR str )
1352 INT32 len = lstrlen32W(str) + 1;
1353 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1354 lstrcpy32W( p, str );
1355 return p;
1359 /***********************************************************************
1360 * HEAP_strdupAtoW
1362 LPWSTR HEAP_strdupAtoW( HANDLE32 heap, DWORD flags, LPCSTR str )
1364 LPWSTR ret;
1366 if (!str) return NULL;
1367 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1368 lstrcpyAtoW( ret, str );
1369 return ret;
1373 /***********************************************************************
1374 * HEAP_strdupWtoA
1376 LPSTR HEAP_strdupWtoA( HANDLE32 heap, DWORD flags, LPCWSTR str )
1378 LPSTR ret;
1380 if (!str) return NULL;
1381 ret = HEAP_xalloc( heap, flags, lstrlen32W(str) + 1 );
1382 lstrcpyWtoA( ret, str );
1383 return ret;
1388 /***********************************************************************
1389 * 32-bit local heap functions (Win95; undocumented)
1392 #define HTABLE_SIZE 0x10000
1393 #define HTABLE_PAGESIZE 0x1000
1394 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1396 #pragma pack(1)
1397 typedef struct _LOCAL32HEADER
1399 WORD freeListFirst[HTABLE_NPAGES];
1400 WORD freeListSize[HTABLE_NPAGES];
1401 WORD freeListLast[HTABLE_NPAGES];
1403 DWORD selectorTableOffset;
1404 WORD selectorTableSize;
1405 WORD selectorDelta;
1407 DWORD segment;
1408 LPBYTE base;
1410 DWORD limit;
1411 DWORD flags;
1413 DWORD magic;
1414 HANDLE32 heap;
1416 } LOCAL32HEADER;
1417 #pragma pack(4)
1419 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1421 /***********************************************************************
1422 * Local32Init (KERNEL.208)
1424 HANDLE32 WINAPI Local32Init( WORD segment, DWORD tableSize,
1425 DWORD heapSize, DWORD flags )
1427 DWORD totSize, segSize = 0;
1428 LPBYTE base;
1429 LOCAL32HEADER *header;
1430 HEAP *heap;
1431 WORD *selectorTable;
1432 WORD selectorEven, selectorOdd;
1433 int i, nrBlocks;
1435 /* Determine new heap size */
1437 if ( segment )
1439 if ( (segSize = GetSelectorLimit( segment )) == 0 )
1440 return 0;
1441 else
1442 segSize++;
1445 if ( heapSize == -1L )
1446 heapSize = 1024L*1024L; /* FIXME */
1448 heapSize = (heapSize + 0xffff) & 0xffff0000;
1449 segSize = (segSize + 0x0fff) & 0xfffff000;
1450 totSize = segSize + HTABLE_SIZE + heapSize;
1453 /* Allocate memory and initialize heap */
1455 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1456 return 0;
1458 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1459 MEM_COMMIT, PAGE_READWRITE ) )
1461 VirtualFree( base, 0, MEM_RELEASE );
1462 return 0;
1465 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1466 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1468 VirtualFree( base, 0, MEM_RELEASE );
1469 return 0;
1473 /* Set up header and handle table */
1475 header = (LOCAL32HEADER *)(base + segSize);
1476 header->base = base;
1477 header->limit = HTABLE_PAGESIZE-1;
1478 header->flags = 0;
1479 header->magic = LOCAL32_MAGIC;
1480 header->heap = (HANDLE32)heap;
1482 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1483 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1484 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1486 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1487 *(DWORD *)((LPBYTE)header + i) = i+4;
1489 header->freeListFirst[1] = 0xffff;
1492 /* Set up selector table */
1494 nrBlocks = (totSize + 0x7fff) >> 15;
1495 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1496 selectorEven = SELECTOR_AllocBlock( base, totSize,
1497 SEGMENT_DATA, FALSE, FALSE );
1498 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1499 SEGMENT_DATA, FALSE, FALSE );
1501 if ( !selectorTable || !selectorEven || !selectorOdd )
1503 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1504 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1505 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1506 HeapDestroy( header->heap );
1507 VirtualFree( base, 0, MEM_RELEASE );
1508 return 0;
1511 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1512 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1513 header->selectorDelta = selectorEven - selectorOdd;
1514 header->segment = segment? segment : selectorEven;
1516 for (i = 0; i < nrBlocks; i++)
1517 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1518 : selectorEven + ((i >> 1) << __AHSHIFT);
1520 /* Move old segment */
1522 if ( segment )
1524 /* FIXME: This is somewhat ugly and relies on implementation
1525 details about 16-bit global memory handles ... */
1527 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1528 memcpy( base, oldBase, segSize );
1529 GLOBAL_MoveBlock( segment, base, totSize );
1530 HeapFree( SystemHeap, 0, oldBase );
1533 return (HANDLE32)header;
1536 /***********************************************************************
1537 * Local32_SearchHandle
1539 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1541 LPDWORD handle;
1543 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1544 handle < (LPDWORD)((LPBYTE)header + header->limit);
1545 handle++)
1547 if (*handle == addr)
1548 return handle;
1551 return NULL;
1554 /***********************************************************************
1555 * Local32_ToHandle
1557 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1558 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1560 *handle = NULL;
1561 *ptr = NULL;
1563 switch (type)
1565 case -2: /* 16:16 pointer, no handles */
1566 *ptr = PTR_SEG_TO_LIN( addr );
1567 *handle = (LPDWORD)*ptr;
1568 break;
1570 case -1: /* 32-bit offset, no handles */
1571 *ptr = header->base + addr;
1572 *handle = (LPDWORD)*ptr;
1573 break;
1575 case 0: /* handle */
1576 if ( addr >= sizeof(LOCAL32HEADER)
1577 && addr < header->limit && !(addr & 3)
1578 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1580 *handle = (LPDWORD)((LPBYTE)header + addr);
1581 *ptr = header->base + **handle;
1583 break;
1585 case 1: /* 16:16 pointer */
1586 *ptr = PTR_SEG_TO_LIN( addr );
1587 *handle = Local32_SearchHandle( header, *ptr - header->base );
1588 break;
1590 case 2: /* 32-bit offset */
1591 *ptr = header->base + addr;
1592 *handle = Local32_SearchHandle( header, *ptr - header->base );
1593 break;
1597 /***********************************************************************
1598 * Local32_FromHandle
1600 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1601 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1603 switch (type)
1605 case -2: /* 16:16 pointer */
1606 case 1:
1608 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1609 DWORD offset = (LPBYTE)ptr - header->base;
1610 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1612 break;
1614 case -1: /* 32-bit offset */
1615 case 2:
1616 *addr = ptr - header->base;
1617 break;
1619 case 0: /* handle */
1620 *addr = (LPBYTE)handle - (LPBYTE)header;
1621 break;
1625 /***********************************************************************
1626 * Local32Alloc (KERNEL.209)
1628 DWORD WINAPI Local32Alloc( HANDLE32 heap, DWORD size, INT16 type, DWORD flags )
1630 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1631 LPDWORD handle;
1632 LPBYTE ptr;
1633 DWORD addr;
1635 /* Allocate memory */
1636 ptr = HeapAlloc( header->heap,
1637 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1638 if (!ptr) return 0;
1641 /* Allocate handle if requested */
1642 if (type >= 0)
1644 int page, i;
1646 /* Find first page of handle table with free slots */
1647 for (page = 0; page < HTABLE_NPAGES; page++)
1648 if (header->freeListFirst[page] != 0)
1649 break;
1650 if (page == HTABLE_NPAGES)
1652 WARN( heap, "Out of handles!\n" );
1653 HeapFree( header->heap, 0, ptr );
1654 return 0;
1657 /* If virgin page, initialize it */
1658 if (header->freeListFirst[page] == 0xffff)
1660 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1661 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1663 WARN( heap, "Cannot grow handle table!\n" );
1664 HeapFree( header->heap, 0, ptr );
1665 return 0;
1668 header->limit += HTABLE_PAGESIZE;
1670 header->freeListFirst[page] = 0;
1671 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1672 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1674 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1675 *(DWORD *)((LPBYTE)header + i) = i+4;
1677 if (page < HTABLE_NPAGES-1)
1678 header->freeListFirst[page+1] = 0xffff;
1681 /* Allocate handle slot from page */
1682 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1683 if (--header->freeListSize[page] == 0)
1684 header->freeListFirst[page] = header->freeListLast[page] = 0;
1685 else
1686 header->freeListFirst[page] = *handle;
1688 /* Store 32-bit offset in handle slot */
1689 *handle = ptr - header->base;
1691 else
1693 handle = (LPDWORD)ptr;
1694 header->flags |= 1;
1698 /* Convert handle to requested output type */
1699 Local32_FromHandle( header, type, &addr, handle, ptr );
1700 return addr;
1703 /***********************************************************************
1704 * Local32ReAlloc (KERNEL.210)
1706 DWORD WINAPI Local32ReAlloc( HANDLE32 heap, DWORD addr, INT16 type,
1707 DWORD size, DWORD flags )
1709 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1710 LPDWORD handle;
1711 LPBYTE ptr;
1713 if (!addr)
1714 return Local32Alloc( heap, size, type, flags );
1716 /* Retrieve handle and pointer */
1717 Local32_ToHandle( header, type, addr, &handle, &ptr );
1718 if (!handle) return FALSE;
1720 /* Reallocate memory block */
1721 ptr = HeapReAlloc( header->heap,
1722 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1723 ptr, size );
1724 if (!ptr) return 0;
1726 /* Modify handle */
1727 if (type >= 0)
1728 *handle = ptr - header->base;
1729 else
1730 handle = (LPDWORD)ptr;
1732 /* Convert handle to requested output type */
1733 Local32_FromHandle( header, type, &addr, handle, ptr );
1734 return addr;
1737 /***********************************************************************
1738 * Local32Free (KERNEL.211)
1740 BOOL32 WINAPI Local32Free( HANDLE32 heap, DWORD addr, INT16 type )
1742 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1743 LPDWORD handle;
1744 LPBYTE ptr;
1746 /* Retrieve handle and pointer */
1747 Local32_ToHandle( header, type, addr, &handle, &ptr );
1748 if (!handle) return FALSE;
1750 /* Free handle if necessary */
1751 if (type >= 0)
1753 int offset = (LPBYTE)handle - (LPBYTE)header;
1754 int page = offset >> 12;
1756 /* Return handle slot to page free list */
1757 if (header->freeListSize[page]++ == 0)
1758 header->freeListFirst[page] = header->freeListLast[page] = offset;
1759 else
1760 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1761 header->freeListLast[page] = offset;
1763 *handle = 0;
1765 /* Shrink handle table when possible */
1766 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1768 if ( VirtualFree( (LPBYTE)header +
1769 (header->limit & ~(HTABLE_PAGESIZE-1)),
1770 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1771 break;
1773 header->limit -= HTABLE_PAGESIZE;
1774 header->freeListFirst[page] = 0xffff;
1775 page--;
1779 /* Free memory */
1780 return HeapFree( header->heap, 0, ptr );
1783 /***********************************************************************
1784 * Local32Translate (KERNEL.213)
1786 DWORD WINAPI Local32Translate( HANDLE32 heap, DWORD addr, INT16 type1, INT16 type2 )
1788 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1789 LPDWORD handle;
1790 LPBYTE ptr;
1792 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1793 if (!handle) return 0;
1795 Local32_FromHandle( header, type2, &addr, handle, ptr );
1796 return addr;
1799 /***********************************************************************
1800 * Local32Size (KERNEL.214)
1802 DWORD WINAPI Local32Size( HANDLE32 heap, DWORD addr, INT16 type )
1804 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1805 LPDWORD handle;
1806 LPBYTE ptr;
1808 Local32_ToHandle( header, type, addr, &handle, &ptr );
1809 if (!handle) return 0;
1811 return HeapSize( header->heap, 0, ptr );
1814 /***********************************************************************
1815 * Local32ValidHandle (KERNEL.215)
1817 BOOL32 WINAPI Local32ValidHandle( HANDLE32 heap, WORD addr )
1819 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1820 LPDWORD handle;
1821 LPBYTE ptr;
1823 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1824 return handle != NULL;
1827 /***********************************************************************
1828 * Local32GetSegment (KERNEL.229)
1830 WORD WINAPI Local32GetSegment( HANDLE32 heap )
1832 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1833 return header->segment;