Replaced all lstr* calls from inside Wine code by their str* equivalent.
[wine/hacks.git] / memory / heap.c
blobda3477c74e118855649a1f98c3f2fb2eebca726d
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 threadId; /* Allocating thread id */
37 WORD magic; /* Magic number */
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 threadId; /* Freeing thread id */
45 WORD magic; /* Magic number */
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 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
451 else
453 /* Turn off PREV_FREE flag in next block */
454 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
455 if (pNext < (char *)subheap + subheap->size)
456 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
460 /***********************************************************************
461 * HEAP_InitSubHeap
463 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
464 DWORD commitSize, DWORD totalSize )
466 SUBHEAP *subheap = (SUBHEAP *)address;
467 WORD selector = 0;
468 FREE_LIST_ENTRY *pEntry;
469 int i;
471 /* Commit memory */
473 if (flags & HEAP_SHARED)
474 commitSize = totalSize; /* always commit everything in a shared heap */
475 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
477 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
478 commitSize, (DWORD)address );
479 return FALSE;
482 /* Allocate a selector if needed */
484 if (flags & HEAP_WINE_SEGPTR)
486 selector = SELECTOR_AllocBlock( address, totalSize,
487 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
488 ? SEGMENT_CODE : SEGMENT_DATA,
489 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
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 );
540 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
543 /* Create the first free block */
545 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
546 subheap->size - subheap->headerSize );
548 return TRUE;
551 /***********************************************************************
552 * HEAP_CreateSubHeap
554 * Create a sub-heap of the given size.
555 * If heap == NULL, creates a main heap.
557 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
558 DWORD commitSize, DWORD totalSize )
560 LPVOID address;
562 /* Round-up sizes on a 64K boundary */
564 if (flags & HEAP_WINE_SEGPTR)
566 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
568 else
570 totalSize = (totalSize + 0xffff) & 0xffff0000;
571 commitSize = (commitSize + 0xffff) & 0xffff0000;
572 if (!commitSize) commitSize = 0x10000;
573 if (totalSize < commitSize) totalSize = commitSize;
576 /* Allocate the memory block */
578 if (!(address = VirtualAlloc( NULL, totalSize,
579 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
581 WARN("Could not VirtualAlloc %08lx bytes\n",
582 totalSize );
583 return NULL;
586 /* Initialize subheap */
588 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
589 address, flags, commitSize, totalSize ))
591 VirtualFree( address, 0, MEM_RELEASE );
592 return NULL;
595 return (SUBHEAP *)address;
599 /***********************************************************************
600 * HEAP_FindFreeBlock
602 * Find a free block at least as large as the requested size, and make sure
603 * the requested size is committed.
605 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
606 SUBHEAP **ppSubHeap )
608 SUBHEAP *subheap;
609 ARENA_FREE *pArena;
610 FREE_LIST_ENTRY *pEntry = heap->freeList;
612 /* Find a suitable free list, and in it find a block large enough */
614 while (pEntry->size < size) pEntry++;
615 pArena = pEntry->arena.next;
616 while (pArena != &heap->freeList[0].arena)
618 if (pArena->size > size)
620 subheap = HEAP_FindSubHeap( heap, pArena );
621 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
622 + size + HEAP_MIN_BLOCK_SIZE))
623 return NULL;
624 *ppSubHeap = subheap;
625 return pArena;
628 pArena = pArena->next;
631 /* If no block was found, attempt to grow the heap */
633 if (!(heap->flags & HEAP_GROWABLE))
635 WARN("Not enough space in heap %08lx for %08lx bytes\n",
636 (DWORD)heap, size );
637 return NULL;
639 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
640 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
641 max( HEAP_DEF_SIZE, size ) )))
642 return NULL;
644 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
645 (DWORD)subheap, size, (DWORD)heap );
647 *ppSubHeap = subheap;
648 return (ARENA_FREE *)(subheap + 1);
652 /***********************************************************************
653 * HEAP_IsValidArenaPtr
655 * Check that the pointer is inside the range possible for arenas.
657 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
659 int i;
660 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
661 if (!subheap) return FALSE;
662 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
663 if (subheap != &heap->subheap) return FALSE;
664 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
665 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
666 return FALSE;
670 /***********************************************************************
671 * HEAP_ValidateFreeArena
673 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
675 char *heapEnd = (char *)subheap + subheap->size;
677 /* Check magic number */
678 if (pArena->magic != ARENA_FREE_MAGIC)
680 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
681 (DWORD)subheap->heap, (DWORD)pArena );
682 return FALSE;
684 /* Check size flags */
685 if (!(pArena->size & ARENA_FLAG_FREE) ||
686 (pArena->size & ARENA_FLAG_PREV_FREE))
688 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
689 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
691 /* Check arena size */
692 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
694 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
695 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
696 return FALSE;
698 /* Check that next pointer is valid */
699 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
701 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
702 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
703 return FALSE;
705 /* Check that next arena is free */
706 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
707 (pArena->next->magic != ARENA_FREE_MAGIC))
709 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
710 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
711 return FALSE;
713 /* Check that prev pointer is valid */
714 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
716 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
717 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
718 return FALSE;
720 /* Check that prev arena is free */
721 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
722 (pArena->prev->magic != ARENA_FREE_MAGIC))
724 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
725 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
726 return FALSE;
728 /* Check that next block has PREV_FREE flag */
729 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
731 if (!(*(DWORD *)((char *)(pArena + 1) +
732 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
734 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
735 (DWORD)subheap->heap, (DWORD)pArena );
736 return FALSE;
738 /* Check next block back pointer */
739 if (*((ARENA_FREE **)((char *)(pArena + 1) +
740 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
742 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
743 (DWORD)subheap->heap, (DWORD)pArena,
744 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
745 return FALSE;
748 return TRUE;
752 /***********************************************************************
753 * HEAP_ValidateInUseArena
755 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
757 char *heapEnd = (char *)subheap + subheap->size;
759 /* Check magic number */
760 if (pArena->magic != ARENA_INUSE_MAGIC)
762 if (quiet == NOISY) {
763 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
764 (DWORD)subheap->heap, (DWORD)pArena );
765 if (TRACE_ON(heap))
766 HEAP_Dump( subheap->heap );
767 } else if (WARN_ON(heap)) {
768 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
769 (DWORD)subheap->heap, (DWORD)pArena );
770 if (TRACE_ON(heap))
771 HEAP_Dump( subheap->heap );
773 return FALSE;
775 /* Check size flags */
776 if (pArena->size & ARENA_FLAG_FREE)
778 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
779 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
781 /* Check arena size */
782 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
784 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
785 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
786 return FALSE;
788 /* Check next arena PREV_FREE flag */
789 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
790 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
792 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
793 (DWORD)subheap->heap, (DWORD)pArena );
794 return FALSE;
796 /* Check prev free arena */
797 if (pArena->size & ARENA_FLAG_PREV_FREE)
799 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
800 /* Check prev pointer */
801 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
803 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
804 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
805 return FALSE;
807 /* Check that prev arena is free */
808 if (!(pPrev->size & ARENA_FLAG_FREE) ||
809 (pPrev->magic != ARENA_FREE_MAGIC))
811 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
812 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
813 return FALSE;
815 /* Check that prev arena is really the previous block */
816 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
818 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
819 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
820 return FALSE;
823 return TRUE;
827 /***********************************************************************
828 * HEAP_IsInsideHeap
829 * Checks whether the pointer points to a block inside a given heap.
831 * NOTES
832 * Should this return BOOL32?
834 * RETURNS
835 * !0: Success
836 * 0: Failure
838 int HEAP_IsInsideHeap(
839 HANDLE heap, /* [in] Heap */
840 DWORD flags, /* [in] Flags */
841 LPCVOID ptr /* [in] Pointer */
843 HEAP *heapPtr = HEAP_GetPtr( heap );
844 SUBHEAP *subheap;
845 int ret;
847 /* Validate the parameters */
849 if (!heapPtr) return 0;
850 flags |= heapPtr->flags;
851 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
852 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
853 (((char *)ptr >= (char *)subheap + subheap->headerSize
854 + sizeof(ARENA_INUSE))));
855 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
856 return ret;
860 /***********************************************************************
861 * HEAP_GetSegptr
863 * Transform a linear pointer into a SEGPTR. The pointer must have been
864 * allocated from a HEAP_WINE_SEGPTR heap.
866 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
868 HEAP *heapPtr = HEAP_GetPtr( heap );
869 SUBHEAP *subheap;
870 SEGPTR ret;
872 /* Validate the parameters */
874 if (!heapPtr) return 0;
875 flags |= heapPtr->flags;
876 if (!(flags & HEAP_WINE_SEGPTR))
878 ERR("Heap %08x is not a SEGPTR heap\n",
879 heap );
880 return 0;
882 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
884 /* Get the subheap */
886 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
888 ERR("%p is not inside heap %08x\n",
889 ptr, heap );
890 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
891 return 0;
894 /* Build the SEGPTR */
896 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
897 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
898 return ret;
901 /***********************************************************************
902 * HEAP_IsRealArena [Internal]
903 * Validates a block is a valid arena.
905 * RETURNS
906 * TRUE: Success
907 * FALSE: Failure
909 static BOOL HEAP_IsRealArena(
910 HANDLE heap, /* [in] Handle to the heap */
911 DWORD flags, /* [in] Bit flags that control access during operation */
912 LPCVOID block, /* [in] Optional pointer to memory block to validate */
913 BOOL quiet /* [in] Flag - if true, HEAP_ValidateInUseArena
914 * does not complain */
916 SUBHEAP *subheap;
917 HEAP *heapPtr = (HEAP *)(heap);
918 BOOL ret = TRUE;
920 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
922 ERR("Invalid heap %08x!\n", heap );
923 return FALSE;
926 flags &= HEAP_NO_SERIALIZE;
927 flags |= heapPtr->flags;
928 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
929 if (!(flags & HEAP_NO_SERIALIZE))
930 EnterCriticalSection( &heapPtr->critSection );
932 if (block)
934 /* Only check this single memory block */
936 /* The following code is really HEAP_IsInsideHeap *
937 * with serialization already done. */
938 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
939 ((char *)block < (char *)subheap + subheap->headerSize
940 + sizeof(ARENA_INUSE)))
942 if (quiet == NOISY)
943 ERR("Heap %08lx: block %08lx is not inside heap\n",
944 (DWORD)heap, (DWORD)block );
945 else if (WARN_ON(heap))
946 WARN("Heap %08lx: block %08lx is not inside heap\n",
947 (DWORD)heap, (DWORD)block );
948 ret = FALSE;
949 } else
950 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
952 if (!(flags & HEAP_NO_SERIALIZE))
953 LeaveCriticalSection( &heapPtr->critSection );
954 return ret;
957 subheap = &heapPtr->subheap;
958 while (subheap && ret)
960 char *ptr = (char *)subheap + subheap->headerSize;
961 while (ptr < (char *)subheap + subheap->size)
963 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
965 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
966 ret = FALSE;
967 break;
969 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
971 else
973 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
974 ret = FALSE;
975 break;
977 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
980 subheap = subheap->next;
983 if (!(flags & HEAP_NO_SERIALIZE))
984 LeaveCriticalSection( &heapPtr->critSection );
985 return ret;
989 /***********************************************************************
990 * HeapCreate (KERNEL32.336)
991 * RETURNS
992 * Handle of heap: Success
993 * NULL: Failure
995 HANDLE WINAPI HeapCreate(
996 DWORD flags, /* [in] Heap allocation flag */
997 DWORD initialSize, /* [in] Initial heap size */
998 DWORD maxSize /* [in] Maximum heap size */
1000 SUBHEAP *subheap;
1002 if ( flags & HEAP_SHARED ) {
1003 FIXME ( "Shared Heap requested, returning system heap.\n" );
1004 return SystemHeap;
1007 /* Allocate the heap block */
1009 if (!maxSize)
1011 maxSize = HEAP_DEF_SIZE;
1012 flags |= HEAP_GROWABLE;
1014 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1016 SetLastError( ERROR_OUTOFMEMORY );
1017 return 0;
1020 /* link it into the per-process heap list */
1021 if (processHeap)
1023 HEAP *heapPtr = subheap->heap;
1024 EnterCriticalSection( &processHeap->critSection );
1025 heapPtr->next = firstHeap;
1026 firstHeap = heapPtr;
1027 LeaveCriticalSection( &processHeap->critSection );
1029 else /* assume the first heap we create is the process main heap */
1031 processHeap = subheap->heap;
1034 return (HANDLE)subheap;
1037 /***********************************************************************
1038 * HeapDestroy (KERNEL32.337)
1039 * RETURNS
1040 * TRUE: Success
1041 * FALSE: Failure
1043 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1045 HEAP *heapPtr = HEAP_GetPtr( heap );
1046 SUBHEAP *subheap;
1048 if ( heap == SystemHeap ) {
1049 FIXME ( "attempt to destroy system heap, returning TRUE!\n" );
1050 return TRUE;
1053 TRACE("%08x\n", heap );
1054 if (!heapPtr) return FALSE;
1056 if (heapPtr == processHeap) /* cannot delete the main process heap */
1058 SetLastError( ERROR_INVALID_PARAMETER );
1059 return FALSE;
1061 else /* remove it from the per-process list */
1063 HEAP **pptr;
1064 EnterCriticalSection( &processHeap->critSection );
1065 pptr = &firstHeap;
1066 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1067 if (*pptr) *pptr = (*pptr)->next;
1068 LeaveCriticalSection( &processHeap->critSection );
1071 DeleteCriticalSection( &heapPtr->critSection );
1072 subheap = &heapPtr->subheap;
1073 while (subheap)
1075 SUBHEAP *next = subheap->next;
1076 if (subheap->selector) FreeSelector16( subheap->selector );
1077 VirtualFree( subheap, 0, MEM_RELEASE );
1078 subheap = next;
1080 return TRUE;
1084 /***********************************************************************
1085 * HeapAlloc (KERNEL32.334)
1086 * RETURNS
1087 * Pointer to allocated memory block
1088 * NULL: Failure
1090 LPVOID WINAPI HeapAlloc(
1091 HANDLE heap, /* [in] Handle of private heap block */
1092 DWORD flags, /* [in] Heap allocation control flags */
1093 DWORD size /* [in] Number of bytes to allocate */
1095 ARENA_FREE *pArena;
1096 ARENA_INUSE *pInUse;
1097 SUBHEAP *subheap;
1098 HEAP *heapPtr = HEAP_GetPtr( heap );
1100 /* Validate the parameters */
1102 if (!heapPtr) return NULL;
1103 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1104 flags |= heapPtr->flags;
1105 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1106 size = (size + 3) & ~3;
1107 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1109 /* Locate a suitable free block */
1111 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1113 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1114 heap, flags, size );
1115 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1116 SetLastError( ERROR_COMMITMENT_LIMIT );
1117 return NULL;
1120 /* Remove the arena from the free list */
1122 pArena->next->prev = pArena->prev;
1123 pArena->prev->next = pArena->next;
1125 /* Build the in-use arena */
1127 pInUse = (ARENA_INUSE *)pArena;
1128 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1129 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1130 pInUse->callerEIP = GET_EIP();
1131 pInUse->threadId = GetCurrentTask();
1132 pInUse->magic = ARENA_INUSE_MAGIC;
1134 /* Shrink the block */
1136 HEAP_ShrinkBlock( subheap, pInUse, size );
1138 if (flags & HEAP_ZERO_MEMORY)
1139 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1140 else if (TRACE_ON(heap))
1141 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1143 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1145 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1146 heap, flags, size, (DWORD)(pInUse + 1) );
1147 return (LPVOID)(pInUse + 1);
1151 /***********************************************************************
1152 * HeapFree (KERNEL32.338)
1153 * RETURNS
1154 * TRUE: Success
1155 * FALSE: Failure
1157 BOOL WINAPI HeapFree(
1158 HANDLE heap, /* [in] Handle of heap */
1159 DWORD flags, /* [in] Heap freeing flags */
1160 LPVOID ptr /* [in] Address of memory to free */
1162 ARENA_INUSE *pInUse;
1163 SUBHEAP *subheap;
1164 HEAP *heapPtr = HEAP_GetPtr( heap );
1166 /* Validate the parameters */
1168 if (!heapPtr) return FALSE;
1169 if (!ptr) /* Freeing a NULL ptr is doesn't indicate an error in Win2k */
1171 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1172 heap, flags, (DWORD)ptr );
1173 return TRUE;
1176 flags &= HEAP_NO_SERIALIZE;
1177 flags |= heapPtr->flags;
1178 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1179 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1181 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1182 SetLastError( ERROR_INVALID_PARAMETER );
1183 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1184 heap, flags, (DWORD)ptr );
1185 return FALSE;
1188 /* Turn the block into a free block */
1190 pInUse = (ARENA_INUSE *)ptr - 1;
1191 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1192 HEAP_MakeInUseBlockFree( subheap, pInUse );
1194 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1196 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1197 heap, flags, (DWORD)ptr );
1198 return TRUE;
1202 /***********************************************************************
1203 * HeapReAlloc (KERNEL32.340)
1204 * RETURNS
1205 * Pointer to reallocated memory block
1206 * NULL: Failure
1208 LPVOID WINAPI HeapReAlloc(
1209 HANDLE heap, /* [in] Handle of heap block */
1210 DWORD flags, /* [in] Heap reallocation flags */
1211 LPVOID ptr, /* [in] Address of memory to reallocate */
1212 DWORD size /* [in] Number of bytes to reallocate */
1214 ARENA_INUSE *pArena;
1215 DWORD oldSize;
1216 HEAP *heapPtr;
1217 SUBHEAP *subheap;
1219 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1220 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1222 /* Validate the parameters */
1224 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1225 HEAP_REALLOC_IN_PLACE_ONLY;
1226 flags |= heapPtr->flags;
1227 size = (size + 3) & ~3;
1228 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1230 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1231 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1233 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1234 SetLastError( ERROR_INVALID_PARAMETER );
1235 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1236 heap, flags, (DWORD)ptr, size );
1237 return NULL;
1240 /* Check if we need to grow the block */
1242 pArena = (ARENA_INUSE *)ptr - 1;
1243 pArena->threadId = GetCurrentTask();
1244 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1245 oldSize = (pArena->size & ARENA_SIZE_MASK);
1246 if (size > oldSize)
1248 char *pNext = (char *)(pArena + 1) + oldSize;
1249 if ((pNext < (char *)subheap + subheap->size) &&
1250 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1251 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1253 /* The next block is free and large enough */
1254 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1255 pFree->next->prev = pFree->prev;
1256 pFree->prev->next = pFree->next;
1257 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1258 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1259 + size + HEAP_MIN_BLOCK_SIZE))
1261 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1262 SetLastError( ERROR_OUTOFMEMORY );
1263 return NULL;
1265 HEAP_ShrinkBlock( subheap, pArena, size );
1267 else /* Do it the hard way */
1269 ARENA_FREE *pNew;
1270 ARENA_INUSE *pInUse;
1271 SUBHEAP *newsubheap;
1273 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1274 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1276 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1277 SetLastError( ERROR_OUTOFMEMORY );
1278 return NULL;
1281 /* Build the in-use arena */
1283 pNew->next->prev = pNew->prev;
1284 pNew->prev->next = pNew->next;
1285 pInUse = (ARENA_INUSE *)pNew;
1286 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1287 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1288 pInUse->threadId = GetCurrentTask();
1289 pInUse->magic = ARENA_INUSE_MAGIC;
1290 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1291 memcpy( pInUse + 1, pArena + 1, oldSize );
1293 /* Free the previous block */
1295 HEAP_MakeInUseBlockFree( subheap, pArena );
1296 subheap = newsubheap;
1297 pArena = pInUse;
1300 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1302 /* Clear the extra bytes if needed */
1304 if (size > oldSize)
1306 if (flags & HEAP_ZERO_MEMORY)
1307 memset( (char *)(pArena + 1) + oldSize, 0,
1308 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1309 else if (TRACE_ON(heap))
1310 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1311 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1314 /* Return the new arena */
1316 pArena->callerEIP = GET_EIP();
1317 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1319 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1320 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1321 return (LPVOID)(pArena + 1);
1325 /***********************************************************************
1326 * HeapCompact (KERNEL32.335)
1328 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1330 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1331 return 0;
1335 /***********************************************************************
1336 * HeapLock (KERNEL32.339)
1337 * Attempts to acquire the critical section object for a specified heap.
1339 * RETURNS
1340 * TRUE: Success
1341 * FALSE: Failure
1343 BOOL WINAPI HeapLock(
1344 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1346 HEAP *heapPtr = HEAP_GetPtr( heap );
1347 if (!heapPtr) return FALSE;
1348 EnterCriticalSection( &heapPtr->critSection );
1349 return TRUE;
1353 /***********************************************************************
1354 * HeapUnlock (KERNEL32.342)
1355 * Releases ownership of the critical section object.
1357 * RETURNS
1358 * TRUE: Success
1359 * FALSE: Failure
1361 BOOL WINAPI HeapUnlock(
1362 HANDLE heap /* [in] Handle to the heap to unlock */
1364 HEAP *heapPtr = HEAP_GetPtr( heap );
1365 if (!heapPtr) return FALSE;
1366 LeaveCriticalSection( &heapPtr->critSection );
1367 return TRUE;
1371 /***********************************************************************
1372 * HeapSize (KERNEL32.341)
1373 * RETURNS
1374 * Size in bytes of allocated memory
1375 * 0xffffffff: Failure
1377 DWORD WINAPI HeapSize(
1378 HANDLE heap, /* [in] Handle of heap */
1379 DWORD flags, /* [in] Heap size control flags */
1380 LPVOID ptr /* [in] Address of memory to return size for */
1382 DWORD ret;
1383 HEAP *heapPtr = HEAP_GetPtr( heap );
1385 if (!heapPtr) return FALSE;
1386 flags &= HEAP_NO_SERIALIZE;
1387 flags |= heapPtr->flags;
1388 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1389 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1391 SetLastError( ERROR_INVALID_PARAMETER );
1392 ret = 0xffffffff;
1394 else
1396 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1397 ret = pArena->size & ARENA_SIZE_MASK;
1399 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1401 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1402 heap, flags, (DWORD)ptr, ret );
1403 return ret;
1407 /***********************************************************************
1408 * HeapValidate (KERNEL32.343)
1409 * Validates a specified heap.
1411 * NOTES
1412 * Flags is ignored.
1414 * RETURNS
1415 * TRUE: Success
1416 * FALSE: Failure
1418 BOOL WINAPI HeapValidate(
1419 HANDLE heap, /* [in] Handle to the heap */
1420 DWORD flags, /* [in] Bit flags that control access during operation */
1421 LPCVOID block /* [in] Optional pointer to memory block to validate */
1424 return HEAP_IsRealArena( heap, flags, block, QUIET );
1428 /***********************************************************************
1429 * HeapWalk (KERNEL32.344)
1430 * Enumerates the memory blocks in a specified heap.
1431 * See HEAP_Dump() for info on heap structure.
1433 * TODO
1434 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1435 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1437 * RETURNS
1438 * TRUE: Success
1439 * FALSE: Failure
1441 BOOL WINAPI HeapWalk(
1442 HANDLE heap, /* [in] Handle to heap to enumerate */
1443 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1445 HEAP *heapPtr = HEAP_GetPtr(heap);
1446 SUBHEAP *sub, *currentheap = NULL;
1447 BOOL ret = FALSE;
1448 char *ptr;
1449 int region_index = 0;
1451 if (!heapPtr || !entry)
1453 SetLastError(ERROR_INVALID_PARAMETER);
1454 return FALSE;
1457 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1459 /* set ptr to the next arena to be examined */
1461 if (!entry->lpData) /* first call (init) ? */
1463 TRACE("begin walking of heap 0x%08x.\n", heap);
1464 /*HEAP_Dump(heapPtr);*/
1465 currentheap = &heapPtr->subheap;
1466 ptr = (char*)currentheap + currentheap->headerSize;
1468 else
1470 ptr = entry->lpData;
1471 sub = &heapPtr->subheap;
1472 while (sub)
1474 if (((char *)ptr >= (char *)sub) &&
1475 ((char *)ptr < (char *)sub + sub->size))
1477 currentheap = sub;
1478 break;
1480 sub = sub->next;
1481 region_index++;
1483 if (currentheap == NULL)
1485 ERR("no matching subheap found, shouldn't happen !\n");
1486 SetLastError(ERROR_NO_MORE_ITEMS);
1487 goto HW_end;
1490 ptr += entry->cbData; /* point to next arena */
1491 if (ptr > (char *)currentheap + currentheap->size - 1)
1492 { /* proceed with next subheap */
1493 if (!(currentheap = currentheap->next))
1494 { /* successfully finished */
1495 TRACE("end reached.\n");
1496 SetLastError(ERROR_NO_MORE_ITEMS);
1497 goto HW_end;
1499 ptr = (char*)currentheap + currentheap->headerSize;
1503 entry->wFlags = 0;
1504 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1506 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1508 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1510 entry->lpData = pArena + 1;
1511 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1512 entry->cbOverhead = sizeof(ARENA_FREE);
1513 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1515 else
1517 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1519 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1521 entry->lpData = pArena + 1;
1522 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1523 entry->cbOverhead = sizeof(ARENA_INUSE);
1524 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1525 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1526 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1529 entry->iRegionIndex = region_index;
1531 /* first element of heap ? */
1532 if (ptr == (char *)(currentheap + currentheap->headerSize))
1534 entry->wFlags |= PROCESS_HEAP_REGION;
1535 entry->Foo.Region.dwCommittedSize = currentheap->commitSize;
1536 entry->Foo.Region.dwUnCommittedSize =
1537 currentheap->size - currentheap->commitSize;
1538 entry->Foo.Region.lpFirstBlock = /* first valid block */
1539 currentheap + currentheap->headerSize;
1540 entry->Foo.Region.lpLastBlock = /* first invalid block */
1541 currentheap + currentheap->size;
1543 ret = TRUE;
1545 HW_end:
1546 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1548 return ret;
1552 /***********************************************************************
1553 * HEAP_CreateSystemHeap
1555 * Create the system heap.
1557 BOOL HEAP_CreateSystemHeap(void)
1559 SYSTEM_HEAP_DESCR *descr;
1560 HANDLE heap;
1561 HEAP *heapPtr;
1562 int created;
1564 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1565 0, HEAP_DEF_SIZE, "__SystemHeap" );
1566 if (!map) return FALSE;
1567 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1569 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1571 /* pre-defined address not available, use any one */
1572 fprintf( stderr, "Warning: system heap base address %p not available\n",
1573 SYSTEM_HEAP_BASE );
1574 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1576 CloseHandle( map );
1577 return FALSE;
1580 heap = (HANDLE)heapPtr;
1582 if (created) /* newly created heap */
1584 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1585 HeapLock( heap );
1586 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1587 assert( descr );
1589 else
1591 /* wait for the heap to be initialized */
1592 while (!heapPtr->private) Sleep(1);
1593 HeapLock( heap );
1594 /* remap it to the right address if necessary */
1595 if (heapPtr->subheap.heap != heapPtr)
1597 void *base = heapPtr->subheap.heap;
1598 HeapUnlock( heap );
1599 UnmapViewOfFile( heapPtr );
1600 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1602 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1603 CloseHandle( map );
1604 return FALSE;
1606 heap = (HANDLE)heapPtr;
1607 HeapLock( heap );
1609 descr = heapPtr->private;
1610 assert( descr );
1612 SystemHeap = heap;
1613 SystemHeapDescr = descr;
1614 HeapUnlock( heap );
1615 CloseHandle( map );
1616 return TRUE;
1620 /***********************************************************************
1621 * GetProcessHeap (KERNEL32.259)
1623 HANDLE WINAPI GetProcessHeap(void)
1625 return (HANDLE)processHeap;
1629 /***********************************************************************
1630 * GetProcessHeaps (KERNEL32.376)
1632 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1634 DWORD total;
1635 HEAP *ptr;
1637 if (!processHeap) return 0; /* should never happen */
1638 total = 1; /* main heap */
1639 EnterCriticalSection( &processHeap->critSection );
1640 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1641 if (total <= count)
1643 *heaps++ = (HANDLE)processHeap;
1644 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1646 LeaveCriticalSection( &processHeap->critSection );
1647 return total;
1651 /***********************************************************************
1652 * HEAP_strdupA
1654 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1656 LPSTR p = HeapAlloc( heap, flags, strlen(str) + 1 );
1657 if(p) {
1658 SET_EIP(p);
1659 strcpy( p, str );
1661 return p;
1665 /***********************************************************************
1666 * HEAP_strdupW
1668 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1670 INT len = lstrlenW(str) + 1;
1671 LPWSTR p = HeapAlloc( heap, flags, len * sizeof(WCHAR) );
1672 if(p) {
1673 SET_EIP(p);
1674 strcpyW( p, str );
1676 return p;
1680 /***********************************************************************
1681 * HEAP_strdupAtoW
1683 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1685 LPWSTR ret;
1687 if (!str) return NULL;
1688 ret = HeapAlloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1689 if (ret) {
1690 SET_EIP(ret);
1691 lstrcpyAtoW( ret, str );
1693 return ret;
1697 /***********************************************************************
1698 * HEAP_strdupWtoA
1700 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1702 LPSTR ret;
1703 INT len;
1705 if (!str) return NULL;
1706 len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
1707 ret = HeapAlloc( heap, flags, len );
1708 if(ret) {
1709 SET_EIP(ret);
1710 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
1712 return ret;
1717 /***********************************************************************
1718 * 32-bit local heap functions (Win95; undocumented)
1721 #define HTABLE_SIZE 0x10000
1722 #define HTABLE_PAGESIZE 0x1000
1723 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1725 #include "pshpack1.h"
1726 typedef struct _LOCAL32HEADER
1728 WORD freeListFirst[HTABLE_NPAGES];
1729 WORD freeListSize[HTABLE_NPAGES];
1730 WORD freeListLast[HTABLE_NPAGES];
1732 DWORD selectorTableOffset;
1733 WORD selectorTableSize;
1734 WORD selectorDelta;
1736 DWORD segment;
1737 LPBYTE base;
1739 DWORD limit;
1740 DWORD flags;
1742 DWORD magic;
1743 HANDLE heap;
1745 } LOCAL32HEADER;
1746 #include "poppack.h"
1748 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1750 /***********************************************************************
1751 * Local32Init (KERNEL.208)
1753 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1754 DWORD heapSize, DWORD flags )
1756 DWORD totSize, segSize = 0;
1757 LPBYTE base;
1758 LOCAL32HEADER *header;
1759 HEAP *heap;
1760 WORD *selectorTable;
1761 WORD selectorEven, selectorOdd;
1762 int i, nrBlocks;
1764 /* Determine new heap size */
1766 if ( segment )
1768 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1769 return 0;
1770 else
1771 segSize++;
1774 if ( heapSize == -1L )
1775 heapSize = 1024L*1024L; /* FIXME */
1777 heapSize = (heapSize + 0xffff) & 0xffff0000;
1778 segSize = (segSize + 0x0fff) & 0xfffff000;
1779 totSize = segSize + HTABLE_SIZE + heapSize;
1782 /* Allocate memory and initialize heap */
1784 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1785 return 0;
1787 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1788 MEM_COMMIT, PAGE_READWRITE ) )
1790 VirtualFree( base, 0, MEM_RELEASE );
1791 return 0;
1794 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1795 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1797 VirtualFree( base, 0, MEM_RELEASE );
1798 return 0;
1802 /* Set up header and handle table */
1804 header = (LOCAL32HEADER *)(base + segSize);
1805 header->base = base;
1806 header->limit = HTABLE_PAGESIZE-1;
1807 header->flags = 0;
1808 header->magic = LOCAL32_MAGIC;
1809 header->heap = (HANDLE)heap;
1811 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1812 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1813 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1815 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1816 *(DWORD *)((LPBYTE)header + i) = i+4;
1818 header->freeListFirst[1] = 0xffff;
1821 /* Set up selector table */
1823 nrBlocks = (totSize + 0x7fff) >> 15;
1824 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1825 selectorEven = SELECTOR_AllocBlock( base, totSize,
1826 SEGMENT_DATA, FALSE, FALSE );
1827 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1828 SEGMENT_DATA, FALSE, FALSE );
1830 if ( !selectorTable || !selectorEven || !selectorOdd )
1832 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1833 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1834 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1835 HeapDestroy( header->heap );
1836 VirtualFree( base, 0, MEM_RELEASE );
1837 return 0;
1840 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1841 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1842 header->selectorDelta = selectorEven - selectorOdd;
1843 header->segment = segment? segment : selectorEven;
1845 for (i = 0; i < nrBlocks; i++)
1846 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1847 : selectorEven + ((i >> 1) << __AHSHIFT);
1849 /* Move old segment */
1851 if ( segment )
1853 /* FIXME: This is somewhat ugly and relies on implementation
1854 details about 16-bit global memory handles ... */
1856 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1857 memcpy( base, oldBase, segSize );
1858 GLOBAL_MoveBlock( segment, base, totSize );
1859 HeapFree( SystemHeap, 0, oldBase );
1862 return (HANDLE)header;
1865 /***********************************************************************
1866 * Local32_SearchHandle
1868 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1870 LPDWORD handle;
1872 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1873 handle < (LPDWORD)((LPBYTE)header + header->limit);
1874 handle++)
1876 if (*handle == addr)
1877 return handle;
1880 return NULL;
1883 /***********************************************************************
1884 * Local32_ToHandle
1886 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1887 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1889 *handle = NULL;
1890 *ptr = NULL;
1892 switch (type)
1894 case -2: /* 16:16 pointer, no handles */
1895 *ptr = PTR_SEG_TO_LIN( addr );
1896 *handle = (LPDWORD)*ptr;
1897 break;
1899 case -1: /* 32-bit offset, no handles */
1900 *ptr = header->base + addr;
1901 *handle = (LPDWORD)*ptr;
1902 break;
1904 case 0: /* handle */
1905 if ( addr >= sizeof(LOCAL32HEADER)
1906 && addr < header->limit && !(addr & 3)
1907 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1909 *handle = (LPDWORD)((LPBYTE)header + addr);
1910 *ptr = header->base + **handle;
1912 break;
1914 case 1: /* 16:16 pointer */
1915 *ptr = PTR_SEG_TO_LIN( addr );
1916 *handle = Local32_SearchHandle( header, *ptr - header->base );
1917 break;
1919 case 2: /* 32-bit offset */
1920 *ptr = header->base + addr;
1921 *handle = Local32_SearchHandle( header, *ptr - header->base );
1922 break;
1926 /***********************************************************************
1927 * Local32_FromHandle
1929 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1930 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1932 switch (type)
1934 case -2: /* 16:16 pointer */
1935 case 1:
1937 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1938 DWORD offset = (LPBYTE)ptr - header->base;
1939 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1941 break;
1943 case -1: /* 32-bit offset */
1944 case 2:
1945 *addr = ptr - header->base;
1946 break;
1948 case 0: /* handle */
1949 *addr = (LPBYTE)handle - (LPBYTE)header;
1950 break;
1954 /***********************************************************************
1955 * Local32Alloc (KERNEL.209)
1957 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1959 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1960 LPDWORD handle;
1961 LPBYTE ptr;
1962 DWORD addr;
1964 /* Allocate memory */
1965 ptr = HeapAlloc( header->heap,
1966 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1967 if (!ptr) return 0;
1970 /* Allocate handle if requested */
1971 if (type >= 0)
1973 int page, i;
1975 /* Find first page of handle table with free slots */
1976 for (page = 0; page < HTABLE_NPAGES; page++)
1977 if (header->freeListFirst[page] != 0)
1978 break;
1979 if (page == HTABLE_NPAGES)
1981 WARN("Out of handles!\n" );
1982 HeapFree( header->heap, 0, ptr );
1983 return 0;
1986 /* If virgin page, initialize it */
1987 if (header->freeListFirst[page] == 0xffff)
1989 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1990 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1992 WARN("Cannot grow handle table!\n" );
1993 HeapFree( header->heap, 0, ptr );
1994 return 0;
1997 header->limit += HTABLE_PAGESIZE;
1999 header->freeListFirst[page] = 0;
2000 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2001 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2003 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2004 *(DWORD *)((LPBYTE)header + i) = i+4;
2006 if (page < HTABLE_NPAGES-1)
2007 header->freeListFirst[page+1] = 0xffff;
2010 /* Allocate handle slot from page */
2011 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2012 if (--header->freeListSize[page] == 0)
2013 header->freeListFirst[page] = header->freeListLast[page] = 0;
2014 else
2015 header->freeListFirst[page] = *handle;
2017 /* Store 32-bit offset in handle slot */
2018 *handle = ptr - header->base;
2020 else
2022 handle = (LPDWORD)ptr;
2023 header->flags |= 1;
2027 /* Convert handle to requested output type */
2028 Local32_FromHandle( header, type, &addr, handle, ptr );
2029 return addr;
2032 /***********************************************************************
2033 * Local32ReAlloc (KERNEL.210)
2035 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2036 DWORD size, DWORD flags )
2038 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2039 LPDWORD handle;
2040 LPBYTE ptr;
2042 if (!addr)
2043 return Local32Alloc16( heap, size, type, flags );
2045 /* Retrieve handle and pointer */
2046 Local32_ToHandle( header, type, addr, &handle, &ptr );
2047 if (!handle) return FALSE;
2049 /* Reallocate memory block */
2050 ptr = HeapReAlloc( header->heap,
2051 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2052 ptr, size );
2053 if (!ptr) return 0;
2055 /* Modify handle */
2056 if (type >= 0)
2057 *handle = ptr - header->base;
2058 else
2059 handle = (LPDWORD)ptr;
2061 /* Convert handle to requested output type */
2062 Local32_FromHandle( header, type, &addr, handle, ptr );
2063 return addr;
2066 /***********************************************************************
2067 * Local32Free (KERNEL.211)
2069 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2071 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2072 LPDWORD handle;
2073 LPBYTE ptr;
2075 /* Retrieve handle and pointer */
2076 Local32_ToHandle( header, type, addr, &handle, &ptr );
2077 if (!handle) return FALSE;
2079 /* Free handle if necessary */
2080 if (type >= 0)
2082 int offset = (LPBYTE)handle - (LPBYTE)header;
2083 int page = offset >> 12;
2085 /* Return handle slot to page free list */
2086 if (header->freeListSize[page]++ == 0)
2087 header->freeListFirst[page] = header->freeListLast[page] = offset;
2088 else
2089 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2090 header->freeListLast[page] = offset;
2092 *handle = 0;
2094 /* Shrink handle table when possible */
2095 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2097 if ( VirtualFree( (LPBYTE)header +
2098 (header->limit & ~(HTABLE_PAGESIZE-1)),
2099 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2100 break;
2102 header->limit -= HTABLE_PAGESIZE;
2103 header->freeListFirst[page] = 0xffff;
2104 page--;
2108 /* Free memory */
2109 return HeapFree( header->heap, 0, ptr );
2112 /***********************************************************************
2113 * Local32Translate (KERNEL.213)
2115 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2117 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2118 LPDWORD handle;
2119 LPBYTE ptr;
2121 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2122 if (!handle) return 0;
2124 Local32_FromHandle( header, type2, &addr, handle, ptr );
2125 return addr;
2128 /***********************************************************************
2129 * Local32Size (KERNEL.214)
2131 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2133 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2134 LPDWORD handle;
2135 LPBYTE ptr;
2137 Local32_ToHandle( header, type, addr, &handle, &ptr );
2138 if (!handle) return 0;
2140 return HeapSize( header->heap, 0, ptr );
2143 /***********************************************************************
2144 * Local32ValidHandle (KERNEL.215)
2146 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2148 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2149 LPDWORD handle;
2150 LPBYTE ptr;
2152 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2153 return handle != NULL;
2156 /***********************************************************************
2157 * Local32GetSegment (KERNEL.229)
2159 WORD WINAPI Local32GetSegment16( HANDLE heap )
2161 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2162 return header->segment;
2165 /***********************************************************************
2166 * Local32_GetHeap
2168 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2170 WORD selector = GlobalHandleToSel16( handle );
2171 DWORD base = GetSelectorBase( selector );
2172 DWORD limit = GetSelectorLimit16( selector );
2174 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2175 it this way ... */
2177 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2178 return (LOCAL32HEADER *)base;
2180 base += 0x10000;
2181 limit -= 0x10000;
2183 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2184 return (LOCAL32HEADER *)base;
2186 return NULL;
2189 /***********************************************************************
2190 * Local32Info (KERNEL.444) (TOOLHELP.84)
2192 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2194 SUBHEAP *heapPtr;
2195 LPBYTE ptr;
2196 int i;
2198 LOCAL32HEADER *header = Local32_GetHeap( handle );
2199 if ( !header ) return FALSE;
2201 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2202 return FALSE;
2204 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2205 pLocal32Info->dwMemReserved = heapPtr->size;
2206 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2207 pLocal32Info->dwTotalFree = 0L;
2208 pLocal32Info->dwLargestFreeBlock = 0L;
2210 /* Note: Local32 heaps always have only one subheap! */
2211 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2212 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2214 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2216 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2217 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2218 ptr += sizeof(*pArena) + size;
2220 pLocal32Info->dwTotalFree += size;
2221 if ( size > pLocal32Info->dwLargestFreeBlock )
2222 pLocal32Info->dwLargestFreeBlock = size;
2224 else
2226 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2227 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2228 ptr += sizeof(*pArena) + size;
2232 pLocal32Info->dwcFreeHandles = 0;
2233 for ( i = 0; i < HTABLE_NPAGES; i++ )
2235 if ( header->freeListFirst[i] == 0xffff ) break;
2236 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2238 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2240 return TRUE;
2243 /***********************************************************************
2244 * Local32First (KERNEL.445) (TOOLHELP.85)
2246 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2248 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2249 return FALSE;
2252 /***********************************************************************
2253 * Local32Next (KERNEL.446) (TOOLHELP.86)
2255 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2257 FIXME("(%p): stub!\n", pLocal32Entry );
2258 return FALSE;