Do not send a WM_CONTEXTMENU message when a TreeView receives a
[wine/wine-kai.git] / memory / heap.c
blobba946d9777150fde1fb6b5c91315784d84a3d65b
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 <stdio.h>
11 #include <string.h>
12 #include "wine/winbase16.h"
13 #include "wine/winestring.h"
14 #include "wine/unicode.h"
15 #include "selectors.h"
16 #include "global.h"
17 #include "winbase.h"
18 #include "winerror.h"
19 #include "winnt.h"
20 #include "heap.h"
21 #include "toolhelp.h"
22 #include "debugtools.h"
23 #include "winnls.h"
25 DEFAULT_DEBUG_CHANNEL(heap);
27 /* Note: the heap data structures are based on what Pietrek describes in his
28 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
29 * the same, but could be easily adapted if it turns out some programs
30 * require it.
33 typedef struct tagARENA_INUSE
35 DWORD size; /* Block size; must be the first field */
36 WORD magic; /* Magic number */
37 WORD threadId; /* Allocating thread id */
38 void *callerEIP; /* EIP of caller upon allocation */
39 } ARENA_INUSE;
41 typedef struct tagARENA_FREE
43 DWORD size; /* Block size; must be the first field */
44 WORD magic; /* Magic number */
45 WORD threadId; /* Freeing thread id */
46 struct tagARENA_FREE *next; /* Next free arena */
47 struct tagARENA_FREE *prev; /* Prev free arena */
48 } ARENA_FREE;
50 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
51 #define ARENA_FLAG_PREV_FREE 0x00000002
52 #define ARENA_SIZE_MASK 0xfffffffc
53 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
54 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
56 #define ARENA_INUSE_FILLER 0x55
57 #define ARENA_FREE_FILLER 0xaa
59 #define QUIET 1 /* Suppress messages */
60 #define NOISY 0 /* Report all errors */
62 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
64 /* Max size of the blocks on the free lists */
65 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
67 0x20, 0x80, 0x200, 0xffffffff
70 typedef struct
72 DWORD size;
73 ARENA_FREE arena;
74 } FREE_LIST_ENTRY;
76 struct tagHEAP;
78 typedef struct tagSUBHEAP
80 DWORD size; /* Size of the whole sub-heap */
81 DWORD commitSize; /* Committed size of the sub-heap */
82 DWORD headerSize; /* Size of the heap header */
83 struct tagSUBHEAP *next; /* Next sub-heap */
84 struct tagHEAP *heap; /* Main heap structure */
85 DWORD magic; /* Magic number */
86 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
87 } SUBHEAP;
89 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
91 typedef struct tagHEAP
93 SUBHEAP subheap; /* First sub-heap */
94 struct tagHEAP *next; /* Next heap for this process */
95 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
96 CRITICAL_SECTION critSection; /* Critical section for serialization */
97 DWORD flags; /* Heap flags */
98 DWORD magic; /* Magic number */
99 void *private; /* Private pointer for the user of the heap */
100 } HEAP;
102 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
104 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
105 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
106 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
108 HANDLE SystemHeap = 0;
109 HANDLE SegptrHeap = 0;
111 SYSTEM_HEAP_DESCR *SystemHeapDescr = 0;
113 static HEAP *processHeap; /* main process heap */
114 static HEAP *firstHeap; /* head of secondary heaps list */
116 /* address where we try to map the system heap */
117 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
119 static BOOL HEAP_IsRealArena( HANDLE heap, DWORD flags, LPCVOID block, BOOL quiet );
121 #ifdef __GNUC__
122 #define GET_EIP() (__builtin_return_address(0))
123 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
124 #else
125 #define GET_EIP() 0
126 #define SET_EIP(ptr) /* nothing */
127 #endif /* __GNUC__ */
129 /***********************************************************************
130 * HEAP_Dump
132 void HEAP_Dump( HEAP *heap )
134 int i;
135 SUBHEAP *subheap;
136 char *ptr;
138 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
139 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
140 (DWORD)heap->next, (DWORD)&heap->subheap );
141 subheap = &heap->subheap;
142 while (subheap->next)
144 DPRINTF( " -> %08lx", (DWORD)subheap->next );
145 subheap = subheap->next;
148 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
149 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
150 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
151 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
152 heap->freeList[i].arena.threadId,
153 (DWORD)heap->freeList[i].arena.prev,
154 (DWORD)heap->freeList[i].arena.next );
156 subheap = &heap->subheap;
157 while (subheap)
159 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
160 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
161 (DWORD)subheap, subheap->size, subheap->commitSize );
163 DPRINTF( "\n Block Stat Size Id\n" );
164 ptr = (char*)subheap + subheap->headerSize;
165 while (ptr < (char *)subheap + subheap->size)
167 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
169 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
170 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
171 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
172 pArena->threadId, (DWORD)pArena->prev,
173 (DWORD)pArena->next);
174 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
175 arenaSize += sizeof(ARENA_FREE);
176 freeSize += pArena->size & ARENA_SIZE_MASK;
178 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
180 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
181 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
182 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
183 pArena->threadId, *((DWORD *)pArena - 1),
184 pArena->callerEIP );
185 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
186 arenaSize += sizeof(ARENA_INUSE);
187 usedSize += pArena->size & ARENA_SIZE_MASK;
189 else
191 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
192 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
193 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
194 pArena->threadId, pArena->callerEIP );
195 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
196 arenaSize += sizeof(ARENA_INUSE);
197 usedSize += pArena->size & ARENA_SIZE_MASK;
200 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
201 subheap->size, subheap->commitSize, freeSize, usedSize,
202 arenaSize, (arenaSize * 100) / subheap->size );
203 subheap = subheap->next;
208 /***********************************************************************
209 * HEAP_GetPtr
210 * RETURNS
211 * Pointer to the heap
212 * NULL: Failure
214 static HEAP *HEAP_GetPtr(
215 HANDLE heap /* [in] Handle to the heap */
217 HEAP *heapPtr = (HEAP *)heap;
218 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
220 ERR("Invalid heap %08x!\n", heap );
221 SetLastError( ERROR_INVALID_HANDLE );
222 return NULL;
224 if (TRACE_ON(heap) && !HEAP_IsRealArena( heap, 0, NULL, NOISY ))
226 HEAP_Dump( heapPtr );
227 assert( FALSE );
228 SetLastError( ERROR_INVALID_HANDLE );
229 return NULL;
231 return heapPtr;
235 /***********************************************************************
236 * HEAP_InsertFreeBlock
238 * Insert a free block into the free list.
240 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
242 FREE_LIST_ENTRY *pEntry = heap->freeList;
243 while (pEntry->size < pArena->size) pEntry++;
244 pArena->size |= ARENA_FLAG_FREE;
245 pArena->next = pEntry->arena.next;
246 pArena->next->prev = pArena;
247 pArena->prev = &pEntry->arena;
248 pEntry->arena.next = pArena;
252 /***********************************************************************
253 * HEAP_FindSubHeap
254 * Find the sub-heap containing a given address.
256 * RETURNS
257 * Pointer: Success
258 * NULL: Failure
260 static SUBHEAP *HEAP_FindSubHeap(
261 HEAP *heap, /* [in] Heap pointer */
262 LPCVOID ptr /* [in] Address */
264 SUBHEAP *sub = &heap->subheap;
265 while (sub)
267 if (((char *)ptr >= (char *)sub) &&
268 ((char *)ptr < (char *)sub + sub->size)) return sub;
269 sub = sub->next;
271 return NULL;
275 /***********************************************************************
276 * HEAP_Commit
278 * Make sure the heap storage is committed up to (not including) ptr.
280 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
282 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
283 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
284 if (size > subheap->size) size = subheap->size;
285 if (size <= subheap->commitSize) return TRUE;
286 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
287 size - subheap->commitSize, MEM_COMMIT,
288 PAGE_EXECUTE_READWRITE))
290 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
291 size - subheap->commitSize,
292 (DWORD)((char *)subheap + subheap->commitSize),
293 (DWORD)subheap->heap );
294 return FALSE;
296 subheap->commitSize = size;
297 return TRUE;
301 /***********************************************************************
302 * HEAP_Decommit
304 * If possible, decommit the heap storage from (including) 'ptr'.
306 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
308 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
309 /* round to next block and add one full block */
310 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
311 if (size >= subheap->commitSize) return TRUE;
312 if (!VirtualFree( (char *)subheap + size,
313 subheap->commitSize - size, MEM_DECOMMIT ))
315 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
316 subheap->commitSize - size,
317 (DWORD)((char *)subheap + size),
318 (DWORD)subheap->heap );
319 return FALSE;
321 subheap->commitSize = size;
322 return TRUE;
326 /***********************************************************************
327 * HEAP_CreateFreeBlock
329 * Create a free block at a specified address. 'size' is the size of the
330 * whole block, including the new arena.
332 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
334 ARENA_FREE *pFree;
336 /* Create a free arena */
338 pFree = (ARENA_FREE *)ptr;
339 pFree->threadId = GetCurrentTask();
340 pFree->magic = ARENA_FREE_MAGIC;
342 /* If debugging, erase the freed block content */
344 if (TRACE_ON(heap))
346 char *pEnd = (char *)ptr + size;
347 if (pEnd > (char *)subheap + subheap->commitSize)
348 pEnd = (char *)subheap + subheap->commitSize;
349 if (pEnd > (char *)(pFree + 1))
350 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
353 /* Check if next block is free also */
355 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
356 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
358 /* Remove the next arena from the free list */
359 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
360 pNext->next->prev = pNext->prev;
361 pNext->prev->next = pNext->next;
362 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
363 if (TRACE_ON(heap))
364 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
367 /* Set the next block PREV_FREE flag and pointer */
369 if ((char *)ptr + size < (char *)subheap + subheap->size)
371 DWORD *pNext = (DWORD *)((char *)ptr + size);
372 *pNext |= ARENA_FLAG_PREV_FREE;
373 *(ARENA_FREE **)(pNext - 1) = pFree;
376 /* Last, insert the new block into the free list */
378 pFree->size = size - sizeof(*pFree);
379 HEAP_InsertFreeBlock( subheap->heap, pFree );
383 /***********************************************************************
384 * HEAP_MakeInUseBlockFree
386 * Turn an in-use block into a free block. Can also decommit the end of
387 * the heap, and possibly even free the sub-heap altogether.
389 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
391 ARENA_FREE *pFree;
392 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
394 /* Check if we can merge with previous block */
396 if (pArena->size & ARENA_FLAG_PREV_FREE)
398 pFree = *((ARENA_FREE **)pArena - 1);
399 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
400 /* Remove it from the free list */
401 pFree->next->prev = pFree->prev;
402 pFree->prev->next = pFree->next;
404 else pFree = (ARENA_FREE *)pArena;
406 /* Create a free block */
408 HEAP_CreateFreeBlock( subheap, pFree, size );
409 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
410 if ((char *)pFree + size < (char *)subheap + subheap->size)
411 return; /* Not the last block, so nothing more to do */
413 /* Free the whole sub-heap if it's empty and not the original one */
415 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
416 (subheap != &subheap->heap->subheap))
418 SUBHEAP *pPrev = &subheap->heap->subheap;
419 /* Remove the free block from the list */
420 pFree->next->prev = pFree->prev;
421 pFree->prev->next = pFree->next;
422 /* Remove the subheap from the list */
423 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
424 if (pPrev) pPrev->next = subheap->next;
425 /* Free the memory */
426 subheap->magic = 0;
427 if (subheap->selector) FreeSelector16( subheap->selector );
428 VirtualFree( subheap, 0, MEM_RELEASE );
429 return;
432 /* Decommit the end of the heap */
434 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
438 /***********************************************************************
439 * HEAP_ShrinkBlock
441 * Shrink an in-use block.
443 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
445 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
447 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
448 (pArena->size & ARENA_SIZE_MASK) - size );
449 /* assign size plus previous arena flags */
450 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
452 else
454 /* Turn off PREV_FREE flag in next block */
455 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
456 if (pNext < (char *)subheap + subheap->size)
457 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
461 /***********************************************************************
462 * HEAP_InitSubHeap
464 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
465 DWORD commitSize, DWORD totalSize )
467 SUBHEAP *subheap = (SUBHEAP *)address;
468 WORD selector = 0;
469 FREE_LIST_ENTRY *pEntry;
470 int i;
472 /* Commit memory */
474 if (flags & HEAP_SHARED)
475 commitSize = totalSize; /* always commit everything in a shared heap */
476 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
478 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
479 commitSize, (DWORD)address );
480 return FALSE;
483 /* Allocate a selector if needed */
485 if (flags & HEAP_WINE_SEGPTR)
487 selector = SELECTOR_AllocBlock( address, totalSize,
488 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
489 ? SEGMENT_CODE : SEGMENT_DATA,
490 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
491 if (!selector)
493 ERR("Could not allocate selector\n" );
494 return FALSE;
498 /* Fill the sub-heap structure */
500 subheap->heap = heap;
501 subheap->selector = selector;
502 subheap->size = totalSize;
503 subheap->commitSize = commitSize;
504 subheap->magic = SUBHEAP_MAGIC;
506 if ( subheap != (SUBHEAP *)heap )
508 /* If this is a secondary subheap, insert it into list */
510 subheap->headerSize = sizeof(SUBHEAP);
511 subheap->next = heap->subheap.next;
512 heap->subheap.next = subheap;
514 else
516 /* If this is a primary subheap, initialize main heap */
518 subheap->headerSize = sizeof(HEAP);
519 subheap->next = NULL;
520 heap->next = NULL;
521 heap->flags = flags;
522 heap->magic = HEAP_MAGIC;
524 /* Build the free lists */
526 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
528 pEntry->size = HEAP_freeListSizes[i];
529 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
530 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
531 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
532 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
533 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
534 pEntry->arena.threadId = 0;
535 pEntry->arena.magic = ARENA_FREE_MAGIC;
538 /* Initialize critical section */
540 InitializeCriticalSection( &heap->critSection );
541 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
544 /* Create the first free block */
546 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
547 subheap->size - subheap->headerSize );
549 return TRUE;
552 /***********************************************************************
553 * HEAP_CreateSubHeap
555 * Create a sub-heap of the given size.
556 * If heap == NULL, creates a main heap.
558 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
559 DWORD commitSize, DWORD totalSize )
561 LPVOID address;
563 /* Round-up sizes on a 64K boundary */
565 if (flags & HEAP_WINE_SEGPTR)
567 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
569 else
571 totalSize = (totalSize + 0xffff) & 0xffff0000;
572 commitSize = (commitSize + 0xffff) & 0xffff0000;
573 if (!commitSize) commitSize = 0x10000;
574 if (totalSize < commitSize) totalSize = commitSize;
577 /* Allocate the memory block */
579 if (!(address = VirtualAlloc( NULL, totalSize,
580 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
582 WARN("Could not VirtualAlloc %08lx bytes\n",
583 totalSize );
584 return NULL;
587 /* Initialize subheap */
589 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
590 address, flags, commitSize, totalSize ))
592 VirtualFree( address, 0, MEM_RELEASE );
593 return NULL;
596 return (SUBHEAP *)address;
600 /***********************************************************************
601 * HEAP_FindFreeBlock
603 * Find a free block at least as large as the requested size, and make sure
604 * the requested size is committed.
606 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
607 SUBHEAP **ppSubHeap )
609 SUBHEAP *subheap;
610 ARENA_FREE *pArena;
611 FREE_LIST_ENTRY *pEntry = heap->freeList;
613 /* Find a suitable free list, and in it find a block large enough */
615 while (pEntry->size < size) pEntry++;
616 pArena = pEntry->arena.next;
617 while (pArena != &heap->freeList[0].arena)
619 if (pArena->size > size)
621 subheap = HEAP_FindSubHeap( heap, pArena );
622 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
623 + size + HEAP_MIN_BLOCK_SIZE))
624 return NULL;
625 *ppSubHeap = subheap;
626 return pArena;
629 pArena = pArena->next;
632 /* If no block was found, attempt to grow the heap */
634 if (!(heap->flags & HEAP_GROWABLE))
636 WARN("Not enough space in heap %08lx for %08lx bytes\n",
637 (DWORD)heap, size );
638 return NULL;
640 /* make sure that we have a big enough size *committed* to fit another
641 * last free arena in !
642 * So just one heap struct, one first free arena which will eventually
643 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
644 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
645 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
646 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
647 max( HEAP_DEF_SIZE, size ) )))
648 return NULL;
650 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
651 (DWORD)subheap, size, (DWORD)heap );
653 *ppSubHeap = subheap;
654 return (ARENA_FREE *)(subheap + 1);
658 /***********************************************************************
659 * HEAP_IsValidArenaPtr
661 * Check that the pointer is inside the range possible for arenas.
663 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
665 int i;
666 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
667 if (!subheap) return FALSE;
668 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
669 if (subheap != &heap->subheap) return FALSE;
670 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
671 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
672 return FALSE;
676 /***********************************************************************
677 * HEAP_ValidateFreeArena
679 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
681 char *heapEnd = (char *)subheap + subheap->size;
683 /* Check magic number */
684 if (pArena->magic != ARENA_FREE_MAGIC)
686 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
687 (DWORD)subheap->heap, (DWORD)pArena );
688 return FALSE;
690 /* Check size flags */
691 if (!(pArena->size & ARENA_FLAG_FREE) ||
692 (pArena->size & ARENA_FLAG_PREV_FREE))
694 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
695 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
697 /* Check arena size */
698 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
700 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
701 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
702 return FALSE;
704 /* Check that next pointer is valid */
705 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
707 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
708 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
709 return FALSE;
711 /* Check that next arena is free */
712 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
713 (pArena->next->magic != ARENA_FREE_MAGIC))
715 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
716 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
717 return FALSE;
719 /* Check that prev pointer is valid */
720 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
722 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
723 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
724 return FALSE;
726 /* Check that prev arena is free */
727 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
728 (pArena->prev->magic != ARENA_FREE_MAGIC))
730 /* this often means that the prev arena got overwritten
731 * by a memory write before that prev arena */
732 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
733 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
734 return FALSE;
736 /* Check that next block has PREV_FREE flag */
737 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
739 if (!(*(DWORD *)((char *)(pArena + 1) +
740 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
742 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
743 (DWORD)subheap->heap, (DWORD)pArena );
744 return FALSE;
746 /* Check next block back pointer */
747 if (*((ARENA_FREE **)((char *)(pArena + 1) +
748 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
750 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
751 (DWORD)subheap->heap, (DWORD)pArena,
752 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
753 return FALSE;
756 return TRUE;
760 /***********************************************************************
761 * HEAP_ValidateInUseArena
763 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
765 char *heapEnd = (char *)subheap + subheap->size;
767 /* Check magic number */
768 if (pArena->magic != ARENA_INUSE_MAGIC)
770 if (quiet == NOISY) {
771 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
772 (DWORD)subheap->heap, (DWORD)pArena );
773 if (TRACE_ON(heap))
774 HEAP_Dump( subheap->heap );
775 } else if (WARN_ON(heap)) {
776 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
777 (DWORD)subheap->heap, (DWORD)pArena );
778 if (TRACE_ON(heap))
779 HEAP_Dump( subheap->heap );
781 return FALSE;
783 /* Check size flags */
784 if (pArena->size & ARENA_FLAG_FREE)
786 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
787 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
789 /* Check arena size */
790 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
792 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
793 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
794 return FALSE;
796 /* Check next arena PREV_FREE flag */
797 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
798 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
800 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
801 (DWORD)subheap->heap, (DWORD)pArena );
802 return FALSE;
804 /* Check prev free arena */
805 if (pArena->size & ARENA_FLAG_PREV_FREE)
807 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
808 /* Check prev pointer */
809 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
811 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
812 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
813 return FALSE;
815 /* Check that prev arena is free */
816 if (!(pPrev->size & ARENA_FLAG_FREE) ||
817 (pPrev->magic != ARENA_FREE_MAGIC))
819 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
820 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
821 return FALSE;
823 /* Check that prev arena is really the previous block */
824 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
826 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
827 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
828 return FALSE;
831 return TRUE;
835 /***********************************************************************
836 * HEAP_IsInsideHeap
837 * Checks whether the pointer points to a block inside a given heap.
839 * NOTES
840 * Should this return BOOL32?
842 * RETURNS
843 * !0: Success
844 * 0: Failure
846 int HEAP_IsInsideHeap(
847 HANDLE heap, /* [in] Heap */
848 DWORD flags, /* [in] Flags */
849 LPCVOID ptr /* [in] Pointer */
851 HEAP *heapPtr = HEAP_GetPtr( heap );
852 SUBHEAP *subheap;
853 int ret;
855 /* Validate the parameters */
857 if (!heapPtr) return 0;
858 flags |= heapPtr->flags;
859 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
860 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
861 (((char *)ptr >= (char *)subheap + subheap->headerSize
862 + sizeof(ARENA_INUSE))));
863 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
864 return ret;
868 /***********************************************************************
869 * HEAP_GetSegptr
871 * Transform a linear pointer into a SEGPTR. The pointer must have been
872 * allocated from a HEAP_WINE_SEGPTR heap.
874 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
876 HEAP *heapPtr = HEAP_GetPtr( heap );
877 SUBHEAP *subheap;
878 SEGPTR ret;
880 /* Validate the parameters */
882 if (!heapPtr) return 0;
883 flags |= heapPtr->flags;
884 if (!(flags & HEAP_WINE_SEGPTR))
886 ERR("Heap %08x is not a SEGPTR heap\n",
887 heap );
888 return 0;
890 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
892 /* Get the subheap */
894 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
896 ERR("%p is not inside heap %08x\n",
897 ptr, heap );
898 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
899 return 0;
902 /* Build the SEGPTR */
904 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
905 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
906 return ret;
909 /***********************************************************************
910 * HEAP_IsRealArena [Internal]
911 * Validates a block is a valid arena.
913 * RETURNS
914 * TRUE: Success
915 * FALSE: Failure
917 static BOOL HEAP_IsRealArena(
918 HANDLE heap, /* [in] Handle to the heap */
919 DWORD flags, /* [in] Bit flags that control access during operation */
920 LPCVOID block, /* [in] Optional pointer to memory block to validate */
921 BOOL quiet /* [in] Flag - if true, HEAP_ValidateInUseArena
922 * does not complain */
924 SUBHEAP *subheap;
925 HEAP *heapPtr = (HEAP *)(heap);
926 BOOL ret = TRUE;
928 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
930 ERR("Invalid heap %08x!\n", heap );
931 return FALSE;
934 flags &= HEAP_NO_SERIALIZE;
935 flags |= heapPtr->flags;
936 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
937 if (!(flags & HEAP_NO_SERIALIZE))
938 EnterCriticalSection( &heapPtr->critSection );
940 if (block)
942 /* Only check this single memory block */
944 /* The following code is really HEAP_IsInsideHeap *
945 * with serialization already done. */
946 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
947 ((char *)block < (char *)subheap + subheap->headerSize
948 + sizeof(ARENA_INUSE)))
950 if (quiet == NOISY)
951 ERR("Heap %08lx: block %08lx is not inside heap\n",
952 (DWORD)heap, (DWORD)block );
953 else if (WARN_ON(heap))
954 WARN("Heap %08lx: block %08lx is not inside heap\n",
955 (DWORD)heap, (DWORD)block );
956 ret = FALSE;
957 } else
958 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
960 if (!(flags & HEAP_NO_SERIALIZE))
961 LeaveCriticalSection( &heapPtr->critSection );
962 return ret;
965 subheap = &heapPtr->subheap;
966 while (subheap && ret)
968 char *ptr = (char *)subheap + subheap->headerSize;
969 while (ptr < (char *)subheap + subheap->size)
971 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
973 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
974 ret = FALSE;
975 break;
977 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
979 else
981 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
982 ret = FALSE;
983 break;
985 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
988 subheap = subheap->next;
991 if (!(flags & HEAP_NO_SERIALIZE))
992 LeaveCriticalSection( &heapPtr->critSection );
993 return ret;
997 /***********************************************************************
998 * HeapCreate (KERNEL32.336)
999 * RETURNS
1000 * Handle of heap: Success
1001 * NULL: Failure
1003 HANDLE WINAPI HeapCreate(
1004 DWORD flags, /* [in] Heap allocation flag */
1005 DWORD initialSize, /* [in] Initial heap size */
1006 DWORD maxSize /* [in] Maximum heap size */
1008 SUBHEAP *subheap;
1010 if ( flags & HEAP_SHARED ) {
1011 WARN( "Shared Heap requested, returning system heap.\n" );
1012 return SystemHeap;
1015 /* Allocate the heap block */
1017 if (!maxSize)
1019 maxSize = HEAP_DEF_SIZE;
1020 flags |= HEAP_GROWABLE;
1022 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1024 SetLastError( ERROR_OUTOFMEMORY );
1025 return 0;
1028 /* link it into the per-process heap list */
1029 if (processHeap)
1031 HEAP *heapPtr = subheap->heap;
1032 EnterCriticalSection( &processHeap->critSection );
1033 heapPtr->next = firstHeap;
1034 firstHeap = heapPtr;
1035 LeaveCriticalSection( &processHeap->critSection );
1037 else /* assume the first heap we create is the process main heap */
1039 processHeap = subheap->heap;
1042 return (HANDLE)subheap;
1045 /***********************************************************************
1046 * HeapDestroy (KERNEL32.337)
1047 * RETURNS
1048 * TRUE: Success
1049 * FALSE: Failure
1051 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1053 HEAP *heapPtr = HEAP_GetPtr( heap );
1054 SUBHEAP *subheap;
1056 if ( heap == SystemHeap ) {
1057 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1058 return TRUE;
1061 TRACE("%08x\n", heap );
1062 if (!heapPtr) return FALSE;
1064 if (heapPtr == processHeap) /* cannot delete the main process heap */
1066 SetLastError( ERROR_INVALID_PARAMETER );
1067 return FALSE;
1069 else /* remove it from the per-process list */
1071 HEAP **pptr;
1072 EnterCriticalSection( &processHeap->critSection );
1073 pptr = &firstHeap;
1074 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1075 if (*pptr) *pptr = (*pptr)->next;
1076 LeaveCriticalSection( &processHeap->critSection );
1079 DeleteCriticalSection( &heapPtr->critSection );
1080 subheap = &heapPtr->subheap;
1081 while (subheap)
1083 SUBHEAP *next = subheap->next;
1084 if (subheap->selector) FreeSelector16( subheap->selector );
1085 VirtualFree( subheap, 0, MEM_RELEASE );
1086 subheap = next;
1088 return TRUE;
1092 /***********************************************************************
1093 * HeapAlloc (KERNEL32.334)
1094 * RETURNS
1095 * Pointer to allocated memory block
1096 * NULL: Failure
1098 LPVOID WINAPI HeapAlloc(
1099 HANDLE heap, /* [in] Handle of private heap block */
1100 DWORD flags, /* [in] Heap allocation control flags */
1101 DWORD size /* [in] Number of bytes to allocate */
1103 ARENA_FREE *pArena;
1104 ARENA_INUSE *pInUse;
1105 SUBHEAP *subheap;
1106 HEAP *heapPtr = HEAP_GetPtr( heap );
1108 /* Validate the parameters */
1110 if (!heapPtr) return NULL;
1111 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1112 flags |= heapPtr->flags;
1113 size = (size + 3) & ~3;
1114 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1116 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1117 /* Locate a suitable free block */
1119 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1121 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1122 heap, flags, size );
1123 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1124 SetLastError( ERROR_COMMITMENT_LIMIT );
1125 return NULL;
1128 /* Remove the arena from the free list */
1130 pArena->next->prev = pArena->prev;
1131 pArena->prev->next = pArena->next;
1133 /* Build the in-use arena */
1135 pInUse = (ARENA_INUSE *)pArena;
1137 /* in-use arena is smaller than free arena,
1138 * so we have to add the difference to the size */
1139 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1140 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1141 pInUse->callerEIP = GET_EIP();
1142 pInUse->threadId = GetCurrentTask();
1143 pInUse->magic = ARENA_INUSE_MAGIC;
1145 /* Shrink the block */
1147 HEAP_ShrinkBlock( subheap, pInUse, size );
1149 if (flags & HEAP_ZERO_MEMORY)
1150 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1151 else if (TRACE_ON(heap))
1152 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1154 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1156 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1157 heap, flags, size, (DWORD)(pInUse + 1) );
1158 return (LPVOID)(pInUse + 1);
1162 /***********************************************************************
1163 * HeapFree (KERNEL32.338)
1164 * RETURNS
1165 * TRUE: Success
1166 * FALSE: Failure
1168 BOOL WINAPI HeapFree(
1169 HANDLE heap, /* [in] Handle of heap */
1170 DWORD flags, /* [in] Heap freeing flags */
1171 LPVOID ptr /* [in] Address of memory to free */
1173 ARENA_INUSE *pInUse;
1174 SUBHEAP *subheap;
1175 HEAP *heapPtr = HEAP_GetPtr( heap );
1177 /* Validate the parameters */
1179 if (!heapPtr) return FALSE;
1180 if (!ptr) /* Freeing a NULL ptr is doesn't indicate an error in Win2k */
1182 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1183 heap, flags, (DWORD)ptr );
1184 return TRUE;
1187 flags &= HEAP_NO_SERIALIZE;
1188 flags |= heapPtr->flags;
1189 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1190 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1192 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1193 SetLastError( ERROR_INVALID_PARAMETER );
1194 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1195 heap, flags, (DWORD)ptr );
1196 return FALSE;
1199 /* Turn the block into a free block */
1201 pInUse = (ARENA_INUSE *)ptr - 1;
1202 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1203 HEAP_MakeInUseBlockFree( subheap, pInUse );
1205 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1207 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1208 heap, flags, (DWORD)ptr );
1209 return TRUE;
1213 /***********************************************************************
1214 * HeapReAlloc (KERNEL32.340)
1215 * RETURNS
1216 * Pointer to reallocated memory block
1217 * NULL: Failure
1219 LPVOID WINAPI HeapReAlloc(
1220 HANDLE heap, /* [in] Handle of heap block */
1221 DWORD flags, /* [in] Heap reallocation flags */
1222 LPVOID ptr, /* [in] Address of memory to reallocate */
1223 DWORD size /* [in] Number of bytes to reallocate */
1225 ARENA_INUSE *pArena;
1226 DWORD oldSize;
1227 HEAP *heapPtr;
1228 SUBHEAP *subheap;
1230 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1231 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1233 /* Validate the parameters */
1235 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1236 HEAP_REALLOC_IN_PLACE_ONLY;
1237 flags |= heapPtr->flags;
1238 size = (size + 3) & ~3;
1239 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1241 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1242 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1244 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1245 SetLastError( ERROR_INVALID_PARAMETER );
1246 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1247 heap, flags, (DWORD)ptr, size );
1248 return NULL;
1251 /* Check if we need to grow the block */
1253 pArena = (ARENA_INUSE *)ptr - 1;
1254 pArena->threadId = GetCurrentTask();
1255 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1256 oldSize = (pArena->size & ARENA_SIZE_MASK);
1257 if (size > oldSize)
1259 char *pNext = (char *)(pArena + 1) + oldSize;
1260 if ((pNext < (char *)subheap + subheap->size) &&
1261 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1262 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1264 /* The next block is free and large enough */
1265 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1266 pFree->next->prev = pFree->prev;
1267 pFree->prev->next = pFree->next;
1268 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1269 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1270 + size + HEAP_MIN_BLOCK_SIZE))
1272 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1273 SetLastError( ERROR_OUTOFMEMORY );
1274 return NULL;
1276 HEAP_ShrinkBlock( subheap, pArena, size );
1278 else /* Do it the hard way */
1280 ARENA_FREE *pNew;
1281 ARENA_INUSE *pInUse;
1282 SUBHEAP *newsubheap;
1284 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1285 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1287 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1288 SetLastError( ERROR_OUTOFMEMORY );
1289 return NULL;
1292 /* Build the in-use arena */
1294 pNew->next->prev = pNew->prev;
1295 pNew->prev->next = pNew->next;
1296 pInUse = (ARENA_INUSE *)pNew;
1297 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1298 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1299 pInUse->threadId = GetCurrentTask();
1300 pInUse->magic = ARENA_INUSE_MAGIC;
1301 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1302 memcpy( pInUse + 1, pArena + 1, oldSize );
1304 /* Free the previous block */
1306 HEAP_MakeInUseBlockFree( subheap, pArena );
1307 subheap = newsubheap;
1308 pArena = pInUse;
1311 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1313 /* Clear the extra bytes if needed */
1315 if (size > oldSize)
1317 if (flags & HEAP_ZERO_MEMORY)
1318 memset( (char *)(pArena + 1) + oldSize, 0,
1319 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1320 else if (TRACE_ON(heap))
1321 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1322 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1325 /* Return the new arena */
1327 pArena->callerEIP = GET_EIP();
1328 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1330 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1331 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1332 return (LPVOID)(pArena + 1);
1336 /***********************************************************************
1337 * HeapCompact (KERNEL32.335)
1339 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1341 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1342 return 0;
1346 /***********************************************************************
1347 * HeapLock (KERNEL32.339)
1348 * Attempts to acquire the critical section object for a specified heap.
1350 * RETURNS
1351 * TRUE: Success
1352 * FALSE: Failure
1354 BOOL WINAPI HeapLock(
1355 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1357 HEAP *heapPtr = HEAP_GetPtr( heap );
1358 if (!heapPtr) return FALSE;
1359 EnterCriticalSection( &heapPtr->critSection );
1360 return TRUE;
1364 /***********************************************************************
1365 * HeapUnlock (KERNEL32.342)
1366 * Releases ownership of the critical section object.
1368 * RETURNS
1369 * TRUE: Success
1370 * FALSE: Failure
1372 BOOL WINAPI HeapUnlock(
1373 HANDLE heap /* [in] Handle to the heap to unlock */
1375 HEAP *heapPtr = HEAP_GetPtr( heap );
1376 if (!heapPtr) return FALSE;
1377 LeaveCriticalSection( &heapPtr->critSection );
1378 return TRUE;
1382 /***********************************************************************
1383 * HeapSize (KERNEL32.341)
1384 * RETURNS
1385 * Size in bytes of allocated memory
1386 * 0xffffffff: Failure
1388 DWORD WINAPI HeapSize(
1389 HANDLE heap, /* [in] Handle of heap */
1390 DWORD flags, /* [in] Heap size control flags */
1391 LPVOID ptr /* [in] Address of memory to return size for */
1393 DWORD ret;
1394 HEAP *heapPtr = HEAP_GetPtr( heap );
1396 if (!heapPtr) return FALSE;
1397 flags &= HEAP_NO_SERIALIZE;
1398 flags |= heapPtr->flags;
1399 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1400 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1402 SetLastError( ERROR_INVALID_PARAMETER );
1403 ret = 0xffffffff;
1405 else
1407 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1408 ret = pArena->size & ARENA_SIZE_MASK;
1410 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1412 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1413 heap, flags, (DWORD)ptr, ret );
1414 return ret;
1418 /***********************************************************************
1419 * HeapValidate (KERNEL32.343)
1420 * Validates a specified heap.
1422 * NOTES
1423 * Flags is ignored.
1425 * RETURNS
1426 * TRUE: Success
1427 * FALSE: Failure
1429 BOOL WINAPI HeapValidate(
1430 HANDLE heap, /* [in] Handle to the heap */
1431 DWORD flags, /* [in] Bit flags that control access during operation */
1432 LPCVOID block /* [in] Optional pointer to memory block to validate */
1435 return HEAP_IsRealArena( heap, flags, block, QUIET );
1439 /***********************************************************************
1440 * HeapWalk (KERNEL32.344)
1441 * Enumerates the memory blocks in a specified heap.
1442 * See HEAP_Dump() for info on heap structure.
1444 * TODO
1445 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1446 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1448 * RETURNS
1449 * TRUE: Success
1450 * FALSE: Failure
1452 BOOL WINAPI HeapWalk(
1453 HANDLE heap, /* [in] Handle to heap to enumerate */
1454 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1456 HEAP *heapPtr = HEAP_GetPtr(heap);
1457 SUBHEAP *sub, *currentheap = NULL;
1458 BOOL ret = FALSE;
1459 char *ptr;
1460 int region_index = 0;
1462 if (!heapPtr || !entry)
1464 SetLastError(ERROR_INVALID_PARAMETER);
1465 return FALSE;
1468 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1470 /* set ptr to the next arena to be examined */
1472 if (!entry->lpData) /* first call (init) ? */
1474 TRACE("begin walking of heap 0x%08x.\n", heap);
1475 /*HEAP_Dump(heapPtr);*/
1476 currentheap = &heapPtr->subheap;
1477 ptr = (char*)currentheap + currentheap->headerSize;
1479 else
1481 ptr = entry->lpData;
1482 sub = &heapPtr->subheap;
1483 while (sub)
1485 if (((char *)ptr >= (char *)sub) &&
1486 ((char *)ptr < (char *)sub + sub->size))
1488 currentheap = sub;
1489 break;
1491 sub = sub->next;
1492 region_index++;
1494 if (currentheap == NULL)
1496 ERR("no matching subheap found, shouldn't happen !\n");
1497 SetLastError(ERROR_NO_MORE_ITEMS);
1498 goto HW_end;
1501 ptr += entry->cbData; /* point to next arena */
1502 if (ptr > (char *)currentheap + currentheap->size - 1)
1503 { /* proceed with next subheap */
1504 if (!(currentheap = currentheap->next))
1505 { /* successfully finished */
1506 TRACE("end reached.\n");
1507 SetLastError(ERROR_NO_MORE_ITEMS);
1508 goto HW_end;
1510 ptr = (char*)currentheap + currentheap->headerSize;
1514 entry->wFlags = 0;
1515 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1517 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1519 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1521 entry->lpData = pArena + 1;
1522 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1523 entry->cbOverhead = sizeof(ARENA_FREE);
1524 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1526 else
1528 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1530 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1532 entry->lpData = pArena + 1;
1533 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1534 entry->cbOverhead = sizeof(ARENA_INUSE);
1535 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1536 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1537 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1540 entry->iRegionIndex = region_index;
1542 /* first element of heap ? */
1543 if (ptr == (char *)(currentheap + currentheap->headerSize))
1545 entry->wFlags |= PROCESS_HEAP_REGION;
1546 entry->Foo.Region.dwCommittedSize = currentheap->commitSize;
1547 entry->Foo.Region.dwUnCommittedSize =
1548 currentheap->size - currentheap->commitSize;
1549 entry->Foo.Region.lpFirstBlock = /* first valid block */
1550 currentheap + currentheap->headerSize;
1551 entry->Foo.Region.lpLastBlock = /* first invalid block */
1552 currentheap + currentheap->size;
1554 ret = TRUE;
1556 HW_end:
1557 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1559 return ret;
1563 /***********************************************************************
1564 * HEAP_CreateSystemHeap
1566 * Create the system heap.
1568 BOOL HEAP_CreateSystemHeap(void)
1570 SYSTEM_HEAP_DESCR *descr;
1571 HANDLE heap;
1572 HEAP *heapPtr;
1573 int created;
1575 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1576 0, HEAP_DEF_SIZE, "__SystemHeap" );
1577 if (!map) return FALSE;
1578 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1580 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1582 /* pre-defined address not available, use any one */
1583 fprintf( stderr, "Warning: system heap base address %p not available\n",
1584 SYSTEM_HEAP_BASE );
1585 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1587 CloseHandle( map );
1588 return FALSE;
1591 heap = (HANDLE)heapPtr;
1593 if (created) /* newly created heap */
1595 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1596 HeapLock( heap );
1597 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1598 assert( descr );
1600 else
1602 /* wait for the heap to be initialized */
1603 while (!heapPtr->private) Sleep(1);
1604 HeapLock( heap );
1605 /* remap it to the right address if necessary */
1606 if (heapPtr->subheap.heap != heapPtr)
1608 void *base = heapPtr->subheap.heap;
1609 HeapUnlock( heap );
1610 UnmapViewOfFile( heapPtr );
1611 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1613 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1614 CloseHandle( map );
1615 return FALSE;
1617 heap = (HANDLE)heapPtr;
1618 HeapLock( heap );
1620 descr = heapPtr->private;
1621 assert( descr );
1623 SystemHeap = heap;
1624 SystemHeapDescr = descr;
1625 HeapUnlock( heap );
1626 CloseHandle( map );
1627 return TRUE;
1631 /***********************************************************************
1632 * GetProcessHeap (KERNEL32.259)
1634 HANDLE WINAPI GetProcessHeap(void)
1636 return (HANDLE)processHeap;
1640 /***********************************************************************
1641 * GetProcessHeaps (KERNEL32.376)
1643 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1645 DWORD total;
1646 HEAP *ptr;
1648 if (!processHeap) return 0; /* should never happen */
1649 total = 1; /* main heap */
1650 EnterCriticalSection( &processHeap->critSection );
1651 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1652 if (total <= count)
1654 *heaps++ = (HANDLE)processHeap;
1655 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1657 LeaveCriticalSection( &processHeap->critSection );
1658 return total;
1662 /***********************************************************************
1663 * HEAP_strdupA
1665 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1667 LPSTR p = HeapAlloc( heap, flags, strlen(str) + 1 );
1668 if(p) {
1669 SET_EIP(p);
1670 strcpy( p, str );
1672 return p;
1676 /***********************************************************************
1677 * HEAP_strdupW
1679 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1681 INT len = lstrlenW(str) + 1;
1682 LPWSTR p = HeapAlloc( heap, flags, len * sizeof(WCHAR) );
1683 if(p) {
1684 SET_EIP(p);
1685 strcpyW( p, str );
1687 return p;
1691 /***********************************************************************
1692 * HEAP_strdupAtoW
1694 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1696 LPWSTR ret;
1698 if (!str) return NULL;
1699 ret = HeapAlloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1700 if (ret) {
1701 SET_EIP(ret);
1702 lstrcpyAtoW( ret, str );
1704 return ret;
1708 /***********************************************************************
1709 * HEAP_strdupWtoA
1711 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1713 LPSTR ret;
1714 INT len;
1716 if (!str) return NULL;
1717 len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
1718 ret = HeapAlloc( heap, flags, len );
1719 if(ret) {
1720 SET_EIP(ret);
1721 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
1723 return ret;
1728 /***********************************************************************
1729 * 32-bit local heap functions (Win95; undocumented)
1732 #define HTABLE_SIZE 0x10000
1733 #define HTABLE_PAGESIZE 0x1000
1734 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1736 #include "pshpack1.h"
1737 typedef struct _LOCAL32HEADER
1739 WORD freeListFirst[HTABLE_NPAGES];
1740 WORD freeListSize[HTABLE_NPAGES];
1741 WORD freeListLast[HTABLE_NPAGES];
1743 DWORD selectorTableOffset;
1744 WORD selectorTableSize;
1745 WORD selectorDelta;
1747 DWORD segment;
1748 LPBYTE base;
1750 DWORD limit;
1751 DWORD flags;
1753 DWORD magic;
1754 HANDLE heap;
1756 } LOCAL32HEADER;
1757 #include "poppack.h"
1759 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1761 /***********************************************************************
1762 * Local32Init (KERNEL.208)
1764 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1765 DWORD heapSize, DWORD flags )
1767 DWORD totSize, segSize = 0;
1768 LPBYTE base;
1769 LOCAL32HEADER *header;
1770 HEAP *heap;
1771 WORD *selectorTable;
1772 WORD selectorEven, selectorOdd;
1773 int i, nrBlocks;
1775 /* Determine new heap size */
1777 if ( segment )
1779 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1780 return 0;
1781 else
1782 segSize++;
1785 if ( heapSize == -1L )
1786 heapSize = 1024L*1024L; /* FIXME */
1788 heapSize = (heapSize + 0xffff) & 0xffff0000;
1789 segSize = (segSize + 0x0fff) & 0xfffff000;
1790 totSize = segSize + HTABLE_SIZE + heapSize;
1793 /* Allocate memory and initialize heap */
1795 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1796 return 0;
1798 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1799 MEM_COMMIT, PAGE_READWRITE ) )
1801 VirtualFree( base, 0, MEM_RELEASE );
1802 return 0;
1805 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1806 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1808 VirtualFree( base, 0, MEM_RELEASE );
1809 return 0;
1813 /* Set up header and handle table */
1815 header = (LOCAL32HEADER *)(base + segSize);
1816 header->base = base;
1817 header->limit = HTABLE_PAGESIZE-1;
1818 header->flags = 0;
1819 header->magic = LOCAL32_MAGIC;
1820 header->heap = (HANDLE)heap;
1822 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1823 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1824 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1826 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1827 *(DWORD *)((LPBYTE)header + i) = i+4;
1829 header->freeListFirst[1] = 0xffff;
1832 /* Set up selector table */
1834 nrBlocks = (totSize + 0x7fff) >> 15;
1835 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1836 selectorEven = SELECTOR_AllocBlock( base, totSize,
1837 SEGMENT_DATA, FALSE, FALSE );
1838 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1839 SEGMENT_DATA, FALSE, FALSE );
1841 if ( !selectorTable || !selectorEven || !selectorOdd )
1843 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1844 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1845 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1846 HeapDestroy( header->heap );
1847 VirtualFree( base, 0, MEM_RELEASE );
1848 return 0;
1851 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1852 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1853 header->selectorDelta = selectorEven - selectorOdd;
1854 header->segment = segment? segment : selectorEven;
1856 for (i = 0; i < nrBlocks; i++)
1857 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1858 : selectorEven + ((i >> 1) << __AHSHIFT);
1860 /* Move old segment */
1862 if ( segment )
1864 /* FIXME: This is somewhat ugly and relies on implementation
1865 details about 16-bit global memory handles ... */
1867 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1868 memcpy( base, oldBase, segSize );
1869 GLOBAL_MoveBlock( segment, base, totSize );
1870 HeapFree( SystemHeap, 0, oldBase );
1873 return (HANDLE)header;
1876 /***********************************************************************
1877 * Local32_SearchHandle
1879 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1881 LPDWORD handle;
1883 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1884 handle < (LPDWORD)((LPBYTE)header + header->limit);
1885 handle++)
1887 if (*handle == addr)
1888 return handle;
1891 return NULL;
1894 /***********************************************************************
1895 * Local32_ToHandle
1897 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1898 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1900 *handle = NULL;
1901 *ptr = NULL;
1903 switch (type)
1905 case -2: /* 16:16 pointer, no handles */
1906 *ptr = PTR_SEG_TO_LIN( addr );
1907 *handle = (LPDWORD)*ptr;
1908 break;
1910 case -1: /* 32-bit offset, no handles */
1911 *ptr = header->base + addr;
1912 *handle = (LPDWORD)*ptr;
1913 break;
1915 case 0: /* handle */
1916 if ( addr >= sizeof(LOCAL32HEADER)
1917 && addr < header->limit && !(addr & 3)
1918 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1920 *handle = (LPDWORD)((LPBYTE)header + addr);
1921 *ptr = header->base + **handle;
1923 break;
1925 case 1: /* 16:16 pointer */
1926 *ptr = PTR_SEG_TO_LIN( addr );
1927 *handle = Local32_SearchHandle( header, *ptr - header->base );
1928 break;
1930 case 2: /* 32-bit offset */
1931 *ptr = header->base + addr;
1932 *handle = Local32_SearchHandle( header, *ptr - header->base );
1933 break;
1937 /***********************************************************************
1938 * Local32_FromHandle
1940 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1941 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1943 switch (type)
1945 case -2: /* 16:16 pointer */
1946 case 1:
1948 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1949 DWORD offset = (LPBYTE)ptr - header->base;
1950 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1952 break;
1954 case -1: /* 32-bit offset */
1955 case 2:
1956 *addr = ptr - header->base;
1957 break;
1959 case 0: /* handle */
1960 *addr = (LPBYTE)handle - (LPBYTE)header;
1961 break;
1965 /***********************************************************************
1966 * Local32Alloc (KERNEL.209)
1968 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1970 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1971 LPDWORD handle;
1972 LPBYTE ptr;
1973 DWORD addr;
1975 /* Allocate memory */
1976 ptr = HeapAlloc( header->heap,
1977 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1978 if (!ptr) return 0;
1981 /* Allocate handle if requested */
1982 if (type >= 0)
1984 int page, i;
1986 /* Find first page of handle table with free slots */
1987 for (page = 0; page < HTABLE_NPAGES; page++)
1988 if (header->freeListFirst[page] != 0)
1989 break;
1990 if (page == HTABLE_NPAGES)
1992 WARN("Out of handles!\n" );
1993 HeapFree( header->heap, 0, ptr );
1994 return 0;
1997 /* If virgin page, initialize it */
1998 if (header->freeListFirst[page] == 0xffff)
2000 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
2001 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
2003 WARN("Cannot grow handle table!\n" );
2004 HeapFree( header->heap, 0, ptr );
2005 return 0;
2008 header->limit += HTABLE_PAGESIZE;
2010 header->freeListFirst[page] = 0;
2011 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2012 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2014 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2015 *(DWORD *)((LPBYTE)header + i) = i+4;
2017 if (page < HTABLE_NPAGES-1)
2018 header->freeListFirst[page+1] = 0xffff;
2021 /* Allocate handle slot from page */
2022 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2023 if (--header->freeListSize[page] == 0)
2024 header->freeListFirst[page] = header->freeListLast[page] = 0;
2025 else
2026 header->freeListFirst[page] = *handle;
2028 /* Store 32-bit offset in handle slot */
2029 *handle = ptr - header->base;
2031 else
2033 handle = (LPDWORD)ptr;
2034 header->flags |= 1;
2038 /* Convert handle to requested output type */
2039 Local32_FromHandle( header, type, &addr, handle, ptr );
2040 return addr;
2043 /***********************************************************************
2044 * Local32ReAlloc (KERNEL.210)
2046 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2047 DWORD size, DWORD flags )
2049 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2050 LPDWORD handle;
2051 LPBYTE ptr;
2053 if (!addr)
2054 return Local32Alloc16( heap, size, type, flags );
2056 /* Retrieve handle and pointer */
2057 Local32_ToHandle( header, type, addr, &handle, &ptr );
2058 if (!handle) return FALSE;
2060 /* Reallocate memory block */
2061 ptr = HeapReAlloc( header->heap,
2062 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2063 ptr, size );
2064 if (!ptr) return 0;
2066 /* Modify handle */
2067 if (type >= 0)
2068 *handle = ptr - header->base;
2069 else
2070 handle = (LPDWORD)ptr;
2072 /* Convert handle to requested output type */
2073 Local32_FromHandle( header, type, &addr, handle, ptr );
2074 return addr;
2077 /***********************************************************************
2078 * Local32Free (KERNEL.211)
2080 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2082 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2083 LPDWORD handle;
2084 LPBYTE ptr;
2086 /* Retrieve handle and pointer */
2087 Local32_ToHandle( header, type, addr, &handle, &ptr );
2088 if (!handle) return FALSE;
2090 /* Free handle if necessary */
2091 if (type >= 0)
2093 int offset = (LPBYTE)handle - (LPBYTE)header;
2094 int page = offset >> 12;
2096 /* Return handle slot to page free list */
2097 if (header->freeListSize[page]++ == 0)
2098 header->freeListFirst[page] = header->freeListLast[page] = offset;
2099 else
2100 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2101 header->freeListLast[page] = offset;
2103 *handle = 0;
2105 /* Shrink handle table when possible */
2106 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2108 if ( VirtualFree( (LPBYTE)header +
2109 (header->limit & ~(HTABLE_PAGESIZE-1)),
2110 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2111 break;
2113 header->limit -= HTABLE_PAGESIZE;
2114 header->freeListFirst[page] = 0xffff;
2115 page--;
2119 /* Free memory */
2120 return HeapFree( header->heap, 0, ptr );
2123 /***********************************************************************
2124 * Local32Translate (KERNEL.213)
2126 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2128 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2129 LPDWORD handle;
2130 LPBYTE ptr;
2132 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2133 if (!handle) return 0;
2135 Local32_FromHandle( header, type2, &addr, handle, ptr );
2136 return addr;
2139 /***********************************************************************
2140 * Local32Size (KERNEL.214)
2142 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2144 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2145 LPDWORD handle;
2146 LPBYTE ptr;
2148 Local32_ToHandle( header, type, addr, &handle, &ptr );
2149 if (!handle) return 0;
2151 return HeapSize( header->heap, 0, ptr );
2154 /***********************************************************************
2155 * Local32ValidHandle (KERNEL.215)
2157 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2159 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2160 LPDWORD handle;
2161 LPBYTE ptr;
2163 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2164 return handle != NULL;
2167 /***********************************************************************
2168 * Local32GetSegment (KERNEL.229)
2170 WORD WINAPI Local32GetSegment16( HANDLE heap )
2172 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2173 return header->segment;
2176 /***********************************************************************
2177 * Local32_GetHeap
2179 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2181 WORD selector = GlobalHandleToSel16( handle );
2182 DWORD base = GetSelectorBase( selector );
2183 DWORD limit = GetSelectorLimit16( selector );
2185 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2186 it this way ... */
2188 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2189 return (LOCAL32HEADER *)base;
2191 base += 0x10000;
2192 limit -= 0x10000;
2194 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2195 return (LOCAL32HEADER *)base;
2197 return NULL;
2200 /***********************************************************************
2201 * Local32Info (KERNEL.444) (TOOLHELP.84)
2203 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2205 SUBHEAP *heapPtr;
2206 LPBYTE ptr;
2207 int i;
2209 LOCAL32HEADER *header = Local32_GetHeap( handle );
2210 if ( !header ) return FALSE;
2212 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2213 return FALSE;
2215 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2216 pLocal32Info->dwMemReserved = heapPtr->size;
2217 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2218 pLocal32Info->dwTotalFree = 0L;
2219 pLocal32Info->dwLargestFreeBlock = 0L;
2221 /* Note: Local32 heaps always have only one subheap! */
2222 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2223 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2225 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2227 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2228 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2229 ptr += sizeof(*pArena) + size;
2231 pLocal32Info->dwTotalFree += size;
2232 if ( size > pLocal32Info->dwLargestFreeBlock )
2233 pLocal32Info->dwLargestFreeBlock = size;
2235 else
2237 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2238 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2239 ptr += sizeof(*pArena) + size;
2243 pLocal32Info->dwcFreeHandles = 0;
2244 for ( i = 0; i < HTABLE_NPAGES; i++ )
2246 if ( header->freeListFirst[i] == 0xffff ) break;
2247 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2249 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2251 return TRUE;
2254 /***********************************************************************
2255 * Local32First (KERNEL.445) (TOOLHELP.85)
2257 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2259 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2260 return FALSE;
2263 /***********************************************************************
2264 * Local32Next (KERNEL.446) (TOOLHELP.86)
2266 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2268 FIXME("(%p): stub!\n", pLocal32Entry );
2269 return FALSE;