Removed __winelib flag.
[wine/dcerpc.git] / memory / heap.c
blobdd74be1c8109fee57df67c091061da783f6b9c79
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 "wine/winbase16.h"
12 #include "wine/winestring.h"
13 #include "selectors.h"
14 #include "global.h"
15 #include "winbase.h"
16 #include "winerror.h"
17 #include "winnt.h"
18 #include "heap.h"
19 #include "toolhelp.h"
20 #include "debugtools.h"
22 DEFAULT_DEBUG_CHANNEL(heap)
24 /* Note: the heap data structures are based on what Pietrek describes in his
25 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
26 * the same, but could be easily adapted if it turns out some programs
27 * require it.
30 typedef struct tagARENA_INUSE
32 DWORD size; /* Block size; must be the first field */
33 WORD threadId; /* Allocating thread id */
34 WORD magic; /* Magic number */
35 void *callerEIP; /* EIP of caller upon allocation */
36 } ARENA_INUSE;
38 typedef struct tagARENA_FREE
40 DWORD size; /* Block size; must be the first field */
41 WORD threadId; /* Freeing thread id */
42 WORD magic; /* Magic number */
43 struct tagARENA_FREE *next; /* Next free arena */
44 struct tagARENA_FREE *prev; /* Prev free arena */
45 } ARENA_FREE;
47 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
48 #define ARENA_FLAG_PREV_FREE 0x00000002
49 #define ARENA_SIZE_MASK 0xfffffffc
50 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
51 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
53 #define ARENA_INUSE_FILLER 0x55
54 #define ARENA_FREE_FILLER 0xaa
56 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
58 /* Max size of the blocks on the free lists */
59 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
61 0x20, 0x80, 0x200, 0xffffffff
64 typedef struct
66 DWORD size;
67 ARENA_FREE arena;
68 } FREE_LIST_ENTRY;
70 struct tagHEAP;
72 typedef struct tagSUBHEAP
74 DWORD size; /* Size of the whole sub-heap */
75 DWORD commitSize; /* Committed size of the sub-heap */
76 DWORD headerSize; /* Size of the heap header */
77 struct tagSUBHEAP *next; /* Next sub-heap */
78 struct tagHEAP *heap; /* Main heap structure */
79 DWORD magic; /* Magic number */
80 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
81 } SUBHEAP;
83 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
85 typedef struct tagHEAP
87 SUBHEAP subheap; /* First sub-heap */
88 struct tagHEAP *next; /* Next heap for this process */
89 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
90 CRITICAL_SECTION critSection; /* Critical section for serialization */
91 DWORD flags; /* Heap flags */
92 DWORD magic; /* Magic number */
93 } HEAP;
95 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
97 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
98 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
100 HANDLE SystemHeap = 0;
101 HANDLE SegptrHeap = 0;
104 #ifdef __GNUC__
105 #define GET_EIP() (__builtin_return_address(0))
106 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
107 #else
108 #define GET_EIP() 0
109 #define SET_EIP(ptr) /* nothing */
110 #endif /* __GNUC__ */
112 /***********************************************************************
113 * HEAP_Dump
115 void HEAP_Dump( HEAP *heap )
117 int i;
118 SUBHEAP *subheap;
119 char *ptr;
121 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
122 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
123 (DWORD)heap->next, (DWORD)&heap->subheap );
124 subheap = &heap->subheap;
125 while (subheap->next)
127 DPRINTF( " -> %08lx", (DWORD)subheap->next );
128 subheap = subheap->next;
131 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
132 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
133 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
134 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
135 heap->freeList[i].arena.threadId,
136 (DWORD)heap->freeList[i].arena.prev,
137 (DWORD)heap->freeList[i].arena.next );
139 subheap = &heap->subheap;
140 while (subheap)
142 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
143 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
144 (DWORD)subheap, subheap->size, subheap->commitSize );
146 DPRINTF( "\n Block Stat Size Id\n" );
147 ptr = (char*)subheap + subheap->headerSize;
148 while (ptr < (char *)subheap + subheap->size)
150 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
152 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
153 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
154 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
155 pArena->threadId, (DWORD)pArena->prev,
156 (DWORD)pArena->next);
157 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
158 arenaSize += sizeof(ARENA_FREE);
159 freeSize += pArena->size & ARENA_SIZE_MASK;
161 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
163 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
164 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
165 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
166 pArena->threadId, *((DWORD *)pArena - 1),
167 pArena->callerEIP );
168 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
169 arenaSize += sizeof(ARENA_INUSE);
170 usedSize += pArena->size & ARENA_SIZE_MASK;
172 else
174 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
175 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
176 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
177 pArena->threadId, pArena->callerEIP );
178 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
179 arenaSize += sizeof(ARENA_INUSE);
180 usedSize += pArena->size & ARENA_SIZE_MASK;
183 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
184 subheap->size, subheap->commitSize, freeSize, usedSize,
185 arenaSize, (arenaSize * 100) / subheap->size );
186 subheap = subheap->next;
191 /***********************************************************************
192 * HEAP_GetPtr
193 * RETURNS
194 * Pointer to the heap
195 * NULL: Failure
197 static HEAP *HEAP_GetPtr(
198 HANDLE heap /* [in] Handle to the heap */
200 HEAP *heapPtr = (HEAP *)heap;
201 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
203 ERR("Invalid heap %08x!\n", heap );
204 SetLastError( ERROR_INVALID_HANDLE );
205 return NULL;
207 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
209 HEAP_Dump( heapPtr );
210 assert( FALSE );
211 SetLastError( ERROR_INVALID_HANDLE );
212 return NULL;
214 return heapPtr;
218 /***********************************************************************
219 * HEAP_InsertFreeBlock
221 * Insert a free block into the free list.
223 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
225 FREE_LIST_ENTRY *pEntry = heap->freeList;
226 while (pEntry->size < pArena->size) pEntry++;
227 pArena->size |= ARENA_FLAG_FREE;
228 pArena->next = pEntry->arena.next;
229 pArena->next->prev = pArena;
230 pArena->prev = &pEntry->arena;
231 pEntry->arena.next = pArena;
235 /***********************************************************************
236 * HEAP_FindSubHeap
237 * Find the sub-heap containing a given address.
239 * RETURNS
240 * Pointer: Success
241 * NULL: Failure
243 static SUBHEAP *HEAP_FindSubHeap(
244 HEAP *heap, /* [in] Heap pointer */
245 LPCVOID ptr /* [in] Address */
247 SUBHEAP *sub = &heap->subheap;
248 while (sub)
250 if (((char *)ptr >= (char *)sub) &&
251 ((char *)ptr < (char *)sub + sub->size)) return sub;
252 sub = sub->next;
254 return NULL;
258 /***********************************************************************
259 * HEAP_Commit
261 * Make sure the heap storage is committed up to (not including) ptr.
263 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
265 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
266 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
267 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
268 if (size > subheap->size) size = subheap->size;
269 if (size <= subheap->commitSize) return TRUE;
270 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
271 size - subheap->commitSize, MEM_COMMIT,
272 PAGE_EXECUTE_READWRITE))
274 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
275 size - subheap->commitSize,
276 (DWORD)((char *)subheap + subheap->commitSize),
277 (DWORD)subheap->heap );
278 return FALSE;
280 subheap->commitSize = size;
281 return TRUE;
285 /***********************************************************************
286 * HEAP_Decommit
288 * If possible, decommit the heap storage from (including) 'ptr'.
290 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
292 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
293 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
294 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
295 if (size >= subheap->commitSize) return TRUE;
296 if (!VirtualFree( (char *)subheap + size,
297 subheap->commitSize - size, MEM_DECOMMIT ))
299 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
300 subheap->commitSize - size,
301 (DWORD)((char *)subheap + size),
302 (DWORD)subheap->heap );
303 return FALSE;
305 subheap->commitSize = size;
306 return TRUE;
310 /***********************************************************************
311 * HEAP_CreateFreeBlock
313 * Create a free block at a specified address. 'size' is the size of the
314 * whole block, including the new arena.
316 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
318 ARENA_FREE *pFree;
320 /* Create a free arena */
322 pFree = (ARENA_FREE *)ptr;
323 pFree->threadId = GetCurrentTask();
324 pFree->magic = ARENA_FREE_MAGIC;
326 /* If debugging, erase the freed block content */
328 if (TRACE_ON(heap))
330 char *pEnd = (char *)ptr + size;
331 if (pEnd > (char *)subheap + subheap->commitSize)
332 pEnd = (char *)subheap + subheap->commitSize;
333 if (pEnd > (char *)(pFree + 1))
334 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
337 /* Check if next block is free also */
339 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
340 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
342 /* Remove the next arena from the free list */
343 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
344 pNext->next->prev = pNext->prev;
345 pNext->prev->next = pNext->next;
346 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
347 if (TRACE_ON(heap))
348 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
351 /* Set the next block PREV_FREE flag and pointer */
353 if ((char *)ptr + size < (char *)subheap + subheap->size)
355 DWORD *pNext = (DWORD *)((char *)ptr + size);
356 *pNext |= ARENA_FLAG_PREV_FREE;
357 *(ARENA_FREE **)(pNext - 1) = pFree;
360 /* Last, insert the new block into the free list */
362 pFree->size = size - sizeof(*pFree);
363 HEAP_InsertFreeBlock( subheap->heap, pFree );
367 /***********************************************************************
368 * HEAP_MakeInUseBlockFree
370 * Turn an in-use block into a free block. Can also decommit the end of
371 * the heap, and possibly even free the sub-heap altogether.
373 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
375 ARENA_FREE *pFree;
376 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
378 /* Check if we can merge with previous block */
380 if (pArena->size & ARENA_FLAG_PREV_FREE)
382 pFree = *((ARENA_FREE **)pArena - 1);
383 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
384 /* Remove it from the free list */
385 pFree->next->prev = pFree->prev;
386 pFree->prev->next = pFree->next;
388 else pFree = (ARENA_FREE *)pArena;
390 /* Create a free block */
392 HEAP_CreateFreeBlock( subheap, pFree, size );
393 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
394 if ((char *)pFree + size < (char *)subheap + subheap->size)
395 return; /* Not the last block, so nothing more to do */
397 /* Free the whole sub-heap if it's empty and not the original one */
399 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
400 (subheap != &subheap->heap->subheap))
402 SUBHEAP *pPrev = &subheap->heap->subheap;
403 /* Remove the free block from the list */
404 pFree->next->prev = pFree->prev;
405 pFree->prev->next = pFree->next;
406 /* Remove the subheap from the list */
407 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
408 if (pPrev) pPrev->next = subheap->next;
409 /* Free the memory */
410 subheap->magic = 0;
411 if (subheap->selector) FreeSelector16( subheap->selector );
412 VirtualFree( subheap, 0, MEM_RELEASE );
413 return;
416 /* Decommit the end of the heap */
418 HEAP_Decommit( subheap, pFree + 1 );
422 /***********************************************************************
423 * HEAP_ShrinkBlock
425 * Shrink an in-use block.
427 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
429 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
431 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
432 (pArena->size & ARENA_SIZE_MASK) - size );
433 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
435 else
437 /* Turn off PREV_FREE flag in next block */
438 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
439 if (pNext < (char *)subheap + subheap->size)
440 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
444 /***********************************************************************
445 * HEAP_InitSubHeap
447 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
448 DWORD commitSize, DWORD totalSize )
450 SUBHEAP *subheap = (SUBHEAP *)address;
451 WORD selector = 0;
452 FREE_LIST_ENTRY *pEntry;
453 int i;
455 /* Commit memory */
457 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
459 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
460 commitSize, (DWORD)address );
461 return FALSE;
464 /* Allocate a selector if needed */
466 if (flags & HEAP_WINE_SEGPTR)
468 selector = SELECTOR_AllocBlock( address, totalSize,
469 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
470 ? SEGMENT_CODE : SEGMENT_DATA,
471 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
472 if (!selector)
474 ERR("Could not allocate selector\n" );
475 return FALSE;
479 /* Fill the sub-heap structure */
481 subheap->heap = heap;
482 subheap->selector = selector;
483 subheap->size = totalSize;
484 subheap->commitSize = commitSize;
485 subheap->magic = SUBHEAP_MAGIC;
487 if ( subheap != (SUBHEAP *)heap )
489 /* If this is a secondary subheap, insert it into list */
491 subheap->headerSize = sizeof(SUBHEAP);
492 subheap->next = heap->subheap.next;
493 heap->subheap.next = subheap;
495 else
497 /* If this is a primary subheap, initialize main heap */
499 subheap->headerSize = sizeof(HEAP);
500 subheap->next = NULL;
501 heap->next = NULL;
502 heap->flags = flags;
503 heap->magic = HEAP_MAGIC;
505 /* Build the free lists */
507 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
509 pEntry->size = HEAP_freeListSizes[i];
510 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
511 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
512 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
513 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
514 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
515 pEntry->arena.threadId = 0;
516 pEntry->arena.magic = ARENA_FREE_MAGIC;
519 /* Initialize critical section */
521 InitializeCriticalSection( &heap->critSection );
522 if (!SystemHeap) /* System heap critical section has to be global */
523 MakeCriticalSectionGlobal( &heap->critSection );
526 /* Create the first free block */
528 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
529 subheap->size - subheap->headerSize );
531 return TRUE;
534 /***********************************************************************
535 * HEAP_CreateSubHeap
537 * Create a sub-heap of the given size.
538 * If heap == NULL, creates a main heap.
540 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
541 DWORD commitSize, DWORD totalSize )
543 LPVOID address;
545 /* Round-up sizes on a 64K boundary */
547 if (flags & HEAP_WINE_SEGPTR)
549 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
551 else
553 totalSize = (totalSize + 0xffff) & 0xffff0000;
554 commitSize = (commitSize + 0xffff) & 0xffff0000;
555 if (!commitSize) commitSize = 0x10000;
556 if (totalSize < commitSize) totalSize = commitSize;
559 /* Allocate the memory block */
561 if (!(address = VirtualAlloc( NULL, totalSize,
562 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
564 WARN("Could not VirtualAlloc %08lx bytes\n",
565 totalSize );
566 return NULL;
569 /* Initialize subheap */
571 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
572 address, flags, commitSize, totalSize ))
574 VirtualFree( address, 0, MEM_RELEASE );
575 return NULL;
578 return (SUBHEAP *)address;
582 /***********************************************************************
583 * HEAP_FindFreeBlock
585 * Find a free block at least as large as the requested size, and make sure
586 * the requested size is committed.
588 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
589 SUBHEAP **ppSubHeap )
591 SUBHEAP *subheap;
592 ARENA_FREE *pArena;
593 FREE_LIST_ENTRY *pEntry = heap->freeList;
595 /* Find a suitable free list, and in it find a block large enough */
597 while (pEntry->size < size) pEntry++;
598 pArena = pEntry->arena.next;
599 while (pArena != &heap->freeList[0].arena)
601 if (pArena->size > size)
603 subheap = HEAP_FindSubHeap( heap, pArena );
604 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
605 + size + HEAP_MIN_BLOCK_SIZE))
606 return NULL;
607 *ppSubHeap = subheap;
608 return pArena;
611 pArena = pArena->next;
614 /* If no block was found, attempt to grow the heap */
616 if (!(heap->flags & HEAP_GROWABLE))
618 WARN("Not enough space in heap %08lx for %08lx bytes\n",
619 (DWORD)heap, size );
620 return NULL;
622 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
623 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
624 MAX( HEAP_DEF_SIZE, size ) )))
625 return NULL;
627 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
628 (DWORD)subheap, size, (DWORD)heap );
630 *ppSubHeap = subheap;
631 return (ARENA_FREE *)(subheap + 1);
635 /***********************************************************************
636 * HEAP_IsValidArenaPtr
638 * Check that the pointer is inside the range possible for arenas.
640 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
642 int i;
643 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
644 if (!subheap) return FALSE;
645 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
646 if (subheap != &heap->subheap) return FALSE;
647 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
648 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
649 return FALSE;
653 /***********************************************************************
654 * HEAP_ValidateFreeArena
656 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
658 char *heapEnd = (char *)subheap + subheap->size;
660 /* Check magic number */
661 if (pArena->magic != ARENA_FREE_MAGIC)
663 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
664 (DWORD)subheap->heap, (DWORD)pArena );
665 return FALSE;
667 /* Check size flags */
668 if (!(pArena->size & ARENA_FLAG_FREE) ||
669 (pArena->size & ARENA_FLAG_PREV_FREE))
671 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
672 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
674 /* Check arena size */
675 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
677 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
678 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
679 return FALSE;
681 /* Check that next pointer is valid */
682 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
684 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
685 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
686 return FALSE;
688 /* Check that next arena is free */
689 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
690 (pArena->next->magic != ARENA_FREE_MAGIC))
692 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
693 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
694 return FALSE;
696 /* Check that prev pointer is valid */
697 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
699 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
700 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
701 return FALSE;
703 /* Check that prev arena is free */
704 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
705 (pArena->prev->magic != ARENA_FREE_MAGIC))
707 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
708 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
709 return FALSE;
711 /* Check that next block has PREV_FREE flag */
712 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
714 if (!(*(DWORD *)((char *)(pArena + 1) +
715 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
717 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
718 (DWORD)subheap->heap, (DWORD)pArena );
719 return FALSE;
721 /* Check next block back pointer */
722 if (*((ARENA_FREE **)((char *)(pArena + 1) +
723 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
725 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
726 (DWORD)subheap->heap, (DWORD)pArena,
727 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
728 return FALSE;
731 return TRUE;
735 /***********************************************************************
736 * HEAP_ValidateInUseArena
738 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
740 char *heapEnd = (char *)subheap + subheap->size;
742 /* Check magic number */
743 if (pArena->magic != ARENA_INUSE_MAGIC)
745 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
746 (DWORD)subheap->heap, (DWORD)pArena );
747 return FALSE;
749 /* Check size flags */
750 if (pArena->size & ARENA_FLAG_FREE)
752 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
753 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
755 /* Check arena size */
756 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
758 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
759 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
760 return FALSE;
762 /* Check next arena PREV_FREE flag */
763 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
764 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
766 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
767 (DWORD)subheap->heap, (DWORD)pArena );
768 return FALSE;
770 /* Check prev free arena */
771 if (pArena->size & ARENA_FLAG_PREV_FREE)
773 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
774 /* Check prev pointer */
775 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
777 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
778 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
779 return FALSE;
781 /* Check that prev arena is free */
782 if (!(pPrev->size & ARENA_FLAG_FREE) ||
783 (pPrev->magic != ARENA_FREE_MAGIC))
785 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
786 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
787 return FALSE;
789 /* Check that prev arena is really the previous block */
790 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
792 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
793 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
794 return FALSE;
797 return TRUE;
801 /***********************************************************************
802 * HEAP_IsInsideHeap
803 * Checks whether the pointer points to a block inside a given heap.
805 * NOTES
806 * Should this return BOOL32?
808 * RETURNS
809 * !0: Success
810 * 0: Failure
812 int HEAP_IsInsideHeap(
813 HANDLE heap, /* [in] Heap */
814 DWORD flags, /* [in] Flags */
815 LPCVOID ptr /* [in] Pointer */
817 HEAP *heapPtr = HEAP_GetPtr( heap );
818 SUBHEAP *subheap;
819 int ret;
821 /* Validate the parameters */
823 if (!heapPtr) return 0;
824 flags |= heapPtr->flags;
825 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
826 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
827 (((char *)ptr >= (char *)subheap + subheap->headerSize
828 + sizeof(ARENA_INUSE))));
829 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
830 return ret;
834 /***********************************************************************
835 * HEAP_GetSegptr
837 * Transform a linear pointer into a SEGPTR. The pointer must have been
838 * allocated from a HEAP_WINE_SEGPTR heap.
840 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
842 HEAP *heapPtr = HEAP_GetPtr( heap );
843 SUBHEAP *subheap;
844 SEGPTR ret;
846 /* Validate the parameters */
848 if (!heapPtr) return 0;
849 flags |= heapPtr->flags;
850 if (!(flags & HEAP_WINE_SEGPTR))
852 ERR("Heap %08x is not a SEGPTR heap\n",
853 heap );
854 return 0;
856 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
858 /* Get the subheap */
860 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
862 ERR("%p is not inside heap %08x\n",
863 ptr, heap );
864 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
865 return 0;
868 /* Build the SEGPTR */
870 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
871 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
872 return ret;
876 /***********************************************************************
877 * HeapCreate (KERNEL32.336)
878 * RETURNS
879 * Handle of heap: Success
880 * NULL: Failure
882 HANDLE WINAPI HeapCreate(
883 DWORD flags, /* [in] Heap allocation flag */
884 DWORD initialSize, /* [in] Initial heap size */
885 DWORD maxSize /* [in] Maximum heap size */
887 SUBHEAP *subheap;
889 /* Allocate the heap block */
891 if (!maxSize)
893 maxSize = HEAP_DEF_SIZE;
894 flags |= HEAP_GROWABLE;
896 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
898 SetLastError( ERROR_OUTOFMEMORY );
899 return 0;
902 return (HANDLE)subheap;
905 /***********************************************************************
906 * HeapDestroy (KERNEL32.337)
907 * RETURNS
908 * TRUE: Success
909 * FALSE: Failure
911 BOOL WINAPI HeapDestroy(
912 HANDLE heap /* [in] Handle of heap */
914 HEAP *heapPtr = HEAP_GetPtr( heap );
915 SUBHEAP *subheap;
917 TRACE("%08x\n", heap );
918 if (!heapPtr) return FALSE;
920 DeleteCriticalSection( &heapPtr->critSection );
921 subheap = &heapPtr->subheap;
922 while (subheap)
924 SUBHEAP *next = subheap->next;
925 if (subheap->selector) FreeSelector16( subheap->selector );
926 VirtualFree( subheap, 0, MEM_RELEASE );
927 subheap = next;
929 return TRUE;
933 /***********************************************************************
934 * HeapAlloc (KERNEL32.334)
935 * RETURNS
936 * Pointer to allocated memory block
937 * NULL: Failure
939 LPVOID WINAPI HeapAlloc(
940 HANDLE heap, /* [in] Handle of private heap block */
941 DWORD flags, /* [in] Heap allocation control flags */
942 DWORD size /* [in] Number of bytes to allocate */
944 ARENA_FREE *pArena;
945 ARENA_INUSE *pInUse;
946 SUBHEAP *subheap;
947 HEAP *heapPtr = HEAP_GetPtr( heap );
949 /* Validate the parameters */
951 if (!heapPtr) return NULL;
952 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
953 flags |= heapPtr->flags;
954 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
955 size = (size + 3) & ~3;
956 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
958 /* Locate a suitable free block */
960 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
962 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
963 heap, flags, size );
964 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
965 SetLastError( ERROR_COMMITMENT_LIMIT );
966 return NULL;
969 /* Remove the arena from the free list */
971 pArena->next->prev = pArena->prev;
972 pArena->prev->next = pArena->next;
974 /* Build the in-use arena */
976 pInUse = (ARENA_INUSE *)pArena;
977 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
978 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
979 pInUse->callerEIP = GET_EIP();
980 pInUse->threadId = GetCurrentTask();
981 pInUse->magic = ARENA_INUSE_MAGIC;
983 /* Shrink the block */
985 HEAP_ShrinkBlock( subheap, pInUse, size );
987 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
988 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
990 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
992 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
993 heap, flags, size, (DWORD)(pInUse + 1) );
994 return (LPVOID)(pInUse + 1);
998 /***********************************************************************
999 * HeapFree (KERNEL32.338)
1000 * RETURNS
1001 * TRUE: Success
1002 * FALSE: Failure
1004 BOOL WINAPI HeapFree(
1005 HANDLE heap, /* [in] Handle of heap */
1006 DWORD flags, /* [in] Heap freeing flags */
1007 LPVOID ptr /* [in] Address of memory to free */
1009 ARENA_INUSE *pInUse;
1010 SUBHEAP *subheap;
1011 HEAP *heapPtr = HEAP_GetPtr( heap );
1013 /* Validate the parameters */
1015 if (!heapPtr) return FALSE;
1016 flags &= HEAP_NO_SERIALIZE;
1017 flags |= heapPtr->flags;
1018 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1019 if (!ptr)
1021 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1022 heap, flags, (DWORD)ptr );
1024 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1026 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1027 SetLastError( ERROR_INVALID_PARAMETER );
1028 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1029 heap, flags, (DWORD)ptr );
1030 return FALSE;
1033 /* Turn the block into a free block */
1035 pInUse = (ARENA_INUSE *)ptr - 1;
1036 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1037 HEAP_MakeInUseBlockFree( subheap, pInUse );
1039 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1040 /* SetLastError( 0 ); */
1042 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1043 heap, flags, (DWORD)ptr );
1044 return TRUE;
1048 /***********************************************************************
1049 * HeapReAlloc (KERNEL32.340)
1050 * RETURNS
1051 * Pointer to reallocated memory block
1052 * NULL: Failure
1054 LPVOID WINAPI HeapReAlloc(
1055 HANDLE heap, /* [in] Handle of heap block */
1056 DWORD flags, /* [in] Heap reallocation flags */
1057 LPVOID ptr, /* [in] Address of memory to reallocate */
1058 DWORD size /* [in] Number of bytes to reallocate */
1060 ARENA_INUSE *pArena;
1061 DWORD oldSize;
1062 HEAP *heapPtr;
1063 SUBHEAP *subheap;
1065 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1066 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1068 /* Validate the parameters */
1070 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1071 HEAP_REALLOC_IN_PLACE_ONLY;
1072 flags |= heapPtr->flags;
1073 size = (size + 3) & ~3;
1074 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1076 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1077 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1079 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1080 SetLastError( ERROR_INVALID_PARAMETER );
1081 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1082 heap, flags, (DWORD)ptr, size );
1083 return NULL;
1086 /* Check if we need to grow the block */
1088 pArena = (ARENA_INUSE *)ptr - 1;
1089 pArena->threadId = GetCurrentTask();
1090 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1091 oldSize = (pArena->size & ARENA_SIZE_MASK);
1092 if (size > oldSize)
1094 char *pNext = (char *)(pArena + 1) + oldSize;
1095 if ((pNext < (char *)subheap + subheap->size) &&
1096 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1097 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1099 /* The next block is free and large enough */
1100 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1101 pFree->next->prev = pFree->prev;
1102 pFree->prev->next = pFree->next;
1103 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1104 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1105 + size + HEAP_MIN_BLOCK_SIZE))
1107 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1108 SetLastError( ERROR_OUTOFMEMORY );
1109 return NULL;
1111 HEAP_ShrinkBlock( subheap, pArena, size );
1113 else /* Do it the hard way */
1115 ARENA_FREE *pNew;
1116 ARENA_INUSE *pInUse;
1117 SUBHEAP *newsubheap;
1119 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1120 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1122 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1123 SetLastError( ERROR_OUTOFMEMORY );
1124 return NULL;
1127 /* Build the in-use arena */
1129 pNew->next->prev = pNew->prev;
1130 pNew->prev->next = pNew->next;
1131 pInUse = (ARENA_INUSE *)pNew;
1132 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1133 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1134 pInUse->threadId = GetCurrentTask();
1135 pInUse->magic = ARENA_INUSE_MAGIC;
1136 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1137 memcpy( pInUse + 1, pArena + 1, oldSize );
1139 /* Free the previous block */
1141 HEAP_MakeInUseBlockFree( subheap, pArena );
1142 subheap = newsubheap;
1143 pArena = pInUse;
1146 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1148 /* Clear the extra bytes if needed */
1150 if (size > oldSize)
1152 if (flags & HEAP_ZERO_MEMORY)
1153 memset( (char *)(pArena + 1) + oldSize, 0,
1154 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1155 else if (TRACE_ON(heap))
1156 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1157 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1160 /* Return the new arena */
1162 pArena->callerEIP = GET_EIP();
1163 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1165 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1166 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1167 return (LPVOID)(pArena + 1);
1171 /***********************************************************************
1172 * HeapCompact (KERNEL32.335)
1174 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1176 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1177 return 0;
1181 /***********************************************************************
1182 * HeapLock (KERNEL32.339)
1183 * Attempts to acquire the critical section object for a specified heap.
1185 * RETURNS
1186 * TRUE: Success
1187 * FALSE: Failure
1189 BOOL WINAPI HeapLock(
1190 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1192 HEAP *heapPtr = HEAP_GetPtr( heap );
1193 if (!heapPtr) return FALSE;
1194 EnterCriticalSection( &heapPtr->critSection );
1195 return TRUE;
1199 /***********************************************************************
1200 * HeapUnlock (KERNEL32.342)
1201 * Releases ownership of the critical section object.
1203 * RETURNS
1204 * TRUE: Success
1205 * FALSE: Failure
1207 BOOL WINAPI HeapUnlock(
1208 HANDLE heap /* [in] Handle to the heap to unlock */
1210 HEAP *heapPtr = HEAP_GetPtr( heap );
1211 if (!heapPtr) return FALSE;
1212 LeaveCriticalSection( &heapPtr->critSection );
1213 return TRUE;
1217 /***********************************************************************
1218 * HeapSize (KERNEL32.341)
1219 * RETURNS
1220 * Size in bytes of allocated memory
1221 * 0xffffffff: Failure
1223 DWORD WINAPI HeapSize(
1224 HANDLE heap, /* [in] Handle of heap */
1225 DWORD flags, /* [in] Heap size control flags */
1226 LPVOID ptr /* [in] Address of memory to return size for */
1228 DWORD ret;
1229 HEAP *heapPtr = HEAP_GetPtr( heap );
1231 if (!heapPtr) return FALSE;
1232 flags &= HEAP_NO_SERIALIZE;
1233 flags |= heapPtr->flags;
1234 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1235 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1237 SetLastError( ERROR_INVALID_PARAMETER );
1238 ret = 0xffffffff;
1240 else
1242 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1243 ret = pArena->size & ARENA_SIZE_MASK;
1245 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1247 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1248 heap, flags, (DWORD)ptr, ret );
1249 return ret;
1253 /***********************************************************************
1254 * HeapValidate (KERNEL32.343)
1255 * Validates a specified heap.
1257 * NOTES
1258 * Flags is ignored.
1260 * RETURNS
1261 * TRUE: Success
1262 * FALSE: Failure
1264 BOOL WINAPI HeapValidate(
1265 HANDLE heap, /* [in] Handle to the heap */
1266 DWORD flags, /* [in] Bit flags that control access during operation */
1267 LPCVOID block /* [in] Optional pointer to memory block to validate */
1269 SUBHEAP *subheap;
1270 HEAP *heapPtr = (HEAP *)(heap);
1271 BOOL ret = TRUE;
1273 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1275 ERR("Invalid heap %08x!\n", heap );
1276 return FALSE;
1279 flags &= HEAP_NO_SERIALIZE;
1280 flags |= heapPtr->flags;
1281 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1282 if (!(flags & HEAP_NO_SERIALIZE))
1283 EnterCriticalSection( &heapPtr->critSection );
1284 if (block)
1286 /* Only check this single memory block */
1287 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1288 ((char *)block < (char *)subheap + subheap->headerSize
1289 + sizeof(ARENA_INUSE)))
1291 ERR("Heap %08lx: block %08lx is not inside heap\n",
1292 (DWORD)heap, (DWORD)block );
1293 ret = FALSE;
1294 } else
1295 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1297 if (!(flags & HEAP_NO_SERIALIZE))
1298 LeaveCriticalSection( &heapPtr->critSection );
1299 return ret;
1302 subheap = &heapPtr->subheap;
1303 while (subheap && ret)
1305 char *ptr = (char *)subheap + subheap->headerSize;
1306 while (ptr < (char *)subheap + subheap->size)
1308 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1310 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1311 ret = FALSE;
1312 break;
1314 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1316 else
1318 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr )) {
1319 ret = FALSE;
1320 break;
1322 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1325 subheap = subheap->next;
1327 if (!(flags & HEAP_NO_SERIALIZE))
1328 LeaveCriticalSection( &heapPtr->critSection );
1329 return ret;
1333 /***********************************************************************
1334 * HeapWalk (KERNEL32.344)
1335 * Enumerates the memory blocks in a specified heap.
1337 * RETURNS
1338 * TRUE: Success
1339 * FALSE: Failure
1341 BOOL WINAPI HeapWalk(
1342 HANDLE heap, /* [in] Handle to heap to enumerate */
1343 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1345 FIXME("(%08x): stub.\n", heap );
1346 return FALSE;
1350 /***********************************************************************
1351 * HEAP_xalloc
1353 * Same as HeapAlloc(), but die on failure.
1355 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1357 LPVOID p = HeapAlloc( heap, flags, size );
1358 if (!p)
1360 MESSAGE("Virtual memory exhausted.\n" );
1361 exit(1);
1363 SET_EIP(p);
1364 return p;
1368 /***********************************************************************
1369 * HEAP_xrealloc
1371 * Same as HeapReAlloc(), but die on failure.
1373 LPVOID HEAP_xrealloc( HANDLE heap, DWORD flags, LPVOID lpMem, DWORD size )
1375 LPVOID p = HeapReAlloc( heap, flags, lpMem, size );
1376 if (!p)
1378 MESSAGE("Virtual memory exhausted.\n" );
1379 exit(1);
1381 SET_EIP(p);
1382 return p;
1386 /***********************************************************************
1387 * HEAP_strdupA
1389 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1391 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1392 SET_EIP(p);
1393 strcpy( p, str );
1394 return p;
1398 /***********************************************************************
1399 * HEAP_strdupW
1401 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1403 INT len = lstrlenW(str) + 1;
1404 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1405 SET_EIP(p);
1406 lstrcpyW( p, str );
1407 return p;
1411 /***********************************************************************
1412 * HEAP_strdupAtoW
1414 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1416 LPWSTR ret;
1418 if (!str) return NULL;
1419 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1420 SET_EIP(ret);
1421 lstrcpyAtoW( ret, str );
1422 return ret;
1426 /***********************************************************************
1427 * HEAP_strdupWtoA
1429 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1431 LPSTR ret;
1433 if (!str) return NULL;
1434 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1435 SET_EIP(ret);
1436 lstrcpyWtoA( ret, str );
1437 return ret;
1442 /***********************************************************************
1443 * 32-bit local heap functions (Win95; undocumented)
1446 #define HTABLE_SIZE 0x10000
1447 #define HTABLE_PAGESIZE 0x1000
1448 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1450 #include "pshpack1.h"
1451 typedef struct _LOCAL32HEADER
1453 WORD freeListFirst[HTABLE_NPAGES];
1454 WORD freeListSize[HTABLE_NPAGES];
1455 WORD freeListLast[HTABLE_NPAGES];
1457 DWORD selectorTableOffset;
1458 WORD selectorTableSize;
1459 WORD selectorDelta;
1461 DWORD segment;
1462 LPBYTE base;
1464 DWORD limit;
1465 DWORD flags;
1467 DWORD magic;
1468 HANDLE heap;
1470 } LOCAL32HEADER;
1471 #include "poppack.h"
1473 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1475 /***********************************************************************
1476 * Local32Init (KERNEL.208)
1478 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1479 DWORD heapSize, DWORD flags )
1481 DWORD totSize, segSize = 0;
1482 LPBYTE base;
1483 LOCAL32HEADER *header;
1484 HEAP *heap;
1485 WORD *selectorTable;
1486 WORD selectorEven, selectorOdd;
1487 int i, nrBlocks;
1489 /* Determine new heap size */
1491 if ( segment )
1493 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1494 return 0;
1495 else
1496 segSize++;
1499 if ( heapSize == -1L )
1500 heapSize = 1024L*1024L; /* FIXME */
1502 heapSize = (heapSize + 0xffff) & 0xffff0000;
1503 segSize = (segSize + 0x0fff) & 0xfffff000;
1504 totSize = segSize + HTABLE_SIZE + heapSize;
1507 /* Allocate memory and initialize heap */
1509 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1510 return 0;
1512 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1513 MEM_COMMIT, PAGE_READWRITE ) )
1515 VirtualFree( base, 0, MEM_RELEASE );
1516 return 0;
1519 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1520 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1522 VirtualFree( base, 0, MEM_RELEASE );
1523 return 0;
1527 /* Set up header and handle table */
1529 header = (LOCAL32HEADER *)(base + segSize);
1530 header->base = base;
1531 header->limit = HTABLE_PAGESIZE-1;
1532 header->flags = 0;
1533 header->magic = LOCAL32_MAGIC;
1534 header->heap = (HANDLE)heap;
1536 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1537 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1538 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1540 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1541 *(DWORD *)((LPBYTE)header + i) = i+4;
1543 header->freeListFirst[1] = 0xffff;
1546 /* Set up selector table */
1548 nrBlocks = (totSize + 0x7fff) >> 15;
1549 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1550 selectorEven = SELECTOR_AllocBlock( base, totSize,
1551 SEGMENT_DATA, FALSE, FALSE );
1552 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1553 SEGMENT_DATA, FALSE, FALSE );
1555 if ( !selectorTable || !selectorEven || !selectorOdd )
1557 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1558 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1559 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1560 HeapDestroy( header->heap );
1561 VirtualFree( base, 0, MEM_RELEASE );
1562 return 0;
1565 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1566 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1567 header->selectorDelta = selectorEven - selectorOdd;
1568 header->segment = segment? segment : selectorEven;
1570 for (i = 0; i < nrBlocks; i++)
1571 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1572 : selectorEven + ((i >> 1) << __AHSHIFT);
1574 /* Move old segment */
1576 if ( segment )
1578 /* FIXME: This is somewhat ugly and relies on implementation
1579 details about 16-bit global memory handles ... */
1581 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1582 memcpy( base, oldBase, segSize );
1583 GLOBAL_MoveBlock( segment, base, totSize );
1584 HeapFree( SystemHeap, 0, oldBase );
1587 return (HANDLE)header;
1590 /***********************************************************************
1591 * Local32_SearchHandle
1593 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1595 LPDWORD handle;
1597 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1598 handle < (LPDWORD)((LPBYTE)header + header->limit);
1599 handle++)
1601 if (*handle == addr)
1602 return handle;
1605 return NULL;
1608 /***********************************************************************
1609 * Local32_ToHandle
1611 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1612 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1614 *handle = NULL;
1615 *ptr = NULL;
1617 switch (type)
1619 case -2: /* 16:16 pointer, no handles */
1620 *ptr = PTR_SEG_TO_LIN( addr );
1621 *handle = (LPDWORD)*ptr;
1622 break;
1624 case -1: /* 32-bit offset, no handles */
1625 *ptr = header->base + addr;
1626 *handle = (LPDWORD)*ptr;
1627 break;
1629 case 0: /* handle */
1630 if ( addr >= sizeof(LOCAL32HEADER)
1631 && addr < header->limit && !(addr & 3)
1632 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1634 *handle = (LPDWORD)((LPBYTE)header + addr);
1635 *ptr = header->base + **handle;
1637 break;
1639 case 1: /* 16:16 pointer */
1640 *ptr = PTR_SEG_TO_LIN( addr );
1641 *handle = Local32_SearchHandle( header, *ptr - header->base );
1642 break;
1644 case 2: /* 32-bit offset */
1645 *ptr = header->base + addr;
1646 *handle = Local32_SearchHandle( header, *ptr - header->base );
1647 break;
1651 /***********************************************************************
1652 * Local32_FromHandle
1654 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1655 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1657 switch (type)
1659 case -2: /* 16:16 pointer */
1660 case 1:
1662 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1663 DWORD offset = (LPBYTE)ptr - header->base;
1664 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1666 break;
1668 case -1: /* 32-bit offset */
1669 case 2:
1670 *addr = ptr - header->base;
1671 break;
1673 case 0: /* handle */
1674 *addr = (LPBYTE)handle - (LPBYTE)header;
1675 break;
1679 /***********************************************************************
1680 * Local32Alloc (KERNEL.209)
1682 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1684 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1685 LPDWORD handle;
1686 LPBYTE ptr;
1687 DWORD addr;
1689 /* Allocate memory */
1690 ptr = HeapAlloc( header->heap,
1691 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1692 if (!ptr) return 0;
1695 /* Allocate handle if requested */
1696 if (type >= 0)
1698 int page, i;
1700 /* Find first page of handle table with free slots */
1701 for (page = 0; page < HTABLE_NPAGES; page++)
1702 if (header->freeListFirst[page] != 0)
1703 break;
1704 if (page == HTABLE_NPAGES)
1706 WARN("Out of handles!\n" );
1707 HeapFree( header->heap, 0, ptr );
1708 return 0;
1711 /* If virgin page, initialize it */
1712 if (header->freeListFirst[page] == 0xffff)
1714 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1715 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1717 WARN("Cannot grow handle table!\n" );
1718 HeapFree( header->heap, 0, ptr );
1719 return 0;
1722 header->limit += HTABLE_PAGESIZE;
1724 header->freeListFirst[page] = 0;
1725 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1726 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1728 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1729 *(DWORD *)((LPBYTE)header + i) = i+4;
1731 if (page < HTABLE_NPAGES-1)
1732 header->freeListFirst[page+1] = 0xffff;
1735 /* Allocate handle slot from page */
1736 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1737 if (--header->freeListSize[page] == 0)
1738 header->freeListFirst[page] = header->freeListLast[page] = 0;
1739 else
1740 header->freeListFirst[page] = *handle;
1742 /* Store 32-bit offset in handle slot */
1743 *handle = ptr - header->base;
1745 else
1747 handle = (LPDWORD)ptr;
1748 header->flags |= 1;
1752 /* Convert handle to requested output type */
1753 Local32_FromHandle( header, type, &addr, handle, ptr );
1754 return addr;
1757 /***********************************************************************
1758 * Local32ReAlloc (KERNEL.210)
1760 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1761 DWORD size, DWORD flags )
1763 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1764 LPDWORD handle;
1765 LPBYTE ptr;
1767 if (!addr)
1768 return Local32Alloc16( heap, size, type, flags );
1770 /* Retrieve handle and pointer */
1771 Local32_ToHandle( header, type, addr, &handle, &ptr );
1772 if (!handle) return FALSE;
1774 /* Reallocate memory block */
1775 ptr = HeapReAlloc( header->heap,
1776 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1777 ptr, size );
1778 if (!ptr) return 0;
1780 /* Modify handle */
1781 if (type >= 0)
1782 *handle = ptr - header->base;
1783 else
1784 handle = (LPDWORD)ptr;
1786 /* Convert handle to requested output type */
1787 Local32_FromHandle( header, type, &addr, handle, ptr );
1788 return addr;
1791 /***********************************************************************
1792 * Local32Free (KERNEL.211)
1794 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1796 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1797 LPDWORD handle;
1798 LPBYTE ptr;
1800 /* Retrieve handle and pointer */
1801 Local32_ToHandle( header, type, addr, &handle, &ptr );
1802 if (!handle) return FALSE;
1804 /* Free handle if necessary */
1805 if (type >= 0)
1807 int offset = (LPBYTE)handle - (LPBYTE)header;
1808 int page = offset >> 12;
1810 /* Return handle slot to page free list */
1811 if (header->freeListSize[page]++ == 0)
1812 header->freeListFirst[page] = header->freeListLast[page] = offset;
1813 else
1814 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1815 header->freeListLast[page] = offset;
1817 *handle = 0;
1819 /* Shrink handle table when possible */
1820 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1822 if ( VirtualFree( (LPBYTE)header +
1823 (header->limit & ~(HTABLE_PAGESIZE-1)),
1824 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1825 break;
1827 header->limit -= HTABLE_PAGESIZE;
1828 header->freeListFirst[page] = 0xffff;
1829 page--;
1833 /* Free memory */
1834 return HeapFree( header->heap, 0, ptr );
1837 /***********************************************************************
1838 * Local32Translate (KERNEL.213)
1840 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
1842 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1843 LPDWORD handle;
1844 LPBYTE ptr;
1846 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1847 if (!handle) return 0;
1849 Local32_FromHandle( header, type2, &addr, handle, ptr );
1850 return addr;
1853 /***********************************************************************
1854 * Local32Size (KERNEL.214)
1856 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
1858 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1859 LPDWORD handle;
1860 LPBYTE ptr;
1862 Local32_ToHandle( header, type, addr, &handle, &ptr );
1863 if (!handle) return 0;
1865 return HeapSize( header->heap, 0, ptr );
1868 /***********************************************************************
1869 * Local32ValidHandle (KERNEL.215)
1871 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
1873 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1874 LPDWORD handle;
1875 LPBYTE ptr;
1877 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1878 return handle != NULL;
1881 /***********************************************************************
1882 * Local32GetSegment (KERNEL.229)
1884 WORD WINAPI Local32GetSegment16( HANDLE heap )
1886 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1887 return header->segment;
1890 /***********************************************************************
1891 * Local32_GetHeap
1893 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
1895 WORD selector = GlobalHandleToSel16( handle );
1896 DWORD base = GetSelectorBase( selector );
1897 DWORD limit = GetSelectorLimit16( selector );
1899 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
1900 it this way ... */
1902 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1903 return (LOCAL32HEADER *)base;
1905 base += 0x10000;
1906 limit -= 0x10000;
1908 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1909 return (LOCAL32HEADER *)base;
1911 return NULL;
1914 /***********************************************************************
1915 * Local32Info (KERNEL.444) (TOOLHELP.84)
1917 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
1919 SUBHEAP *heapPtr;
1920 LPBYTE ptr;
1921 int i;
1923 LOCAL32HEADER *header = Local32_GetHeap( handle );
1924 if ( !header ) return FALSE;
1926 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
1927 return FALSE;
1929 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
1930 pLocal32Info->dwMemReserved = heapPtr->size;
1931 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
1932 pLocal32Info->dwTotalFree = 0L;
1933 pLocal32Info->dwLargestFreeBlock = 0L;
1935 /* Note: Local32 heaps always have only one subheap! */
1936 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
1937 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
1939 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1941 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1942 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1943 ptr += sizeof(*pArena) + size;
1945 pLocal32Info->dwTotalFree += size;
1946 if ( size > pLocal32Info->dwLargestFreeBlock )
1947 pLocal32Info->dwLargestFreeBlock = size;
1949 else
1951 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1952 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1953 ptr += sizeof(*pArena) + size;
1957 pLocal32Info->dwcFreeHandles = 0;
1958 for ( i = 0; i < HTABLE_NPAGES; i++ )
1960 if ( header->freeListFirst[i] == 0xffff ) break;
1961 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
1963 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
1965 return TRUE;
1968 /***********************************************************************
1969 * Local32First (KERNEL.445) (TOOLHELP.85)
1971 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
1973 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
1974 return FALSE;
1977 /***********************************************************************
1978 * Local32Next (KERNEL.446) (TOOLHELP.86)
1980 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
1982 FIXME("(%p): stub!\n", pLocal32Entry );
1983 return FALSE;