CompareStringW returned wrong results sometimes.
[wine/testsucceed.git] / memory / heap.c
bloba3e03956de039aefe682f74d48c2e837152d93b2
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 unsigned char selflags = WINE_LDT_FLAGS_DATA;
489 if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
490 selflags = WINE_LDT_FLAGS_CODE;
491 if (flags & HEAP_WINE_CODESEG)
492 selflags |= WINE_LDT_FLAGS_32BIT;
493 selector = SELECTOR_AllocBlock( address, totalSize, selflags );
494 if (!selector)
496 ERR("Could not allocate selector\n" );
497 return FALSE;
501 /* Fill the sub-heap structure */
503 subheap->heap = heap;
504 subheap->selector = selector;
505 subheap->size = totalSize;
506 subheap->commitSize = commitSize;
507 subheap->magic = SUBHEAP_MAGIC;
509 if ( subheap != (SUBHEAP *)heap )
511 /* If this is a secondary subheap, insert it into list */
513 subheap->headerSize = sizeof(SUBHEAP);
514 subheap->next = heap->subheap.next;
515 heap->subheap.next = subheap;
517 else
519 /* If this is a primary subheap, initialize main heap */
521 subheap->headerSize = sizeof(HEAP);
522 subheap->next = NULL;
523 heap->next = NULL;
524 heap->flags = flags;
525 heap->magic = HEAP_MAGIC;
527 /* Build the free lists */
529 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
531 pEntry->size = HEAP_freeListSizes[i];
532 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
533 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
534 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
535 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
536 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
537 pEntry->arena.threadId = 0;
538 pEntry->arena.magic = ARENA_FREE_MAGIC;
541 /* Initialize critical section */
543 InitializeCriticalSection( &heap->critSection );
544 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
547 /* Create the first free block */
549 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
550 subheap->size - subheap->headerSize );
552 return TRUE;
555 /***********************************************************************
556 * HEAP_CreateSubHeap
558 * Create a sub-heap of the given size.
559 * If heap == NULL, creates a main heap.
561 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
562 DWORD commitSize, DWORD totalSize )
564 LPVOID address;
566 /* Round-up sizes on a 64K boundary */
568 if (flags & HEAP_WINE_SEGPTR)
570 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
572 else
574 totalSize = (totalSize + 0xffff) & 0xffff0000;
575 commitSize = (commitSize + 0xffff) & 0xffff0000;
576 if (!commitSize) commitSize = 0x10000;
577 if (totalSize < commitSize) totalSize = commitSize;
580 /* Allocate the memory block */
582 if (!(address = VirtualAlloc( NULL, totalSize,
583 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
585 WARN("Could not VirtualAlloc %08lx bytes\n",
586 totalSize );
587 return NULL;
590 /* Initialize subheap */
592 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
593 address, flags, commitSize, totalSize ))
595 VirtualFree( address, 0, MEM_RELEASE );
596 return NULL;
599 return (SUBHEAP *)address;
603 /***********************************************************************
604 * HEAP_FindFreeBlock
606 * Find a free block at least as large as the requested size, and make sure
607 * the requested size is committed.
609 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
610 SUBHEAP **ppSubHeap )
612 SUBHEAP *subheap;
613 ARENA_FREE *pArena;
614 FREE_LIST_ENTRY *pEntry = heap->freeList;
616 /* Find a suitable free list, and in it find a block large enough */
618 while (pEntry->size < size) pEntry++;
619 pArena = pEntry->arena.next;
620 while (pArena != &heap->freeList[0].arena)
622 if (pArena->size > size)
624 subheap = HEAP_FindSubHeap( heap, pArena );
625 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
626 + size + HEAP_MIN_BLOCK_SIZE))
627 return NULL;
628 *ppSubHeap = subheap;
629 return pArena;
632 pArena = pArena->next;
635 /* If no block was found, attempt to grow the heap */
637 if (!(heap->flags & HEAP_GROWABLE))
639 WARN("Not enough space in heap %08lx for %08lx bytes\n",
640 (DWORD)heap, size );
641 return NULL;
643 /* make sure that we have a big enough size *committed* to fit another
644 * last free arena in !
645 * So just one heap struct, one first free arena which will eventually
646 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
647 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
648 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
649 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
650 max( HEAP_DEF_SIZE, size ) )))
651 return NULL;
653 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
654 (DWORD)subheap, size, (DWORD)heap );
656 *ppSubHeap = subheap;
657 return (ARENA_FREE *)(subheap + 1);
661 /***********************************************************************
662 * HEAP_IsValidArenaPtr
664 * Check that the pointer is inside the range possible for arenas.
666 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
668 int i;
669 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
670 if (!subheap) return FALSE;
671 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
672 if (subheap != &heap->subheap) return FALSE;
673 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
674 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
675 return FALSE;
679 /***********************************************************************
680 * HEAP_ValidateFreeArena
682 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
684 char *heapEnd = (char *)subheap + subheap->size;
686 /* Check magic number */
687 if (pArena->magic != ARENA_FREE_MAGIC)
689 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
690 (DWORD)subheap->heap, (DWORD)pArena );
691 return FALSE;
693 /* Check size flags */
694 if (!(pArena->size & ARENA_FLAG_FREE) ||
695 (pArena->size & ARENA_FLAG_PREV_FREE))
697 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
698 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
700 /* Check arena size */
701 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
703 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
704 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
705 return FALSE;
707 /* Check that next pointer is valid */
708 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
710 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
711 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
712 return FALSE;
714 /* Check that next arena is free */
715 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
716 (pArena->next->magic != ARENA_FREE_MAGIC))
718 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
719 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
720 return FALSE;
722 /* Check that prev pointer is valid */
723 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
725 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
726 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
727 return FALSE;
729 /* Check that prev arena is free */
730 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
731 (pArena->prev->magic != ARENA_FREE_MAGIC))
733 /* this often means that the prev arena got overwritten
734 * by a memory write before that prev arena */
735 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
736 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
737 return FALSE;
739 /* Check that next block has PREV_FREE flag */
740 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
742 if (!(*(DWORD *)((char *)(pArena + 1) +
743 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
745 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
746 (DWORD)subheap->heap, (DWORD)pArena );
747 return FALSE;
749 /* Check next block back pointer */
750 if (*((ARENA_FREE **)((char *)(pArena + 1) +
751 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
753 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
754 (DWORD)subheap->heap, (DWORD)pArena,
755 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
756 return FALSE;
759 return TRUE;
763 /***********************************************************************
764 * HEAP_ValidateInUseArena
766 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
768 char *heapEnd = (char *)subheap + subheap->size;
770 /* Check magic number */
771 if (pArena->magic != ARENA_INUSE_MAGIC)
773 if (quiet == NOISY) {
774 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
775 (DWORD)subheap->heap, (DWORD)pArena );
776 if (TRACE_ON(heap))
777 HEAP_Dump( subheap->heap );
778 } else if (WARN_ON(heap)) {
779 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
780 (DWORD)subheap->heap, (DWORD)pArena );
781 if (TRACE_ON(heap))
782 HEAP_Dump( subheap->heap );
784 return FALSE;
786 /* Check size flags */
787 if (pArena->size & ARENA_FLAG_FREE)
789 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
790 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
792 /* Check arena size */
793 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
795 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
796 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
797 return FALSE;
799 /* Check next arena PREV_FREE flag */
800 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
801 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
803 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
804 (DWORD)subheap->heap, (DWORD)pArena );
805 return FALSE;
807 /* Check prev free arena */
808 if (pArena->size & ARENA_FLAG_PREV_FREE)
810 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
811 /* Check prev pointer */
812 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
814 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
815 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
816 return FALSE;
818 /* Check that prev arena is free */
819 if (!(pPrev->size & ARENA_FLAG_FREE) ||
820 (pPrev->magic != ARENA_FREE_MAGIC))
822 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
823 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
824 return FALSE;
826 /* Check that prev arena is really the previous block */
827 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
829 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
830 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
831 return FALSE;
834 return TRUE;
838 /***********************************************************************
839 * HEAP_IsInsideHeap
840 * Checks whether the pointer points to a block inside a given heap.
842 * NOTES
843 * Should this return BOOL32?
845 * RETURNS
846 * !0: Success
847 * 0: Failure
849 int HEAP_IsInsideHeap(
850 HANDLE heap, /* [in] Heap */
851 DWORD flags, /* [in] Flags */
852 LPCVOID ptr /* [in] Pointer */
854 HEAP *heapPtr = HEAP_GetPtr( heap );
855 SUBHEAP *subheap;
856 int ret;
858 /* Validate the parameters */
860 if (!heapPtr) return 0;
861 flags |= heapPtr->flags;
862 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
863 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
864 (((char *)ptr >= (char *)subheap + subheap->headerSize
865 + sizeof(ARENA_INUSE))));
866 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
867 return ret;
871 /***********************************************************************
872 * HEAP_GetSegptr
874 * Transform a linear pointer into a SEGPTR. The pointer must have been
875 * allocated from a HEAP_WINE_SEGPTR heap.
877 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
879 HEAP *heapPtr = HEAP_GetPtr( heap );
880 SUBHEAP *subheap;
881 SEGPTR ret;
883 /* Validate the parameters */
885 if (!heapPtr) return 0;
886 flags |= heapPtr->flags;
887 if (!(flags & HEAP_WINE_SEGPTR))
889 ERR("Heap %08x is not a SEGPTR heap\n",
890 heap );
891 return 0;
893 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
895 /* Get the subheap */
897 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
899 ERR("%p is not inside heap %08x\n",
900 ptr, heap );
901 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
902 return 0;
905 /* Build the SEGPTR */
907 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
908 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
909 return ret;
912 /***********************************************************************
913 * HEAP_IsRealArena [Internal]
914 * Validates a block is a valid arena.
916 * RETURNS
917 * TRUE: Success
918 * FALSE: Failure
920 static BOOL HEAP_IsRealArena(
921 HANDLE heap, /* [in] Handle to the heap */
922 DWORD flags, /* [in] Bit flags that control access during operation */
923 LPCVOID block, /* [in] Optional pointer to memory block to validate */
924 BOOL quiet /* [in] Flag - if true, HEAP_ValidateInUseArena
925 * does not complain */
927 SUBHEAP *subheap;
928 HEAP *heapPtr = (HEAP *)(heap);
929 BOOL ret = TRUE;
931 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
933 ERR("Invalid heap %08x!\n", heap );
934 return FALSE;
937 flags &= HEAP_NO_SERIALIZE;
938 flags |= heapPtr->flags;
939 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
940 if (!(flags & HEAP_NO_SERIALIZE))
941 EnterCriticalSection( &heapPtr->critSection );
943 if (block)
945 /* Only check this single memory block */
947 /* The following code is really HEAP_IsInsideHeap *
948 * with serialization already done. */
949 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
950 ((char *)block < (char *)subheap + subheap->headerSize
951 + sizeof(ARENA_INUSE)))
953 if (quiet == NOISY)
954 ERR("Heap %08lx: block %08lx is not inside heap\n",
955 (DWORD)heap, (DWORD)block );
956 else if (WARN_ON(heap))
957 WARN("Heap %08lx: block %08lx is not inside heap\n",
958 (DWORD)heap, (DWORD)block );
959 ret = FALSE;
960 } else
961 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
963 if (!(flags & HEAP_NO_SERIALIZE))
964 LeaveCriticalSection( &heapPtr->critSection );
965 return ret;
968 subheap = &heapPtr->subheap;
969 while (subheap && ret)
971 char *ptr = (char *)subheap + subheap->headerSize;
972 while (ptr < (char *)subheap + subheap->size)
974 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
976 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
977 ret = FALSE;
978 break;
980 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
982 else
984 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
985 ret = FALSE;
986 break;
988 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
991 subheap = subheap->next;
994 if (!(flags & HEAP_NO_SERIALIZE))
995 LeaveCriticalSection( &heapPtr->critSection );
996 return ret;
1000 /***********************************************************************
1001 * HeapCreate (KERNEL32.336)
1002 * RETURNS
1003 * Handle of heap: Success
1004 * NULL: Failure
1006 HANDLE WINAPI HeapCreate(
1007 DWORD flags, /* [in] Heap allocation flag */
1008 DWORD initialSize, /* [in] Initial heap size */
1009 DWORD maxSize /* [in] Maximum heap size */
1011 SUBHEAP *subheap;
1013 if ( flags & HEAP_SHARED ) {
1014 WARN( "Shared Heap requested, returning system heap.\n" );
1015 return SystemHeap;
1018 /* Allocate the heap block */
1020 if (!maxSize)
1022 maxSize = HEAP_DEF_SIZE;
1023 flags |= HEAP_GROWABLE;
1025 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1027 SetLastError( ERROR_OUTOFMEMORY );
1028 return 0;
1031 /* link it into the per-process heap list */
1032 if (processHeap)
1034 HEAP *heapPtr = subheap->heap;
1035 EnterCriticalSection( &processHeap->critSection );
1036 heapPtr->next = firstHeap;
1037 firstHeap = heapPtr;
1038 LeaveCriticalSection( &processHeap->critSection );
1040 else /* assume the first heap we create is the process main heap */
1042 processHeap = subheap->heap;
1045 return (HANDLE)subheap;
1048 /***********************************************************************
1049 * HeapDestroy (KERNEL32.337)
1050 * RETURNS
1051 * TRUE: Success
1052 * FALSE: Failure
1054 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1056 HEAP *heapPtr = HEAP_GetPtr( heap );
1057 SUBHEAP *subheap;
1059 if ( heap == SystemHeap ) {
1060 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1061 return TRUE;
1064 TRACE("%08x\n", heap );
1065 if (!heapPtr) return FALSE;
1067 if (heapPtr == processHeap) /* cannot delete the main process heap */
1069 SetLastError( ERROR_INVALID_PARAMETER );
1070 return FALSE;
1072 else /* remove it from the per-process list */
1074 HEAP **pptr;
1075 EnterCriticalSection( &processHeap->critSection );
1076 pptr = &firstHeap;
1077 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1078 if (*pptr) *pptr = (*pptr)->next;
1079 LeaveCriticalSection( &processHeap->critSection );
1082 DeleteCriticalSection( &heapPtr->critSection );
1083 subheap = &heapPtr->subheap;
1084 while (subheap)
1086 SUBHEAP *next = subheap->next;
1087 if (subheap->selector) FreeSelector16( subheap->selector );
1088 VirtualFree( subheap, 0, MEM_RELEASE );
1089 subheap = next;
1091 return TRUE;
1095 /***********************************************************************
1096 * HeapAlloc (KERNEL32.334)
1097 * RETURNS
1098 * Pointer to allocated memory block
1099 * NULL: Failure
1101 LPVOID WINAPI HeapAlloc(
1102 HANDLE heap, /* [in] Handle of private heap block */
1103 DWORD flags, /* [in] Heap allocation control flags */
1104 DWORD size /* [in] Number of bytes to allocate */
1106 ARENA_FREE *pArena;
1107 ARENA_INUSE *pInUse;
1108 SUBHEAP *subheap;
1109 HEAP *heapPtr = HEAP_GetPtr( heap );
1111 /* Validate the parameters */
1113 if (!heapPtr) return NULL;
1114 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1115 flags |= heapPtr->flags;
1116 size = (size + 3) & ~3;
1117 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1119 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1120 /* Locate a suitable free block */
1122 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1124 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1125 heap, flags, size );
1126 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1127 SetLastError( ERROR_COMMITMENT_LIMIT );
1128 return NULL;
1131 /* Remove the arena from the free list */
1133 pArena->next->prev = pArena->prev;
1134 pArena->prev->next = pArena->next;
1136 /* Build the in-use arena */
1138 pInUse = (ARENA_INUSE *)pArena;
1140 /* in-use arena is smaller than free arena,
1141 * so we have to add the difference to the size */
1142 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1143 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1144 pInUse->callerEIP = GET_EIP();
1145 pInUse->threadId = GetCurrentTask();
1146 pInUse->magic = ARENA_INUSE_MAGIC;
1148 /* Shrink the block */
1150 HEAP_ShrinkBlock( subheap, pInUse, size );
1152 if (flags & HEAP_ZERO_MEMORY)
1153 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1154 else if (TRACE_ON(heap))
1155 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1157 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1159 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1160 heap, flags, size, (DWORD)(pInUse + 1) );
1161 return (LPVOID)(pInUse + 1);
1165 /***********************************************************************
1166 * HeapFree (KERNEL32.338)
1167 * RETURNS
1168 * TRUE: Success
1169 * FALSE: Failure
1171 BOOL WINAPI HeapFree(
1172 HANDLE heap, /* [in] Handle of heap */
1173 DWORD flags, /* [in] Heap freeing flags */
1174 LPVOID ptr /* [in] Address of memory to free */
1176 ARENA_INUSE *pInUse;
1177 SUBHEAP *subheap;
1178 HEAP *heapPtr = HEAP_GetPtr( heap );
1180 /* Validate the parameters */
1182 if (!heapPtr) return FALSE;
1183 if (!ptr) /* Freeing a NULL ptr is doesn't indicate an error in Win2k */
1185 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1186 heap, flags, (DWORD)ptr );
1187 return TRUE;
1190 flags &= HEAP_NO_SERIALIZE;
1191 flags |= heapPtr->flags;
1192 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1193 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1195 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1196 SetLastError( ERROR_INVALID_PARAMETER );
1197 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1198 heap, flags, (DWORD)ptr );
1199 return FALSE;
1202 /* Turn the block into a free block */
1204 pInUse = (ARENA_INUSE *)ptr - 1;
1205 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1206 HEAP_MakeInUseBlockFree( subheap, pInUse );
1208 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1210 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1211 heap, flags, (DWORD)ptr );
1212 return TRUE;
1216 /***********************************************************************
1217 * HeapReAlloc (KERNEL32.340)
1218 * RETURNS
1219 * Pointer to reallocated memory block
1220 * NULL: Failure
1222 LPVOID WINAPI HeapReAlloc(
1223 HANDLE heap, /* [in] Handle of heap block */
1224 DWORD flags, /* [in] Heap reallocation flags */
1225 LPVOID ptr, /* [in] Address of memory to reallocate */
1226 DWORD size /* [in] Number of bytes to reallocate */
1228 ARENA_INUSE *pArena;
1229 DWORD oldSize;
1230 HEAP *heapPtr;
1231 SUBHEAP *subheap;
1233 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1234 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1236 /* Validate the parameters */
1238 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1239 HEAP_REALLOC_IN_PLACE_ONLY;
1240 flags |= heapPtr->flags;
1241 size = (size + 3) & ~3;
1242 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1244 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1245 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1247 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1248 SetLastError( ERROR_INVALID_PARAMETER );
1249 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1250 heap, flags, (DWORD)ptr, size );
1251 return NULL;
1254 /* Check if we need to grow the block */
1256 pArena = (ARENA_INUSE *)ptr - 1;
1257 pArena->threadId = GetCurrentTask();
1258 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1259 oldSize = (pArena->size & ARENA_SIZE_MASK);
1260 if (size > oldSize)
1262 char *pNext = (char *)(pArena + 1) + oldSize;
1263 if ((pNext < (char *)subheap + subheap->size) &&
1264 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1265 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1267 /* The next block is free and large enough */
1268 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1269 pFree->next->prev = pFree->prev;
1270 pFree->prev->next = pFree->next;
1271 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1272 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1273 + size + HEAP_MIN_BLOCK_SIZE))
1275 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1276 SetLastError( ERROR_OUTOFMEMORY );
1277 return NULL;
1279 HEAP_ShrinkBlock( subheap, pArena, size );
1281 else /* Do it the hard way */
1283 ARENA_FREE *pNew;
1284 ARENA_INUSE *pInUse;
1285 SUBHEAP *newsubheap;
1287 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1288 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1290 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1291 SetLastError( ERROR_OUTOFMEMORY );
1292 return NULL;
1295 /* Build the in-use arena */
1297 pNew->next->prev = pNew->prev;
1298 pNew->prev->next = pNew->next;
1299 pInUse = (ARENA_INUSE *)pNew;
1300 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1301 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1302 pInUse->threadId = GetCurrentTask();
1303 pInUse->magic = ARENA_INUSE_MAGIC;
1304 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1305 memcpy( pInUse + 1, pArena + 1, oldSize );
1307 /* Free the previous block */
1309 HEAP_MakeInUseBlockFree( subheap, pArena );
1310 subheap = newsubheap;
1311 pArena = pInUse;
1314 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1316 /* Clear the extra bytes if needed */
1318 if (size > oldSize)
1320 if (flags & HEAP_ZERO_MEMORY)
1321 memset( (char *)(pArena + 1) + oldSize, 0,
1322 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1323 else if (TRACE_ON(heap))
1324 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1325 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1328 /* Return the new arena */
1330 pArena->callerEIP = GET_EIP();
1331 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1333 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1334 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1335 return (LPVOID)(pArena + 1);
1339 /***********************************************************************
1340 * HeapCompact (KERNEL32.335)
1342 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1344 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1345 return 0;
1349 /***********************************************************************
1350 * HeapLock (KERNEL32.339)
1351 * Attempts to acquire the critical section object for a specified heap.
1353 * RETURNS
1354 * TRUE: Success
1355 * FALSE: Failure
1357 BOOL WINAPI HeapLock(
1358 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1360 HEAP *heapPtr = HEAP_GetPtr( heap );
1361 if (!heapPtr) return FALSE;
1362 EnterCriticalSection( &heapPtr->critSection );
1363 return TRUE;
1367 /***********************************************************************
1368 * HeapUnlock (KERNEL32.342)
1369 * Releases ownership of the critical section object.
1371 * RETURNS
1372 * TRUE: Success
1373 * FALSE: Failure
1375 BOOL WINAPI HeapUnlock(
1376 HANDLE heap /* [in] Handle to the heap to unlock */
1378 HEAP *heapPtr = HEAP_GetPtr( heap );
1379 if (!heapPtr) return FALSE;
1380 LeaveCriticalSection( &heapPtr->critSection );
1381 return TRUE;
1385 /***********************************************************************
1386 * HeapSize (KERNEL32.341)
1387 * RETURNS
1388 * Size in bytes of allocated memory
1389 * 0xffffffff: Failure
1391 DWORD WINAPI HeapSize(
1392 HANDLE heap, /* [in] Handle of heap */
1393 DWORD flags, /* [in] Heap size control flags */
1394 LPVOID ptr /* [in] Address of memory to return size for */
1396 DWORD ret;
1397 HEAP *heapPtr = HEAP_GetPtr( heap );
1399 if (!heapPtr) return FALSE;
1400 flags &= HEAP_NO_SERIALIZE;
1401 flags |= heapPtr->flags;
1402 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1403 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1405 SetLastError( ERROR_INVALID_PARAMETER );
1406 ret = 0xffffffff;
1408 else
1410 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1411 ret = pArena->size & ARENA_SIZE_MASK;
1413 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1415 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1416 heap, flags, (DWORD)ptr, ret );
1417 return ret;
1421 /***********************************************************************
1422 * HeapValidate (KERNEL32.343)
1423 * Validates a specified heap.
1425 * NOTES
1426 * Flags is ignored.
1428 * RETURNS
1429 * TRUE: Success
1430 * FALSE: Failure
1432 BOOL WINAPI HeapValidate(
1433 HANDLE heap, /* [in] Handle to the heap */
1434 DWORD flags, /* [in] Bit flags that control access during operation */
1435 LPCVOID block /* [in] Optional pointer to memory block to validate */
1438 return HEAP_IsRealArena( heap, flags, block, QUIET );
1442 /***********************************************************************
1443 * HeapWalk (KERNEL32.344)
1444 * Enumerates the memory blocks in a specified heap.
1445 * See HEAP_Dump() for info on heap structure.
1447 * TODO
1448 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1449 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1451 * RETURNS
1452 * TRUE: Success
1453 * FALSE: Failure
1455 BOOL WINAPI HeapWalk(
1456 HANDLE heap, /* [in] Handle to heap to enumerate */
1457 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1459 HEAP *heapPtr = HEAP_GetPtr(heap);
1460 SUBHEAP *sub, *currentheap = NULL;
1461 BOOL ret = FALSE;
1462 char *ptr;
1463 int region_index = 0;
1465 if (!heapPtr || !entry)
1467 SetLastError(ERROR_INVALID_PARAMETER);
1468 return FALSE;
1471 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1473 /* set ptr to the next arena to be examined */
1475 if (!entry->lpData) /* first call (init) ? */
1477 TRACE("begin walking of heap 0x%08x.\n", heap);
1478 /*HEAP_Dump(heapPtr);*/
1479 currentheap = &heapPtr->subheap;
1480 ptr = (char*)currentheap + currentheap->headerSize;
1482 else
1484 ptr = entry->lpData;
1485 sub = &heapPtr->subheap;
1486 while (sub)
1488 if (((char *)ptr >= (char *)sub) &&
1489 ((char *)ptr < (char *)sub + sub->size))
1491 currentheap = sub;
1492 break;
1494 sub = sub->next;
1495 region_index++;
1497 if (currentheap == NULL)
1499 ERR("no matching subheap found, shouldn't happen !\n");
1500 SetLastError(ERROR_NO_MORE_ITEMS);
1501 goto HW_end;
1504 ptr += entry->cbData; /* point to next arena */
1505 if (ptr > (char *)currentheap + currentheap->size - 1)
1506 { /* proceed with next subheap */
1507 if (!(currentheap = currentheap->next))
1508 { /* successfully finished */
1509 TRACE("end reached.\n");
1510 SetLastError(ERROR_NO_MORE_ITEMS);
1511 goto HW_end;
1513 ptr = (char*)currentheap + currentheap->headerSize;
1517 entry->wFlags = 0;
1518 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1520 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1522 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1524 entry->lpData = pArena + 1;
1525 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1526 entry->cbOverhead = sizeof(ARENA_FREE);
1527 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1529 else
1531 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1533 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1535 entry->lpData = pArena + 1;
1536 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1537 entry->cbOverhead = sizeof(ARENA_INUSE);
1538 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1539 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1540 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1543 entry->iRegionIndex = region_index;
1545 /* first element of heap ? */
1546 if (ptr == (char *)(currentheap + currentheap->headerSize))
1548 entry->wFlags |= PROCESS_HEAP_REGION;
1549 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1550 entry->u.Region.dwUnCommittedSize =
1551 currentheap->size - currentheap->commitSize;
1552 entry->u.Region.lpFirstBlock = /* first valid block */
1553 currentheap + currentheap->headerSize;
1554 entry->u.Region.lpLastBlock = /* first invalid block */
1555 currentheap + currentheap->size;
1557 ret = TRUE;
1559 HW_end:
1560 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1562 return ret;
1566 /***********************************************************************
1567 * HEAP_CreateSystemHeap
1569 * Create the system heap.
1571 BOOL HEAP_CreateSystemHeap(void)
1573 SYSTEM_HEAP_DESCR *descr;
1574 HANDLE heap;
1575 HEAP *heapPtr;
1576 int created;
1578 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1579 0, HEAP_DEF_SIZE, "__SystemHeap" );
1580 if (!map) return FALSE;
1581 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1583 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1585 /* pre-defined address not available, use any one */
1586 fprintf( stderr, "Warning: system heap base address %p not available\n",
1587 SYSTEM_HEAP_BASE );
1588 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1590 CloseHandle( map );
1591 return FALSE;
1594 heap = (HANDLE)heapPtr;
1596 if (created) /* newly created heap */
1598 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1599 HeapLock( heap );
1600 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1601 assert( descr );
1603 else
1605 /* wait for the heap to be initialized */
1606 while (!heapPtr->private) Sleep(1);
1607 HeapLock( heap );
1608 /* remap it to the right address if necessary */
1609 if (heapPtr->subheap.heap != heapPtr)
1611 void *base = heapPtr->subheap.heap;
1612 HeapUnlock( heap );
1613 UnmapViewOfFile( heapPtr );
1614 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1616 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1617 CloseHandle( map );
1618 return FALSE;
1620 heap = (HANDLE)heapPtr;
1621 HeapLock( heap );
1623 descr = heapPtr->private;
1624 assert( descr );
1626 SystemHeap = heap;
1627 SystemHeapDescr = descr;
1628 HeapUnlock( heap );
1629 CloseHandle( map );
1630 return TRUE;
1634 /***********************************************************************
1635 * GetProcessHeap (KERNEL32.259)
1637 HANDLE WINAPI GetProcessHeap(void)
1639 return (HANDLE)processHeap;
1643 /***********************************************************************
1644 * GetProcessHeaps (KERNEL32.376)
1646 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1648 DWORD total;
1649 HEAP *ptr;
1651 if (!processHeap) return 0; /* should never happen */
1652 total = 1; /* main heap */
1653 EnterCriticalSection( &processHeap->critSection );
1654 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1655 if (total <= count)
1657 *heaps++ = (HANDLE)processHeap;
1658 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1660 LeaveCriticalSection( &processHeap->critSection );
1661 return total;
1665 /***********************************************************************
1666 * HEAP_strdupA
1668 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1670 LPSTR p = HeapAlloc( heap, flags, strlen(str) + 1 );
1671 if(p) {
1672 SET_EIP(p);
1673 strcpy( p, str );
1675 return p;
1679 /***********************************************************************
1680 * HEAP_strdupW
1682 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1684 INT len = strlenW(str) + 1;
1685 LPWSTR p = HeapAlloc( heap, flags, len * sizeof(WCHAR) );
1686 if(p) {
1687 SET_EIP(p);
1688 strcpyW( p, str );
1690 return p;
1694 /***********************************************************************
1695 * HEAP_strdupAtoW
1697 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1699 LPWSTR ret;
1700 INT len;
1702 if (!str) return NULL;
1703 len = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
1704 ret = HeapAlloc( heap, flags, len * sizeof(WCHAR) );
1705 if (ret) {
1706 SET_EIP(ret);
1707 MultiByteToWideChar( CP_ACP, 0, str, -1, ret, len );
1709 return ret;
1713 /***********************************************************************
1714 * HEAP_strdupWtoA
1716 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1718 LPSTR ret;
1719 INT len;
1721 if (!str) return NULL;
1722 len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
1723 ret = HeapAlloc( heap, flags, len );
1724 if(ret) {
1725 SET_EIP(ret);
1726 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
1728 return ret;
1733 /***********************************************************************
1734 * 32-bit local heap functions (Win95; undocumented)
1737 #define HTABLE_SIZE 0x10000
1738 #define HTABLE_PAGESIZE 0x1000
1739 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1741 #include "pshpack1.h"
1742 typedef struct _LOCAL32HEADER
1744 WORD freeListFirst[HTABLE_NPAGES];
1745 WORD freeListSize[HTABLE_NPAGES];
1746 WORD freeListLast[HTABLE_NPAGES];
1748 DWORD selectorTableOffset;
1749 WORD selectorTableSize;
1750 WORD selectorDelta;
1752 DWORD segment;
1753 LPBYTE base;
1755 DWORD limit;
1756 DWORD flags;
1758 DWORD magic;
1759 HANDLE heap;
1761 } LOCAL32HEADER;
1762 #include "poppack.h"
1764 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1766 /***********************************************************************
1767 * Local32Init (KERNEL.208)
1769 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1770 DWORD heapSize, DWORD flags )
1772 DWORD totSize, segSize = 0;
1773 LPBYTE base;
1774 LOCAL32HEADER *header;
1775 HEAP *heap;
1776 WORD *selectorTable;
1777 WORD selectorEven, selectorOdd;
1778 int i, nrBlocks;
1780 /* Determine new heap size */
1782 if ( segment )
1784 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1785 return 0;
1786 else
1787 segSize++;
1790 if ( heapSize == -1L )
1791 heapSize = 1024L*1024L; /* FIXME */
1793 heapSize = (heapSize + 0xffff) & 0xffff0000;
1794 segSize = (segSize + 0x0fff) & 0xfffff000;
1795 totSize = segSize + HTABLE_SIZE + heapSize;
1798 /* Allocate memory and initialize heap */
1800 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1801 return 0;
1803 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1804 MEM_COMMIT, PAGE_READWRITE ) )
1806 VirtualFree( base, 0, MEM_RELEASE );
1807 return 0;
1810 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1811 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1813 VirtualFree( base, 0, MEM_RELEASE );
1814 return 0;
1818 /* Set up header and handle table */
1820 header = (LOCAL32HEADER *)(base + segSize);
1821 header->base = base;
1822 header->limit = HTABLE_PAGESIZE-1;
1823 header->flags = 0;
1824 header->magic = LOCAL32_MAGIC;
1825 header->heap = (HANDLE)heap;
1827 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1828 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1829 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1831 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1832 *(DWORD *)((LPBYTE)header + i) = i+4;
1834 header->freeListFirst[1] = 0xffff;
1837 /* Set up selector table */
1839 nrBlocks = (totSize + 0x7fff) >> 15;
1840 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1841 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1842 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1843 if ( !selectorTable || !selectorEven || !selectorOdd )
1845 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1846 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1847 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1848 HeapDestroy( header->heap );
1849 VirtualFree( base, 0, MEM_RELEASE );
1850 return 0;
1853 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1854 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1855 header->selectorDelta = selectorEven - selectorOdd;
1856 header->segment = segment? segment : selectorEven;
1858 for (i = 0; i < nrBlocks; i++)
1859 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1860 : selectorEven + ((i >> 1) << __AHSHIFT);
1862 /* Move old segment */
1864 if ( segment )
1866 /* FIXME: This is somewhat ugly and relies on implementation
1867 details about 16-bit global memory handles ... */
1869 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1870 memcpy( base, oldBase, segSize );
1871 GLOBAL_MoveBlock( segment, base, totSize );
1872 HeapFree( SystemHeap, 0, oldBase );
1875 return (HANDLE)header;
1878 /***********************************************************************
1879 * Local32_SearchHandle
1881 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1883 LPDWORD handle;
1885 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1886 handle < (LPDWORD)((LPBYTE)header + header->limit);
1887 handle++)
1889 if (*handle == addr)
1890 return handle;
1893 return NULL;
1896 /***********************************************************************
1897 * Local32_ToHandle
1899 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1900 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1902 *handle = NULL;
1903 *ptr = NULL;
1905 switch (type)
1907 case -2: /* 16:16 pointer, no handles */
1908 *ptr = PTR_SEG_TO_LIN( addr );
1909 *handle = (LPDWORD)*ptr;
1910 break;
1912 case -1: /* 32-bit offset, no handles */
1913 *ptr = header->base + addr;
1914 *handle = (LPDWORD)*ptr;
1915 break;
1917 case 0: /* handle */
1918 if ( addr >= sizeof(LOCAL32HEADER)
1919 && addr < header->limit && !(addr & 3)
1920 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1922 *handle = (LPDWORD)((LPBYTE)header + addr);
1923 *ptr = header->base + **handle;
1925 break;
1927 case 1: /* 16:16 pointer */
1928 *ptr = PTR_SEG_TO_LIN( addr );
1929 *handle = Local32_SearchHandle( header, *ptr - header->base );
1930 break;
1932 case 2: /* 32-bit offset */
1933 *ptr = header->base + addr;
1934 *handle = Local32_SearchHandle( header, *ptr - header->base );
1935 break;
1939 /***********************************************************************
1940 * Local32_FromHandle
1942 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1943 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1945 switch (type)
1947 case -2: /* 16:16 pointer */
1948 case 1:
1950 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1951 DWORD offset = (LPBYTE)ptr - header->base;
1952 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1954 break;
1956 case -1: /* 32-bit offset */
1957 case 2:
1958 *addr = ptr - header->base;
1959 break;
1961 case 0: /* handle */
1962 *addr = (LPBYTE)handle - (LPBYTE)header;
1963 break;
1967 /***********************************************************************
1968 * Local32Alloc (KERNEL.209)
1970 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1972 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1973 LPDWORD handle;
1974 LPBYTE ptr;
1975 DWORD addr;
1977 /* Allocate memory */
1978 ptr = HeapAlloc( header->heap,
1979 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1980 if (!ptr) return 0;
1983 /* Allocate handle if requested */
1984 if (type >= 0)
1986 int page, i;
1988 /* Find first page of handle table with free slots */
1989 for (page = 0; page < HTABLE_NPAGES; page++)
1990 if (header->freeListFirst[page] != 0)
1991 break;
1992 if (page == HTABLE_NPAGES)
1994 WARN("Out of handles!\n" );
1995 HeapFree( header->heap, 0, ptr );
1996 return 0;
1999 /* If virgin page, initialize it */
2000 if (header->freeListFirst[page] == 0xffff)
2002 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
2003 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
2005 WARN("Cannot grow handle table!\n" );
2006 HeapFree( header->heap, 0, ptr );
2007 return 0;
2010 header->limit += HTABLE_PAGESIZE;
2012 header->freeListFirst[page] = 0;
2013 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2014 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2016 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2017 *(DWORD *)((LPBYTE)header + i) = i+4;
2019 if (page < HTABLE_NPAGES-1)
2020 header->freeListFirst[page+1] = 0xffff;
2023 /* Allocate handle slot from page */
2024 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2025 if (--header->freeListSize[page] == 0)
2026 header->freeListFirst[page] = header->freeListLast[page] = 0;
2027 else
2028 header->freeListFirst[page] = *handle;
2030 /* Store 32-bit offset in handle slot */
2031 *handle = ptr - header->base;
2033 else
2035 handle = (LPDWORD)ptr;
2036 header->flags |= 1;
2040 /* Convert handle to requested output type */
2041 Local32_FromHandle( header, type, &addr, handle, ptr );
2042 return addr;
2045 /***********************************************************************
2046 * Local32ReAlloc (KERNEL.210)
2048 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2049 DWORD size, DWORD flags )
2051 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2052 LPDWORD handle;
2053 LPBYTE ptr;
2055 if (!addr)
2056 return Local32Alloc16( heap, size, type, flags );
2058 /* Retrieve handle and pointer */
2059 Local32_ToHandle( header, type, addr, &handle, &ptr );
2060 if (!handle) return FALSE;
2062 /* Reallocate memory block */
2063 ptr = HeapReAlloc( header->heap,
2064 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2065 ptr, size );
2066 if (!ptr) return 0;
2068 /* Modify handle */
2069 if (type >= 0)
2070 *handle = ptr - header->base;
2071 else
2072 handle = (LPDWORD)ptr;
2074 /* Convert handle to requested output type */
2075 Local32_FromHandle( header, type, &addr, handle, ptr );
2076 return addr;
2079 /***********************************************************************
2080 * Local32Free (KERNEL.211)
2082 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2084 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2085 LPDWORD handle;
2086 LPBYTE ptr;
2088 /* Retrieve handle and pointer */
2089 Local32_ToHandle( header, type, addr, &handle, &ptr );
2090 if (!handle) return FALSE;
2092 /* Free handle if necessary */
2093 if (type >= 0)
2095 int offset = (LPBYTE)handle - (LPBYTE)header;
2096 int page = offset >> 12;
2098 /* Return handle slot to page free list */
2099 if (header->freeListSize[page]++ == 0)
2100 header->freeListFirst[page] = header->freeListLast[page] = offset;
2101 else
2102 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2103 header->freeListLast[page] = offset;
2105 *handle = 0;
2107 /* Shrink handle table when possible */
2108 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2110 if ( VirtualFree( (LPBYTE)header +
2111 (header->limit & ~(HTABLE_PAGESIZE-1)),
2112 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2113 break;
2115 header->limit -= HTABLE_PAGESIZE;
2116 header->freeListFirst[page] = 0xffff;
2117 page--;
2121 /* Free memory */
2122 return HeapFree( header->heap, 0, ptr );
2125 /***********************************************************************
2126 * Local32Translate (KERNEL.213)
2128 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2130 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2131 LPDWORD handle;
2132 LPBYTE ptr;
2134 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2135 if (!handle) return 0;
2137 Local32_FromHandle( header, type2, &addr, handle, ptr );
2138 return addr;
2141 /***********************************************************************
2142 * Local32Size (KERNEL.214)
2144 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2146 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2147 LPDWORD handle;
2148 LPBYTE ptr;
2150 Local32_ToHandle( header, type, addr, &handle, &ptr );
2151 if (!handle) return 0;
2153 return HeapSize( header->heap, 0, ptr );
2156 /***********************************************************************
2157 * Local32ValidHandle (KERNEL.215)
2159 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2161 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2162 LPDWORD handle;
2163 LPBYTE ptr;
2165 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2166 return handle != NULL;
2169 /***********************************************************************
2170 * Local32GetSegment (KERNEL.229)
2172 WORD WINAPI Local32GetSegment16( HANDLE heap )
2174 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2175 return header->segment;
2178 /***********************************************************************
2179 * Local32_GetHeap
2181 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2183 WORD selector = GlobalHandleToSel16( handle );
2184 DWORD base = GetSelectorBase( selector );
2185 DWORD limit = GetSelectorLimit16( selector );
2187 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2188 it this way ... */
2190 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2191 return (LOCAL32HEADER *)base;
2193 base += 0x10000;
2194 limit -= 0x10000;
2196 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2197 return (LOCAL32HEADER *)base;
2199 return NULL;
2202 /***********************************************************************
2203 * Local32Info (KERNEL.444) (TOOLHELP.84)
2205 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2207 SUBHEAP *heapPtr;
2208 LPBYTE ptr;
2209 int i;
2211 LOCAL32HEADER *header = Local32_GetHeap( handle );
2212 if ( !header ) return FALSE;
2214 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2215 return FALSE;
2217 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2218 pLocal32Info->dwMemReserved = heapPtr->size;
2219 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2220 pLocal32Info->dwTotalFree = 0L;
2221 pLocal32Info->dwLargestFreeBlock = 0L;
2223 /* Note: Local32 heaps always have only one subheap! */
2224 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2225 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2227 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2229 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2230 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2231 ptr += sizeof(*pArena) + size;
2233 pLocal32Info->dwTotalFree += size;
2234 if ( size > pLocal32Info->dwLargestFreeBlock )
2235 pLocal32Info->dwLargestFreeBlock = size;
2237 else
2239 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2240 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2241 ptr += sizeof(*pArena) + size;
2245 pLocal32Info->dwcFreeHandles = 0;
2246 for ( i = 0; i < HTABLE_NPAGES; i++ )
2248 if ( header->freeListFirst[i] == 0xffff ) break;
2249 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2251 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2253 return TRUE;
2256 /***********************************************************************
2257 * Local32First (KERNEL.445) (TOOLHELP.85)
2259 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2261 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2262 return FALSE;
2265 /***********************************************************************
2266 * Local32Next (KERNEL.446) (TOOLHELP.86)
2268 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2270 FIXME("(%p): stub!\n", pLocal32Entry );
2271 return FALSE;