Fixed COORD structure definition.
[wine/multimedia.git] / memory / heap.c
blobe4f97be2e6c55f7b68f064f77374b44954e7c0a2
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 "selectors.h"
15 #include "global.h"
16 #include "winbase.h"
17 #include "winerror.h"
18 #include "winnt.h"
19 #include "heap.h"
20 #include "toolhelp.h"
21 #include "debugtools.h"
23 DEFAULT_DEBUG_CHANNEL(heap);
25 /* Note: the heap data structures are based on what Pietrek describes in his
26 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
27 * the same, but could be easily adapted if it turns out some programs
28 * require it.
31 typedef struct tagARENA_INUSE
33 DWORD size; /* Block size; must be the first field */
34 WORD threadId; /* Allocating thread id */
35 WORD magic; /* Magic number */
36 void *callerEIP; /* EIP of caller upon allocation */
37 } ARENA_INUSE;
39 typedef struct tagARENA_FREE
41 DWORD size; /* Block size; must be the first field */
42 WORD threadId; /* Freeing thread id */
43 WORD magic; /* Magic number */
44 struct tagARENA_FREE *next; /* Next free arena */
45 struct tagARENA_FREE *prev; /* Prev free arena */
46 } ARENA_FREE;
48 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
49 #define ARENA_FLAG_PREV_FREE 0x00000002
50 #define ARENA_SIZE_MASK 0xfffffffc
51 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
52 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
54 #define ARENA_INUSE_FILLER 0x55
55 #define ARENA_FREE_FILLER 0xaa
57 #define QUIET 1 /* Suppress messages */
58 #define NOISY 0 /* Report all errors */
60 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
62 /* Max size of the blocks on the free lists */
63 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
65 0x20, 0x80, 0x200, 0xffffffff
68 typedef struct
70 DWORD size;
71 ARENA_FREE arena;
72 } FREE_LIST_ENTRY;
74 struct tagHEAP;
76 typedef struct tagSUBHEAP
78 DWORD size; /* Size of the whole sub-heap */
79 DWORD commitSize; /* Committed size of the sub-heap */
80 DWORD headerSize; /* Size of the heap header */
81 struct tagSUBHEAP *next; /* Next sub-heap */
82 struct tagHEAP *heap; /* Main heap structure */
83 DWORD magic; /* Magic number */
84 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
85 } SUBHEAP;
87 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
89 typedef struct tagHEAP
91 SUBHEAP subheap; /* First sub-heap */
92 struct tagHEAP *next; /* Next heap for this process */
93 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
94 CRITICAL_SECTION critSection; /* Critical section for serialization */
95 DWORD flags; /* Heap flags */
96 DWORD magic; /* Magic number */
97 void *private; /* Private pointer for the user of the heap */
98 } HEAP;
100 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
102 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
103 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
105 HANDLE SystemHeap = 0;
106 HANDLE SegptrHeap = 0;
108 SYSTEM_HEAP_DESCR *SystemHeapDescr = 0;
110 static HEAP *processHeap; /* main process heap */
111 static HEAP *firstHeap; /* head of secondary heaps list */
113 /* address where we try to map the system heap */
114 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
116 static BOOL HEAP_IsRealArena( HANDLE heap, DWORD flags, LPCVOID block, BOOL quiet );
118 #ifdef __GNUC__
119 #define GET_EIP() (__builtin_return_address(0))
120 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
121 #else
122 #define GET_EIP() 0
123 #define SET_EIP(ptr) /* nothing */
124 #endif /* __GNUC__ */
126 /***********************************************************************
127 * HEAP_Dump
129 void HEAP_Dump( HEAP *heap )
131 int i;
132 SUBHEAP *subheap;
133 char *ptr;
135 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
136 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
137 (DWORD)heap->next, (DWORD)&heap->subheap );
138 subheap = &heap->subheap;
139 while (subheap->next)
141 DPRINTF( " -> %08lx", (DWORD)subheap->next );
142 subheap = subheap->next;
145 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
146 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
147 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
148 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
149 heap->freeList[i].arena.threadId,
150 (DWORD)heap->freeList[i].arena.prev,
151 (DWORD)heap->freeList[i].arena.next );
153 subheap = &heap->subheap;
154 while (subheap)
156 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
157 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
158 (DWORD)subheap, subheap->size, subheap->commitSize );
160 DPRINTF( "\n Block Stat Size Id\n" );
161 ptr = (char*)subheap + subheap->headerSize;
162 while (ptr < (char *)subheap + subheap->size)
164 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
166 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
167 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
168 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
169 pArena->threadId, (DWORD)pArena->prev,
170 (DWORD)pArena->next);
171 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
172 arenaSize += sizeof(ARENA_FREE);
173 freeSize += pArena->size & ARENA_SIZE_MASK;
175 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
177 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
178 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
179 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
180 pArena->threadId, *((DWORD *)pArena - 1),
181 pArena->callerEIP );
182 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
183 arenaSize += sizeof(ARENA_INUSE);
184 usedSize += pArena->size & ARENA_SIZE_MASK;
186 else
188 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
189 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
190 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
191 pArena->threadId, pArena->callerEIP );
192 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
193 arenaSize += sizeof(ARENA_INUSE);
194 usedSize += pArena->size & ARENA_SIZE_MASK;
197 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
198 subheap->size, subheap->commitSize, freeSize, usedSize,
199 arenaSize, (arenaSize * 100) / subheap->size );
200 subheap = subheap->next;
205 /***********************************************************************
206 * HEAP_GetPtr
207 * RETURNS
208 * Pointer to the heap
209 * NULL: Failure
211 static HEAP *HEAP_GetPtr(
212 HANDLE heap /* [in] Handle to the heap */
214 HEAP *heapPtr = (HEAP *)heap;
215 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
217 ERR("Invalid heap %08x!\n", heap );
218 SetLastError( ERROR_INVALID_HANDLE );
219 return NULL;
221 if (TRACE_ON(heap) && !HEAP_IsRealArena( heap, 0, NULL, NOISY ))
223 HEAP_Dump( heapPtr );
224 assert( FALSE );
225 SetLastError( ERROR_INVALID_HANDLE );
226 return NULL;
228 return heapPtr;
232 /***********************************************************************
233 * HEAP_InsertFreeBlock
235 * Insert a free block into the free list.
237 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
239 FREE_LIST_ENTRY *pEntry = heap->freeList;
240 while (pEntry->size < pArena->size) pEntry++;
241 pArena->size |= ARENA_FLAG_FREE;
242 pArena->next = pEntry->arena.next;
243 pArena->next->prev = pArena;
244 pArena->prev = &pEntry->arena;
245 pEntry->arena.next = pArena;
249 /***********************************************************************
250 * HEAP_FindSubHeap
251 * Find the sub-heap containing a given address.
253 * RETURNS
254 * Pointer: Success
255 * NULL: Failure
257 static SUBHEAP *HEAP_FindSubHeap(
258 HEAP *heap, /* [in] Heap pointer */
259 LPCVOID ptr /* [in] Address */
261 SUBHEAP *sub = &heap->subheap;
262 while (sub)
264 if (((char *)ptr >= (char *)sub) &&
265 ((char *)ptr < (char *)sub + sub->size)) return sub;
266 sub = sub->next;
268 return NULL;
272 /***********************************************************************
273 * HEAP_Commit
275 * Make sure the heap storage is committed up to (not including) ptr.
277 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
279 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
280 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
281 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
282 if (size > subheap->size) size = subheap->size;
283 if (size <= subheap->commitSize) return TRUE;
284 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
285 size - subheap->commitSize, MEM_COMMIT,
286 PAGE_EXECUTE_READWRITE))
288 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
289 size - subheap->commitSize,
290 (DWORD)((char *)subheap + subheap->commitSize),
291 (DWORD)subheap->heap );
292 return FALSE;
294 subheap->commitSize = size;
295 return TRUE;
299 /***********************************************************************
300 * HEAP_Decommit
302 * If possible, decommit the heap storage from (including) 'ptr'.
304 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
306 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
307 DWORD pageMask = VIRTUAL_GetPageSize() - 1;
308 size = (size + pageMask) & ~pageMask; /* Align size on a page boundary */
309 if (size >= subheap->commitSize) return TRUE;
310 if (!VirtualFree( (char *)subheap + size,
311 subheap->commitSize - size, MEM_DECOMMIT ))
313 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
314 subheap->commitSize - size,
315 (DWORD)((char *)subheap + size),
316 (DWORD)subheap->heap );
317 return FALSE;
319 subheap->commitSize = size;
320 return TRUE;
324 /***********************************************************************
325 * HEAP_CreateFreeBlock
327 * Create a free block at a specified address. 'size' is the size of the
328 * whole block, including the new arena.
330 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
332 ARENA_FREE *pFree;
334 /* Create a free arena */
336 pFree = (ARENA_FREE *)ptr;
337 pFree->threadId = GetCurrentTask();
338 pFree->magic = ARENA_FREE_MAGIC;
340 /* If debugging, erase the freed block content */
342 if (TRACE_ON(heap))
344 char *pEnd = (char *)ptr + size;
345 if (pEnd > (char *)subheap + subheap->commitSize)
346 pEnd = (char *)subheap + subheap->commitSize;
347 if (pEnd > (char *)(pFree + 1))
348 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
351 /* Check if next block is free also */
353 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
354 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
356 /* Remove the next arena from the free list */
357 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
358 pNext->next->prev = pNext->prev;
359 pNext->prev->next = pNext->next;
360 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
361 if (TRACE_ON(heap))
362 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
365 /* Set the next block PREV_FREE flag and pointer */
367 if ((char *)ptr + size < (char *)subheap + subheap->size)
369 DWORD *pNext = (DWORD *)((char *)ptr + size);
370 *pNext |= ARENA_FLAG_PREV_FREE;
371 *(ARENA_FREE **)(pNext - 1) = pFree;
374 /* Last, insert the new block into the free list */
376 pFree->size = size - sizeof(*pFree);
377 HEAP_InsertFreeBlock( subheap->heap, pFree );
381 /***********************************************************************
382 * HEAP_MakeInUseBlockFree
384 * Turn an in-use block into a free block. Can also decommit the end of
385 * the heap, and possibly even free the sub-heap altogether.
387 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
389 ARENA_FREE *pFree;
390 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
392 /* Check if we can merge with previous block */
394 if (pArena->size & ARENA_FLAG_PREV_FREE)
396 pFree = *((ARENA_FREE **)pArena - 1);
397 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
398 /* Remove it from the free list */
399 pFree->next->prev = pFree->prev;
400 pFree->prev->next = pFree->next;
402 else pFree = (ARENA_FREE *)pArena;
404 /* Create a free block */
406 HEAP_CreateFreeBlock( subheap, pFree, size );
407 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
408 if ((char *)pFree + size < (char *)subheap + subheap->size)
409 return; /* Not the last block, so nothing more to do */
411 /* Free the whole sub-heap if it's empty and not the original one */
413 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
414 (subheap != &subheap->heap->subheap))
416 SUBHEAP *pPrev = &subheap->heap->subheap;
417 /* Remove the free block from the list */
418 pFree->next->prev = pFree->prev;
419 pFree->prev->next = pFree->next;
420 /* Remove the subheap from the list */
421 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
422 if (pPrev) pPrev->next = subheap->next;
423 /* Free the memory */
424 subheap->magic = 0;
425 if (subheap->selector) FreeSelector16( subheap->selector );
426 VirtualFree( subheap, 0, MEM_RELEASE );
427 return;
430 /* Decommit the end of the heap */
432 if (!(subheap->heap->flags & HEAP_WINE_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
436 /***********************************************************************
437 * HEAP_ShrinkBlock
439 * Shrink an in-use block.
441 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
443 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
445 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
446 (pArena->size & ARENA_SIZE_MASK) - size );
447 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
449 else
451 /* Turn off PREV_FREE flag in next block */
452 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
453 if (pNext < (char *)subheap + subheap->size)
454 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
458 /***********************************************************************
459 * HEAP_InitSubHeap
461 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
462 DWORD commitSize, DWORD totalSize )
464 SUBHEAP *subheap = (SUBHEAP *)address;
465 WORD selector = 0;
466 FREE_LIST_ENTRY *pEntry;
467 int i;
469 /* Commit memory */
471 if (flags & HEAP_WINE_SHARED)
472 commitSize = totalSize; /* always commit everything in a shared heap */
473 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
475 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
476 commitSize, (DWORD)address );
477 return FALSE;
480 /* Allocate a selector if needed */
482 if (flags & HEAP_WINE_SEGPTR)
484 selector = SELECTOR_AllocBlock( address, totalSize,
485 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
486 ? SEGMENT_CODE : SEGMENT_DATA,
487 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
488 if (!selector)
490 ERR("Could not allocate selector\n" );
491 return FALSE;
495 /* Fill the sub-heap structure */
497 subheap->heap = heap;
498 subheap->selector = selector;
499 subheap->size = totalSize;
500 subheap->commitSize = commitSize;
501 subheap->magic = SUBHEAP_MAGIC;
503 if ( subheap != (SUBHEAP *)heap )
505 /* If this is a secondary subheap, insert it into list */
507 subheap->headerSize = sizeof(SUBHEAP);
508 subheap->next = heap->subheap.next;
509 heap->subheap.next = subheap;
511 else
513 /* If this is a primary subheap, initialize main heap */
515 subheap->headerSize = sizeof(HEAP);
516 subheap->next = NULL;
517 heap->next = NULL;
518 heap->flags = flags;
519 heap->magic = HEAP_MAGIC;
521 /* Build the free lists */
523 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
525 pEntry->size = HEAP_freeListSizes[i];
526 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
527 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
528 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
529 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
530 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
531 pEntry->arena.threadId = 0;
532 pEntry->arena.magic = ARENA_FREE_MAGIC;
535 /* Initialize critical section */
537 InitializeCriticalSection( &heap->critSection );
538 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
541 /* Create the first free block */
543 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
544 subheap->size - subheap->headerSize );
546 return TRUE;
549 /***********************************************************************
550 * HEAP_CreateSubHeap
552 * Create a sub-heap of the given size.
553 * If heap == NULL, creates a main heap.
555 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
556 DWORD commitSize, DWORD totalSize )
558 LPVOID address;
560 /* Round-up sizes on a 64K boundary */
562 if (flags & HEAP_WINE_SEGPTR)
564 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
566 else
568 totalSize = (totalSize + 0xffff) & 0xffff0000;
569 commitSize = (commitSize + 0xffff) & 0xffff0000;
570 if (!commitSize) commitSize = 0x10000;
571 if (totalSize < commitSize) totalSize = commitSize;
574 /* Allocate the memory block */
576 if (!(address = VirtualAlloc( NULL, totalSize,
577 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
579 WARN("Could not VirtualAlloc %08lx bytes\n",
580 totalSize );
581 return NULL;
584 /* Initialize subheap */
586 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
587 address, flags, commitSize, totalSize ))
589 VirtualFree( address, 0, MEM_RELEASE );
590 return NULL;
593 return (SUBHEAP *)address;
597 /***********************************************************************
598 * HEAP_FindFreeBlock
600 * Find a free block at least as large as the requested size, and make sure
601 * the requested size is committed.
603 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
604 SUBHEAP **ppSubHeap )
606 SUBHEAP *subheap;
607 ARENA_FREE *pArena;
608 FREE_LIST_ENTRY *pEntry = heap->freeList;
610 /* Find a suitable free list, and in it find a block large enough */
612 while (pEntry->size < size) pEntry++;
613 pArena = pEntry->arena.next;
614 while (pArena != &heap->freeList[0].arena)
616 if (pArena->size > size)
618 subheap = HEAP_FindSubHeap( heap, pArena );
619 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
620 + size + HEAP_MIN_BLOCK_SIZE))
621 return NULL;
622 *ppSubHeap = subheap;
623 return pArena;
626 pArena = pArena->next;
629 /* If no block was found, attempt to grow the heap */
631 if (!(heap->flags & HEAP_GROWABLE))
633 WARN("Not enough space in heap %08lx for %08lx bytes\n",
634 (DWORD)heap, size );
635 return NULL;
637 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
638 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
639 max( HEAP_DEF_SIZE, size ) )))
640 return NULL;
642 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
643 (DWORD)subheap, size, (DWORD)heap );
645 *ppSubHeap = subheap;
646 return (ARENA_FREE *)(subheap + 1);
650 /***********************************************************************
651 * HEAP_IsValidArenaPtr
653 * Check that the pointer is inside the range possible for arenas.
655 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
657 int i;
658 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
659 if (!subheap) return FALSE;
660 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
661 if (subheap != &heap->subheap) return FALSE;
662 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
663 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
664 return FALSE;
668 /***********************************************************************
669 * HEAP_ValidateFreeArena
671 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
673 char *heapEnd = (char *)subheap + subheap->size;
675 /* Check magic number */
676 if (pArena->magic != ARENA_FREE_MAGIC)
678 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
679 (DWORD)subheap->heap, (DWORD)pArena );
680 return FALSE;
682 /* Check size flags */
683 if (!(pArena->size & ARENA_FLAG_FREE) ||
684 (pArena->size & ARENA_FLAG_PREV_FREE))
686 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
687 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
689 /* Check arena size */
690 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
692 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
693 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
694 return FALSE;
696 /* Check that next pointer is valid */
697 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
699 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
700 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
701 return FALSE;
703 /* Check that next arena is free */
704 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
705 (pArena->next->magic != ARENA_FREE_MAGIC))
707 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
708 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
709 return FALSE;
711 /* Check that prev pointer is valid */
712 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
714 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
715 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
716 return FALSE;
718 /* Check that prev arena is free */
719 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
720 (pArena->prev->magic != ARENA_FREE_MAGIC))
722 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
723 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
724 return FALSE;
726 /* Check that next block has PREV_FREE flag */
727 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
729 if (!(*(DWORD *)((char *)(pArena + 1) +
730 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
732 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
733 (DWORD)subheap->heap, (DWORD)pArena );
734 return FALSE;
736 /* Check next block back pointer */
737 if (*((ARENA_FREE **)((char *)(pArena + 1) +
738 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
740 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
741 (DWORD)subheap->heap, (DWORD)pArena,
742 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
743 return FALSE;
746 return TRUE;
750 /***********************************************************************
751 * HEAP_ValidateInUseArena
753 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
755 char *heapEnd = (char *)subheap + subheap->size;
757 /* Check magic number */
758 if (pArena->magic != ARENA_INUSE_MAGIC)
760 if (quiet == NOISY) {
761 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
762 (DWORD)subheap->heap, (DWORD)pArena );
763 if (TRACE_ON(heap))
764 HEAP_Dump( subheap->heap );
765 } else if (WARN_ON(heap)) {
766 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
767 (DWORD)subheap->heap, (DWORD)pArena );
768 if (TRACE_ON(heap))
769 HEAP_Dump( subheap->heap );
771 return FALSE;
773 /* Check size flags */
774 if (pArena->size & ARENA_FLAG_FREE)
776 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
777 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
779 /* Check arena size */
780 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
782 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
783 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
784 return FALSE;
786 /* Check next arena PREV_FREE flag */
787 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
788 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
790 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
791 (DWORD)subheap->heap, (DWORD)pArena );
792 return FALSE;
794 /* Check prev free arena */
795 if (pArena->size & ARENA_FLAG_PREV_FREE)
797 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
798 /* Check prev pointer */
799 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
801 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
802 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
803 return FALSE;
805 /* Check that prev arena is free */
806 if (!(pPrev->size & ARENA_FLAG_FREE) ||
807 (pPrev->magic != ARENA_FREE_MAGIC))
809 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
810 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
811 return FALSE;
813 /* Check that prev arena is really the previous block */
814 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
816 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
817 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
818 return FALSE;
821 return TRUE;
825 /***********************************************************************
826 * HEAP_IsInsideHeap
827 * Checks whether the pointer points to a block inside a given heap.
829 * NOTES
830 * Should this return BOOL32?
832 * RETURNS
833 * !0: Success
834 * 0: Failure
836 int HEAP_IsInsideHeap(
837 HANDLE heap, /* [in] Heap */
838 DWORD flags, /* [in] Flags */
839 LPCVOID ptr /* [in] Pointer */
841 HEAP *heapPtr = HEAP_GetPtr( heap );
842 SUBHEAP *subheap;
843 int ret;
845 /* Validate the parameters */
847 if (!heapPtr) return 0;
848 flags |= heapPtr->flags;
849 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
850 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
851 (((char *)ptr >= (char *)subheap + subheap->headerSize
852 + sizeof(ARENA_INUSE))));
853 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
854 return ret;
858 /***********************************************************************
859 * HEAP_GetSegptr
861 * Transform a linear pointer into a SEGPTR. The pointer must have been
862 * allocated from a HEAP_WINE_SEGPTR heap.
864 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
866 HEAP *heapPtr = HEAP_GetPtr( heap );
867 SUBHEAP *subheap;
868 SEGPTR ret;
870 /* Validate the parameters */
872 if (!heapPtr) return 0;
873 flags |= heapPtr->flags;
874 if (!(flags & HEAP_WINE_SEGPTR))
876 ERR("Heap %08x is not a SEGPTR heap\n",
877 heap );
878 return 0;
880 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
882 /* Get the subheap */
884 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
886 ERR("%p is not inside heap %08x\n",
887 ptr, heap );
888 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
889 return 0;
892 /* Build the SEGPTR */
894 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
895 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
896 return ret;
899 /***********************************************************************
900 * HEAP_IsRealArena [Internal]
901 * Validates a block is a valid arena.
903 * RETURNS
904 * TRUE: Success
905 * FALSE: Failure
907 static BOOL HEAP_IsRealArena(
908 HANDLE heap, /* [in] Handle to the heap */
909 DWORD flags, /* [in] Bit flags that control access during operation */
910 LPCVOID block, /* [in] Optional pointer to memory block to validate */
911 BOOL quiet /* [in] Flag - if true, HEAP_ValidateInUseArena
912 * does not complain */
914 SUBHEAP *subheap;
915 HEAP *heapPtr = (HEAP *)(heap);
916 BOOL ret = TRUE;
918 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
920 ERR("Invalid heap %08x!\n", heap );
921 return FALSE;
924 flags &= HEAP_NO_SERIALIZE;
925 flags |= heapPtr->flags;
926 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
927 if (!(flags & HEAP_NO_SERIALIZE))
928 EnterCriticalSection( &heapPtr->critSection );
930 if (block)
932 /* Only check this single memory block */
934 /* The following code is really HEAP_IsInsideHeap *
935 * with serialization already done. */
936 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
937 ((char *)block < (char *)subheap + subheap->headerSize
938 + sizeof(ARENA_INUSE)))
940 if (quiet == NOISY)
941 ERR("Heap %08lx: block %08lx is not inside heap\n",
942 (DWORD)heap, (DWORD)block );
943 else if (WARN_ON(heap))
944 WARN("Heap %08lx: block %08lx is not inside heap\n",
945 (DWORD)heap, (DWORD)block );
946 ret = FALSE;
947 } else
948 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
950 if (!(flags & HEAP_NO_SERIALIZE))
951 LeaveCriticalSection( &heapPtr->critSection );
952 return ret;
955 subheap = &heapPtr->subheap;
956 while (subheap && ret)
958 char *ptr = (char *)subheap + subheap->headerSize;
959 while (ptr < (char *)subheap + subheap->size)
961 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
963 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
964 ret = FALSE;
965 break;
967 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
969 else
971 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
972 ret = FALSE;
973 break;
975 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
978 subheap = subheap->next;
981 if (!(flags & HEAP_NO_SERIALIZE))
982 LeaveCriticalSection( &heapPtr->critSection );
983 return ret;
987 /***********************************************************************
988 * HeapCreate (KERNEL32.336)
989 * RETURNS
990 * Handle of heap: Success
991 * NULL: Failure
993 HANDLE WINAPI HeapCreate(
994 DWORD flags, /* [in] Heap allocation flag */
995 DWORD initialSize, /* [in] Initial heap size */
996 DWORD maxSize /* [in] Maximum heap size */
998 SUBHEAP *subheap;
1000 /* Allocate the heap block */
1002 if (!maxSize)
1004 maxSize = HEAP_DEF_SIZE;
1005 flags |= HEAP_GROWABLE;
1007 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1009 SetLastError( ERROR_OUTOFMEMORY );
1010 return 0;
1013 /* link it into the per-process heap list */
1014 if (processHeap)
1016 HEAP *heapPtr = subheap->heap;
1017 EnterCriticalSection( &processHeap->critSection );
1018 heapPtr->next = firstHeap;
1019 firstHeap = heapPtr;
1020 LeaveCriticalSection( &processHeap->critSection );
1022 else /* assume the first heap we create is the process main heap */
1024 processHeap = subheap->heap;
1027 return (HANDLE)subheap;
1030 /***********************************************************************
1031 * HeapDestroy (KERNEL32.337)
1032 * RETURNS
1033 * TRUE: Success
1034 * FALSE: Failure
1036 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1038 HEAP *heapPtr = HEAP_GetPtr( heap );
1039 SUBHEAP *subheap;
1041 TRACE("%08x\n", heap );
1042 if (!heapPtr) return FALSE;
1044 if (heapPtr == processHeap) /* cannot delete the main process heap */
1046 SetLastError( ERROR_INVALID_PARAMETER );
1047 return FALSE;
1049 else /* remove it from the per-process list */
1051 HEAP **pptr;
1052 EnterCriticalSection( &processHeap->critSection );
1053 pptr = &firstHeap;
1054 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1055 if (*pptr) *pptr = (*pptr)->next;
1056 LeaveCriticalSection( &processHeap->critSection );
1059 DeleteCriticalSection( &heapPtr->critSection );
1060 subheap = &heapPtr->subheap;
1061 while (subheap)
1063 SUBHEAP *next = subheap->next;
1064 if (subheap->selector) FreeSelector16( subheap->selector );
1065 VirtualFree( subheap, 0, MEM_RELEASE );
1066 subheap = next;
1068 return TRUE;
1072 /***********************************************************************
1073 * HeapAlloc (KERNEL32.334)
1074 * RETURNS
1075 * Pointer to allocated memory block
1076 * NULL: Failure
1078 LPVOID WINAPI HeapAlloc(
1079 HANDLE heap, /* [in] Handle of private heap block */
1080 DWORD flags, /* [in] Heap allocation control flags */
1081 DWORD size /* [in] Number of bytes to allocate */
1083 ARENA_FREE *pArena;
1084 ARENA_INUSE *pInUse;
1085 SUBHEAP *subheap;
1086 HEAP *heapPtr = HEAP_GetPtr( heap );
1088 /* Validate the parameters */
1090 if (!heapPtr) return NULL;
1091 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1092 flags |= heapPtr->flags;
1093 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1094 size = (size + 3) & ~3;
1095 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1097 /* Locate a suitable free block */
1099 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1101 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1102 heap, flags, size );
1103 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1104 SetLastError( ERROR_COMMITMENT_LIMIT );
1105 return NULL;
1108 /* Remove the arena from the free list */
1110 pArena->next->prev = pArena->prev;
1111 pArena->prev->next = pArena->next;
1113 /* Build the in-use arena */
1115 pInUse = (ARENA_INUSE *)pArena;
1116 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1117 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1118 pInUse->callerEIP = GET_EIP();
1119 pInUse->threadId = GetCurrentTask();
1120 pInUse->magic = ARENA_INUSE_MAGIC;
1122 /* Shrink the block */
1124 HEAP_ShrinkBlock( subheap, pInUse, size );
1126 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
1127 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
1129 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1131 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1132 heap, flags, size, (DWORD)(pInUse + 1) );
1133 return (LPVOID)(pInUse + 1);
1137 /***********************************************************************
1138 * HeapFree (KERNEL32.338)
1139 * RETURNS
1140 * TRUE: Success
1141 * FALSE: Failure
1143 BOOL WINAPI HeapFree(
1144 HANDLE heap, /* [in] Handle of heap */
1145 DWORD flags, /* [in] Heap freeing flags */
1146 LPVOID ptr /* [in] Address of memory to free */
1148 ARENA_INUSE *pInUse;
1149 SUBHEAP *subheap;
1150 HEAP *heapPtr = HEAP_GetPtr( heap );
1152 /* Validate the parameters */
1154 if (!heapPtr) return FALSE;
1155 flags &= HEAP_NO_SERIALIZE;
1156 flags |= heapPtr->flags;
1157 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1158 if (!ptr)
1160 WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
1161 heap, flags, (DWORD)ptr );
1163 if (!ptr || !HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1165 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1166 SetLastError( ERROR_INVALID_PARAMETER );
1167 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1168 heap, flags, (DWORD)ptr );
1169 return FALSE;
1172 /* Turn the block into a free block */
1174 pInUse = (ARENA_INUSE *)ptr - 1;
1175 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1176 HEAP_MakeInUseBlockFree( subheap, pInUse );
1178 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1179 /* SetLastError( 0 ); */
1181 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1182 heap, flags, (DWORD)ptr );
1183 return TRUE;
1187 /***********************************************************************
1188 * HeapReAlloc (KERNEL32.340)
1189 * RETURNS
1190 * Pointer to reallocated memory block
1191 * NULL: Failure
1193 LPVOID WINAPI HeapReAlloc(
1194 HANDLE heap, /* [in] Handle of heap block */
1195 DWORD flags, /* [in] Heap reallocation flags */
1196 LPVOID ptr, /* [in] Address of memory to reallocate */
1197 DWORD size /* [in] Number of bytes to reallocate */
1199 ARENA_INUSE *pArena;
1200 DWORD oldSize;
1201 HEAP *heapPtr;
1202 SUBHEAP *subheap;
1204 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1205 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1207 /* Validate the parameters */
1209 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1210 HEAP_REALLOC_IN_PLACE_ONLY;
1211 flags |= heapPtr->flags;
1212 size = (size + 3) & ~3;
1213 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1215 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1216 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1218 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1219 SetLastError( ERROR_INVALID_PARAMETER );
1220 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1221 heap, flags, (DWORD)ptr, size );
1222 return NULL;
1225 /* Check if we need to grow the block */
1227 pArena = (ARENA_INUSE *)ptr - 1;
1228 pArena->threadId = GetCurrentTask();
1229 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1230 oldSize = (pArena->size & ARENA_SIZE_MASK);
1231 if (size > oldSize)
1233 char *pNext = (char *)(pArena + 1) + oldSize;
1234 if ((pNext < (char *)subheap + subheap->size) &&
1235 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1236 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1238 /* The next block is free and large enough */
1239 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1240 pFree->next->prev = pFree->prev;
1241 pFree->prev->next = pFree->next;
1242 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1243 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1244 + size + HEAP_MIN_BLOCK_SIZE))
1246 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1247 SetLastError( ERROR_OUTOFMEMORY );
1248 return NULL;
1250 HEAP_ShrinkBlock( subheap, pArena, size );
1252 else /* Do it the hard way */
1254 ARENA_FREE *pNew;
1255 ARENA_INUSE *pInUse;
1256 SUBHEAP *newsubheap;
1258 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1259 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1261 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1262 SetLastError( ERROR_OUTOFMEMORY );
1263 return NULL;
1266 /* Build the in-use arena */
1268 pNew->next->prev = pNew->prev;
1269 pNew->prev->next = pNew->next;
1270 pInUse = (ARENA_INUSE *)pNew;
1271 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1272 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1273 pInUse->threadId = GetCurrentTask();
1274 pInUse->magic = ARENA_INUSE_MAGIC;
1275 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1276 memcpy( pInUse + 1, pArena + 1, oldSize );
1278 /* Free the previous block */
1280 HEAP_MakeInUseBlockFree( subheap, pArena );
1281 subheap = newsubheap;
1282 pArena = pInUse;
1285 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1287 /* Clear the extra bytes if needed */
1289 if (size > oldSize)
1291 if (flags & HEAP_ZERO_MEMORY)
1292 memset( (char *)(pArena + 1) + oldSize, 0,
1293 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1294 else if (TRACE_ON(heap))
1295 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1296 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1299 /* Return the new arena */
1301 pArena->callerEIP = GET_EIP();
1302 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1304 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1305 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1306 return (LPVOID)(pArena + 1);
1310 /***********************************************************************
1311 * HeapCompact (KERNEL32.335)
1313 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1315 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1316 return 0;
1320 /***********************************************************************
1321 * HeapLock (KERNEL32.339)
1322 * Attempts to acquire the critical section object for a specified heap.
1324 * RETURNS
1325 * TRUE: Success
1326 * FALSE: Failure
1328 BOOL WINAPI HeapLock(
1329 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1331 HEAP *heapPtr = HEAP_GetPtr( heap );
1332 if (!heapPtr) return FALSE;
1333 EnterCriticalSection( &heapPtr->critSection );
1334 return TRUE;
1338 /***********************************************************************
1339 * HeapUnlock (KERNEL32.342)
1340 * Releases ownership of the critical section object.
1342 * RETURNS
1343 * TRUE: Success
1344 * FALSE: Failure
1346 BOOL WINAPI HeapUnlock(
1347 HANDLE heap /* [in] Handle to the heap to unlock */
1349 HEAP *heapPtr = HEAP_GetPtr( heap );
1350 if (!heapPtr) return FALSE;
1351 LeaveCriticalSection( &heapPtr->critSection );
1352 return TRUE;
1356 /***********************************************************************
1357 * HeapSize (KERNEL32.341)
1358 * RETURNS
1359 * Size in bytes of allocated memory
1360 * 0xffffffff: Failure
1362 DWORD WINAPI HeapSize(
1363 HANDLE heap, /* [in] Handle of heap */
1364 DWORD flags, /* [in] Heap size control flags */
1365 LPVOID ptr /* [in] Address of memory to return size for */
1367 DWORD ret;
1368 HEAP *heapPtr = HEAP_GetPtr( heap );
1370 if (!heapPtr) return FALSE;
1371 flags &= HEAP_NO_SERIALIZE;
1372 flags |= heapPtr->flags;
1373 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1374 if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
1376 SetLastError( ERROR_INVALID_PARAMETER );
1377 ret = 0xffffffff;
1379 else
1381 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1382 ret = pArena->size & ARENA_SIZE_MASK;
1384 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1386 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1387 heap, flags, (DWORD)ptr, ret );
1388 return ret;
1392 /***********************************************************************
1393 * HeapValidate (KERNEL32.343)
1394 * Validates a specified heap.
1396 * NOTES
1397 * Flags is ignored.
1399 * RETURNS
1400 * TRUE: Success
1401 * FALSE: Failure
1403 BOOL WINAPI HeapValidate(
1404 HANDLE heap, /* [in] Handle to the heap */
1405 DWORD flags, /* [in] Bit flags that control access during operation */
1406 LPCVOID block /* [in] Optional pointer to memory block to validate */
1409 return HEAP_IsRealArena( heap, flags, block, QUIET );
1413 /***********************************************************************
1414 * HeapWalk (KERNEL32.344)
1415 * Enumerates the memory blocks in a specified heap.
1416 * See HEAP_Dump() for info on heap structure.
1418 * TODO
1419 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1420 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1422 * RETURNS
1423 * TRUE: Success
1424 * FALSE: Failure
1426 BOOL WINAPI HeapWalk(
1427 HANDLE heap, /* [in] Handle to heap to enumerate */
1428 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1430 HEAP *heapPtr = HEAP_GetPtr(heap);
1431 SUBHEAP *sub, *currentheap = NULL;
1432 BOOL ret = FALSE;
1433 char *ptr;
1434 int region_index = 0;
1436 if (!heapPtr || !entry)
1438 SetLastError(ERROR_INVALID_PARAMETER);
1439 return FALSE;
1442 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1444 /* set ptr to the next arena to be examined */
1446 if (!entry->lpData) /* first call (init) ? */
1448 TRACE("begin walking of heap 0x%08x.\n", heap);
1449 /*HEAP_Dump(heapPtr);*/
1450 currentheap = &heapPtr->subheap;
1451 ptr = (char*)currentheap + currentheap->headerSize;
1453 else
1455 ptr = entry->lpData;
1456 sub = &heapPtr->subheap;
1457 while (sub)
1459 if (((char *)ptr >= (char *)sub) &&
1460 ((char *)ptr < (char *)sub + sub->size))
1462 currentheap = sub;
1463 break;
1465 sub = sub->next;
1466 region_index++;
1468 if (currentheap == NULL)
1470 ERR("no matching subheap found, shouldn't happen !\n");
1471 SetLastError(ERROR_NO_MORE_ITEMS);
1472 goto HW_end;
1475 ptr += entry->cbData; /* point to next arena */
1476 if (ptr > (char *)currentheap + currentheap->size - 1)
1477 { /* proceed with next subheap */
1478 if (!(currentheap = currentheap->next))
1479 { /* successfully finished */
1480 TRACE("end reached.\n");
1481 SetLastError(ERROR_NO_MORE_ITEMS);
1482 goto HW_end;
1484 ptr = (char*)currentheap + currentheap->headerSize;
1488 entry->wFlags = 0;
1489 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1491 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1493 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1495 entry->lpData = pArena + 1;
1496 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1497 entry->cbOverhead = sizeof(ARENA_FREE);
1498 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1500 else
1502 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1504 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1506 entry->lpData = pArena + 1;
1507 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1508 entry->cbOverhead = sizeof(ARENA_INUSE);
1509 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1510 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1511 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1514 entry->iRegionIndex = region_index;
1516 /* first element of heap ? */
1517 if (ptr == (char *)(currentheap + currentheap->headerSize))
1519 entry->wFlags |= PROCESS_HEAP_REGION;
1520 entry->Foo.Region.dwCommittedSize = currentheap->commitSize;
1521 entry->Foo.Region.dwUnCommittedSize =
1522 currentheap->size - currentheap->commitSize;
1523 entry->Foo.Region.lpFirstBlock = /* first valid block */
1524 currentheap + currentheap->headerSize;
1525 entry->Foo.Region.lpLastBlock = /* first invalid block */
1526 currentheap + currentheap->size;
1528 ret = TRUE;
1530 HW_end:
1531 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1533 return ret;
1537 /***********************************************************************
1538 * HEAP_CreateSystemHeap
1540 * Create the system heap.
1542 BOOL HEAP_CreateSystemHeap(void)
1544 SYSTEM_HEAP_DESCR *descr;
1545 HANDLE heap;
1546 HEAP *heapPtr;
1547 int created;
1549 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1550 0, HEAP_DEF_SIZE, "__SystemHeap" );
1551 if (!map) return FALSE;
1552 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1554 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1556 /* pre-defined address not available, use any one */
1557 fprintf( stderr, "Warning: system heap base address %p not available\n",
1558 SYSTEM_HEAP_BASE );
1559 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1561 CloseHandle( map );
1562 return FALSE;
1565 heap = (HANDLE)heapPtr;
1567 if (created) /* newly created heap */
1569 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_WINE_SHARED, 0, HEAP_DEF_SIZE );
1570 HeapLock( heap );
1571 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1572 assert( descr );
1574 else
1576 /* wait for the heap to be initialized */
1577 while (!heapPtr->private) Sleep(1);
1578 HeapLock( heap );
1579 /* remap it to the right address if necessary */
1580 if (heapPtr->subheap.heap != heapPtr)
1582 void *base = heapPtr->subheap.heap;
1583 HeapUnlock( heap );
1584 UnmapViewOfFile( heapPtr );
1585 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1587 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1588 CloseHandle( map );
1589 return FALSE;
1591 heap = (HANDLE)heapPtr;
1592 HeapLock( heap );
1594 descr = heapPtr->private;
1595 assert( descr );
1597 SystemHeap = heap;
1598 SystemHeapDescr = descr;
1599 HeapUnlock( heap );
1600 CloseHandle( map );
1601 return TRUE;
1605 /***********************************************************************
1606 * GetProcessHeap (KERNEL32.259)
1608 HANDLE WINAPI GetProcessHeap(void)
1610 return (HANDLE)processHeap;
1614 /***********************************************************************
1615 * GetProcessHeaps (KERNEL32.376)
1617 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1619 DWORD total;
1620 HEAP *ptr;
1622 if (!processHeap) return 0; /* should never happen */
1623 total = 1; /* main heap */
1624 EnterCriticalSection( &processHeap->critSection );
1625 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1626 if (total <= count)
1628 *heaps++ = (HANDLE)processHeap;
1629 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1631 LeaveCriticalSection( &processHeap->critSection );
1632 return total;
1636 /***********************************************************************
1637 * HEAP_strdupA
1639 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1641 LPSTR p = HeapAlloc( heap, flags, strlen(str) + 1 );
1642 if(p) {
1643 SET_EIP(p);
1644 strcpy( p, str );
1646 return p;
1650 /***********************************************************************
1651 * HEAP_strdupW
1653 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1655 INT len = lstrlenW(str) + 1;
1656 LPWSTR p = HeapAlloc( heap, flags, len * sizeof(WCHAR) );
1657 if(p) {
1658 SET_EIP(p);
1659 lstrcpyW( p, str );
1661 return p;
1665 /***********************************************************************
1666 * HEAP_strdupAtoW
1668 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1670 LPWSTR ret;
1672 if (!str) return NULL;
1673 ret = HeapAlloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1674 if (ret) {
1675 SET_EIP(ret);
1676 lstrcpyAtoW( ret, str );
1678 return ret;
1682 /***********************************************************************
1683 * HEAP_strdupWtoA
1685 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1687 LPSTR ret;
1689 if (!str) return NULL;
1690 ret = HeapAlloc( heap, flags, lstrlenW(str) + 1 );
1691 if(ret) {
1692 SET_EIP(ret);
1693 lstrcpyWtoA( ret, str );
1695 return ret;
1700 /***********************************************************************
1701 * 32-bit local heap functions (Win95; undocumented)
1704 #define HTABLE_SIZE 0x10000
1705 #define HTABLE_PAGESIZE 0x1000
1706 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1708 #include "pshpack1.h"
1709 typedef struct _LOCAL32HEADER
1711 WORD freeListFirst[HTABLE_NPAGES];
1712 WORD freeListSize[HTABLE_NPAGES];
1713 WORD freeListLast[HTABLE_NPAGES];
1715 DWORD selectorTableOffset;
1716 WORD selectorTableSize;
1717 WORD selectorDelta;
1719 DWORD segment;
1720 LPBYTE base;
1722 DWORD limit;
1723 DWORD flags;
1725 DWORD magic;
1726 HANDLE heap;
1728 } LOCAL32HEADER;
1729 #include "poppack.h"
1731 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1733 /***********************************************************************
1734 * Local32Init (KERNEL.208)
1736 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1737 DWORD heapSize, DWORD flags )
1739 DWORD totSize, segSize = 0;
1740 LPBYTE base;
1741 LOCAL32HEADER *header;
1742 HEAP *heap;
1743 WORD *selectorTable;
1744 WORD selectorEven, selectorOdd;
1745 int i, nrBlocks;
1747 /* Determine new heap size */
1749 if ( segment )
1751 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1752 return 0;
1753 else
1754 segSize++;
1757 if ( heapSize == -1L )
1758 heapSize = 1024L*1024L; /* FIXME */
1760 heapSize = (heapSize + 0xffff) & 0xffff0000;
1761 segSize = (segSize + 0x0fff) & 0xfffff000;
1762 totSize = segSize + HTABLE_SIZE + heapSize;
1765 /* Allocate memory and initialize heap */
1767 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1768 return 0;
1770 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1771 MEM_COMMIT, PAGE_READWRITE ) )
1773 VirtualFree( base, 0, MEM_RELEASE );
1774 return 0;
1777 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1778 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1780 VirtualFree( base, 0, MEM_RELEASE );
1781 return 0;
1785 /* Set up header and handle table */
1787 header = (LOCAL32HEADER *)(base + segSize);
1788 header->base = base;
1789 header->limit = HTABLE_PAGESIZE-1;
1790 header->flags = 0;
1791 header->magic = LOCAL32_MAGIC;
1792 header->heap = (HANDLE)heap;
1794 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1795 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1796 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1798 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1799 *(DWORD *)((LPBYTE)header + i) = i+4;
1801 header->freeListFirst[1] = 0xffff;
1804 /* Set up selector table */
1806 nrBlocks = (totSize + 0x7fff) >> 15;
1807 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1808 selectorEven = SELECTOR_AllocBlock( base, totSize,
1809 SEGMENT_DATA, FALSE, FALSE );
1810 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1811 SEGMENT_DATA, FALSE, FALSE );
1813 if ( !selectorTable || !selectorEven || !selectorOdd )
1815 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1816 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1817 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1818 HeapDestroy( header->heap );
1819 VirtualFree( base, 0, MEM_RELEASE );
1820 return 0;
1823 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1824 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1825 header->selectorDelta = selectorEven - selectorOdd;
1826 header->segment = segment? segment : selectorEven;
1828 for (i = 0; i < nrBlocks; i++)
1829 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1830 : selectorEven + ((i >> 1) << __AHSHIFT);
1832 /* Move old segment */
1834 if ( segment )
1836 /* FIXME: This is somewhat ugly and relies on implementation
1837 details about 16-bit global memory handles ... */
1839 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1840 memcpy( base, oldBase, segSize );
1841 GLOBAL_MoveBlock( segment, base, totSize );
1842 HeapFree( SystemHeap, 0, oldBase );
1845 return (HANDLE)header;
1848 /***********************************************************************
1849 * Local32_SearchHandle
1851 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1853 LPDWORD handle;
1855 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1856 handle < (LPDWORD)((LPBYTE)header + header->limit);
1857 handle++)
1859 if (*handle == addr)
1860 return handle;
1863 return NULL;
1866 /***********************************************************************
1867 * Local32_ToHandle
1869 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1870 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1872 *handle = NULL;
1873 *ptr = NULL;
1875 switch (type)
1877 case -2: /* 16:16 pointer, no handles */
1878 *ptr = PTR_SEG_TO_LIN( addr );
1879 *handle = (LPDWORD)*ptr;
1880 break;
1882 case -1: /* 32-bit offset, no handles */
1883 *ptr = header->base + addr;
1884 *handle = (LPDWORD)*ptr;
1885 break;
1887 case 0: /* handle */
1888 if ( addr >= sizeof(LOCAL32HEADER)
1889 && addr < header->limit && !(addr & 3)
1890 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1892 *handle = (LPDWORD)((LPBYTE)header + addr);
1893 *ptr = header->base + **handle;
1895 break;
1897 case 1: /* 16:16 pointer */
1898 *ptr = PTR_SEG_TO_LIN( addr );
1899 *handle = Local32_SearchHandle( header, *ptr - header->base );
1900 break;
1902 case 2: /* 32-bit offset */
1903 *ptr = header->base + addr;
1904 *handle = Local32_SearchHandle( header, *ptr - header->base );
1905 break;
1909 /***********************************************************************
1910 * Local32_FromHandle
1912 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1913 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1915 switch (type)
1917 case -2: /* 16:16 pointer */
1918 case 1:
1920 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1921 DWORD offset = (LPBYTE)ptr - header->base;
1922 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1924 break;
1926 case -1: /* 32-bit offset */
1927 case 2:
1928 *addr = ptr - header->base;
1929 break;
1931 case 0: /* handle */
1932 *addr = (LPBYTE)handle - (LPBYTE)header;
1933 break;
1937 /***********************************************************************
1938 * Local32Alloc (KERNEL.209)
1940 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1942 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1943 LPDWORD handle;
1944 LPBYTE ptr;
1945 DWORD addr;
1947 /* Allocate memory */
1948 ptr = HeapAlloc( header->heap,
1949 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1950 if (!ptr) return 0;
1953 /* Allocate handle if requested */
1954 if (type >= 0)
1956 int page, i;
1958 /* Find first page of handle table with free slots */
1959 for (page = 0; page < HTABLE_NPAGES; page++)
1960 if (header->freeListFirst[page] != 0)
1961 break;
1962 if (page == HTABLE_NPAGES)
1964 WARN("Out of handles!\n" );
1965 HeapFree( header->heap, 0, ptr );
1966 return 0;
1969 /* If virgin page, initialize it */
1970 if (header->freeListFirst[page] == 0xffff)
1972 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1973 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1975 WARN("Cannot grow handle table!\n" );
1976 HeapFree( header->heap, 0, ptr );
1977 return 0;
1980 header->limit += HTABLE_PAGESIZE;
1982 header->freeListFirst[page] = 0;
1983 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1984 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1986 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1987 *(DWORD *)((LPBYTE)header + i) = i+4;
1989 if (page < HTABLE_NPAGES-1)
1990 header->freeListFirst[page+1] = 0xffff;
1993 /* Allocate handle slot from page */
1994 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1995 if (--header->freeListSize[page] == 0)
1996 header->freeListFirst[page] = header->freeListLast[page] = 0;
1997 else
1998 header->freeListFirst[page] = *handle;
2000 /* Store 32-bit offset in handle slot */
2001 *handle = ptr - header->base;
2003 else
2005 handle = (LPDWORD)ptr;
2006 header->flags |= 1;
2010 /* Convert handle to requested output type */
2011 Local32_FromHandle( header, type, &addr, handle, ptr );
2012 return addr;
2015 /***********************************************************************
2016 * Local32ReAlloc (KERNEL.210)
2018 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2019 DWORD size, DWORD flags )
2021 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2022 LPDWORD handle;
2023 LPBYTE ptr;
2025 if (!addr)
2026 return Local32Alloc16( heap, size, type, flags );
2028 /* Retrieve handle and pointer */
2029 Local32_ToHandle( header, type, addr, &handle, &ptr );
2030 if (!handle) return FALSE;
2032 /* Reallocate memory block */
2033 ptr = HeapReAlloc( header->heap,
2034 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2035 ptr, size );
2036 if (!ptr) return 0;
2038 /* Modify handle */
2039 if (type >= 0)
2040 *handle = ptr - header->base;
2041 else
2042 handle = (LPDWORD)ptr;
2044 /* Convert handle to requested output type */
2045 Local32_FromHandle( header, type, &addr, handle, ptr );
2046 return addr;
2049 /***********************************************************************
2050 * Local32Free (KERNEL.211)
2052 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2054 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2055 LPDWORD handle;
2056 LPBYTE ptr;
2058 /* Retrieve handle and pointer */
2059 Local32_ToHandle( header, type, addr, &handle, &ptr );
2060 if (!handle) return FALSE;
2062 /* Free handle if necessary */
2063 if (type >= 0)
2065 int offset = (LPBYTE)handle - (LPBYTE)header;
2066 int page = offset >> 12;
2068 /* Return handle slot to page free list */
2069 if (header->freeListSize[page]++ == 0)
2070 header->freeListFirst[page] = header->freeListLast[page] = offset;
2071 else
2072 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2073 header->freeListLast[page] = offset;
2075 *handle = 0;
2077 /* Shrink handle table when possible */
2078 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2080 if ( VirtualFree( (LPBYTE)header +
2081 (header->limit & ~(HTABLE_PAGESIZE-1)),
2082 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2083 break;
2085 header->limit -= HTABLE_PAGESIZE;
2086 header->freeListFirst[page] = 0xffff;
2087 page--;
2091 /* Free memory */
2092 return HeapFree( header->heap, 0, ptr );
2095 /***********************************************************************
2096 * Local32Translate (KERNEL.213)
2098 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2100 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2101 LPDWORD handle;
2102 LPBYTE ptr;
2104 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2105 if (!handle) return 0;
2107 Local32_FromHandle( header, type2, &addr, handle, ptr );
2108 return addr;
2111 /***********************************************************************
2112 * Local32Size (KERNEL.214)
2114 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2116 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2117 LPDWORD handle;
2118 LPBYTE ptr;
2120 Local32_ToHandle( header, type, addr, &handle, &ptr );
2121 if (!handle) return 0;
2123 return HeapSize( header->heap, 0, ptr );
2126 /***********************************************************************
2127 * Local32ValidHandle (KERNEL.215)
2129 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2131 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2132 LPDWORD handle;
2133 LPBYTE ptr;
2135 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2136 return handle != NULL;
2139 /***********************************************************************
2140 * Local32GetSegment (KERNEL.229)
2142 WORD WINAPI Local32GetSegment16( HANDLE heap )
2144 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2145 return header->segment;
2148 /***********************************************************************
2149 * Local32_GetHeap
2151 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2153 WORD selector = GlobalHandleToSel16( handle );
2154 DWORD base = GetSelectorBase( selector );
2155 DWORD limit = GetSelectorLimit16( selector );
2157 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2158 it this way ... */
2160 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2161 return (LOCAL32HEADER *)base;
2163 base += 0x10000;
2164 limit -= 0x10000;
2166 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2167 return (LOCAL32HEADER *)base;
2169 return NULL;
2172 /***********************************************************************
2173 * Local32Info (KERNEL.444) (TOOLHELP.84)
2175 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2177 SUBHEAP *heapPtr;
2178 LPBYTE ptr;
2179 int i;
2181 LOCAL32HEADER *header = Local32_GetHeap( handle );
2182 if ( !header ) return FALSE;
2184 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2185 return FALSE;
2187 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2188 pLocal32Info->dwMemReserved = heapPtr->size;
2189 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2190 pLocal32Info->dwTotalFree = 0L;
2191 pLocal32Info->dwLargestFreeBlock = 0L;
2193 /* Note: Local32 heaps always have only one subheap! */
2194 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2195 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2197 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2199 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2200 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2201 ptr += sizeof(*pArena) + size;
2203 pLocal32Info->dwTotalFree += size;
2204 if ( size > pLocal32Info->dwLargestFreeBlock )
2205 pLocal32Info->dwLargestFreeBlock = size;
2207 else
2209 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2210 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2211 ptr += sizeof(*pArena) + size;
2215 pLocal32Info->dwcFreeHandles = 0;
2216 for ( i = 0; i < HTABLE_NPAGES; i++ )
2218 if ( header->freeListFirst[i] == 0xffff ) break;
2219 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2221 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2223 return TRUE;
2226 /***********************************************************************
2227 * Local32First (KERNEL.445) (TOOLHELP.85)
2229 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2231 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2232 return FALSE;
2235 /***********************************************************************
2236 * Local32Next (KERNEL.446) (TOOLHELP.86)
2238 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2240 FIXME("(%p): stub!\n", pLocal32Entry );
2241 return FALSE;