Allow depth of DIB to differ from depth of bitmap in GetDIBits.
[wine.git] / memory / heap.c
blobe6b195d195b2b2dcc14b3263981a41d2f4ba2029
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 <string.h>
11 #include "wine/winbase16.h"
12 #include "wine/winestring.h"
13 #include "selectors.h"
14 #include "global.h"
15 #include "winbase.h"
16 #include "winerror.h"
17 #include "winnt.h"
18 #include "heap.h"
19 #include "toolhelp.h"
20 #include "debug.h"
22 /* Note: the heap data structures are based on what Pietrek describes in his
23 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
24 * the same, but could be easily adapted if it turns out some programs
25 * require it.
28 typedef struct tagARENA_INUSE
30 DWORD size; /* Block size; must be the first field */
31 WORD threadId; /* Allocating thread id */
32 WORD magic; /* Magic number */
33 DWORD callerEIP; /* EIP of caller upon allocation */
34 } ARENA_INUSE;
36 typedef struct tagARENA_FREE
38 DWORD size; /* Block size; must be the first field */
39 WORD threadId; /* Freeing thread id */
40 WORD magic; /* Magic number */
41 struct tagARENA_FREE *next; /* Next free arena */
42 struct tagARENA_FREE *prev; /* Prev free arena */
43 } ARENA_FREE;
45 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
46 #define ARENA_FLAG_PREV_FREE 0x00000002
47 #define ARENA_SIZE_MASK 0xfffffffc
48 #define ARENA_INUSE_MAGIC 0x4842 /* Value for arena 'magic' field */
49 #define ARENA_FREE_MAGIC 0x4846 /* Value for arena 'magic' field */
51 #define ARENA_INUSE_FILLER 0x55
52 #define ARENA_FREE_FILLER 0xaa
54 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
56 /* Max size of the blocks on the free lists */
57 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
59 0x20, 0x80, 0x200, 0xffffffff
62 typedef struct
64 DWORD size;
65 ARENA_FREE arena;
66 } FREE_LIST_ENTRY;
68 struct tagHEAP;
70 typedef struct tagSUBHEAP
72 DWORD size; /* Size of the whole sub-heap */
73 DWORD commitSize; /* Committed size of the sub-heap */
74 DWORD headerSize; /* Size of the heap header */
75 struct tagSUBHEAP *next; /* Next sub-heap */
76 struct tagHEAP *heap; /* Main heap structure */
77 DWORD magic; /* Magic number */
78 WORD selector; /* Selector for HEAP_WINE_SEGPTR heaps */
79 } SUBHEAP;
81 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
83 typedef struct tagHEAP
85 SUBHEAP subheap; /* First sub-heap */
86 struct tagHEAP *next; /* Next heap for this process */
87 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
88 CRITICAL_SECTION critSection; /* Critical section for serialization */
89 DWORD flags; /* Heap flags */
90 DWORD magic; /* Magic number */
91 } HEAP;
93 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
95 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
96 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
98 HANDLE SystemHeap = 0;
99 HANDLE SegptrHeap = 0;
102 /***********************************************************************
103 * HEAP_Dump
105 void HEAP_Dump( HEAP *heap )
107 int i;
108 SUBHEAP *subheap;
109 char *ptr;
111 DUMP( "Heap: %08lx\n", (DWORD)heap );
112 DUMP( "Next: %08lx Sub-heaps: %08lx",
113 (DWORD)heap->next, (DWORD)&heap->subheap );
114 subheap = &heap->subheap;
115 while (subheap->next)
117 DUMP( " -> %08lx", (DWORD)subheap->next );
118 subheap = subheap->next;
121 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
122 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
123 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
124 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
125 heap->freeList[i].arena.threadId,
126 (DWORD)heap->freeList[i].arena.prev,
127 (DWORD)heap->freeList[i].arena.next );
129 subheap = &heap->subheap;
130 while (subheap)
132 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
133 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
134 (DWORD)subheap, subheap->size, subheap->commitSize );
136 DUMP( "\n Block Stat Size Id\n" );
137 ptr = (char*)subheap + subheap->headerSize;
138 while (ptr < (char *)subheap + subheap->size)
140 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
142 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
143 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
144 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
145 pArena->threadId, (DWORD)pArena->prev,
146 (DWORD)pArena->next);
147 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
148 arenaSize += sizeof(ARENA_FREE);
149 freeSize += pArena->size & ARENA_SIZE_MASK;
151 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
153 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
154 DUMP( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
155 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
156 pArena->threadId, *((DWORD *)pArena - 1),
157 pArena->callerEIP );
158 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
159 arenaSize += sizeof(ARENA_INUSE);
160 usedSize += pArena->size & ARENA_SIZE_MASK;
162 else
164 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
165 DUMP( "%08lx used %08lx %04x EIP=%08lx\n",
166 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
167 pArena->threadId, pArena->callerEIP );
168 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
169 arenaSize += sizeof(ARENA_INUSE);
170 usedSize += pArena->size & ARENA_SIZE_MASK;
173 DUMP( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
174 subheap->size, subheap->commitSize, freeSize, usedSize,
175 arenaSize, (arenaSize * 100) / subheap->size );
176 subheap = subheap->next;
181 /***********************************************************************
182 * HEAP_GetPtr
183 * RETURNS
184 * Pointer to the heap
185 * NULL: Failure
187 static HEAP *HEAP_GetPtr(
188 HANDLE heap /* [in] Handle to the heap */
190 HEAP *heapPtr = (HEAP *)heap;
191 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
193 ERR(heap, "Invalid heap %08x!\n", heap );
194 SetLastError( ERROR_INVALID_HANDLE );
195 return NULL;
197 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
199 HEAP_Dump( heapPtr );
200 assert( FALSE );
201 SetLastError( ERROR_INVALID_HANDLE );
202 return NULL;
204 return heapPtr;
208 /***********************************************************************
209 * HEAP_InsertFreeBlock
211 * Insert a free block into the free list.
213 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
215 FREE_LIST_ENTRY *pEntry = heap->freeList;
216 while (pEntry->size < pArena->size) pEntry++;
217 pArena->size |= ARENA_FLAG_FREE;
218 pArena->next = pEntry->arena.next;
219 pArena->next->prev = pArena;
220 pArena->prev = &pEntry->arena;
221 pEntry->arena.next = pArena;
225 /***********************************************************************
226 * HEAP_FindSubHeap
227 * Find the sub-heap containing a given address.
229 * RETURNS
230 * Pointer: Success
231 * NULL: Failure
233 static SUBHEAP *HEAP_FindSubHeap(
234 HEAP *heap, /* [in] Heap pointer */
235 LPCVOID ptr /* [in] Address */
237 SUBHEAP *sub = &heap->subheap;
238 while (sub)
240 if (((char *)ptr >= (char *)sub) &&
241 ((char *)ptr < (char *)sub + sub->size)) return sub;
242 sub = sub->next;
244 return NULL;
248 /***********************************************************************
249 * HEAP_Commit
251 * Make sure the heap storage is committed up to (not including) ptr.
253 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
255 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
256 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
257 if (size > subheap->size) size = subheap->size;
258 if (size <= subheap->commitSize) return TRUE;
259 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
260 size - subheap->commitSize, MEM_COMMIT,
261 PAGE_EXECUTE_READWRITE))
263 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
264 size - subheap->commitSize,
265 (DWORD)((char *)subheap + subheap->commitSize),
266 (DWORD)subheap->heap );
267 return FALSE;
269 subheap->commitSize = size;
270 return TRUE;
274 /***********************************************************************
275 * HEAP_Decommit
277 * If possible, decommit the heap storage from (including) 'ptr'.
279 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
281 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
282 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
283 if (size >= subheap->commitSize) return TRUE;
284 if (!VirtualFree( (char *)subheap + size,
285 subheap->commitSize - size, MEM_DECOMMIT ))
287 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
288 subheap->commitSize - size,
289 (DWORD)((char *)subheap + size),
290 (DWORD)subheap->heap );
291 return FALSE;
293 subheap->commitSize = size;
294 return TRUE;
298 /***********************************************************************
299 * HEAP_CreateFreeBlock
301 * Create a free block at a specified address. 'size' is the size of the
302 * whole block, including the new arena.
304 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
306 ARENA_FREE *pFree;
308 /* Create a free arena */
310 pFree = (ARENA_FREE *)ptr;
311 pFree->threadId = GetCurrentTask();
312 pFree->magic = ARENA_FREE_MAGIC;
314 /* If debugging, erase the freed block content */
316 if (TRACE_ON(heap))
318 char *pEnd = (char *)ptr + size;
319 if (pEnd > (char *)subheap + subheap->commitSize)
320 pEnd = (char *)subheap + subheap->commitSize;
321 if (pEnd > (char *)(pFree + 1))
322 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
325 /* Check if next block is free also */
327 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
328 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
330 /* Remove the next arena from the free list */
331 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
332 pNext->next->prev = pNext->prev;
333 pNext->prev->next = pNext->next;
334 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
335 if (TRACE_ON(heap))
336 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
339 /* Set the next block PREV_FREE flag and pointer */
341 if ((char *)ptr + size < (char *)subheap + subheap->size)
343 DWORD *pNext = (DWORD *)((char *)ptr + size);
344 *pNext |= ARENA_FLAG_PREV_FREE;
345 *(ARENA_FREE **)(pNext - 1) = pFree;
348 /* Last, insert the new block into the free list */
350 pFree->size = size - sizeof(*pFree);
351 HEAP_InsertFreeBlock( subheap->heap, pFree );
355 /***********************************************************************
356 * HEAP_MakeInUseBlockFree
358 * Turn an in-use block into a free block. Can also decommit the end of
359 * the heap, and possibly even free the sub-heap altogether.
361 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
363 ARENA_FREE *pFree;
364 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
366 /* Check if we can merge with previous block */
368 if (pArena->size & ARENA_FLAG_PREV_FREE)
370 pFree = *((ARENA_FREE **)pArena - 1);
371 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
372 /* Remove it from the free list */
373 pFree->next->prev = pFree->prev;
374 pFree->prev->next = pFree->next;
376 else pFree = (ARENA_FREE *)pArena;
378 /* Create a free block */
380 HEAP_CreateFreeBlock( subheap, pFree, size );
381 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
382 if ((char *)pFree + size < (char *)subheap + subheap->size)
383 return; /* Not the last block, so nothing more to do */
385 /* Free the whole sub-heap if it's empty and not the original one */
387 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
388 (subheap != &subheap->heap->subheap))
390 SUBHEAP *pPrev = &subheap->heap->subheap;
391 /* Remove the free block from the list */
392 pFree->next->prev = pFree->prev;
393 pFree->prev->next = pFree->next;
394 /* Remove the subheap from the list */
395 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
396 if (pPrev) pPrev->next = subheap->next;
397 /* Free the memory */
398 subheap->magic = 0;
399 if (subheap->selector) FreeSelector16( subheap->selector );
400 VirtualFree( subheap, 0, MEM_RELEASE );
401 return;
404 /* Decommit the end of the heap */
406 HEAP_Decommit( subheap, pFree + 1 );
410 /***********************************************************************
411 * HEAP_ShrinkBlock
413 * Shrink an in-use block.
415 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
417 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
419 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
420 (pArena->size & ARENA_SIZE_MASK) - size );
421 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
423 else
425 /* Turn off PREV_FREE flag in next block */
426 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
427 if (pNext < (char *)subheap + subheap->size)
428 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
432 /***********************************************************************
433 * HEAP_InitSubHeap
435 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
436 DWORD commitSize, DWORD totalSize )
438 SUBHEAP *subheap = (SUBHEAP *)address;
439 WORD selector = 0;
440 FREE_LIST_ENTRY *pEntry;
441 int i;
443 /* Commit memory */
445 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
447 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
448 commitSize, (DWORD)address );
449 return FALSE;
452 /* Allocate a selector if needed */
454 if (flags & HEAP_WINE_SEGPTR)
456 selector = SELECTOR_AllocBlock( address, totalSize,
457 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
458 ? SEGMENT_CODE : SEGMENT_DATA,
459 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
460 if (!selector)
462 ERR(heap, "Could not allocate selector\n" );
463 return FALSE;
467 /* Fill the sub-heap structure */
469 subheap->heap = heap;
470 subheap->selector = selector;
471 subheap->size = totalSize;
472 subheap->commitSize = commitSize;
473 subheap->magic = SUBHEAP_MAGIC;
475 if ( subheap != (SUBHEAP *)heap )
477 /* If this is a secondary subheap, insert it into list */
479 subheap->headerSize = sizeof(SUBHEAP);
480 subheap->next = heap->subheap.next;
481 heap->subheap.next = subheap;
483 else
485 /* If this is a primary subheap, initialize main heap */
487 subheap->headerSize = sizeof(HEAP);
488 subheap->next = NULL;
489 heap->next = NULL;
490 heap->flags = flags;
491 heap->magic = HEAP_MAGIC;
493 /* Build the free lists */
495 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
497 pEntry->size = HEAP_freeListSizes[i];
498 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
499 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
500 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
501 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
502 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
503 pEntry->arena.threadId = 0;
504 pEntry->arena.magic = ARENA_FREE_MAGIC;
507 /* Initialize critical section */
509 InitializeCriticalSection( &heap->critSection );
510 if (!SystemHeap) /* System heap critical section has to be global */
511 MakeCriticalSectionGlobal( &heap->critSection );
514 /* Create the first free block */
516 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
517 subheap->size - subheap->headerSize );
519 return TRUE;
522 /***********************************************************************
523 * HEAP_CreateSubHeap
525 * Create a sub-heap of the given size.
526 * If heap == NULL, creates a main heap.
528 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags,
529 DWORD commitSize, DWORD totalSize )
531 LPVOID address;
533 /* Round-up sizes on a 64K boundary */
535 if (flags & HEAP_WINE_SEGPTR)
537 totalSize = commitSize = 0x10000; /* Only 64K at a time for SEGPTRs */
539 else
541 totalSize = (totalSize + 0xffff) & 0xffff0000;
542 commitSize = (commitSize + 0xffff) & 0xffff0000;
543 if (!commitSize) commitSize = 0x10000;
544 if (totalSize < commitSize) totalSize = commitSize;
547 /* Allocate the memory block */
549 if (!(address = VirtualAlloc( NULL, totalSize,
550 MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
552 WARN(heap, "Could not VirtualAlloc %08lx bytes\n",
553 totalSize );
554 return NULL;
557 /* Initialize subheap */
559 if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address,
560 address, flags, commitSize, totalSize ))
562 VirtualFree( address, 0, MEM_RELEASE );
563 return NULL;
566 return (SUBHEAP *)address;
570 /***********************************************************************
571 * HEAP_FindFreeBlock
573 * Find a free block at least as large as the requested size, and make sure
574 * the requested size is committed.
576 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
577 SUBHEAP **ppSubHeap )
579 SUBHEAP *subheap;
580 ARENA_FREE *pArena;
581 FREE_LIST_ENTRY *pEntry = heap->freeList;
583 /* Find a suitable free list, and in it find a block large enough */
585 while (pEntry->size < size) pEntry++;
586 pArena = pEntry->arena.next;
587 while (pArena != &heap->freeList[0].arena)
589 if (pArena->size > size)
591 subheap = HEAP_FindSubHeap( heap, pArena );
592 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
593 + size + HEAP_MIN_BLOCK_SIZE))
594 return NULL;
595 *ppSubHeap = subheap;
596 return pArena;
599 pArena = pArena->next;
602 /* If no block was found, attempt to grow the heap */
604 if (!(heap->flags & HEAP_GROWABLE))
606 WARN(heap, "Not enough space in heap %08lx for %08lx bytes\n",
607 (DWORD)heap, size );
608 return NULL;
610 size += sizeof(SUBHEAP) + sizeof(ARENA_FREE);
611 if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
612 MAX( HEAP_DEF_SIZE, size ) )))
613 return NULL;
615 TRACE(heap, "created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
616 (DWORD)subheap, size, (DWORD)heap );
618 *ppSubHeap = subheap;
619 return (ARENA_FREE *)(subheap + 1);
623 /***********************************************************************
624 * HEAP_IsValidArenaPtr
626 * Check that the pointer is inside the range possible for arenas.
628 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
630 int i;
631 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
632 if (!subheap) return FALSE;
633 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
634 if (subheap != &heap->subheap) return FALSE;
635 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
636 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
637 return FALSE;
641 /***********************************************************************
642 * HEAP_ValidateFreeArena
644 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
646 char *heapEnd = (char *)subheap + subheap->size;
648 /* Check magic number */
649 if (pArena->magic != ARENA_FREE_MAGIC)
651 ERR(heap, "Heap %08lx: invalid free arena magic for %08lx\n",
652 (DWORD)subheap->heap, (DWORD)pArena );
653 return FALSE;
655 /* Check size flags */
656 if (!(pArena->size & ARENA_FLAG_FREE) ||
657 (pArena->size & ARENA_FLAG_PREV_FREE))
659 ERR(heap, "Heap %08lx: bad flags %lx for free arena %08lx\n",
660 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
662 /* Check arena size */
663 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
665 ERR(heap, "Heap %08lx: bad size %08lx for free arena %08lx\n",
666 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
667 return FALSE;
669 /* Check that next pointer is valid */
670 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
672 ERR(heap, "Heap %08lx: bad next ptr %08lx for arena %08lx\n",
673 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
674 return FALSE;
676 /* Check that next arena is free */
677 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
678 (pArena->next->magic != ARENA_FREE_MAGIC))
680 ERR(heap, "Heap %08lx: next arena %08lx invalid for %08lx\n",
681 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
682 return FALSE;
684 /* Check that prev pointer is valid */
685 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
687 ERR(heap, "Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
688 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
689 return FALSE;
691 /* Check that prev arena is free */
692 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
693 (pArena->prev->magic != ARENA_FREE_MAGIC))
695 ERR(heap, "Heap %08lx: prev arena %08lx invalid for %08lx\n",
696 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
697 return FALSE;
699 /* Check that next block has PREV_FREE flag */
700 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
702 if (!(*(DWORD *)((char *)(pArena + 1) +
703 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
705 ERR(heap, "Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
706 (DWORD)subheap->heap, (DWORD)pArena );
707 return FALSE;
709 /* Check next block back pointer */
710 if (*((ARENA_FREE **)((char *)(pArena + 1) +
711 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
713 ERR(heap, "Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
714 (DWORD)subheap->heap, (DWORD)pArena,
715 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
716 return FALSE;
719 return TRUE;
723 /***********************************************************************
724 * HEAP_ValidateInUseArena
726 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
728 char *heapEnd = (char *)subheap + subheap->size;
730 /* Check magic number */
731 if (pArena->magic != ARENA_INUSE_MAGIC)
733 ERR(heap, "Heap %08lx: invalid in-use arena magic for %08lx\n",
734 (DWORD)subheap->heap, (DWORD)pArena );
735 return FALSE;
737 /* Check size flags */
738 if (pArena->size & ARENA_FLAG_FREE)
740 ERR(heap, "Heap %08lx: bad flags %lx for in-use arena %08lx\n",
741 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
743 /* Check arena size */
744 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
746 ERR(heap, "Heap %08lx: bad size %08lx for in-use arena %08lx\n",
747 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
748 return FALSE;
750 /* Check next arena PREV_FREE flag */
751 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
752 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
754 ERR(heap, "Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
755 (DWORD)subheap->heap, (DWORD)pArena );
756 return FALSE;
758 /* Check prev free arena */
759 if (pArena->size & ARENA_FLAG_PREV_FREE)
761 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
762 /* Check prev pointer */
763 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
765 ERR(heap, "Heap %08lx: bad back ptr %08lx for arena %08lx\n",
766 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
767 return FALSE;
769 /* Check that prev arena is free */
770 if (!(pPrev->size & ARENA_FLAG_FREE) ||
771 (pPrev->magic != ARENA_FREE_MAGIC))
773 ERR(heap, "Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
774 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
775 return FALSE;
777 /* Check that prev arena is really the previous block */
778 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
780 ERR(heap, "Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
781 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
782 return FALSE;
785 return TRUE;
789 /***********************************************************************
790 * HEAP_IsInsideHeap
791 * Checks whether the pointer points to a block inside a given heap.
793 * NOTES
794 * Should this return BOOL32?
796 * RETURNS
797 * !0: Success
798 * 0: Failure
800 int HEAP_IsInsideHeap(
801 HANDLE heap, /* [in] Heap */
802 DWORD flags, /* [in] Flags */
803 LPCVOID ptr /* [in] Pointer */
805 HEAP *heapPtr = HEAP_GetPtr( heap );
806 SUBHEAP *subheap;
807 int ret;
809 /* Validate the parameters */
811 if (!heapPtr) return 0;
812 flags |= heapPtr->flags;
813 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
814 ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
815 (((char *)ptr >= (char *)subheap + subheap->headerSize
816 + sizeof(ARENA_INUSE))));
817 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
818 return ret;
822 /***********************************************************************
823 * HEAP_GetSegptr
825 * Transform a linear pointer into a SEGPTR. The pointer must have been
826 * allocated from a HEAP_WINE_SEGPTR heap.
828 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
830 HEAP *heapPtr = HEAP_GetPtr( heap );
831 SUBHEAP *subheap;
832 SEGPTR ret;
834 /* Validate the parameters */
836 if (!heapPtr) return 0;
837 flags |= heapPtr->flags;
838 if (!(flags & HEAP_WINE_SEGPTR))
840 ERR(heap, "Heap %08x is not a SEGPTR heap\n",
841 heap );
842 return 0;
844 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
846 /* Get the subheap */
848 if (!(subheap = HEAP_FindSubHeap( heapPtr, ptr )))
850 ERR(heap, "%p is not inside heap %08x\n",
851 ptr, heap );
852 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
853 return 0;
856 /* Build the SEGPTR */
858 ret = PTR_SEG_OFF_TO_SEGPTR(subheap->selector, (DWORD)ptr-(DWORD)subheap);
859 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
860 return ret;
864 /***********************************************************************
865 * HeapCreate (KERNEL32.336)
866 * RETURNS
867 * Handle of heap: Success
868 * NULL: Failure
870 HANDLE WINAPI HeapCreate(
871 DWORD flags, /* [in] Heap allocation flag */
872 DWORD initialSize, /* [in] Initial heap size */
873 DWORD maxSize /* [in] Maximum heap size */
875 SUBHEAP *subheap;
877 /* Allocate the heap block */
879 if (!maxSize)
881 maxSize = HEAP_DEF_SIZE;
882 flags |= HEAP_GROWABLE;
884 if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
886 SetLastError( ERROR_OUTOFMEMORY );
887 return 0;
890 return (HANDLE)subheap;
893 /***********************************************************************
894 * HeapDestroy (KERNEL32.337)
895 * RETURNS
896 * TRUE: Success
897 * FALSE: Failure
899 BOOL WINAPI HeapDestroy(
900 HANDLE heap /* [in] Handle of heap */
902 HEAP *heapPtr = HEAP_GetPtr( heap );
903 SUBHEAP *subheap;
905 TRACE(heap, "%08x\n", heap );
906 if (!heapPtr) return FALSE;
908 DeleteCriticalSection( &heapPtr->critSection );
909 subheap = &heapPtr->subheap;
910 while (subheap)
912 SUBHEAP *next = subheap->next;
913 if (subheap->selector) FreeSelector16( subheap->selector );
914 VirtualFree( subheap, 0, MEM_RELEASE );
915 subheap = next;
917 return TRUE;
921 /***********************************************************************
922 * HeapAlloc (KERNEL32.334)
923 * RETURNS
924 * Pointer to allocated memory block
925 * NULL: Failure
927 LPVOID WINAPI HeapAlloc(
928 HANDLE heap, /* [in] Handle of private heap block */
929 DWORD flags, /* [in] Heap allocation control flags */
930 DWORD size /* [in] Number of bytes to allocate */
932 ARENA_FREE *pArena;
933 ARENA_INUSE *pInUse;
934 SUBHEAP *subheap;
935 HEAP *heapPtr = HEAP_GetPtr( heap );
937 /* Validate the parameters */
939 if (!heapPtr) return NULL;
940 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
941 flags |= heapPtr->flags;
942 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
943 size = (size + 3) & ~3;
944 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
946 /* Locate a suitable free block */
948 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
950 TRACE(heap, "(%08x,%08lx,%08lx): returning NULL\n",
951 heap, flags, size );
952 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
953 SetLastError( ERROR_COMMITMENT_LIMIT );
954 return NULL;
957 /* Remove the arena from the free list */
959 pArena->next->prev = pArena->prev;
960 pArena->prev->next = pArena->next;
962 /* Build the in-use arena */
964 pInUse = (ARENA_INUSE *)pArena;
965 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
966 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
967 pInUse->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
968 pInUse->threadId = GetCurrentTask();
969 pInUse->magic = ARENA_INUSE_MAGIC;
971 /* Shrink the block */
973 HEAP_ShrinkBlock( subheap, pInUse, size );
975 if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
976 else if (TRACE_ON(heap)) memset( pInUse + 1, ARENA_INUSE_FILLER, size );
978 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
980 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
981 heap, flags, size, (DWORD)(pInUse + 1) );
982 return (LPVOID)(pInUse + 1);
986 /***********************************************************************
987 * HeapFree (KERNEL32.338)
988 * RETURNS
989 * TRUE: Success
990 * FALSE: Failure
992 BOOL WINAPI HeapFree(
993 HANDLE heap, /* [in] Handle of heap */
994 DWORD flags, /* [in] Heap freeing flags */
995 LPVOID ptr /* [in] Address of memory to free */
997 ARENA_INUSE *pInUse;
998 SUBHEAP *subheap;
999 HEAP *heapPtr = HEAP_GetPtr( heap );
1001 /* Validate the parameters */
1003 if (!heapPtr) return FALSE;
1004 flags &= HEAP_NO_SERIALIZE;
1005 flags |= heapPtr->flags;
1006 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1007 if (!ptr)
1009 WARN(heap, "(%08x,%08lx,%08lx): asked to free NULL\n",
1010 heap, flags, (DWORD)ptr );
1012 if (!ptr || !HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1014 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1015 SetLastError( ERROR_INVALID_PARAMETER );
1016 TRACE(heap, "(%08x,%08lx,%08lx): returning FALSE\n",
1017 heap, flags, (DWORD)ptr );
1018 return FALSE;
1021 /* Turn the block into a free block */
1023 pInUse = (ARENA_INUSE *)ptr - 1;
1024 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1025 HEAP_MakeInUseBlockFree( subheap, pInUse );
1027 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1028 /* SetLastError( 0 ); */
1030 TRACE(heap, "(%08x,%08lx,%08lx): returning TRUE\n",
1031 heap, flags, (DWORD)ptr );
1032 return TRUE;
1036 /***********************************************************************
1037 * HeapReAlloc (KERNEL32.340)
1038 * RETURNS
1039 * Pointer to reallocated memory block
1040 * NULL: Failure
1042 LPVOID WINAPI HeapReAlloc(
1043 HANDLE heap, /* [in] Handle of heap block */
1044 DWORD flags, /* [in] Heap reallocation flags */
1045 LPVOID ptr, /* [in] Address of memory to reallocate */
1046 DWORD size /* [in] Number of bytes to reallocate */
1048 ARENA_INUSE *pArena;
1049 DWORD oldSize;
1050 HEAP *heapPtr;
1051 SUBHEAP *subheap;
1053 if (!ptr) return HeapAlloc( heap, flags, size ); /* FIXME: correct? */
1054 if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1056 /* Validate the parameters */
1058 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1059 HEAP_REALLOC_IN_PLACE_ONLY;
1060 flags |= heapPtr->flags;
1061 size = (size + 3) & ~3;
1062 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1064 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1065 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1067 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1068 SetLastError( ERROR_INVALID_PARAMETER );
1069 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1070 heap, flags, (DWORD)ptr, size );
1071 return NULL;
1074 /* Check if we need to grow the block */
1076 pArena = (ARENA_INUSE *)ptr - 1;
1077 pArena->threadId = GetCurrentTask();
1078 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1079 oldSize = (pArena->size & ARENA_SIZE_MASK);
1080 if (size > oldSize)
1082 char *pNext = (char *)(pArena + 1) + oldSize;
1083 if ((pNext < (char *)subheap + subheap->size) &&
1084 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1085 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1087 /* The next block is free and large enough */
1088 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1089 pFree->next->prev = pFree->prev;
1090 pFree->prev->next = pFree->next;
1091 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1092 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1093 + size + HEAP_MIN_BLOCK_SIZE))
1095 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1096 SetLastError( ERROR_OUTOFMEMORY );
1097 return NULL;
1099 HEAP_ShrinkBlock( subheap, pArena, size );
1101 else /* Do it the hard way */
1103 ARENA_FREE *pNew;
1104 ARENA_INUSE *pInUse;
1105 SUBHEAP *newsubheap;
1107 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1108 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1110 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1111 SetLastError( ERROR_OUTOFMEMORY );
1112 return NULL;
1115 /* Build the in-use arena */
1117 pNew->next->prev = pNew->prev;
1118 pNew->prev->next = pNew->next;
1119 pInUse = (ARENA_INUSE *)pNew;
1120 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1121 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1122 pInUse->threadId = GetCurrentTask();
1123 pInUse->magic = ARENA_INUSE_MAGIC;
1124 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1125 memcpy( pInUse + 1, pArena + 1, oldSize );
1127 /* Free the previous block */
1129 HEAP_MakeInUseBlockFree( subheap, pArena );
1130 subheap = newsubheap;
1131 pArena = pInUse;
1134 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1136 /* Clear the extra bytes if needed */
1138 if (size > oldSize)
1140 if (flags & HEAP_ZERO_MEMORY)
1141 memset( (char *)(pArena + 1) + oldSize, 0,
1142 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1143 else if (TRACE_ON(heap))
1144 memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1145 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1148 /* Return the new arena */
1150 pArena->callerEIP = *((DWORD *)&heap - 1); /* hack hack */
1151 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1153 TRACE(heap, "(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1154 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1155 return (LPVOID)(pArena + 1);
1159 /***********************************************************************
1160 * HeapCompact (KERNEL32.335)
1162 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1164 return 0;
1168 /***********************************************************************
1169 * HeapLock (KERNEL32.339)
1170 * Attempts to acquire the critical section object for a specified heap.
1172 * RETURNS
1173 * TRUE: Success
1174 * FALSE: Failure
1176 BOOL WINAPI HeapLock(
1177 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1179 HEAP *heapPtr = HEAP_GetPtr( heap );
1180 if (!heapPtr) return FALSE;
1181 EnterCriticalSection( &heapPtr->critSection );
1182 return TRUE;
1186 /***********************************************************************
1187 * HeapUnlock (KERNEL32.342)
1188 * Releases ownership of the critical section object.
1190 * RETURNS
1191 * TRUE: Success
1192 * FALSE: Failure
1194 BOOL WINAPI HeapUnlock(
1195 HANDLE heap /* [in] Handle to the heap to unlock */
1197 HEAP *heapPtr = HEAP_GetPtr( heap );
1198 if (!heapPtr) return FALSE;
1199 LeaveCriticalSection( &heapPtr->critSection );
1200 return TRUE;
1204 /***********************************************************************
1205 * HeapSize (KERNEL32.341)
1206 * RETURNS
1207 * Size in bytes of allocated memory
1208 * 0xffffffff: Failure
1210 DWORD WINAPI HeapSize(
1211 HANDLE heap, /* [in] Handle of heap */
1212 DWORD flags, /* [in] Heap size control flags */
1213 LPVOID ptr /* [in] Address of memory to return size for */
1215 DWORD ret;
1216 HEAP *heapPtr = HEAP_GetPtr( heap );
1218 if (!heapPtr) return FALSE;
1219 flags &= HEAP_NO_SERIALIZE;
1220 flags |= heapPtr->flags;
1221 if (!(flags & HEAP_NO_SERIALIZE)) HeapLock( heap );
1222 if (!HeapValidate( heap, HEAP_NO_SERIALIZE, ptr ))
1224 SetLastError( ERROR_INVALID_PARAMETER );
1225 ret = 0xffffffff;
1227 else
1229 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1230 ret = pArena->size & ARENA_SIZE_MASK;
1232 if (!(flags & HEAP_NO_SERIALIZE)) HeapUnlock( heap );
1234 TRACE(heap, "(%08x,%08lx,%08lx): returning %08lx\n",
1235 heap, flags, (DWORD)ptr, ret );
1236 return ret;
1240 /***********************************************************************
1241 * HeapValidate (KERNEL32.343)
1242 * Validates a specified heap.
1244 * NOTES
1245 * Flags is ignored.
1247 * RETURNS
1248 * TRUE: Success
1249 * FALSE: Failure
1251 BOOL WINAPI HeapValidate(
1252 HANDLE heap, /* [in] Handle to the heap */
1253 DWORD flags, /* [in] Bit flags that control access during operation */
1254 LPCVOID block /* [in] Optional pointer to memory block to validate */
1256 SUBHEAP *subheap;
1257 HEAP *heapPtr = (HEAP *)(heap);
1259 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
1261 ERR(heap, "Invalid heap %08x!\n", heap );
1262 return FALSE;
1265 if (block)
1267 /* Only check this single memory block */
1268 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1269 ((char *)block < (char *)subheap + subheap->headerSize
1270 + sizeof(ARENA_INUSE)))
1272 ERR(heap, "Heap %08lx: block %08lx is not inside heap\n",
1273 (DWORD)heap, (DWORD)block );
1274 return FALSE;
1276 return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
1279 subheap = &heapPtr->subheap;
1280 while (subheap)
1282 char *ptr = (char *)subheap + subheap->headerSize;
1283 while (ptr < (char *)subheap + subheap->size)
1285 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1287 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
1288 return FALSE;
1289 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1291 else
1293 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
1294 return FALSE;
1295 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1298 subheap = subheap->next;
1300 return TRUE;
1304 /***********************************************************************
1305 * HeapWalk (KERNEL32.344)
1306 * Enumerates the memory blocks in a specified heap.
1308 * RETURNS
1309 * TRUE: Success
1310 * FALSE: Failure
1312 BOOL WINAPI HeapWalk(
1313 HANDLE heap, /* [in] Handle to heap to enumerate */
1314 LPPROCESS_HEAP_ENTRY *entry /* [out] Pointer to structure of enumeration info */
1316 FIXME(heap, "(%08x): stub.\n", heap );
1317 return FALSE;
1321 /***********************************************************************
1322 * HEAP_xalloc
1324 * Same as HeapAlloc(), but die on failure.
1326 LPVOID HEAP_xalloc( HANDLE heap, DWORD flags, DWORD size )
1328 LPVOID p = HeapAlloc( heap, flags, size );
1329 if (!p)
1331 MSG("Virtual memory exhausted.\n" );
1332 exit(1);
1334 return p;
1338 /***********************************************************************
1339 * HEAP_strdupA
1341 LPSTR HEAP_strdupA( HANDLE heap, DWORD flags, LPCSTR str )
1343 LPSTR p = HEAP_xalloc( heap, flags, strlen(str) + 1 );
1344 strcpy( p, str );
1345 return p;
1349 /***********************************************************************
1350 * HEAP_strdupW
1352 LPWSTR HEAP_strdupW( HANDLE heap, DWORD flags, LPCWSTR str )
1354 INT len = lstrlenW(str) + 1;
1355 LPWSTR p = HEAP_xalloc( heap, flags, len * sizeof(WCHAR) );
1356 lstrcpyW( p, str );
1357 return p;
1361 /***********************************************************************
1362 * HEAP_strdupAtoW
1364 LPWSTR HEAP_strdupAtoW( HANDLE heap, DWORD flags, LPCSTR str )
1366 LPWSTR ret;
1368 if (!str) return NULL;
1369 ret = HEAP_xalloc( heap, flags, (strlen(str)+1) * sizeof(WCHAR) );
1370 lstrcpyAtoW( ret, str );
1371 return ret;
1375 /***********************************************************************
1376 * HEAP_strdupWtoA
1378 LPSTR HEAP_strdupWtoA( HANDLE heap, DWORD flags, LPCWSTR str )
1380 LPSTR ret;
1382 if (!str) return NULL;
1383 ret = HEAP_xalloc( heap, flags, lstrlenW(str) + 1 );
1384 lstrcpyWtoA( ret, str );
1385 return ret;
1390 /***********************************************************************
1391 * 32-bit local heap functions (Win95; undocumented)
1394 #define HTABLE_SIZE 0x10000
1395 #define HTABLE_PAGESIZE 0x1000
1396 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
1398 #pragma pack(1)
1399 typedef struct _LOCAL32HEADER
1401 WORD freeListFirst[HTABLE_NPAGES];
1402 WORD freeListSize[HTABLE_NPAGES];
1403 WORD freeListLast[HTABLE_NPAGES];
1405 DWORD selectorTableOffset;
1406 WORD selectorTableSize;
1407 WORD selectorDelta;
1409 DWORD segment;
1410 LPBYTE base;
1412 DWORD limit;
1413 DWORD flags;
1415 DWORD magic;
1416 HANDLE heap;
1418 } LOCAL32HEADER;
1419 #pragma pack(4)
1421 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1423 /***********************************************************************
1424 * Local32Init (KERNEL.208)
1426 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1427 DWORD heapSize, DWORD flags )
1429 DWORD totSize, segSize = 0;
1430 LPBYTE base;
1431 LOCAL32HEADER *header;
1432 HEAP *heap;
1433 WORD *selectorTable;
1434 WORD selectorEven, selectorOdd;
1435 int i, nrBlocks;
1437 /* Determine new heap size */
1439 if ( segment )
1441 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1442 return 0;
1443 else
1444 segSize++;
1447 if ( heapSize == -1L )
1448 heapSize = 1024L*1024L; /* FIXME */
1450 heapSize = (heapSize + 0xffff) & 0xffff0000;
1451 segSize = (segSize + 0x0fff) & 0xfffff000;
1452 totSize = segSize + HTABLE_SIZE + heapSize;
1455 /* Allocate memory and initialize heap */
1457 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1458 return 0;
1460 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1461 MEM_COMMIT, PAGE_READWRITE ) )
1463 VirtualFree( base, 0, MEM_RELEASE );
1464 return 0;
1467 heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1468 if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1470 VirtualFree( base, 0, MEM_RELEASE );
1471 return 0;
1475 /* Set up header and handle table */
1477 header = (LOCAL32HEADER *)(base + segSize);
1478 header->base = base;
1479 header->limit = HTABLE_PAGESIZE-1;
1480 header->flags = 0;
1481 header->magic = LOCAL32_MAGIC;
1482 header->heap = (HANDLE)heap;
1484 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1485 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1486 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1488 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1489 *(DWORD *)((LPBYTE)header + i) = i+4;
1491 header->freeListFirst[1] = 0xffff;
1494 /* Set up selector table */
1496 nrBlocks = (totSize + 0x7fff) >> 15;
1497 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1498 selectorEven = SELECTOR_AllocBlock( base, totSize,
1499 SEGMENT_DATA, FALSE, FALSE );
1500 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000,
1501 SEGMENT_DATA, FALSE, FALSE );
1503 if ( !selectorTable || !selectorEven || !selectorOdd )
1505 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1506 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven, totSize >> 16 );
1507 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd, (totSize-0x8000) >> 16 );
1508 HeapDestroy( header->heap );
1509 VirtualFree( base, 0, MEM_RELEASE );
1510 return 0;
1513 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1514 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1515 header->selectorDelta = selectorEven - selectorOdd;
1516 header->segment = segment? segment : selectorEven;
1518 for (i = 0; i < nrBlocks; i++)
1519 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1520 : selectorEven + ((i >> 1) << __AHSHIFT);
1522 /* Move old segment */
1524 if ( segment )
1526 /* FIXME: This is somewhat ugly and relies on implementation
1527 details about 16-bit global memory handles ... */
1529 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1530 memcpy( base, oldBase, segSize );
1531 GLOBAL_MoveBlock( segment, base, totSize );
1532 HeapFree( SystemHeap, 0, oldBase );
1535 return (HANDLE)header;
1538 /***********************************************************************
1539 * Local32_SearchHandle
1541 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1543 LPDWORD handle;
1545 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1546 handle < (LPDWORD)((LPBYTE)header + header->limit);
1547 handle++)
1549 if (*handle == addr)
1550 return handle;
1553 return NULL;
1556 /***********************************************************************
1557 * Local32_ToHandle
1559 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1560 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1562 *handle = NULL;
1563 *ptr = NULL;
1565 switch (type)
1567 case -2: /* 16:16 pointer, no handles */
1568 *ptr = PTR_SEG_TO_LIN( addr );
1569 *handle = (LPDWORD)*ptr;
1570 break;
1572 case -1: /* 32-bit offset, no handles */
1573 *ptr = header->base + addr;
1574 *handle = (LPDWORD)*ptr;
1575 break;
1577 case 0: /* handle */
1578 if ( addr >= sizeof(LOCAL32HEADER)
1579 && addr < header->limit && !(addr & 3)
1580 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1582 *handle = (LPDWORD)((LPBYTE)header + addr);
1583 *ptr = header->base + **handle;
1585 break;
1587 case 1: /* 16:16 pointer */
1588 *ptr = PTR_SEG_TO_LIN( addr );
1589 *handle = Local32_SearchHandle( header, *ptr - header->base );
1590 break;
1592 case 2: /* 32-bit offset */
1593 *ptr = header->base + addr;
1594 *handle = Local32_SearchHandle( header, *ptr - header->base );
1595 break;
1599 /***********************************************************************
1600 * Local32_FromHandle
1602 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1603 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1605 switch (type)
1607 case -2: /* 16:16 pointer */
1608 case 1:
1610 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1611 DWORD offset = (LPBYTE)ptr - header->base;
1612 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1614 break;
1616 case -1: /* 32-bit offset */
1617 case 2:
1618 *addr = ptr - header->base;
1619 break;
1621 case 0: /* handle */
1622 *addr = (LPBYTE)handle - (LPBYTE)header;
1623 break;
1627 /***********************************************************************
1628 * Local32Alloc (KERNEL.209)
1630 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1632 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1633 LPDWORD handle;
1634 LPBYTE ptr;
1635 DWORD addr;
1637 /* Allocate memory */
1638 ptr = HeapAlloc( header->heap,
1639 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1640 if (!ptr) return 0;
1643 /* Allocate handle if requested */
1644 if (type >= 0)
1646 int page, i;
1648 /* Find first page of handle table with free slots */
1649 for (page = 0; page < HTABLE_NPAGES; page++)
1650 if (header->freeListFirst[page] != 0)
1651 break;
1652 if (page == HTABLE_NPAGES)
1654 WARN( heap, "Out of handles!\n" );
1655 HeapFree( header->heap, 0, ptr );
1656 return 0;
1659 /* If virgin page, initialize it */
1660 if (header->freeListFirst[page] == 0xffff)
1662 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1663 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1665 WARN( heap, "Cannot grow handle table!\n" );
1666 HeapFree( header->heap, 0, ptr );
1667 return 0;
1670 header->limit += HTABLE_PAGESIZE;
1672 header->freeListFirst[page] = 0;
1673 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
1674 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
1676 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1677 *(DWORD *)((LPBYTE)header + i) = i+4;
1679 if (page < HTABLE_NPAGES-1)
1680 header->freeListFirst[page+1] = 0xffff;
1683 /* Allocate handle slot from page */
1684 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1685 if (--header->freeListSize[page] == 0)
1686 header->freeListFirst[page] = header->freeListLast[page] = 0;
1687 else
1688 header->freeListFirst[page] = *handle;
1690 /* Store 32-bit offset in handle slot */
1691 *handle = ptr - header->base;
1693 else
1695 handle = (LPDWORD)ptr;
1696 header->flags |= 1;
1700 /* Convert handle to requested output type */
1701 Local32_FromHandle( header, type, &addr, handle, ptr );
1702 return addr;
1705 /***********************************************************************
1706 * Local32ReAlloc (KERNEL.210)
1708 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1709 DWORD size, DWORD flags )
1711 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1712 LPDWORD handle;
1713 LPBYTE ptr;
1715 if (!addr)
1716 return Local32Alloc16( heap, size, type, flags );
1718 /* Retrieve handle and pointer */
1719 Local32_ToHandle( header, type, addr, &handle, &ptr );
1720 if (!handle) return FALSE;
1722 /* Reallocate memory block */
1723 ptr = HeapReAlloc( header->heap,
1724 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
1725 ptr, size );
1726 if (!ptr) return 0;
1728 /* Modify handle */
1729 if (type >= 0)
1730 *handle = ptr - header->base;
1731 else
1732 handle = (LPDWORD)ptr;
1734 /* Convert handle to requested output type */
1735 Local32_FromHandle( header, type, &addr, handle, ptr );
1736 return addr;
1739 /***********************************************************************
1740 * Local32Free (KERNEL.211)
1742 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
1744 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1745 LPDWORD handle;
1746 LPBYTE ptr;
1748 /* Retrieve handle and pointer */
1749 Local32_ToHandle( header, type, addr, &handle, &ptr );
1750 if (!handle) return FALSE;
1752 /* Free handle if necessary */
1753 if (type >= 0)
1755 int offset = (LPBYTE)handle - (LPBYTE)header;
1756 int page = offset >> 12;
1758 /* Return handle slot to page free list */
1759 if (header->freeListSize[page]++ == 0)
1760 header->freeListFirst[page] = header->freeListLast[page] = offset;
1761 else
1762 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
1763 header->freeListLast[page] = offset;
1765 *handle = 0;
1767 /* Shrink handle table when possible */
1768 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
1770 if ( VirtualFree( (LPBYTE)header +
1771 (header->limit & ~(HTABLE_PAGESIZE-1)),
1772 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
1773 break;
1775 header->limit -= HTABLE_PAGESIZE;
1776 header->freeListFirst[page] = 0xffff;
1777 page--;
1781 /* Free memory */
1782 return HeapFree( header->heap, 0, ptr );
1785 /***********************************************************************
1786 * Local32Translate (KERNEL.213)
1788 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
1790 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1791 LPDWORD handle;
1792 LPBYTE ptr;
1794 Local32_ToHandle( header, type1, addr, &handle, &ptr );
1795 if (!handle) return 0;
1797 Local32_FromHandle( header, type2, &addr, handle, ptr );
1798 return addr;
1801 /***********************************************************************
1802 * Local32Size (KERNEL.214)
1804 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
1806 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1807 LPDWORD handle;
1808 LPBYTE ptr;
1810 Local32_ToHandle( header, type, addr, &handle, &ptr );
1811 if (!handle) return 0;
1813 return HeapSize( header->heap, 0, ptr );
1816 /***********************************************************************
1817 * Local32ValidHandle (KERNEL.215)
1819 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
1821 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1822 LPDWORD handle;
1823 LPBYTE ptr;
1825 Local32_ToHandle( header, 0, addr, &handle, &ptr );
1826 return handle != NULL;
1829 /***********************************************************************
1830 * Local32GetSegment (KERNEL.229)
1832 WORD WINAPI Local32GetSegment16( HANDLE heap )
1834 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1835 return header->segment;
1838 /***********************************************************************
1839 * Local32_GetHeap
1841 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
1843 WORD selector = GlobalHandleToSel16( handle );
1844 DWORD base = GetSelectorBase( selector );
1845 DWORD limit = GetSelectorLimit16( selector );
1847 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
1848 it this way ... */
1850 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1851 return (LOCAL32HEADER *)base;
1853 base += 0x10000;
1854 limit -= 0x10000;
1856 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
1857 return (LOCAL32HEADER *)base;
1859 return NULL;
1862 /***********************************************************************
1863 * Local32Info (KERNEL.444) (TOOLHELP.84)
1865 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
1867 SUBHEAP *heapPtr;
1868 LPBYTE ptr;
1869 int i;
1871 LOCAL32HEADER *header = Local32_GetHeap( handle );
1872 if ( !header ) return FALSE;
1874 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
1875 return FALSE;
1877 heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
1878 pLocal32Info->dwMemReserved = heapPtr->size;
1879 pLocal32Info->dwMemCommitted = heapPtr->commitSize;
1880 pLocal32Info->dwTotalFree = 0L;
1881 pLocal32Info->dwLargestFreeBlock = 0L;
1883 /* Note: Local32 heaps always have only one subheap! */
1884 ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
1885 while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
1887 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1889 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1890 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1891 ptr += sizeof(*pArena) + size;
1893 pLocal32Info->dwTotalFree += size;
1894 if ( size > pLocal32Info->dwLargestFreeBlock )
1895 pLocal32Info->dwLargestFreeBlock = size;
1897 else
1899 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1900 DWORD size = (pArena->size & ARENA_SIZE_MASK);
1901 ptr += sizeof(*pArena) + size;
1905 pLocal32Info->dwcFreeHandles = 0;
1906 for ( i = 0; i < HTABLE_NPAGES; i++ )
1908 if ( header->freeListFirst[i] == 0xffff ) break;
1909 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
1911 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
1913 return TRUE;
1916 /***********************************************************************
1917 * Local32First (KERNEL.445) (TOOLHELP.85)
1919 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
1921 FIXME( heap, "(%p, %04X): stub!\n", pLocal32Entry, handle );
1922 return FALSE;
1925 /***********************************************************************
1926 * Local32Next (KERNEL.446) (TOOLHELP.86)
1928 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
1930 FIXME( heap, "(%p): stub!\n", pLocal32Entry );
1931 return FALSE;