4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
13 #include "wine/winbase16.h"
14 #include "wine/unicode.h"
15 #include "selectors.h"
22 #include "debugtools.h"
25 DEFAULT_DEBUG_CHANNEL(heap);
27 /* Note: the heap data structures are based on what Pietrek describes in his
28 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
29 * the same, but could be easily adapted if it turns out some programs
33 typedef struct tagARENA_INUSE
35 DWORD size; /* Block size; must be the first field */
36 WORD magic; /* Magic number */
37 WORD threadId; /* Allocating thread id */
38 void *callerEIP; /* EIP of caller upon allocation */
41 typedef struct tagARENA_FREE
43 DWORD size; /* Block size; must be the first field */
44 WORD magic; /* Magic number */
45 WORD threadId; /* Freeing thread id */
46 struct tagARENA_FREE *next; /* Next free arena */
47 struct tagARENA_FREE *prev; /* Prev free arena */
50 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
51 #define ARENA_FLAG_PREV_FREE 0x00000002
52 #define ARENA_SIZE_MASK 0xfffffffc
53 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
54 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
56 #define ARENA_INUSE_FILLER 0x55
57 #define ARENA_FREE_FILLER 0xaa
59 #define QUIET 1 /* Suppress messages */
60 #define NOISY 0 /* Report all errors */
62 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
64 /* Max size of the blocks on the free lists */
65 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
67 0x20, 0x80, 0x200, 0xffffffff
78 typedef struct tagSUBHEAP
80 DWORD size; /* Size of the whole sub-heap */
81 DWORD commitSize; /* Committed size of the sub-heap */
82 DWORD headerSize; /* Size of the heap header */
83 struct tagSUBHEAP *next; /* Next sub-heap */
84 struct tagHEAP *heap; /* Main heap structure */
85 DWORD magic; /* Magic number */
86 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
89 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
91 typedef struct tagHEAP
93 SUBHEAP subheap; /* First sub-heap */
94 struct tagHEAP *next; /* Next heap for this process */
95 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
96 CRITICAL_SECTION critSection; /* Critical section for serialization */
97 DWORD flags; /* Heap flags */
98 DWORD magic; /* Magic number */
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 static HEAP *systemHeap; /* globally shared heap */
108 static HEAP *processHeap; /* main process heap */
109 static HEAP *segptrHeap; /* main segptr heap */
110 static HEAP *firstHeap; /* head of secondary heaps list */
112 /* address where we try to map the system heap */
113 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
115 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
118 #define GET_EIP() (__builtin_return_address(0))
119 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
122 #define SET_EIP(ptr) /* nothing */
123 #endif /* __GNUC__ */
125 /***********************************************************************
128 void HEAP_Dump( HEAP *heap )
134 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
135 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
136 (DWORD)heap->next, (DWORD)&heap->subheap );
137 subheap = &heap->subheap;
138 while (subheap->next)
140 DPRINTF( " -> %08lx", (DWORD)subheap->next );
141 subheap = subheap->next;
144 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
145 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
146 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
147 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
148 heap->freeList[i].arena.threadId,
149 (DWORD)heap->freeList[i].arena.prev,
150 (DWORD)heap->freeList[i].arena.next );
152 subheap = &heap->subheap;
155 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
156 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
157 (DWORD)subheap, subheap->size, subheap->commitSize );
159 DPRINTF( "\n Block Stat Size Id\n" );
160 ptr = (char*)subheap + subheap->headerSize;
161 while (ptr < (char *)subheap + subheap->size)
163 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
165 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
166 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
167 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168 pArena->threadId, (DWORD)pArena->prev,
169 (DWORD)pArena->next);
170 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171 arenaSize += sizeof(ARENA_FREE);
172 freeSize += pArena->size & ARENA_SIZE_MASK;
174 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
176 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
177 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
178 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
179 pArena->threadId, *((DWORD *)pArena - 1),
181 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
182 arenaSize += sizeof(ARENA_INUSE);
183 usedSize += pArena->size & ARENA_SIZE_MASK;
187 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
188 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
189 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
190 pArena->threadId, pArena->callerEIP );
191 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
192 arenaSize += sizeof(ARENA_INUSE);
193 usedSize += pArena->size & ARENA_SIZE_MASK;
196 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
197 subheap->size, subheap->commitSize, freeSize, usedSize,
198 arenaSize, (arenaSize * 100) / subheap->size );
199 subheap = subheap->next;
204 /***********************************************************************
207 * Pointer to the heap
210 static HEAP *HEAP_GetPtr(
211 HANDLE heap /* [in] Handle to the heap */
213 HEAP *heapPtr = (HEAP *)heap;
214 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
216 ERR("Invalid heap %08x!\n", heap );
217 SetLastError( ERROR_INVALID_HANDLE );
220 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
222 HEAP_Dump( heapPtr );
224 SetLastError( ERROR_INVALID_HANDLE );
231 /***********************************************************************
232 * HEAP_InsertFreeBlock
234 * Insert a free block into the free list.
236 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
238 FREE_LIST_ENTRY *pEntry = heap->freeList;
239 while (pEntry->size < pArena->size) pEntry++;
240 pArena->size |= ARENA_FLAG_FREE;
241 pArena->next = pEntry->arena.next;
242 pArena->next->prev = pArena;
243 pArena->prev = &pEntry->arena;
244 pEntry->arena.next = pArena;
248 /***********************************************************************
250 * Find the sub-heap containing a given address.
256 static SUBHEAP *HEAP_FindSubHeap(
257 HEAP *heap, /* [in] Heap pointer */
258 LPCVOID ptr /* [in] Address */
260 SUBHEAP *sub = &heap->subheap;
263 if (((char *)ptr >= (char *)sub) &&
264 ((char *)ptr < (char *)sub + sub->size)) return sub;
271 /***********************************************************************
274 * Make sure the heap storage is committed up to (not including) ptr.
276 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
278 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
279 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
280 if (size > subheap->size) size = subheap->size;
281 if (size <= subheap->commitSize) return TRUE;
282 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
283 size - subheap->commitSize, MEM_COMMIT,
284 PAGE_EXECUTE_READWRITE))
286 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
287 size - subheap->commitSize,
288 (DWORD)((char *)subheap + subheap->commitSize),
289 (DWORD)subheap->heap );
292 subheap->commitSize = size;
297 /***********************************************************************
300 * If possible, decommit the heap storage from (including) 'ptr'.
302 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
304 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
305 /* round to next block and add one full block */
306 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
307 if (size >= subheap->commitSize) return TRUE;
308 if (!VirtualFree( (char *)subheap + size,
309 subheap->commitSize - size, MEM_DECOMMIT ))
311 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
312 subheap->commitSize - size,
313 (DWORD)((char *)subheap + size),
314 (DWORD)subheap->heap );
317 subheap->commitSize = size;
322 /***********************************************************************
323 * HEAP_CreateFreeBlock
325 * Create a free block at a specified address. 'size' is the size of the
326 * whole block, including the new arena.
328 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
332 /* Create a free arena */
334 pFree = (ARENA_FREE *)ptr;
335 pFree->threadId = GetCurrentTask();
336 pFree->magic = ARENA_FREE_MAGIC;
338 /* If debugging, erase the freed block content */
342 char *pEnd = (char *)ptr + size;
343 if (pEnd > (char *)subheap + subheap->commitSize)
344 pEnd = (char *)subheap + subheap->commitSize;
345 if (pEnd > (char *)(pFree + 1))
346 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
349 /* Check if next block is free also */
351 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
352 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
354 /* Remove the next arena from the free list */
355 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
356 pNext->next->prev = pNext->prev;
357 pNext->prev->next = pNext->next;
358 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
360 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
363 /* Set the next block PREV_FREE flag and pointer */
365 if ((char *)ptr + size < (char *)subheap + subheap->size)
367 DWORD *pNext = (DWORD *)((char *)ptr + size);
368 *pNext |= ARENA_FLAG_PREV_FREE;
369 *(ARENA_FREE **)(pNext - 1) = pFree;
372 /* Last, insert the new block into the free list */
374 pFree->size = size - sizeof(*pFree);
375 HEAP_InsertFreeBlock( subheap->heap, pFree );
379 /***********************************************************************
380 * HEAP_MakeInUseBlockFree
382 * Turn an in-use block into a free block. Can also decommit the end of
383 * the heap, and possibly even free the sub-heap altogether.
385 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
388 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
390 /* Check if we can merge with previous block */
392 if (pArena->size & ARENA_FLAG_PREV_FREE)
394 pFree = *((ARENA_FREE **)pArena - 1);
395 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
396 /* Remove it from the free list */
397 pFree->next->prev = pFree->prev;
398 pFree->prev->next = pFree->next;
400 else pFree = (ARENA_FREE *)pArena;
402 /* Create a free block */
404 HEAP_CreateFreeBlock( subheap, pFree, size );
405 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
406 if ((char *)pFree + size < (char *)subheap + subheap->size)
407 return; /* Not the last block, so nothing more to do */
409 /* Free the whole sub-heap if it's empty and not the original one */
411 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
412 (subheap != &subheap->heap->subheap))
414 SUBHEAP *pPrev = &subheap->heap->subheap;
415 /* Remove the free block from the list */
416 pFree->next->prev = pFree->prev;
417 pFree->prev->next = pFree->next;
418 /* Remove the subheap from the list */
419 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
420 if (pPrev) pPrev->next = subheap->next;
421 /* Free the memory */
423 if (subheap->selector) FreeSelector16( subheap->selector );
424 VirtualFree( subheap, 0, MEM_RELEASE );
428 /* Decommit the end of the heap */
430 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
434 /***********************************************************************
437 * Shrink an in-use block.
439 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
441 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
443 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
444 (pArena->size & ARENA_SIZE_MASK) - size );
445 /* assign size plus previous arena flags */
446 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
450 /* Turn off PREV_FREE flag in next block */
451 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
452 if (pNext < (char *)subheap + subheap->size)
453 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
457 /***********************************************************************
460 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
461 DWORD commitSize, DWORD totalSize )
463 SUBHEAP *subheap = (SUBHEAP *)address;
465 FREE_LIST_ENTRY *pEntry;
470 if (flags & HEAP_SHARED)
471 commitSize = totalSize; /* always commit everything in a shared heap */
472 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
474 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
475 commitSize, (DWORD)address );
479 /* Allocate a selector if needed */
481 if (flags & HEAP_WINE_SEGPTR)
483 unsigned char selflags = WINE_LDT_FLAGS_DATA;
485 if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
486 selflags = WINE_LDT_FLAGS_CODE;
487 if (flags & HEAP_WINE_CODESEG)
488 selflags |= WINE_LDT_FLAGS_32BIT;
489 selector = SELECTOR_AllocBlock( address, totalSize, selflags );
492 ERR("Could not allocate selector\n" );
497 /* Fill the sub-heap structure */
499 subheap->heap = heap;
500 subheap->selector = selector;
501 subheap->size = totalSize;
502 subheap->commitSize = commitSize;
503 subheap->magic = SUBHEAP_MAGIC;
505 if ( subheap != (SUBHEAP *)heap )
507 /* If this is a secondary subheap, insert it into list */
509 subheap->headerSize = sizeof(SUBHEAP);
510 subheap->next = heap->subheap.next;
511 heap->subheap.next = subheap;
515 /* If this is a primary subheap, initialize main heap */
517 subheap->headerSize = sizeof(HEAP);
518 subheap->next = NULL;
521 heap->magic = HEAP_MAGIC;
523 /* Build the free lists */
525 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
527 pEntry->size = HEAP_freeListSizes[i];
528 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
529 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
530 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
531 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
532 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
533 pEntry->arena.threadId = 0;
534 pEntry->arena.magic = ARENA_FREE_MAGIC;
537 /* Initialize critical section */
539 InitializeCriticalSection( &heap->critSection );
542 /* Create the first free block */
544 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
545 subheap->size - subheap->headerSize );
550 /***********************************************************************
553 * Create a sub-heap of the given size.
554 * If heap == NULL, creates a main heap.
556 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
557 DWORD commitSize, DWORD totalSize )
561 /* Round-up sizes on a 64K boundary */
563 if (flags & HEAP_WINE_SEGPTR)
565 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
569 totalSize = (totalSize + 0xffff) & 0xffff0000;
570 commitSize = (commitSize + 0xffff) & 0xffff0000;
571 if (!commitSize) commitSize = 0x10000;
572 if (totalSize < commitSize) totalSize = commitSize;
575 /* Allocate the memory block */
577 if (!(address = VirtualAlloc( NULL, totalSize,
578 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
580 WARN("Could not VirtualAlloc %08lx bytes\n",
585 /* Initialize subheap */
587 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
588 address, flags, commitSize, totalSize ))
590 VirtualFree( address, 0, MEM_RELEASE );
594 return (SUBHEAP *)address;
598 /***********************************************************************
601 * Find a free block at least as large as the requested size, and make sure
602 * the requested size is committed.
604 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
605 SUBHEAP **ppSubHeap )
609 FREE_LIST_ENTRY *pEntry = heap->freeList;
611 /* Find a suitable free list, and in it find a block large enough */
613 while (pEntry->size < size) pEntry++;
614 pArena = pEntry->arena.next;
615 while (pArena != &heap->freeList[0].arena)
617 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
618 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
619 if (arena_size >= size)
621 subheap = HEAP_FindSubHeap( heap, pArena );
622 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
623 + size + HEAP_MIN_BLOCK_SIZE))
625 *ppSubHeap = subheap;
628 pArena = pArena->next;
631 /* If no block was found, attempt to grow the heap */
633 if (!(heap->flags & HEAP_GROWABLE))
635 WARN("Not enough space in heap %08lx for %08lx bytes\n",
639 /* make sure that we have a big enough size *committed* to fit another
640 * last free arena in !
641 * So just one heap struct, one first free arena which will eventually
642 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
643 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
644 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
645 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
646 max( HEAP_DEF_SIZE, size ) )))
649 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
650 (DWORD)subheap, size, (DWORD)heap );
652 *ppSubHeap = subheap;
653 return (ARENA_FREE *)(subheap + 1);
657 /***********************************************************************
658 * HEAP_IsValidArenaPtr
660 * Check that the pointer is inside the range possible for arenas.
662 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
665 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
666 if (!subheap) return FALSE;
667 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
668 if (subheap != &heap->subheap) return FALSE;
669 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
670 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
675 /***********************************************************************
676 * HEAP_ValidateFreeArena
678 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
680 char *heapEnd = (char *)subheap + subheap->size;
682 #if !defined(ALLOW_UNALIGNED_ACCESS)
683 /* Check for unaligned pointers */
684 if ( (long)pArena % sizeof(void *) != 0 )
686 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
687 (DWORD)subheap->heap, (DWORD)pArena );
692 /* Check magic number */
693 if (pArena->magic != ARENA_FREE_MAGIC)
695 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
696 (DWORD)subheap->heap, (DWORD)pArena );
699 /* Check size flags */
700 if (!(pArena->size & ARENA_FLAG_FREE) ||
701 (pArena->size & ARENA_FLAG_PREV_FREE))
703 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
704 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
706 /* Check arena size */
707 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
709 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
710 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
713 /* Check that next pointer is valid */
714 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
716 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
717 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
720 /* Check that next arena is free */
721 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
722 (pArena->next->magic != ARENA_FREE_MAGIC))
724 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
725 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
728 /* Check that prev pointer is valid */
729 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
731 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
732 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
735 /* Check that prev arena is free */
736 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
737 (pArena->prev->magic != ARENA_FREE_MAGIC))
739 /* this often means that the prev arena got overwritten
740 * by a memory write before that prev arena */
741 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
742 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
745 /* Check that next block has PREV_FREE flag */
746 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
748 if (!(*(DWORD *)((char *)(pArena + 1) +
749 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
751 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
752 (DWORD)subheap->heap, (DWORD)pArena );
755 /* Check next block back pointer */
756 if (*((ARENA_FREE **)((char *)(pArena + 1) +
757 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
759 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
760 (DWORD)subheap->heap, (DWORD)pArena,
761 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
769 /***********************************************************************
770 * HEAP_ValidateInUseArena
772 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
774 char *heapEnd = (char *)subheap + subheap->size;
776 #if !defined(ALLOW_UNALIGNED_ACCESS)
777 /* Check for unaligned pointers */
778 if ( (long)pArena % sizeof(void *) != 0 )
780 if ( quiet == NOISY )
782 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
783 (DWORD)subheap->heap, (DWORD)pArena );
784 if ( TRACE_ON(heap) )
785 HEAP_Dump( subheap->heap );
787 else if ( WARN_ON(heap) )
789 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
790 (DWORD)subheap->heap, (DWORD)pArena );
791 if ( TRACE_ON(heap) )
792 HEAP_Dump( subheap->heap );
798 /* Check magic number */
799 if (pArena->magic != ARENA_INUSE_MAGIC)
801 if (quiet == NOISY) {
802 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
803 (DWORD)subheap->heap, (DWORD)pArena );
805 HEAP_Dump( subheap->heap );
806 } else if (WARN_ON(heap)) {
807 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
808 (DWORD)subheap->heap, (DWORD)pArena );
810 HEAP_Dump( subheap->heap );
814 /* Check size flags */
815 if (pArena->size & ARENA_FLAG_FREE)
817 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
818 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
820 /* Check arena size */
821 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
823 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
824 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
827 /* Check next arena PREV_FREE flag */
828 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
829 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
831 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
832 (DWORD)subheap->heap, (DWORD)pArena );
835 /* Check prev free arena */
836 if (pArena->size & ARENA_FLAG_PREV_FREE)
838 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
839 /* Check prev pointer */
840 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
842 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
843 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
846 /* Check that prev arena is free */
847 if (!(pPrev->size & ARENA_FLAG_FREE) ||
848 (pPrev->magic != ARENA_FREE_MAGIC))
850 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
851 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
854 /* Check that prev arena is really the previous block */
855 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
857 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
858 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
866 /***********************************************************************
869 * Transform a linear pointer into a SEGPTR. The pointer must have been
870 * allocated from a HEAP_WINE_SEGPTR heap.
872 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
874 HEAP *heapPtr = HEAP_GetPtr( heap );
878 /* Validate the parameters */
880 if (!heapPtr) return 0;
881 flags |= heapPtr->flags;
882 if (!(flags & HEAP_WINE_SEGPTR))
884 ERR("Heap %08x is not a SEGPTR heap\n",
888 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
890 /* Get the subheap */
892 if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
893 ret = MAKESEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
895 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
899 /***********************************************************************
903 * Maps linear pointer to segmented.
905 SEGPTR WINAPI MapLS( LPCVOID ptr )
910 if (!HIWORD(ptr)) return (SEGPTR)ptr;
912 /* check if the pointer is inside the segptr heap */
913 EnterCriticalSection( &segptrHeap->critSection );
914 if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
915 ret = MAKESEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
916 LeaveCriticalSection( &segptrHeap->critSection );
918 /* otherwise, allocate a brand-new selector */
921 WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
922 ret = MAKESEGPTR( sel, 0 );
928 /***********************************************************************
929 * UnMapLS (KERNEL32.@)
930 * UnMapLS (KERNEL.359)
932 * Free mapped selector.
934 void WINAPI UnMapLS( SEGPTR sptr )
937 if (!SELECTOROF(sptr)) return;
939 /* check if ptr is inside segptr heap */
940 EnterCriticalSection( &segptrHeap->critSection );
941 subheap = HEAP_FindSubHeap( segptrHeap, MapSL(sptr) );
942 if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
943 LeaveCriticalSection( &segptrHeap->critSection );
944 /* if not inside heap, free the selector */
945 if (!subheap) FreeSelector16( SELECTOROF(sptr) );
948 /***********************************************************************
949 * HEAP_IsRealArena [Internal]
950 * Validates a block is a valid arena.
956 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
957 DWORD flags, /* [in] Bit flags that control access during operation */
958 LPCVOID block, /* [in] Optional pointer to memory block to validate */
959 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
960 * does not complain */
965 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
967 ERR("Invalid heap %p!\n", heapPtr );
971 flags &= HEAP_NO_SERIALIZE;
972 flags |= heapPtr->flags;
973 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
974 if (!(flags & HEAP_NO_SERIALIZE))
975 EnterCriticalSection( &heapPtr->critSection );
979 /* Only check this single memory block */
981 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
982 ((char *)block < (char *)subheap + subheap->headerSize
983 + sizeof(ARENA_INUSE)))
986 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
987 else if (WARN_ON(heap))
988 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
991 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
993 if (!(flags & HEAP_NO_SERIALIZE))
994 LeaveCriticalSection( &heapPtr->critSection );
998 subheap = &heapPtr->subheap;
999 while (subheap && ret)
1001 char *ptr = (char *)subheap + subheap->headerSize;
1002 while (ptr < (char *)subheap + subheap->size)
1004 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1006 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1010 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1014 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1018 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1021 subheap = subheap->next;
1024 if (!(flags & HEAP_NO_SERIALIZE))
1025 LeaveCriticalSection( &heapPtr->critSection );
1030 /***********************************************************************
1031 * HEAP_CreateSystemHeap
1033 * Create the system heap.
1035 static HANDLE HEAP_CreateSystemHeap(void)
1039 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1040 0, HEAP_DEF_SIZE, "__SystemHeap" );
1042 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1044 if (!(systemHeap = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1046 /* pre-defined address not available, use any one */
1047 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
1051 if (created) /* newly created heap */
1053 HEAP_InitSubHeap( systemHeap, systemHeap, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1054 MakeCriticalSectionGlobal( &systemHeap->critSection );
1058 /* wait for the heap to be initialized */
1059 while (!systemHeap->critSection.LockSemaphore) Sleep(1);
1062 return (HANDLE)systemHeap;
1066 /***********************************************************************
1067 * HeapCreate (KERNEL32.@)
1069 * Handle of heap: Success
1072 HANDLE WINAPI HeapCreate(
1073 DWORD flags, /* [in] Heap allocation flag */
1074 DWORD initialSize, /* [in] Initial heap size */
1075 DWORD maxSize /* [in] Maximum heap size */
1079 if ( flags & HEAP_SHARED ) {
1080 if (!systemHeap) HEAP_CreateSystemHeap();
1081 else WARN( "Shared Heap requested, returning system heap.\n" );
1082 return (HANDLE)systemHeap;
1085 /* Allocate the heap block */
1089 maxSize = HEAP_DEF_SIZE;
1090 flags |= HEAP_GROWABLE;
1092 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1094 SetLastError( ERROR_OUTOFMEMORY );
1098 /* link it into the per-process heap list */
1101 HEAP *heapPtr = subheap->heap;
1102 EnterCriticalSection( &processHeap->critSection );
1103 heapPtr->next = firstHeap;
1104 firstHeap = heapPtr;
1105 LeaveCriticalSection( &processHeap->critSection );
1107 else /* assume the first heap we create is the process main heap */
1110 processHeap = subheap->heap;
1111 /* create the SEGPTR heap */
1112 if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1114 SetLastError( ERROR_OUTOFMEMORY );
1117 segptrHeap = segptr->heap;
1119 return (HANDLE)subheap;
1122 /***********************************************************************
1123 * HeapDestroy (KERNEL32.@)
1128 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1130 HEAP *heapPtr = HEAP_GetPtr( heap );
1133 TRACE("%08x\n", heap );
1134 if (!heapPtr) return FALSE;
1136 if (heapPtr == systemHeap)
1138 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1141 if (heapPtr == processHeap) /* cannot delete the main process heap */
1143 SetLastError( ERROR_INVALID_PARAMETER );
1146 else /* remove it from the per-process list */
1149 EnterCriticalSection( &processHeap->critSection );
1151 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1152 if (*pptr) *pptr = (*pptr)->next;
1153 LeaveCriticalSection( &processHeap->critSection );
1156 DeleteCriticalSection( &heapPtr->critSection );
1157 subheap = &heapPtr->subheap;
1160 SUBHEAP *next = subheap->next;
1161 if (subheap->selector) FreeSelector16( subheap->selector );
1162 VirtualFree( subheap, 0, MEM_RELEASE );
1169 /***********************************************************************
1170 * HeapAlloc (KERNEL32.@)
1172 * Pointer to allocated memory block
1175 LPVOID WINAPI HeapAlloc(
1176 HANDLE heap, /* [in] Handle of private heap block */
1177 DWORD flags, /* [in] Heap allocation control flags */
1178 DWORD size /* [in] Number of bytes to allocate */
1181 ARENA_INUSE *pInUse;
1183 HEAP *heapPtr = HEAP_GetPtr( heap );
1185 /* Validate the parameters */
1187 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1188 if (!heapPtr) return NULL;
1189 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1190 flags |= heapPtr->flags;
1191 size = (size + 3) & ~3;
1192 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1194 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1195 /* Locate a suitable free block */
1197 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1199 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1200 heap, flags, size );
1201 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1202 SetLastError( ERROR_COMMITMENT_LIMIT );
1206 /* Remove the arena from the free list */
1208 pArena->next->prev = pArena->prev;
1209 pArena->prev->next = pArena->next;
1211 /* Build the in-use arena */
1213 pInUse = (ARENA_INUSE *)pArena;
1215 /* in-use arena is smaller than free arena,
1216 * so we have to add the difference to the size */
1217 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1218 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1219 pInUse->callerEIP = GET_EIP();
1220 pInUse->threadId = GetCurrentTask();
1221 pInUse->magic = ARENA_INUSE_MAGIC;
1223 /* Shrink the block */
1225 HEAP_ShrinkBlock( subheap, pInUse, size );
1227 if (flags & HEAP_ZERO_MEMORY)
1228 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1229 else if (TRACE_ON(heap))
1230 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1232 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1234 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1235 heap, flags, size, (DWORD)(pInUse + 1) );
1236 return (LPVOID)(pInUse + 1);
1240 /***********************************************************************
1241 * HeapFree (KERNEL32.@)
1246 BOOL WINAPI HeapFree(
1247 HANDLE heap, /* [in] Handle of heap */
1248 DWORD flags, /* [in] Heap freeing flags */
1249 LPVOID ptr /* [in] Address of memory to free */
1251 ARENA_INUSE *pInUse;
1253 HEAP *heapPtr = HEAP_GetPtr( heap );
1255 /* Validate the parameters */
1257 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1258 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1259 if (!heapPtr) return FALSE;
1261 flags &= HEAP_NO_SERIALIZE;
1262 flags |= heapPtr->flags;
1263 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1264 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1266 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1267 SetLastError( ERROR_INVALID_PARAMETER );
1268 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1269 heap, flags, (DWORD)ptr );
1273 /* Turn the block into a free block */
1275 pInUse = (ARENA_INUSE *)ptr - 1;
1276 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1277 HEAP_MakeInUseBlockFree( subheap, pInUse );
1279 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1281 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1282 heap, flags, (DWORD)ptr );
1287 /***********************************************************************
1288 * HeapReAlloc (KERNEL32.@)
1290 * Pointer to reallocated memory block
1293 LPVOID WINAPI HeapReAlloc(
1294 HANDLE heap, /* [in] Handle of heap block */
1295 DWORD flags, /* [in] Heap reallocation flags */
1296 LPVOID ptr, /* [in] Address of memory to reallocate */
1297 DWORD size /* [in] Number of bytes to reallocate */
1299 ARENA_INUSE *pArena;
1304 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1305 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1306 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1308 /* Validate the parameters */
1310 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1311 HEAP_REALLOC_IN_PLACE_ONLY;
1312 flags |= heapPtr->flags;
1313 size = (size + 3) & ~3;
1314 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1316 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1317 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1319 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1320 SetLastError( ERROR_INVALID_PARAMETER );
1321 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1322 heap, flags, (DWORD)ptr, size );
1326 /* Check if we need to grow the block */
1328 pArena = (ARENA_INUSE *)ptr - 1;
1329 pArena->threadId = GetCurrentTask();
1330 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1331 oldSize = (pArena->size & ARENA_SIZE_MASK);
1334 char *pNext = (char *)(pArena + 1) + oldSize;
1335 if ((pNext < (char *)subheap + subheap->size) &&
1336 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1337 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1339 /* The next block is free and large enough */
1340 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1341 pFree->next->prev = pFree->prev;
1342 pFree->prev->next = pFree->next;
1343 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1344 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1345 + size + HEAP_MIN_BLOCK_SIZE))
1347 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1348 SetLastError( ERROR_OUTOFMEMORY );
1351 HEAP_ShrinkBlock( subheap, pArena, size );
1353 else /* Do it the hard way */
1356 ARENA_INUSE *pInUse;
1357 SUBHEAP *newsubheap;
1359 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1360 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1362 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1363 SetLastError( ERROR_OUTOFMEMORY );
1367 /* Build the in-use arena */
1369 pNew->next->prev = pNew->prev;
1370 pNew->prev->next = pNew->next;
1371 pInUse = (ARENA_INUSE *)pNew;
1372 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1373 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1374 pInUse->threadId = GetCurrentTask();
1375 pInUse->magic = ARENA_INUSE_MAGIC;
1376 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1377 memcpy( pInUse + 1, pArena + 1, oldSize );
1379 /* Free the previous block */
1381 HEAP_MakeInUseBlockFree( subheap, pArena );
1382 subheap = newsubheap;
1386 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1388 /* Clear the extra bytes if needed */
1392 if (flags & HEAP_ZERO_MEMORY)
1393 memset( (char *)(pArena + 1) + oldSize, 0,
1394 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1395 else if (TRACE_ON(heap))
1396 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1397 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1400 /* Return the new arena */
1402 pArena->callerEIP = GET_EIP();
1403 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1405 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1406 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1407 return (LPVOID)(pArena + 1);
1411 /***********************************************************************
1412 * HeapCompact (KERNEL32.@)
1414 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1416 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1421 /***********************************************************************
1422 * HeapLock (KERNEL32.@)
1423 * Attempts to acquire the critical section object for a specified heap.
1429 BOOL WINAPI HeapLock(
1430 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1432 HEAP *heapPtr = HEAP_GetPtr( heap );
1433 if (!heapPtr) return FALSE;
1434 EnterCriticalSection( &heapPtr->critSection );
1439 /***********************************************************************
1440 * HeapUnlock (KERNEL32.@)
1441 * Releases ownership of the critical section object.
1447 BOOL WINAPI HeapUnlock(
1448 HANDLE heap /* [in] Handle to the heap to unlock */
1450 HEAP *heapPtr = HEAP_GetPtr( heap );
1451 if (!heapPtr) return FALSE;
1452 LeaveCriticalSection( &heapPtr->critSection );
1457 /***********************************************************************
1458 * HeapSize (KERNEL32.@)
1460 * Size in bytes of allocated memory
1461 * 0xffffffff: Failure
1463 DWORD WINAPI HeapSize(
1464 HANDLE heap, /* [in] Handle of heap */
1465 DWORD flags, /* [in] Heap size control flags */
1466 LPVOID ptr /* [in] Address of memory to return size for */
1469 HEAP *heapPtr = HEAP_GetPtr( heap );
1471 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1472 if (!heapPtr) return FALSE;
1473 flags &= HEAP_NO_SERIALIZE;
1474 flags |= heapPtr->flags;
1475 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1476 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1478 SetLastError( ERROR_INVALID_PARAMETER );
1483 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1484 ret = pArena->size & ARENA_SIZE_MASK;
1486 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1488 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1489 heap, flags, (DWORD)ptr, ret );
1494 /***********************************************************************
1495 * HeapValidate (KERNEL32.@)
1496 * Validates a specified heap.
1505 BOOL WINAPI HeapValidate(
1506 HANDLE heap, /* [in] Handle to the heap */
1507 DWORD flags, /* [in] Bit flags that control access during operation */
1508 LPCVOID block /* [in] Optional pointer to memory block to validate */
1510 HEAP *heapPtr = HEAP_GetPtr( heap );
1511 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1512 if (!heapPtr) return FALSE;
1513 return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1517 /***********************************************************************
1518 * HeapWalk (KERNEL32.@)
1519 * Enumerates the memory blocks in a specified heap.
1520 * See HEAP_Dump() for info on heap structure.
1523 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1524 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1530 BOOL WINAPI HeapWalk(
1531 HANDLE heap, /* [in] Handle to heap to enumerate */
1532 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1534 HEAP *heapPtr = HEAP_GetPtr(heap);
1535 SUBHEAP *sub, *currentheap = NULL;
1538 int region_index = 0;
1540 if (!heapPtr || !entry)
1542 SetLastError(ERROR_INVALID_PARAMETER);
1546 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1548 /* set ptr to the next arena to be examined */
1550 if (!entry->lpData) /* first call (init) ? */
1552 TRACE("begin walking of heap 0x%08x.\n", heap);
1553 /*HEAP_Dump(heapPtr);*/
1554 currentheap = &heapPtr->subheap;
1555 ptr = (char*)currentheap + currentheap->headerSize;
1559 ptr = entry->lpData;
1560 sub = &heapPtr->subheap;
1563 if (((char *)ptr >= (char *)sub) &&
1564 ((char *)ptr < (char *)sub + sub->size))
1572 if (currentheap == NULL)
1574 ERR("no matching subheap found, shouldn't happen !\n");
1575 SetLastError(ERROR_NO_MORE_ITEMS);
1579 ptr += entry->cbData; /* point to next arena */
1580 if (ptr > (char *)currentheap + currentheap->size - 1)
1581 { /* proceed with next subheap */
1582 if (!(currentheap = currentheap->next))
1583 { /* successfully finished */
1584 TRACE("end reached.\n");
1585 SetLastError(ERROR_NO_MORE_ITEMS);
1588 ptr = (char*)currentheap + currentheap->headerSize;
1593 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1595 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1597 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1599 entry->lpData = pArena + 1;
1600 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1601 entry->cbOverhead = sizeof(ARENA_FREE);
1602 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1606 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1608 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1610 entry->lpData = pArena + 1;
1611 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1612 entry->cbOverhead = sizeof(ARENA_INUSE);
1613 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1614 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1615 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1618 entry->iRegionIndex = region_index;
1620 /* first element of heap ? */
1621 if (ptr == (char *)(currentheap + currentheap->headerSize))
1623 entry->wFlags |= PROCESS_HEAP_REGION;
1624 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1625 entry->u.Region.dwUnCommittedSize =
1626 currentheap->size - currentheap->commitSize;
1627 entry->u.Region.lpFirstBlock = /* first valid block */
1628 currentheap + currentheap->headerSize;
1629 entry->u.Region.lpLastBlock = /* first invalid block */
1630 currentheap + currentheap->size;
1635 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1641 /***********************************************************************
1642 * GetProcessHeap (KERNEL32.@)
1644 HANDLE WINAPI GetProcessHeap(void)
1646 return (HANDLE)processHeap;
1650 /***********************************************************************
1651 * GetProcessHeaps (KERNEL32.@)
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 /***********************************************************************
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( GetProcessHeap(), 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 = MapSL( 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 = MapSL( 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 /***********************************************************************
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 /***********************************************************************
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 /***********************************************************************
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 /***********************************************************************
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 /***********************************************************************
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 /***********************************************************************
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 /***********************************************************************
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)
2143 * Local32Info (TOOLHELP.84)
2145 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2151 LOCAL32HEADER *header = Local32_GetHeap( handle );
2152 if ( !header ) return FALSE;
2154 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2157 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2158 pLocal32Info->dwMemReserved = heapPtr->size;
2159 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2160 pLocal32Info->dwTotalFree = 0L;
2161 pLocal32Info->dwLargestFreeBlock = 0L;
2163 /* Note: Local32 heaps always have only one subheap! */
2164 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2165 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2167 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2169 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2170 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2171 ptr += sizeof(*pArena) + size;
2173 pLocal32Info->dwTotalFree += size;
2174 if ( size > pLocal32Info->dwLargestFreeBlock )
2175 pLocal32Info->dwLargestFreeBlock = size;
2179 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2180 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2181 ptr += sizeof(*pArena) + size;
2185 pLocal32Info->dwcFreeHandles = 0;
2186 for ( i = 0; i < HTABLE_NPAGES; i++ )
2188 if ( header->freeListFirst[i] == 0xffff ) break;
2189 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2191 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2196 /***********************************************************************
2197 * Local32First (KERNEL.445)
2198 * Local32First (TOOLHELP.85)
2200 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2202 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2206 /***********************************************************************
2207 * Local32Next (KERNEL.446)
2208 * Local32Next (TOOLHELP.86)
2210 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2212 FIXME("(%p): stub!\n", pLocal32Entry );