Use a linked list instead of a DPA for the hook list.
[wine/gsoc_dplay.git] / memory / heap.c
blob161cccbdf10671ac0feec24db0f6e76357532a77
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 "debugtools.h"
22 DEFAULT_DEBUG_CHANNEL(heap)
24 /* Note: the heap data structures are based on what Pietrek describes in his
25 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
26 * the same, but could be easily adapted if it turns out some programs
27 * require it.
30 typedef struct tagARENA_INUSE
32 DWORD size; /* Block size; must be the first field */
33 WORD threadId; /* Allocating thread id */
34 WORD magic; /* Magic number */
35 void *callerEIP; /* EIP of caller upon allocation */
36 } ARENA_INUSE;
38 typedef struct tagARENA_FREE
40 DWORD size; /* Block size; must be the first field */
41 WORD threadId; /* Freeing thread id */
42 WORD magic; /* Magic number */
43 struct tagARENA_FREE *next; /* Next free arena */
44 struct tagARENA_FREE *prev; /* Prev free arena */
45 } ARENA_FREE;
47 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
48 #define ARENA_FLAG_PREV_FREE 0x00000002
49 #define ARENA_SIZE_MASK 0xfffffffc
50 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
51 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
53 #define ARENA_INUSE_FILLER 0x55
54 #define ARENA_FREE_FILLER 0xaa
56 #define QUIET 1 /* Suppress messages */
57 #define NOISY 0 /* Report all errors */
59 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
61 /* Max size of the blocks on the free lists */
62 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
64 0x20, 0x80, 0x200, 0xffffffff
67 typedef struct
69 DWORD size;
70 ARENA_FREE arena;
71 } FREE_LIST_ENTRY;
73 struct tagHEAP;
75 typedef struct tagSUBHEAP
77 DWORD size; /* Size of the whole sub-heap */
78 DWORD commitSize; /* Committed size of the sub-heap */
79 DWORD headerSize; /* Size of the heap header */
80 struct tagSUBHEAP *next; /* Next sub-heap */
81 struct tagHEAP *heap; /* Main heap structure */
82 DWORD magic; /* Magic number */
83 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
84 } SUBHEAP;
86 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
88 typedef struct tagHEAP
90 SUBHEAP subheap; /* First sub-heap */
91 struct tagHEAP *next; /* Next heap for this process */
92 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
93 CRITICAL_SECTION critSection; /* Critical section for serialization */
94 DWORD flags; /* Heap flags */
95 DWORD magic; /* Magic number */
96 void *private; /* Private pointer for the user of the heap */
97 } HEAP;
99 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
101 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
102 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
104 HANDLE SystemHeap = 0;
105 HANDLE SegptrHeap = 0;
107 SYSTEM_HEAP_DESCR *SystemHeapDescr = 0;
109 static HEAP *processHeap; /* main process heap */
110 static HEAP *firstHeap; /* head of secondary heaps list */
112 /* address where we try to map the system heap */
113 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
115 static BOOL HEAP_IsRealArena( HANDLE heap, DWORD flags, LPCVOID block, BOOL quiet );
117 #ifdef __GNUC__
118 #define GET_EIP() (__builtin_return_address(0))
119 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
120 #else
121 #define GET_EIP() 0
122 #define SET_EIP(ptr) /* nothing */
123 #endif /* __GNUC__ */
125 /***********************************************************************
126 * HEAP_Dump
128 void HEAP_Dump( HEAP *heap )
130 int i;
131 SUBHEAP *subheap;
132 char *ptr;
134 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
135 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
136 (DWORD)heap->next, (DWORD)&heap->subheap );
137 subheap = &heap->subheap;
138 while (subheap->next)
140 DPRINTF( " -> %08lx", (DWORD)subheap->next );
141 subheap = subheap->next;
144 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
145 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
146 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
147 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
148 heap->freeList[i].arena.threadId,
149 (DWORD)heap->freeList[i].arena.prev,
150 (DWORD)heap->freeList[i].arena.next );
152 subheap = &heap->subheap;
153 while (subheap)
155 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
156 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
157 (DWORD)subheap, subheap->size, subheap->commitSize );
159 DPRINTF( "\n Block Stat Size Id\n" );
160 ptr = (char*)subheap + subheap->headerSize;
161 while (ptr < (char *)subheap + subheap->size)
163 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
165 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
166 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
167 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168 pArena->threadId, (DWORD)pArena->prev,
169 (DWORD)pArena->next);
170 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171 arenaSize += sizeof(ARENA_FREE);
172 freeSize += pArena->size & ARENA_SIZE_MASK;
174 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
176 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
177 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
178 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
179 pArena->threadId, *((DWORD *)pArena - 1),
180 pArena->callerEIP );
181 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
182 arenaSize += sizeof(ARENA_INUSE);
183 usedSize += pArena->size & ARENA_SIZE_MASK;
185 else
187 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
188 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
189 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
190 pArena->threadId, pArena->callerEIP );
191 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
192 arenaSize += sizeof(ARENA_INUSE);
193 usedSize += pArena->size & ARENA_SIZE_MASK;
196 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
197 subheap->size, subheap->commitSize, freeSize, usedSize,
198 arenaSize, (arenaSize * 100) / subheap->size );
199 subheap = subheap->next;
204 /***********************************************************************
205 * HEAP_GetPtr
206 * RETURNS
207 * Pointer to the heap
208 * NULL: Failure
210 static HEAP *HEAP_GetPtr(
211 HANDLE heap /* [in] Handle to the heap */
213 HEAP *heapPtr = (HEAP *)heap;
214 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
216 ERR("Invalid heap %08x!\n", heap );
217 SetLastError( ERROR_INVALID_HANDLE );
218 return NULL;
220 if (TRACE_ON(heap) && !HEAP_IsRealArena( heap, 0, NULL, NOISY ))
222 HEAP_Dump( heapPtr );
223 assert( FALSE );
224 SetLastError( ERROR_INVALID_HANDLE );
225 return NULL;
227 return heapPtr;
231 /***********************************************************************
232 * HEAP_InsertFreeBlock
234 * Insert a free block into the free list.
236 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
238 FREE_LIST_ENTRY *pEntry = heap->freeList;
239 while (pEntry->size < pArena->size) pEntry++;
240 pArena->size |= ARENA_FLAG_FREE;
241 pArena->next = pEntry->arena.next;
242 pArena->next->prev = pArena;
243 pArena->prev = &pEntry->arena;
244 pEntry->arena.next = pArena;
248 /***********************************************************************
249 * HEAP_FindSubHeap
250 * Find the sub-heap containing a given address.
252 * RETURNS
253 * Pointer: Success
254 * NULL: Failure
256 static SUBHEAP *HEAP_FindSubHeap(
257 HEAP *heap, /* [in] Heap pointer */
258 LPCVOID ptr /* [in] Address */
260 SUBHEAP *sub = &heap->subheap;
261 while (sub)
263 if (((char *)ptr >= (char *)sub) &&
264 ((char *)ptr < (char *)sub + sub->size)) return sub;
265 sub = sub->next;
267 return NULL;
271 /***********************************************************************
272 * HEAP_Commit
274 * Make sure the heap storage is committed up to (not including) ptr.
276 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
278 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
279 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
280 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
281 if (size > subheap->size) size = subheap->size;
282 if (size <= subheap->commitSize) return TRUE;
283 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
284 size - subheap->commitSize, MEM_COMMIT,
285 PAGE_EXECUTE_READWRITE))
287 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
288 size - subheap->commitSize,
289 (DWORD)((char *)subheap + subheap->commitSize),
290 (DWORD)subheap->heap );
291 return FALSE;
293 subheap->commitSize = size;
294 return TRUE;
298 /***********************************************************************
299 * HEAP_Decommit
301 * If possible, decommit the heap storage from (including) 'ptr'.
303 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
305 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
306 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
307 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
308 if (size >= subheap->commitSize) return TRUE;
309 if (!VirtualFree( (char *)subheap + size,
310 subheap->commitSize - size, MEM_DECOMMIT ))
312 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
313 subheap->commitSize - size,
314 (DWORD)((char *)subheap + size),
315 (DWORD)subheap->heap );
316 return FALSE;
318 subheap->commitSize = size;
319 return TRUE;
323 /***********************************************************************
324 * HEAP_CreateFreeBlock
326 * Create a free block at a specified address. 'size' is the size of the
327 * whole block, including the new arena.
329 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
331 ARENA_FREE *pFree;
333 /* Create a free arena */
335 pFree = (ARENA_FREE *)ptr;
336 pFree->threadId = GetCurrentTask();
337 pFree->magic = ARENA_FREE_MAGIC;
339 /* If debugging, erase the freed block content */
341 if (TRACE_ON(heap))
343 char *pEnd = (char *)ptr + size;
344 if (pEnd > (char *)subheap + subheap->commitSize)
345 pEnd = (char *)subheap + subheap->commitSize;
346 if (pEnd > (char *)(pFree + 1))
347 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
350 /* Check if next block is free also */
352 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
353 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
355 /* Remove the next arena from the free list */
356 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
357 pNext->next->prev = pNext->prev;
358 pNext->prev->next = pNext->next;
359 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
360 if (TRACE_ON(heap))
361 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
364 /* Set the next block PREV_FREE flag and pointer */
366 if ((char *)ptr + size < (char *)subheap + subheap->size)
368 DWORD *pNext = (DWORD *)((char *)ptr + size);
369 *pNext |= ARENA_FLAG_PREV_FREE;
370 *(ARENA_FREE **)(pNext - 1) = pFree;
373 /* Last, insert the new block into the free list */
375 pFree->size = size - sizeof(*pFree);
376 HEAP_InsertFreeBlock( subheap->heap, pFree );
380 /***********************************************************************
381 * HEAP_MakeInUseBlockFree
383 * Turn an in-use block into a free block. Can also decommit the end of
384 * the heap, and possibly even free the sub-heap altogether.
386 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
388 ARENA_FREE *pFree;
389 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
391 /* Check if we can merge with previous block */
393 if (pArena->size & ARENA_FLAG_PREV_FREE)
395 pFree = *((ARENA_FREE **)pArena - 1);
396 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
397 /* Remove it from the free list */
398 pFree->next->prev = pFree->prev;
399 pFree->prev->next = pFree->next;
401 else pFree = (ARENA_FREE *)pArena;
403 /* Create a free block */
405 HEAP_CreateFreeBlock( subheap, pFree, size );
406 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
407 if ((char *)pFree + size < (char *)subheap + subheap->size)
408 return; /* Not the last block, so nothing more to do */
410 /* Free the whole sub-heap if it's empty and not the original one */
412 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
413 (subheap != &subheap->heap->subheap))
415 SUBHEAP *pPrev = &subheap->heap->subheap;
416 /* Remove the free block from the list */
417 pFree->next->prev = pFree->prev;
418 pFree->prev->next = pFree->next;
419 /* Remove the subheap from the list */
420 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
421 if (pPrev) pPrev->next = subheap->next;
422 /* Free the memory */
423 subheap->magic = 0;
424 if (subheap->selector) FreeSelector16( subheap->selector );
425 VirtualFree( subheap, 0, MEM_RELEASE );
426 return;
429 /* Decommit the end of the heap */
431 if (!(subheap->heap->flags & HEAP_WINE_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
435 /***********************************************************************
436 * HEAP_ShrinkBlock
438 * Shrink an in-use block.
440 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
442 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
444 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
445 (pArena->size & ARENA_SIZE_MASK) - size );
446 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
448 else
450 /* Turn off PREV_FREE flag in next block */
451 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
452 if (pNext < (char *)subheap + subheap->size)
453 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
457 /***********************************************************************
458 * HEAP_InitSubHeap
460 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
461 DWORD commitSize, DWORD totalSize )
463 SUBHEAP *subheap = (SUBHEAP *)address;
464 WORD selector = 0;
465 FREE_LIST_ENTRY *pEntry;
466 int i;
468 /* Commit memory */
470 if (flags & HEAP_WINE_SHARED)
471 commitSize = totalSize; /* always commit everything in a shared heap */
472 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
474 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
475 commitSize, (DWORD)address );
476 return FALSE;
479 /* Allocate a selector if needed */
481 if (flags & HEAP_WINE_SEGPTR)
483 selector = SELECTOR_AllocBlock( address, totalSize,
484 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
485 ? SEGMENT_CODE : SEGMENT_DATA,
486 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
487 if (!selector)
489 ERR("Could not allocate selector\n" );
490 return FALSE;
494 /* Fill the sub-heap structure */
496 subheap->heap = heap;
497 subheap->selector = selector;
498 subheap->size = totalSize;
499 subheap->commitSize = commitSize;
500 subheap->magic = SUBHEAP_MAGIC;
502 if ( subheap != (SUBHEAP *)heap )
504 /* If this is a secondary subheap, insert it into list */
506 subheap->headerSize = sizeof(SUBHEAP);
507 subheap->next = heap->subheap.next;
508 heap->subheap.next = subheap;
510 else
512 /* If this is a primary subheap, initialize main heap */
514 subheap->headerSize = sizeof(HEAP);
515 subheap->next = NULL;
516 heap->next = NULL;
517 heap->flags = flags;
518 heap->magic = HEAP_MAGIC;
520 /* Build the free lists */
522 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
524 pEntry->size = HEAP_freeListSizes[i];
525 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
526 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
527 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
528 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
529 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
530 pEntry->arena.threadId = 0;
531 pEntry->arena.magic = ARENA_FREE_MAGIC;
534 /* Initialize critical section */
536 InitializeCriticalSection( &heap->critSection );
537 /* FIXME: once separate address spaces are implemented, only */
538 /* the SystemHeap critical section should be global */
539 /* if (!SystemHeap) */
540 MakeCriticalSectionGlobal( &heap->critSection );
543 /* Create the first free block */
545 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
546 subheap->size - subheap->headerSize );
548 return TRUE;
551 /***********************************************************************
552 * HEAP_CreateSubHeap
554 * Create a sub-heap of the given size.
555 * If heap == NULL, creates a main heap.
557 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
558 DWORD commitSize, DWORD totalSize )
560 LPVOID address;
562 /* Round-up sizes on a 64K boundary */
564 if (flags & HEAP_WINE_SEGPTR)
566 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
568 else
570 totalSize = (totalSize + 0xffff) & 0xffff0000;
571 commitSize = (commitSize + 0xffff) & 0xffff0000;
572 if (!commitSize) commitSize = 0x10000;
573 if (totalSize < commitSize) totalSize = commitSize;
576 /* Allocate the memory block */
578 if (!(address = VirtualAlloc( NULL, totalSize,
579 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
581 WARN("Could not VirtualAlloc %08lx bytes\n",
582 totalSize );
583 return NULL;
586 /* Initialize subheap */
588 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
589 address, flags, commitSize, totalSize ))
591 VirtualFree( address, 0, MEM_RELEASE );
592 return NULL;
595 return (SUBHEAP *)address;
599 /***********************************************************************
600 * HEAP_FindFreeBlock
602 * Find a free block at least as large as the requested size, and make sure
603 * the requested size is committed.
605 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
606 SUBHEAP **ppSubHeap )
608 SUBHEAP *subheap;
609 ARENA_FREE *pArena;
610 FREE_LIST_ENTRY *pEntry = heap->freeList;
612 /* Find a suitable free list, and in it find a block large enough */
614 while (pEntry->size < size) pEntry++;
615 pArena = pEntry->arena.next;
616 while (pArena != &heap->freeList[0].arena)
618 if (pArena->size > size)
620 subheap = HEAP_FindSubHeap( heap, pArena );
621 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
622 + size + HEAP_MIN_BLOCK_SIZE))
623 return NULL;
624 *ppSubHeap = subheap;
625 return pArena;
628 pArena = pArena->next;
631 /* If no block was found, attempt to grow the heap */
633 if (!(heap->flags & HEAP_GROWABLE))
635 WARN("Not enough space in heap %08lx for %08lx bytes\n",
636 (DWORD)heap, size );
637 return NULL;
639 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
640 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
641 MAX( HEAP_DEF_SIZE, size ) )))
642 return NULL;
644 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
645 (DWORD)subheap, size, (DWORD)heap );
647 *ppSubHeap = subheap;
648 return (ARENA_FREE *)(subheap + 1);
652 /***********************************************************************
653 * HEAP_IsValidArenaPtr
655 * Check that the pointer is inside the range possible for arenas.
657 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
659 int i;
660 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
661 if (!subheap) return FALSE;
662 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
663 if (subheap != &heap->subheap) return FALSE;
664 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
665 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
666 return FALSE;
670 /***********************************************************************
671 * HEAP_ValidateFreeArena
673 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
675 char *heapEnd = (char *)subheap + subheap->size;
677 /* Check magic number */
678 if (pArena->magic != ARENA_FREE_MAGIC)
680 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
681 (DWORD)subheap->heap, (DWORD)pArena );
682 return FALSE;
684 /* Check size flags */
685 if (!(pArena->size & ARENA_FLAG_FREE) ||
686 (pArena->size & ARENA_FLAG_PREV_FREE))
688 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
689 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
691 /* Check arena size */
692 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
694 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
695 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
696 return FALSE;
698 /* Check that next pointer is valid */
699 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
701 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
702 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
703 return FALSE;
705 /* Check that next arena is free */
706 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
707 (pArena->next->magic != ARENA_FREE_MAGIC))
709 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
710 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
711 return FALSE;
713 /* Check that prev pointer is valid */
714 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
716 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
717 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
718 return FALSE;
720 /* Check that prev arena is free */
721 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
722 (pArena->prev->magic != ARENA_FREE_MAGIC))
724 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
725 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
726 return FALSE;
728 /* Check that next block has PREV_FREE flag */
729 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
731 if (!(*(DWORD *)((char *)(pArena + 1) +
732 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
734 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
735 (DWORD)subheap->heap, (DWORD)pArena );
736 return FALSE;
738 /* Check next block back pointer */
739 if (*((ARENA_FREE **)((char *)(pArena + 1) +
740 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
742 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
743 (DWORD)subheap->heap, (DWORD)pArena,
744 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
745 return FALSE;
748 return TRUE;
752 /***********************************************************************
753 * HEAP_ValidateInUseArena
755 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
757 char *heapEnd = (char *)subheap + subheap->size;
759 /* Check magic number */
760 if (pArena->magic != ARENA_INUSE_MAGIC)
762 if (quiet == NOISY) {
763 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
764 (DWORD)subheap->heap, (DWORD)pArena );
765 if (TRACE_ON(heap))
766 HEAP_Dump( subheap->heap );
767 } else if (WARN_ON(heap)) {
768 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
769 (DWORD)subheap->heap, (DWORD)pArena );
770 if (TRACE_ON(heap))
771 HEAP_Dump( subheap->heap );
773 return FALSE;
775 /* Check size flags */
776 if (pArena->size & ARENA_FLAG_FREE)
778 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
779 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
781 /* Check arena size */
782 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
784 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
785 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
786 return FALSE;
788 /* Check next arena PREV_FREE flag */
789 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
790 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
792 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
793 (DWORD)subheap->heap, (DWORD)pArena );
794 return FALSE;
796 /* Check prev free arena */
797 if (pArena->size & ARENA_FLAG_PREV_FREE)
799 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
800 /* Check prev pointer */
801 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
803 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
804 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
805 return FALSE;
807 /* Check that prev arena is free */
808 if (!(pPrev->size & ARENA_FLAG_FREE) ||
809 (pPrev->magic != ARENA_FREE_MAGIC))
811 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
812 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
813 return FALSE;
815 /* Check that prev arena is really the previous block */
816 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
818 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
819 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
820 return FALSE;
823 return TRUE;
827 /***********************************************************************
828 * HEAP_IsInsideHeap
829 * Checks whether the pointer points to a block inside a given heap.
831 * NOTES
832 * Should this return BOOL32?
834 * RETURNS
835 * !0: Success
836 * 0: Failure
838 int HEAP_IsInsideHeap(
839 HANDLE heap, /* [in] Heap */
840 DWORD flags, /* [in] Flags */
841 LPCVOID ptr /* [in] Pointer */
843 HEAP *heapPtr = HEAP_GetPtr( heap );
844 SUBHEAP *subheap;
845 int ret;
847 /* Validate the parameters */
849 if (!heapPtr) return 0;
850 flags |= heapPtr->flags;
851 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
852 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
853 (((char *)ptr >= (char *)subheap + subheap->headerSize
854 + sizeof(ARENA_INUSE))));
855 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
856 return ret;
860 /***********************************************************************
861 * HEAP_GetSegptr
863 * Transform a linear pointer into a SEGPTR. The pointer must have been
864 * allocated from a HEAP_WINE_SEGPTR heap.
866 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
868 HEAP *heapPtr = HEAP_GetPtr( heap );
869 SUBHEAP *subheap;
870 SEGPTR ret;
872 /* Validate the parameters */
874 if (!heapPtr) return 0;
875 flags |= heapPtr->flags;
876 if (!(flags & HEAP_WINE_SEGPTR))
878 ERR("Heap %08x is not a SEGPTR heap\n",
879 heap );
880 return 0;
882 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
884 /* Get the subheap */
886 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
888 ERR("%p is not inside heap %08x\n",
889 ptr, heap );
890 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
891 return 0;
894 /* Build the SEGPTR */
896 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
897 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
898 return ret;
901 /***********************************************************************
902 * HEAP_IsRealArena [Internal]
903 * Validates a block is a valid arena.
905 * RETURNS
906 * TRUE: Success
907 * FALSE: Failure
909 static BOOL HEAP_IsRealArena(
910 HANDLE heap, /* [in] Handle to the heap */
911 DWORD flags, /* [in] Bit flags that control access during operation */
912 LPCVOID block, /* [in] Optional pointer to memory block to validate */
913 BOOL quiet /* [in] Flag - if true, HEAP_ValidateInUseArena
914 * does not complain */
916 SUBHEAP *subheap;
917 HEAP *heapPtr = (HEAP *)(heap);
918 BOOL ret = TRUE;
920 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
922 ERR("Invalid heap %08x!\n", heap );
923 return FALSE;
926 flags &= HEAP_NO_SERIALIZE;
927 flags |= heapPtr->flags;
928 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
929 if (!(flags & HEAP_NO_SERIALIZE))
930 EnterCriticalSection( &heapPtr->critSection );
932 if (block)
934 /* Only check this single memory block */
936 /* The following code is really HEAP_IsInsideHeap *
937 * with serialization already done. */
938 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
939 ((char *)block < (char *)subheap + subheap->headerSize
940 + sizeof(ARENA_INUSE)))
942 if (quiet == NOISY)
943 ERR("Heap %08lx: block %08lx is not inside heap\n",
944 (DWORD)heap, (DWORD)block );
945 else if (WARN_ON(heap))
946 WARN("Heap %08lx: block %08lx is not inside heap\n",
947 (DWORD)heap, (DWORD)block );
948 ret = FALSE;
949 } else
950 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
952 if (!(flags & HEAP_NO_SERIALIZE))
953 LeaveCriticalSection( &heapPtr->critSection );
954 return ret;
957 subheap = &heapPtr->subheap;
958 while (subheap && ret)
960 char *ptr = (char *)subheap + subheap->headerSize;
961 while (ptr < (char *)subheap + subheap->size)
963 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
965 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
966 ret = FALSE;
967 break;
969 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
971 else
973 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
974 ret = FALSE;
975 break;
977 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
980 subheap = subheap->next;
983 if (!(flags & HEAP_NO_SERIALIZE))
984 LeaveCriticalSection( &heapPtr->critSection );
985 return ret;
989 /***********************************************************************
990 * HeapCreate (KERNEL32.336)
991 * RETURNS
992 * Handle of heap: Success
993 * NULL: Failure
995 HANDLE WINAPI HeapCreate(
996 DWORD flags, /* [in] Heap allocation flag */
997 DWORD initialSize, /* [in] Initial heap size */
998 DWORD maxSize /* [in] Maximum heap size */
1000 SUBHEAP *subheap;
1002 /* Allocate the heap block */
1004 if (!maxSize)
1006 maxSize = HEAP_DEF_SIZE;
1007 flags |= HEAP_GROWABLE;
1009 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1011 SetLastError( ERROR_OUTOFMEMORY );
1012 return 0;
1015 /* link it into the per-process heap list */
1016 if (processHeap)
1018 HEAP *heapPtr = subheap->heap;
1019 EnterCriticalSection( &processHeap->critSection );
1020 heapPtr->next = firstHeap;
1021 firstHeap = heapPtr;
1022 LeaveCriticalSection( &processHeap->critSection );
1024 else /* assume the first heap we create is the process main heap */
1026 processHeap = subheap->heap;
1029 return (HANDLE)subheap;
1032 /***********************************************************************
1033 * HeapDestroy (KERNEL32.337)
1034 * RETURNS
1035 * TRUE: Success
1036 * FALSE: Failure
1038 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1040 HEAP *heapPtr = HEAP_GetPtr( heap );
1041 SUBHEAP *subheap;
1043 TRACE("%08x\n", heap );
1044 if (!heapPtr) return FALSE;
1046 if (heapPtr == processHeap) /* cannot delete the main process heap */
1048 SetLastError( ERROR_INVALID_PARAMETER );
1049 return FALSE;
1051 else /* remove it from the per-process list */
1053 HEAP **pptr;
1054 EnterCriticalSection( &processHeap->critSection );
1055 pptr = &firstHeap;
1056 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1057 if (*pptr) *pptr = (*pptr)->next;
1058 LeaveCriticalSection( &processHeap->critSection );
1061 DeleteCriticalSection( &heapPtr->critSection );
1062 subheap = &heapPtr->subheap;
1063 while (subheap)
1065 SUBHEAP *next = subheap->next;
1066 if (subheap->selector) FreeSelector16( subheap->selector );
1067 VirtualFree( subheap, 0, MEM_RELEASE );
1068 subheap = next;
1070 return TRUE;
1074 /***********************************************************************
1075 * HeapAlloc (KERNEL32.334)
1076 * RETURNS
1077 * Pointer to allocated memory block
1078 * NULL: Failure
1080 LPVOID WINAPI HeapAlloc(
1081 HANDLE heap, /* [in] Handle of private heap block */
1082 DWORD flags, /* [in] Heap allocation control flags */
1083 DWORD size /* [in] Number of bytes to allocate */
1085 ARENA_FREE *pArena;
1086 ARENA_INUSE *pInUse;
1087 SUBHEAP *subheap;
1088 HEAP *heapPtr = HEAP_GetPtr( heap );
1090 /* Validate the parameters */
1092 if (!heapPtr) return NULL;
1093 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1094 flags |= heapPtr->flags;
1095 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1096 size = (size + 3) & ~3;
1097 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1099 /* Locate a suitable free block */
1101 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1103 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1104 heap, flags, size );
1105 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1106 SetLastError( ERROR_COMMITMENT_LIMIT );
1107 return NULL;
1110 /* Remove the arena from the free list */
1112 pArena->next->prev = pArena->prev;
1113 pArena->prev->next = pArena->next;
1115 /* Build the in-use arena */
1117 pInUse = (ARENA_INUSE *)pArena;
1118 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1119 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1120 pInUse->callerEIP = GET_EIP();
1121 pInUse->threadId = GetCurrentTask();
1122 pInUse->magic = ARENA_INUSE_MAGIC;
1124 /* Shrink the block */
1126 HEAP_ShrinkBlock( subheap, pInUse, size );
1128 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
1129 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
1131 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1133 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1134 heap, flags, size, (DWORD)(pInUse + 1) );
1135 return (LPVOID)(pInUse + 1);
1139 /***********************************************************************
1140 * HeapFree (KERNEL32.338)
1141 * RETURNS
1142 * TRUE: Success
1143 * FALSE: Failure
1145 BOOL WINAPI HeapFree(
1146 HANDLE heap, /* [in] Handle of heap */
1147 DWORD flags, /* [in] Heap freeing flags */
1148 LPVOID ptr /* [in] Address of memory to free */
1150 ARENA_INUSE *pInUse;
1151 SUBHEAP *subheap;
1152 HEAP *heapPtr = HEAP_GetPtr( heap );
1154 /* Validate the parameters */
1156 if (!heapPtr) return FALSE;
1157 flags &= HEAP_NO_SERIALIZE;
1158 flags |= heapPtr->flags;
1159 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1160 if (!ptr)
1162 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1163 heap, flags, (DWORD)ptr );
1165 if (!ptr || !HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1167 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1168 SetLastError( ERROR_INVALID_PARAMETER );
1169 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1170 heap, flags, (DWORD)ptr );
1171 return FALSE;
1174 /* Turn the block into a free block */
1176 pInUse = (ARENA_INUSE *)ptr - 1;
1177 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1178 HEAP_MakeInUseBlockFree( subheap, pInUse );
1180 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1181 /* SetLastError( 0 ); */
1183 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1184 heap, flags, (DWORD)ptr );
1185 return TRUE;
1189 /***********************************************************************
1190 * HeapReAlloc (KERNEL32.340)
1191 * RETURNS
1192 * Pointer to reallocated memory block
1193 * NULL: Failure
1195 LPVOID WINAPI HeapReAlloc(
1196 HANDLE heap, /* [in] Handle of heap block */
1197 DWORD flags, /* [in] Heap reallocation flags */
1198 LPVOID ptr, /* [in] Address of memory to reallocate */
1199 DWORD size /* [in] Number of bytes to reallocate */
1201 ARENA_INUSE *pArena;
1202 DWORD oldSize;
1203 HEAP *heapPtr;
1204 SUBHEAP *subheap;
1206 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1207 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1209 /* Validate the parameters */
1211 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1212 HEAP_REALLOC_IN_PLACE_ONLY;
1213 flags |= heapPtr->flags;
1214 size = (size + 3) & ~3;
1215 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1217 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1218 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1220 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1221 SetLastError( ERROR_INVALID_PARAMETER );
1222 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1223 heap, flags, (DWORD)ptr, size );
1224 return NULL;
1227 /* Check if we need to grow the block */
1229 pArena = (ARENA_INUSE *)ptr - 1;
1230 pArena->threadId = GetCurrentTask();
1231 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1232 oldSize = (pArena->size & ARENA_SIZE_MASK);
1233 if (size > oldSize)
1235 char *pNext = (char *)(pArena + 1) + oldSize;
1236 if ((pNext < (char *)subheap + subheap->size) &&
1237 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1238 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1240 /* The next block is free and large enough */
1241 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1242 pFree->next->prev = pFree->prev;
1243 pFree->prev->next = pFree->next;
1244 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1245 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1246 + size + HEAP_MIN_BLOCK_SIZE))
1248 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1249 SetLastError( ERROR_OUTOFMEMORY );
1250 return NULL;
1252 HEAP_ShrinkBlock( subheap, pArena, size );
1254 else /* Do it the hard way */
1256 ARENA_FREE *pNew;
1257 ARENA_INUSE *pInUse;
1258 SUBHEAP *newsubheap;
1260 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1261 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1263 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1264 SetLastError( ERROR_OUTOFMEMORY );
1265 return NULL;
1268 /* Build the in-use arena */
1270 pNew->next->prev = pNew->prev;
1271 pNew->prev->next = pNew->next;
1272 pInUse = (ARENA_INUSE *)pNew;
1273 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1274 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1275 pInUse->threadId = GetCurrentTask();
1276 pInUse->magic = ARENA_INUSE_MAGIC;
1277 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1278 memcpy( pInUse + 1, pArena + 1, oldSize );
1280 /* Free the previous block */
1282 HEAP_MakeInUseBlockFree( subheap, pArena );
1283 subheap = newsubheap;
1284 pArena = pInUse;
1287 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1289 /* Clear the extra bytes if needed */
1291 if (size > oldSize)
1293 if (flags & HEAP_ZERO_MEMORY)
1294 memset( (char *)(pArena + 1) + oldSize, 0,
1295 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1296 else if (TRACE_ON(heap))
1297 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1298 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1301 /* Return the new arena */
1303 pArena->callerEIP = GET_EIP();
1304 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1306 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1307 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1308 return (LPVOID)(pArena + 1);
1312 /***********************************************************************
1313 * HeapCompact (KERNEL32.335)
1315 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1317 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1318 return 0;
1322 /***********************************************************************
1323 * HeapLock (KERNEL32.339)
1324 * Attempts to acquire the critical section object for a specified heap.
1326 * RETURNS
1327 * TRUE: Success
1328 * FALSE: Failure
1330 BOOL WINAPI HeapLock(
1331 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1333 HEAP *heapPtr = HEAP_GetPtr( heap );
1334 if (!heapPtr) return FALSE;
1335 EnterCriticalSection( &heapPtr->critSection );
1336 return TRUE;
1340 /***********************************************************************
1341 * HeapUnlock (KERNEL32.342)
1342 * Releases ownership of the critical section object.
1344 * RETURNS
1345 * TRUE: Success
1346 * FALSE: Failure
1348 BOOL WINAPI HeapUnlock(
1349 HANDLE heap /* [in] Handle to the heap to unlock */
1351 HEAP *heapPtr = HEAP_GetPtr( heap );
1352 if (!heapPtr) return FALSE;
1353 LeaveCriticalSection( &heapPtr->critSection );
1354 return TRUE;
1358 /***********************************************************************
1359 * HeapSize (KERNEL32.341)
1360 * RETURNS
1361 * Size in bytes of allocated memory
1362 * 0xffffffff: Failure
1364 DWORD WINAPI HeapSize(
1365 HANDLE heap, /* [in] Handle of heap */
1366 DWORD flags, /* [in] Heap size control flags */
1367 LPVOID ptr /* [in] Address of memory to return size for */
1369 DWORD ret;
1370 HEAP *heapPtr = HEAP_GetPtr( heap );
1372 if (!heapPtr) return FALSE;
1373 flags &= HEAP_NO_SERIALIZE;
1374 flags |= heapPtr->flags;
1375 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1376 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1378 SetLastError( ERROR_INVALID_PARAMETER );
1379 ret = 0xffffffff;
1381 else
1383 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1384 ret = pArena->size & ARENA_SIZE_MASK;
1386 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1388 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1389 heap, flags, (DWORD)ptr, ret );
1390 return ret;
1394 /***********************************************************************
1395 * HeapValidate (KERNEL32.343)
1396 * Validates a specified heap.
1398 * NOTES
1399 * Flags is ignored.
1401 * RETURNS
1402 * TRUE: Success
1403 * FALSE: Failure
1405 BOOL WINAPI HeapValidate(
1406 HANDLE heap, /* [in] Handle to the heap */
1407 DWORD flags, /* [in] Bit flags that control access during operation */
1408 LPCVOID block /* [in] Optional pointer to memory block to validate */
1411 return HEAP_IsRealArena( heap, flags, block, QUIET );
1415 /***********************************************************************
1416 * HeapWalk (KERNEL32.344)
1417 * Enumerates the memory blocks in a specified heap.
1419 * RETURNS
1420 * TRUE: Success
1421 * FALSE: Failure
1423 BOOL WINAPI HeapWalk(
1424 HANDLE heap, /* [in] Handle to heap to enumerate */
1425 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1427 FIXME("(%08x): stub.\n", heap );
1428 return FALSE;
1432 /***********************************************************************
1433 * HEAP_CreateSystemHeap
1435 * Create the system heap.
1437 BOOL HEAP_CreateSystemHeap(void)
1439 SYSTEM_HEAP_DESCR *descr;
1440 HANDLE heap;
1441 HEAP *heapPtr;
1442 int created;
1444 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1445 0, HEAP_DEF_SIZE, "__SystemHeap" );
1446 if (!map) return FALSE;
1447 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1449 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1451 /* pre-defined address not available, use any one */
1452 fprintf( stderr, "Warning: system heap base address %p not available\n",
1453 SYSTEM_HEAP_BASE );
1454 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1456 CloseHandle( map );
1457 return FALSE;
1460 heap = (HANDLE)heapPtr;
1462 if (created) /* newly created heap */
1464 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_WINE_SHARED, 0, HEAP_DEF_SIZE );
1465 HeapLock( heap );
1466 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1467 assert( descr );
1469 else
1471 /* wait for the heap to be initialized */
1472 while (!heapPtr->private) Sleep(1);
1473 HeapLock( heap );
1474 /* remap it to the right address if necessary */
1475 if (heapPtr->subheap.heap != heapPtr)
1477 void *base = heapPtr->subheap.heap;
1478 HeapUnlock( heap );
1479 UnmapViewOfFile( heapPtr );
1480 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1482 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1483 CloseHandle( map );
1484 return FALSE;
1486 heap = (HANDLE)heapPtr;
1487 HeapLock( heap );
1489 descr = heapPtr->private;
1490 assert( descr );
1492 SystemHeap = heap;
1493 SystemHeapDescr = descr;
1494 HeapUnlock( heap );
1495 CloseHandle( map );
1496 return TRUE;
1500 /***********************************************************************
1501 * GetProcessHeap (KERNEL32.259)
1503 HANDLE WINAPI GetProcessHeap(void)
1505 return (HANDLE)processHeap;
1509 /***********************************************************************
1510 * GetProcessHeaps (KERNEL32.376)
1512 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1514 DWORD total;
1515 HEAP *ptr;
1517 if (!processHeap) return 0; /* should never happen */
1518 total = 1; /* main heap */
1519 EnterCriticalSection( &processHeap->critSection );
1520 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1521 if (total <= count)
1523 *heaps++ = (HANDLE)processHeap;
1524 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1526 LeaveCriticalSection( &processHeap->critSection );
1527 return total;
1531 /***********************************************************************
1532 * HEAP_xalloc
1534 * Same as HeapAlloc(), but die on failure.
1536 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1538 LPVOID p = HeapAlloc( heap, flags, size );
1539 if (!p)
1541 MESSAGE("Virtual memory exhausted.\n" );
1542 exit(1);
1544 SET_EIP(p);
1545 return p;
1549 /***********************************************************************
1550 * HEAP_xrealloc
1552 * Same as HeapReAlloc(), but die on failure.
1554 LPVOID HEAP_xrealloc( HANDLE heap, DWORD flags, LPVOID lpMem, DWORD size )
1556 LPVOID p = HeapReAlloc( heap, flags, lpMem, size );
1557 if (!p)
1559 MESSAGE("Virtual memory exhausted.\n" );
1560 exit(1);
1562 SET_EIP(p);
1563 return p;
1567 /***********************************************************************
1568 * HEAP_strdupA
1570 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1572 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1573 SET_EIP(p);
1574 strcpy( p, str );
1575 return p;
1579 /***********************************************************************
1580 * HEAP_strdupW
1582 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1584 INT len = lstrlenW(str) + 1;
1585 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1586 SET_EIP(p);
1587 lstrcpyW( p, str );
1588 return p;
1592 /***********************************************************************
1593 * HEAP_strdupAtoW
1595 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1597 LPWSTR ret;
1599 if (!str) return NULL;
1600 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1601 SET_EIP(ret);
1602 lstrcpyAtoW( ret, str );
1603 return ret;
1607 /***********************************************************************
1608 * HEAP_strdupWtoA
1610 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1612 LPSTR ret;
1614 if (!str) return NULL;
1615 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1616 SET_EIP(ret);
1617 lstrcpyWtoA( ret, str );
1618 return ret;
1623 /***********************************************************************
1624 * 32-bit local heap functions (Win95; undocumented)
1627 #define HTABLE_SIZE 0x10000
1628 #define HTABLE_PAGESIZE 0x1000
1629 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1631 #include "pshpack1.h"
1632 typedef struct _LOCAL32HEADER
1634 WORD freeListFirst[HTABLE_NPAGES];
1635 WORD freeListSize[HTABLE_NPAGES];
1636 WORD freeListLast[HTABLE_NPAGES];
1638 DWORD selectorTableOffset;
1639 WORD selectorTableSize;
1640 WORD selectorDelta;
1642 DWORD segment;
1643 LPBYTE base;
1645 DWORD limit;
1646 DWORD flags;
1648 DWORD magic;
1649 HANDLE heap;
1651 } LOCAL32HEADER;
1652 #include "poppack.h"
1654 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1656 /***********************************************************************
1657 * Local32Init (KERNEL.208)
1659 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1660 DWORD heapSize, DWORD flags )
1662 DWORD totSize, segSize = 0;
1663 LPBYTE base;
1664 LOCAL32HEADER *header;
1665 HEAP *heap;
1666 WORD *selectorTable;
1667 WORD selectorEven, selectorOdd;
1668 int i, nrBlocks;
1670 /* Determine new heap size */
1672 if ( segment )
1674 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1675 return 0;
1676 else
1677 segSize++;
1680 if ( heapSize == -1L )
1681 heapSize = 1024L*1024L; /* FIXME */
1683 heapSize = (heapSize + 0xffff) & 0xffff0000;
1684 segSize = (segSize + 0x0fff) & 0xfffff000;
1685 totSize = segSize + HTABLE_SIZE + heapSize;
1688 /* Allocate memory and initialize heap */
1690 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1691 return 0;
1693 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1694 MEM_COMMIT, PAGE_READWRITE ) )
1696 VirtualFree( base, 0, MEM_RELEASE );
1697 return 0;
1700 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1701 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1703 VirtualFree( base, 0, MEM_RELEASE );
1704 return 0;
1708 /* Set up header and handle table */
1710 header = (LOCAL32HEADER *)(base + segSize);
1711 header->base = base;
1712 header->limit = HTABLE_PAGESIZE-1;
1713 header->flags = 0;
1714 header->magic = LOCAL32_MAGIC;
1715 header->heap = (HANDLE)heap;
1717 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1718 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1719 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1721 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1722 *(DWORD *)((LPBYTE)header + i) = i+4;
1724 header->freeListFirst[1] = 0xffff;
1727 /* Set up selector table */
1729 nrBlocks = (totSize + 0x7fff) >> 15;
1730 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1731 selectorEven = SELECTOR_AllocBlock( base, totSize,
1732 SEGMENT_DATA, FALSE, FALSE );
1733 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1734 SEGMENT_DATA, FALSE, FALSE );
1736 if ( !selectorTable || !selectorEven || !selectorOdd )
1738 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1739 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1740 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1741 HeapDestroy( header->heap );
1742 VirtualFree( base, 0, MEM_RELEASE );
1743 return 0;
1746 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1747 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1748 header->selectorDelta = selectorEven - selectorOdd;
1749 header->segment = segment? segment : selectorEven;
1751 for (i = 0; i < nrBlocks; i++)
1752 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1753 : selectorEven + ((i >> 1) << __AHSHIFT);
1755 /* Move old segment */
1757 if ( segment )
1759 /* FIXME: This is somewhat ugly and relies on implementation
1760 details about 16-bit global memory handles ... */
1762 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1763 memcpy( base, oldBase, segSize );
1764 GLOBAL_MoveBlock( segment, base, totSize );
1765 HeapFree( SystemHeap, 0, oldBase );
1768 return (HANDLE)header;
1771 /***********************************************************************
1772 * Local32_SearchHandle
1774 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1776 LPDWORD handle;
1778 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1779 handle < (LPDWORD)((LPBYTE)header + header->limit);
1780 handle++)
1782 if (*handle == addr)
1783 return handle;
1786 return NULL;
1789 /***********************************************************************
1790 * Local32_ToHandle
1792 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1793 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1795 *handle = NULL;
1796 *ptr = NULL;
1798 switch (type)
1800 case -2: /* 16:16 pointer, no handles */
1801 *ptr = PTR_SEG_TO_LIN( addr );
1802 *handle = (LPDWORD)*ptr;
1803 break;
1805 case -1: /* 32-bit offset, no handles */
1806 *ptr = header->base + addr;
1807 *handle = (LPDWORD)*ptr;
1808 break;
1810 case 0: /* handle */
1811 if ( addr >= sizeof(LOCAL32HEADER)
1812 && addr < header->limit && !(addr & 3)
1813 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1815 *handle = (LPDWORD)((LPBYTE)header + addr);
1816 *ptr = header->base + **handle;
1818 break;
1820 case 1: /* 16:16 pointer */
1821 *ptr = PTR_SEG_TO_LIN( addr );
1822 *handle = Local32_SearchHandle( header, *ptr - header->base );
1823 break;
1825 case 2: /* 32-bit offset */
1826 *ptr = header->base + addr;
1827 *handle = Local32_SearchHandle( header, *ptr - header->base );
1828 break;
1832 /***********************************************************************
1833 * Local32_FromHandle
1835 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1836 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1838 switch (type)
1840 case -2: /* 16:16 pointer */
1841 case 1:
1843 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1844 DWORD offset = (LPBYTE)ptr - header->base;
1845 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1847 break;
1849 case -1: /* 32-bit offset */
1850 case 2:
1851 *addr = ptr - header->base;
1852 break;
1854 case 0: /* handle */
1855 *addr = (LPBYTE)handle - (LPBYTE)header;
1856 break;
1860 /***********************************************************************
1861 * Local32Alloc (KERNEL.209)
1863 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1865 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1866 LPDWORD handle;
1867 LPBYTE ptr;
1868 DWORD addr;
1870 /* Allocate memory */
1871 ptr = HeapAlloc( header->heap,
1872 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1873 if (!ptr) return 0;
1876 /* Allocate handle if requested */
1877 if (type >= 0)
1879 int page, i;
1881 /* Find first page of handle table with free slots */
1882 for (page = 0; page < HTABLE_NPAGES; page++)
1883 if (header->freeListFirst[page] != 0)
1884 break;
1885 if (page == HTABLE_NPAGES)
1887 WARN("Out of handles!\n" );
1888 HeapFree( header->heap, 0, ptr );
1889 return 0;
1892 /* If virgin page, initialize it */
1893 if (header->freeListFirst[page] == 0xffff)
1895 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1896 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1898 WARN("Cannot grow handle table!\n" );
1899 HeapFree( header->heap, 0, ptr );
1900 return 0;
1903 header->limit += HTABLE_PAGESIZE;
1905 header->freeListFirst[page] = 0;
1906 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1907 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1909 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1910 *(DWORD *)((LPBYTE)header + i) = i+4;
1912 if (page < HTABLE_NPAGES-1)
1913 header->freeListFirst[page+1] = 0xffff;
1916 /* Allocate handle slot from page */
1917 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1918 if (--header->freeListSize[page] == 0)
1919 header->freeListFirst[page] = header->freeListLast[page] = 0;
1920 else
1921 header->freeListFirst[page] = *handle;
1923 /* Store 32-bit offset in handle slot */
1924 *handle = ptr - header->base;
1926 else
1928 handle = (LPDWORD)ptr;
1929 header->flags |= 1;
1933 /* Convert handle to requested output type */
1934 Local32_FromHandle( header, type, &addr, handle, ptr );
1935 return addr;
1938 /***********************************************************************
1939 * Local32ReAlloc (KERNEL.210)
1941 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1942 DWORD size, DWORD flags )
1944 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1945 LPDWORD handle;
1946 LPBYTE ptr;
1948 if (!addr)
1949 return Local32Alloc16( heap, size, type, flags );
1951 /* Retrieve handle and pointer */
1952 Local32_ToHandle( header, type, addr, &handle, &ptr );
1953 if (!handle) return FALSE;
1955 /* Reallocate memory block */
1956 ptr = HeapReAlloc( header->heap,
1957 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1958 ptr, size );
1959 if (!ptr) return 0;
1961 /* Modify handle */
1962 if (type >= 0)
1963 *handle = ptr - header->base;
1964 else
1965 handle = (LPDWORD)ptr;
1967 /* Convert handle to requested output type */
1968 Local32_FromHandle( header, type, &addr, handle, ptr );
1969 return addr;
1972 /***********************************************************************
1973 * Local32Free (KERNEL.211)
1975 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1977 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1978 LPDWORD handle;
1979 LPBYTE ptr;
1981 /* Retrieve handle and pointer */
1982 Local32_ToHandle( header, type, addr, &handle, &ptr );
1983 if (!handle) return FALSE;
1985 /* Free handle if necessary */
1986 if (type >= 0)
1988 int offset = (LPBYTE)handle - (LPBYTE)header;
1989 int page = offset >> 12;
1991 /* Return handle slot to page free list */
1992 if (header->freeListSize[page]++ == 0)
1993 header->freeListFirst[page] = header->freeListLast[page] = offset;
1994 else
1995 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1996 header->freeListLast[page] = offset;
1998 *handle = 0;
2000 /* Shrink handle table when possible */
2001 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2003 if ( VirtualFree( (LPBYTE)header +
2004 (header->limit & ~(HTABLE_PAGESIZE-1)),
2005 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2006 break;
2008 header->limit -= HTABLE_PAGESIZE;
2009 header->freeListFirst[page] = 0xffff;
2010 page--;
2014 /* Free memory */
2015 return HeapFree( header->heap, 0, ptr );
2018 /***********************************************************************
2019 * Local32Translate (KERNEL.213)
2021 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2023 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2024 LPDWORD handle;
2025 LPBYTE ptr;
2027 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2028 if (!handle) return 0;
2030 Local32_FromHandle( header, type2, &addr, handle, ptr );
2031 return addr;
2034 /***********************************************************************
2035 * Local32Size (KERNEL.214)
2037 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2039 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2040 LPDWORD handle;
2041 LPBYTE ptr;
2043 Local32_ToHandle( header, type, addr, &handle, &ptr );
2044 if (!handle) return 0;
2046 return HeapSize( header->heap, 0, ptr );
2049 /***********************************************************************
2050 * Local32ValidHandle (KERNEL.215)
2052 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2054 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2055 LPDWORD handle;
2056 LPBYTE ptr;
2058 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2059 return handle != NULL;
2062 /***********************************************************************
2063 * Local32GetSegment (KERNEL.229)
2065 WORD WINAPI Local32GetSegment16( HANDLE heap )
2067 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2068 return header->segment;
2071 /***********************************************************************
2072 * Local32_GetHeap
2074 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2076 WORD selector = GlobalHandleToSel16( handle );
2077 DWORD base = GetSelectorBase( selector );
2078 DWORD limit = GetSelectorLimit16( selector );
2080 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2081 it this way ... */
2083 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2084 return (LOCAL32HEADER *)base;
2086 base += 0x10000;
2087 limit -= 0x10000;
2089 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2090 return (LOCAL32HEADER *)base;
2092 return NULL;
2095 /***********************************************************************
2096 * Local32Info (KERNEL.444) (TOOLHELP.84)
2098 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2100 SUBHEAP *heapPtr;
2101 LPBYTE ptr;
2102 int i;
2104 LOCAL32HEADER *header = Local32_GetHeap( handle );
2105 if ( !header ) return FALSE;
2107 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2108 return FALSE;
2110 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2111 pLocal32Info->dwMemReserved = heapPtr->size;
2112 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2113 pLocal32Info->dwTotalFree = 0L;
2114 pLocal32Info->dwLargestFreeBlock = 0L;
2116 /* Note: Local32 heaps always have only one subheap! */
2117 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2118 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2120 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2122 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2123 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2124 ptr += sizeof(*pArena) + size;
2126 pLocal32Info->dwTotalFree += size;
2127 if ( size > pLocal32Info->dwLargestFreeBlock )
2128 pLocal32Info->dwLargestFreeBlock = size;
2130 else
2132 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2133 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2134 ptr += sizeof(*pArena) + size;
2138 pLocal32Info->dwcFreeHandles = 0;
2139 for ( i = 0; i < HTABLE_NPAGES; i++ )
2141 if ( header->freeListFirst[i] == 0xffff ) break;
2142 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2144 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2146 return TRUE;
2149 /***********************************************************************
2150 * Local32First (KERNEL.445) (TOOLHELP.85)
2152 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2154 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2155 return FALSE;
2158 /***********************************************************************
2159 * Local32Next (KERNEL.446) (TOOLHELP.86)
2161 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2163 FIXME("(%p): stub!\n", pLocal32Entry );
2164 return FALSE;