No longer used.
[wine/wine-kai.git] / memory / heap.c
blobc73d52a99e68e50b3b8e7ff7914cc9bb8556ed94
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
6 */
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include "config.h"
13 #include "wine/winbase16.h"
14 #include "wine/unicode.h"
15 #include "selectors.h"
16 #include "global.h"
17 #include "winbase.h"
18 #include "winerror.h"
19 #include "winnt.h"
20 #include "heap.h"
21 #include "toolhelp.h"
22 #include "debugtools.h"
23 #include "winnls.h"
25 DEFAULT_DEBUG_CHANNEL(heap);
27 /* Note: the heap data structures are based on what Pietrek describes in his
28 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
29 * the same, but could be easily adapted if it turns out some programs
30 * require it.
33 typedef struct tagARENA_INUSE
35 DWORD size; /* Block size; must be the first field */
36 WORD magic; /* Magic number */
37 WORD threadId; /* Allocating thread id */
38 void *callerEIP; /* EIP of caller upon allocation */
39 } ARENA_INUSE;
41 typedef struct tagARENA_FREE
43 DWORD size; /* Block size; must be the first field */
44 WORD magic; /* Magic number */
45 WORD threadId; /* Freeing thread id */
46 struct tagARENA_FREE *next; /* Next free arena */
47 struct tagARENA_FREE *prev; /* Prev free arena */
48 } ARENA_FREE;
50 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
51 #define ARENA_FLAG_PREV_FREE 0x00000002
52 #define ARENA_SIZE_MASK 0xfffffffc
53 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
54 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
56 #define ARENA_INUSE_FILLER 0x55
57 #define ARENA_FREE_FILLER 0xaa
59 #define QUIET 1 /* Suppress messages */
60 #define NOISY 0 /* Report all errors */
62 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
64 /* Max size of the blocks on the free lists */
65 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
67 0x20, 0x80, 0x200, 0xffffffff
70 typedef struct
72 DWORD size;
73 ARENA_FREE arena;
74 } FREE_LIST_ENTRY;
76 struct tagHEAP;
78 typedef struct tagSUBHEAP
80 DWORD size; /* Size of the whole sub-heap */
81 DWORD commitSize; /* Committed size of the sub-heap */
82 DWORD headerSize; /* Size of the heap header */
83 struct tagSUBHEAP *next; /* Next sub-heap */
84 struct tagHEAP *heap; /* Main heap structure */
85 DWORD magic; /* Magic number */
86 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
87 } SUBHEAP;
89 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
91 typedef struct tagHEAP
93 SUBHEAP subheap; /* First sub-heap */
94 struct tagHEAP *next; /* Next heap for this process */
95 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
96 CRITICAL_SECTION critSection; /* Critical section for serialization */
97 DWORD flags; /* Heap flags */
98 DWORD magic; /* Magic number */
99 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;
110 SYSTEM_HEAP_DESCR *SystemHeapDescr = 0;
112 static HEAP *processHeap; /* main process heap */
113 static HEAP *segptrHeap; /* main segptr 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( HEAP *heapPtr, 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( heapPtr, 0, NULL, NOISY ))
226 HEAP_Dump( heapPtr );
227 assert( FALSE );
228 SetLastError( ERROR_INVALID_HANDLE );
229 return NULL;
231 return heapPtr;
235 /***********************************************************************
236 * HEAP_InsertFreeBlock
238 * Insert a free block into the free list.
240 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
242 FREE_LIST_ENTRY *pEntry = heap->freeList;
243 while (pEntry->size < pArena->size) pEntry++;
244 pArena->size |= ARENA_FLAG_FREE;
245 pArena->next = pEntry->arena.next;
246 pArena->next->prev = pArena;
247 pArena->prev = &pEntry->arena;
248 pEntry->arena.next = pArena;
252 /***********************************************************************
253 * HEAP_FindSubHeap
254 * Find the sub-heap containing a given address.
256 * RETURNS
257 * Pointer: Success
258 * NULL: Failure
260 static SUBHEAP *HEAP_FindSubHeap(
261 HEAP *heap, /* [in] Heap pointer */
262 LPCVOID ptr /* [in] Address */
264 SUBHEAP *sub = &heap->subheap;
265 while (sub)
267 if (((char *)ptr >= (char *)sub) &&
268 ((char *)ptr < (char *)sub + sub->size)) return sub;
269 sub = sub->next;
271 return NULL;
275 /***********************************************************************
276 * HEAP_Commit
278 * Make sure the heap storage is committed up to (not including) ptr.
280 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
282 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
283 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
284 if (size > subheap->size) size = subheap->size;
285 if (size <= subheap->commitSize) return TRUE;
286 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
287 size - subheap->commitSize, MEM_COMMIT,
288 PAGE_EXECUTE_READWRITE))
290 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
291 size - subheap->commitSize,
292 (DWORD)((char *)subheap + subheap->commitSize),
293 (DWORD)subheap->heap );
294 return FALSE;
296 subheap->commitSize = size;
297 return TRUE;
301 /***********************************************************************
302 * HEAP_Decommit
304 * If possible, decommit the heap storage from (including) 'ptr'.
306 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
308 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
309 /* round to next block and add one full block */
310 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
311 if (size >= subheap->commitSize) return TRUE;
312 if (!VirtualFree( (char *)subheap + size,
313 subheap->commitSize - size, MEM_DECOMMIT ))
315 WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
316 subheap->commitSize - size,
317 (DWORD)((char *)subheap + size),
318 (DWORD)subheap->heap );
319 return FALSE;
321 subheap->commitSize = size;
322 return TRUE;
326 /***********************************************************************
327 * HEAP_CreateFreeBlock
329 * Create a free block at a specified address. 'size' is the size of the
330 * whole block, including the new arena.
332 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
334 ARENA_FREE *pFree;
336 /* Create a free arena */
338 pFree = (ARENA_FREE *)ptr;
339 pFree->threadId = GetCurrentTask();
340 pFree->magic = ARENA_FREE_MAGIC;
342 /* If debugging, erase the freed block content */
344 if (TRACE_ON(heap))
346 char *pEnd = (char *)ptr + size;
347 if (pEnd > (char *)subheap + subheap->commitSize)
348 pEnd = (char *)subheap + subheap->commitSize;
349 if (pEnd > (char *)(pFree + 1))
350 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
353 /* Check if next block is free also */
355 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
356 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
358 /* Remove the next arena from the free list */
359 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
360 pNext->next->prev = pNext->prev;
361 pNext->prev->next = pNext->next;
362 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
363 if (TRACE_ON(heap))
364 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
367 /* Set the next block PREV_FREE flag and pointer */
369 if ((char *)ptr + size < (char *)subheap + subheap->size)
371 DWORD *pNext = (DWORD *)((char *)ptr + size);
372 *pNext |= ARENA_FLAG_PREV_FREE;
373 *(ARENA_FREE **)(pNext - 1) = pFree;
376 /* Last, insert the new block into the free list */
378 pFree->size = size - sizeof(*pFree);
379 HEAP_InsertFreeBlock( subheap->heap, pFree );
383 /***********************************************************************
384 * HEAP_MakeInUseBlockFree
386 * Turn an in-use block into a free block. Can also decommit the end of
387 * the heap, and possibly even free the sub-heap altogether.
389 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
391 ARENA_FREE *pFree;
392 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
394 /* Check if we can merge with previous block */
396 if (pArena->size & ARENA_FLAG_PREV_FREE)
398 pFree = *((ARENA_FREE **)pArena - 1);
399 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
400 /* Remove it from the free list */
401 pFree->next->prev = pFree->prev;
402 pFree->prev->next = pFree->next;
404 else pFree = (ARENA_FREE *)pArena;
406 /* Create a free block */
408 HEAP_CreateFreeBlock( subheap, pFree, size );
409 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
410 if ((char *)pFree + size < (char *)subheap + subheap->size)
411 return; /* Not the last block, so nothing more to do */
413 /* Free the whole sub-heap if it's empty and not the original one */
415 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
416 (subheap != &subheap->heap->subheap))
418 SUBHEAP *pPrev = &subheap->heap->subheap;
419 /* Remove the free block from the list */
420 pFree->next->prev = pFree->prev;
421 pFree->prev->next = pFree->next;
422 /* Remove the subheap from the list */
423 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
424 if (pPrev) pPrev->next = subheap->next;
425 /* Free the memory */
426 subheap->magic = 0;
427 if (subheap->selector) FreeSelector16( subheap->selector );
428 VirtualFree( subheap, 0, MEM_RELEASE );
429 return;
432 /* Decommit the end of the heap */
434 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
438 /***********************************************************************
439 * HEAP_ShrinkBlock
441 * Shrink an in-use block.
443 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
445 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
447 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
448 (pArena->size & ARENA_SIZE_MASK) - size );
449 /* assign size plus previous arena flags */
450 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
452 else
454 /* Turn off PREV_FREE flag in next block */
455 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
456 if (pNext < (char *)subheap + subheap->size)
457 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
461 /***********************************************************************
462 * HEAP_InitSubHeap
464 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
465 DWORD commitSize, DWORD totalSize )
467 SUBHEAP *subheap = (SUBHEAP *)address;
468 WORD selector = 0;
469 FREE_LIST_ENTRY *pEntry;
470 int i;
472 /* Commit memory */
474 if (flags & HEAP_SHARED)
475 commitSize = totalSize; /* always commit everything in a shared heap */
476 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
478 WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
479 commitSize, (DWORD)address );
480 return FALSE;
483 /* Allocate a selector if needed */
485 if (flags & HEAP_WINE_SEGPTR)
487 unsigned char selflags = WINE_LDT_FLAGS_DATA;
489 if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
490 selflags = WINE_LDT_FLAGS_CODE;
491 if (flags & HEAP_WINE_CODESEG)
492 selflags |= WINE_LDT_FLAGS_32BIT;
493 selector = SELECTOR_AllocBlock( address, totalSize, selflags );
494 if (!selector)
496 ERR("Could not allocate selector\n" );
497 return FALSE;
501 /* Fill the sub-heap structure */
503 subheap->heap = heap;
504 subheap->selector = selector;
505 subheap->size = totalSize;
506 subheap->commitSize = commitSize;
507 subheap->magic = SUBHEAP_MAGIC;
509 if ( subheap != (SUBHEAP *)heap )
511 /* If this is a secondary subheap, insert it into list */
513 subheap->headerSize = sizeof(SUBHEAP);
514 subheap->next = heap->subheap.next;
515 heap->subheap.next = subheap;
517 else
519 /* If this is a primary subheap, initialize main heap */
521 subheap->headerSize = sizeof(HEAP);
522 subheap->next = NULL;
523 heap->next = NULL;
524 heap->flags = flags;
525 heap->magic = HEAP_MAGIC;
527 /* Build the free lists */
529 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
531 pEntry->size = HEAP_freeListSizes[i];
532 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
533 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
534 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
535 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
536 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
537 pEntry->arena.threadId = 0;
538 pEntry->arena.magic = ARENA_FREE_MAGIC;
541 /* Initialize critical section */
543 InitializeCriticalSection( &heap->critSection );
544 if (!SystemHeap) MakeCriticalSectionGlobal( &heap->critSection );
547 /* Create the first free block */
549 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
550 subheap->size - subheap->headerSize );
552 return TRUE;
555 /***********************************************************************
556 * HEAP_CreateSubHeap
558 * Create a sub-heap of the given size.
559 * If heap == NULL, creates a main heap.
561 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
562 DWORD commitSize, DWORD totalSize )
564 LPVOID address;
566 /* Round-up sizes on a 64K boundary */
568 if (flags & HEAP_WINE_SEGPTR)
570 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
572 else
574 totalSize = (totalSize + 0xffff) & 0xffff0000;
575 commitSize = (commitSize + 0xffff) & 0xffff0000;
576 if (!commitSize) commitSize = 0x10000;
577 if (totalSize < commitSize) totalSize = commitSize;
580 /* Allocate the memory block */
582 if (!(address = VirtualAlloc( NULL, totalSize,
583 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
585 WARN("Could not VirtualAlloc %08lx bytes\n",
586 totalSize );
587 return NULL;
590 /* Initialize subheap */
592 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
593 address, flags, commitSize, totalSize ))
595 VirtualFree( address, 0, MEM_RELEASE );
596 return NULL;
599 return (SUBHEAP *)address;
603 /***********************************************************************
604 * HEAP_FindFreeBlock
606 * Find a free block at least as large as the requested size, and make sure
607 * the requested size is committed.
609 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
610 SUBHEAP **ppSubHeap )
612 SUBHEAP *subheap;
613 ARENA_FREE *pArena;
614 FREE_LIST_ENTRY *pEntry = heap->freeList;
616 /* Find a suitable free list, and in it find a block large enough */
618 while (pEntry->size < size) pEntry++;
619 pArena = pEntry->arena.next;
620 while (pArena != &heap->freeList[0].arena)
622 if (pArena->size > size)
624 subheap = HEAP_FindSubHeap( heap, pArena );
625 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
626 + size + HEAP_MIN_BLOCK_SIZE))
627 return NULL;
628 *ppSubHeap = subheap;
629 return pArena;
632 pArena = pArena->next;
635 /* If no block was found, attempt to grow the heap */
637 if (!(heap->flags & HEAP_GROWABLE))
639 WARN("Not enough space in heap %08lx for %08lx bytes\n",
640 (DWORD)heap, size );
641 return NULL;
643 /* make sure that we have a big enough size *committed* to fit another
644 * last free arena in !
645 * So just one heap struct, one first free arena which will eventually
646 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
647 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
648 size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
649 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
650 max( HEAP_DEF_SIZE, size ) )))
651 return NULL;
653 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
654 (DWORD)subheap, size, (DWORD)heap );
656 *ppSubHeap = subheap;
657 return (ARENA_FREE *)(subheap + 1);
661 /***********************************************************************
662 * HEAP_IsValidArenaPtr
664 * Check that the pointer is inside the range possible for arenas.
666 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
668 int i;
669 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
670 if (!subheap) return FALSE;
671 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
672 if (subheap != &heap->subheap) return FALSE;
673 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
674 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
675 return FALSE;
679 /***********************************************************************
680 * HEAP_ValidateFreeArena
682 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
684 char *heapEnd = (char *)subheap + subheap->size;
686 #if !defined(ALLOW_UNALIGNED_ACCESS)
687 /* Check for unaligned pointers */
688 if ( (long)pArena % sizeof(void *) != 0 )
690 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
691 (DWORD)subheap->heap, (DWORD)pArena );
692 return FALSE;
694 #endif
696 /* Check magic number */
697 if (pArena->magic != ARENA_FREE_MAGIC)
699 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
700 (DWORD)subheap->heap, (DWORD)pArena );
701 return FALSE;
703 /* Check size flags */
704 if (!(pArena->size & ARENA_FLAG_FREE) ||
705 (pArena->size & ARENA_FLAG_PREV_FREE))
707 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
708 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
710 /* Check arena size */
711 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
713 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
714 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
715 return FALSE;
717 /* Check that next pointer is valid */
718 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
720 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
721 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
722 return FALSE;
724 /* Check that next arena is free */
725 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
726 (pArena->next->magic != ARENA_FREE_MAGIC))
728 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
729 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
730 return FALSE;
732 /* Check that prev pointer is valid */
733 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
735 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
736 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
737 return FALSE;
739 /* Check that prev arena is free */
740 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
741 (pArena->prev->magic != ARENA_FREE_MAGIC))
743 /* this often means that the prev arena got overwritten
744 * by a memory write before that prev arena */
745 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
746 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
747 return FALSE;
749 /* Check that next block has PREV_FREE flag */
750 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
752 if (!(*(DWORD *)((char *)(pArena + 1) +
753 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
755 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
756 (DWORD)subheap->heap, (DWORD)pArena );
757 return FALSE;
759 /* Check next block back pointer */
760 if (*((ARENA_FREE **)((char *)(pArena + 1) +
761 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
763 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
764 (DWORD)subheap->heap, (DWORD)pArena,
765 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
766 return FALSE;
769 return TRUE;
773 /***********************************************************************
774 * HEAP_ValidateInUseArena
776 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
778 char *heapEnd = (char *)subheap + subheap->size;
780 #if !defined(ALLOW_UNALIGNED_ACCESS)
781 /* Check for unaligned pointers */
782 if ( (long)pArena % sizeof(void *) != 0 )
784 if ( quiet == NOISY )
786 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
787 (DWORD)subheap->heap, (DWORD)pArena );
788 if ( TRACE_ON(heap) )
789 HEAP_Dump( subheap->heap );
791 else if ( WARN_ON(heap) )
793 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
794 (DWORD)subheap->heap, (DWORD)pArena );
795 if ( TRACE_ON(heap) )
796 HEAP_Dump( subheap->heap );
798 return FALSE;
800 #endif
802 /* Check magic number */
803 if (pArena->magic != ARENA_INUSE_MAGIC)
805 if (quiet == NOISY) {
806 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
807 (DWORD)subheap->heap, (DWORD)pArena );
808 if (TRACE_ON(heap))
809 HEAP_Dump( subheap->heap );
810 } else if (WARN_ON(heap)) {
811 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
812 (DWORD)subheap->heap, (DWORD)pArena );
813 if (TRACE_ON(heap))
814 HEAP_Dump( subheap->heap );
816 return FALSE;
818 /* Check size flags */
819 if (pArena->size & ARENA_FLAG_FREE)
821 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
822 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
824 /* Check arena size */
825 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
827 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
828 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
829 return FALSE;
831 /* Check next arena PREV_FREE flag */
832 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
833 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
835 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
836 (DWORD)subheap->heap, (DWORD)pArena );
837 return FALSE;
839 /* Check prev free arena */
840 if (pArena->size & ARENA_FLAG_PREV_FREE)
842 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
843 /* Check prev pointer */
844 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
846 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
847 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
848 return FALSE;
850 /* Check that prev arena is free */
851 if (!(pPrev->size & ARENA_FLAG_FREE) ||
852 (pPrev->magic != ARENA_FREE_MAGIC))
854 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
855 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
856 return FALSE;
858 /* Check that prev arena is really the previous block */
859 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
861 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
862 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
863 return FALSE;
866 return TRUE;
870 /***********************************************************************
871 * HEAP_GetSegptr
873 * Transform a linear pointer into a SEGPTR. The pointer must have been
874 * allocated from a HEAP_WINE_SEGPTR heap.
876 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
878 HEAP *heapPtr = HEAP_GetPtr( heap );
879 SUBHEAP *subheap;
880 SEGPTR ret = 0;
882 /* Validate the parameters */
884 if (!heapPtr) return 0;
885 flags |= heapPtr->flags;
886 if (!(flags & HEAP_WINE_SEGPTR))
888 ERR("Heap %08x is not a SEGPTR heap\n",
889 heap );
890 return 0;
892 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
894 /* Get the subheap */
896 if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
897 ret = MAKESEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
899 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
900 return ret;
903 /***********************************************************************
904 * MapLS (KERNEL32.522)
906 * Maps linear pointer to segmented.
908 SEGPTR WINAPI MapLS( LPCVOID ptr )
910 SUBHEAP *subheap;
911 SEGPTR ret = 0;
913 if (!HIWORD(ptr)) return (SEGPTR)ptr;
915 /* check if the pointer is inside the segptr heap */
916 EnterCriticalSection( &segptrHeap->critSection );
917 if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
918 ret = MAKESEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
919 LeaveCriticalSection( &segptrHeap->critSection );
921 /* otherwise, allocate a brand-new selector */
922 if (!ret)
924 WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
925 ret = MAKESEGPTR( sel, 0 );
927 return ret;
931 /***********************************************************************
932 * UnMapLS (KERNEL32.700)
934 * Free mapped selector.
936 void WINAPI UnMapLS( SEGPTR sptr )
938 SUBHEAP *subheap;
939 if (!SELECTOROF(sptr)) return;
941 /* check if ptr is inside segptr heap */
942 EnterCriticalSection( &segptrHeap->critSection );
943 subheap = HEAP_FindSubHeap( segptrHeap, MapSL(sptr) );
944 if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
945 LeaveCriticalSection( &segptrHeap->critSection );
946 /* if not inside heap, free the selector */
947 if (!subheap) FreeSelector16( SELECTOROF(sptr) );
950 /***********************************************************************
951 * HEAP_IsRealArena [Internal]
952 * Validates a block is a valid arena.
954 * RETURNS
955 * TRUE: Success
956 * FALSE: Failure
958 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
959 DWORD flags, /* [in] Bit flags that control access during operation */
960 LPCVOID block, /* [in] Optional pointer to memory block to validate */
961 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
962 * does not complain */
964 SUBHEAP *subheap;
965 BOOL ret = TRUE;
967 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
969 ERR("Invalid heap %p!\n", heapPtr );
970 return FALSE;
973 flags &= HEAP_NO_SERIALIZE;
974 flags |= heapPtr->flags;
975 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
976 if (!(flags & HEAP_NO_SERIALIZE))
977 EnterCriticalSection( &heapPtr->critSection );
979 if (block)
981 /* Only check this single memory block */
983 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
984 ((char *)block < (char *)subheap + subheap->headerSize
985 + sizeof(ARENA_INUSE)))
987 if (quiet == NOISY)
988 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
989 else if (WARN_ON(heap))
990 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
991 ret = FALSE;
992 } else
993 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
995 if (!(flags & HEAP_NO_SERIALIZE))
996 LeaveCriticalSection( &heapPtr->critSection );
997 return ret;
1000 subheap = &heapPtr->subheap;
1001 while (subheap && ret)
1003 char *ptr = (char *)subheap + subheap->headerSize;
1004 while (ptr < (char *)subheap + subheap->size)
1006 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1008 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1009 ret = FALSE;
1010 break;
1012 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1014 else
1016 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1017 ret = FALSE;
1018 break;
1020 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1023 subheap = subheap->next;
1026 if (!(flags & HEAP_NO_SERIALIZE))
1027 LeaveCriticalSection( &heapPtr->critSection );
1028 return ret;
1032 /***********************************************************************
1033 * HeapCreate (KERNEL32.336)
1034 * RETURNS
1035 * Handle of heap: Success
1036 * NULL: Failure
1038 HANDLE WINAPI HeapCreate(
1039 DWORD flags, /* [in] Heap allocation flag */
1040 DWORD initialSize, /* [in] Initial heap size */
1041 DWORD maxSize /* [in] Maximum heap size */
1043 SUBHEAP *subheap;
1045 if ( flags & HEAP_SHARED ) {
1046 WARN( "Shared Heap requested, returning system heap.\n" );
1047 return SystemHeap;
1050 /* Allocate the heap block */
1052 if (!maxSize)
1054 maxSize = HEAP_DEF_SIZE;
1055 flags |= HEAP_GROWABLE;
1057 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1059 SetLastError( ERROR_OUTOFMEMORY );
1060 return 0;
1063 /* link it into the per-process heap list */
1064 if (processHeap)
1066 HEAP *heapPtr = subheap->heap;
1067 EnterCriticalSection( &processHeap->critSection );
1068 heapPtr->next = firstHeap;
1069 firstHeap = heapPtr;
1070 LeaveCriticalSection( &processHeap->critSection );
1072 else /* assume the first heap we create is the process main heap */
1074 SUBHEAP *segptr;
1075 processHeap = subheap->heap;
1076 /* create the SEGPTR heap */
1077 if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1079 SetLastError( ERROR_OUTOFMEMORY );
1080 return 0;
1082 segptrHeap = segptr->heap;
1084 return (HANDLE)subheap;
1087 /***********************************************************************
1088 * HeapDestroy (KERNEL32.337)
1089 * RETURNS
1090 * TRUE: Success
1091 * FALSE: Failure
1093 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1095 HEAP *heapPtr = HEAP_GetPtr( heap );
1096 SUBHEAP *subheap;
1098 if ( heap == SystemHeap ) {
1099 WARN( "attempt to destroy system heap, returning TRUE!\n" );
1100 return TRUE;
1103 TRACE("%08x\n", heap );
1104 if (!heapPtr) return FALSE;
1106 if (heapPtr == processHeap) /* cannot delete the main process heap */
1108 SetLastError( ERROR_INVALID_PARAMETER );
1109 return FALSE;
1111 else /* remove it from the per-process list */
1113 HEAP **pptr;
1114 EnterCriticalSection( &processHeap->critSection );
1115 pptr = &firstHeap;
1116 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1117 if (*pptr) *pptr = (*pptr)->next;
1118 LeaveCriticalSection( &processHeap->critSection );
1121 DeleteCriticalSection( &heapPtr->critSection );
1122 subheap = &heapPtr->subheap;
1123 while (subheap)
1125 SUBHEAP *next = subheap->next;
1126 if (subheap->selector) FreeSelector16( subheap->selector );
1127 VirtualFree( subheap, 0, MEM_RELEASE );
1128 subheap = next;
1130 return TRUE;
1134 /***********************************************************************
1135 * HeapAlloc (KERNEL32.334)
1136 * RETURNS
1137 * Pointer to allocated memory block
1138 * NULL: Failure
1140 LPVOID WINAPI HeapAlloc(
1141 HANDLE heap, /* [in] Handle of private heap block */
1142 DWORD flags, /* [in] Heap allocation control flags */
1143 DWORD size /* [in] Number of bytes to allocate */
1145 ARENA_FREE *pArena;
1146 ARENA_INUSE *pInUse;
1147 SUBHEAP *subheap;
1148 HEAP *heapPtr = HEAP_GetPtr( heap );
1150 /* Validate the parameters */
1152 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1153 if (!heapPtr) return NULL;
1154 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1155 flags |= heapPtr->flags;
1156 size = (size + 3) & ~3;
1157 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1159 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1160 /* Locate a suitable free block */
1162 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1164 TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1165 heap, flags, size );
1166 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1167 SetLastError( ERROR_COMMITMENT_LIMIT );
1168 return NULL;
1171 /* Remove the arena from the free list */
1173 pArena->next->prev = pArena->prev;
1174 pArena->prev->next = pArena->next;
1176 /* Build the in-use arena */
1178 pInUse = (ARENA_INUSE *)pArena;
1180 /* in-use arena is smaller than free arena,
1181 * so we have to add the difference to the size */
1182 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1183 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1184 pInUse->callerEIP = GET_EIP();
1185 pInUse->threadId = GetCurrentTask();
1186 pInUse->magic = ARENA_INUSE_MAGIC;
1188 /* Shrink the block */
1190 HEAP_ShrinkBlock( subheap, pInUse, size );
1192 if (flags & HEAP_ZERO_MEMORY)
1193 memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1194 else if (TRACE_ON(heap))
1195 memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1197 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1199 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1200 heap, flags, size, (DWORD)(pInUse + 1) );
1201 return (LPVOID)(pInUse + 1);
1205 /***********************************************************************
1206 * HeapFree (KERNEL32.338)
1207 * RETURNS
1208 * TRUE: Success
1209 * FALSE: Failure
1211 BOOL WINAPI HeapFree(
1212 HANDLE heap, /* [in] Handle of heap */
1213 DWORD flags, /* [in] Heap freeing flags */
1214 LPVOID ptr /* [in] Address of memory to free */
1216 ARENA_INUSE *pInUse;
1217 SUBHEAP *subheap;
1218 HEAP *heapPtr = HEAP_GetPtr( heap );
1220 /* Validate the parameters */
1222 if (!ptr) return TRUE; /* freeing a NULL ptr is doesn't indicate an error in Win2k */
1223 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1224 if (!heapPtr) return FALSE;
1226 flags &= HEAP_NO_SERIALIZE;
1227 flags |= heapPtr->flags;
1228 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1229 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1231 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1232 SetLastError( ERROR_INVALID_PARAMETER );
1233 TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1234 heap, flags, (DWORD)ptr );
1235 return FALSE;
1238 /* Turn the block into a free block */
1240 pInUse = (ARENA_INUSE *)ptr - 1;
1241 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1242 HEAP_MakeInUseBlockFree( subheap, pInUse );
1244 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1246 TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1247 heap, flags, (DWORD)ptr );
1248 return TRUE;
1252 /***********************************************************************
1253 * HeapReAlloc (KERNEL32.340)
1254 * RETURNS
1255 * Pointer to reallocated memory block
1256 * NULL: Failure
1258 LPVOID WINAPI HeapReAlloc(
1259 HANDLE heap, /* [in] Handle of heap block */
1260 DWORD flags, /* [in] Heap reallocation flags */
1261 LPVOID ptr, /* [in] Address of memory to reallocate */
1262 DWORD size /* [in] Number of bytes to reallocate */
1264 ARENA_INUSE *pArena;
1265 DWORD oldSize;
1266 HEAP *heapPtr;
1267 SUBHEAP *subheap;
1269 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1270 if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1271 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1273 /* Validate the parameters */
1275 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1276 HEAP_REALLOC_IN_PLACE_ONLY;
1277 flags |= heapPtr->flags;
1278 size = (size + 3) & ~3;
1279 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1281 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1282 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1284 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1285 SetLastError( ERROR_INVALID_PARAMETER );
1286 TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1287 heap, flags, (DWORD)ptr, size );
1288 return NULL;
1291 /* Check if we need to grow the block */
1293 pArena = (ARENA_INUSE *)ptr - 1;
1294 pArena->threadId = GetCurrentTask();
1295 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1296 oldSize = (pArena->size & ARENA_SIZE_MASK);
1297 if (size > oldSize)
1299 char *pNext = (char *)(pArena + 1) + oldSize;
1300 if ((pNext < (char *)subheap + subheap->size) &&
1301 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1302 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1304 /* The next block is free and large enough */
1305 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1306 pFree->next->prev = pFree->prev;
1307 pFree->prev->next = pFree->next;
1308 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1309 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1310 + size + HEAP_MIN_BLOCK_SIZE))
1312 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1313 SetLastError( ERROR_OUTOFMEMORY );
1314 return NULL;
1316 HEAP_ShrinkBlock( subheap, pArena, size );
1318 else /* Do it the hard way */
1320 ARENA_FREE *pNew;
1321 ARENA_INUSE *pInUse;
1322 SUBHEAP *newsubheap;
1324 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1325 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1327 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1328 SetLastError( ERROR_OUTOFMEMORY );
1329 return NULL;
1332 /* Build the in-use arena */
1334 pNew->next->prev = pNew->prev;
1335 pNew->prev->next = pNew->next;
1336 pInUse = (ARENA_INUSE *)pNew;
1337 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1338 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1339 pInUse->threadId = GetCurrentTask();
1340 pInUse->magic = ARENA_INUSE_MAGIC;
1341 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1342 memcpy( pInUse + 1, pArena + 1, oldSize );
1344 /* Free the previous block */
1346 HEAP_MakeInUseBlockFree( subheap, pArena );
1347 subheap = newsubheap;
1348 pArena = pInUse;
1351 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1353 /* Clear the extra bytes if needed */
1355 if (size > oldSize)
1357 if (flags & HEAP_ZERO_MEMORY)
1358 memset( (char *)(pArena + 1) + oldSize, 0,
1359 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1360 else if (TRACE_ON(heap))
1361 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1362 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1365 /* Return the new arena */
1367 pArena->callerEIP = GET_EIP();
1368 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1370 TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1371 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1372 return (LPVOID)(pArena + 1);
1376 /***********************************************************************
1377 * HeapCompact (KERNEL32.335)
1379 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1381 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1382 return 0;
1386 /***********************************************************************
1387 * HeapLock (KERNEL32.339)
1388 * Attempts to acquire the critical section object for a specified heap.
1390 * RETURNS
1391 * TRUE: Success
1392 * FALSE: Failure
1394 BOOL WINAPI HeapLock(
1395 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1397 HEAP *heapPtr = HEAP_GetPtr( heap );
1398 if (!heapPtr) return FALSE;
1399 EnterCriticalSection( &heapPtr->critSection );
1400 return TRUE;
1404 /***********************************************************************
1405 * HeapUnlock (KERNEL32.342)
1406 * Releases ownership of the critical section object.
1408 * RETURNS
1409 * TRUE: Success
1410 * FALSE: Failure
1412 BOOL WINAPI HeapUnlock(
1413 HANDLE heap /* [in] Handle to the heap to unlock */
1415 HEAP *heapPtr = HEAP_GetPtr( heap );
1416 if (!heapPtr) return FALSE;
1417 LeaveCriticalSection( &heapPtr->critSection );
1418 return TRUE;
1422 /***********************************************************************
1423 * HeapSize (KERNEL32.341)
1424 * RETURNS
1425 * Size in bytes of allocated memory
1426 * 0xffffffff: Failure
1428 DWORD WINAPI HeapSize(
1429 HANDLE heap, /* [in] Handle of heap */
1430 DWORD flags, /* [in] Heap size control flags */
1431 LPVOID ptr /* [in] Address of memory to return size for */
1433 DWORD ret;
1434 HEAP *heapPtr = HEAP_GetPtr( heap );
1436 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1437 if (!heapPtr) return FALSE;
1438 flags &= HEAP_NO_SERIALIZE;
1439 flags |= heapPtr->flags;
1440 if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1441 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1443 SetLastError( ERROR_INVALID_PARAMETER );
1444 ret = 0xffffffff;
1446 else
1448 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1449 ret = pArena->size & ARENA_SIZE_MASK;
1451 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1453 TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1454 heap, flags, (DWORD)ptr, ret );
1455 return ret;
1459 /***********************************************************************
1460 * HeapValidate (KERNEL32.343)
1461 * Validates a specified heap.
1463 * NOTES
1464 * Flags is ignored.
1466 * RETURNS
1467 * TRUE: Success
1468 * FALSE: Failure
1470 BOOL WINAPI HeapValidate(
1471 HANDLE heap, /* [in] Handle to the heap */
1472 DWORD flags, /* [in] Bit flags that control access during operation */
1473 LPCVOID block /* [in] Optional pointer to memory block to validate */
1475 HEAP *heapPtr = HEAP_GetPtr( heap );
1476 if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1477 if (!heapPtr) return FALSE;
1478 return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1482 /***********************************************************************
1483 * HeapWalk (KERNEL32.344)
1484 * Enumerates the memory blocks in a specified heap.
1485 * See HEAP_Dump() for info on heap structure.
1487 * TODO
1488 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1489 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1491 * RETURNS
1492 * TRUE: Success
1493 * FALSE: Failure
1495 BOOL WINAPI HeapWalk(
1496 HANDLE heap, /* [in] Handle to heap to enumerate */
1497 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1499 HEAP *heapPtr = HEAP_GetPtr(heap);
1500 SUBHEAP *sub, *currentheap = NULL;
1501 BOOL ret = FALSE;
1502 char *ptr;
1503 int region_index = 0;
1505 if (!heapPtr || !entry)
1507 SetLastError(ERROR_INVALID_PARAMETER);
1508 return FALSE;
1511 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1513 /* set ptr to the next arena to be examined */
1515 if (!entry->lpData) /* first call (init) ? */
1517 TRACE("begin walking of heap 0x%08x.\n", heap);
1518 /*HEAP_Dump(heapPtr);*/
1519 currentheap = &heapPtr->subheap;
1520 ptr = (char*)currentheap + currentheap->headerSize;
1522 else
1524 ptr = entry->lpData;
1525 sub = &heapPtr->subheap;
1526 while (sub)
1528 if (((char *)ptr >= (char *)sub) &&
1529 ((char *)ptr < (char *)sub + sub->size))
1531 currentheap = sub;
1532 break;
1534 sub = sub->next;
1535 region_index++;
1537 if (currentheap == NULL)
1539 ERR("no matching subheap found, shouldn't happen !\n");
1540 SetLastError(ERROR_NO_MORE_ITEMS);
1541 goto HW_end;
1544 ptr += entry->cbData; /* point to next arena */
1545 if (ptr > (char *)currentheap + currentheap->size - 1)
1546 { /* proceed with next subheap */
1547 if (!(currentheap = currentheap->next))
1548 { /* successfully finished */
1549 TRACE("end reached.\n");
1550 SetLastError(ERROR_NO_MORE_ITEMS);
1551 goto HW_end;
1553 ptr = (char*)currentheap + currentheap->headerSize;
1557 entry->wFlags = 0;
1558 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1560 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1562 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1564 entry->lpData = pArena + 1;
1565 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1566 entry->cbOverhead = sizeof(ARENA_FREE);
1567 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1569 else
1571 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1573 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1575 entry->lpData = pArena + 1;
1576 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1577 entry->cbOverhead = sizeof(ARENA_INUSE);
1578 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1579 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1580 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1583 entry->iRegionIndex = region_index;
1585 /* first element of heap ? */
1586 if (ptr == (char *)(currentheap + currentheap->headerSize))
1588 entry->wFlags |= PROCESS_HEAP_REGION;
1589 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1590 entry->u.Region.dwUnCommittedSize =
1591 currentheap->size - currentheap->commitSize;
1592 entry->u.Region.lpFirstBlock = /* first valid block */
1593 currentheap + currentheap->headerSize;
1594 entry->u.Region.lpLastBlock = /* first invalid block */
1595 currentheap + currentheap->size;
1597 ret = TRUE;
1599 HW_end:
1600 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1602 return ret;
1606 /***********************************************************************
1607 * HEAP_CreateSystemHeap
1609 * Create the system heap.
1611 BOOL HEAP_CreateSystemHeap(void)
1613 SYSTEM_HEAP_DESCR *descr;
1614 HANDLE heap;
1615 HEAP *heapPtr;
1616 int created;
1618 HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1619 0, HEAP_DEF_SIZE, "__SystemHeap" );
1620 if (!map) return FALSE;
1621 created = (GetLastError() != ERROR_ALREADY_EXISTS);
1623 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1625 /* pre-defined address not available, use any one */
1626 fprintf( stderr, "Warning: system heap base address %p not available\n",
1627 SYSTEM_HEAP_BASE );
1628 if (!(heapPtr = MapViewOfFile( map, FILE_MAP_ALL_ACCESS, 0, 0, 0 )))
1630 CloseHandle( map );
1631 return FALSE;
1634 heap = (HANDLE)heapPtr;
1636 if (created) /* newly created heap */
1638 HEAP_InitSubHeap( heapPtr, heapPtr, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1639 HeapLock( heap );
1640 descr = heapPtr->private = HeapAlloc( heap, HEAP_ZERO_MEMORY, sizeof(*descr) );
1641 assert( descr );
1643 else
1645 /* wait for the heap to be initialized */
1646 while (!heapPtr->private) Sleep(1);
1647 HeapLock( heap );
1648 /* remap it to the right address if necessary */
1649 if (heapPtr->subheap.heap != heapPtr)
1651 void *base = heapPtr->subheap.heap;
1652 HeapUnlock( heap );
1653 UnmapViewOfFile( heapPtr );
1654 if (!(heapPtr = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, base )))
1656 fprintf( stderr, "Couldn't map system heap at the correct address (%p)\n", base );
1657 CloseHandle( map );
1658 return FALSE;
1660 heap = (HANDLE)heapPtr;
1661 HeapLock( heap );
1663 descr = heapPtr->private;
1664 assert( descr );
1666 SystemHeap = heap;
1667 SystemHeapDescr = descr;
1668 HeapUnlock( heap );
1669 CloseHandle( map );
1670 return TRUE;
1674 /***********************************************************************
1675 * GetProcessHeap (KERNEL32.259)
1677 HANDLE WINAPI GetProcessHeap(void)
1679 return (HANDLE)processHeap;
1683 /***********************************************************************
1684 * GetProcessHeaps (KERNEL32.376)
1686 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1688 DWORD total;
1689 HEAP *ptr;
1691 if (!processHeap) return 0; /* should never happen */
1692 total = 1; /* main heap */
1693 EnterCriticalSection( &processHeap->critSection );
1694 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1695 if (total <= count)
1697 *heaps++ = (HANDLE)processHeap;
1698 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1700 LeaveCriticalSection( &processHeap->critSection );
1701 return total;
1705 /***********************************************************************
1706 * 32-bit local heap functions (Win95; undocumented)
1709 #define HTABLE_SIZE 0x10000
1710 #define HTABLE_PAGESIZE 0x1000
1711 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1713 #include "pshpack1.h"
1714 typedef struct _LOCAL32HEADER
1716 WORD freeListFirst[HTABLE_NPAGES];
1717 WORD freeListSize[HTABLE_NPAGES];
1718 WORD freeListLast[HTABLE_NPAGES];
1720 DWORD selectorTableOffset;
1721 WORD selectorTableSize;
1722 WORD selectorDelta;
1724 DWORD segment;
1725 LPBYTE base;
1727 DWORD limit;
1728 DWORD flags;
1730 DWORD magic;
1731 HANDLE heap;
1733 } LOCAL32HEADER;
1734 #include "poppack.h"
1736 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1738 /***********************************************************************
1739 * Local32Init (KERNEL.208)
1741 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1742 DWORD heapSize, DWORD flags )
1744 DWORD totSize, segSize = 0;
1745 LPBYTE base;
1746 LOCAL32HEADER *header;
1747 HEAP *heap;
1748 WORD *selectorTable;
1749 WORD selectorEven, selectorOdd;
1750 int i, nrBlocks;
1752 /* Determine new heap size */
1754 if ( segment )
1756 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1757 return 0;
1758 else
1759 segSize++;
1762 if ( heapSize == -1L )
1763 heapSize = 1024L*1024L; /* FIXME */
1765 heapSize = (heapSize + 0xffff) & 0xffff0000;
1766 segSize = (segSize + 0x0fff) & 0xfffff000;
1767 totSize = segSize + HTABLE_SIZE + heapSize;
1770 /* Allocate memory and initialize heap */
1772 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1773 return 0;
1775 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1776 MEM_COMMIT, PAGE_READWRITE ) )
1778 VirtualFree( base, 0, MEM_RELEASE );
1779 return 0;
1782 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1783 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1785 VirtualFree( base, 0, MEM_RELEASE );
1786 return 0;
1790 /* Set up header and handle table */
1792 header = (LOCAL32HEADER *)(base + segSize);
1793 header->base = base;
1794 header->limit = HTABLE_PAGESIZE-1;
1795 header->flags = 0;
1796 header->magic = LOCAL32_MAGIC;
1797 header->heap = (HANDLE)heap;
1799 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1800 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1801 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1803 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1804 *(DWORD *)((LPBYTE)header + i) = i+4;
1806 header->freeListFirst[1] = 0xffff;
1809 /* Set up selector table */
1811 nrBlocks = (totSize + 0x7fff) >> 15;
1812 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1813 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1814 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1815 if ( !selectorTable || !selectorEven || !selectorOdd )
1817 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1818 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1819 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1820 HeapDestroy( header->heap );
1821 VirtualFree( base, 0, MEM_RELEASE );
1822 return 0;
1825 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1826 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1827 header->selectorDelta = selectorEven - selectorOdd;
1828 header->segment = segment? segment : selectorEven;
1830 for (i = 0; i < nrBlocks; i++)
1831 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1832 : selectorEven + ((i >> 1) << __AHSHIFT);
1834 /* Move old segment */
1836 if ( segment )
1838 /* FIXME: This is somewhat ugly and relies on implementation
1839 details about 16-bit global memory handles ... */
1841 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1842 memcpy( base, oldBase, segSize );
1843 GLOBAL_MoveBlock( segment, base, totSize );
1844 HeapFree( SystemHeap, 0, oldBase );
1847 return (HANDLE)header;
1850 /***********************************************************************
1851 * Local32_SearchHandle
1853 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1855 LPDWORD handle;
1857 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1858 handle < (LPDWORD)((LPBYTE)header + header->limit);
1859 handle++)
1861 if (*handle == addr)
1862 return handle;
1865 return NULL;
1868 /***********************************************************************
1869 * Local32_ToHandle
1871 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1872 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1874 *handle = NULL;
1875 *ptr = NULL;
1877 switch (type)
1879 case -2: /* 16:16 pointer, no handles */
1880 *ptr = MapSL( addr );
1881 *handle = (LPDWORD)*ptr;
1882 break;
1884 case -1: /* 32-bit offset, no handles */
1885 *ptr = header->base + addr;
1886 *handle = (LPDWORD)*ptr;
1887 break;
1889 case 0: /* handle */
1890 if ( addr >= sizeof(LOCAL32HEADER)
1891 && addr < header->limit && !(addr & 3)
1892 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1894 *handle = (LPDWORD)((LPBYTE)header + addr);
1895 *ptr = header->base + **handle;
1897 break;
1899 case 1: /* 16:16 pointer */
1900 *ptr = MapSL( addr );
1901 *handle = Local32_SearchHandle( header, *ptr - header->base );
1902 break;
1904 case 2: /* 32-bit offset */
1905 *ptr = header->base + addr;
1906 *handle = Local32_SearchHandle( header, *ptr - header->base );
1907 break;
1911 /***********************************************************************
1912 * Local32_FromHandle
1914 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1915 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1917 switch (type)
1919 case -2: /* 16:16 pointer */
1920 case 1:
1922 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1923 DWORD offset = (LPBYTE)ptr - header->base;
1924 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1926 break;
1928 case -1: /* 32-bit offset */
1929 case 2:
1930 *addr = ptr - header->base;
1931 break;
1933 case 0: /* handle */
1934 *addr = (LPBYTE)handle - (LPBYTE)header;
1935 break;
1939 /***********************************************************************
1940 * Local32Alloc (KERNEL.209)
1942 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1944 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1945 LPDWORD handle;
1946 LPBYTE ptr;
1947 DWORD addr;
1949 /* Allocate memory */
1950 ptr = HeapAlloc( header->heap,
1951 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1952 if (!ptr) return 0;
1955 /* Allocate handle if requested */
1956 if (type >= 0)
1958 int page, i;
1960 /* Find first page of handle table with free slots */
1961 for (page = 0; page < HTABLE_NPAGES; page++)
1962 if (header->freeListFirst[page] != 0)
1963 break;
1964 if (page == HTABLE_NPAGES)
1966 WARN("Out of handles!\n" );
1967 HeapFree( header->heap, 0, ptr );
1968 return 0;
1971 /* If virgin page, initialize it */
1972 if (header->freeListFirst[page] == 0xffff)
1974 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1975 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1977 WARN("Cannot grow handle table!\n" );
1978 HeapFree( header->heap, 0, ptr );
1979 return 0;
1982 header->limit += HTABLE_PAGESIZE;
1984 header->freeListFirst[page] = 0;
1985 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1986 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1988 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1989 *(DWORD *)((LPBYTE)header + i) = i+4;
1991 if (page < HTABLE_NPAGES-1)
1992 header->freeListFirst[page+1] = 0xffff;
1995 /* Allocate handle slot from page */
1996 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1997 if (--header->freeListSize[page] == 0)
1998 header->freeListFirst[page] = header->freeListLast[page] = 0;
1999 else
2000 header->freeListFirst[page] = *handle;
2002 /* Store 32-bit offset in handle slot */
2003 *handle = ptr - header->base;
2005 else
2007 handle = (LPDWORD)ptr;
2008 header->flags |= 1;
2012 /* Convert handle to requested output type */
2013 Local32_FromHandle( header, type, &addr, handle, ptr );
2014 return addr;
2017 /***********************************************************************
2018 * Local32ReAlloc (KERNEL.210)
2020 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2021 DWORD size, DWORD flags )
2023 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2024 LPDWORD handle;
2025 LPBYTE ptr;
2027 if (!addr)
2028 return Local32Alloc16( heap, size, type, flags );
2030 /* Retrieve handle and pointer */
2031 Local32_ToHandle( header, type, addr, &handle, &ptr );
2032 if (!handle) return FALSE;
2034 /* Reallocate memory block */
2035 ptr = HeapReAlloc( header->heap,
2036 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2037 ptr, size );
2038 if (!ptr) return 0;
2040 /* Modify handle */
2041 if (type >= 0)
2042 *handle = ptr - header->base;
2043 else
2044 handle = (LPDWORD)ptr;
2046 /* Convert handle to requested output type */
2047 Local32_FromHandle( header, type, &addr, handle, ptr );
2048 return addr;
2051 /***********************************************************************
2052 * Local32Free (KERNEL.211)
2054 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2056 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2057 LPDWORD handle;
2058 LPBYTE ptr;
2060 /* Retrieve handle and pointer */
2061 Local32_ToHandle( header, type, addr, &handle, &ptr );
2062 if (!handle) return FALSE;
2064 /* Free handle if necessary */
2065 if (type >= 0)
2067 int offset = (LPBYTE)handle - (LPBYTE)header;
2068 int page = offset >> 12;
2070 /* Return handle slot to page free list */
2071 if (header->freeListSize[page]++ == 0)
2072 header->freeListFirst[page] = header->freeListLast[page] = offset;
2073 else
2074 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2075 header->freeListLast[page] = offset;
2077 *handle = 0;
2079 /* Shrink handle table when possible */
2080 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2082 if ( VirtualFree( (LPBYTE)header +
2083 (header->limit & ~(HTABLE_PAGESIZE-1)),
2084 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2085 break;
2087 header->limit -= HTABLE_PAGESIZE;
2088 header->freeListFirst[page] = 0xffff;
2089 page--;
2093 /* Free memory */
2094 return HeapFree( header->heap, 0, ptr );
2097 /***********************************************************************
2098 * Local32Translate (KERNEL.213)
2100 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2102 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2103 LPDWORD handle;
2104 LPBYTE ptr;
2106 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2107 if (!handle) return 0;
2109 Local32_FromHandle( header, type2, &addr, handle, ptr );
2110 return addr;
2113 /***********************************************************************
2114 * Local32Size (KERNEL.214)
2116 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2118 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2119 LPDWORD handle;
2120 LPBYTE ptr;
2122 Local32_ToHandle( header, type, addr, &handle, &ptr );
2123 if (!handle) return 0;
2125 return HeapSize( header->heap, 0, ptr );
2128 /***********************************************************************
2129 * Local32ValidHandle (KERNEL.215)
2131 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2133 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2134 LPDWORD handle;
2135 LPBYTE ptr;
2137 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2138 return handle != NULL;
2141 /***********************************************************************
2142 * Local32GetSegment (KERNEL.229)
2144 WORD WINAPI Local32GetSegment16( HANDLE heap )
2146 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2147 return header->segment;
2150 /***********************************************************************
2151 * Local32_GetHeap
2153 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2155 WORD selector = GlobalHandleToSel16( handle );
2156 DWORD base = GetSelectorBase( selector );
2157 DWORD limit = GetSelectorLimit16( selector );
2159 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2160 it this way ... */
2162 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2163 return (LOCAL32HEADER *)base;
2165 base += 0x10000;
2166 limit -= 0x10000;
2168 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2169 return (LOCAL32HEADER *)base;
2171 return NULL;
2174 /***********************************************************************
2175 * Local32Info (KERNEL.444) (TOOLHELP.84)
2177 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2179 SUBHEAP *heapPtr;
2180 LPBYTE ptr;
2181 int i;
2183 LOCAL32HEADER *header = Local32_GetHeap( handle );
2184 if ( !header ) return FALSE;
2186 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2187 return FALSE;
2189 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2190 pLocal32Info->dwMemReserved = heapPtr->size;
2191 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2192 pLocal32Info->dwTotalFree = 0L;
2193 pLocal32Info->dwLargestFreeBlock = 0L;
2195 /* Note: Local32 heaps always have only one subheap! */
2196 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2197 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2199 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2201 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2202 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2203 ptr += sizeof(*pArena) + size;
2205 pLocal32Info->dwTotalFree += size;
2206 if ( size > pLocal32Info->dwLargestFreeBlock )
2207 pLocal32Info->dwLargestFreeBlock = size;
2209 else
2211 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2212 DWORD size = (pArena->size & ARENA_SIZE_MASK);
2213 ptr += sizeof(*pArena) + size;
2217 pLocal32Info->dwcFreeHandles = 0;
2218 for ( i = 0; i < HTABLE_NPAGES; i++ )
2220 if ( header->freeListFirst[i] == 0xffff ) break;
2221 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2223 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2225 return TRUE;
2228 /***********************************************************************
2229 * Local32First (KERNEL.445) (TOOLHELP.85)
2231 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2233 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2234 return FALSE;
2237 /***********************************************************************
2238 * Local32Next (KERNEL.446) (TOOLHELP.86)
2240 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2242 FIXME("(%p): stub!\n", pLocal32Entry );
2243 return FALSE;