Added support for forwarded ordinals in built-in dlls.
[wine/multimedia.git] / memory / heap.c
blobd8db469f72f62a1d969d6f8a1efb42b46f4bf1d9
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 "debug.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 DUMP( "Heap: %08lx\n", (DWORD)heap );
122 DUMP( "Next: %08lx Sub-heaps: %08lx",
123 (DWORD)heap->next, (DWORD)&heap->subheap );
124 subheap = &heap->subheap;
125 while (subheap->next)
127 DUMP( " -> %08lx", (DWORD)subheap->next );
128 subheap = subheap->next;
131 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
132 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
133 DUMP( "%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 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
144 (DWORD)subheap, subheap->size, subheap->commitSize );
146 DUMP( "\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 DUMP( "%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 DUMP( "%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 DUMP( "%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 DUMP( "\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(heap, "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 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
267 if (size > subheap->size) size = subheap->size;
268 if (size <= subheap->commitSize) return TRUE;
269 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
270 size - subheap->commitSize, MEM_COMMIT,
271 PAGE_EXECUTE_READWRITE))
273 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
274 size - subheap->commitSize,
275 (DWORD)((char *)subheap + subheap->commitSize),
276 (DWORD)subheap->heap );
277 return FALSE;
279 subheap->commitSize = size;
280 return TRUE;
284 /***********************************************************************
285 * HEAP_Decommit
287 * If possible, decommit the heap storage from (including) 'ptr'.
289 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
291 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
292 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
293 if (size >= subheap->commitSize) return TRUE;
294 if (!VirtualFree( (char *)subheap + size,
295 subheap->commitSize - size, MEM_DECOMMIT ))
297 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
298 subheap->commitSize - size,
299 (DWORD)((char *)subheap + size),
300 (DWORD)subheap->heap );
301 return FALSE;
303 subheap->commitSize = size;
304 return TRUE;
308 /***********************************************************************
309 * HEAP_CreateFreeBlock
311 * Create a free block at a specified address. 'size' is the size of the
312 * whole block, including the new arena.
314 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
316 ARENA_FREE *pFree;
318 /* Create a free arena */
320 pFree = (ARENA_FREE *)ptr;
321 pFree->threadId = GetCurrentTask();
322 pFree->magic = ARENA_FREE_MAGIC;
324 /* If debugging, erase the freed block content */
326 if (TRACE_ON(heap))
328 char *pEnd = (char *)ptr + size;
329 if (pEnd > (char *)subheap + subheap->commitSize)
330 pEnd = (char *)subheap + subheap->commitSize;
331 if (pEnd > (char *)(pFree + 1))
332 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
335 /* Check if next block is free also */
337 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
338 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
340 /* Remove the next arena from the free list */
341 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
342 pNext->next->prev = pNext->prev;
343 pNext->prev->next = pNext->next;
344 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
345 if (TRACE_ON(heap))
346 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
349 /* Set the next block PREV_FREE flag and pointer */
351 if ((char *)ptr + size < (char *)subheap + subheap->size)
353 DWORD *pNext = (DWORD *)((char *)ptr + size);
354 *pNext |= ARENA_FLAG_PREV_FREE;
355 *(ARENA_FREE **)(pNext - 1) = pFree;
358 /* Last, insert the new block into the free list */
360 pFree->size = size - sizeof(*pFree);
361 HEAP_InsertFreeBlock( subheap->heap, pFree );
365 /***********************************************************************
366 * HEAP_MakeInUseBlockFree
368 * Turn an in-use block into a free block. Can also decommit the end of
369 * the heap, and possibly even free the sub-heap altogether.
371 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
373 ARENA_FREE *pFree;
374 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
376 /* Check if we can merge with previous block */
378 if (pArena->size & ARENA_FLAG_PREV_FREE)
380 pFree = *((ARENA_FREE **)pArena - 1);
381 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
382 /* Remove it from the free list */
383 pFree->next->prev = pFree->prev;
384 pFree->prev->next = pFree->next;
386 else pFree = (ARENA_FREE *)pArena;
388 /* Create a free block */
390 HEAP_CreateFreeBlock( subheap, pFree, size );
391 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
392 if ((char *)pFree + size < (char *)subheap + subheap->size)
393 return; /* Not the last block, so nothing more to do */
395 /* Free the whole sub-heap if it's empty and not the original one */
397 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
398 (subheap != &subheap->heap->subheap))
400 SUBHEAP *pPrev = &subheap->heap->subheap;
401 /* Remove the free block from the list */
402 pFree->next->prev = pFree->prev;
403 pFree->prev->next = pFree->next;
404 /* Remove the subheap from the list */
405 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
406 if (pPrev) pPrev->next = subheap->next;
407 /* Free the memory */
408 subheap->magic = 0;
409 if (subheap->selector) FreeSelector16( subheap->selector );
410 VirtualFree( subheap, 0, MEM_RELEASE );
411 return;
414 /* Decommit the end of the heap */
416 HEAP_Decommit( subheap, pFree + 1 );
420 /***********************************************************************
421 * HEAP_ShrinkBlock
423 * Shrink an in-use block.
425 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
427 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
429 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
430 (pArena->size & ARENA_SIZE_MASK) - size );
431 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
433 else
435 /* Turn off PREV_FREE flag in next block */
436 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
437 if (pNext < (char *)subheap + subheap->size)
438 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
442 /***********************************************************************
443 * HEAP_InitSubHeap
445 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
446 DWORD commitSize, DWORD totalSize )
448 SUBHEAP *subheap = (SUBHEAP *)address;
449 WORD selector = 0;
450 FREE_LIST_ENTRY *pEntry;
451 int i;
453 /* Commit memory */
455 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
457 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
458 commitSize, (DWORD)address );
459 return FALSE;
462 /* Allocate a selector if needed */
464 if (flags & HEAP_WINE_SEGPTR)
466 selector = SELECTOR_AllocBlock( address, totalSize,
467 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
468 ? SEGMENT_CODE : SEGMENT_DATA,
469 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
470 if (!selector)
472 ERR(heap, "Could not allocate selector\n" );
473 return FALSE;
477 /* Fill the sub-heap structure */
479 subheap->heap = heap;
480 subheap->selector = selector;
481 subheap->size = totalSize;
482 subheap->commitSize = commitSize;
483 subheap->magic = SUBHEAP_MAGIC;
485 if ( subheap != (SUBHEAP *)heap )
487 /* If this is a secondary subheap, insert it into list */
489 subheap->headerSize = sizeof(SUBHEAP);
490 subheap->next = heap->subheap.next;
491 heap->subheap.next = subheap;
493 else
495 /* If this is a primary subheap, initialize main heap */
497 subheap->headerSize = sizeof(HEAP);
498 subheap->next = NULL;
499 heap->next = NULL;
500 heap->flags = flags;
501 heap->magic = HEAP_MAGIC;
503 /* Build the free lists */
505 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
507 pEntry->size = HEAP_freeListSizes[i];
508 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
509 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
510 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
511 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
512 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
513 pEntry->arena.threadId = 0;
514 pEntry->arena.magic = ARENA_FREE_MAGIC;
517 /* Initialize critical section */
519 InitializeCriticalSection( &heap->critSection );
520 if (!SystemHeap) /* System heap critical section has to be global */
521 MakeCriticalSectionGlobal( &heap->critSection );
524 /* Create the first free block */
526 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
527 subheap->size - subheap->headerSize );
529 return TRUE;
532 /***********************************************************************
533 * HEAP_CreateSubHeap
535 * Create a sub-heap of the given size.
536 * If heap == NULL, creates a main heap.
538 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
539 DWORD commitSize, DWORD totalSize )
541 LPVOID address;
543 /* Round-up sizes on a 64K boundary */
545 if (flags & HEAP_WINE_SEGPTR)
547 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
549 else
551 totalSize = (totalSize + 0xffff) & 0xffff0000;
552 commitSize = (commitSize + 0xffff) & 0xffff0000;
553 if (!commitSize) commitSize = 0x10000;
554 if (totalSize < commitSize) totalSize = commitSize;
557 /* Allocate the memory block */
559 if (!(address = VirtualAlloc( NULL, totalSize,
560 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
562 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
563 totalSize );
564 return NULL;
567 /* Initialize subheap */
569 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
570 address, flags, commitSize, totalSize ))
572 VirtualFree( address, 0, MEM_RELEASE );
573 return NULL;
576 return (SUBHEAP *)address;
580 /***********************************************************************
581 * HEAP_FindFreeBlock
583 * Find a free block at least as large as the requested size, and make sure
584 * the requested size is committed.
586 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
587 SUBHEAP **ppSubHeap )
589 SUBHEAP *subheap;
590 ARENA_FREE *pArena;
591 FREE_LIST_ENTRY *pEntry = heap->freeList;
593 /* Find a suitable free list, and in it find a block large enough */
595 while (pEntry->size < size) pEntry++;
596 pArena = pEntry->arena.next;
597 while (pArena != &heap->freeList[0].arena)
599 if (pArena->size > size)
601 subheap = HEAP_FindSubHeap( heap, pArena );
602 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
603 + size + HEAP_MIN_BLOCK_SIZE))
604 return NULL;
605 *ppSubHeap = subheap;
606 return pArena;
609 pArena = pArena->next;
612 /* If no block was found, attempt to grow the heap */
614 if (!(heap->flags & HEAP_GROWABLE))
616 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
617 (DWORD)heap, size );
618 return NULL;
620 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
621 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
622 MAX( HEAP_DEF_SIZE, size ) )))
623 return NULL;
625 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
626 (DWORD)subheap, size, (DWORD)heap );
628 *ppSubHeap = subheap;
629 return (ARENA_FREE *)(subheap + 1);
633 /***********************************************************************
634 * HEAP_IsValidArenaPtr
636 * Check that the pointer is inside the range possible for arenas.
638 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
640 int i;
641 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
642 if (!subheap) return FALSE;
643 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
644 if (subheap != &heap->subheap) return FALSE;
645 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
646 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
647 return FALSE;
651 /***********************************************************************
652 * HEAP_ValidateFreeArena
654 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
656 char *heapEnd = (char *)subheap + subheap->size;
658 /* Check magic number */
659 if (pArena->magic != ARENA_FREE_MAGIC)
661 ERR(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
662 (DWORD)subheap->heap, (DWORD)pArena );
663 return FALSE;
665 /* Check size flags */
666 if (!(pArena->size & ARENA_FLAG_FREE) ||
667 (pArena->size & ARENA_FLAG_PREV_FREE))
669 ERR(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
670 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
672 /* Check arena size */
673 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
675 ERR(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
676 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
677 return FALSE;
679 /* Check that next pointer is valid */
680 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
682 ERR(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
683 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
684 return FALSE;
686 /* Check that next arena is free */
687 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
688 (pArena->next->magic != ARENA_FREE_MAGIC))
690 ERR(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
691 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
692 return FALSE;
694 /* Check that prev pointer is valid */
695 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
697 ERR(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
698 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
699 return FALSE;
701 /* Check that prev arena is free */
702 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
703 (pArena->prev->magic != ARENA_FREE_MAGIC))
705 ERR(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
706 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
707 return FALSE;
709 /* Check that next block has PREV_FREE flag */
710 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
712 if (!(*(DWORD *)((char *)(pArena + 1) +
713 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
715 ERR(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
716 (DWORD)subheap->heap, (DWORD)pArena );
717 return FALSE;
719 /* Check next block back pointer */
720 if (*((ARENA_FREE **)((char *)(pArena + 1) +
721 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
723 ERR(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
724 (DWORD)subheap->heap, (DWORD)pArena,
725 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
726 return FALSE;
729 return TRUE;
733 /***********************************************************************
734 * HEAP_ValidateInUseArena
736 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
738 char *heapEnd = (char *)subheap + subheap->size;
740 /* Check magic number */
741 if (pArena->magic != ARENA_INUSE_MAGIC)
743 ERR(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
744 (DWORD)subheap->heap, (DWORD)pArena );
745 return FALSE;
747 /* Check size flags */
748 if (pArena->size & ARENA_FLAG_FREE)
750 ERR(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
751 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
753 /* Check arena size */
754 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
756 ERR(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
757 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
758 return FALSE;
760 /* Check next arena PREV_FREE flag */
761 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
762 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
764 ERR(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
765 (DWORD)subheap->heap, (DWORD)pArena );
766 return FALSE;
768 /* Check prev free arena */
769 if (pArena->size & ARENA_FLAG_PREV_FREE)
771 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
772 /* Check prev pointer */
773 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
775 ERR(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
776 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
777 return FALSE;
779 /* Check that prev arena is free */
780 if (!(pPrev->size & ARENA_FLAG_FREE) ||
781 (pPrev->magic != ARENA_FREE_MAGIC))
783 ERR(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
784 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
785 return FALSE;
787 /* Check that prev arena is really the previous block */
788 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
790 ERR(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
791 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
792 return FALSE;
795 return TRUE;
799 /***********************************************************************
800 * HEAP_IsInsideHeap
801 * Checks whether the pointer points to a block inside a given heap.
803 * NOTES
804 * Should this return BOOL32?
806 * RETURNS
807 * !0: Success
808 * 0: Failure
810 int HEAP_IsInsideHeap(
811 HANDLE heap, /* [in] Heap */
812 DWORD flags, /* [in] Flags */
813 LPCVOID ptr /* [in] Pointer */
815 HEAP *heapPtr = HEAP_GetPtr( heap );
816 SUBHEAP *subheap;
817 int ret;
819 /* Validate the parameters */
821 if (!heapPtr) return 0;
822 flags |= heapPtr->flags;
823 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
824 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
825 (((char *)ptr >= (char *)subheap + subheap->headerSize
826 + sizeof(ARENA_INUSE))));
827 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
828 return ret;
832 /***********************************************************************
833 * HEAP_GetSegptr
835 * Transform a linear pointer into a SEGPTR. The pointer must have been
836 * allocated from a HEAP_WINE_SEGPTR heap.
838 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
840 HEAP *heapPtr = HEAP_GetPtr( heap );
841 SUBHEAP *subheap;
842 SEGPTR ret;
844 /* Validate the parameters */
846 if (!heapPtr) return 0;
847 flags |= heapPtr->flags;
848 if (!(flags & HEAP_WINE_SEGPTR))
850 ERR(heap, "Heap %08x is not a SEGPTR heap\n",
851 heap );
852 return 0;
854 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
856 /* Get the subheap */
858 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
860 ERR(heap, "%p is not inside heap %08x\n",
861 ptr, heap );
862 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
863 return 0;
866 /* Build the SEGPTR */
868 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
869 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
870 return ret;
874 /***********************************************************************
875 * HeapCreate (KERNEL32.336)
876 * RETURNS
877 * Handle of heap: Success
878 * NULL: Failure
880 HANDLE WINAPI HeapCreate(
881 DWORD flags, /* [in] Heap allocation flag */
882 DWORD initialSize, /* [in] Initial heap size */
883 DWORD maxSize /* [in] Maximum heap size */
885 SUBHEAP *subheap;
887 /* Allocate the heap block */
889 if (!maxSize)
891 maxSize = HEAP_DEF_SIZE;
892 flags |= HEAP_GROWABLE;
894 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
896 SetLastError( ERROR_OUTOFMEMORY );
897 return 0;
900 return (HANDLE)subheap;
903 /***********************************************************************
904 * HeapDestroy (KERNEL32.337)
905 * RETURNS
906 * TRUE: Success
907 * FALSE: Failure
909 BOOL WINAPI HeapDestroy(
910 HANDLE heap /* [in] Handle of heap */
912 HEAP *heapPtr = HEAP_GetPtr( heap );
913 SUBHEAP *subheap;
915 TRACE(heap, "%08x\n", heap );
916 if (!heapPtr) return FALSE;
918 DeleteCriticalSection( &heapPtr->critSection );
919 subheap = &heapPtr->subheap;
920 while (subheap)
922 SUBHEAP *next = subheap->next;
923 if (subheap->selector) FreeSelector16( subheap->selector );
924 VirtualFree( subheap, 0, MEM_RELEASE );
925 subheap = next;
927 return TRUE;
931 /***********************************************************************
932 * HeapAlloc (KERNEL32.334)
933 * RETURNS
934 * Pointer to allocated memory block
935 * NULL: Failure
937 LPVOID WINAPI HeapAlloc(
938 HANDLE heap, /* [in] Handle of private heap block */
939 DWORD flags, /* [in] Heap allocation control flags */
940 DWORD size /* [in] Number of bytes to allocate */
942 ARENA_FREE *pArena;
943 ARENA_INUSE *pInUse;
944 SUBHEAP *subheap;
945 HEAP *heapPtr = HEAP_GetPtr( heap );
947 /* Validate the parameters */
949 if (!heapPtr) return NULL;
950 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
951 flags |= heapPtr->flags;
952 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
953 size = (size + 3) & ~3;
954 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
956 /* Locate a suitable free block */
958 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
960 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
961 heap, flags, size );
962 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
963 SetLastError( ERROR_COMMITMENT_LIMIT );
964 return NULL;
967 /* Remove the arena from the free list */
969 pArena->next->prev = pArena->prev;
970 pArena->prev->next = pArena->next;
972 /* Build the in-use arena */
974 pInUse = (ARENA_INUSE *)pArena;
975 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
976 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
977 pInUse->callerEIP = GET_EIP();
978 pInUse->threadId = GetCurrentTask();
979 pInUse->magic = ARENA_INUSE_MAGIC;
981 /* Shrink the block */
983 HEAP_ShrinkBlock( subheap, pInUse, size );
985 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
986 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
988 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
990 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
991 heap, flags, size, (DWORD)(pInUse + 1) );
992 return (LPVOID)(pInUse + 1);
996 /***********************************************************************
997 * HeapFree (KERNEL32.338)
998 * RETURNS
999 * TRUE: Success
1000 * FALSE: Failure
1002 BOOL WINAPI HeapFree(
1003 HANDLE heap, /* [in] Handle of heap */
1004 DWORD flags, /* [in] Heap freeing flags */
1005 LPVOID ptr /* [in] Address of memory to free */
1007 ARENA_INUSE *pInUse;
1008 SUBHEAP *subheap;
1009 HEAP *heapPtr = HEAP_GetPtr( heap );
1011 /* Validate the parameters */
1013 if (!heapPtr) return FALSE;
1014 flags &= HEAP_NO_SERIALIZE;
1015 flags |= heapPtr->flags;
1016 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1017 if (!ptr)
1019 WARN(heap, "(%08x,%08lx,%08lx): asked to free NULL\n",
1020 heap, flags, (DWORD)ptr );
1022 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1024 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1025 SetLastError( ERROR_INVALID_PARAMETER );
1026 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1027 heap, flags, (DWORD)ptr );
1028 return FALSE;
1031 /* Turn the block into a free block */
1033 pInUse = (ARENA_INUSE *)ptr - 1;
1034 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1035 HEAP_MakeInUseBlockFree( subheap, pInUse );
1037 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1038 /* SetLastError( 0 ); */
1040 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1041 heap, flags, (DWORD)ptr );
1042 return TRUE;
1046 /***********************************************************************
1047 * HeapReAlloc (KERNEL32.340)
1048 * RETURNS
1049 * Pointer to reallocated memory block
1050 * NULL: Failure
1052 LPVOID WINAPI HeapReAlloc(
1053 HANDLE heap, /* [in] Handle of heap block */
1054 DWORD flags, /* [in] Heap reallocation flags */
1055 LPVOID ptr, /* [in] Address of memory to reallocate */
1056 DWORD size /* [in] Number of bytes to reallocate */
1058 ARENA_INUSE *pArena;
1059 DWORD oldSize;
1060 HEAP *heapPtr;
1061 SUBHEAP *subheap;
1063 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1064 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1066 /* Validate the parameters */
1068 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1069 HEAP_REALLOC_IN_PLACE_ONLY;
1070 flags |= heapPtr->flags;
1071 size = (size + 3) & ~3;
1072 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1074 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1075 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1077 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1078 SetLastError( ERROR_INVALID_PARAMETER );
1079 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1080 heap, flags, (DWORD)ptr, size );
1081 return NULL;
1084 /* Check if we need to grow the block */
1086 pArena = (ARENA_INUSE *)ptr - 1;
1087 pArena->threadId = GetCurrentTask();
1088 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1089 oldSize = (pArena->size & ARENA_SIZE_MASK);
1090 if (size > oldSize)
1092 char *pNext = (char *)(pArena + 1) + oldSize;
1093 if ((pNext < (char *)subheap + subheap->size) &&
1094 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1095 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1097 /* The next block is free and large enough */
1098 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1099 pFree->next->prev = pFree->prev;
1100 pFree->prev->next = pFree->next;
1101 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1102 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1103 + size + HEAP_MIN_BLOCK_SIZE))
1105 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1106 SetLastError( ERROR_OUTOFMEMORY );
1107 return NULL;
1109 HEAP_ShrinkBlock( subheap, pArena, size );
1111 else /* Do it the hard way */
1113 ARENA_FREE *pNew;
1114 ARENA_INUSE *pInUse;
1115 SUBHEAP *newsubheap;
1117 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1118 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1120 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1121 SetLastError( ERROR_OUTOFMEMORY );
1122 return NULL;
1125 /* Build the in-use arena */
1127 pNew->next->prev = pNew->prev;
1128 pNew->prev->next = pNew->next;
1129 pInUse = (ARENA_INUSE *)pNew;
1130 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1131 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1132 pInUse->threadId = GetCurrentTask();
1133 pInUse->magic = ARENA_INUSE_MAGIC;
1134 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1135 memcpy( pInUse + 1, pArena + 1, oldSize );
1137 /* Free the previous block */
1139 HEAP_MakeInUseBlockFree( subheap, pArena );
1140 subheap = newsubheap;
1141 pArena = pInUse;
1144 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1146 /* Clear the extra bytes if needed */
1148 if (size > oldSize)
1150 if (flags & HEAP_ZERO_MEMORY)
1151 memset( (char *)(pArena + 1) + oldSize, 0,
1152 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1153 else if (TRACE_ON(heap))
1154 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1155 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1158 /* Return the new arena */
1160 pArena->callerEIP = GET_EIP();
1161 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1163 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1164 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1165 return (LPVOID)(pArena + 1);
1169 /***********************************************************************
1170 * HeapCompact (KERNEL32.335)
1172 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1174 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1175 return 0;
1179 /***********************************************************************
1180 * HeapLock (KERNEL32.339)
1181 * Attempts to acquire the critical section object for a specified heap.
1183 * RETURNS
1184 * TRUE: Success
1185 * FALSE: Failure
1187 BOOL WINAPI HeapLock(
1188 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1190 HEAP *heapPtr = HEAP_GetPtr( heap );
1191 if (!heapPtr) return FALSE;
1192 EnterCriticalSection( &heapPtr->critSection );
1193 return TRUE;
1197 /***********************************************************************
1198 * HeapUnlock (KERNEL32.342)
1199 * Releases ownership of the critical section object.
1201 * RETURNS
1202 * TRUE: Success
1203 * FALSE: Failure
1205 BOOL WINAPI HeapUnlock(
1206 HANDLE heap /* [in] Handle to the heap to unlock */
1208 HEAP *heapPtr = HEAP_GetPtr( heap );
1209 if (!heapPtr) return FALSE;
1210 LeaveCriticalSection( &heapPtr->critSection );
1211 return TRUE;
1215 /***********************************************************************
1216 * HeapSize (KERNEL32.341)
1217 * RETURNS
1218 * Size in bytes of allocated memory
1219 * 0xffffffff: Failure
1221 DWORD WINAPI HeapSize(
1222 HANDLE heap, /* [in] Handle of heap */
1223 DWORD flags, /* [in] Heap size control flags */
1224 LPVOID ptr /* [in] Address of memory to return size for */
1226 DWORD ret;
1227 HEAP *heapPtr = HEAP_GetPtr( heap );
1229 if (!heapPtr) return FALSE;
1230 flags &= HEAP_NO_SERIALIZE;
1231 flags |= heapPtr->flags;
1232 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1233 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1235 SetLastError( ERROR_INVALID_PARAMETER );
1236 ret = 0xffffffff;
1238 else
1240 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1241 ret = pArena->size & ARENA_SIZE_MASK;
1243 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1245 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1246 heap, flags, (DWORD)ptr, ret );
1247 return ret;
1251 /***********************************************************************
1252 * HeapValidate (KERNEL32.343)
1253 * Validates a specified heap.
1255 * NOTES
1256 * Flags is ignored.
1258 * RETURNS
1259 * TRUE: Success
1260 * FALSE: Failure
1262 BOOL WINAPI HeapValidate(
1263 HANDLE heap, /* [in] Handle to the heap */
1264 DWORD flags, /* [in] Bit flags that control access during operation */
1265 LPCVOID block /* [in] Optional pointer to memory block to validate */
1267 SUBHEAP *subheap;
1268 HEAP *heapPtr = (HEAP *)(heap);
1269 BOOL ret = TRUE;
1271 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1273 ERR(heap, "Invalid heap %08x!\n", heap );
1274 return FALSE;
1277 flags &= HEAP_NO_SERIALIZE;
1278 flags |= heapPtr->flags;
1279 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1280 if (!(flags & HEAP_NO_SERIALIZE))
1281 EnterCriticalSection( &heapPtr->critSection );
1282 if (block)
1284 /* Only check this single memory block */
1285 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1286 ((char *)block < (char *)subheap + subheap->headerSize
1287 + sizeof(ARENA_INUSE)))
1289 ERR(heap, "Heap %08lx: block %08lx is not inside heap\n",
1290 (DWORD)heap, (DWORD)block );
1291 ret = FALSE;
1292 } else
1293 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1295 if (!(flags & HEAP_NO_SERIALIZE))
1296 LeaveCriticalSection( &heapPtr->critSection );
1297 return ret;
1300 subheap = &heapPtr->subheap;
1301 while (subheap && ret)
1303 char *ptr = (char *)subheap + subheap->headerSize;
1304 while (ptr < (char *)subheap + subheap->size)
1306 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1308 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1309 ret = FALSE;
1310 break;
1312 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1314 else
1316 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr )) {
1317 ret = FALSE;
1318 break;
1320 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1323 subheap = subheap->next;
1325 if (!(flags & HEAP_NO_SERIALIZE))
1326 LeaveCriticalSection( &heapPtr->critSection );
1327 return ret;
1331 /***********************************************************************
1332 * HeapWalk (KERNEL32.344)
1333 * Enumerates the memory blocks in a specified heap.
1335 * RETURNS
1336 * TRUE: Success
1337 * FALSE: Failure
1339 BOOL WINAPI HeapWalk(
1340 HANDLE heap, /* [in] Handle to heap to enumerate */
1341 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1343 FIXME(heap, "(%08x): stub.\n", heap );
1344 return FALSE;
1348 /***********************************************************************
1349 * HEAP_xalloc
1351 * Same as HeapAlloc(), but die on failure.
1353 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1355 LPVOID p = HeapAlloc( heap, flags, size );
1356 if (!p)
1358 MSG("Virtual memory exhausted.\n" );
1359 exit(1);
1361 SET_EIP(p);
1362 return p;
1366 /***********************************************************************
1367 * HEAP_xrealloc
1369 * Same as HeapReAlloc(), but die on failure.
1371 LPVOID HEAP_xrealloc( HANDLE heap, DWORD flags, LPVOID lpMem, DWORD size )
1373 LPVOID p = HeapReAlloc( heap, flags, lpMem, size );
1374 if (!p)
1376 MSG("Virtual memory exhausted.\n" );
1377 exit(1);
1379 SET_EIP(p);
1380 return p;
1384 /***********************************************************************
1385 * HEAP_strdupA
1387 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1389 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1390 SET_EIP(p);
1391 strcpy( p, str );
1392 return p;
1396 /***********************************************************************
1397 * HEAP_strdupW
1399 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1401 INT len = lstrlenW(str) + 1;
1402 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1403 SET_EIP(p);
1404 lstrcpyW( p, str );
1405 return p;
1409 /***********************************************************************
1410 * HEAP_strdupAtoW
1412 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1414 LPWSTR ret;
1416 if (!str) return NULL;
1417 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1418 SET_EIP(ret);
1419 lstrcpyAtoW( ret, str );
1420 return ret;
1424 /***********************************************************************
1425 * HEAP_strdupWtoA
1427 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1429 LPSTR ret;
1431 if (!str) return NULL;
1432 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1433 SET_EIP(ret);
1434 lstrcpyWtoA( ret, str );
1435 return ret;
1440 /***********************************************************************
1441 * 32-bit local heap functions (Win95; undocumented)
1444 #define HTABLE_SIZE 0x10000
1445 #define HTABLE_PAGESIZE 0x1000
1446 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1448 #include "pshpack1.h"
1449 typedef struct _LOCAL32HEADER
1451 WORD freeListFirst[HTABLE_NPAGES];
1452 WORD freeListSize[HTABLE_NPAGES];
1453 WORD freeListLast[HTABLE_NPAGES];
1455 DWORD selectorTableOffset;
1456 WORD selectorTableSize;
1457 WORD selectorDelta;
1459 DWORD segment;
1460 LPBYTE base;
1462 DWORD limit;
1463 DWORD flags;
1465 DWORD magic;
1466 HANDLE heap;
1468 } LOCAL32HEADER;
1469 #include "poppack.h"
1471 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1473 /***********************************************************************
1474 * Local32Init (KERNEL.208)
1476 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1477 DWORD heapSize, DWORD flags )
1479 DWORD totSize, segSize = 0;
1480 LPBYTE base;
1481 LOCAL32HEADER *header;
1482 HEAP *heap;
1483 WORD *selectorTable;
1484 WORD selectorEven, selectorOdd;
1485 int i, nrBlocks;
1487 /* Determine new heap size */
1489 if ( segment )
1491 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1492 return 0;
1493 else
1494 segSize++;
1497 if ( heapSize == -1L )
1498 heapSize = 1024L*1024L; /* FIXME */
1500 heapSize = (heapSize + 0xffff) & 0xffff0000;
1501 segSize = (segSize + 0x0fff) & 0xfffff000;
1502 totSize = segSize + HTABLE_SIZE + heapSize;
1505 /* Allocate memory and initialize heap */
1507 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1508 return 0;
1510 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1511 MEM_COMMIT, PAGE_READWRITE ) )
1513 VirtualFree( base, 0, MEM_RELEASE );
1514 return 0;
1517 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1518 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1520 VirtualFree( base, 0, MEM_RELEASE );
1521 return 0;
1525 /* Set up header and handle table */
1527 header = (LOCAL32HEADER *)(base + segSize);
1528 header->base = base;
1529 header->limit = HTABLE_PAGESIZE-1;
1530 header->flags = 0;
1531 header->magic = LOCAL32_MAGIC;
1532 header->heap = (HANDLE)heap;
1534 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1535 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1536 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1538 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1539 *(DWORD *)((LPBYTE)header + i) = i+4;
1541 header->freeListFirst[1] = 0xffff;
1544 /* Set up selector table */
1546 nrBlocks = (totSize + 0x7fff) >> 15;
1547 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1548 selectorEven = SELECTOR_AllocBlock( base, totSize,
1549 SEGMENT_DATA, FALSE, FALSE );
1550 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1551 SEGMENT_DATA, FALSE, FALSE );
1553 if ( !selectorTable || !selectorEven || !selectorOdd )
1555 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1556 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1557 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1558 HeapDestroy( header->heap );
1559 VirtualFree( base, 0, MEM_RELEASE );
1560 return 0;
1563 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1564 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1565 header->selectorDelta = selectorEven - selectorOdd;
1566 header->segment = segment? segment : selectorEven;
1568 for (i = 0; i < nrBlocks; i++)
1569 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1570 : selectorEven + ((i >> 1) << __AHSHIFT);
1572 /* Move old segment */
1574 if ( segment )
1576 /* FIXME: This is somewhat ugly and relies on implementation
1577 details about 16-bit global memory handles ... */
1579 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1580 memcpy( base, oldBase, segSize );
1581 GLOBAL_MoveBlock( segment, base, totSize );
1582 HeapFree( SystemHeap, 0, oldBase );
1585 return (HANDLE)header;
1588 /***********************************************************************
1589 * Local32_SearchHandle
1591 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1593 LPDWORD handle;
1595 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1596 handle < (LPDWORD)((LPBYTE)header + header->limit);
1597 handle++)
1599 if (*handle == addr)
1600 return handle;
1603 return NULL;
1606 /***********************************************************************
1607 * Local32_ToHandle
1609 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1610 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1612 *handle = NULL;
1613 *ptr = NULL;
1615 switch (type)
1617 case -2: /* 16:16 pointer, no handles */
1618 *ptr = PTR_SEG_TO_LIN( addr );
1619 *handle = (LPDWORD)*ptr;
1620 break;
1622 case -1: /* 32-bit offset, no handles */
1623 *ptr = header->base + addr;
1624 *handle = (LPDWORD)*ptr;
1625 break;
1627 case 0: /* handle */
1628 if ( addr >= sizeof(LOCAL32HEADER)
1629 && addr < header->limit && !(addr & 3)
1630 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1632 *handle = (LPDWORD)((LPBYTE)header + addr);
1633 *ptr = header->base + **handle;
1635 break;
1637 case 1: /* 16:16 pointer */
1638 *ptr = PTR_SEG_TO_LIN( addr );
1639 *handle = Local32_SearchHandle( header, *ptr - header->base );
1640 break;
1642 case 2: /* 32-bit offset */
1643 *ptr = header->base + addr;
1644 *handle = Local32_SearchHandle( header, *ptr - header->base );
1645 break;
1649 /***********************************************************************
1650 * Local32_FromHandle
1652 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1653 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1655 switch (type)
1657 case -2: /* 16:16 pointer */
1658 case 1:
1660 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1661 DWORD offset = (LPBYTE)ptr - header->base;
1662 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1664 break;
1666 case -1: /* 32-bit offset */
1667 case 2:
1668 *addr = ptr - header->base;
1669 break;
1671 case 0: /* handle */
1672 *addr = (LPBYTE)handle - (LPBYTE)header;
1673 break;
1677 /***********************************************************************
1678 * Local32Alloc (KERNEL.209)
1680 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1682 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1683 LPDWORD handle;
1684 LPBYTE ptr;
1685 DWORD addr;
1687 /* Allocate memory */
1688 ptr = HeapAlloc( header->heap,
1689 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1690 if (!ptr) return 0;
1693 /* Allocate handle if requested */
1694 if (type >= 0)
1696 int page, i;
1698 /* Find first page of handle table with free slots */
1699 for (page = 0; page < HTABLE_NPAGES; page++)
1700 if (header->freeListFirst[page] != 0)
1701 break;
1702 if (page == HTABLE_NPAGES)
1704 WARN( heap, "Out of handles!\n" );
1705 HeapFree( header->heap, 0, ptr );
1706 return 0;
1709 /* If virgin page, initialize it */
1710 if (header->freeListFirst[page] == 0xffff)
1712 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1713 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1715 WARN( heap, "Cannot grow handle table!\n" );
1716 HeapFree( header->heap, 0, ptr );
1717 return 0;
1720 header->limit += HTABLE_PAGESIZE;
1722 header->freeListFirst[page] = 0;
1723 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1724 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1726 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1727 *(DWORD *)((LPBYTE)header + i) = i+4;
1729 if (page < HTABLE_NPAGES-1)
1730 header->freeListFirst[page+1] = 0xffff;
1733 /* Allocate handle slot from page */
1734 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1735 if (--header->freeListSize[page] == 0)
1736 header->freeListFirst[page] = header->freeListLast[page] = 0;
1737 else
1738 header->freeListFirst[page] = *handle;
1740 /* Store 32-bit offset in handle slot */
1741 *handle = ptr - header->base;
1743 else
1745 handle = (LPDWORD)ptr;
1746 header->flags |= 1;
1750 /* Convert handle to requested output type */
1751 Local32_FromHandle( header, type, &addr, handle, ptr );
1752 return addr;
1755 /***********************************************************************
1756 * Local32ReAlloc (KERNEL.210)
1758 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1759 DWORD size, DWORD flags )
1761 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1762 LPDWORD handle;
1763 LPBYTE ptr;
1765 if (!addr)
1766 return Local32Alloc16( heap, size, type, flags );
1768 /* Retrieve handle and pointer */
1769 Local32_ToHandle( header, type, addr, &handle, &ptr );
1770 if (!handle) return FALSE;
1772 /* Reallocate memory block */
1773 ptr = HeapReAlloc( header->heap,
1774 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1775 ptr, size );
1776 if (!ptr) return 0;
1778 /* Modify handle */
1779 if (type >= 0)
1780 *handle = ptr - header->base;
1781 else
1782 handle = (LPDWORD)ptr;
1784 /* Convert handle to requested output type */
1785 Local32_FromHandle( header, type, &addr, handle, ptr );
1786 return addr;
1789 /***********************************************************************
1790 * Local32Free (KERNEL.211)
1792 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1794 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1795 LPDWORD handle;
1796 LPBYTE ptr;
1798 /* Retrieve handle and pointer */
1799 Local32_ToHandle( header, type, addr, &handle, &ptr );
1800 if (!handle) return FALSE;
1802 /* Free handle if necessary */
1803 if (type >= 0)
1805 int offset = (LPBYTE)handle - (LPBYTE)header;
1806 int page = offset >> 12;
1808 /* Return handle slot to page free list */
1809 if (header->freeListSize[page]++ == 0)
1810 header->freeListFirst[page] = header->freeListLast[page] = offset;
1811 else
1812 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1813 header->freeListLast[page] = offset;
1815 *handle = 0;
1817 /* Shrink handle table when possible */
1818 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1820 if ( VirtualFree( (LPBYTE)header +
1821 (header->limit & ~(HTABLE_PAGESIZE-1)),
1822 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1823 break;
1825 header->limit -= HTABLE_PAGESIZE;
1826 header->freeListFirst[page] = 0xffff;
1827 page--;
1831 /* Free memory */
1832 return HeapFree( header->heap, 0, ptr );
1835 /***********************************************************************
1836 * Local32Translate (KERNEL.213)
1838 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
1840 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1841 LPDWORD handle;
1842 LPBYTE ptr;
1844 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1845 if (!handle) return 0;
1847 Local32_FromHandle( header, type2, &addr, handle, ptr );
1848 return addr;
1851 /***********************************************************************
1852 * Local32Size (KERNEL.214)
1854 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
1856 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1857 LPDWORD handle;
1858 LPBYTE ptr;
1860 Local32_ToHandle( header, type, addr, &handle, &ptr );
1861 if (!handle) return 0;
1863 return HeapSize( header->heap, 0, ptr );
1866 /***********************************************************************
1867 * Local32ValidHandle (KERNEL.215)
1869 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
1871 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1872 LPDWORD handle;
1873 LPBYTE ptr;
1875 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1876 return handle != NULL;
1879 /***********************************************************************
1880 * Local32GetSegment (KERNEL.229)
1882 WORD WINAPI Local32GetSegment16( HANDLE heap )
1884 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1885 return header->segment;
1888 /***********************************************************************
1889 * Local32_GetHeap
1891 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
1893 WORD selector = GlobalHandleToSel16( handle );
1894 DWORD base = GetSelectorBase( selector );
1895 DWORD limit = GetSelectorLimit16( selector );
1897 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
1898 it this way ... */
1900 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1901 return (LOCAL32HEADER *)base;
1903 base += 0x10000;
1904 limit -= 0x10000;
1906 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1907 return (LOCAL32HEADER *)base;
1909 return NULL;
1912 /***********************************************************************
1913 * Local32Info (KERNEL.444) (TOOLHELP.84)
1915 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
1917 SUBHEAP *heapPtr;
1918 LPBYTE ptr;
1919 int i;
1921 LOCAL32HEADER *header = Local32_GetHeap( handle );
1922 if ( !header ) return FALSE;
1924 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
1925 return FALSE;
1927 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
1928 pLocal32Info->dwMemReserved = heapPtr->size;
1929 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
1930 pLocal32Info->dwTotalFree = 0L;
1931 pLocal32Info->dwLargestFreeBlock = 0L;
1933 /* Note: Local32 heaps always have only one subheap! */
1934 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
1935 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
1937 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1939 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1940 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1941 ptr += sizeof(*pArena) + size;
1943 pLocal32Info->dwTotalFree += size;
1944 if ( size > pLocal32Info->dwLargestFreeBlock )
1945 pLocal32Info->dwLargestFreeBlock = size;
1947 else
1949 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1950 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1951 ptr += sizeof(*pArena) + size;
1955 pLocal32Info->dwcFreeHandles = 0;
1956 for ( i = 0; i < HTABLE_NPAGES; i++ )
1958 if ( header->freeListFirst[i] == 0xffff ) break;
1959 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
1961 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
1963 return TRUE;
1966 /***********************************************************************
1967 * Local32First (KERNEL.445) (TOOLHELP.85)
1969 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
1971 FIXME( heap, "(%p, %04X): stub!\n", pLocal32Entry, handle );
1972 return FALSE;
1975 /***********************************************************************
1976 * Local32Next (KERNEL.446) (TOOLHELP.86)
1978 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
1980 FIXME( heap, "(%p): stub!\n", pLocal32Entry );
1981 return FALSE;