Various registry-related PostScript driver enhancements.
[wine.git] / memory / heap.c
blob66e1f45146bf97581698b225f55326f13002a33a
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 "config.h"
13 #include "wine/winbase16.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 } HEAP;
101 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
103 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
104 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
105 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
107 static HEAP *systemHeap; /* globally shared heap */
108 static HEAP *processHeap; /* main process heap */
109 static HEAP *segptrHeap; /* main segptr heap */
110 static HEAP *firstHeap; /* head of secondary heaps list */
112 /* address where we try to map the system heap */
113 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
115 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
117 #ifdef __GNUC__
118 #define GET_EIP() (__builtin_return_address(0))
119 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
120 #else
121 #define GET_EIP() 0
122 #define SET_EIP(ptr) /* nothing */
123 #endif /* __GNUC__ */
125 /***********************************************************************
126 * HEAP_Dump
128 void HEAP_Dump( HEAP *heap )
130 int i;
131 SUBHEAP *subheap;
132 char *ptr;
134 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
135 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
136 (DWORD)heap->next, (DWORD)&heap->subheap );
137 subheap = &heap->subheap;
138 while (subheap->next)
140 DPRINTF( " -> %08lx", (DWORD)subheap->next );
141 subheap = subheap->next;
144 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
145 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
146 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
147 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
148 heap->freeList[i].arena.threadId,
149 (DWORD)heap->freeList[i].arena.prev,
150 (DWORD)heap->freeList[i].arena.next );
152 subheap = &heap->subheap;
153 while (subheap)
155 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
156 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
157 (DWORD)subheap, subheap->size, subheap->commitSize );
159 DPRINTF( "\n Block Stat Size Id\n" );
160 ptr = (char*)subheap + subheap->headerSize;
161 while (ptr < (char *)subheap + subheap->size)
163 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
165 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
166 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
167 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168 pArena->threadId, (DWORD)pArena->prev,
169 (DWORD)pArena->next);
170 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171 arenaSize += sizeof(ARENA_FREE);
172 freeSize += pArena->size & ARENA_SIZE_MASK;
174 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
176 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
177 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
178 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
179 pArena->threadId, *((DWORD *)pArena - 1),
180 pArena->callerEIP );
181 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
182 arenaSize += sizeof(ARENA_INUSE);
183 usedSize += pArena->size & ARENA_SIZE_MASK;
185 else
187 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
188 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
189 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
190 pArena->threadId, pArena->callerEIP );
191 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
192 arenaSize += sizeof(ARENA_INUSE);
193 usedSize += pArena->size & ARENA_SIZE_MASK;
196 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
197 subheap->size, subheap->commitSize, freeSize, usedSize,
198 arenaSize, (arenaSize * 100) / subheap->size );
199 subheap = subheap->next;
204 /***********************************************************************
205 * HEAP_GetPtr
206 * RETURNS
207 * Pointer to the heap
208 * NULL: Failure
210 static HEAP *HEAP_GetPtr(
211 HANDLE heap /* [in] Handle to the heap */
213 HEAP *heapPtr = (HEAP *)heap;
214 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
216 ERR("Invalid heap %08x!\n", heap );
217 SetLastError( ERROR_INVALID_HANDLE );
218 return NULL;
220 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
222 HEAP_Dump( heapPtr );
223 assert( FALSE );
224 SetLastError( ERROR_INVALID_HANDLE );
225 return NULL;
227 return heapPtr;
231 /***********************************************************************
232 * HEAP_InsertFreeBlock
234 * Insert a free block into the free list.
236 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
238 FREE_LIST_ENTRY *pEntry = heap->freeList;
239 while (pEntry->size < pArena->size) pEntry++;
240 pArena->size |= ARENA_FLAG_FREE;
241 pArena->next = pEntry->arena.next;
242 pArena->next->prev = pArena;
243 pArena->prev = &pEntry->arena;
244 pEntry->arena.next = pArena;
248 /***********************************************************************
249 * HEAP_FindSubHeap
250 * Find the sub-heap containing a given address.
252 * RETURNS
253 * Pointer: Success
254 * NULL: Failure
256 static SUBHEAP *HEAP_FindSubHeap(
257 HEAP *heap, /* [in] Heap pointer */
258 LPCVOID ptr /* [in] Address */
260 SUBHEAP *sub = &heap->subheap;
261 while (sub)
263 if (((char *)ptr >= (char *)sub) &&
264 ((char *)ptr < (char *)sub + sub->size)) return sub;
265 sub = sub->next;
267 return NULL;
271 /***********************************************************************
272 * HEAP_Commit
274 * Make sure the heap storage is committed up to (not including) ptr.
276 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
278 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
279 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
280 if (size > subheap->size) size = subheap->size;
281 if (size <= subheap->commitSize) return TRUE;
282 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
283 size - subheap->commitSize, MEM_COMMIT,
284 PAGE_EXECUTE_READWRITE))
286 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
287 size - subheap->commitSize,
288 (DWORD)((char *)subheap + subheap->commitSize),
289 (DWORD)subheap->heap );
290 return FALSE;
292 subheap->commitSize = size;
293 return TRUE;
297 /***********************************************************************
298 * HEAP_Decommit
300 * If possible, decommit the heap storage from (including) 'ptr'.
302 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
304 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
305 /* round to next block and add one full block */
306 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
307 if (size >= subheap->commitSize) return TRUE;
308 if (!VirtualFree( (char *)subheap + size,
309 subheap->commitSize - size, MEM_DECOMMIT ))
311 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
312 subheap->commitSize - size,
313 (DWORD)((char *)subheap + size),
314 (DWORD)subheap->heap );
315 return FALSE;
317 subheap->commitSize = size;
318 return TRUE;
322 /***********************************************************************
323 * HEAP_CreateFreeBlock
325 * Create a free block at a specified address. 'size' is the size of the
326 * whole block, including the new arena.
328 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
330 ARENA_FREE *pFree;
332 /* Create a free arena */
334 pFree = (ARENA_FREE *)ptr;
335 pFree->threadId = GetCurrentTask();
336 pFree->magic = ARENA_FREE_MAGIC;
338 /* If debugging, erase the freed block content */
340 if (TRACE_ON(heap))
342 char *pEnd = (char *)ptr + size;
343 if (pEnd > (char *)subheap + subheap->commitSize)
344 pEnd = (char *)subheap + subheap->commitSize;
345 if (pEnd > (char *)(pFree + 1))
346 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
349 /* Check if next block is free also */
351 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
352 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
354 /* Remove the next arena from the free list */
355 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
356 pNext->next->prev = pNext->prev;
357 pNext->prev->next = pNext->next;
358 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
359 if (TRACE_ON(heap))
360 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
363 /* Set the next block PREV_FREE flag and pointer */
365 if ((char *)ptr + size < (char *)subheap + subheap->size)
367 DWORD *pNext = (DWORD *)((char *)ptr + size);
368 *pNext |= ARENA_FLAG_PREV_FREE;
369 *(ARENA_FREE **)(pNext - 1) = pFree;
372 /* Last, insert the new block into the free list */
374 pFree->size = size - sizeof(*pFree);
375 HEAP_InsertFreeBlock( subheap->heap, pFree );
379 /***********************************************************************
380 * HEAP_MakeInUseBlockFree
382 * Turn an in-use block into a free block. Can also decommit the end of
383 * the heap, and possibly even free the sub-heap altogether.
385 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
387 ARENA_FREE *pFree;
388 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
390 /* Check if we can merge with previous block */
392 if (pArena->size & ARENA_FLAG_PREV_FREE)
394 pFree = *((ARENA_FREE **)pArena - 1);
395 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
396 /* Remove it from the free list */
397 pFree->next->prev = pFree->prev;
398 pFree->prev->next = pFree->next;
400 else pFree = (ARENA_FREE *)pArena;
402 /* Create a free block */
404 HEAP_CreateFreeBlock( subheap, pFree, size );
405 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
406 if ((char *)pFree + size < (char *)subheap + subheap->size)
407 return; /* Not the last block, so nothing more to do */
409 /* Free the whole sub-heap if it's empty and not the original one */
411 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
412 (subheap != &subheap->heap->subheap))
414 SUBHEAP *pPrev = &subheap->heap->subheap;
415 /* Remove the free block from the list */
416 pFree->next->prev = pFree->prev;
417 pFree->prev->next = pFree->next;
418 /* Remove the subheap from the list */
419 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
420 if (pPrev) pPrev->next = subheap->next;
421 /* Free the memory */
422 subheap->magic = 0;
423 if (subheap->selector) FreeSelector16( subheap->selector );
424 VirtualFree( subheap, 0, MEM_RELEASE );
425 return;
428 /* Decommit the end of the heap */
430 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
434 /***********************************************************************
435 * HEAP_ShrinkBlock
437 * Shrink an in-use block.
439 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
441 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
443 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
444 (pArena->size & ARENA_SIZE_MASK) - size );
445 /* assign size plus previous arena flags */
446 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
448 else
450 /* Turn off PREV_FREE flag in next block */
451 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
452 if (pNext < (char *)subheap + subheap->size)
453 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
457 /***********************************************************************
458 * HEAP_InitSubHeap
460 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
461 DWORD commitSize, DWORD totalSize )
463 SUBHEAP *subheap = (SUBHEAP *)address;
464 WORD selector = 0;
465 FREE_LIST_ENTRY *pEntry;
466 int i;
468 /* Commit memory */
470 if (flags & HEAP_SHARED)
471 commitSize = totalSize; /* always commit everything in a shared heap */
472 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
474 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
475 commitSize, (DWORD)address );
476 return FALSE;
479 /* Allocate a selector if needed */
481 if (flags & HEAP_WINE_SEGPTR)
483 unsigned char selflags = WINE_LDT_FLAGS_DATA;
485 if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
486 selflags = WINE_LDT_FLAGS_CODE;
487 if (flags & HEAP_WINE_CODESEG)
488 selflags |= WINE_LDT_FLAGS_32BIT;
489 selector = SELECTOR_AllocBlock( address, totalSize, selflags );
490 if (!selector)
492 ERR("Could not allocate selector\n" );
493 return FALSE;
497 /* Fill the sub-heap structure */
499 subheap->heap = heap;
500 subheap->selector = selector;
501 subheap->size = totalSize;
502 subheap->commitSize = commitSize;
503 subheap->magic = SUBHEAP_MAGIC;
505 if ( subheap != (SUBHEAP *)heap )
507 /* If this is a secondary subheap, insert it into list */
509 subheap->headerSize = sizeof(SUBHEAP);
510 subheap->next = heap->subheap.next;
511 heap->subheap.next = subheap;
513 else
515 /* If this is a primary subheap, initialize main heap */
517 subheap->headerSize = sizeof(HEAP);
518 subheap->next = NULL;
519 heap->next = NULL;
520 heap->flags = flags;
521 heap->magic = HEAP_MAGIC;
523 /* Build the free lists */
525 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
527 pEntry->size = HEAP_freeListSizes[i];
528 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
529 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
530 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
531 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
532 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
533 pEntry->arena.threadId = 0;
534 pEntry->arena.magic = ARENA_FREE_MAGIC;
537 /* Initialize critical section */
539 InitializeCriticalSection( &heap->critSection );
542 /* Create the first free block */
544 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
545 subheap->size - subheap->headerSize );
547 return TRUE;
550 /***********************************************************************
551 * HEAP_CreateSubHeap
553 * Create a sub-heap of the given size.
554 * If heap == NULL, creates a main heap.
556 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
557 DWORD commitSize, DWORD totalSize )
559 LPVOID address;
561 /* Round-up sizes on a 64K boundary */
563 if (flags & HEAP_WINE_SEGPTR)
565 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
567 else
569 totalSize = (totalSize + 0xffff) & 0xffff0000;
570 commitSize = (commitSize + 0xffff) & 0xffff0000;
571 if (!commitSize) commitSize = 0x10000;
572 if (totalSize < commitSize) totalSize = commitSize;
575 /* Allocate the memory block */
577 if (!(address = VirtualAlloc( NULL, totalSize,
578 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
580 WARN("Could not VirtualAlloc %08lx bytes\n",
581 totalSize );
582 return NULL;
585 /* Initialize subheap */
587 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
588 address, flags, commitSize, totalSize ))
590 VirtualFree( address, 0, MEM_RELEASE );
591 return NULL;
594 return (SUBHEAP *)address;
598 /***********************************************************************
599 * HEAP_FindFreeBlock
601 * Find a free block at least as large as the requested size, and make sure
602 * the requested size is committed.
604 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
605 SUBHEAP **ppSubHeap )
607 SUBHEAP *subheap;
608 ARENA_FREE *pArena;
609 FREE_LIST_ENTRY *pEntry = heap->freeList;
611 /* Find a suitable free list, and in it find a block large enough */
613 while (pEntry->size < size) pEntry++;
614 pArena = pEntry->arena.next;
615 while (pArena != &heap->freeList[0].arena)
617 if (pArena->size > size)
619 subheap = HEAP_FindSubHeap( heap, pArena );
620 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
621 + size + HEAP_MIN_BLOCK_SIZE))
622 return NULL;
623 *ppSubHeap = subheap;
624 return pArena;
627 pArena = pArena->next;
630 /* If no block was found, attempt to grow the heap */
632 if (!(heap->flags & HEAP_GROWABLE))
634 WARN("Not enough space in heap %08lx for %08lx bytes\n",
635 (DWORD)heap, size );
636 return NULL;
638 /* make sure that we have a big enough size *committed* to fit another
639 * last free arena in !
640 * So just one heap struct, one first free arena which will eventually
641 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
642 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
643 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
644 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
645 max( HEAP_DEF_SIZE, size ) )))
646 return NULL;
648 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
649 (DWORD)subheap, size, (DWORD)heap );
651 *ppSubHeap = subheap;
652 return (ARENA_FREE *)(subheap + 1);
656 /***********************************************************************
657 * HEAP_IsValidArenaPtr
659 * Check that the pointer is inside the range possible for arenas.
661 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
663 int i;
664 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
665 if (!subheap) return FALSE;
666 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
667 if (subheap != &heap->subheap) return FALSE;
668 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
669 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
670 return FALSE;
674 /***********************************************************************
675 * HEAP_ValidateFreeArena
677 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
679 char *heapEnd = (char *)subheap + subheap->size;
681 #if !defined(ALLOW_UNALIGNED_ACCESS)
682 /* Check for unaligned pointers */
683 if ( (long)pArena % sizeof(void *) != 0 )
685 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
686 (DWORD)subheap->heap, (DWORD)pArena );
687 return FALSE;
689 #endif
691 /* Check magic number */
692 if (pArena->magic != ARENA_FREE_MAGIC)
694 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
695 (DWORD)subheap->heap, (DWORD)pArena );
696 return FALSE;
698 /* Check size flags */
699 if (!(pArena->size & ARENA_FLAG_FREE) ||
700 (pArena->size & ARENA_FLAG_PREV_FREE))
702 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
703 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
705 /* Check arena size */
706 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
708 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
709 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
710 return FALSE;
712 /* Check that next pointer is valid */
713 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
715 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
716 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
717 return FALSE;
719 /* Check that next arena is free */
720 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
721 (pArena->next->magic != ARENA_FREE_MAGIC))
723 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
724 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
725 return FALSE;
727 /* Check that prev pointer is valid */
728 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
730 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
731 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
732 return FALSE;
734 /* Check that prev arena is free */
735 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
736 (pArena->prev->magic != ARENA_FREE_MAGIC))
738 /* this often means that the prev arena got overwritten
739 * by a memory write before that prev arena */
740 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
741 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
742 return FALSE;
744 /* Check that next block has PREV_FREE flag */
745 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
747 if (!(*(DWORD *)((char *)(pArena + 1) +
748 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
750 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
751 (DWORD)subheap->heap, (DWORD)pArena );
752 return FALSE;
754 /* Check next block back pointer */
755 if (*((ARENA_FREE **)((char *)(pArena + 1) +
756 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
758 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
759 (DWORD)subheap->heap, (DWORD)pArena,
760 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
761 return FALSE;
764 return TRUE;
768 /***********************************************************************
769 * HEAP_ValidateInUseArena
771 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
773 char *heapEnd = (char *)subheap + subheap->size;
775 #if !defined(ALLOW_UNALIGNED_ACCESS)
776 /* Check for unaligned pointers */
777 if ( (long)pArena % sizeof(void *) != 0 )
779 if ( quiet == NOISY )
781 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
782 (DWORD)subheap->heap, (DWORD)pArena );
783 if ( TRACE_ON(heap) )
784 HEAP_Dump( subheap->heap );
786 else if ( WARN_ON(heap) )
788 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
789 (DWORD)subheap->heap, (DWORD)pArena );
790 if ( TRACE_ON(heap) )
791 HEAP_Dump( subheap->heap );
793 return FALSE;
795 #endif
797 /* Check magic number */
798 if (pArena->magic != ARENA_INUSE_MAGIC)
800 if (quiet == NOISY) {
801 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
802 (DWORD)subheap->heap, (DWORD)pArena );
803 if (TRACE_ON(heap))
804 HEAP_Dump( subheap->heap );
805 } else if (WARN_ON(heap)) {
806 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
807 (DWORD)subheap->heap, (DWORD)pArena );
808 if (TRACE_ON(heap))
809 HEAP_Dump( subheap->heap );
811 return FALSE;
813 /* Check size flags */
814 if (pArena->size & ARENA_FLAG_FREE)
816 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
817 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
819 /* Check arena size */
820 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
822 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
823 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
824 return FALSE;
826 /* Check next arena PREV_FREE flag */
827 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
828 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
830 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
831 (DWORD)subheap->heap, (DWORD)pArena );
832 return FALSE;
834 /* Check prev free arena */
835 if (pArena->size & ARENA_FLAG_PREV_FREE)
837 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
838 /* Check prev pointer */
839 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
841 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
842 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
843 return FALSE;
845 /* Check that prev arena is free */
846 if (!(pPrev->size & ARENA_FLAG_FREE) ||
847 (pPrev->magic != ARENA_FREE_MAGIC))
849 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
850 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
851 return FALSE;
853 /* Check that prev arena is really the previous block */
854 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
856 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
857 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
858 return FALSE;
861 return TRUE;
865 /***********************************************************************
866 * HEAP_GetSegptr
868 * Transform a linear pointer into a SEGPTR. The pointer must have been
869 * allocated from a HEAP_WINE_SEGPTR heap.
871 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
873 HEAP *heapPtr = HEAP_GetPtr( heap );
874 SUBHEAP *subheap;
875 SEGPTR ret = 0;
877 /* Validate the parameters */
879 if (!heapPtr) return 0;
880 flags |= heapPtr->flags;
881 if (!(flags & HEAP_WINE_SEGPTR))
883 ERR("Heap %08x is not a SEGPTR heap\n",
884 heap );
885 return 0;
887 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
889 /* Get the subheap */
891 if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
892 ret = MAKESEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
894 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
895 return ret;
898 /***********************************************************************
899 * MapLS (KERNEL32.522)
901 * Maps linear pointer to segmented.
903 SEGPTR WINAPI MapLS( LPCVOID ptr )
905 SUBHEAP *subheap;
906 SEGPTR ret = 0;
908 if (!HIWORD(ptr)) return (SEGPTR)ptr;
910 /* check if the pointer is inside the segptr heap */
911 EnterCriticalSection( &segptrHeap->critSection );
912 if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
913 ret = MAKESEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
914 LeaveCriticalSection( &segptrHeap->critSection );
916 /* otherwise, allocate a brand-new selector */
917 if (!ret)
919 WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
920 ret = MAKESEGPTR( sel, 0 );
922 return ret;
926 /***********************************************************************
927 * UnMapLS (KERNEL32.700)
929 * Free mapped selector.
931 void WINAPI UnMapLS( SEGPTR sptr )
933 SUBHEAP *subheap;
934 if (!SELECTOROF(sptr)) return;
936 /* check if ptr is inside segptr heap */
937 EnterCriticalSection( &segptrHeap->critSection );
938 subheap = HEAP_FindSubHeap( segptrHeap, MapSL(sptr) );
939 if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
940 LeaveCriticalSection( &segptrHeap->critSection );
941 /* if not inside heap, free the selector */
942 if (!subheap) FreeSelector16( SELECTOROF(sptr) );
945 /***********************************************************************
946 * HEAP_IsRealArena [Internal]
947 * Validates a block is a valid arena.
949 * RETURNS
950 * TRUE: Success
951 * FALSE: Failure
953 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
954 DWORD flags, /* [in] Bit flags that control access during operation */
955 LPCVOID block, /* [in] Optional pointer to memory block to validate */
956 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
957 * does not complain */
959 SUBHEAP *subheap;
960 BOOL ret = TRUE;
962 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
964 ERR("Invalid heap %p!\n", heapPtr );
965 return FALSE;
968 flags &= HEAP_NO_SERIALIZE;
969 flags |= heapPtr->flags;
970 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
971 if (!(flags & HEAP_NO_SERIALIZE))
972 EnterCriticalSection( &heapPtr->critSection );
974 if (block)
976 /* Only check this single memory block */
978 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
979 ((char *)block < (char *)subheap + subheap->headerSize
980 + sizeof(ARENA_INUSE)))
982 if (quiet == NOISY)
983 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
984 else if (WARN_ON(heap))
985 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
986 ret = FALSE;
987 } else
988 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
990 if (!(flags & HEAP_NO_SERIALIZE))
991 LeaveCriticalSection( &heapPtr->critSection );
992 return ret;
995 subheap = &heapPtr->subheap;
996 while (subheap && ret)
998 char *ptr = (char *)subheap + subheap->headerSize;
999 while (ptr < (char *)subheap + subheap->size)
1001 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1003 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1004 ret = FALSE;
1005 break;
1007 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1009 else
1011 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1012 ret = FALSE;
1013 break;
1015 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1018 subheap = subheap->next;
1021 if (!(flags & HEAP_NO_SERIALIZE))
1022 LeaveCriticalSection( &heapPtr->critSection );
1023 return ret;
1027 /***********************************************************************
1028 * HEAP_CreateSystemHeap
1030 * Create the system heap.
1032 static HANDLE HEAP_CreateSystemHeap(void)
1034 int created;
1036 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1037 0, HEAP_DEF_SIZE, "__SystemHeap" );
1038 if (!map) return 0;
1039 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1041 if (!(systemHeap = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1043 /* pre-defined address not available, use any one */
1044 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
1045 return 0;
1048 if (created) /* newly created heap */
1050 HEAP_InitSubHeap( systemHeap, systemHeap, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1051 MakeCriticalSectionGlobal( &systemHeap->critSection );
1053 else
1055 /* wait for the heap to be initialized */
1056 while (!systemHeap->critSection.LockSemaphore) Sleep(1);
1058 CloseHandle( map );
1059 return (HANDLE)systemHeap;
1063 /***********************************************************************
1064 * HeapCreate (KERNEL32.336)
1065 * RETURNS
1066 * Handle of heap: Success
1067 * NULL: Failure
1069 HANDLE WINAPI HeapCreate(
1070 DWORD flags, /* [in] Heap allocation flag */
1071 DWORD initialSize, /* [in] Initial heap size */
1072 DWORD maxSize /* [in] Maximum heap size */
1074 SUBHEAP *subheap;
1076 if ( flags & HEAP_SHARED ) {
1077 if (!systemHeap) HEAP_CreateSystemHeap();
1078 else WARN( "Shared Heap requested, returning system heap.\n" );
1079 return (HANDLE)systemHeap;
1082 /* Allocate the heap block */
1084 if (!maxSize)
1086 maxSize = HEAP_DEF_SIZE;
1087 flags |= HEAP_GROWABLE;
1089 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1091 SetLastError( ERROR_OUTOFMEMORY );
1092 return 0;
1095 /* link it into the per-process heap list */
1096 if (processHeap)
1098 HEAP *heapPtr = subheap->heap;
1099 EnterCriticalSection( &processHeap->critSection );
1100 heapPtr->next = firstHeap;
1101 firstHeap = heapPtr;
1102 LeaveCriticalSection( &processHeap->critSection );
1104 else /* assume the first heap we create is the process main heap */
1106 SUBHEAP *segptr;
1107 processHeap = subheap->heap;
1108 /* create the SEGPTR heap */
1109 if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1111 SetLastError( ERROR_OUTOFMEMORY );
1112 return 0;
1114 segptrHeap = segptr->heap;
1116 return (HANDLE)subheap;
1119 /***********************************************************************
1120 * HeapDestroy (KERNEL32.337)
1121 * RETURNS
1122 * TRUE: Success
1123 * FALSE: Failure
1125 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1127 HEAP *heapPtr = HEAP_GetPtr( heap );
1128 SUBHEAP *subheap;
1130 TRACE("%08x\n", heap );
1131 if (!heapPtr) return FALSE;
1133 if (heapPtr == systemHeap)
1135 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1136 return TRUE;
1138 if (heapPtr == processHeap) /* cannot delete the main process heap */
1140 SetLastError( ERROR_INVALID_PARAMETER );
1141 return FALSE;
1143 else /* remove it from the per-process list */
1145 HEAP **pptr;
1146 EnterCriticalSection( &processHeap->critSection );
1147 pptr = &firstHeap;
1148 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1149 if (*pptr) *pptr = (*pptr)->next;
1150 LeaveCriticalSection( &processHeap->critSection );
1153 DeleteCriticalSection( &heapPtr->critSection );
1154 subheap = &heapPtr->subheap;
1155 while (subheap)
1157 SUBHEAP *next = subheap->next;
1158 if (subheap->selector) FreeSelector16( subheap->selector );
1159 VirtualFree( subheap, 0, MEM_RELEASE );
1160 subheap = next;
1162 return TRUE;
1166 /***********************************************************************
1167 * HeapAlloc (KERNEL32.334)
1168 * RETURNS
1169 * Pointer to allocated memory block
1170 * NULL: Failure
1172 LPVOID WINAPI HeapAlloc(
1173 HANDLE heap, /* [in] Handle of private heap block */
1174 DWORD flags, /* [in] Heap allocation control flags */
1175 DWORD size /* [in] Number of bytes to allocate */
1177 ARENA_FREE *pArena;
1178 ARENA_INUSE *pInUse;
1179 SUBHEAP *subheap;
1180 HEAP *heapPtr = HEAP_GetPtr( heap );
1182 /* Validate the parameters */
1184 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1185 if (!heapPtr) return NULL;
1186 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1187 flags |= heapPtr->flags;
1188 size = (size + 3) & ~3;
1189 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1191 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1192 /* Locate a suitable free block */
1194 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1196 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1197 heap, flags, size );
1198 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1199 SetLastError( ERROR_COMMITMENT_LIMIT );
1200 return NULL;
1203 /* Remove the arena from the free list */
1205 pArena->next->prev = pArena->prev;
1206 pArena->prev->next = pArena->next;
1208 /* Build the in-use arena */
1210 pInUse = (ARENA_INUSE *)pArena;
1212 /* in-use arena is smaller than free arena,
1213 * so we have to add the difference to the size */
1214 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1215 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1216 pInUse->callerEIP = GET_EIP();
1217 pInUse->threadId = GetCurrentTask();
1218 pInUse->magic = ARENA_INUSE_MAGIC;
1220 /* Shrink the block */
1222 HEAP_ShrinkBlock( subheap, pInUse, size );
1224 if (flags & HEAP_ZERO_MEMORY)
1225 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1226 else if (TRACE_ON(heap))
1227 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1229 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1231 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1232 heap, flags, size, (DWORD)(pInUse + 1) );
1233 return (LPVOID)(pInUse + 1);
1237 /***********************************************************************
1238 * HeapFree (KERNEL32.338)
1239 * RETURNS
1240 * TRUE: Success
1241 * FALSE: Failure
1243 BOOL WINAPI HeapFree(
1244 HANDLE heap, /* [in] Handle of heap */
1245 DWORD flags, /* [in] Heap freeing flags */
1246 LPVOID ptr /* [in] Address of memory to free */
1248 ARENA_INUSE *pInUse;
1249 SUBHEAP *subheap;
1250 HEAP *heapPtr = HEAP_GetPtr( heap );
1252 /* Validate the parameters */
1254 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1255 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1256 if (!heapPtr) return FALSE;
1258 flags &= HEAP_NO_SERIALIZE;
1259 flags |= heapPtr->flags;
1260 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1261 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1263 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1264 SetLastError( ERROR_INVALID_PARAMETER );
1265 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1266 heap, flags, (DWORD)ptr );
1267 return FALSE;
1270 /* Turn the block into a free block */
1272 pInUse = (ARENA_INUSE *)ptr - 1;
1273 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1274 HEAP_MakeInUseBlockFree( subheap, pInUse );
1276 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1278 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1279 heap, flags, (DWORD)ptr );
1280 return TRUE;
1284 /***********************************************************************
1285 * HeapReAlloc (KERNEL32.340)
1286 * RETURNS
1287 * Pointer to reallocated memory block
1288 * NULL: Failure
1290 LPVOID WINAPI HeapReAlloc(
1291 HANDLE heap, /* [in] Handle of heap block */
1292 DWORD flags, /* [in] Heap reallocation flags */
1293 LPVOID ptr, /* [in] Address of memory to reallocate */
1294 DWORD size /* [in] Number of bytes to reallocate */
1296 ARENA_INUSE *pArena;
1297 DWORD oldSize;
1298 HEAP *heapPtr;
1299 SUBHEAP *subheap;
1301 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1302 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1303 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1305 /* Validate the parameters */
1307 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1308 HEAP_REALLOC_IN_PLACE_ONLY;
1309 flags |= heapPtr->flags;
1310 size = (size + 3) & ~3;
1311 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1313 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1314 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1316 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1317 SetLastError( ERROR_INVALID_PARAMETER );
1318 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1319 heap, flags, (DWORD)ptr, size );
1320 return NULL;
1323 /* Check if we need to grow the block */
1325 pArena = (ARENA_INUSE *)ptr - 1;
1326 pArena->threadId = GetCurrentTask();
1327 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1328 oldSize = (pArena->size & ARENA_SIZE_MASK);
1329 if (size > oldSize)
1331 char *pNext = (char *)(pArena + 1) + oldSize;
1332 if ((pNext < (char *)subheap + subheap->size) &&
1333 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1334 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1336 /* The next block is free and large enough */
1337 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1338 pFree->next->prev = pFree->prev;
1339 pFree->prev->next = pFree->next;
1340 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1341 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1342 + size + HEAP_MIN_BLOCK_SIZE))
1344 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1345 SetLastError( ERROR_OUTOFMEMORY );
1346 return NULL;
1348 HEAP_ShrinkBlock( subheap, pArena, size );
1350 else /* Do it the hard way */
1352 ARENA_FREE *pNew;
1353 ARENA_INUSE *pInUse;
1354 SUBHEAP *newsubheap;
1356 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1357 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1359 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1360 SetLastError( ERROR_OUTOFMEMORY );
1361 return NULL;
1364 /* Build the in-use arena */
1366 pNew->next->prev = pNew->prev;
1367 pNew->prev->next = pNew->next;
1368 pInUse = (ARENA_INUSE *)pNew;
1369 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1370 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1371 pInUse->threadId = GetCurrentTask();
1372 pInUse->magic = ARENA_INUSE_MAGIC;
1373 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1374 memcpy( pInUse + 1, pArena + 1, oldSize );
1376 /* Free the previous block */
1378 HEAP_MakeInUseBlockFree( subheap, pArena );
1379 subheap = newsubheap;
1380 pArena = pInUse;
1383 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1385 /* Clear the extra bytes if needed */
1387 if (size > oldSize)
1389 if (flags & HEAP_ZERO_MEMORY)
1390 memset( (char *)(pArena + 1) + oldSize, 0,
1391 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1392 else if (TRACE_ON(heap))
1393 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1394 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1397 /* Return the new arena */
1399 pArena->callerEIP = GET_EIP();
1400 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1402 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1403 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1404 return (LPVOID)(pArena + 1);
1408 /***********************************************************************
1409 * HeapCompact (KERNEL32.335)
1411 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1413 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1414 return 0;
1418 /***********************************************************************
1419 * HeapLock (KERNEL32.339)
1420 * Attempts to acquire the critical section object for a specified heap.
1422 * RETURNS
1423 * TRUE: Success
1424 * FALSE: Failure
1426 BOOL WINAPI HeapLock(
1427 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1429 HEAP *heapPtr = HEAP_GetPtr( heap );
1430 if (!heapPtr) return FALSE;
1431 EnterCriticalSection( &heapPtr->critSection );
1432 return TRUE;
1436 /***********************************************************************
1437 * HeapUnlock (KERNEL32.342)
1438 * Releases ownership of the critical section object.
1440 * RETURNS
1441 * TRUE: Success
1442 * FALSE: Failure
1444 BOOL WINAPI HeapUnlock(
1445 HANDLE heap /* [in] Handle to the heap to unlock */
1447 HEAP *heapPtr = HEAP_GetPtr( heap );
1448 if (!heapPtr) return FALSE;
1449 LeaveCriticalSection( &heapPtr->critSection );
1450 return TRUE;
1454 /***********************************************************************
1455 * HeapSize (KERNEL32.341)
1456 * RETURNS
1457 * Size in bytes of allocated memory
1458 * 0xffffffff: Failure
1460 DWORD WINAPI HeapSize(
1461 HANDLE heap, /* [in] Handle of heap */
1462 DWORD flags, /* [in] Heap size control flags */
1463 LPVOID ptr /* [in] Address of memory to return size for */
1465 DWORD ret;
1466 HEAP *heapPtr = HEAP_GetPtr( heap );
1468 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1469 if (!heapPtr) return FALSE;
1470 flags &= HEAP_NO_SERIALIZE;
1471 flags |= heapPtr->flags;
1472 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1473 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1475 SetLastError( ERROR_INVALID_PARAMETER );
1476 ret = 0xffffffff;
1478 else
1480 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1481 ret = pArena->size & ARENA_SIZE_MASK;
1483 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1485 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1486 heap, flags, (DWORD)ptr, ret );
1487 return ret;
1491 /***********************************************************************
1492 * HeapValidate (KERNEL32.343)
1493 * Validates a specified heap.
1495 * NOTES
1496 * Flags is ignored.
1498 * RETURNS
1499 * TRUE: Success
1500 * FALSE: Failure
1502 BOOL WINAPI HeapValidate(
1503 HANDLE heap, /* [in] Handle to the heap */
1504 DWORD flags, /* [in] Bit flags that control access during operation */
1505 LPCVOID block /* [in] Optional pointer to memory block to validate */
1507 HEAP *heapPtr = HEAP_GetPtr( heap );
1508 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1509 if (!heapPtr) return FALSE;
1510 return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1514 /***********************************************************************
1515 * HeapWalk (KERNEL32.344)
1516 * Enumerates the memory blocks in a specified heap.
1517 * See HEAP_Dump() for info on heap structure.
1519 * TODO
1520 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1521 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1523 * RETURNS
1524 * TRUE: Success
1525 * FALSE: Failure
1527 BOOL WINAPI HeapWalk(
1528 HANDLE heap, /* [in] Handle to heap to enumerate */
1529 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1531 HEAP *heapPtr = HEAP_GetPtr(heap);
1532 SUBHEAP *sub, *currentheap = NULL;
1533 BOOL ret = FALSE;
1534 char *ptr;
1535 int region_index = 0;
1537 if (!heapPtr || !entry)
1539 SetLastError(ERROR_INVALID_PARAMETER);
1540 return FALSE;
1543 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1545 /* set ptr to the next arena to be examined */
1547 if (!entry->lpData) /* first call (init) ? */
1549 TRACE("begin walking of heap 0x%08x.\n", heap);
1550 /*HEAP_Dump(heapPtr);*/
1551 currentheap = &heapPtr->subheap;
1552 ptr = (char*)currentheap + currentheap->headerSize;
1554 else
1556 ptr = entry->lpData;
1557 sub = &heapPtr->subheap;
1558 while (sub)
1560 if (((char *)ptr >= (char *)sub) &&
1561 ((char *)ptr < (char *)sub + sub->size))
1563 currentheap = sub;
1564 break;
1566 sub = sub->next;
1567 region_index++;
1569 if (currentheap == NULL)
1571 ERR("no matching subheap found, shouldn't happen !\n");
1572 SetLastError(ERROR_NO_MORE_ITEMS);
1573 goto HW_end;
1576 ptr += entry->cbData; /* point to next arena */
1577 if (ptr > (char *)currentheap + currentheap->size - 1)
1578 { /* proceed with next subheap */
1579 if (!(currentheap = currentheap->next))
1580 { /* successfully finished */
1581 TRACE("end reached.\n");
1582 SetLastError(ERROR_NO_MORE_ITEMS);
1583 goto HW_end;
1585 ptr = (char*)currentheap + currentheap->headerSize;
1589 entry->wFlags = 0;
1590 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1592 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1594 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1596 entry->lpData = pArena + 1;
1597 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1598 entry->cbOverhead = sizeof(ARENA_FREE);
1599 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1601 else
1603 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1605 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1607 entry->lpData = pArena + 1;
1608 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1609 entry->cbOverhead = sizeof(ARENA_INUSE);
1610 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1611 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1612 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1615 entry->iRegionIndex = region_index;
1617 /* first element of heap ? */
1618 if (ptr == (char *)(currentheap + currentheap->headerSize))
1620 entry->wFlags |= PROCESS_HEAP_REGION;
1621 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1622 entry->u.Region.dwUnCommittedSize =
1623 currentheap->size - currentheap->commitSize;
1624 entry->u.Region.lpFirstBlock = /* first valid block */
1625 currentheap + currentheap->headerSize;
1626 entry->u.Region.lpLastBlock = /* first invalid block */
1627 currentheap + currentheap->size;
1629 ret = TRUE;
1631 HW_end:
1632 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1634 return ret;
1638 /***********************************************************************
1639 * GetProcessHeap (KERNEL32.259)
1641 HANDLE WINAPI GetProcessHeap(void)
1643 return (HANDLE)processHeap;
1647 /***********************************************************************
1648 * GetProcessHeaps (KERNEL32.376)
1650 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1652 DWORD total;
1653 HEAP *ptr;
1655 if (!processHeap) return 0; /* should never happen */
1656 total = 1; /* main heap */
1657 EnterCriticalSection( &processHeap->critSection );
1658 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1659 if (total <= count)
1661 *heaps++ = (HANDLE)processHeap;
1662 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1664 LeaveCriticalSection( &processHeap->critSection );
1665 return total;
1669 /***********************************************************************
1670 * 32-bit local heap functions (Win95; undocumented)
1673 #define HTABLE_SIZE 0x10000
1674 #define HTABLE_PAGESIZE 0x1000
1675 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1677 #include "pshpack1.h"
1678 typedef struct _LOCAL32HEADER
1680 WORD freeListFirst[HTABLE_NPAGES];
1681 WORD freeListSize[HTABLE_NPAGES];
1682 WORD freeListLast[HTABLE_NPAGES];
1684 DWORD selectorTableOffset;
1685 WORD selectorTableSize;
1686 WORD selectorDelta;
1688 DWORD segment;
1689 LPBYTE base;
1691 DWORD limit;
1692 DWORD flags;
1694 DWORD magic;
1695 HANDLE heap;
1697 } LOCAL32HEADER;
1698 #include "poppack.h"
1700 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1702 /***********************************************************************
1703 * Local32Init (KERNEL.208)
1705 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1706 DWORD heapSize, DWORD flags )
1708 DWORD totSize, segSize = 0;
1709 LPBYTE base;
1710 LOCAL32HEADER *header;
1711 HEAP *heap;
1712 WORD *selectorTable;
1713 WORD selectorEven, selectorOdd;
1714 int i, nrBlocks;
1716 /* Determine new heap size */
1718 if ( segment )
1720 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1721 return 0;
1722 else
1723 segSize++;
1726 if ( heapSize == -1L )
1727 heapSize = 1024L*1024L; /* FIXME */
1729 heapSize = (heapSize + 0xffff) & 0xffff0000;
1730 segSize = (segSize + 0x0fff) & 0xfffff000;
1731 totSize = segSize + HTABLE_SIZE + heapSize;
1734 /* Allocate memory and initialize heap */
1736 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1737 return 0;
1739 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1740 MEM_COMMIT, PAGE_READWRITE ) )
1742 VirtualFree( base, 0, MEM_RELEASE );
1743 return 0;
1746 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1747 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1749 VirtualFree( base, 0, MEM_RELEASE );
1750 return 0;
1754 /* Set up header and handle table */
1756 header = (LOCAL32HEADER *)(base + segSize);
1757 header->base = base;
1758 header->limit = HTABLE_PAGESIZE-1;
1759 header->flags = 0;
1760 header->magic = LOCAL32_MAGIC;
1761 header->heap = (HANDLE)heap;
1763 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1764 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1765 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1767 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1768 *(DWORD *)((LPBYTE)header + i) = i+4;
1770 header->freeListFirst[1] = 0xffff;
1773 /* Set up selector table */
1775 nrBlocks = (totSize + 0x7fff) >> 15;
1776 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1777 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1778 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1779 if ( !selectorTable || !selectorEven || !selectorOdd )
1781 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1782 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1783 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1784 HeapDestroy( header->heap );
1785 VirtualFree( base, 0, MEM_RELEASE );
1786 return 0;
1789 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1790 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1791 header->selectorDelta = selectorEven - selectorOdd;
1792 header->segment = segment? segment : selectorEven;
1794 for (i = 0; i < nrBlocks; i++)
1795 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1796 : selectorEven + ((i >> 1) << __AHSHIFT);
1798 /* Move old segment */
1800 if ( segment )
1802 /* FIXME: This is somewhat ugly and relies on implementation
1803 details about 16-bit global memory handles ... */
1805 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1806 memcpy( base, oldBase, segSize );
1807 GLOBAL_MoveBlock( segment, base, totSize );
1808 HeapFree( GetProcessHeap(), 0, oldBase );
1811 return (HANDLE)header;
1814 /***********************************************************************
1815 * Local32_SearchHandle
1817 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1819 LPDWORD handle;
1821 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1822 handle < (LPDWORD)((LPBYTE)header + header->limit);
1823 handle++)
1825 if (*handle == addr)
1826 return handle;
1829 return NULL;
1832 /***********************************************************************
1833 * Local32_ToHandle
1835 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1836 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1838 *handle = NULL;
1839 *ptr = NULL;
1841 switch (type)
1843 case -2: /* 16:16 pointer, no handles */
1844 *ptr = MapSL( addr );
1845 *handle = (LPDWORD)*ptr;
1846 break;
1848 case -1: /* 32-bit offset, no handles */
1849 *ptr = header->base + addr;
1850 *handle = (LPDWORD)*ptr;
1851 break;
1853 case 0: /* handle */
1854 if ( addr >= sizeof(LOCAL32HEADER)
1855 && addr < header->limit && !(addr & 3)
1856 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1858 *handle = (LPDWORD)((LPBYTE)header + addr);
1859 *ptr = header->base + **handle;
1861 break;
1863 case 1: /* 16:16 pointer */
1864 *ptr = MapSL( addr );
1865 *handle = Local32_SearchHandle( header, *ptr - header->base );
1866 break;
1868 case 2: /* 32-bit offset */
1869 *ptr = header->base + addr;
1870 *handle = Local32_SearchHandle( header, *ptr - header->base );
1871 break;
1875 /***********************************************************************
1876 * Local32_FromHandle
1878 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1879 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1881 switch (type)
1883 case -2: /* 16:16 pointer */
1884 case 1:
1886 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1887 DWORD offset = (LPBYTE)ptr - header->base;
1888 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1890 break;
1892 case -1: /* 32-bit offset */
1893 case 2:
1894 *addr = ptr - header->base;
1895 break;
1897 case 0: /* handle */
1898 *addr = (LPBYTE)handle - (LPBYTE)header;
1899 break;
1903 /***********************************************************************
1904 * Local32Alloc (KERNEL.209)
1906 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1908 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1909 LPDWORD handle;
1910 LPBYTE ptr;
1911 DWORD addr;
1913 /* Allocate memory */
1914 ptr = HeapAlloc( header->heap,
1915 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1916 if (!ptr) return 0;
1919 /* Allocate handle if requested */
1920 if (type >= 0)
1922 int page, i;
1924 /* Find first page of handle table with free slots */
1925 for (page = 0; page < HTABLE_NPAGES; page++)
1926 if (header->freeListFirst[page] != 0)
1927 break;
1928 if (page == HTABLE_NPAGES)
1930 WARN("Out of handles!\n" );
1931 HeapFree( header->heap, 0, ptr );
1932 return 0;
1935 /* If virgin page, initialize it */
1936 if (header->freeListFirst[page] == 0xffff)
1938 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1939 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1941 WARN("Cannot grow handle table!\n" );
1942 HeapFree( header->heap, 0, ptr );
1943 return 0;
1946 header->limit += HTABLE_PAGESIZE;
1948 header->freeListFirst[page] = 0;
1949 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1950 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1952 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1953 *(DWORD *)((LPBYTE)header + i) = i+4;
1955 if (page < HTABLE_NPAGES-1)
1956 header->freeListFirst[page+1] = 0xffff;
1959 /* Allocate handle slot from page */
1960 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1961 if (--header->freeListSize[page] == 0)
1962 header->freeListFirst[page] = header->freeListLast[page] = 0;
1963 else
1964 header->freeListFirst[page] = *handle;
1966 /* Store 32-bit offset in handle slot */
1967 *handle = ptr - header->base;
1969 else
1971 handle = (LPDWORD)ptr;
1972 header->flags |= 1;
1976 /* Convert handle to requested output type */
1977 Local32_FromHandle( header, type, &addr, handle, ptr );
1978 return addr;
1981 /***********************************************************************
1982 * Local32ReAlloc (KERNEL.210)
1984 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1985 DWORD size, DWORD flags )
1987 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1988 LPDWORD handle;
1989 LPBYTE ptr;
1991 if (!addr)
1992 return Local32Alloc16( heap, size, type, flags );
1994 /* Retrieve handle and pointer */
1995 Local32_ToHandle( header, type, addr, &handle, &ptr );
1996 if (!handle) return FALSE;
1998 /* Reallocate memory block */
1999 ptr = HeapReAlloc( header->heap,
2000 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2001 ptr, size );
2002 if (!ptr) return 0;
2004 /* Modify handle */
2005 if (type >= 0)
2006 *handle = ptr - header->base;
2007 else
2008 handle = (LPDWORD)ptr;
2010 /* Convert handle to requested output type */
2011 Local32_FromHandle( header, type, &addr, handle, ptr );
2012 return addr;
2015 /***********************************************************************
2016 * Local32Free (KERNEL.211)
2018 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2020 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2021 LPDWORD handle;
2022 LPBYTE ptr;
2024 /* Retrieve handle and pointer */
2025 Local32_ToHandle( header, type, addr, &handle, &ptr );
2026 if (!handle) return FALSE;
2028 /* Free handle if necessary */
2029 if (type >= 0)
2031 int offset = (LPBYTE)handle - (LPBYTE)header;
2032 int page = offset >> 12;
2034 /* Return handle slot to page free list */
2035 if (header->freeListSize[page]++ == 0)
2036 header->freeListFirst[page] = header->freeListLast[page] = offset;
2037 else
2038 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2039 header->freeListLast[page] = offset;
2041 *handle = 0;
2043 /* Shrink handle table when possible */
2044 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2046 if ( VirtualFree( (LPBYTE)header +
2047 (header->limit & ~(HTABLE_PAGESIZE-1)),
2048 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2049 break;
2051 header->limit -= HTABLE_PAGESIZE;
2052 header->freeListFirst[page] = 0xffff;
2053 page--;
2057 /* Free memory */
2058 return HeapFree( header->heap, 0, ptr );
2061 /***********************************************************************
2062 * Local32Translate (KERNEL.213)
2064 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2066 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2067 LPDWORD handle;
2068 LPBYTE ptr;
2070 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2071 if (!handle) return 0;
2073 Local32_FromHandle( header, type2, &addr, handle, ptr );
2074 return addr;
2077 /***********************************************************************
2078 * Local32Size (KERNEL.214)
2080 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2082 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2083 LPDWORD handle;
2084 LPBYTE ptr;
2086 Local32_ToHandle( header, type, addr, &handle, &ptr );
2087 if (!handle) return 0;
2089 return HeapSize( header->heap, 0, ptr );
2092 /***********************************************************************
2093 * Local32ValidHandle (KERNEL.215)
2095 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2097 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2098 LPDWORD handle;
2099 LPBYTE ptr;
2101 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2102 return handle != NULL;
2105 /***********************************************************************
2106 * Local32GetSegment (KERNEL.229)
2108 WORD WINAPI Local32GetSegment16( HANDLE heap )
2110 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2111 return header->segment;
2114 /***********************************************************************
2115 * Local32_GetHeap
2117 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2119 WORD selector = GlobalHandleToSel16( handle );
2120 DWORD base = GetSelectorBase( selector );
2121 DWORD limit = GetSelectorLimit16( selector );
2123 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2124 it this way ... */
2126 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2127 return (LOCAL32HEADER *)base;
2129 base += 0x10000;
2130 limit -= 0x10000;
2132 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2133 return (LOCAL32HEADER *)base;
2135 return NULL;
2138 /***********************************************************************
2139 * Local32Info (KERNEL.444) (TOOLHELP.84)
2141 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2143 SUBHEAP *heapPtr;
2144 LPBYTE ptr;
2145 int i;
2147 LOCAL32HEADER *header = Local32_GetHeap( handle );
2148 if ( !header ) return FALSE;
2150 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2151 return FALSE;
2153 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2154 pLocal32Info->dwMemReserved = heapPtr->size;
2155 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2156 pLocal32Info->dwTotalFree = 0L;
2157 pLocal32Info->dwLargestFreeBlock = 0L;
2159 /* Note: Local32 heaps always have only one subheap! */
2160 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2161 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2163 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2165 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2166 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2167 ptr += sizeof(*pArena) + size;
2169 pLocal32Info->dwTotalFree += size;
2170 if ( size > pLocal32Info->dwLargestFreeBlock )
2171 pLocal32Info->dwLargestFreeBlock = size;
2173 else
2175 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2176 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2177 ptr += sizeof(*pArena) + size;
2181 pLocal32Info->dwcFreeHandles = 0;
2182 for ( i = 0; i < HTABLE_NPAGES; i++ )
2184 if ( header->freeListFirst[i] == 0xffff ) break;
2185 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2187 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2189 return TRUE;
2192 /***********************************************************************
2193 * Local32First (KERNEL.445) (TOOLHELP.85)
2195 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2197 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2198 return FALSE;
2201 /***********************************************************************
2202 * Local32Next (KERNEL.446) (TOOLHELP.86)
2204 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2206 FIXME("(%p): stub!\n", pLocal32Entry );
2207 return FALSE;