Fixed Filesystem documentation.
[wine/wine64.git] / memory / heap.c
blobe4755abd2925b35718740e6f3407da21d1fcb533
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;
100 CRITICAL_SECTION *HEAP_SystemLock = NULL;
103 /***********************************************************************
104 * HEAP_Dump
106 void HEAP_Dump( HEAP *heap )
108 int i;
109 SUBHEAP *subheap;
110 char *ptr;
112 DUMP( "Heap: %08lx\n", (DWORD)heap );
113 DUMP( "Next: %08lx Sub-heaps: %08lx",
114 (DWORD)heap->next, (DWORD)&heap->subheap );
115 subheap = &heap->subheap;
116 while (subheap->next)
118 DUMP( " -> %08lx", (DWORD)subheap->next );
119 subheap = subheap->next;
122 DUMP( "\nFree lists:\n Block Stat Size Id\n" );
123 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
124 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
125 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
126 heap->freeList[i].arena.threadId,
127 (DWORD)heap->freeList[i].arena.prev,
128 (DWORD)heap->freeList[i].arena.next );
130 subheap = &heap->subheap;
131 while (subheap)
133 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
134 DUMP( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
135 (DWORD)subheap, subheap->size, subheap->commitSize );
137 DUMP( "\n Block Stat Size Id\n" );
138 ptr = (char*)subheap + subheap->headerSize;
139 while (ptr < (char *)subheap + subheap->size)
141 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
143 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
144 DUMP( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
145 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
146 pArena->threadId, (DWORD)pArena->prev,
147 (DWORD)pArena->next);
148 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
149 arenaSize += sizeof(ARENA_FREE);
150 freeSize += pArena->size & ARENA_SIZE_MASK;
152 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
154 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
155 DUMP( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
156 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
157 pArena->threadId, *((DWORD *)pArena - 1),
158 pArena->callerEIP );
159 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
160 arenaSize += sizeof(ARENA_INUSE);
161 usedSize += pArena->size & ARENA_SIZE_MASK;
163 else
165 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
166 DUMP( "%08lx used %08lx %04x EIP=%08lx\n",
167 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168 pArena->threadId, pArena->callerEIP );
169 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
170 arenaSize += sizeof(ARENA_INUSE);
171 usedSize += pArena->size & ARENA_SIZE_MASK;
174 DUMP( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
175 subheap->size, subheap->commitSize, freeSize, usedSize,
176 arenaSize, (arenaSize * 100) / subheap->size );
177 subheap = subheap->next;
182 /***********************************************************************
183 * HEAP_GetPtr
184 * RETURNS
185 * Pointer to the heap
186 * NULL: Failure
188 static HEAP *HEAP_GetPtr(
189 HANDLE heap /* [in] Handle to the heap */
191 HEAP *heapPtr = (HEAP *)heap;
192 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
194 ERR(heap, "Invalid heap %08x!\n", heap );
195 SetLastError( ERROR_INVALID_HANDLE );
196 return NULL;
198 if (TRACE_ON(heap) && !HeapValidate( heap, 0, NULL ))
200 HEAP_Dump( heapPtr );
201 assert( FALSE );
202 SetLastError( ERROR_INVALID_HANDLE );
203 return NULL;
205 return heapPtr;
209 /***********************************************************************
210 * HEAP_InsertFreeBlock
212 * Insert a free block into the free list.
214 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
216 FREE_LIST_ENTRY *pEntry = heap->freeList;
217 while (pEntry->size < pArena->size) pEntry++;
218 pArena->size |= ARENA_FLAG_FREE;
219 pArena->next = pEntry->arena.next;
220 pArena->next->prev = pArena;
221 pArena->prev = &pEntry->arena;
222 pEntry->arena.next = pArena;
226 /***********************************************************************
227 * HEAP_FindSubHeap
228 * Find the sub-heap containing a given address.
230 * RETURNS
231 * Pointer: Success
232 * NULL: Failure
234 static SUBHEAP *HEAP_FindSubHeap(
235 HEAP *heap, /* [in] Heap pointer */
236 LPCVOID ptr /* [in] Address */
238 SUBHEAP *sub = &heap->subheap;
239 while (sub)
241 if (((char *)ptr >= (char *)sub) &&
242 ((char *)ptr < (char *)sub + sub->size)) return sub;
243 sub = sub->next;
245 return NULL;
249 /***********************************************************************
250 * HEAP_Commit
252 * Make sure the heap storage is committed up to (not including) ptr.
254 static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
256 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
257 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
258 if (size > subheap->size) size = subheap->size;
259 if (size <= subheap->commitSize) return TRUE;
260 if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
261 size - subheap->commitSize, MEM_COMMIT,
262 PAGE_EXECUTE_READWRITE))
264 WARN(heap, "Could not commit %08lx bytes at %08lx for heap %08lx\n",
265 size - subheap->commitSize,
266 (DWORD)((char *)subheap + subheap->commitSize),
267 (DWORD)subheap->heap );
268 return FALSE;
270 subheap->commitSize = size;
271 return TRUE;
275 /***********************************************************************
276 * HEAP_Decommit
278 * If possible, decommit the heap storage from (including) 'ptr'.
280 static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
282 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
283 size = (size + 0xfff) & 0xfffff000; /* Align size on a page boundary */
284 if (size >= subheap->commitSize) return TRUE;
285 if (!VirtualFree( (char *)subheap + size,
286 subheap->commitSize - size, MEM_DECOMMIT ))
288 WARN(heap, "Could not decommit %08lx bytes at %08lx for heap %08lx\n",
289 subheap->commitSize - size,
290 (DWORD)((char *)subheap + size),
291 (DWORD)subheap->heap );
292 return FALSE;
294 subheap->commitSize = size;
295 return TRUE;
299 /***********************************************************************
300 * HEAP_CreateFreeBlock
302 * Create a free block at a specified address. 'size' is the size of the
303 * whole block, including the new arena.
305 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
307 ARENA_FREE *pFree;
309 /* Create a free arena */
311 pFree = (ARENA_FREE *)ptr;
312 pFree->threadId = GetCurrentTask();
313 pFree->magic = ARENA_FREE_MAGIC;
315 /* If debugging, erase the freed block content */
317 if (TRACE_ON(heap))
319 char *pEnd = (char *)ptr + size;
320 if (pEnd > (char *)subheap + subheap->commitSize)
321 pEnd = (char *)subheap + subheap->commitSize;
322 if (pEnd > (char *)(pFree + 1))
323 memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
326 /* Check if next block is free also */
328 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
329 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
331 /* Remove the next arena from the free list */
332 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
333 pNext->next->prev = pNext->prev;
334 pNext->prev->next = pNext->next;
335 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
336 if (TRACE_ON(heap))
337 memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
340 /* Set the next block PREV_FREE flag and pointer */
342 if ((char *)ptr + size < (char *)subheap + subheap->size)
344 DWORD *pNext = (DWORD *)((char *)ptr + size);
345 *pNext |= ARENA_FLAG_PREV_FREE;
346 *(ARENA_FREE **)(pNext - 1) = pFree;
349 /* Last, insert the new block into the free list */
351 pFree->size = size - sizeof(*pFree);
352 HEAP_InsertFreeBlock( subheap->heap, pFree );
356 /***********************************************************************
357 * HEAP_MakeInUseBlockFree
359 * Turn an in-use block into a free block. Can also decommit the end of
360 * the heap, and possibly even free the sub-heap altogether.
362 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
364 ARENA_FREE *pFree;
365 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
367 /* Check if we can merge with previous block */
369 if (pArena->size & ARENA_FLAG_PREV_FREE)
371 pFree = *((ARENA_FREE **)pArena - 1);
372 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
373 /* Remove it from the free list */
374 pFree->next->prev = pFree->prev;
375 pFree->prev->next = pFree->next;
377 else pFree = (ARENA_FREE *)pArena;
379 /* Create a free block */
381 HEAP_CreateFreeBlock( subheap, pFree, size );
382 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
383 if ((char *)pFree + size < (char *)subheap + subheap->size)
384 return; /* Not the last block, so nothing more to do */
386 /* Free the whole sub-heap if it's empty and not the original one */
388 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
389 (subheap != &subheap->heap->subheap))
391 SUBHEAP *pPrev = &subheap->heap->subheap;
392 /* Remove the free block from the list */
393 pFree->next->prev = pFree->prev;
394 pFree->prev->next = pFree->next;
395 /* Remove the subheap from the list */
396 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
397 if (pPrev) pPrev->next = subheap->next;
398 /* Free the memory */
399 subheap->magic = 0;
400 if (subheap->selector) FreeSelector16( subheap->selector );
401 VirtualFree( subheap, 0, MEM_RELEASE );
402 return;
405 /* Decommit the end of the heap */
407 HEAP_Decommit( subheap, pFree + 1 );
411 /***********************************************************************
412 * HEAP_ShrinkBlock
414 * Shrink an in-use block.
416 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
418 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
420 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
421 (pArena->size & ARENA_SIZE_MASK) - size );
422 pArena->size = (pArena->size & ~ARENA_SIZE_MASK) | size;
424 else
426 /* Turn off PREV_FREE flag in next block */
427 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
428 if (pNext < (char *)subheap + subheap->size)
429 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
433 /***********************************************************************
434 * HEAP_InitSubHeap
436 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
437 DWORD commitSize, DWORD totalSize )
439 SUBHEAP *subheap = (SUBHEAP *)address;
440 WORD selector = 0;
441 FREE_LIST_ENTRY *pEntry;
442 int i;
444 /* Commit memory */
446 if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
448 WARN(heap, "Could not commit %08lx bytes for sub-heap %08lx\n",
449 commitSize, (DWORD)address );
450 return FALSE;
453 /* Allocate a selector if needed */
455 if (flags & HEAP_WINE_SEGPTR)
457 selector = SELECTOR_AllocBlock( address, totalSize,
458 (flags & (HEAP_WINE_CODESEG|HEAP_WINE_CODE16SEG))
459 ? SEGMENT_CODE : SEGMENT_DATA,
460 (flags & HEAP_WINE_CODESEG) != 0, FALSE );
461 if (!selector)
463 ERR(heap, "Could not allocate selector\n" );
464 return FALSE;
468 /* Fill the sub-heap structure */
470 subheap->heap = heap;
471 subheap->selector = selector;
472 subheap->size = totalSize;
473 subheap->commitSize = commitSize;
474 subheap->magic = SUBHEAP_MAGIC;
476 if ( subheap != (SUBHEAP *)heap )
478 /* If this is a secondary subheap, insert it into list */
480 subheap->headerSize = sizeof(SUBHEAP);
481 subheap->next = heap->subheap.next;
482 heap->subheap.next = subheap;
484 else
486 /* If this is a primary subheap, initialize main heap */
488 subheap->headerSize = sizeof(HEAP);
489 subheap->next = NULL;
490 heap->next = NULL;
491 heap->flags = flags;
492 heap->magic = HEAP_MAGIC;
494 /* Build the free lists */
496 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
498 pEntry->size = HEAP_freeListSizes[i];
499 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
500 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
501 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
502 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
503 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
504 pEntry->arena.threadId = 0;
505 pEntry->arena.magic = ARENA_FREE_MAGIC;
508 /* Initialize critical section */
510 InitializeCriticalSection( &heap->critSection );
511 if (!SystemHeap) HEAP_SystemLock = &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;