New debug scheme with explicit debug channels declaration.
[wine/testsucceed.git] / memory / heap.c
blobdfd174c3fefa2e323cdb0d52a49d1e1a6648121c
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
6 */
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include "wine/winbase16.h"
12 #include "wine/winestring.h"
13 #include "selectors.h"
14 #include "global.h"
15 #include "winbase.h"
16 #include "winerror.h"
17 #include "winnt.h"
18 #include "heap.h"
19 #include "toolhelp.h"
20 #include "debug.h"
22 DEFAULT_DEBUG_CHANNEL(heap)
24 /* Note: the heap data structures are based on what Pietrek describes in his
25 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
26 * the same, but could be easily adapted if it turns out some programs
27 * require it.
30 typedef struct tagARENA_INUSE
32 DWORD size; /* Block size; must be the first field */
33 WORD threadId; /* Allocating thread id */
34 WORD magic; /* Magic number */
35 DWORD callerEIP; /* EIP of caller upon allocation */
36 } ARENA_INUSE;
38 typedef struct tagARENA_FREE
40 DWORD size; /* Block size; must be the first field */
41 WORD threadId; /* Freeing thread id */
42 WORD magic; /* Magic number */
43 struct tagARENA_FREE *next; /* Next free arena */
44 struct tagARENA_FREE *prev; /* Prev free arena */
45 } ARENA_FREE;
47 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
48 #define ARENA_FLAG_PREV_FREE 0x00000002
49 #define ARENA_SIZE_MASK 0xfffffffc
50 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
51 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
53 #define ARENA_INUSE_FILLER 0x55
54 #define ARENA_FREE_FILLER 0xaa
56 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
58 /* Max size of the blocks on the free lists */
59 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
61 0x20, 0x80, 0x200, 0xffffffff
64 typedef struct
66 DWORD size;
67 ARENA_FREE arena;
68 } FREE_LIST_ENTRY;
70 struct tagHEAP;
72 typedef struct tagSUBHEAP
74 DWORD size; /* Size of the whole sub-heap */
75 DWORD commitSize; /* Committed size of the sub-heap */
76 DWORD headerSize; /* Size of the heap header */
77 struct tagSUBHEAP *next; /* Next sub-heap */
78 struct tagHEAP *heap; /* Main heap structure */
79 DWORD magic; /* Magic number */
80 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
81 } SUBHEAP;
83 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
85 typedef struct tagHEAP
87 SUBHEAP subheap; /* First sub-heap */
88 struct tagHEAP *next; /* Next heap for this process */
89 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
90 CRITICAL_SECTION critSection; /* Critical section for serialization */
91 DWORD flags; /* Heap flags */
92 DWORD magic; /* Magic number */
93 } HEAP;
95 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
97 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
98 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
100 HANDLE SystemHeap = 0;
101 HANDLE SegptrHeap = 0;
104 /***********************************************************************
105 * HEAP_Dump
107 void HEAP_Dump( HEAP *heap )
109 int i;
110 SUBHEAP *subheap;
111 char *ptr;
113 DUMP( "Heap: %08lx\n", (DWORD)heap );
114 DUMP( "Next: %08lx Sub-heaps: %08lx",
115 (DWORD)heap->next, (DWORD)&heap->subheap );
116 subheap = &heap->subheap;
117 while (subheap->next)
119 DUMP( " -> %08lx", (DWORD)subheap->next );
120 subheap = subheap->next;
123 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
124 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
125 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
126 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
127 heap->freeList[i].arena.threadId,
128 (DWORD)heap->freeList[i].arena.prev,
129 (DWORD)heap->freeList[i].arena.next );
131 subheap = &heap->subheap;
132 while (subheap)
134 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
135 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
136 (DWORD)subheap, subheap->size, subheap->commitSize );
138 DUMP( "\n Block Stat Size Id\n" );
139 ptr = (char*)subheap + subheap->headerSize;
140 while (ptr < (char *)subheap + subheap->size)
142 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
144 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
145 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
146 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
147 pArena->threadId, (DWORD)pArena->prev,
148 (DWORD)pArena->next);
149 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
150 arenaSize += sizeof(ARENA_FREE);
151 freeSize += pArena->size & ARENA_SIZE_MASK;
153 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
155 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
156 DUMP( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
157 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
158 pArena->threadId, *((DWORD *)pArena - 1),
159 pArena->callerEIP );
160 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
161 arenaSize += sizeof(ARENA_INUSE);
162 usedSize += pArena->size & ARENA_SIZE_MASK;
164 else
166 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
167 DUMP( "%08lx used %08lx %04x EIP=%08lx\n",
168 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
169 pArena->threadId, pArena->callerEIP );
170 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171 arenaSize += sizeof(ARENA_INUSE);
172 usedSize += pArena->size & ARENA_SIZE_MASK;
175 DUMP( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
176 subheap->size, subheap->commitSize, freeSize, usedSize,
177 arenaSize, (arenaSize * 100) / subheap->size );
178 subheap = subheap->next;
183 /***********************************************************************
184 * HEAP_GetPtr
185 * RETURNS
186 * Pointer to the heap
187 * NULL: Failure
189 static HEAP *HEAP_GetPtr(
190 HANDLE heap /* [in] Handle to the heap */
192 HEAP *heapPtr = (HEAP *)heap;
193 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
195 ERR(heap, "Invalid heap %08x!\n", heap );
196 SetLastError( ERROR_INVALID_HANDLE );
197 return NULL;
199 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
201 HEAP_Dump( heapPtr );
202 assert( FALSE );
203 SetLastError( ERROR_INVALID_HANDLE );
204 return NULL;
206 return heapPtr;
210 /***********************************************************************
211 * HEAP_InsertFreeBlock
213 * Insert a free block into the free list.
215 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
217 FREE_LIST_ENTRY *pEntry = heap->freeList;
218 while (pEntry->size < pArena->size) pEntry++;
219 pArena->size |= ARENA_FLAG_FREE;
220 pArena->next = pEntry->arena.next;
221 pArena->next->prev = pArena;
222 pArena->prev = &pEntry->arena;
223 pEntry->arena.next = pArena;
227 /***********************************************************************
228 * HEAP_FindSubHeap
229 * Find the sub-heap containing a given address.
231 * RETURNS
232 * Pointer: Success
233 * NULL: Failure
235 static SUBHEAP *HEAP_FindSubHeap(
236 HEAP *heap, /* [in] Heap pointer */
237 LPCVOID ptr /* [in] Address */
239 SUBHEAP *sub = &heap->subheap;
240 while (sub)
242 if (((char *)ptr >= (char *)sub) &&
243 ((char *)ptr < (char *)sub + sub->size)) return sub;
244 sub = sub->next;
246 return NULL;
250 /***********************************************************************
251 * HEAP_Commit
253 * Make sure the heap storage is committed up to (not including) ptr.
255 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
257 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
258 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
259 if (size > subheap->size) size = subheap->size;
260 if (size <= subheap->commitSize) return TRUE;
261 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
262 size - subheap->commitSize, MEM_COMMIT,
263 PAGE_EXECUTE_READWRITE))
265 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
266 size - subheap->commitSize,
267 (DWORD)((char *)subheap + subheap->commitSize),
268 (DWORD)subheap->heap );
269 return FALSE;
271 subheap->commitSize = size;
272 return TRUE;
276 /***********************************************************************
277 * HEAP_Decommit
279 * If possible, decommit the heap storage from (including) 'ptr'.
281 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
283 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
284 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
285 if (size >= subheap->commitSize) return TRUE;
286 if (!VirtualFree( (char *)subheap + size,
287 subheap->commitSize - size, MEM_DECOMMIT ))
289 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
290 subheap->commitSize - size,
291 (DWORD)((char *)subheap + size),
292 (DWORD)subheap->heap );
293 return FALSE;
295 subheap->commitSize = size;
296 return TRUE;
300 /***********************************************************************
301 * HEAP_CreateFreeBlock
303 * Create a free block at a specified address. 'size' is the size of the
304 * whole block, including the new arena.
306 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
308 ARENA_FREE *pFree;
310 /* Create a free arena */
312 pFree = (ARENA_FREE *)ptr;
313 pFree->threadId = GetCurrentTask();
314 pFree->magic = ARENA_FREE_MAGIC;
316 /* If debugging, erase the freed block content */
318 if (TRACE_ON(heap))
320 char *pEnd = (char *)ptr + size;
321 if (pEnd > (char *)subheap + subheap->commitSize)
322 pEnd = (char *)subheap + subheap->commitSize;
323 if (pEnd > (char *)(pFree + 1))
324 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
327 /* Check if next block is free also */
329 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
330 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
332 /* Remove the next arena from the free list */
333 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
334 pNext->next->prev = pNext->prev;
335 pNext->prev->next = pNext->next;
336 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
337 if (TRACE_ON(heap))
338 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
341 /* Set the next block PREV_FREE flag and pointer */
343 if ((char *)ptr + size < (char *)subheap + subheap->size)
345 DWORD *pNext = (DWORD *)((char *)ptr + size);
346 *pNext |= ARENA_FLAG_PREV_FREE;
347 *(ARENA_FREE **)(pNext - 1) = pFree;
350 /* Last, insert the new block into the free list */
352 pFree->size = size - sizeof(*pFree);
353 HEAP_InsertFreeBlock( subheap->heap, pFree );
357 /***********************************************************************
358 * HEAP_MakeInUseBlockFree
360 * Turn an in-use block into a free block. Can also decommit the end of
361 * the heap, and possibly even free the sub-heap altogether.
363 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
365 ARENA_FREE *pFree;
366 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
368 /* Check if we can merge with previous block */
370 if (pArena->size & ARENA_FLAG_PREV_FREE)
372 pFree = *((ARENA_FREE **)pArena - 1);
373 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
374 /* Remove it from the free list */
375 pFree->next->prev = pFree->prev;
376 pFree->prev->next = pFree->next;
378 else pFree = (ARENA_FREE *)pArena;
380 /* Create a free block */
382 HEAP_CreateFreeBlock( subheap, pFree, size );
383 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
384 if ((char *)pFree + size < (char *)subheap + subheap->size)
385 return; /* Not the last block, so nothing more to do */
387 /* Free the whole sub-heap if it's empty and not the original one */
389 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
390 (subheap != &subheap->heap->subheap))
392 SUBHEAP *pPrev = &subheap->heap->subheap;
393 /* Remove the free block from the list */
394 pFree->next->prev = pFree->prev;
395 pFree->prev->next = pFree->next;
396 /* Remove the subheap from the list */
397 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
398 if (pPrev) pPrev->next = subheap->next;
399 /* Free the memory */
400 subheap->magic = 0;
401 if (subheap->selector) FreeSelector16( subheap->selector );
402 VirtualFree( subheap, 0, MEM_RELEASE );
403 return;
406 /* Decommit the end of the heap */
408 HEAP_Decommit( subheap, pFree + 1 );
412 /***********************************************************************
413 * HEAP_ShrinkBlock
415 * Shrink an in-use block.
417 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
419 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
421 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
422 (pArena->size & ARENA_SIZE_MASK) - size );
423 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
425 else
427 /* Turn off PREV_FREE flag in next block */
428 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
429 if (pNext < (char *)subheap + subheap->size)
430 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
434 /***********************************************************************
435 * HEAP_InitSubHeap
437 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
438 DWORD commitSize, DWORD totalSize )
440 SUBHEAP *subheap = (SUBHEAP *)address;
441 WORD selector = 0;
442 FREE_LIST_ENTRY *pEntry;
443 int i;
445 /* Commit memory */
447 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
449 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
450 commitSize, (DWORD)address );
451 return FALSE;
454 /* Allocate a selector if needed */
456 if (flags & HEAP_WINE_SEGPTR)
458 selector = SELECTOR_AllocBlock( address, totalSize,
459 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
460 ? SEGMENT_CODE : SEGMENT_DATA,
461 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
462 if (!selector)
464 ERR(heap, "Could not allocate selector\n" );
465 return FALSE;
469 /* Fill the sub-heap structure */
471 subheap->heap = heap;
472 subheap->selector = selector;
473 subheap->size = totalSize;
474 subheap->commitSize = commitSize;
475 subheap->magic = SUBHEAP_MAGIC;
477 if ( subheap != (SUBHEAP *)heap )
479 /* If this is a secondary subheap, insert it into list */
481 subheap->headerSize = sizeof(SUBHEAP);
482 subheap->next = heap->subheap.next;
483 heap->subheap.next = subheap;
485 else
487 /* If this is a primary subheap, initialize main heap */
489 subheap->headerSize = sizeof(HEAP);
490 subheap->next = NULL;
491 heap->next = NULL;
492 heap->flags = flags;
493 heap->magic = HEAP_MAGIC;
495 /* Build the free lists */
497 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
499 pEntry->size = HEAP_freeListSizes[i];
500 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
501 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
502 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
503 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
504 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
505 pEntry->arena.threadId = 0;
506 pEntry->arena.magic = ARENA_FREE_MAGIC;
509 /* Initialize critical section */
511 InitializeCriticalSection( &heap->critSection );
512 if (!SystemHeap) /* System heap critical section has to be global */
513 MakeCriticalSectionGlobal( &heap->critSection );
516 /* Create the first free block */
518 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
519 subheap->size - subheap->headerSize );
521 return TRUE;
524 /***********************************************************************
525 * HEAP_CreateSubHeap
527 * Create a sub-heap of the given size.
528 * If heap == NULL, creates a main heap.
530 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
531 DWORD commitSize, DWORD totalSize )
533 LPVOID address;
535 /* Round-up sizes on a 64K boundary */
537 if (flags & HEAP_WINE_SEGPTR)
539 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
541 else
543 totalSize = (totalSize + 0xffff) & 0xffff0000;
544 commitSize = (commitSize + 0xffff) & 0xffff0000;
545 if (!commitSize) commitSize = 0x10000;
546 if (totalSize < commitSize) totalSize = commitSize;
549 /* Allocate the memory block */
551 if (!(address = VirtualAlloc( NULL, totalSize,
552 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
554 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
555 totalSize );
556 return NULL;
559 /* Initialize subheap */
561 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
562 address, flags, commitSize, totalSize ))
564 VirtualFree( address, 0, MEM_RELEASE );
565 return NULL;
568 return (SUBHEAP *)address;
572 /***********************************************************************
573 * HEAP_FindFreeBlock
575 * Find a free block at least as large as the requested size, and make sure
576 * the requested size is committed.
578 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
579 SUBHEAP **ppSubHeap )
581 SUBHEAP *subheap;
582 ARENA_FREE *pArena;
583 FREE_LIST_ENTRY *pEntry = heap->freeList;
585 /* Find a suitable free list, and in it find a block large enough */
587 while (pEntry->size < size) pEntry++;
588 pArena = pEntry->arena.next;
589 while (pArena != &heap->freeList[0].arena)
591 if (pArena->size > size)
593 subheap = HEAP_FindSubHeap( heap, pArena );
594 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
595 + size + HEAP_MIN_BLOCK_SIZE))
596 return NULL;
597 *ppSubHeap = subheap;
598 return pArena;
601 pArena = pArena->next;
604 /* If no block was found, attempt to grow the heap */
606 if (!(heap->flags & HEAP_GROWABLE))
608 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
609 (DWORD)heap, size );
610 return NULL;
612 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
613 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
614 MAX( HEAP_DEF_SIZE, size ) )))
615 return NULL;
617 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
618 (DWORD)subheap, size, (DWORD)heap );
620 *ppSubHeap = subheap;
621 return (ARENA_FREE *)(subheap + 1);
625 /***********************************************************************
626 * HEAP_IsValidArenaPtr
628 * Check that the pointer is inside the range possible for arenas.
630 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
632 int i;
633 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
634 if (!subheap) return FALSE;
635 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
636 if (subheap != &heap->subheap) return FALSE;
637 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
638 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
639 return FALSE;
643 /***********************************************************************
644 * HEAP_ValidateFreeArena
646 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
648 char *heapEnd = (char *)subheap + subheap->size;
650 /* Check magic number */
651 if (pArena->magic != ARENA_FREE_MAGIC)
653 ERR(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
654 (DWORD)subheap->heap, (DWORD)pArena );
655 return FALSE;
657 /* Check size flags */
658 if (!(pArena->size & ARENA_FLAG_FREE) ||
659 (pArena->size & ARENA_FLAG_PREV_FREE))
661 ERR(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
662 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
664 /* Check arena size */
665 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
667 ERR(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
668 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
669 return FALSE;
671 /* Check that next pointer is valid */
672 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
674 ERR(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
675 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
676 return FALSE;
678 /* Check that next arena is free */
679 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
680 (pArena->next->magic != ARENA_FREE_MAGIC))
682 ERR(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
683 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
684 return FALSE;
686 /* Check that prev pointer is valid */
687 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
689 ERR(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
690 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
691 return FALSE;
693 /* Check that prev arena is free */
694 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
695 (pArena->prev->magic != ARENA_FREE_MAGIC))
697 ERR(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
698 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
699 return FALSE;
701 /* Check that next block has PREV_FREE flag */
702 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
704 if (!(*(DWORD *)((char *)(pArena + 1) +
705 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
707 ERR(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
708 (DWORD)subheap->heap, (DWORD)pArena );
709 return FALSE;
711 /* Check next block back pointer */
712 if (*((ARENA_FREE **)((char *)(pArena + 1) +
713 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
715 ERR(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
716 (DWORD)subheap->heap, (DWORD)pArena,
717 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
718 return FALSE;
721 return TRUE;
725 /***********************************************************************
726 * HEAP_ValidateInUseArena
728 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
730 char *heapEnd = (char *)subheap + subheap->size;
732 /* Check magic number */
733 if (pArena->magic != ARENA_INUSE_MAGIC)
735 ERR(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
736 (DWORD)subheap->heap, (DWORD)pArena );
737 return FALSE;
739 /* Check size flags */
740 if (pArena->size & ARENA_FLAG_FREE)
742 ERR(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
743 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
745 /* Check arena size */
746 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
748 ERR(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
749 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
750 return FALSE;
752 /* Check next arena PREV_FREE flag */
753 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
754 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
756 ERR(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
757 (DWORD)subheap->heap, (DWORD)pArena );
758 return FALSE;
760 /* Check prev free arena */
761 if (pArena->size & ARENA_FLAG_PREV_FREE)
763 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
764 /* Check prev pointer */
765 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
767 ERR(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
768 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
769 return FALSE;
771 /* Check that prev arena is free */
772 if (!(pPrev->size & ARENA_FLAG_FREE) ||
773 (pPrev->magic != ARENA_FREE_MAGIC))
775 ERR(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
776 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
777 return FALSE;
779 /* Check that prev arena is really the previous block */
780 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
782 ERR(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
783 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
784 return FALSE;
787 return TRUE;
791 /***********************************************************************
792 * HEAP_IsInsideHeap
793 * Checks whether the pointer points to a block inside a given heap.
795 * NOTES
796 * Should this return BOOL32?
798 * RETURNS
799 * !0: Success
800 * 0: Failure
802 int HEAP_IsInsideHeap(
803 HANDLE heap, /* [in] Heap */
804 DWORD flags, /* [in] Flags */
805 LPCVOID ptr /* [in] Pointer */
807 HEAP *heapPtr = HEAP_GetPtr( heap );
808 SUBHEAP *subheap;
809 int ret;
811 /* Validate the parameters */
813 if (!heapPtr) return 0;
814 flags |= heapPtr->flags;
815 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
816 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
817 (((char *)ptr >= (char *)subheap + subheap->headerSize
818 + sizeof(ARENA_INUSE))));
819 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
820 return ret;
824 /***********************************************************************
825 * HEAP_GetSegptr
827 * Transform a linear pointer into a SEGPTR. The pointer must have been
828 * allocated from a HEAP_WINE_SEGPTR heap.
830 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
832 HEAP *heapPtr = HEAP_GetPtr( heap );
833 SUBHEAP *subheap;
834 SEGPTR ret;
836 /* Validate the parameters */
838 if (!heapPtr) return 0;
839 flags |= heapPtr->flags;
840 if (!(flags & HEAP_WINE_SEGPTR))
842 ERR(heap, "Heap %08x is not a SEGPTR heap\n",
843 heap );
844 return 0;
846 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
848 /* Get the subheap */
850 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
852 ERR(heap, "%p is not inside heap %08x\n",
853 ptr, heap );
854 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
855 return 0;
858 /* Build the SEGPTR */
860 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
861 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
862 return ret;
866 /***********************************************************************
867 * HeapCreate (KERNEL32.336)
868 * RETURNS
869 * Handle of heap: Success
870 * NULL: Failure
872 HANDLE WINAPI HeapCreate(
873 DWORD flags, /* [in] Heap allocation flag */
874 DWORD initialSize, /* [in] Initial heap size */
875 DWORD maxSize /* [in] Maximum heap size */
877 SUBHEAP *subheap;
879 /* Allocate the heap block */
881 if (!maxSize)
883 maxSize = HEAP_DEF_SIZE;
884 flags |= HEAP_GROWABLE;
886 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
888 SetLastError( ERROR_OUTOFMEMORY );
889 return 0;
892 return (HANDLE)subheap;
895 /***********************************************************************
896 * HeapDestroy (KERNEL32.337)
897 * RETURNS
898 * TRUE: Success
899 * FALSE: Failure
901 BOOL WINAPI HeapDestroy(
902 HANDLE heap /* [in] Handle of heap */
904 HEAP *heapPtr = HEAP_GetPtr( heap );
905 SUBHEAP *subheap;
907 TRACE(heap, "%08x\n", heap );
908 if (!heapPtr) return FALSE;
910 DeleteCriticalSection( &heapPtr->critSection );
911 subheap = &heapPtr->subheap;
912 while (subheap)
914 SUBHEAP *next = subheap->next;
915 if (subheap->selector) FreeSelector16( subheap->selector );
916 VirtualFree( subheap, 0, MEM_RELEASE );
917 subheap = next;
919 return TRUE;
923 /***********************************************************************
924 * HeapAlloc (KERNEL32.334)
925 * RETURNS
926 * Pointer to allocated memory block
927 * NULL: Failure
929 LPVOID WINAPI HeapAlloc(
930 HANDLE heap, /* [in] Handle of private heap block */
931 DWORD flags, /* [in] Heap allocation control flags */
932 DWORD size /* [in] Number of bytes to allocate */
934 ARENA_FREE *pArena;
935 ARENA_INUSE *pInUse;
936 SUBHEAP *subheap;
937 HEAP *heapPtr = HEAP_GetPtr( heap );
939 /* Validate the parameters */
941 if (!heapPtr) return NULL;
942 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
943 flags |= heapPtr->flags;
944 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
945 size = (size + 3) & ~3;
946 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
948 /* Locate a suitable free block */
950 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
952 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
953 heap, flags, size );
954 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
955 SetLastError( ERROR_COMMITMENT_LIMIT );
956 return NULL;
959 /* Remove the arena from the free list */
961 pArena->next->prev = pArena->prev;
962 pArena->prev->next = pArena->next;
964 /* Build the in-use arena */
966 pInUse = (ARENA_INUSE *)pArena;
967 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
968 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
969 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
970 pInUse->threadId = GetCurrentTask();
971 pInUse->magic = ARENA_INUSE_MAGIC;
973 /* Shrink the block */
975 HEAP_ShrinkBlock( subheap, pInUse, size );
977 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
978 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
980 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
982 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
983 heap, flags, size, (DWORD)(pInUse + 1) );
984 return (LPVOID)(pInUse + 1);
988 /***********************************************************************
989 * HeapFree (KERNEL32.338)
990 * RETURNS
991 * TRUE: Success
992 * FALSE: Failure
994 BOOL WINAPI HeapFree(
995 HANDLE heap, /* [in] Handle of heap */
996 DWORD flags, /* [in] Heap freeing flags */
997 LPVOID ptr /* [in] Address of memory to free */
999 ARENA_INUSE *pInUse;
1000 SUBHEAP *subheap;
1001 HEAP *heapPtr = HEAP_GetPtr( heap );
1003 /* Validate the parameters */
1005 if (!heapPtr) return FALSE;
1006 flags &= HEAP_NO_SERIALIZE;
1007 flags |= heapPtr->flags;
1008 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1009 if (!ptr)
1011 WARN(heap, "(%08x,%08lx,%08lx): asked to free NULL\n",
1012 heap, flags, (DWORD)ptr );
1014 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1016 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1017 SetLastError( ERROR_INVALID_PARAMETER );
1018 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1019 heap, flags, (DWORD)ptr );
1020 return FALSE;
1023 /* Turn the block into a free block */
1025 pInUse = (ARENA_INUSE *)ptr - 1;
1026 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1027 HEAP_MakeInUseBlockFree( subheap, pInUse );
1029 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1030 /* SetLastError( 0 ); */
1032 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1033 heap, flags, (DWORD)ptr );
1034 return TRUE;
1038 /***********************************************************************
1039 * HeapReAlloc (KERNEL32.340)
1040 * RETURNS
1041 * Pointer to reallocated memory block
1042 * NULL: Failure
1044 LPVOID WINAPI HeapReAlloc(
1045 HANDLE heap, /* [in] Handle of heap block */
1046 DWORD flags, /* [in] Heap reallocation flags */
1047 LPVOID ptr, /* [in] Address of memory to reallocate */
1048 DWORD size /* [in] Number of bytes to reallocate */
1050 ARENA_INUSE *pArena;
1051 DWORD oldSize;
1052 HEAP *heapPtr;
1053 SUBHEAP *subheap;
1055 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1056 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1058 /* Validate the parameters */
1060 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1061 HEAP_REALLOC_IN_PLACE_ONLY;
1062 flags |= heapPtr->flags;
1063 size = (size + 3) & ~3;
1064 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1066 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1067 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1069 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1070 SetLastError( ERROR_INVALID_PARAMETER );
1071 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1072 heap, flags, (DWORD)ptr, size );
1073 return NULL;
1076 /* Check if we need to grow the block */
1078 pArena = (ARENA_INUSE *)ptr - 1;
1079 pArena->threadId = GetCurrentTask();
1080 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1081 oldSize = (pArena->size & ARENA_SIZE_MASK);
1082 if (size > oldSize)
1084 char *pNext = (char *)(pArena + 1) + oldSize;
1085 if ((pNext < (char *)subheap + subheap->size) &&
1086 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1087 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1089 /* The next block is free and large enough */
1090 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1091 pFree->next->prev = pFree->prev;
1092 pFree->prev->next = pFree->next;
1093 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1094 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1095 + size + HEAP_MIN_BLOCK_SIZE))
1097 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1098 SetLastError( ERROR_OUTOFMEMORY );
1099 return NULL;
1101 HEAP_ShrinkBlock( subheap, pArena, size );
1103 else /* Do it the hard way */
1105 ARENA_FREE *pNew;
1106 ARENA_INUSE *pInUse;
1107 SUBHEAP *newsubheap;
1109 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1110 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1112 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1113 SetLastError( ERROR_OUTOFMEMORY );
1114 return NULL;
1117 /* Build the in-use arena */
1119 pNew->next->prev = pNew->prev;
1120 pNew->prev->next = pNew->next;
1121 pInUse = (ARENA_INUSE *)pNew;
1122 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1123 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1124 pInUse->threadId = GetCurrentTask();
1125 pInUse->magic = ARENA_INUSE_MAGIC;
1126 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1127 memcpy( pInUse + 1, pArena + 1, oldSize );
1129 /* Free the previous block */
1131 HEAP_MakeInUseBlockFree( subheap, pArena );
1132 subheap = newsubheap;
1133 pArena = pInUse;
1136 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1138 /* Clear the extra bytes if needed */
1140 if (size > oldSize)
1142 if (flags & HEAP_ZERO_MEMORY)
1143 memset( (char *)(pArena + 1) + oldSize, 0,
1144 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1145 else if (TRACE_ON(heap))
1146 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1147 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1150 /* Return the new arena */
1152 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1153 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1155 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1156 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1157 return (LPVOID)(pArena + 1);
1161 /***********************************************************************
1162 * HeapCompact (KERNEL32.335)
1164 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1166 return 0;
1170 /***********************************************************************
1171 * HeapLock (KERNEL32.339)
1172 * Attempts to acquire the critical section object for a specified heap.
1174 * RETURNS
1175 * TRUE: Success
1176 * FALSE: Failure
1178 BOOL WINAPI HeapLock(
1179 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1181 HEAP *heapPtr = HEAP_GetPtr( heap );
1182 if (!heapPtr) return FALSE;
1183 EnterCriticalSection( &heapPtr->critSection );
1184 return TRUE;
1188 /***********************************************************************
1189 * HeapUnlock (KERNEL32.342)
1190 * Releases ownership of the critical section object.
1192 * RETURNS
1193 * TRUE: Success
1194 * FALSE: Failure
1196 BOOL WINAPI HeapUnlock(
1197 HANDLE heap /* [in] Handle to the heap to unlock */
1199 HEAP *heapPtr = HEAP_GetPtr( heap );
1200 if (!heapPtr) return FALSE;
1201 LeaveCriticalSection( &heapPtr->critSection );
1202 return TRUE;
1206 /***********************************************************************
1207 * HeapSize (KERNEL32.341)
1208 * RETURNS
1209 * Size in bytes of allocated memory
1210 * 0xffffffff: Failure
1212 DWORD WINAPI HeapSize(
1213 HANDLE heap, /* [in] Handle of heap */
1214 DWORD flags, /* [in] Heap size control flags */
1215 LPVOID ptr /* [in] Address of memory to return size for */
1217 DWORD ret;
1218 HEAP *heapPtr = HEAP_GetPtr( heap );
1220 if (!heapPtr) return FALSE;
1221 flags &= HEAP_NO_SERIALIZE;
1222 flags |= heapPtr->flags;
1223 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1224 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1226 SetLastError( ERROR_INVALID_PARAMETER );
1227 ret = 0xffffffff;
1229 else
1231 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1232 ret = pArena->size & ARENA_SIZE_MASK;
1234 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1236 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1237 heap, flags, (DWORD)ptr, ret );
1238 return ret;
1242 /***********************************************************************
1243 * HeapValidate (KERNEL32.343)
1244 * Validates a specified heap.
1246 * NOTES
1247 * Flags is ignored.
1249 * RETURNS
1250 * TRUE: Success
1251 * FALSE: Failure
1253 BOOL WINAPI HeapValidate(
1254 HANDLE heap, /* [in] Handle to the heap */
1255 DWORD flags, /* [in] Bit flags that control access during operation */
1256 LPCVOID block /* [in] Optional pointer to memory block to validate */
1258 SUBHEAP *subheap;
1259 HEAP *heapPtr = (HEAP *)(heap);
1261 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1263 ERR(heap, "Invalid heap %08x!\n", heap );
1264 return FALSE;
1267 if (block)
1269 /* Only check this single memory block */
1270 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1271 ((char *)block < (char *)subheap + subheap->headerSize
1272 + sizeof(ARENA_INUSE)))
1274 ERR(heap, "Heap %08lx: block %08lx is not inside heap\n",
1275 (DWORD)heap, (DWORD)block );
1276 return FALSE;
1278 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1281 subheap = &heapPtr->subheap;
1282 while (subheap)
1284 char *ptr = (char *)subheap + subheap->headerSize;
1285 while (ptr < (char *)subheap + subheap->size)
1287 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1289 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1290 return FALSE;
1291 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1293 else
1295 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1296 return FALSE;
1297 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1300 subheap = subheap->next;
1302 return TRUE;
1306 /***********************************************************************
1307 * HeapWalk (KERNEL32.344)
1308 * Enumerates the memory blocks in a specified heap.
1310 * RETURNS
1311 * TRUE: Success
1312 * FALSE: Failure
1314 BOOL WINAPI HeapWalk(
1315 HANDLE heap, /* [in] Handle to heap to enumerate */
1316 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1318 FIXME(heap, "(%08x): stub.\n", heap );
1319 return FALSE;
1323 /***********************************************************************
1324 * HEAP_xalloc
1326 * Same as HeapAlloc(), but die on failure.
1328 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1330 LPVOID p = HeapAlloc( heap, flags, size );
1331 if (!p)
1333 MSG("Virtual memory exhausted.\n" );
1334 exit(1);
1336 return p;
1340 /***********************************************************************
1341 * HEAP_strdupA
1343 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1345 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1346 strcpy( p, str );
1347 return p;
1351 /***********************************************************************
1352 * HEAP_strdupW
1354 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1356 INT len = lstrlenW(str) + 1;
1357 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1358 lstrcpyW( p, str );
1359 return p;
1363 /***********************************************************************
1364 * HEAP_strdupAtoW
1366 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1368 LPWSTR ret;
1370 if (!str) return NULL;
1371 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1372 lstrcpyAtoW( ret, str );
1373 return ret;
1377 /***********************************************************************
1378 * HEAP_strdupWtoA
1380 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1382 LPSTR ret;
1384 if (!str) return NULL;
1385 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1386 lstrcpyWtoA( ret, str );
1387 return ret;
1392 /***********************************************************************
1393 * 32-bit local heap functions (Win95; undocumented)
1396 #define HTABLE_SIZE 0x10000
1397 #define HTABLE_PAGESIZE 0x1000
1398 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1400 #pragma pack(1)
1401 typedef struct _LOCAL32HEADER
1403 WORD freeListFirst[HTABLE_NPAGES];
1404 WORD freeListSize[HTABLE_NPAGES];
1405 WORD freeListLast[HTABLE_NPAGES];
1407 DWORD selectorTableOffset;
1408 WORD selectorTableSize;
1409 WORD selectorDelta;
1411 DWORD segment;
1412 LPBYTE base;
1414 DWORD limit;
1415 DWORD flags;
1417 DWORD magic;
1418 HANDLE heap;
1420 } LOCAL32HEADER;
1421 #pragma pack(4)
1423 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1425 /***********************************************************************
1426 * Local32Init (KERNEL.208)
1428 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1429 DWORD heapSize, DWORD flags )
1431 DWORD totSize, segSize = 0;
1432 LPBYTE base;
1433 LOCAL32HEADER *header;
1434 HEAP *heap;
1435 WORD *selectorTable;
1436 WORD selectorEven, selectorOdd;
1437 int i, nrBlocks;
1439 /* Determine new heap size */
1441 if ( segment )
1443 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1444 return 0;
1445 else
1446 segSize++;
1449 if ( heapSize == -1L )
1450 heapSize = 1024L*1024L; /* FIXME */
1452 heapSize = (heapSize + 0xffff) & 0xffff0000;
1453 segSize = (segSize + 0x0fff) & 0xfffff000;
1454 totSize = segSize + HTABLE_SIZE + heapSize;
1457 /* Allocate memory and initialize heap */
1459 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1460 return 0;
1462 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1463 MEM_COMMIT, PAGE_READWRITE ) )
1465 VirtualFree( base, 0, MEM_RELEASE );
1466 return 0;
1469 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1470 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1472 VirtualFree( base, 0, MEM_RELEASE );
1473 return 0;
1477 /* Set up header and handle table */
1479 header = (LOCAL32HEADER *)(base + segSize);
1480 header->base = base;
1481 header->limit = HTABLE_PAGESIZE-1;
1482 header->flags = 0;
1483 header->magic = LOCAL32_MAGIC;
1484 header->heap = (HANDLE)heap;
1486 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1487 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1488 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1490 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1491 *(DWORD *)((LPBYTE)header + i) = i+4;
1493 header->freeListFirst[1] = 0xffff;
1496 /* Set up selector table */
1498 nrBlocks = (totSize + 0x7fff) >> 15;
1499 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1500 selectorEven = SELECTOR_AllocBlock( base, totSize,
1501 SEGMENT_DATA, FALSE, FALSE );
1502 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1503 SEGMENT_DATA, FALSE, FALSE );
1505 if ( !selectorTable || !selectorEven || !selectorOdd )
1507 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1508 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1509 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1510 HeapDestroy( header->heap );
1511 VirtualFree( base, 0, MEM_RELEASE );
1512 return 0;
1515 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1516 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1517 header->selectorDelta = selectorEven - selectorOdd;
1518 header->segment = segment? segment : selectorEven;
1520 for (i = 0; i < nrBlocks; i++)
1521 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1522 : selectorEven + ((i >> 1) << __AHSHIFT);
1524 /* Move old segment */
1526 if ( segment )
1528 /* FIXME: This is somewhat ugly and relies on implementation
1529 details about 16-bit global memory handles ... */
1531 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1532 memcpy( base, oldBase, segSize );
1533 GLOBAL_MoveBlock( segment, base, totSize );
1534 HeapFree( SystemHeap, 0, oldBase );
1537 return (HANDLE)header;
1540 /***********************************************************************
1541 * Local32_SearchHandle
1543 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1545 LPDWORD handle;
1547 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1548 handle < (LPDWORD)((LPBYTE)header + header->limit);
1549 handle++)
1551 if (*handle == addr)
1552 return handle;
1555 return NULL;
1558 /***********************************************************************
1559 * Local32_ToHandle
1561 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1562 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1564 *handle = NULL;
1565 *ptr = NULL;
1567 switch (type)
1569 case -2: /* 16:16 pointer, no handles */
1570 *ptr = PTR_SEG_TO_LIN( addr );
1571 *handle = (LPDWORD)*ptr;
1572 break;
1574 case -1: /* 32-bit offset, no handles */
1575 *ptr = header->base + addr;
1576 *handle = (LPDWORD)*ptr;
1577 break;
1579 case 0: /* handle */
1580 if ( addr >= sizeof(LOCAL32HEADER)
1581 && addr < header->limit && !(addr & 3)
1582 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1584 *handle = (LPDWORD)((LPBYTE)header + addr);
1585 *ptr = header->base + **handle;
1587 break;
1589 case 1: /* 16:16 pointer */
1590 *ptr = PTR_SEG_TO_LIN( addr );
1591 *handle = Local32_SearchHandle( header, *ptr - header->base );
1592 break;
1594 case 2: /* 32-bit offset */
1595 *ptr = header->base + addr;
1596 *handle = Local32_SearchHandle( header, *ptr - header->base );
1597 break;
1601 /***********************************************************************
1602 * Local32_FromHandle
1604 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1605 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1607 switch (type)
1609 case -2: /* 16:16 pointer */
1610 case 1:
1612 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1613 DWORD offset = (LPBYTE)ptr - header->base;
1614 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1616 break;
1618 case -1: /* 32-bit offset */
1619 case 2:
1620 *addr = ptr - header->base;
1621 break;
1623 case 0: /* handle */
1624 *addr = (LPBYTE)handle - (LPBYTE)header;
1625 break;
1629 /***********************************************************************
1630 * Local32Alloc (KERNEL.209)
1632 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1634 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1635 LPDWORD handle;
1636 LPBYTE ptr;
1637 DWORD addr;
1639 /* Allocate memory */
1640 ptr = HeapAlloc( header->heap,
1641 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1642 if (!ptr) return 0;
1645 /* Allocate handle if requested */
1646 if (type >= 0)
1648 int page, i;
1650 /* Find first page of handle table with free slots */
1651 for (page = 0; page < HTABLE_NPAGES; page++)
1652 if (header->freeListFirst[page] != 0)
1653 break;
1654 if (page == HTABLE_NPAGES)
1656 WARN( heap, "Out of handles!\n" );
1657 HeapFree( header->heap, 0, ptr );
1658 return 0;
1661 /* If virgin page, initialize it */
1662 if (header->freeListFirst[page] == 0xffff)
1664 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1665 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1667 WARN( heap, "Cannot grow handle table!\n" );
1668 HeapFree( header->heap, 0, ptr );
1669 return 0;
1672 header->limit += HTABLE_PAGESIZE;
1674 header->freeListFirst[page] = 0;
1675 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1676 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1678 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1679 *(DWORD *)((LPBYTE)header + i) = i+4;
1681 if (page < HTABLE_NPAGES-1)
1682 header->freeListFirst[page+1] = 0xffff;
1685 /* Allocate handle slot from page */
1686 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1687 if (--header->freeListSize[page] == 0)
1688 header->freeListFirst[page] = header->freeListLast[page] = 0;
1689 else
1690 header->freeListFirst[page] = *handle;
1692 /* Store 32-bit offset in handle slot */
1693 *handle = ptr - header->base;
1695 else
1697 handle = (LPDWORD)ptr;
1698 header->flags |= 1;
1702 /* Convert handle to requested output type */
1703 Local32_FromHandle( header, type, &addr, handle, ptr );
1704 return addr;
1707 /***********************************************************************
1708 * Local32ReAlloc (KERNEL.210)
1710 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1711 DWORD size, DWORD flags )
1713 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1714 LPDWORD handle;
1715 LPBYTE ptr;
1717 if (!addr)
1718 return Local32Alloc16( heap, size, type, flags );
1720 /* Retrieve handle and pointer */
1721 Local32_ToHandle( header, type, addr, &handle, &ptr );
1722 if (!handle) return FALSE;
1724 /* Reallocate memory block */
1725 ptr = HeapReAlloc( header->heap,
1726 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1727 ptr, size );
1728 if (!ptr) return 0;
1730 /* Modify handle */
1731 if (type >= 0)
1732 *handle = ptr - header->base;
1733 else
1734 handle = (LPDWORD)ptr;
1736 /* Convert handle to requested output type */
1737 Local32_FromHandle( header, type, &addr, handle, ptr );
1738 return addr;
1741 /***********************************************************************
1742 * Local32Free (KERNEL.211)
1744 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1746 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1747 LPDWORD handle;
1748 LPBYTE ptr;
1750 /* Retrieve handle and pointer */
1751 Local32_ToHandle( header, type, addr, &handle, &ptr );
1752 if (!handle) return FALSE;
1754 /* Free handle if necessary */
1755 if (type >= 0)
1757 int offset = (LPBYTE)handle - (LPBYTE)header;
1758 int page = offset >> 12;
1760 /* Return handle slot to page free list */
1761 if (header->freeListSize[page]++ == 0)
1762 header->freeListFirst[page] = header->freeListLast[page] = offset;
1763 else
1764 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1765 header->freeListLast[page] = offset;
1767 *handle = 0;
1769 /* Shrink handle table when possible */
1770 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1772 if ( VirtualFree( (LPBYTE)header +
1773 (header->limit & ~(HTABLE_PAGESIZE-1)),
1774 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1775 break;
1777 header->limit -= HTABLE_PAGESIZE;
1778 header->freeListFirst[page] = 0xffff;
1779 page--;
1783 /* Free memory */
1784 return HeapFree( header->heap, 0, ptr );
1787 /***********************************************************************
1788 * Local32Translate (KERNEL.213)
1790 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
1792 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1793 LPDWORD handle;
1794 LPBYTE ptr;
1796 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1797 if (!handle) return 0;
1799 Local32_FromHandle( header, type2, &addr, handle, ptr );
1800 return addr;
1803 /***********************************************************************
1804 * Local32Size (KERNEL.214)
1806 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
1808 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1809 LPDWORD handle;
1810 LPBYTE ptr;
1812 Local32_ToHandle( header, type, addr, &handle, &ptr );
1813 if (!handle) return 0;
1815 return HeapSize( header->heap, 0, ptr );
1818 /***********************************************************************
1819 * Local32ValidHandle (KERNEL.215)
1821 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
1823 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1824 LPDWORD handle;
1825 LPBYTE ptr;
1827 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1828 return handle != NULL;
1831 /***********************************************************************
1832 * Local32GetSegment (KERNEL.229)
1834 WORD WINAPI Local32GetSegment16( HANDLE heap )
1836 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1837 return header->segment;
1840 /***********************************************************************
1841 * Local32_GetHeap
1843 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
1845 WORD selector = GlobalHandleToSel16( handle );
1846 DWORD base = GetSelectorBase( selector );
1847 DWORD limit = GetSelectorLimit16( selector );
1849 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
1850 it this way ... */
1852 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1853 return (LOCAL32HEADER *)base;
1855 base += 0x10000;
1856 limit -= 0x10000;
1858 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1859 return (LOCAL32HEADER *)base;
1861 return NULL;
1864 /***********************************************************************
1865 * Local32Info (KERNEL.444) (TOOLHELP.84)
1867 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
1869 SUBHEAP *heapPtr;
1870 LPBYTE ptr;
1871 int i;
1873 LOCAL32HEADER *header = Local32_GetHeap( handle );
1874 if ( !header ) return FALSE;
1876 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
1877 return FALSE;
1879 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
1880 pLocal32Info->dwMemReserved = heapPtr->size;
1881 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
1882 pLocal32Info->dwTotalFree = 0L;
1883 pLocal32Info->dwLargestFreeBlock = 0L;
1885 /* Note: Local32 heaps always have only one subheap! */
1886 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
1887 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
1889 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1891 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1892 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1893 ptr += sizeof(*pArena) + size;
1895 pLocal32Info->dwTotalFree += size;
1896 if ( size > pLocal32Info->dwLargestFreeBlock )
1897 pLocal32Info->dwLargestFreeBlock = size;
1899 else
1901 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1902 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1903 ptr += sizeof(*pArena) + size;
1907 pLocal32Info->dwcFreeHandles = 0;
1908 for ( i = 0; i < HTABLE_NPAGES; i++ )
1910 if ( header->freeListFirst[i] == 0xffff ) break;
1911 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
1913 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
1915 return TRUE;
1918 /***********************************************************************
1919 * Local32First (KERNEL.445) (TOOLHELP.85)
1921 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
1923 FIXME( heap, "(%p, %04X): stub!\n", pLocal32Entry, handle );
1924 return FALSE;
1927 /***********************************************************************
1928 * Local32Next (KERNEL.446) (TOOLHELP.86)
1930 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
1932 FIXME( heap, "(%p): stub!\n", pLocal32Entry );
1933 return FALSE;