4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
12 #include "wine/winbase16.h"
13 #include "wine/unicode.h"
14 #include "selectors.h"
21 #include "debugtools.h"
24 DEFAULT_DEBUG_CHANNEL(heap);
26 /* Note: the heap data structures are based on what Pietrek describes in his
27 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
28 * the same, but could be easily adapted if it turns out some programs
32 typedef struct tagARENA_INUSE
34 DWORD size; /* Block size; must be the first field */
35 WORD magic; /* Magic number */
36 WORD threadId; /* Allocating thread id */
37 void *callerEIP; /* EIP of caller upon allocation */
40 typedef struct tagARENA_FREE
42 DWORD size; /* Block size; must be the first field */
43 WORD magic; /* Magic number */
44 WORD threadId; /* Freeing thread id */
45 struct tagARENA_FREE *next; /* Next free arena */
46 struct tagARENA_FREE *prev; /* Prev free arena */
49 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
50 #define ARENA_FLAG_PREV_FREE 0x00000002
51 #define ARENA_SIZE_MASK 0xfffffffc
52 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
53 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
55 #define ARENA_INUSE_FILLER 0x55
56 #define ARENA_FREE_FILLER 0xaa
58 #define QUIET 1 /* Suppress messages */
59 #define NOISY 0 /* Report all errors */
61 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
63 /* Max size of the blocks on the free lists */
64 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
66 0x20, 0x80, 0x200, 0xffffffff
77 typedef struct tagSUBHEAP
79 DWORD size; /* Size of the whole sub-heap */
80 DWORD commitSize; /* Committed size of the sub-heap */
81 DWORD headerSize; /* Size of the heap header */
82 struct tagSUBHEAP *next; /* Next sub-heap */
83 struct tagHEAP *heap; /* Main heap structure */
84 DWORD magic; /* Magic number */
85 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
88 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
90 typedef struct tagHEAP
92 SUBHEAP subheap; /* First sub-heap */
93 struct tagHEAP *next; /* Next heap for this process */
94 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
95 CRITICAL_SECTION critSection; /* Critical section for serialization */
96 DWORD flags; /* Heap flags */
97 DWORD magic; /* Magic number */
98 void *private; /* Private pointer for the user of the heap */
101 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
103 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
104 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
105 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
107 HANDLE SystemHeap = 0;
109 SYSTEM_HEAP_DESCR *SystemHeapDescr = 0;
111 static HEAP *processHeap; /* main process heap */
112 static HEAP *segptrHeap; /* main segptr heap */
113 static HEAP *firstHeap; /* head of secondary heaps list */
115 /* address where we try to map the system heap */
116 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
118 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
121 #define GET_EIP() (__builtin_return_address(0))
122 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
125 #define SET_EIP(ptr) /* nothing */
126 #endif /* __GNUC__ */
128 /***********************************************************************
131 void HEAP_Dump( HEAP *heap )
137 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
138 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
139 (DWORD)heap->next, (DWORD)&heap->subheap );
140 subheap = &heap->subheap;
141 while (subheap->next)
143 DPRINTF( " -> %08lx", (DWORD)subheap->next );
144 subheap = subheap->next;
147 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
148 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
149 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
150 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
151 heap->freeList[i].arena.threadId,
152 (DWORD)heap->freeList[i].arena.prev,
153 (DWORD)heap->freeList[i].arena.next );
155 subheap = &heap->subheap;
158 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
159 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
160 (DWORD)subheap, subheap->size, subheap->commitSize );
162 DPRINTF( "\n Block Stat Size Id\n" );
163 ptr = (char*)subheap + subheap->headerSize;
164 while (ptr < (char *)subheap + subheap->size)
166 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
168 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
169 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
170 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
171 pArena->threadId, (DWORD)pArena->prev,
172 (DWORD)pArena->next);
173 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
174 arenaSize += sizeof(ARENA_FREE);
175 freeSize += pArena->size & ARENA_SIZE_MASK;
177 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
179 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
180 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
181 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
182 pArena->threadId, *((DWORD *)pArena - 1),
184 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
185 arenaSize += sizeof(ARENA_INUSE);
186 usedSize += pArena->size & ARENA_SIZE_MASK;
190 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
191 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
192 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
193 pArena->threadId, pArena->callerEIP );
194 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
195 arenaSize += sizeof(ARENA_INUSE);
196 usedSize += pArena->size & ARENA_SIZE_MASK;
199 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
200 subheap->size, subheap->commitSize, freeSize, usedSize,
201 arenaSize, (arenaSize * 100) / subheap->size );
202 subheap = subheap->next;
207 /***********************************************************************
210 * Pointer to the heap
213 static HEAP *HEAP_GetPtr(
214 HANDLE heap /* [in] Handle to the heap */
216 HEAP *heapPtr = (HEAP *)heap;
217 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
219 ERR("Invalid heap %08x!\n", heap );
220 SetLastError( ERROR_INVALID_HANDLE );
223 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
225 HEAP_Dump( heapPtr );
227 SetLastError( ERROR_INVALID_HANDLE );
234 /***********************************************************************
235 * HEAP_InsertFreeBlock
237 * Insert a free block into the free list.
239 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
241 FREE_LIST_ENTRY *pEntry = heap->freeList;
242 while (pEntry->size < pArena->size) pEntry++;
243 pArena->size |= ARENA_FLAG_FREE;
244 pArena->next = pEntry->arena.next;
245 pArena->next->prev = pArena;
246 pArena->prev = &pEntry->arena;
247 pEntry->arena.next = pArena;
251 /***********************************************************************
253 * Find the sub-heap containing a given address.
259 static SUBHEAP *HEAP_FindSubHeap(
260 HEAP *heap, /* [in] Heap pointer */
261 LPCVOID ptr /* [in] Address */
263 SUBHEAP *sub = &heap->subheap;
266 if (((char *)ptr >= (char *)sub) &&
267 ((char *)ptr < (char *)sub + sub->size)) return sub;
274 /***********************************************************************
277 * Make sure the heap storage is committed up to (not including) ptr.
279 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
281 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
282 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
283 if (size > subheap->size) size = subheap->size;
284 if (size <= subheap->commitSize) return TRUE;
285 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
286 size - subheap->commitSize, MEM_COMMIT,
287 PAGE_EXECUTE_READWRITE))
289 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
290 size - subheap->commitSize,
291 (DWORD)((char *)subheap + subheap->commitSize),
292 (DWORD)subheap->heap );
295 subheap->commitSize = size;
300 /***********************************************************************
303 * If possible, decommit the heap storage from (including) 'ptr'.
305 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
307 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
308 /* round to next block and add one full block */
309 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
310 if (size >= subheap->commitSize) return TRUE;
311 if (!VirtualFree( (char *)subheap + size,
312 subheap->commitSize - size, MEM_DECOMMIT ))
314 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
315 subheap->commitSize - size,
316 (DWORD)((char *)subheap + size),
317 (DWORD)subheap->heap );
320 subheap->commitSize = size;
325 /***********************************************************************
326 * HEAP_CreateFreeBlock
328 * Create a free block at a specified address. 'size' is the size of the
329 * whole block, including the new arena.
331 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
335 /* Create a free arena */
337 pFree = (ARENA_FREE *)ptr;
338 pFree->threadId = GetCurrentTask();
339 pFree->magic = ARENA_FREE_MAGIC;
341 /* If debugging, erase the freed block content */
345 char *pEnd = (char *)ptr + size;
346 if (pEnd > (char *)subheap + subheap->commitSize)
347 pEnd = (char *)subheap + subheap->commitSize;
348 if (pEnd > (char *)(pFree + 1))
349 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
352 /* Check if next block is free also */
354 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
355 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
357 /* Remove the next arena from the free list */
358 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
359 pNext->next->prev = pNext->prev;
360 pNext->prev->next = pNext->next;
361 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
363 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
366 /* Set the next block PREV_FREE flag and pointer */
368 if ((char *)ptr + size < (char *)subheap + subheap->size)
370 DWORD *pNext = (DWORD *)((char *)ptr + size);
371 *pNext |= ARENA_FLAG_PREV_FREE;
372 *(ARENA_FREE **)(pNext - 1) = pFree;
375 /* Last, insert the new block into the free list */
377 pFree->size = size - sizeof(*pFree);
378 HEAP_InsertFreeBlock( subheap->heap, pFree );
382 /***********************************************************************
383 * HEAP_MakeInUseBlockFree
385 * Turn an in-use block into a free block. Can also decommit the end of
386 * the heap, and possibly even free the sub-heap altogether.
388 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
391 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
393 /* Check if we can merge with previous block */
395 if (pArena->size & ARENA_FLAG_PREV_FREE)
397 pFree = *((ARENA_FREE **)pArena - 1);
398 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
399 /* Remove it from the free list */
400 pFree->next->prev = pFree->prev;
401 pFree->prev->next = pFree->next;
403 else pFree = (ARENA_FREE *)pArena;
405 /* Create a free block */
407 HEAP_CreateFreeBlock( subheap, pFree, size );
408 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
409 if ((char *)pFree + size < (char *)subheap + subheap->size)
410 return; /* Not the last block, so nothing more to do */
412 /* Free the whole sub-heap if it's empty and not the original one */
414 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
415 (subheap != &subheap->heap->subheap))
417 SUBHEAP *pPrev = &subheap->heap->subheap;
418 /* Remove the free block from the list */
419 pFree->next->prev = pFree->prev;
420 pFree->prev->next = pFree->next;
421 /* Remove the subheap from the list */
422 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
423 if (pPrev) pPrev->next = subheap->next;
424 /* Free the memory */
426 if (subheap->selector) FreeSelector16( subheap->selector );
427 VirtualFree( subheap, 0, MEM_RELEASE );
431 /* Decommit the end of the heap */
433 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
437 /***********************************************************************
440 * Shrink an in-use block.
442 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
444 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
446 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
447 (pArena->size & ARENA_SIZE_MASK) - size );
448 /* assign size plus previous arena flags */
449 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
453 /* Turn off PREV_FREE flag in next block */
454 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
455 if (pNext < (char *)subheap + subheap->size)
456 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
460 /***********************************************************************
463 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
464 DWORD commitSize, DWORD totalSize )
466 SUBHEAP *subheap = (SUBHEAP *)address;
468 FREE_LIST_ENTRY *pEntry;
473 if (flags & HEAP_SHARED)
474 commitSize = totalSize; /* always commit everything in a shared heap */
475 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
477 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
478 commitSize, (DWORD)address );
482 /* Allocate a selector if needed */
484 if (flags & HEAP_WINE_SEGPTR)
486 unsigned char selflags = WINE_LDT_FLAGS_DATA;
488 if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
489 selflags = WINE_LDT_FLAGS_CODE;
490 if (flags & HEAP_WINE_CODESEG)
491 selflags |= WINE_LDT_FLAGS_32BIT;
492 selector = SELECTOR_AllocBlock( address, totalSize, selflags );
495 ERR("Could not allocate selector\n" );
500 /* Fill the sub-heap structure */
502 subheap->heap = heap;
503 subheap->selector = selector;
504 subheap->size = totalSize;
505 subheap->commitSize = commitSize;
506 subheap->magic = SUBHEAP_MAGIC;
508 if ( subheap != (SUBHEAP *)heap )
510 /* If this is a secondary subheap, insert it into list */
512 subheap->headerSize = sizeof(SUBHEAP);
513 subheap->next = heap->subheap.next;
514 heap->subheap.next = subheap;
518 /* If this is a primary subheap, initialize main heap */
520 subheap->headerSize = sizeof(HEAP);
521 subheap->next = NULL;
524 heap->magic = HEAP_MAGIC;
526 /* Build the free lists */
528 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
530 pEntry->size = HEAP_freeListSizes[i];
531 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
532 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
533 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
534 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
535 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
536 pEntry->arena.threadId = 0;
537 pEntry->arena.magic = ARENA_FREE_MAGIC;
540 /* Initialize critical section */
542 InitializeCriticalSection( &heap->critSection );
543 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
546 /* Create the first free block */
548 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
549 subheap->size - subheap->headerSize );
554 /***********************************************************************
557 * Create a sub-heap of the given size.
558 * If heap == NULL, creates a main heap.
560 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
561 DWORD commitSize, DWORD totalSize )
565 /* Round-up sizes on a 64K boundary */
567 if (flags & HEAP_WINE_SEGPTR)
569 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
573 totalSize = (totalSize + 0xffff) & 0xffff0000;
574 commitSize = (commitSize + 0xffff) & 0xffff0000;
575 if (!commitSize) commitSize = 0x10000;
576 if (totalSize < commitSize) totalSize = commitSize;
579 /* Allocate the memory block */
581 if (!(address = VirtualAlloc( NULL, totalSize,
582 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
584 WARN("Could not VirtualAlloc %08lx bytes\n",
589 /* Initialize subheap */
591 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
592 address, flags, commitSize, totalSize ))
594 VirtualFree( address, 0, MEM_RELEASE );
598 return (SUBHEAP *)address;
602 /***********************************************************************
605 * Find a free block at least as large as the requested size, and make sure
606 * the requested size is committed.
608 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
609 SUBHEAP **ppSubHeap )
613 FREE_LIST_ENTRY *pEntry = heap->freeList;
615 /* Find a suitable free list, and in it find a block large enough */
617 while (pEntry->size < size) pEntry++;
618 pArena = pEntry->arena.next;
619 while (pArena != &heap->freeList[0].arena)
621 if (pArena->size > size)
623 subheap = HEAP_FindSubHeap( heap, pArena );
624 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
625 + size + HEAP_MIN_BLOCK_SIZE))
627 *ppSubHeap = subheap;
631 pArena = pArena->next;
634 /* If no block was found, attempt to grow the heap */
636 if (!(heap->flags & HEAP_GROWABLE))
638 WARN("Not enough space in heap %08lx for %08lx bytes\n",
642 /* make sure that we have a big enough size *committed* to fit another
643 * last free arena in !
644 * So just one heap struct, one first free arena which will eventually
645 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
646 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
647 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
648 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
649 max( HEAP_DEF_SIZE, size ) )))
652 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
653 (DWORD)subheap, size, (DWORD)heap );
655 *ppSubHeap = subheap;
656 return (ARENA_FREE *)(subheap + 1);
660 /***********************************************************************
661 * HEAP_IsValidArenaPtr
663 * Check that the pointer is inside the range possible for arenas.
665 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
668 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
669 if (!subheap) return FALSE;
670 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
671 if (subheap != &heap->subheap) return FALSE;
672 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
673 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
678 /***********************************************************************
679 * HEAP_ValidateFreeArena
681 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
683 char *heapEnd = (char *)subheap + subheap->size;
685 /* Check magic number */
686 if (pArena->magic != ARENA_FREE_MAGIC)
688 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
689 (DWORD)subheap->heap, (DWORD)pArena );
692 /* Check size flags */
693 if (!(pArena->size & ARENA_FLAG_FREE) ||
694 (pArena->size & ARENA_FLAG_PREV_FREE))
696 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
697 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
699 /* Check arena size */
700 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
702 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
703 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
706 /* Check that next pointer is valid */
707 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
709 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
710 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
713 /* Check that next arena is free */
714 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
715 (pArena->next->magic != ARENA_FREE_MAGIC))
717 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
718 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
721 /* Check that prev pointer is valid */
722 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
724 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
725 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
728 /* Check that prev arena is free */
729 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
730 (pArena->prev->magic != ARENA_FREE_MAGIC))
732 /* this often means that the prev arena got overwritten
733 * by a memory write before that prev arena */
734 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
735 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
738 /* Check that next block has PREV_FREE flag */
739 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
741 if (!(*(DWORD *)((char *)(pArena + 1) +
742 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
744 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
745 (DWORD)subheap->heap, (DWORD)pArena );
748 /* Check next block back pointer */
749 if (*((ARENA_FREE **)((char *)(pArena + 1) +
750 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
752 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
753 (DWORD)subheap->heap, (DWORD)pArena,
754 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
762 /***********************************************************************
763 * HEAP_ValidateInUseArena
765 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
767 char *heapEnd = (char *)subheap + subheap->size;
769 /* Check magic number */
770 if (pArena->magic != ARENA_INUSE_MAGIC)
772 if (quiet == NOISY) {
773 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
774 (DWORD)subheap->heap, (DWORD)pArena );
776 HEAP_Dump( subheap->heap );
777 } else if (WARN_ON(heap)) {
778 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
779 (DWORD)subheap->heap, (DWORD)pArena );
781 HEAP_Dump( subheap->heap );
785 /* Check size flags */
786 if (pArena->size & ARENA_FLAG_FREE)
788 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
789 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
791 /* Check arena size */
792 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
794 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
795 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
798 /* Check next arena PREV_FREE flag */
799 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
800 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
802 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
803 (DWORD)subheap->heap, (DWORD)pArena );
806 /* Check prev free arena */
807 if (pArena->size & ARENA_FLAG_PREV_FREE)
809 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
810 /* Check prev pointer */
811 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
813 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
814 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
817 /* Check that prev arena is free */
818 if (!(pPrev->size & ARENA_FLAG_FREE) ||
819 (pPrev->magic != ARENA_FREE_MAGIC))
821 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
822 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
825 /* Check that prev arena is really the previous block */
826 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
828 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
829 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
837 /***********************************************************************
840 * Transform a linear pointer into a SEGPTR. The pointer must have been
841 * allocated from a HEAP_WINE_SEGPTR heap.
843 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
845 HEAP *heapPtr = HEAP_GetPtr( heap );
849 /* Validate the parameters */
851 if (!heapPtr) return 0;
852 flags |= heapPtr->flags;
853 if (!(flags & HEAP_WINE_SEGPTR))
855 ERR("Heap %08x is not a SEGPTR heap\n",
859 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
861 /* Get the subheap */
863 if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
864 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
866 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
870 /***********************************************************************
871 * MapLS (KERNEL32.522)
873 * Maps linear pointer to segmented.
875 SEGPTR WINAPI MapLS( LPCVOID ptr )
880 if (!HIWORD(ptr)) return (SEGPTR)ptr;
882 /* check if the pointer is inside the segptr heap */
883 EnterCriticalSection( &segptrHeap->critSection );
884 if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
885 ret = PTR_SEG_OFF_TO_SEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
886 LeaveCriticalSection( &segptrHeap->critSection );
888 /* otherwise, allocate a brand-new selector */
891 WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
892 ret = PTR_SEG_OFF_TO_SEGPTR( sel, 0 );
898 /***********************************************************************
899 * UnMapLS (KERNEL32.700)
901 * Free mapped selector.
903 void WINAPI UnMapLS( SEGPTR sptr )
906 if (!SELECTOROF(sptr)) return;
908 /* check if ptr is inside segptr heap */
909 EnterCriticalSection( &segptrHeap->critSection );
910 subheap = HEAP_FindSubHeap( segptrHeap, PTR_SEG_TO_LIN(sptr) );
911 if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
912 LeaveCriticalSection( &segptrHeap->critSection );
913 /* if not inside heap, free the selector */
914 if (!subheap) FreeSelector16( SELECTOROF(sptr) );
917 /***********************************************************************
918 * HEAP_IsRealArena [Internal]
919 * Validates a block is a valid arena.
925 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
926 DWORD flags, /* [in] Bit flags that control access during operation */
927 LPCVOID block, /* [in] Optional pointer to memory block to validate */
928 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
929 * does not complain */
934 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
936 ERR("Invalid heap %p!\n", heapPtr );
940 flags &= HEAP_NO_SERIALIZE;
941 flags |= heapPtr->flags;
942 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
943 if (!(flags & HEAP_NO_SERIALIZE))
944 EnterCriticalSection( &heapPtr->critSection );
948 /* Only check this single memory block */
950 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
951 ((char *)block < (char *)subheap + subheap->headerSize
952 + sizeof(ARENA_INUSE)))
955 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
956 else if (WARN_ON(heap))
957 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
960 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
962 if (!(flags & HEAP_NO_SERIALIZE))
963 LeaveCriticalSection( &heapPtr->critSection );
967 subheap = &heapPtr->subheap;
968 while (subheap && ret)
970 char *ptr = (char *)subheap + subheap->headerSize;
971 while (ptr < (char *)subheap + subheap->size)
973 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
975 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
979 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
983 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
987 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
990 subheap = subheap->next;
993 if (!(flags & HEAP_NO_SERIALIZE))
994 LeaveCriticalSection( &heapPtr->critSection );
999 /***********************************************************************
1000 * HeapCreate (KERNEL32.336)
1002 * Handle of heap: Success
1005 HANDLE WINAPI HeapCreate(
1006 DWORD flags, /* [in] Heap allocation flag */
1007 DWORD initialSize, /* [in] Initial heap size */
1008 DWORD maxSize /* [in] Maximum heap size */
1012 if ( flags & HEAP_SHARED ) {
1013 WARN( "Shared Heap requested, returning system heap.\n" );
1017 /* Allocate the heap block */
1021 maxSize = HEAP_DEF_SIZE;
1022 flags |= HEAP_GROWABLE;
1024 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1026 SetLastError( ERROR_OUTOFMEMORY );
1030 /* link it into the per-process heap list */
1033 HEAP *heapPtr = subheap->heap;
1034 EnterCriticalSection( &processHeap->critSection );
1035 heapPtr->next = firstHeap;
1036 firstHeap = heapPtr;
1037 LeaveCriticalSection( &processHeap->critSection );
1039 else /* assume the first heap we create is the process main heap */
1042 processHeap = subheap->heap;
1043 /* create the SEGPTR heap */
1044 if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1046 SetLastError( ERROR_OUTOFMEMORY );
1049 segptrHeap = segptr->heap;
1051 return (HANDLE)subheap;
1054 /***********************************************************************
1055 * HeapDestroy (KERNEL32.337)
1060 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1062 HEAP *heapPtr = HEAP_GetPtr( heap );
1065 if ( heap == SystemHeap ) {
1066 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1070 TRACE("%08x\n", heap );
1071 if (!heapPtr) return FALSE;
1073 if (heapPtr == processHeap) /* cannot delete the main process heap */
1075 SetLastError( ERROR_INVALID_PARAMETER );
1078 else /* remove it from the per-process list */
1081 EnterCriticalSection( &processHeap->critSection );
1083 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1084 if (*pptr) *pptr = (*pptr)->next;
1085 LeaveCriticalSection( &processHeap->critSection );
1088 DeleteCriticalSection( &heapPtr->critSection );
1089 subheap = &heapPtr->subheap;
1092 SUBHEAP *next = subheap->next;
1093 if (subheap->selector) FreeSelector16( subheap->selector );
1094 VirtualFree( subheap, 0, MEM_RELEASE );
1101 /***********************************************************************
1102 * HeapAlloc (KERNEL32.334)
1104 * Pointer to allocated memory block
1107 LPVOID WINAPI HeapAlloc(
1108 HANDLE heap, /* [in] Handle of private heap block */
1109 DWORD flags, /* [in] Heap allocation control flags */
1110 DWORD size /* [in] Number of bytes to allocate */
1113 ARENA_INUSE *pInUse;
1115 HEAP *heapPtr = HEAP_GetPtr( heap );
1117 /* Validate the parameters */
1119 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1120 if (!heapPtr) return NULL;
1121 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1122 flags |= heapPtr->flags;
1123 size = (size + 3) & ~3;
1124 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1126 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1127 /* Locate a suitable free block */
1129 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1131 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1132 heap, flags, size );
1133 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1134 SetLastError( ERROR_COMMITMENT_LIMIT );
1138 /* Remove the arena from the free list */
1140 pArena->next->prev = pArena->prev;
1141 pArena->prev->next = pArena->next;
1143 /* Build the in-use arena */
1145 pInUse = (ARENA_INUSE *)pArena;
1147 /* in-use arena is smaller than free arena,
1148 * so we have to add the difference to the size */
1149 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1150 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1151 pInUse->callerEIP = GET_EIP();
1152 pInUse->threadId = GetCurrentTask();
1153 pInUse->magic = ARENA_INUSE_MAGIC;
1155 /* Shrink the block */
1157 HEAP_ShrinkBlock( subheap, pInUse, size );
1159 if (flags & HEAP_ZERO_MEMORY)
1160 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1161 else if (TRACE_ON(heap))
1162 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1164 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1166 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1167 heap, flags, size, (DWORD)(pInUse + 1) );
1168 return (LPVOID)(pInUse + 1);
1172 /***********************************************************************
1173 * HeapFree (KERNEL32.338)
1178 BOOL WINAPI HeapFree(
1179 HANDLE heap, /* [in] Handle of heap */
1180 DWORD flags, /* [in] Heap freeing flags */
1181 LPVOID ptr /* [in] Address of memory to free */
1183 ARENA_INUSE *pInUse;
1185 HEAP *heapPtr = HEAP_GetPtr( heap );
1187 /* Validate the parameters */
1189 if (!ptr) return TRUE; /* freeing a NULL ptr is doesn't indicate an error in Win2k */
1190 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1191 if (!heapPtr) return FALSE;
1193 flags &= HEAP_NO_SERIALIZE;
1194 flags |= heapPtr->flags;
1195 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1196 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1198 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1199 SetLastError( ERROR_INVALID_PARAMETER );
1200 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1201 heap, flags, (DWORD)ptr );
1205 /* Turn the block into a free block */
1207 pInUse = (ARENA_INUSE *)ptr - 1;
1208 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1209 HEAP_MakeInUseBlockFree( subheap, pInUse );
1211 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1213 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1214 heap, flags, (DWORD)ptr );
1219 /***********************************************************************
1220 * HeapReAlloc (KERNEL32.340)
1222 * Pointer to reallocated memory block
1225 LPVOID WINAPI HeapReAlloc(
1226 HANDLE heap, /* [in] Handle of heap block */
1227 DWORD flags, /* [in] Heap reallocation flags */
1228 LPVOID ptr, /* [in] Address of memory to reallocate */
1229 DWORD size /* [in] Number of bytes to reallocate */
1231 ARENA_INUSE *pArena;
1236 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1237 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1238 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1240 /* Validate the parameters */
1242 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1243 HEAP_REALLOC_IN_PLACE_ONLY;
1244 flags |= heapPtr->flags;
1245 size = (size + 3) & ~3;
1246 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1248 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1249 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1251 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1252 SetLastError( ERROR_INVALID_PARAMETER );
1253 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1254 heap, flags, (DWORD)ptr, size );
1258 /* Check if we need to grow the block */
1260 pArena = (ARENA_INUSE *)ptr - 1;
1261 pArena->threadId = GetCurrentTask();
1262 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1263 oldSize = (pArena->size & ARENA_SIZE_MASK);
1266 char *pNext = (char *)(pArena + 1) + oldSize;
1267 if ((pNext < (char *)subheap + subheap->size) &&
1268 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1269 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1271 /* The next block is free and large enough */
1272 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1273 pFree->next->prev = pFree->prev;
1274 pFree->prev->next = pFree->next;
1275 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1276 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1277 + size + HEAP_MIN_BLOCK_SIZE))
1279 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1280 SetLastError( ERROR_OUTOFMEMORY );
1283 HEAP_ShrinkBlock( subheap, pArena, size );
1285 else /* Do it the hard way */
1288 ARENA_INUSE *pInUse;
1289 SUBHEAP *newsubheap;
1291 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1292 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1294 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1295 SetLastError( ERROR_OUTOFMEMORY );
1299 /* Build the in-use arena */
1301 pNew->next->prev = pNew->prev;
1302 pNew->prev->next = pNew->next;
1303 pInUse = (ARENA_INUSE *)pNew;
1304 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1305 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1306 pInUse->threadId = GetCurrentTask();
1307 pInUse->magic = ARENA_INUSE_MAGIC;
1308 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1309 memcpy( pInUse + 1, pArena + 1, oldSize );
1311 /* Free the previous block */
1313 HEAP_MakeInUseBlockFree( subheap, pArena );
1314 subheap = newsubheap;
1318 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1320 /* Clear the extra bytes if needed */
1324 if (flags & HEAP_ZERO_MEMORY)
1325 memset( (char *)(pArena + 1) + oldSize, 0,
1326 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1327 else if (TRACE_ON(heap))
1328 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1329 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1332 /* Return the new arena */
1334 pArena->callerEIP = GET_EIP();
1335 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1337 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1338 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1339 return (LPVOID)(pArena + 1);
1343 /***********************************************************************
1344 * HeapCompact (KERNEL32.335)
1346 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1348 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1353 /***********************************************************************
1354 * HeapLock (KERNEL32.339)
1355 * Attempts to acquire the critical section object for a specified heap.
1361 BOOL WINAPI HeapLock(
1362 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1364 HEAP *heapPtr = HEAP_GetPtr( heap );
1365 if (!heapPtr) return FALSE;
1366 EnterCriticalSection( &heapPtr->critSection );
1371 /***********************************************************************
1372 * HeapUnlock (KERNEL32.342)
1373 * Releases ownership of the critical section object.
1379 BOOL WINAPI HeapUnlock(
1380 HANDLE heap /* [in] Handle to the heap to unlock */
1382 HEAP *heapPtr = HEAP_GetPtr( heap );
1383 if (!heapPtr) return FALSE;
1384 LeaveCriticalSection( &heapPtr->critSection );
1389 /***********************************************************************
1390 * HeapSize (KERNEL32.341)
1392 * Size in bytes of allocated memory
1393 * 0xffffffff: Failure
1395 DWORD WINAPI HeapSize(
1396 HANDLE heap, /* [in] Handle of heap */
1397 DWORD flags, /* [in] Heap size control flags */
1398 LPVOID ptr /* [in] Address of memory to return size for */
1401 HEAP *heapPtr = HEAP_GetPtr( heap );
1403 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1404 if (!heapPtr) return FALSE;
1405 flags &= HEAP_NO_SERIALIZE;
1406 flags |= heapPtr->flags;
1407 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1408 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1410 SetLastError( ERROR_INVALID_PARAMETER );
1415 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1416 ret = pArena->size & ARENA_SIZE_MASK;
1418 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1420 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1421 heap, flags, (DWORD)ptr, ret );
1426 /***********************************************************************
1427 * HeapValidate (KERNEL32.343)
1428 * Validates a specified heap.
1437 BOOL WINAPI HeapValidate(
1438 HANDLE heap, /* [in] Handle to the heap */
1439 DWORD flags, /* [in] Bit flags that control access during operation */
1440 LPCVOID block /* [in] Optional pointer to memory block to validate */
1442 HEAP *heapPtr = HEAP_GetPtr( heap );
1443 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1444 if (!heapPtr) return FALSE;
1445 return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1449 /***********************************************************************
1450 * HeapWalk (KERNEL32.344)
1451 * Enumerates the memory blocks in a specified heap.
1452 * See HEAP_Dump() for info on heap structure.
1455 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1456 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1462 BOOL WINAPI HeapWalk(
1463 HANDLE heap, /* [in] Handle to heap to enumerate */
1464 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1466 HEAP *heapPtr = HEAP_GetPtr(heap);
1467 SUBHEAP *sub, *currentheap = NULL;
1470 int region_index = 0;
1472 if (!heapPtr || !entry)
1474 SetLastError(ERROR_INVALID_PARAMETER);
1478 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1480 /* set ptr to the next arena to be examined */
1482 if (!entry->lpData) /* first call (init) ? */
1484 TRACE("begin walking of heap 0x%08x.\n", heap);
1485 /*HEAP_Dump(heapPtr);*/
1486 currentheap = &heapPtr->subheap;
1487 ptr = (char*)currentheap + currentheap->headerSize;
1491 ptr = entry->lpData;
1492 sub = &heapPtr->subheap;
1495 if (((char *)ptr >= (char *)sub) &&
1496 ((char *)ptr < (char *)sub + sub->size))
1504 if (currentheap == NULL)
1506 ERR("no matching subheap found, shouldn't happen !\n");
1507 SetLastError(ERROR_NO_MORE_ITEMS);
1511 ptr += entry->cbData; /* point to next arena */
1512 if (ptr > (char *)currentheap + currentheap->size - 1)
1513 { /* proceed with next subheap */
1514 if (!(currentheap = currentheap->next))
1515 { /* successfully finished */
1516 TRACE("end reached.\n");
1517 SetLastError(ERROR_NO_MORE_ITEMS);
1520 ptr = (char*)currentheap + currentheap->headerSize;
1525 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1527 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1529 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1531 entry->lpData = pArena + 1;
1532 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1533 entry->cbOverhead = sizeof(ARENA_FREE);
1534 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1538 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1540 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1542 entry->lpData = pArena + 1;
1543 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1544 entry->cbOverhead = sizeof(ARENA_INUSE);
1545 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1546 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1547 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1550 entry->iRegionIndex = region_index;
1552 /* first element of heap ? */
1553 if (ptr == (char *)(currentheap + currentheap->headerSize))
1555 entry->wFlags |= PROCESS_HEAP_REGION;
1556 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1557 entry->u.Region.dwUnCommittedSize =
1558 currentheap->size - currentheap->commitSize;
1559 entry->u.Region.lpFirstBlock = /* first valid block */
1560 currentheap + currentheap->headerSize;
1561 entry->u.Region.lpLastBlock = /* first invalid block */
1562 currentheap + currentheap->size;
1567 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1573 /***********************************************************************
1574 * HEAP_CreateSystemHeap
1576 * Create the system heap.
1578 BOOL HEAP_CreateSystemHeap(void)
1580 SYSTEM_HEAP_DESCR *descr;
1585 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1586 0, HEAP_DEF_SIZE, "__SystemHeap" );
1587 if (!map) return FALSE;
1588 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1590 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1592 /* pre-defined address not available, use any one */
1593 fprintf( stderr, "Warning: system heap base address %p not available\n",
1595 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1601 heap = (HANDLE)heapPtr;
1603 if (created) /* newly created heap */
1605 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1607 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1612 /* wait for the heap to be initialized */
1613 while (!heapPtr->private) Sleep(1);
1615 /* remap it to the right address if necessary */
1616 if (heapPtr->subheap.heap != heapPtr)
1618 void *base = heapPtr->subheap.heap;
1620 UnmapViewOfFile( heapPtr );
1621 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1623 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1627 heap = (HANDLE)heapPtr;
1630 descr = heapPtr->private;
1634 SystemHeapDescr = descr;
1641 /***********************************************************************
1642 * GetProcessHeap (KERNEL32.259)
1644 HANDLE WINAPI GetProcessHeap(void)
1646 return (HANDLE)processHeap;
1650 /***********************************************************************
1651 * GetProcessHeaps (KERNEL32.376)
1653 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1658 if (!processHeap) return 0; /* should never happen */
1659 total = 1; /* main heap */
1660 EnterCriticalSection( &processHeap->critSection );
1661 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1664 *heaps++ = (HANDLE)processHeap;
1665 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1667 LeaveCriticalSection( &processHeap->critSection );
1672 /***********************************************************************
1673 * 32-bit local heap functions (Win95; undocumented)
1676 #define HTABLE_SIZE 0x10000
1677 #define HTABLE_PAGESIZE 0x1000
1678 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1680 #include "pshpack1.h"
1681 typedef struct _LOCAL32HEADER
1683 WORD freeListFirst[HTABLE_NPAGES];
1684 WORD freeListSize[HTABLE_NPAGES];
1685 WORD freeListLast[HTABLE_NPAGES];
1687 DWORD selectorTableOffset;
1688 WORD selectorTableSize;
1701 #include "poppack.h"
1703 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1705 /***********************************************************************
1706 * Local32Init (KERNEL.208)
1708 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1709 DWORD heapSize, DWORD flags )
1711 DWORD totSize, segSize = 0;
1713 LOCAL32HEADER *header;
1715 WORD *selectorTable;
1716 WORD selectorEven, selectorOdd;
1719 /* Determine new heap size */
1723 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1729 if ( heapSize == -1L )
1730 heapSize = 1024L*1024L; /* FIXME */
1732 heapSize = (heapSize + 0xffff) & 0xffff0000;
1733 segSize = (segSize + 0x0fff) & 0xfffff000;
1734 totSize = segSize + HTABLE_SIZE + heapSize;
1737 /* Allocate memory and initialize heap */
1739 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1742 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1743 MEM_COMMIT, PAGE_READWRITE ) )
1745 VirtualFree( base, 0, MEM_RELEASE );
1749 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1750 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1752 VirtualFree( base, 0, MEM_RELEASE );
1757 /* Set up header and handle table */
1759 header = (LOCAL32HEADER *)(base + segSize);
1760 header->base = base;
1761 header->limit = HTABLE_PAGESIZE-1;
1763 header->magic = LOCAL32_MAGIC;
1764 header->heap = (HANDLE)heap;
1766 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1767 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1768 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1770 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1771 *(DWORD *)((LPBYTE)header + i) = i+4;
1773 header->freeListFirst[1] = 0xffff;
1776 /* Set up selector table */
1778 nrBlocks = (totSize + 0x7fff) >> 15;
1779 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1780 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1781 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1782 if ( !selectorTable || !selectorEven || !selectorOdd )
1784 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1785 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1786 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1787 HeapDestroy( header->heap );
1788 VirtualFree( base, 0, MEM_RELEASE );
1792 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1793 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1794 header->selectorDelta = selectorEven - selectorOdd;
1795 header->segment = segment? segment : selectorEven;
1797 for (i = 0; i < nrBlocks; i++)
1798 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1799 : selectorEven + ((i >> 1) << __AHSHIFT);
1801 /* Move old segment */
1805 /* FIXME: This is somewhat ugly and relies on implementation
1806 details about 16-bit global memory handles ... */
1808 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1809 memcpy( base, oldBase, segSize );
1810 GLOBAL_MoveBlock( segment, base, totSize );
1811 HeapFree( SystemHeap, 0, oldBase );
1814 return (HANDLE)header;
1817 /***********************************************************************
1818 * Local32_SearchHandle
1820 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1824 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1825 handle < (LPDWORD)((LPBYTE)header + header->limit);
1828 if (*handle == addr)
1835 /***********************************************************************
1838 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1839 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1846 case -2: /* 16:16 pointer, no handles */
1847 *ptr = PTR_SEG_TO_LIN( addr );
1848 *handle = (LPDWORD)*ptr;
1851 case -1: /* 32-bit offset, no handles */
1852 *ptr = header->base + addr;
1853 *handle = (LPDWORD)*ptr;
1856 case 0: /* handle */
1857 if ( addr >= sizeof(LOCAL32HEADER)
1858 && addr < header->limit && !(addr & 3)
1859 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1861 *handle = (LPDWORD)((LPBYTE)header + addr);
1862 *ptr = header->base + **handle;
1866 case 1: /* 16:16 pointer */
1867 *ptr = PTR_SEG_TO_LIN( addr );
1868 *handle = Local32_SearchHandle( header, *ptr - header->base );
1871 case 2: /* 32-bit offset */
1872 *ptr = header->base + addr;
1873 *handle = Local32_SearchHandle( header, *ptr - header->base );
1878 /***********************************************************************
1879 * Local32_FromHandle
1881 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1882 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1886 case -2: /* 16:16 pointer */
1889 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1890 DWORD offset = (LPBYTE)ptr - header->base;
1891 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1895 case -1: /* 32-bit offset */
1897 *addr = ptr - header->base;
1900 case 0: /* handle */
1901 *addr = (LPBYTE)handle - (LPBYTE)header;
1906 /***********************************************************************
1907 * Local32Alloc (KERNEL.209)
1909 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1911 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1916 /* Allocate memory */
1917 ptr = HeapAlloc( header->heap,
1918 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1922 /* Allocate handle if requested */
1927 /* Find first page of handle table with free slots */
1928 for (page = 0; page < HTABLE_NPAGES; page++)
1929 if (header->freeListFirst[page] != 0)
1931 if (page == HTABLE_NPAGES)
1933 WARN("Out of handles!\n" );
1934 HeapFree( header->heap, 0, ptr );
1938 /* If virgin page, initialize it */
1939 if (header->freeListFirst[page] == 0xffff)
1941 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1942 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1944 WARN("Cannot grow handle table!\n" );
1945 HeapFree( header->heap, 0, ptr );
1949 header->limit += HTABLE_PAGESIZE;
1951 header->freeListFirst[page] = 0;
1952 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1953 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1955 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1956 *(DWORD *)((LPBYTE)header + i) = i+4;
1958 if (page < HTABLE_NPAGES-1)
1959 header->freeListFirst[page+1] = 0xffff;
1962 /* Allocate handle slot from page */
1963 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1964 if (--header->freeListSize[page] == 0)
1965 header->freeListFirst[page] = header->freeListLast[page] = 0;
1967 header->freeListFirst[page] = *handle;
1969 /* Store 32-bit offset in handle slot */
1970 *handle = ptr - header->base;
1974 handle = (LPDWORD)ptr;
1979 /* Convert handle to requested output type */
1980 Local32_FromHandle( header, type, &addr, handle, ptr );
1984 /***********************************************************************
1985 * Local32ReAlloc (KERNEL.210)
1987 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1988 DWORD size, DWORD flags )
1990 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1995 return Local32Alloc16( heap, size, type, flags );
1997 /* Retrieve handle and pointer */
1998 Local32_ToHandle( header, type, addr, &handle, &ptr );
1999 if (!handle) return FALSE;
2001 /* Reallocate memory block */
2002 ptr = HeapReAlloc( header->heap,
2003 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2009 *handle = ptr - header->base;
2011 handle = (LPDWORD)ptr;
2013 /* Convert handle to requested output type */
2014 Local32_FromHandle( header, type, &addr, handle, ptr );
2018 /***********************************************************************
2019 * Local32Free (KERNEL.211)
2021 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2023 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2027 /* Retrieve handle and pointer */
2028 Local32_ToHandle( header, type, addr, &handle, &ptr );
2029 if (!handle) return FALSE;
2031 /* Free handle if necessary */
2034 int offset = (LPBYTE)handle - (LPBYTE)header;
2035 int page = offset >> 12;
2037 /* Return handle slot to page free list */
2038 if (header->freeListSize[page]++ == 0)
2039 header->freeListFirst[page] = header->freeListLast[page] = offset;
2041 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2042 header->freeListLast[page] = offset;
2046 /* Shrink handle table when possible */
2047 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2049 if ( VirtualFree( (LPBYTE)header +
2050 (header->limit & ~(HTABLE_PAGESIZE-1)),
2051 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2054 header->limit -= HTABLE_PAGESIZE;
2055 header->freeListFirst[page] = 0xffff;
2061 return HeapFree( header->heap, 0, ptr );
2064 /***********************************************************************
2065 * Local32Translate (KERNEL.213)
2067 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2069 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2073 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2074 if (!handle) return 0;
2076 Local32_FromHandle( header, type2, &addr, handle, ptr );
2080 /***********************************************************************
2081 * Local32Size (KERNEL.214)
2083 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2085 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2089 Local32_ToHandle( header, type, addr, &handle, &ptr );
2090 if (!handle) return 0;
2092 return HeapSize( header->heap, 0, ptr );
2095 /***********************************************************************
2096 * Local32ValidHandle (KERNEL.215)
2098 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2100 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2104 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2105 return handle != NULL;
2108 /***********************************************************************
2109 * Local32GetSegment (KERNEL.229)
2111 WORD WINAPI Local32GetSegment16( HANDLE heap )
2113 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2114 return header->segment;
2117 /***********************************************************************
2120 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2122 WORD selector = GlobalHandleToSel16( handle );
2123 DWORD base = GetSelectorBase( selector );
2124 DWORD limit = GetSelectorLimit16( selector );
2126 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2129 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2130 return (LOCAL32HEADER *)base;
2135 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2136 return (LOCAL32HEADER *)base;
2141 /***********************************************************************
2142 * Local32Info (KERNEL.444) (TOOLHELP.84)
2144 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2150 LOCAL32HEADER *header = Local32_GetHeap( handle );
2151 if ( !header ) return FALSE;
2153 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2156 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2157 pLocal32Info->dwMemReserved = heapPtr->size;
2158 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2159 pLocal32Info->dwTotalFree = 0L;
2160 pLocal32Info->dwLargestFreeBlock = 0L;
2162 /* Note: Local32 heaps always have only one subheap! */
2163 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2164 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2166 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2168 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2169 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2170 ptr += sizeof(*pArena) + size;
2172 pLocal32Info->dwTotalFree += size;
2173 if ( size > pLocal32Info->dwLargestFreeBlock )
2174 pLocal32Info->dwLargestFreeBlock = size;
2178 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2179 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2180 ptr += sizeof(*pArena) + size;
2184 pLocal32Info->dwcFreeHandles = 0;
2185 for ( i = 0; i < HTABLE_NPAGES; i++ )
2187 if ( header->freeListFirst[i] == 0xffff ) break;
2188 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2190 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2195 /***********************************************************************
2196 * Local32First (KERNEL.445) (TOOLHELP.85)
2198 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2200 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2204 /***********************************************************************
2205 * Local32Next (KERNEL.446) (TOOLHELP.86)
2207 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2209 FIXME("(%p): stub!\n", pLocal32Entry );