Added new function CDAUDIO_Seek().
[wine/testsucceed.git] / memory / heap.c
blob6b00960c2555a7a7483e435ba503752414cee103
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 /* Note: the heap data structures are based on what Pietrek describes in his
23 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
24 * the same, but could be easily adapted if it turns out some programs
25 * require it.
28 typedef struct tagARENA_INUSE
30 DWORD size; /* Block size; must be the first field */
31 WORD threadId; /* Allocating thread id */
32 WORD magic; /* Magic number */
33 DWORD callerEIP; /* EIP of caller upon allocation */
34 } ARENA_INUSE;
36 typedef struct tagARENA_FREE
38 DWORD size; /* Block size; must be the first field */
39 WORD threadId; /* Freeing thread id */
40 WORD magic; /* Magic number */
41 struct tagARENA_FREE *next; /* Next free arena */
42 struct tagARENA_FREE *prev; /* Prev free arena */
43 } ARENA_FREE;
45 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
46 #define ARENA_FLAG_PREV_FREE 0x00000002
47 #define ARENA_SIZE_MASK 0xfffffffc
48 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
49 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
51 #define ARENA_INUSE_FILLER 0x55
52 #define ARENA_FREE_FILLER 0xaa
54 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
56 /* Max size of the blocks on the free lists */
57 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
59 0x20, 0x80, 0x200, 0xffffffff
62 typedef struct
64 DWORD size;
65 ARENA_FREE arena;
66 } FREE_LIST_ENTRY;
68 struct tagHEAP;
70 typedef struct tagSUBHEAP
72 DWORD size; /* Size of the whole sub-heap */
73 DWORD commitSize; /* Committed size of the sub-heap */
74 DWORD headerSize; /* Size of the heap header */
75 struct tagSUBHEAP *next; /* Next sub-heap */
76 struct tagHEAP *heap; /* Main heap structure */
77 DWORD magic; /* Magic number */
78 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
79 } SUBHEAP;
81 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
83 typedef struct tagHEAP
85 SUBHEAP subheap; /* First sub-heap */
86 struct tagHEAP *next; /* Next heap for this process */
87 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
88 CRITICAL_SECTION critSection; /* Critical section for serialization */
89 DWORD flags; /* Heap flags */
90 DWORD magic; /* Magic number */
91 } HEAP;
93 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
95 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
96 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
98 HANDLE SystemHeap = 0;
99 HANDLE SegptrHeap = 0;
100 CRITICAL_SECTION *HEAP_SystemLock = NULL;
103 /***********************************************************************
104 * HEAP_Dump
106 void HEAP_Dump( HEAP *heap )
108 int i;
109 SUBHEAP *subheap;
110 char *ptr;
112 DUMP( "Heap: %08lx\n", (DWORD)heap );
113 DUMP( "Next: %08lx Sub-heaps: %08lx",
114 (DWORD)heap->next, (DWORD)&heap->subheap );
115 subheap = &heap->subheap;
116 while (subheap->next)
118 DUMP( " -> %08lx", (DWORD)subheap->next );
119 subheap = subheap->next;
122 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
123 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
124 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
125 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
126 heap->freeList[i].arena.threadId,
127 (DWORD)heap->freeList[i].arena.prev,
128 (DWORD)heap->freeList[i].arena.next );
130 subheap = &heap->subheap;
131 while (subheap)
133 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
134 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
135 (DWORD)subheap, subheap->size, subheap->commitSize );
137 DUMP( "\n Block Stat Size Id\n" );
138 ptr = (char*)subheap + subheap->headerSize;
139 while (ptr < (char *)subheap + subheap->size)
141 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
143 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
144 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
145 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
146 pArena->threadId, (DWORD)pArena->prev,
147 (DWORD)pArena->next);
148 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
149 arenaSize += sizeof(ARENA_FREE);
150 freeSize += pArena->size & ARENA_SIZE_MASK;
152 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
154 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
155 DUMP( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
156 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
157 pArena->threadId, *((DWORD *)pArena - 1),
158 pArena->callerEIP );
159 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
160 arenaSize += sizeof(ARENA_INUSE);
161 usedSize += pArena->size & ARENA_SIZE_MASK;
163 else
165 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
166 DUMP( "%08lx used %08lx %04x EIP=%08lx\n",
167 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168 pArena->threadId, pArena->callerEIP );
169 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
170 arenaSize += sizeof(ARENA_INUSE);
171 usedSize += pArena->size & ARENA_SIZE_MASK;
174 DUMP( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
175 subheap->size, subheap->commitSize, freeSize, usedSize,
176 arenaSize, (arenaSize * 100) / subheap->size );
177 subheap = subheap->next;
182 /***********************************************************************
183 * HEAP_GetPtr
184 * RETURNS
185 * Pointer to the heap
186 * NULL: Failure
188 static HEAP *HEAP_GetPtr(
189 HANDLE heap /* [in] Handle to the heap */
191 HEAP *heapPtr = (HEAP *)heap;
192 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
194 ERR(heap, "Invalid heap %08x!\n", heap );
195 SetLastError( ERROR_INVALID_HANDLE );
196 return NULL;
198 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
200 HEAP_Dump( heapPtr );
201 assert( FALSE );
202 SetLastError( ERROR_INVALID_HANDLE );
203 return NULL;
205 return heapPtr;
209 /***********************************************************************
210 * HEAP_InsertFreeBlock
212 * Insert a free block into the free list.
214 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
216 FREE_LIST_ENTRY *pEntry = heap->freeList;
217 while (pEntry->size < pArena->size) pEntry++;
218 pArena->size |= ARENA_FLAG_FREE;
219 pArena->next = pEntry->arena.next;
220 pArena->next->prev = pArena;
221 pArena->prev = &pEntry->arena;
222 pEntry->arena.next = pArena;
226 /***********************************************************************
227 * HEAP_FindSubHeap
228 * Find the sub-heap containing a given address.
230 * RETURNS
231 * Pointer: Success
232 * NULL: Failure
234 static SUBHEAP *HEAP_FindSubHeap(
235 HEAP *heap, /* [in] Heap pointer */
236 LPCVOID ptr /* [in] Address */
238 SUBHEAP *sub = &heap->subheap;
239 while (sub)
241 if (((char *)ptr >= (char *)sub) &&
242 ((char *)ptr < (char *)sub + sub->size)) return sub;
243 sub = sub->next;
245 return NULL;
249 /***********************************************************************
250 * HEAP_Commit
252 * Make sure the heap storage is committed up to (not including) ptr.
254 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
256 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
257 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
258 if (size > subheap->size) size = subheap->size;
259 if (size <= subheap->commitSize) return TRUE;
260 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
261 size - subheap->commitSize, MEM_COMMIT,
262 PAGE_EXECUTE_READWRITE))
264 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
265 size - subheap->commitSize,
266 (DWORD)((char *)subheap + subheap->commitSize),
267 (DWORD)subheap->heap );
268 return FALSE;
270 subheap->commitSize = size;
271 return TRUE;
275 /***********************************************************************
276 * HEAP_Decommit
278 * If possible, decommit the heap storage from (including) 'ptr'.
280 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
282 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
283 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
284 if (size >= subheap->commitSize) return TRUE;
285 if (!VirtualFree( (char *)subheap + size,
286 subheap->commitSize - size, MEM_DECOMMIT ))
288 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
289 subheap->commitSize - size,
290 (DWORD)((char *)subheap + size),
291 (DWORD)subheap->heap );
292 return FALSE;
294 subheap->commitSize = size;
295 return TRUE;
299 /***********************************************************************
300 * HEAP_CreateFreeBlock
302 * Create a free block at a specified address. 'size' is the size of the
303 * whole block, including the new arena.
305 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
307 ARENA_FREE *pFree;
309 /* Create a free arena */
311 pFree = (ARENA_FREE *)ptr;
312 pFree->threadId = GetCurrentTask();
313 pFree->magic = ARENA_FREE_MAGIC;
315 /* If debugging, erase the freed block content */
317 if (TRACE_ON(heap))
319 char *pEnd = (char *)ptr + size;
320 if (pEnd > (char *)subheap + subheap->commitSize)
321 pEnd = (char *)subheap + subheap->commitSize;
322 if (pEnd > (char *)(pFree + 1))
323 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
326 /* Check if next block is free also */
328 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
329 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
331 /* Remove the next arena from the free list */
332 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
333 pNext->next->prev = pNext->prev;
334 pNext->prev->next = pNext->next;
335 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
336 if (TRACE_ON(heap))
337 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
340 /* Set the next block PREV_FREE flag and pointer */
342 if ((char *)ptr + size < (char *)subheap + subheap->size)
344 DWORD *pNext = (DWORD *)((char *)ptr + size);
345 *pNext |= ARENA_FLAG_PREV_FREE;
346 *(ARENA_FREE **)(pNext - 1) = pFree;
349 /* Last, insert the new block into the free list */
351 pFree->size = size - sizeof(*pFree);
352 HEAP_InsertFreeBlock( subheap->heap, pFree );
356 /***********************************************************************
357 * HEAP_MakeInUseBlockFree
359 * Turn an in-use block into a free block. Can also decommit the end of
360 * the heap, and possibly even free the sub-heap altogether.
362 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
364 ARENA_FREE *pFree;
365 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
367 /* Check if we can merge with previous block */
369 if (pArena->size & ARENA_FLAG_PREV_FREE)
371 pFree = *((ARENA_FREE **)pArena - 1);
372 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
373 /* Remove it from the free list */
374 pFree->next->prev = pFree->prev;
375 pFree->prev->next = pFree->next;
377 else pFree = (ARENA_FREE *)pArena;
379 /* Create a free block */
381 HEAP_CreateFreeBlock( subheap, pFree, size );
382 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
383 if ((char *)pFree + size < (char *)subheap + subheap->size)
384 return; /* Not the last block, so nothing more to do */
386 /* Free the whole sub-heap if it's empty and not the original one */
388 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
389 (subheap != &subheap->heap->subheap))
391 SUBHEAP *pPrev = &subheap->heap->subheap;
392 /* Remove the free block from the list */
393 pFree->next->prev = pFree->prev;
394 pFree->prev->next = pFree->next;
395 /* Remove the subheap from the list */
396 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
397 if (pPrev) pPrev->next = subheap->next;
398 /* Free the memory */
399 subheap->magic = 0;
400 if (subheap->selector) FreeSelector16( subheap->selector );
401 VirtualFree( subheap, 0, MEM_RELEASE );
402 return;
405 /* Decommit the end of the heap */
407 HEAP_Decommit( subheap, pFree + 1 );
411 /***********************************************************************
412 * HEAP_ShrinkBlock
414 * Shrink an in-use block.
416 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
418 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
420 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
421 (pArena->size & ARENA_SIZE_MASK) - size );
422 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
424 else
426 /* Turn off PREV_FREE flag in next block */
427 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
428 if (pNext < (char *)subheap + subheap->size)
429 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
433 /***********************************************************************
434 * HEAP_InitSubHeap
436 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
437 DWORD commitSize, DWORD totalSize )
439 SUBHEAP *subheap = (SUBHEAP *)address;
440 WORD selector = 0;
441 FREE_LIST_ENTRY *pEntry;
442 int i;
444 /* Commit memory */
446 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
448 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
449 commitSize, (DWORD)address );
450 return FALSE;
453 /* Allocate a selector if needed */
455 if (flags & HEAP_WINE_SEGPTR)
457 selector = SELECTOR_AllocBlock( address, totalSize,
458 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
459 ? SEGMENT_CODE : SEGMENT_DATA,
460 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
461 if (!selector)
463 ERR(heap, "Could not allocate selector\n" );
464 return FALSE;
468 /* Fill the sub-heap structure */
470 subheap->heap = heap;
471 subheap->selector = selector;
472 subheap->size = totalSize;
473 subheap->commitSize = commitSize;
474 subheap->magic = SUBHEAP_MAGIC;
476 if ( subheap != (SUBHEAP *)heap )
478 /* If this is a secondary subheap, insert it into list */
480 subheap->headerSize = sizeof(SUBHEAP);
481 subheap->next = heap->subheap.next;
482 heap->subheap.next = subheap;
484 else
486 /* If this is a primary subheap, initialize main heap */
488 subheap->headerSize = sizeof(HEAP);
489 subheap->next = NULL;
490 heap->next = NULL;
491 heap->flags = flags;
492 heap->magic = HEAP_MAGIC;
494 /* Build the free lists */
496 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
498 pEntry->size = HEAP_freeListSizes[i];
499 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
500 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
501 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
502 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
503 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
504 pEntry->arena.threadId = 0;
505 pEntry->arena.magic = ARENA_FREE_MAGIC;
508 /* Initialize critical section */
510 InitializeCriticalSection( &heap->critSection );
511 if (!SystemHeap)
513 HEAP_SystemLock = &heap->critSection;
514 /* System heap critical section has to be global */
515 MakeCriticalSectionGlobal( &heap->critSection );
519 /* Create the first free block */
521 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
522 subheap->size - subheap->headerSize );
524 return TRUE;
527 /***********************************************************************
528 * HEAP_CreateSubHeap
530 * Create a sub-heap of the given size.
531 * If heap == NULL, creates a main heap.
533 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
534 DWORD commitSize, DWORD totalSize )
536 LPVOID address;
538 /* Round-up sizes on a 64K boundary */
540 if (flags & HEAP_WINE_SEGPTR)
542 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
544 else
546 totalSize = (totalSize + 0xffff) & 0xffff0000;
547 commitSize = (commitSize + 0xffff) & 0xffff0000;
548 if (!commitSize) commitSize = 0x10000;
549 if (totalSize < commitSize) totalSize = commitSize;
552 /* Allocate the memory block */
554 if (!(address = VirtualAlloc( NULL, totalSize,
555 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
557 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
558 totalSize );
559 return NULL;
562 /* Initialize subheap */
564 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
565 address, flags, commitSize, totalSize ))
567 VirtualFree( address, 0, MEM_RELEASE );
568 return NULL;
571 return (SUBHEAP *)address;
575 /***********************************************************************
576 * HEAP_FindFreeBlock
578 * Find a free block at least as large as the requested size, and make sure
579 * the requested size is committed.
581 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
582 SUBHEAP **ppSubHeap )
584 SUBHEAP *subheap;
585 ARENA_FREE *pArena;
586 FREE_LIST_ENTRY *pEntry = heap->freeList;
588 /* Find a suitable free list, and in it find a block large enough */
590 while (pEntry->size < size) pEntry++;
591 pArena = pEntry->arena.next;
592 while (pArena != &heap->freeList[0].arena)
594 if (pArena->size > size)
596 subheap = HEAP_FindSubHeap( heap, pArena );
597 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
598 + size + HEAP_MIN_BLOCK_SIZE))
599 return NULL;
600 *ppSubHeap = subheap;
601 return pArena;
604 pArena = pArena->next;
607 /* If no block was found, attempt to grow the heap */
609 if (!(heap->flags & HEAP_GROWABLE))
611 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
612 (DWORD)heap, size );
613 return NULL;
615 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
616 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
617 MAX( HEAP_DEF_SIZE, size ) )))
618 return NULL;
620 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
621 (DWORD)subheap, size, (DWORD)heap );
623 *ppSubHeap = subheap;
624 return (ARENA_FREE *)(subheap + 1);
628 /***********************************************************************
629 * HEAP_IsValidArenaPtr
631 * Check that the pointer is inside the range possible for arenas.
633 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
635 int i;
636 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
637 if (!subheap) return FALSE;
638 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
639 if (subheap != &heap->subheap) return FALSE;
640 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
641 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
642 return FALSE;
646 /***********************************************************************
647 * HEAP_ValidateFreeArena
649 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
651 char *heapEnd = (char *)subheap + subheap->size;
653 /* Check magic number */
654 if (pArena->magic != ARENA_FREE_MAGIC)
656 ERR(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
657 (DWORD)subheap->heap, (DWORD)pArena );
658 return FALSE;
660 /* Check size flags */
661 if (!(pArena->size & ARENA_FLAG_FREE) ||
662 (pArena->size & ARENA_FLAG_PREV_FREE))
664 ERR(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
665 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
667 /* Check arena size */
668 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
670 ERR(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
671 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
672 return FALSE;
674 /* Check that next pointer is valid */
675 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
677 ERR(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
678 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
679 return FALSE;
681 /* Check that next arena is free */
682 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
683 (pArena->next->magic != ARENA_FREE_MAGIC))
685 ERR(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
686 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
687 return FALSE;
689 /* Check that prev pointer is valid */
690 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
692 ERR(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
693 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
694 return FALSE;
696 /* Check that prev arena is free */
697 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
698 (pArena->prev->magic != ARENA_FREE_MAGIC))
700 ERR(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
701 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
702 return FALSE;
704 /* Check that next block has PREV_FREE flag */
705 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
707 if (!(*(DWORD *)((char *)(pArena + 1) +
708 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
710 ERR(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
711 (DWORD)subheap->heap, (DWORD)pArena );
712 return FALSE;
714 /* Check next block back pointer */
715 if (*((ARENA_FREE **)((char *)(pArena + 1) +
716 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
718 ERR(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
719 (DWORD)subheap->heap, (DWORD)pArena,
720 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
721 return FALSE;
724 return TRUE;
728 /***********************************************************************
729 * HEAP_ValidateInUseArena
731 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
733 char *heapEnd = (char *)subheap + subheap->size;
735 /* Check magic number */
736 if (pArena->magic != ARENA_INUSE_MAGIC)
738 ERR(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
739 (DWORD)subheap->heap, (DWORD)pArena );
740 return FALSE;
742 /* Check size flags */
743 if (pArena->size & ARENA_FLAG_FREE)
745 ERR(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
746 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
748 /* Check arena size */
749 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
751 ERR(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
752 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
753 return FALSE;
755 /* Check next arena PREV_FREE flag */
756 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
757 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
759 ERR(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
760 (DWORD)subheap->heap, (DWORD)pArena );
761 return FALSE;
763 /* Check prev free arena */
764 if (pArena->size & ARENA_FLAG_PREV_FREE)
766 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
767 /* Check prev pointer */
768 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
770 ERR(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
771 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
772 return FALSE;
774 /* Check that prev arena is free */
775 if (!(pPrev->size & ARENA_FLAG_FREE) ||
776 (pPrev->magic != ARENA_FREE_MAGIC))
778 ERR(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
779 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
780 return FALSE;
782 /* Check that prev arena is really the previous block */
783 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
785 ERR(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
786 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
787 return FALSE;
790 return TRUE;
794 /***********************************************************************
795 * HEAP_IsInsideHeap
796 * Checks whether the pointer points to a block inside a given heap.
798 * NOTES
799 * Should this return BOOL32?
801 * RETURNS
802 * !0: Success
803 * 0: Failure
805 int HEAP_IsInsideHeap(
806 HANDLE heap, /* [in] Heap */
807 DWORD flags, /* [in] Flags */
808 LPCVOID ptr /* [in] Pointer */
810 HEAP *heapPtr = HEAP_GetPtr( heap );
811 SUBHEAP *subheap;
812 int ret;
814 /* Validate the parameters */
816 if (!heapPtr) return 0;
817 flags |= heapPtr->flags;
818 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
819 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
820 (((char *)ptr >= (char *)subheap + subheap->headerSize
821 + sizeof(ARENA_INUSE))));
822 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
823 return ret;
827 /***********************************************************************
828 * HEAP_GetSegptr
830 * Transform a linear pointer into a SEGPTR. The pointer must have been
831 * allocated from a HEAP_WINE_SEGPTR heap.
833 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
835 HEAP *heapPtr = HEAP_GetPtr( heap );
836 SUBHEAP *subheap;
837 SEGPTR ret;
839 /* Validate the parameters */
841 if (!heapPtr) return 0;
842 flags |= heapPtr->flags;
843 if (!(flags & HEAP_WINE_SEGPTR))
845 ERR(heap, "Heap %08x is not a SEGPTR heap\n",
846 heap );
847 return 0;
849 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
851 /* Get the subheap */
853 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
855 ERR(heap, "%p is not inside heap %08x\n",
856 ptr, heap );
857 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
858 return 0;
861 /* Build the SEGPTR */
863 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
864 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
865 return ret;
869 /***********************************************************************
870 * HeapCreate (KERNEL32.336)
871 * RETURNS
872 * Handle of heap: Success
873 * NULL: Failure
875 HANDLE WINAPI HeapCreate(
876 DWORD flags, /* [in] Heap allocation flag */
877 DWORD initialSize, /* [in] Initial heap size */
878 DWORD maxSize /* [in] Maximum heap size */
880 SUBHEAP *subheap;
882 /* Allocate the heap block */
884 if (!maxSize)
886 maxSize = HEAP_DEF_SIZE;
887 flags |= HEAP_GROWABLE;
889 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
891 SetLastError( ERROR_OUTOFMEMORY );
892 return 0;
895 return (HANDLE)subheap;
898 /***********************************************************************
899 * HeapDestroy (KERNEL32.337)
900 * RETURNS
901 * TRUE: Success
902 * FALSE: Failure
904 BOOL WINAPI HeapDestroy(
905 HANDLE heap /* [in] Handle of heap */
907 HEAP *heapPtr = HEAP_GetPtr( heap );
908 SUBHEAP *subheap;
910 TRACE(heap, "%08x\n", heap );
911 if (!heapPtr) return FALSE;
913 DeleteCriticalSection( &heapPtr->critSection );
914 subheap = &heapPtr->subheap;
915 while (subheap)
917 SUBHEAP *next = subheap->next;
918 if (subheap->selector) FreeSelector16( subheap->selector );
919 VirtualFree( subheap, 0, MEM_RELEASE );
920 subheap = next;
922 return TRUE;
926 /***********************************************************************
927 * HeapAlloc (KERNEL32.334)
928 * RETURNS
929 * Pointer to allocated memory block
930 * NULL: Failure
932 LPVOID WINAPI HeapAlloc(
933 HANDLE heap, /* [in] Handle of private heap block */
934 DWORD flags, /* [in] Heap allocation control flags */
935 DWORD size /* [in] Number of bytes to allocate */
937 ARENA_FREE *pArena;
938 ARENA_INUSE *pInUse;
939 SUBHEAP *subheap;
940 HEAP *heapPtr = HEAP_GetPtr( heap );
942 /* Validate the parameters */
944 if (!heapPtr) return NULL;
945 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
946 flags |= heapPtr->flags;
947 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
948 size = (size + 3) & ~3;
949 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
951 /* Locate a suitable free block */
953 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
955 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
956 heap, flags, size );
957 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
958 SetLastError( ERROR_COMMITMENT_LIMIT );
959 return NULL;
962 /* Remove the arena from the free list */
964 pArena->next->prev = pArena->prev;
965 pArena->prev->next = pArena->next;
967 /* Build the in-use arena */
969 pInUse = (ARENA_INUSE *)pArena;
970 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
971 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
972 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
973 pInUse->threadId = GetCurrentTask();
974 pInUse->magic = ARENA_INUSE_MAGIC;
976 /* Shrink the block */
978 HEAP_ShrinkBlock( subheap, pInUse, size );
980 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
981 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
983 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
985 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
986 heap, flags, size, (DWORD)(pInUse + 1) );
987 return (LPVOID)(pInUse + 1);
991 /***********************************************************************
992 * HeapFree (KERNEL32.338)
993 * RETURNS
994 * TRUE: Success
995 * FALSE: Failure
997 BOOL WINAPI HeapFree(
998 HANDLE heap, /* [in] Handle of heap */
999 DWORD flags, /* [in] Heap freeing flags */
1000 LPVOID ptr /* [in] Address of memory to free */
1002 ARENA_INUSE *pInUse;
1003 SUBHEAP *subheap;
1004 HEAP *heapPtr = HEAP_GetPtr( heap );
1006 /* Validate the parameters */
1008 if (!heapPtr) return FALSE;
1009 flags &= HEAP_NO_SERIALIZE;
1010 flags |= heapPtr->flags;
1011 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1012 if (!ptr)
1014 WARN(heap, "(%08x,%08lx,%08lx): asked to free NULL\n",
1015 heap, flags, (DWORD)ptr );
1017 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1019 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1020 SetLastError( ERROR_INVALID_PARAMETER );
1021 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1022 heap, flags, (DWORD)ptr );
1023 return FALSE;
1026 /* Turn the block into a free block */
1028 pInUse = (ARENA_INUSE *)ptr - 1;
1029 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1030 HEAP_MakeInUseBlockFree( subheap, pInUse );
1032 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1033 /* SetLastError( 0 ); */
1035 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1036 heap, flags, (DWORD)ptr );
1037 return TRUE;
1041 /***********************************************************************
1042 * HeapReAlloc (KERNEL32.340)
1043 * RETURNS
1044 * Pointer to reallocated memory block
1045 * NULL: Failure
1047 LPVOID WINAPI HeapReAlloc(
1048 HANDLE heap, /* [in] Handle of heap block */
1049 DWORD flags, /* [in] Heap reallocation flags */
1050 LPVOID ptr, /* [in] Address of memory to reallocate */
1051 DWORD size /* [in] Number of bytes to reallocate */
1053 ARENA_INUSE *pArena;
1054 DWORD oldSize;
1055 HEAP *heapPtr;
1056 SUBHEAP *subheap;
1058 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1059 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1061 /* Validate the parameters */
1063 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1064 HEAP_REALLOC_IN_PLACE_ONLY;
1065 flags |= heapPtr->flags;
1066 size = (size + 3) & ~3;
1067 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1069 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1070 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1072 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1073 SetLastError( ERROR_INVALID_PARAMETER );
1074 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1075 heap, flags, (DWORD)ptr, size );
1076 return NULL;
1079 /* Check if we need to grow the block */
1081 pArena = (ARENA_INUSE *)ptr - 1;
1082 pArena->threadId = GetCurrentTask();
1083 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1084 oldSize = (pArena->size & ARENA_SIZE_MASK);
1085 if (size > oldSize)
1087 char *pNext = (char *)(pArena + 1) + oldSize;
1088 if ((pNext < (char *)subheap + subheap->size) &&
1089 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1090 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1092 /* The next block is free and large enough */
1093 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1094 pFree->next->prev = pFree->prev;
1095 pFree->prev->next = pFree->next;
1096 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1097 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1098 + size + HEAP_MIN_BLOCK_SIZE))
1100 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1101 SetLastError( ERROR_OUTOFMEMORY );
1102 return NULL;
1104 HEAP_ShrinkBlock( subheap, pArena, size );
1106 else /* Do it the hard way */
1108 ARENA_FREE *pNew;
1109 ARENA_INUSE *pInUse;
1110 SUBHEAP *newsubheap;
1112 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1113 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1115 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1116 SetLastError( ERROR_OUTOFMEMORY );
1117 return NULL;
1120 /* Build the in-use arena */
1122 pNew->next->prev = pNew->prev;
1123 pNew->prev->next = pNew->next;
1124 pInUse = (ARENA_INUSE *)pNew;
1125 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1126 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1127 pInUse->threadId = GetCurrentTask();
1128 pInUse->magic = ARENA_INUSE_MAGIC;
1129 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1130 memcpy( pInUse + 1, pArena + 1, oldSize );
1132 /* Free the previous block */
1134 HEAP_MakeInUseBlockFree( subheap, pArena );
1135 subheap = newsubheap;
1136 pArena = pInUse;
1139 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1141 /* Clear the extra bytes if needed */
1143 if (size > oldSize)
1145 if (flags & HEAP_ZERO_MEMORY)
1146 memset( (char *)(pArena + 1) + oldSize, 0,
1147 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1148 else if (TRACE_ON(heap))
1149 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1150 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1153 /* Return the new arena */
1155 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1156 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1158 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1159 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1160 return (LPVOID)(pArena + 1);
1164 /***********************************************************************
1165 * HeapCompact (KERNEL32.335)
1167 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1169 return 0;
1173 /***********************************************************************
1174 * HeapLock (KERNEL32.339)
1175 * Attempts to acquire the critical section object for a specified heap.
1177 * RETURNS
1178 * TRUE: Success
1179 * FALSE: Failure
1181 BOOL WINAPI HeapLock(
1182 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1184 HEAP *heapPtr = HEAP_GetPtr( heap );
1185 if (!heapPtr) return FALSE;
1186 EnterCriticalSection( &heapPtr->critSection );
1187 return TRUE;
1191 /***********************************************************************
1192 * HeapUnlock (KERNEL32.342)
1193 * Releases ownership of the critical section object.
1195 * RETURNS
1196 * TRUE: Success
1197 * FALSE: Failure
1199 BOOL WINAPI HeapUnlock(
1200 HANDLE heap /* [in] Handle to the heap to unlock */
1202 HEAP *heapPtr = HEAP_GetPtr( heap );
1203 if (!heapPtr) return FALSE;
1204 LeaveCriticalSection( &heapPtr->critSection );
1205 return TRUE;
1209 /***********************************************************************
1210 * HeapSize (KERNEL32.341)
1211 * RETURNS
1212 * Size in bytes of allocated memory
1213 * 0xffffffff: Failure
1215 DWORD WINAPI HeapSize(
1216 HANDLE heap, /* [in] Handle of heap */
1217 DWORD flags, /* [in] Heap size control flags */
1218 LPVOID ptr /* [in] Address of memory to return size for */
1220 DWORD ret;
1221 HEAP *heapPtr = HEAP_GetPtr( heap );
1223 if (!heapPtr) return FALSE;
1224 flags &= HEAP_NO_SERIALIZE;
1225 flags |= heapPtr->flags;
1226 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1227 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1229 SetLastError( ERROR_INVALID_PARAMETER );
1230 ret = 0xffffffff;
1232 else
1234 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1235 ret = pArena->size & ARENA_SIZE_MASK;
1237 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1239 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1240 heap, flags, (DWORD)ptr, ret );
1241 return ret;
1245 /***********************************************************************
1246 * HeapValidate (KERNEL32.343)
1247 * Validates a specified heap.
1249 * NOTES
1250 * Flags is ignored.
1252 * RETURNS
1253 * TRUE: Success
1254 * FALSE: Failure
1256 BOOL WINAPI HeapValidate(
1257 HANDLE heap, /* [in] Handle to the heap */
1258 DWORD flags, /* [in] Bit flags that control access during operation */
1259 LPCVOID block /* [in] Optional pointer to memory block to validate */
1261 SUBHEAP *subheap;
1262 HEAP *heapPtr = (HEAP *)(heap);
1264 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1266 ERR(heap, "Invalid heap %08x!\n", heap );
1267 return FALSE;
1270 if (block)
1272 /* Only check this single memory block */
1273 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1274 ((char *)block < (char *)subheap + subheap->headerSize
1275 + sizeof(ARENA_INUSE)))
1277 ERR(heap, "Heap %08lx: block %08lx is not inside heap\n",
1278 (DWORD)heap, (DWORD)block );
1279 return FALSE;
1281 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1284 subheap = &heapPtr->subheap;
1285 while (subheap)
1287 char *ptr = (char *)subheap + subheap->headerSize;
1288 while (ptr < (char *)subheap + subheap->size)
1290 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1292 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1293 return FALSE;
1294 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1296 else
1298 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1299 return FALSE;
1300 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1303 subheap = subheap->next;
1305 return TRUE;
1309 /***********************************************************************
1310 * HeapWalk (KERNEL32.344)
1311 * Enumerates the memory blocks in a specified heap.
1313 * RETURNS
1314 * TRUE: Success
1315 * FALSE: Failure
1317 BOOL WINAPI HeapWalk(
1318 HANDLE heap, /* [in] Handle to heap to enumerate */
1319 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1321 FIXME(heap, "(%08x): stub.\n", heap );
1322 return FALSE;
1326 /***********************************************************************
1327 * HEAP_xalloc
1329 * Same as HeapAlloc(), but die on failure.
1331 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1333 LPVOID p = HeapAlloc( heap, flags, size );
1334 if (!p)
1336 MSG("Virtual memory exhausted.\n" );
1337 exit(1);
1339 return p;
1343 /***********************************************************************
1344 * HEAP_strdupA
1346 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1348 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1349 strcpy( p, str );
1350 return p;
1354 /***********************************************************************
1355 * HEAP_strdupW
1357 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1359 INT len = lstrlenW(str) + 1;
1360 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1361 lstrcpyW( p, str );
1362 return p;
1366 /***********************************************************************
1367 * HEAP_strdupAtoW
1369 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1371 LPWSTR ret;
1373 if (!str) return NULL;
1374 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1375 lstrcpyAtoW( ret, str );
1376 return ret;
1380 /***********************************************************************
1381 * HEAP_strdupWtoA
1383 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1385 LPSTR ret;
1387 if (!str) return NULL;
1388 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1389 lstrcpyWtoA( ret, str );
1390 return ret;
1395 /***********************************************************************
1396 * 32-bit local heap functions (Win95; undocumented)
1399 #define HTABLE_SIZE 0x10000
1400 #define HTABLE_PAGESIZE 0x1000
1401 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1403 #pragma pack(1)
1404 typedef struct _LOCAL32HEADER
1406 WORD freeListFirst[HTABLE_NPAGES];
1407 WORD freeListSize[HTABLE_NPAGES];
1408 WORD freeListLast[HTABLE_NPAGES];
1410 DWORD selectorTableOffset;
1411 WORD selectorTableSize;
1412 WORD selectorDelta;
1414 DWORD segment;
1415 LPBYTE base;
1417 DWORD limit;
1418 DWORD flags;
1420 DWORD magic;
1421 HANDLE heap;
1423 } LOCAL32HEADER;
1424 #pragma pack(4)
1426 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1428 /***********************************************************************
1429 * Local32Init (KERNEL.208)
1431 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1432 DWORD heapSize, DWORD flags )
1434 DWORD totSize, segSize = 0;
1435 LPBYTE base;
1436 LOCAL32HEADER *header;
1437 HEAP *heap;
1438 WORD *selectorTable;
1439 WORD selectorEven, selectorOdd;
1440 int i, nrBlocks;
1442 /* Determine new heap size */
1444 if ( segment )
1446 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1447 return 0;
1448 else
1449 segSize++;
1452 if ( heapSize == -1L )
1453 heapSize = 1024L*1024L; /* FIXME */
1455 heapSize = (heapSize + 0xffff) & 0xffff0000;
1456 segSize = (segSize + 0x0fff) & 0xfffff000;
1457 totSize = segSize + HTABLE_SIZE + heapSize;
1460 /* Allocate memory and initialize heap */
1462 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1463 return 0;
1465 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1466 MEM_COMMIT, PAGE_READWRITE ) )
1468 VirtualFree( base, 0, MEM_RELEASE );
1469 return 0;
1472 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1473 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1475 VirtualFree( base, 0, MEM_RELEASE );
1476 return 0;
1480 /* Set up header and handle table */
1482 header = (LOCAL32HEADER *)(base + segSize);
1483 header->base = base;
1484 header->limit = HTABLE_PAGESIZE-1;
1485 header->flags = 0;
1486 header->magic = LOCAL32_MAGIC;
1487 header->heap = (HANDLE)heap;
1489 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1490 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1491 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1493 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1494 *(DWORD *)((LPBYTE)header + i) = i+4;
1496 header->freeListFirst[1] = 0xffff;
1499 /* Set up selector table */
1501 nrBlocks = (totSize + 0x7fff) >> 15;
1502 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1503 selectorEven = SELECTOR_AllocBlock( base, totSize,
1504 SEGMENT_DATA, FALSE, FALSE );
1505 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1506 SEGMENT_DATA, FALSE, FALSE );
1508 if ( !selectorTable || !selectorEven || !selectorOdd )
1510 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1511 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1512 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1513 HeapDestroy( header->heap );
1514 VirtualFree( base, 0, MEM_RELEASE );
1515 return 0;
1518 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1519 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1520 header->selectorDelta = selectorEven - selectorOdd;
1521 header->segment = segment? segment : selectorEven;
1523 for (i = 0; i < nrBlocks; i++)
1524 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1525 : selectorEven + ((i >> 1) << __AHSHIFT);
1527 /* Move old segment */
1529 if ( segment )
1531 /* FIXME: This is somewhat ugly and relies on implementation
1532 details about 16-bit global memory handles ... */
1534 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1535 memcpy( base, oldBase, segSize );
1536 GLOBAL_MoveBlock( segment, base, totSize );
1537 HeapFree( SystemHeap, 0, oldBase );
1540 return (HANDLE)header;
1543 /***********************************************************************
1544 * Local32_SearchHandle
1546 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1548 LPDWORD handle;
1550 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1551 handle < (LPDWORD)((LPBYTE)header + header->limit);
1552 handle++)
1554 if (*handle == addr)
1555 return handle;
1558 return NULL;
1561 /***********************************************************************
1562 * Local32_ToHandle
1564 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1565 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1567 *handle = NULL;
1568 *ptr = NULL;
1570 switch (type)
1572 case -2: /* 16:16 pointer, no handles */
1573 *ptr = PTR_SEG_TO_LIN( addr );
1574 *handle = (LPDWORD)*ptr;
1575 break;
1577 case -1: /* 32-bit offset, no handles */
1578 *ptr = header->base + addr;
1579 *handle = (LPDWORD)*ptr;
1580 break;
1582 case 0: /* handle */
1583 if ( addr >= sizeof(LOCAL32HEADER)
1584 && addr < header->limit && !(addr & 3)
1585 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1587 *handle = (LPDWORD)((LPBYTE)header + addr);
1588 *ptr = header->base + **handle;
1590 break;
1592 case 1: /* 16:16 pointer */
1593 *ptr = PTR_SEG_TO_LIN( addr );
1594 *handle = Local32_SearchHandle( header, *ptr - header->base );
1595 break;
1597 case 2: /* 32-bit offset */
1598 *ptr = header->base + addr;
1599 *handle = Local32_SearchHandle( header, *ptr - header->base );
1600 break;
1604 /***********************************************************************
1605 * Local32_FromHandle
1607 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1608 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1610 switch (type)
1612 case -2: /* 16:16 pointer */
1613 case 1:
1615 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1616 DWORD offset = (LPBYTE)ptr - header->base;
1617 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1619 break;
1621 case -1: /* 32-bit offset */
1622 case 2:
1623 *addr = ptr - header->base;
1624 break;
1626 case 0: /* handle */
1627 *addr = (LPBYTE)handle - (LPBYTE)header;
1628 break;
1632 /***********************************************************************
1633 * Local32Alloc (KERNEL.209)
1635 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1637 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1638 LPDWORD handle;
1639 LPBYTE ptr;
1640 DWORD addr;
1642 /* Allocate memory */
1643 ptr = HeapAlloc( header->heap,
1644 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1645 if (!ptr) return 0;
1648 /* Allocate handle if requested */
1649 if (type >= 0)
1651 int page, i;
1653 /* Find first page of handle table with free slots */
1654 for (page = 0; page < HTABLE_NPAGES; page++)
1655 if (header->freeListFirst[page] != 0)
1656 break;
1657 if (page == HTABLE_NPAGES)
1659 WARN( heap, "Out of handles!\n" );
1660 HeapFree( header->heap, 0, ptr );
1661 return 0;
1664 /* If virgin page, initialize it */
1665 if (header->freeListFirst[page] == 0xffff)
1667 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1668 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1670 WARN( heap, "Cannot grow handle table!\n" );
1671 HeapFree( header->heap, 0, ptr );
1672 return 0;
1675 header->limit += HTABLE_PAGESIZE;
1677 header->freeListFirst[page] = 0;
1678 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1679 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1681 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1682 *(DWORD *)((LPBYTE)header + i) = i+4;
1684 if (page < HTABLE_NPAGES-1)
1685 header->freeListFirst[page+1] = 0xffff;
1688 /* Allocate handle slot from page */
1689 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1690 if (--header->freeListSize[page] == 0)
1691 header->freeListFirst[page] = header->freeListLast[page] = 0;
1692 else
1693 header->freeListFirst[page] = *handle;
1695 /* Store 32-bit offset in handle slot */
1696 *handle = ptr - header->base;
1698 else
1700 handle = (LPDWORD)ptr;
1701 header->flags |= 1;
1705 /* Convert handle to requested output type */
1706 Local32_FromHandle( header, type, &addr, handle, ptr );
1707 return addr;
1710 /***********************************************************************
1711 * Local32ReAlloc (KERNEL.210)
1713 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1714 DWORD size, DWORD flags )
1716 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1717 LPDWORD handle;
1718 LPBYTE ptr;
1720 if (!addr)
1721 return Local32Alloc16( heap, size, type, flags );
1723 /* Retrieve handle and pointer */
1724 Local32_ToHandle( header, type, addr, &handle, &ptr );
1725 if (!handle) return FALSE;
1727 /* Reallocate memory block */
1728 ptr = HeapReAlloc( header->heap,
1729 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1730 ptr, size );
1731 if (!ptr) return 0;
1733 /* Modify handle */
1734 if (type >= 0)
1735 *handle = ptr - header->base;
1736 else
1737 handle = (LPDWORD)ptr;
1739 /* Convert handle to requested output type */
1740 Local32_FromHandle( header, type, &addr, handle, ptr );
1741 return addr;
1744 /***********************************************************************
1745 * Local32Free (KERNEL.211)
1747 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1749 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1750 LPDWORD handle;
1751 LPBYTE ptr;
1753 /* Retrieve handle and pointer */
1754 Local32_ToHandle( header, type, addr, &handle, &ptr );
1755 if (!handle) return FALSE;
1757 /* Free handle if necessary */
1758 if (type >= 0)
1760 int offset = (LPBYTE)handle - (LPBYTE)header;
1761 int page = offset >> 12;
1763 /* Return handle slot to page free list */
1764 if (header->freeListSize[page]++ == 0)
1765 header->freeListFirst[page] = header->freeListLast[page] = offset;
1766 else
1767 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1768 header->freeListLast[page] = offset;
1770 *handle = 0;
1772 /* Shrink handle table when possible */
1773 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1775 if ( VirtualFree( (LPBYTE)header +
1776 (header->limit & ~(HTABLE_PAGESIZE-1)),
1777 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1778 break;
1780 header->limit -= HTABLE_PAGESIZE;
1781 header->freeListFirst[page] = 0xffff;
1782 page--;
1786 /* Free memory */
1787 return HeapFree( header->heap, 0, ptr );
1790 /***********************************************************************
1791 * Local32Translate (KERNEL.213)
1793 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
1795 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1796 LPDWORD handle;
1797 LPBYTE ptr;
1799 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1800 if (!handle) return 0;
1802 Local32_FromHandle( header, type2, &addr, handle, ptr );
1803 return addr;
1806 /***********************************************************************
1807 * Local32Size (KERNEL.214)
1809 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
1811 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1812 LPDWORD handle;
1813 LPBYTE ptr;
1815 Local32_ToHandle( header, type, addr, &handle, &ptr );
1816 if (!handle) return 0;
1818 return HeapSize( header->heap, 0, ptr );
1821 /***********************************************************************
1822 * Local32ValidHandle (KERNEL.215)
1824 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
1826 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1827 LPDWORD handle;
1828 LPBYTE ptr;
1830 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1831 return handle != NULL;
1834 /***********************************************************************
1835 * Local32GetSegment (KERNEL.229)
1837 WORD WINAPI Local32GetSegment16( HANDLE heap )
1839 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1840 return header->segment;
1843 /***********************************************************************
1844 * Local32_GetHeap
1846 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
1848 WORD selector = GlobalHandleToSel16( handle );
1849 DWORD base = GetSelectorBase( selector );
1850 DWORD limit = GetSelectorLimit16( selector );
1852 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
1853 it this way ... */
1855 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1856 return (LOCAL32HEADER *)base;
1858 base += 0x10000;
1859 limit -= 0x10000;
1861 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1862 return (LOCAL32HEADER *)base;
1864 return NULL;
1867 /***********************************************************************
1868 * Local32Info (KERNEL.444) (TOOLHELP.84)
1870 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
1872 SUBHEAP *heapPtr;
1873 LPBYTE ptr;
1874 int i;
1876 LOCAL32HEADER *header = Local32_GetHeap( handle );
1877 if ( !header ) return FALSE;
1879 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
1880 return FALSE;
1882 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
1883 pLocal32Info->dwMemReserved = heapPtr->size;
1884 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
1885 pLocal32Info->dwTotalFree = 0L;
1886 pLocal32Info->dwLargestFreeBlock = 0L;
1888 /* Note: Local32 heaps always have only one subheap! */
1889 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
1890 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
1892 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1894 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1895 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1896 ptr += sizeof(*pArena) + size;
1898 pLocal32Info->dwTotalFree += size;
1899 if ( size > pLocal32Info->dwLargestFreeBlock )
1900 pLocal32Info->dwLargestFreeBlock = size;
1902 else
1904 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1905 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1906 ptr += sizeof(*pArena) + size;
1910 pLocal32Info->dwcFreeHandles = 0;
1911 for ( i = 0; i < HTABLE_NPAGES; i++ )
1913 if ( header->freeListFirst[i] == 0xffff ) break;
1914 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
1916 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
1918 return TRUE;
1921 /***********************************************************************
1922 * Local32First (KERNEL.445) (TOOLHELP.85)
1924 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
1926 FIXME( heap, "(%p, %04X): stub!\n", pLocal32Entry, handle );
1927 return FALSE;
1930 /***********************************************************************
1931 * Local32Next (KERNEL.446) (TOOLHELP.86)
1933 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
1935 FIXME( heap, "(%p): stub!\n", pLocal32Entry );
1936 return FALSE;