New set of macros for server calls; makes requests without variable
[wine] / memory / heap.c
1 /*
2  * Win32 heap functions
3  *
4  * Copyright 1996 Alexandre Julliard
5  * Copyright 1998 Ulrich Weigand
6  */
7
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include "config.h"
13 #include "wine/winbase16.h"
14 #include "wine/unicode.h"
15 #include "selectors.h"
16 #include "global.h"
17 #include "winbase.h"
18 #include "winerror.h"
19 #include "winnt.h"
20 #include "heap.h"
21 #include "toolhelp.h"
22 #include "debugtools.h"
23 #include "winnls.h"
24
25 DEFAULT_DEBUG_CHANNEL(heap);
26
27 /* Note: the heap data structures are based on what Pietrek describes in his
28  * book 'Windows 95 System Programming Secrets'. The layout is not exactly
29  * the same, but could be easily adapted if it turns out some programs
30  * require it.
31  */
32
33 typedef struct tagARENA_INUSE
34 {
35     DWORD  size;                    /* Block size; must be the first field */
36     WORD   magic;                   /* Magic number */
37     WORD   threadId;                /* Allocating thread id */
38     void  *callerEIP;               /* EIP of caller upon allocation */
39 } ARENA_INUSE;
40
41 typedef struct tagARENA_FREE
42 {
43     DWORD                 size;     /* Block size; must be the first field */
44     WORD                  magic;    /* Magic number */
45     WORD                  threadId; /* Freeing thread id */
46     struct tagARENA_FREE *next;     /* Next free arena */
47     struct tagARENA_FREE *prev;     /* Prev free arena */
48 } ARENA_FREE;
49
50 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
51 #define ARENA_FLAG_PREV_FREE   0x00000002
52 #define ARENA_SIZE_MASK        0xfffffffc
53 #define ARENA_INUSE_MAGIC      0x4842      /* Value for arena 'magic' field */
54 #define ARENA_FREE_MAGIC       0x4846      /* Value for arena 'magic' field */
55
56 #define ARENA_INUSE_FILLER     0x55
57 #define ARENA_FREE_FILLER      0xaa
58
59 #define QUIET                  1           /* Suppress messages  */
60 #define NOISY                  0           /* Report all errors  */
61
62 #define HEAP_NB_FREE_LISTS   4   /* Number of free lists */
63
64 /* Max size of the blocks on the free lists */
65 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
66 {
67     0x20, 0x80, 0x200, 0xffffffff
68 };
69
70 typedef struct
71 {
72     DWORD       size;
73     ARENA_FREE  arena;
74 } FREE_LIST_ENTRY;
75
76 struct tagHEAP;
77
78 typedef struct tagSUBHEAP
79 {
80     DWORD               size;       /* Size of the whole sub-heap */
81     DWORD               commitSize; /* Committed size of the sub-heap */
82     DWORD               headerSize; /* Size of the heap header */
83     struct tagSUBHEAP  *next;       /* Next sub-heap */
84     struct tagHEAP     *heap;       /* Main heap structure */
85     DWORD               magic;      /* Magic number */
86     WORD                selector;   /* Selector for HEAP_WINE_SEGPTR heaps */
87 } SUBHEAP;
88
89 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
90
91 typedef struct tagHEAP
92 {
93     SUBHEAP          subheap;       /* First sub-heap */
94     struct tagHEAP  *next;          /* Next heap for this process */
95     FREE_LIST_ENTRY  freeList[HEAP_NB_FREE_LISTS];  /* Free lists */
96     CRITICAL_SECTION critSection;   /* Critical section for serialization */
97     DWORD            flags;         /* Heap flags */
98     DWORD            magic;         /* Magic number */
99 } HEAP;
100
101 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
102
103 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
104 #define HEAP_MIN_BLOCK_SIZE  (8+sizeof(ARENA_FREE))  /* Min. heap block size */
105 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
106
107 static HEAP *systemHeap;   /* globally shared heap */
108 static HEAP *processHeap;  /* main process heap */
109 static HEAP *segptrHeap;   /* main segptr heap */
110 static HEAP *firstHeap;    /* head of secondary heaps list */
111
112 /* address where we try to map the system heap */
113 #define SYSTEM_HEAP_BASE  ((void*)0x65430000)
114
115 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
116
117 #ifdef __GNUC__
118 #define GET_EIP()    (__builtin_return_address(0))
119 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
120 #else
121 #define GET_EIP()    0
122 #define SET_EIP(ptr) /* nothing */
123 #endif  /* __GNUC__ */
124
125 /***********************************************************************
126  *           HEAP_Dump
127  */
128 void HEAP_Dump( HEAP *heap )
129 {
130     int i;
131     SUBHEAP *subheap;
132     char *ptr;
133
134     DPRINTF( "Heap: %08lx\n", (DWORD)heap );
135     DPRINTF( "Next: %08lx  Sub-heaps: %08lx",
136           (DWORD)heap->next, (DWORD)&heap->subheap );
137     subheap = &heap->subheap;
138     while (subheap->next)
139     {
140         DPRINTF( " -> %08lx", (DWORD)subheap->next );
141         subheap = subheap->next;
142     }
143
144     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
145     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
146         DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
147               (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
148               heap->freeList[i].arena.threadId,
149               (DWORD)heap->freeList[i].arena.prev,
150               (DWORD)heap->freeList[i].arena.next );
151
152     subheap = &heap->subheap;
153     while (subheap)
154     {
155         DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
156         DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
157               (DWORD)subheap, subheap->size, subheap->commitSize );
158         
159         DPRINTF( "\n Block   Stat   Size    Id\n" );
160         ptr = (char*)subheap + subheap->headerSize;
161         while (ptr < (char *)subheap + subheap->size)
162         {
163             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
164             {
165                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
166                 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
167                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168                       pArena->threadId, (DWORD)pArena->prev,
169                       (DWORD)pArena->next);
170                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171                 arenaSize += sizeof(ARENA_FREE);
172                 freeSize += pArena->size & ARENA_SIZE_MASK;
173             }
174             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
175             {
176                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
177                 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
178                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
179                       pArena->threadId, *((DWORD *)pArena - 1),
180                       pArena->callerEIP );
181                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
182                 arenaSize += sizeof(ARENA_INUSE);
183                 usedSize += pArena->size & ARENA_SIZE_MASK;
184             }
185             else
186             {
187                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
188                 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
189                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
190                       pArena->threadId, pArena->callerEIP );
191                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
192                 arenaSize += sizeof(ARENA_INUSE);
193                 usedSize += pArena->size & ARENA_SIZE_MASK;
194             }
195         }
196         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
197               subheap->size, subheap->commitSize, freeSize, usedSize,
198               arenaSize, (arenaSize * 100) / subheap->size );
199         subheap = subheap->next;
200     }
201 }
202
203
204 /***********************************************************************
205  *           HEAP_GetPtr
206  * RETURNS
207  *      Pointer to the heap
208  *      NULL: Failure
209  */
210 static HEAP *HEAP_GetPtr(
211              HANDLE heap /* [in] Handle to the heap */
212 ) {
213     HEAP *heapPtr = (HEAP *)heap;
214     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
215     {
216         ERR("Invalid heap %08x!\n", heap );
217         SetLastError( ERROR_INVALID_HANDLE );
218         return NULL;
219     }
220     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
221     {
222         HEAP_Dump( heapPtr );
223         assert( FALSE );
224         SetLastError( ERROR_INVALID_HANDLE );
225         return NULL;
226     }
227     return heapPtr;
228 }
229
230
231 /***********************************************************************
232  *           HEAP_InsertFreeBlock
233  *
234  * Insert a free block into the free list.
235  */
236 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
237 {
238     FREE_LIST_ENTRY *pEntry = heap->freeList;
239     while (pEntry->size < pArena->size) pEntry++;
240     pArena->size      |= ARENA_FLAG_FREE;
241     pArena->next       = pEntry->arena.next;
242     pArena->next->prev = pArena;
243     pArena->prev       = &pEntry->arena;
244     pEntry->arena.next = pArena;
245 }
246
247
248 /***********************************************************************
249  *           HEAP_FindSubHeap
250  * Find the sub-heap containing a given address.
251  *
252  * RETURNS
253  *      Pointer: Success
254  *      NULL: Failure
255  */
256 static SUBHEAP *HEAP_FindSubHeap(
257                 HEAP *heap, /* [in] Heap pointer */
258                 LPCVOID ptr /* [in] Address */
259 ) {
260     SUBHEAP *sub = &heap->subheap;
261     while (sub)
262     {
263         if (((char *)ptr >= (char *)sub) &&
264             ((char *)ptr < (char *)sub + sub->size)) return sub;
265         sub = sub->next;
266     }
267     return NULL;
268 }
269
270
271 /***********************************************************************
272  *           HEAP_Commit
273  *
274  * Make sure the heap storage is committed up to (not including) ptr.
275  */
276 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
277 {
278     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
279     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
280     if (size > subheap->size) size = subheap->size;
281     if (size <= subheap->commitSize) return TRUE;
282     if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
283                        size - subheap->commitSize, MEM_COMMIT,
284                        PAGE_EXECUTE_READWRITE))
285     {
286         WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
287                  size - subheap->commitSize,
288                  (DWORD)((char *)subheap + subheap->commitSize),
289                  (DWORD)subheap->heap );
290         return FALSE;
291     }
292     subheap->commitSize = size;
293     return TRUE;
294 }
295
296
297 /***********************************************************************
298  *           HEAP_Decommit
299  *
300  * If possible, decommit the heap storage from (including) 'ptr'.
301  */
302 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
303 {
304     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
305     /* round to next block and add one full block */
306     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
307     if (size >= subheap->commitSize) return TRUE;
308     if (!VirtualFree( (char *)subheap + size,
309                       subheap->commitSize - size, MEM_DECOMMIT ))
310     {
311         WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
312                  subheap->commitSize - size,
313                  (DWORD)((char *)subheap + size),
314                  (DWORD)subheap->heap );
315         return FALSE;
316     }
317     subheap->commitSize = size;
318     return TRUE;
319 }
320
321
322 /***********************************************************************
323  *           HEAP_CreateFreeBlock
324  *
325  * Create a free block at a specified address. 'size' is the size of the
326  * whole block, including the new arena.
327  */
328 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
329 {
330     ARENA_FREE *pFree;
331
332     /* Create a free arena */
333
334     pFree = (ARENA_FREE *)ptr;
335     pFree->threadId = GetCurrentTask();
336     pFree->magic = ARENA_FREE_MAGIC;
337
338     /* If debugging, erase the freed block content */
339
340     if (TRACE_ON(heap))
341     {
342         char *pEnd = (char *)ptr + size;
343         if (pEnd > (char *)subheap + subheap->commitSize)
344             pEnd = (char *)subheap + subheap->commitSize;
345         if (pEnd > (char *)(pFree + 1))
346             memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
347     }
348
349     /* Check if next block is free also */
350
351     if (((char *)ptr + size < (char *)subheap + subheap->size) &&
352         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
353     {
354         /* Remove the next arena from the free list */
355         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
356         pNext->next->prev = pNext->prev;
357         pNext->prev->next = pNext->next;
358         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
359         if (TRACE_ON(heap))
360             memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
361     }
362
363     /* Set the next block PREV_FREE flag and pointer */
364
365     if ((char *)ptr + size < (char *)subheap + subheap->size)
366     {
367         DWORD *pNext = (DWORD *)((char *)ptr + size);
368         *pNext |= ARENA_FLAG_PREV_FREE;
369         *(ARENA_FREE **)(pNext - 1) = pFree;
370     }
371
372     /* Last, insert the new block into the free list */
373
374     pFree->size = size - sizeof(*pFree);
375     HEAP_InsertFreeBlock( subheap->heap, pFree );
376 }
377
378
379 /***********************************************************************
380  *           HEAP_MakeInUseBlockFree
381  *
382  * Turn an in-use block into a free block. Can also decommit the end of
383  * the heap, and possibly even free the sub-heap altogether.
384  */
385 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
386 {
387     ARENA_FREE *pFree;
388     DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
389
390     /* Check if we can merge with previous block */
391
392     if (pArena->size & ARENA_FLAG_PREV_FREE)
393     {
394         pFree = *((ARENA_FREE **)pArena - 1);
395         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
396         /* Remove it from the free list */
397         pFree->next->prev = pFree->prev;
398         pFree->prev->next = pFree->next;
399     }
400     else pFree = (ARENA_FREE *)pArena;
401
402     /* Create a free block */
403
404     HEAP_CreateFreeBlock( subheap, pFree, size );
405     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
406     if ((char *)pFree + size < (char *)subheap + subheap->size)
407         return;  /* Not the last block, so nothing more to do */
408
409     /* Free the whole sub-heap if it's empty and not the original one */
410
411     if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
412         (subheap != &subheap->heap->subheap))
413     {
414         SUBHEAP *pPrev = &subheap->heap->subheap;
415         /* Remove the free block from the list */
416         pFree->next->prev = pFree->prev;
417         pFree->prev->next = pFree->next;
418         /* Remove the subheap from the list */
419         while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
420         if (pPrev) pPrev->next = subheap->next;
421         /* Free the memory */
422         subheap->magic = 0;
423         if (subheap->selector) FreeSelector16( subheap->selector );
424         VirtualFree( subheap, 0, MEM_RELEASE );
425         return;
426     }
427     
428     /* Decommit the end of the heap */
429
430     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
431 }
432
433
434 /***********************************************************************
435  *           HEAP_ShrinkBlock
436  *
437  * Shrink an in-use block.
438  */
439 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
440 {
441     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
442     {
443         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
444                               (pArena->size & ARENA_SIZE_MASK) - size );
445         /* assign size plus previous arena flags */
446         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
447     }
448     else
449     {
450         /* Turn off PREV_FREE flag in next block */
451         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
452         if (pNext < (char *)subheap + subheap->size)
453             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
454     }
455 }
456
457 /***********************************************************************
458  *           HEAP_InitSubHeap
459  */
460 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
461                                 DWORD commitSize, DWORD totalSize )
462 {
463     SUBHEAP *subheap = (SUBHEAP *)address;
464     WORD selector = 0;
465     FREE_LIST_ENTRY *pEntry;
466     int i;
467
468     /* Commit memory */
469
470     if (flags & HEAP_SHARED)
471         commitSize = totalSize;  /* always commit everything in a shared heap */
472     if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
473     {
474         WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
475                    commitSize, (DWORD)address );
476         return FALSE;
477     }
478
479     /* Allocate a selector if needed */
480
481     if (flags & HEAP_WINE_SEGPTR)
482     {
483         unsigned char selflags = WINE_LDT_FLAGS_DATA;
484
485         if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
486             selflags = WINE_LDT_FLAGS_CODE;
487         if (flags & HEAP_WINE_CODESEG)
488             selflags |= WINE_LDT_FLAGS_32BIT;
489         selector = SELECTOR_AllocBlock( address, totalSize, selflags );
490         if (!selector)
491         {
492             ERR("Could not allocate selector\n" );
493             return FALSE;
494         }
495     }
496
497     /* Fill the sub-heap structure */
498
499     subheap->heap       = heap;
500     subheap->selector   = selector;
501     subheap->size       = totalSize;
502     subheap->commitSize = commitSize;
503     subheap->magic      = SUBHEAP_MAGIC;
504
505     if ( subheap != (SUBHEAP *)heap )
506     {
507         /* If this is a secondary subheap, insert it into list */
508
509         subheap->headerSize = sizeof(SUBHEAP);
510         subheap->next       = heap->subheap.next;
511         heap->subheap.next  = subheap;
512     }
513     else
514     {
515         /* If this is a primary subheap, initialize main heap */
516
517         subheap->headerSize = sizeof(HEAP);
518         subheap->next       = NULL;
519         heap->next          = NULL;
520         heap->flags         = flags;
521         heap->magic         = HEAP_MAGIC;
522
523         /* Build the free lists */
524
525         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
526         {
527             pEntry->size           = HEAP_freeListSizes[i];
528             pEntry->arena.size     = 0 | ARENA_FLAG_FREE;
529             pEntry->arena.next     = i < HEAP_NB_FREE_LISTS-1 ?
530                          &heap->freeList[i+1].arena : &heap->freeList[0].arena;
531             pEntry->arena.prev     = i ? &heap->freeList[i-1].arena : 
532                                    &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
533             pEntry->arena.threadId = 0;
534             pEntry->arena.magic    = ARENA_FREE_MAGIC;
535         }
536
537         /* Initialize critical section */
538
539         InitializeCriticalSection( &heap->critSection );
540     }
541
542     /* Create the first free block */
543
544     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize, 
545                           subheap->size - subheap->headerSize );
546
547     return TRUE;
548 }
549
550 /***********************************************************************
551  *           HEAP_CreateSubHeap
552  *
553  * Create a sub-heap of the given size.
554  * If heap == NULL, creates a main heap.
555  */
556 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags, 
557                                     DWORD commitSize, DWORD totalSize )
558 {
559     LPVOID address;
560
561     /* Round-up sizes on a 64K boundary */
562
563     if (flags & HEAP_WINE_SEGPTR)
564     {
565         totalSize = commitSize = 0x10000;  /* Only 64K at a time for SEGPTRs */
566     }
567     else
568     {
569         totalSize  = (totalSize + 0xffff) & 0xffff0000;
570         commitSize = (commitSize + 0xffff) & 0xffff0000;
571         if (!commitSize) commitSize = 0x10000;
572         if (totalSize < commitSize) totalSize = commitSize;
573     }
574
575     /* Allocate the memory block */
576
577     if (!(address = VirtualAlloc( NULL, totalSize,
578                                   MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
579     {
580         WARN("Could not VirtualAlloc %08lx bytes\n",
581                  totalSize );
582         return NULL;
583     }
584
585     /* Initialize subheap */
586
587     if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address, 
588                            address, flags, commitSize, totalSize ))
589     {
590         VirtualFree( address, 0, MEM_RELEASE );
591         return NULL;
592     }
593
594     return (SUBHEAP *)address;
595 }
596
597
598 /***********************************************************************
599  *           HEAP_FindFreeBlock
600  *
601  * Find a free block at least as large as the requested size, and make sure
602  * the requested size is committed.
603  */
604 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
605                                        SUBHEAP **ppSubHeap )
606 {
607     SUBHEAP *subheap;
608     ARENA_FREE *pArena;
609     FREE_LIST_ENTRY *pEntry = heap->freeList;
610
611     /* Find a suitable free list, and in it find a block large enough */
612
613     while (pEntry->size < size) pEntry++;
614     pArena = pEntry->arena.next;
615     while (pArena != &heap->freeList[0].arena)
616     {
617         if (pArena->size > size)
618         {
619             subheap = HEAP_FindSubHeap( heap, pArena );
620             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
621                                                + size + HEAP_MIN_BLOCK_SIZE))
622                 return NULL;
623             *ppSubHeap = subheap;
624             return pArena;
625         }
626
627         pArena = pArena->next;
628     }
629
630     /* If no block was found, attempt to grow the heap */
631
632     if (!(heap->flags & HEAP_GROWABLE))
633     {
634         WARN("Not enough space in heap %08lx for %08lx bytes\n",
635                  (DWORD)heap, size );
636         return NULL;
637     }
638     /* make sure that we have a big enough size *committed* to fit another
639      * last free arena in !
640      * So just one heap struct, one first free arena which will eventually
641      * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
642      * might get assigned all remaining free space in HEAP_ShrinkBlock() */
643     size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
644     if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
645                                         max( HEAP_DEF_SIZE, size ) )))
646         return NULL;
647
648     TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
649                 (DWORD)subheap, size, (DWORD)heap );
650
651     *ppSubHeap = subheap;
652     return (ARENA_FREE *)(subheap + 1);
653 }
654
655
656 /***********************************************************************
657  *           HEAP_IsValidArenaPtr
658  *
659  * Check that the pointer is inside the range possible for arenas.
660  */
661 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
662 {
663     int i;
664     SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
665     if (!subheap) return FALSE;
666     if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
667     if (subheap != &heap->subheap) return FALSE;
668     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
669         if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
670     return FALSE;
671 }
672
673
674 /***********************************************************************
675  *           HEAP_ValidateFreeArena
676  */
677 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
678 {
679     char *heapEnd = (char *)subheap + subheap->size;
680
681 #if !defined(ALLOW_UNALIGNED_ACCESS)
682     /* Check for unaligned pointers */
683     if ( (long)pArena % sizeof(void *) != 0 )
684     {
685         ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
686              (DWORD)subheap->heap, (DWORD)pArena );
687         return FALSE;
688     }
689 #endif
690
691     /* Check magic number */
692     if (pArena->magic != ARENA_FREE_MAGIC)
693     {
694         ERR("Heap %08lx: invalid free arena magic for %08lx\n",
695                  (DWORD)subheap->heap, (DWORD)pArena );
696         return FALSE;
697     }
698     /* Check size flags */
699     if (!(pArena->size & ARENA_FLAG_FREE) ||
700         (pArena->size & ARENA_FLAG_PREV_FREE))
701     {
702         ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
703                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
704     }
705     /* Check arena size */
706     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
707     {
708         ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
709                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
710         return FALSE;
711     }
712     /* Check that next pointer is valid */
713     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
714     {
715         ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
716                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
717         return FALSE;
718     }
719     /* Check that next arena is free */
720     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
721         (pArena->next->magic != ARENA_FREE_MAGIC))
722     { 
723         ERR("Heap %08lx: next arena %08lx invalid for %08lx\n", 
724                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
725         return FALSE;
726     }
727     /* Check that prev pointer is valid */
728     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
729     {
730         ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
731                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
732         return FALSE;
733     }
734     /* Check that prev arena is free */
735     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
736         (pArena->prev->magic != ARENA_FREE_MAGIC))
737     { 
738         /* this often means that the prev arena got overwritten
739          * by a memory write before that prev arena */
740         ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n", 
741                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
742         return FALSE;
743     }
744     /* Check that next block has PREV_FREE flag */
745     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
746     {
747         if (!(*(DWORD *)((char *)(pArena + 1) +
748             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
749         {
750             ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
751                      (DWORD)subheap->heap, (DWORD)pArena );
752             return FALSE;
753         }
754         /* Check next block back pointer */
755         if (*((ARENA_FREE **)((char *)(pArena + 1) +
756             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
757         {
758             ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
759                      (DWORD)subheap->heap, (DWORD)pArena,
760                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
761             return FALSE;
762         }
763     }
764     return TRUE;
765 }
766
767
768 /***********************************************************************
769  *           HEAP_ValidateInUseArena
770  */
771 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
772 {
773     char *heapEnd = (char *)subheap + subheap->size;
774
775 #if !defined(ALLOW_UNALIGNED_ACCESS)
776     /* Check for unaligned pointers */
777     if ( (long)pArena % sizeof(void *) != 0 )
778     {
779         if ( quiet == NOISY )
780         {
781             ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
782                   (DWORD)subheap->heap, (DWORD)pArena );
783             if ( TRACE_ON(heap) )
784                 HEAP_Dump( subheap->heap );
785         }
786         else if ( WARN_ON(heap) )
787         {
788             WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
789                   (DWORD)subheap->heap, (DWORD)pArena );
790             if ( TRACE_ON(heap) )
791                 HEAP_Dump( subheap->heap );
792         }
793         return FALSE;
794     }
795 #endif
796
797     /* Check magic number */
798     if (pArena->magic != ARENA_INUSE_MAGIC)
799     {
800         if (quiet == NOISY) {
801         ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
802                  (DWORD)subheap->heap, (DWORD)pArena );
803             if (TRACE_ON(heap))
804                HEAP_Dump( subheap->heap );
805         }  else if (WARN_ON(heap)) {
806             WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
807                  (DWORD)subheap->heap, (DWORD)pArena );
808             if (TRACE_ON(heap))
809                HEAP_Dump( subheap->heap );
810         }
811         return FALSE;
812     }
813     /* Check size flags */
814     if (pArena->size & ARENA_FLAG_FREE) 
815     {
816         ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
817                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
818     }
819     /* Check arena size */
820     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
821     {
822         ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
823                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
824         return FALSE;
825     }
826     /* Check next arena PREV_FREE flag */
827     if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
828         (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
829     {
830         ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
831                  (DWORD)subheap->heap, (DWORD)pArena );
832         return FALSE;
833     }
834     /* Check prev free arena */
835     if (pArena->size & ARENA_FLAG_PREV_FREE)
836     {
837         ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
838         /* Check prev pointer */
839         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
840         {
841             ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
842                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
843             return FALSE;
844         }
845         /* Check that prev arena is free */
846         if (!(pPrev->size & ARENA_FLAG_FREE) ||
847             (pPrev->magic != ARENA_FREE_MAGIC))
848         { 
849             ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
850                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
851             return FALSE;
852         }
853         /* Check that prev arena is really the previous block */
854         if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
855         {
856             ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
857                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
858             return FALSE;
859         }
860     }
861     return TRUE;
862 }
863
864
865 /***********************************************************************
866  *           HEAP_GetSegptr
867  *
868  * Transform a linear pointer into a SEGPTR. The pointer must have been
869  * allocated from a HEAP_WINE_SEGPTR heap.
870  */
871 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
872 {
873     HEAP *heapPtr = HEAP_GetPtr( heap );
874     SUBHEAP *subheap;
875     SEGPTR ret = 0;
876
877     /* Validate the parameters */
878
879     if (!heapPtr) return 0;
880     flags |= heapPtr->flags;
881     if (!(flags & HEAP_WINE_SEGPTR))
882     {
883         ERR("Heap %08x is not a SEGPTR heap\n",
884                  heap );
885         return 0;
886     }
887     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
888
889     /* Get the subheap */
890
891     if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
892         ret = MAKESEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
893
894     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
895     return ret;
896 }
897
898 /***********************************************************************
899  *           MapLS   (KERNEL32.522)
900  *
901  * Maps linear pointer to segmented.
902  */
903 SEGPTR WINAPI MapLS( LPCVOID ptr )
904 {
905     SUBHEAP *subheap;
906     SEGPTR ret = 0;
907
908     if (!HIWORD(ptr)) return (SEGPTR)ptr;
909
910     /* check if the pointer is inside the segptr heap */
911     EnterCriticalSection( &segptrHeap->critSection );
912     if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
913         ret = MAKESEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
914     LeaveCriticalSection( &segptrHeap->critSection );
915
916     /* otherwise, allocate a brand-new selector */
917     if (!ret)
918     {
919         WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
920         ret = MAKESEGPTR( sel, 0 );
921     }
922     return ret;
923 }
924
925
926 /***********************************************************************
927  *           UnMapLS   (KERNEL32.700)
928  *
929  * Free mapped selector.
930  */
931 void WINAPI UnMapLS( SEGPTR sptr )
932 {
933     SUBHEAP *subheap;
934     if (!SELECTOROF(sptr)) return;
935
936     /* check if ptr is inside segptr heap */
937     EnterCriticalSection( &segptrHeap->critSection );
938     subheap = HEAP_FindSubHeap( segptrHeap, MapSL(sptr) );
939     if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
940     LeaveCriticalSection( &segptrHeap->critSection );
941     /* if not inside heap, free the selector */
942     if (!subheap) FreeSelector16( SELECTOROF(sptr) );
943 }
944
945 /***********************************************************************
946  *           HEAP_IsRealArena  [Internal]
947  * Validates a block is a valid arena.
948  *
949  * RETURNS
950  *      TRUE: Success
951  *      FALSE: Failure
952  */
953 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
954               DWORD flags,   /* [in] Bit flags that control access during operation */
955               LPCVOID block, /* [in] Optional pointer to memory block to validate */
956               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
957                               *             does not complain    */
958 {
959     SUBHEAP *subheap;
960     BOOL ret = TRUE;
961
962     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
963     {
964         ERR("Invalid heap %p!\n", heapPtr );
965         return FALSE;
966     }
967
968     flags &= HEAP_NO_SERIALIZE;
969     flags |= heapPtr->flags;
970     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
971     if (!(flags & HEAP_NO_SERIALIZE))
972         EnterCriticalSection( &heapPtr->critSection );
973
974     if (block)
975     {
976         /* Only check this single memory block */
977
978         if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
979             ((char *)block < (char *)subheap + subheap->headerSize
980                               + sizeof(ARENA_INUSE)))
981         {
982             if (quiet == NOISY) 
983                 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
984             else if (WARN_ON(heap)) 
985                 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
986             ret = FALSE;
987         } else
988             ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
989
990         if (!(flags & HEAP_NO_SERIALIZE))
991             LeaveCriticalSection( &heapPtr->critSection );
992         return ret;
993     }
994
995     subheap = &heapPtr->subheap;
996     while (subheap && ret)
997     {
998         char *ptr = (char *)subheap + subheap->headerSize;
999         while (ptr < (char *)subheap + subheap->size)
1000         {
1001             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1002             {
1003                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1004                     ret = FALSE;
1005                     break;
1006                 }
1007                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1008             }
1009             else
1010             {
1011                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1012                     ret = FALSE;
1013                     break;
1014                 }
1015                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1016             }
1017         }
1018         subheap = subheap->next;
1019     }
1020
1021     if (!(flags & HEAP_NO_SERIALIZE))
1022         LeaveCriticalSection( &heapPtr->critSection );
1023     return ret;
1024 }
1025
1026
1027 /***********************************************************************
1028  *           HEAP_CreateSystemHeap
1029  *
1030  * Create the system heap.
1031  */
1032 static HANDLE HEAP_CreateSystemHeap(void)
1033 {
1034     int created;
1035
1036     HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1037                                      0, HEAP_DEF_SIZE, "__SystemHeap" );
1038     if (!map) return 0;
1039     created = (GetLastError() != ERROR_ALREADY_EXISTS);
1040
1041     if (!(systemHeap = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1042     {
1043         /* pre-defined address not available, use any one */
1044         ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
1045         return 0;
1046     }
1047
1048     if (created)  /* newly created heap */
1049     {
1050         HEAP_InitSubHeap( systemHeap, systemHeap, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1051         MakeCriticalSectionGlobal( &systemHeap->critSection );
1052     }
1053     else
1054     {
1055         /* wait for the heap to be initialized */
1056         while (!systemHeap->critSection.LockSemaphore) Sleep(1);
1057     }
1058     CloseHandle( map );
1059     return (HANDLE)systemHeap;
1060 }
1061
1062
1063 /***********************************************************************
1064  *           HeapCreate   (KERNEL32.336)
1065  * RETURNS
1066  *      Handle of heap: Success
1067  *      NULL: Failure
1068  */
1069 HANDLE WINAPI HeapCreate(
1070                 DWORD flags,       /* [in] Heap allocation flag */
1071                 DWORD initialSize, /* [in] Initial heap size */
1072                 DWORD maxSize      /* [in] Maximum heap size */
1073 ) {
1074     SUBHEAP *subheap;
1075
1076     if ( flags & HEAP_SHARED ) {
1077         WARN( "Shared Heap requested, returning system heap.\n" );
1078         if (!systemHeap) HEAP_CreateSystemHeap();
1079         return (HANDLE)systemHeap;
1080     }
1081
1082     /* Allocate the heap block */
1083
1084     if (!maxSize)
1085     {
1086         maxSize = HEAP_DEF_SIZE;
1087         flags |= HEAP_GROWABLE;
1088     }
1089     if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1090     {
1091         SetLastError( ERROR_OUTOFMEMORY );
1092         return 0;
1093     }
1094
1095     /* link it into the per-process heap list */
1096     if (processHeap)
1097     {
1098         HEAP *heapPtr = subheap->heap;
1099         EnterCriticalSection( &processHeap->critSection );
1100         heapPtr->next = firstHeap;
1101         firstHeap = heapPtr;
1102         LeaveCriticalSection( &processHeap->critSection );
1103     }
1104     else  /* assume the first heap we create is the process main heap */
1105     {
1106         SUBHEAP *segptr;
1107         processHeap = subheap->heap;
1108         /* create the SEGPTR heap */
1109         if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1110         {
1111             SetLastError( ERROR_OUTOFMEMORY );
1112             return 0;
1113         }
1114         segptrHeap = segptr->heap;
1115     }
1116     return (HANDLE)subheap;
1117 }
1118
1119 /***********************************************************************
1120  *           HeapDestroy   (KERNEL32.337)
1121  * RETURNS
1122  *      TRUE: Success
1123  *      FALSE: Failure
1124  */
1125 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1126 {
1127     HEAP *heapPtr = HEAP_GetPtr( heap );
1128     SUBHEAP *subheap;
1129
1130     TRACE("%08x\n", heap );
1131     if (!heapPtr) return FALSE;
1132
1133     if (heapPtr == systemHeap)
1134     {
1135         WARN( "attempt to destroy system heap, returning TRUE!\n" );
1136         return TRUE;
1137     }
1138     if (heapPtr == processHeap)  /* cannot delete the main process heap */
1139     {
1140         SetLastError( ERROR_INVALID_PARAMETER );
1141         return FALSE;
1142     }
1143     else /* remove it from the per-process list */
1144     {
1145         HEAP **pptr;
1146         EnterCriticalSection( &processHeap->critSection );
1147         pptr = &firstHeap;
1148         while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1149         if (*pptr) *pptr = (*pptr)->next;
1150         LeaveCriticalSection( &processHeap->critSection );
1151     }
1152
1153     DeleteCriticalSection( &heapPtr->critSection );
1154     subheap = &heapPtr->subheap;
1155     while (subheap)
1156     {
1157         SUBHEAP *next = subheap->next;
1158         if (subheap->selector) FreeSelector16( subheap->selector );
1159         VirtualFree( subheap, 0, MEM_RELEASE );
1160         subheap = next;
1161     }
1162     return TRUE;
1163 }
1164
1165
1166 /***********************************************************************
1167  *           HeapAlloc   (KERNEL32.334)
1168  * RETURNS
1169  *      Pointer to allocated memory block
1170  *      NULL: Failure
1171  */
1172 LPVOID WINAPI HeapAlloc(
1173               HANDLE heap, /* [in] Handle of private heap block */
1174               DWORD flags,   /* [in] Heap allocation control flags */
1175               DWORD size     /* [in] Number of bytes to allocate */
1176 ) {
1177     ARENA_FREE *pArena;
1178     ARENA_INUSE *pInUse;
1179     SUBHEAP *subheap;
1180     HEAP *heapPtr = HEAP_GetPtr( heap );
1181
1182     /* Validate the parameters */
1183
1184     if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1185     if (!heapPtr) return NULL;
1186     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1187     flags |= heapPtr->flags;
1188     size = (size + 3) & ~3;
1189     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1190
1191     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1192     /* Locate a suitable free block */
1193
1194     if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1195     {
1196         TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1197                   heap, flags, size  );
1198         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1199         SetLastError( ERROR_COMMITMENT_LIMIT );
1200         return NULL;
1201     }
1202
1203     /* Remove the arena from the free list */
1204
1205     pArena->next->prev = pArena->prev;
1206     pArena->prev->next = pArena->next;
1207
1208     /* Build the in-use arena */
1209
1210     pInUse = (ARENA_INUSE *)pArena;
1211
1212     /* in-use arena is smaller than free arena,
1213      * so we have to add the difference to the size */
1214     pInUse->size      = (pInUse->size & ~ARENA_FLAG_FREE)
1215                         + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1216     pInUse->callerEIP = GET_EIP();
1217     pInUse->threadId  = GetCurrentTask();
1218     pInUse->magic     = ARENA_INUSE_MAGIC;
1219
1220     /* Shrink the block */
1221
1222     HEAP_ShrinkBlock( subheap, pInUse, size );
1223
1224     if (flags & HEAP_ZERO_MEMORY)
1225         memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1226     else if (TRACE_ON(heap))
1227         memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1228
1229     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1230
1231     TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1232                   heap, flags, size, (DWORD)(pInUse + 1) );
1233     return (LPVOID)(pInUse + 1);
1234 }
1235
1236
1237 /***********************************************************************
1238  *           HeapFree   (KERNEL32.338)
1239  * RETURNS
1240  *      TRUE: Success
1241  *      FALSE: Failure
1242  */
1243 BOOL WINAPI HeapFree(
1244               HANDLE heap, /* [in] Handle of heap */
1245               DWORD flags,   /* [in] Heap freeing flags */
1246               LPVOID ptr     /* [in] Address of memory to free */
1247 ) {
1248     ARENA_INUSE *pInUse;
1249     SUBHEAP *subheap;
1250     HEAP *heapPtr = HEAP_GetPtr( heap );
1251
1252     /* Validate the parameters */
1253
1254     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1255     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1256     if (!heapPtr) return FALSE;
1257
1258     flags &= HEAP_NO_SERIALIZE;
1259     flags |= heapPtr->flags;
1260     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1261     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1262     {
1263         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1264         SetLastError( ERROR_INVALID_PARAMETER );
1265         TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1266                       heap, flags, (DWORD)ptr );
1267         return FALSE;
1268     }
1269
1270     /* Turn the block into a free block */
1271
1272     pInUse  = (ARENA_INUSE *)ptr - 1;
1273     subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1274     HEAP_MakeInUseBlockFree( subheap, pInUse );
1275
1276     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1277
1278     TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1279                   heap, flags, (DWORD)ptr );
1280     return TRUE;
1281 }
1282
1283
1284 /***********************************************************************
1285  *           HeapReAlloc   (KERNEL32.340)
1286  * RETURNS
1287  *      Pointer to reallocated memory block
1288  *      NULL: Failure
1289  */
1290 LPVOID WINAPI HeapReAlloc(
1291               HANDLE heap, /* [in] Handle of heap block */
1292               DWORD flags,   /* [in] Heap reallocation flags */
1293               LPVOID ptr,    /* [in] Address of memory to reallocate */
1294               DWORD size     /* [in] Number of bytes to reallocate */
1295 ) {
1296     ARENA_INUSE *pArena;
1297     DWORD oldSize;
1298     HEAP *heapPtr;
1299     SUBHEAP *subheap;
1300
1301     if (!ptr) return HeapAlloc( heap, flags, size );  /* FIXME: correct? */
1302     if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1303     if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1304
1305     /* Validate the parameters */
1306
1307     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1308              HEAP_REALLOC_IN_PLACE_ONLY;
1309     flags |= heapPtr->flags;
1310     size = (size + 3) & ~3;
1311     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1312
1313     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1314     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1315     {
1316         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1317         SetLastError( ERROR_INVALID_PARAMETER );
1318         TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1319                       heap, flags, (DWORD)ptr, size );
1320         return NULL;
1321     }
1322
1323     /* Check if we need to grow the block */
1324
1325     pArena = (ARENA_INUSE *)ptr - 1;
1326     pArena->threadId = GetCurrentTask();
1327     subheap = HEAP_FindSubHeap( heapPtr, pArena );
1328     oldSize = (pArena->size & ARENA_SIZE_MASK);
1329     if (size > oldSize)
1330     {
1331         char *pNext = (char *)(pArena + 1) + oldSize;
1332         if ((pNext < (char *)subheap + subheap->size) &&
1333             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1334             (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1335         {
1336             /* The next block is free and large enough */
1337             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1338             pFree->next->prev = pFree->prev;
1339             pFree->prev->next = pFree->next;
1340             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1341             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1342                                                + size + HEAP_MIN_BLOCK_SIZE))
1343             {
1344                 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1345                 SetLastError( ERROR_OUTOFMEMORY );
1346                 return NULL;
1347             }
1348             HEAP_ShrinkBlock( subheap, pArena, size );
1349         }
1350         else  /* Do it the hard way */
1351         {
1352             ARENA_FREE *pNew;
1353             ARENA_INUSE *pInUse;
1354             SUBHEAP *newsubheap;
1355
1356             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1357                 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1358             {
1359                 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1360                 SetLastError( ERROR_OUTOFMEMORY );
1361                 return NULL;
1362             }
1363
1364             /* Build the in-use arena */
1365
1366             pNew->next->prev = pNew->prev;
1367             pNew->prev->next = pNew->next;
1368             pInUse = (ARENA_INUSE *)pNew;
1369             pInUse->size     = (pInUse->size & ~ARENA_FLAG_FREE)
1370                                + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1371             pInUse->threadId = GetCurrentTask();
1372             pInUse->magic    = ARENA_INUSE_MAGIC;
1373             HEAP_ShrinkBlock( newsubheap, pInUse, size );
1374             memcpy( pInUse + 1, pArena + 1, oldSize );
1375
1376             /* Free the previous block */
1377
1378             HEAP_MakeInUseBlockFree( subheap, pArena );
1379             subheap = newsubheap;
1380             pArena  = pInUse;
1381         }
1382     }
1383     else HEAP_ShrinkBlock( subheap, pArena, size );  /* Shrink the block */
1384
1385     /* Clear the extra bytes if needed */
1386
1387     if (size > oldSize)
1388     {
1389         if (flags & HEAP_ZERO_MEMORY)
1390             memset( (char *)(pArena + 1) + oldSize, 0,
1391                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
1392         else if (TRACE_ON(heap))
1393             memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1394                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
1395     }
1396
1397     /* Return the new arena */
1398
1399     pArena->callerEIP = GET_EIP();
1400     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1401
1402     TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1403                   heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1404     return (LPVOID)(pArena + 1);
1405 }
1406
1407
1408 /***********************************************************************
1409  *           HeapCompact   (KERNEL32.335)
1410  */
1411 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1412 {
1413     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1414     return 0;
1415 }
1416
1417
1418 /***********************************************************************
1419  *           HeapLock   (KERNEL32.339)
1420  * Attempts to acquire the critical section object for a specified heap.
1421  *
1422  * RETURNS
1423  *      TRUE: Success
1424  *      FALSE: Failure
1425  */
1426 BOOL WINAPI HeapLock(
1427               HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1428 ) {
1429     HEAP *heapPtr = HEAP_GetPtr( heap );
1430     if (!heapPtr) return FALSE;
1431     EnterCriticalSection( &heapPtr->critSection );
1432     return TRUE;
1433 }
1434
1435
1436 /***********************************************************************
1437  *           HeapUnlock   (KERNEL32.342)
1438  * Releases ownership of the critical section object.
1439  *
1440  * RETURNS
1441  *      TRUE: Success
1442  *      FALSE: Failure
1443  */
1444 BOOL WINAPI HeapUnlock(
1445               HANDLE heap /* [in] Handle to the heap to unlock */
1446 ) {
1447     HEAP *heapPtr = HEAP_GetPtr( heap );
1448     if (!heapPtr) return FALSE;
1449     LeaveCriticalSection( &heapPtr->critSection );
1450     return TRUE;
1451 }
1452
1453
1454 /***********************************************************************
1455  *           HeapSize   (KERNEL32.341)
1456  * RETURNS
1457  *      Size in bytes of allocated memory
1458  *      0xffffffff: Failure
1459  */
1460 DWORD WINAPI HeapSize(
1461              HANDLE heap, /* [in] Handle of heap */
1462              DWORD flags,   /* [in] Heap size control flags */
1463              LPVOID ptr     /* [in] Address of memory to return size for */
1464 ) {
1465     DWORD ret;
1466     HEAP *heapPtr = HEAP_GetPtr( heap );
1467
1468     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1469     if (!heapPtr) return FALSE;
1470     flags &= HEAP_NO_SERIALIZE;
1471     flags |= heapPtr->flags;
1472     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1473     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1474     {
1475         SetLastError( ERROR_INVALID_PARAMETER );
1476         ret = 0xffffffff;
1477     }
1478     else
1479     {
1480         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1481         ret = pArena->size & ARENA_SIZE_MASK;
1482     }
1483     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1484
1485     TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1486                   heap, flags, (DWORD)ptr, ret );
1487     return ret;
1488 }
1489
1490
1491 /***********************************************************************
1492  *           HeapValidate   (KERNEL32.343)
1493  * Validates a specified heap.
1494  *
1495  * NOTES
1496  *      Flags is ignored.
1497  *
1498  * RETURNS
1499  *      TRUE: Success
1500  *      FALSE: Failure
1501  */
1502 BOOL WINAPI HeapValidate(
1503               HANDLE heap, /* [in] Handle to the heap */
1504               DWORD flags,   /* [in] Bit flags that control access during operation */
1505               LPCVOID block  /* [in] Optional pointer to memory block to validate */
1506 ) {
1507     HEAP *heapPtr = HEAP_GetPtr( heap );
1508     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1509     if (!heapPtr) return FALSE;
1510     return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1511 }
1512
1513
1514 /***********************************************************************
1515  *           HeapWalk   (KERNEL32.344)
1516  * Enumerates the memory blocks in a specified heap.
1517  * See HEAP_Dump() for info on heap structure.
1518  *
1519  * TODO
1520  *   - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1521  *     PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1522  *
1523  * RETURNS
1524  *      TRUE: Success
1525  *      FALSE: Failure
1526  */
1527 BOOL WINAPI HeapWalk(
1528               HANDLE heap,               /* [in]  Handle to heap to enumerate */
1529               LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1530 ) {
1531     HEAP *heapPtr = HEAP_GetPtr(heap);
1532     SUBHEAP *sub, *currentheap = NULL;
1533     BOOL ret = FALSE;
1534     char *ptr;
1535     int region_index = 0;
1536
1537     if (!heapPtr || !entry)
1538     {
1539         SetLastError(ERROR_INVALID_PARAMETER);
1540         return FALSE;
1541     }
1542
1543     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1544
1545     /* set ptr to the next arena to be examined */
1546
1547     if (!entry->lpData) /* first call (init) ? */
1548     {
1549         TRACE("begin walking of heap 0x%08x.\n", heap);
1550         /*HEAP_Dump(heapPtr);*/
1551         currentheap = &heapPtr->subheap;
1552         ptr = (char*)currentheap + currentheap->headerSize;
1553     }
1554     else
1555     {
1556         ptr = entry->lpData;
1557         sub = &heapPtr->subheap;
1558         while (sub)
1559         {
1560             if (((char *)ptr >= (char *)sub) &&
1561                 ((char *)ptr < (char *)sub + sub->size))
1562             {
1563                 currentheap = sub;
1564                 break;
1565             }
1566             sub = sub->next;
1567             region_index++;
1568         }
1569         if (currentheap == NULL)
1570         {
1571             ERR("no matching subheap found, shouldn't happen !\n");
1572             SetLastError(ERROR_NO_MORE_ITEMS);
1573             goto HW_end;
1574         }
1575
1576         ptr += entry->cbData; /* point to next arena */
1577         if (ptr > (char *)currentheap + currentheap->size - 1)
1578         {   /* proceed with next subheap */
1579             if (!(currentheap = currentheap->next))
1580             {  /* successfully finished */
1581                 TRACE("end reached.\n");
1582                 SetLastError(ERROR_NO_MORE_ITEMS);
1583                 goto HW_end;
1584             }
1585             ptr = (char*)currentheap + currentheap->headerSize;
1586         }
1587     }
1588
1589     entry->wFlags = 0;
1590     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1591     {
1592         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1593
1594         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1595
1596         entry->lpData = pArena + 1;
1597         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1598         entry->cbOverhead = sizeof(ARENA_FREE);
1599         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1600     }
1601     else
1602     {
1603         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1604
1605         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1606         
1607         entry->lpData = pArena + 1;
1608         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1609         entry->cbOverhead = sizeof(ARENA_INUSE);
1610         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1611         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1612         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1613     }
1614
1615     entry->iRegionIndex = region_index;
1616
1617     /* first element of heap ? */
1618     if (ptr == (char *)(currentheap + currentheap->headerSize))
1619     {
1620         entry->wFlags |= PROCESS_HEAP_REGION;
1621         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1622         entry->u.Region.dwUnCommittedSize =
1623                 currentheap->size - currentheap->commitSize;
1624         entry->u.Region.lpFirstBlock = /* first valid block */
1625                 currentheap + currentheap->headerSize;
1626         entry->u.Region.lpLastBlock  = /* first invalid block */
1627                 currentheap + currentheap->size;
1628     }
1629     ret = TRUE;
1630
1631 HW_end:
1632     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1633
1634     return ret;
1635 }
1636
1637
1638 /***********************************************************************
1639  *           GetProcessHeap    (KERNEL32.259)
1640  */
1641 HANDLE WINAPI GetProcessHeap(void)
1642 {
1643     return (HANDLE)processHeap;
1644 }
1645
1646
1647 /***********************************************************************
1648  *           GetProcessHeaps    (KERNEL32.376)
1649  */
1650 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1651 {
1652     DWORD total;
1653     HEAP *ptr;
1654
1655     if (!processHeap) return 0;  /* should never happen */
1656     total = 1;  /* main heap */
1657     EnterCriticalSection( &processHeap->critSection );
1658     for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1659     if (total <= count)
1660     {
1661         *heaps++ = (HANDLE)processHeap;
1662         for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1663     }
1664     LeaveCriticalSection( &processHeap->critSection );
1665     return total;
1666 }
1667
1668
1669 /***********************************************************************
1670  * 32-bit local heap functions (Win95; undocumented)
1671  */
1672
1673 #define HTABLE_SIZE      0x10000
1674 #define HTABLE_PAGESIZE  0x1000
1675 #define HTABLE_NPAGES    (HTABLE_SIZE / HTABLE_PAGESIZE)
1676
1677 #include "pshpack1.h"
1678 typedef struct _LOCAL32HEADER
1679 {
1680     WORD     freeListFirst[HTABLE_NPAGES];
1681     WORD     freeListSize[HTABLE_NPAGES];
1682     WORD     freeListLast[HTABLE_NPAGES];
1683
1684     DWORD    selectorTableOffset;
1685     WORD     selectorTableSize;
1686     WORD     selectorDelta;
1687
1688     DWORD    segment;
1689     LPBYTE   base;
1690
1691     DWORD    limit;
1692     DWORD    flags;
1693
1694     DWORD    magic;
1695     HANDLE heap;
1696
1697 } LOCAL32HEADER;
1698 #include "poppack.h"
1699
1700 #define LOCAL32_MAGIC    ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1701
1702 /***********************************************************************
1703  *           Local32Init   (KERNEL.208)
1704  */
1705 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1706                              DWORD heapSize, DWORD flags )
1707 {
1708     DWORD totSize, segSize = 0;
1709     LPBYTE base;
1710     LOCAL32HEADER *header;
1711     HEAP *heap;
1712     WORD *selectorTable;
1713     WORD selectorEven, selectorOdd;
1714     int i, nrBlocks;
1715
1716     /* Determine new heap size */
1717
1718     if ( segment )
1719     {
1720         if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1721             return 0;
1722         else
1723             segSize++;
1724     }
1725
1726     if ( heapSize == -1L )
1727         heapSize = 1024L*1024L;   /* FIXME */
1728
1729     heapSize = (heapSize + 0xffff) & 0xffff0000;
1730     segSize  = (segSize  + 0x0fff) & 0xfffff000;
1731     totSize  = segSize + HTABLE_SIZE + heapSize;
1732
1733
1734     /* Allocate memory and initialize heap */
1735
1736     if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1737         return 0;
1738
1739     if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE, 
1740                         MEM_COMMIT, PAGE_READWRITE ) )
1741     {
1742         VirtualFree( base, 0, MEM_RELEASE );
1743         return 0;
1744     }
1745
1746     heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1747     if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1748     {
1749         VirtualFree( base, 0, MEM_RELEASE );
1750         return 0;
1751     }
1752
1753
1754     /* Set up header and handle table */
1755     
1756     header = (LOCAL32HEADER *)(base + segSize);
1757     header->base    = base;
1758     header->limit   = HTABLE_PAGESIZE-1;
1759     header->flags   = 0;
1760     header->magic   = LOCAL32_MAGIC;
1761     header->heap    = (HANDLE)heap;
1762
1763     header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1764     header->freeListLast[0]  = HTABLE_PAGESIZE - 4;
1765     header->freeListSize[0]  = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1766
1767     for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1768         *(DWORD *)((LPBYTE)header + i) = i+4;
1769
1770     header->freeListFirst[1] = 0xffff;
1771
1772
1773     /* Set up selector table */
1774   
1775     nrBlocks      = (totSize + 0x7fff) >> 15; 
1776     selectorTable = (LPWORD) HeapAlloc( header->heap,  0, nrBlocks * 2 );
1777     selectorEven  = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1778     selectorOdd   = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1779     if ( !selectorTable || !selectorEven || !selectorOdd )
1780     {
1781         if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1782         if ( selectorEven  ) SELECTOR_FreeBlock( selectorEven );
1783         if ( selectorOdd   ) SELECTOR_FreeBlock( selectorOdd );
1784         HeapDestroy( header->heap );
1785         VirtualFree( base, 0, MEM_RELEASE );
1786         return 0;
1787     }
1788
1789     header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1790     header->selectorTableSize   = nrBlocks * 4;  /* ??? Win95 does it this way! */
1791     header->selectorDelta       = selectorEven - selectorOdd;
1792     header->segment             = segment? segment : selectorEven;
1793
1794     for (i = 0; i < nrBlocks; i++)
1795         selectorTable[i] = (i & 1)? selectorOdd  + ((i >> 1) << __AHSHIFT)
1796                                   : selectorEven + ((i >> 1) << __AHSHIFT);
1797
1798     /* Move old segment */
1799
1800     if ( segment )
1801     {
1802         /* FIXME: This is somewhat ugly and relies on implementation
1803                   details about 16-bit global memory handles ... */
1804
1805         LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1806         memcpy( base, oldBase, segSize );
1807         GLOBAL_MoveBlock( segment, base, totSize );
1808         HeapFree( GetProcessHeap(), 0, oldBase );
1809     }
1810     
1811     return (HANDLE)header;
1812 }
1813
1814 /***********************************************************************
1815  *           Local32_SearchHandle
1816  */
1817 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1818 {
1819     LPDWORD handle;
1820
1821     for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1822           handle < (LPDWORD)((LPBYTE)header + header->limit);
1823           handle++)
1824     {
1825         if (*handle == addr)
1826             return handle;
1827     }
1828
1829     return NULL;
1830 }
1831
1832 /***********************************************************************
1833  *           Local32_ToHandle
1834  */
1835 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type, 
1836                               DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1837 {
1838     *handle = NULL;
1839     *ptr    = NULL;
1840
1841     switch (type)
1842     {
1843         case -2:    /* 16:16 pointer, no handles */
1844             *ptr    = MapSL( addr );
1845             *handle = (LPDWORD)*ptr;
1846             break;
1847
1848         case -1:    /* 32-bit offset, no handles */
1849             *ptr    = header->base + addr;
1850             *handle = (LPDWORD)*ptr;
1851             break;
1852
1853         case 0:     /* handle */
1854             if (    addr >= sizeof(LOCAL32HEADER) 
1855                  && addr <  header->limit && !(addr & 3) 
1856                  && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1857             {
1858                 *handle = (LPDWORD)((LPBYTE)header + addr);
1859                 *ptr    = header->base + **handle;
1860             }
1861             break;
1862
1863         case 1:     /* 16:16 pointer */
1864             *ptr    = MapSL( addr );
1865             *handle = Local32_SearchHandle( header, *ptr - header->base );
1866             break;
1867
1868         case 2:     /* 32-bit offset */
1869             *ptr    = header->base + addr;
1870             *handle = Local32_SearchHandle( header, *ptr - header->base );
1871             break;
1872     }
1873 }
1874
1875 /***********************************************************************
1876  *           Local32_FromHandle
1877  */
1878 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type, 
1879                                 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1880 {
1881     switch (type)
1882     {
1883         case -2:    /* 16:16 pointer */
1884         case  1:
1885         {
1886             WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1887             DWORD offset   = (LPBYTE)ptr - header->base;
1888             *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] ); 
1889         }
1890         break;
1891
1892         case -1:    /* 32-bit offset */
1893         case  2:
1894             *addr = ptr - header->base;
1895             break;
1896
1897         case  0:    /* handle */
1898             *addr = (LPBYTE)handle - (LPBYTE)header;
1899             break;
1900     }
1901 }
1902
1903 /***********************************************************************
1904  *           Local32Alloc   (KERNEL.209)
1905  */
1906 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1907 {
1908     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1909     LPDWORD handle;
1910     LPBYTE ptr;
1911     DWORD addr;
1912
1913     /* Allocate memory */
1914     ptr = HeapAlloc( header->heap, 
1915                      (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1916     if (!ptr) return 0;
1917
1918
1919     /* Allocate handle if requested */
1920     if (type >= 0)
1921     {
1922         int page, i;
1923
1924         /* Find first page of handle table with free slots */
1925         for (page = 0; page < HTABLE_NPAGES; page++)
1926             if (header->freeListFirst[page] != 0)
1927                 break;
1928         if (page == HTABLE_NPAGES)
1929         {
1930             WARN("Out of handles!\n" );
1931             HeapFree( header->heap, 0, ptr );
1932             return 0;
1933         }
1934
1935         /* If virgin page, initialize it */
1936         if (header->freeListFirst[page] == 0xffff)
1937         {
1938             if ( !VirtualAlloc( (LPBYTE)header + (page << 12), 
1939                                 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1940             {
1941                 WARN("Cannot grow handle table!\n" );
1942                 HeapFree( header->heap, 0, ptr );
1943                 return 0;
1944             }
1945             
1946             header->limit += HTABLE_PAGESIZE;
1947
1948             header->freeListFirst[page] = 0;
1949             header->freeListLast[page]  = HTABLE_PAGESIZE - 4;
1950             header->freeListSize[page]  = HTABLE_PAGESIZE / 4;
1951            
1952             for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1953                 *(DWORD *)((LPBYTE)header + i) = i+4;
1954
1955             if (page < HTABLE_NPAGES-1) 
1956                 header->freeListFirst[page+1] = 0xffff;
1957         }
1958
1959         /* Allocate handle slot from page */
1960         handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1961         if (--header->freeListSize[page] == 0)
1962             header->freeListFirst[page] = header->freeListLast[page] = 0;
1963         else
1964             header->freeListFirst[page] = *handle;
1965
1966         /* Store 32-bit offset in handle slot */
1967         *handle = ptr - header->base;
1968     }
1969     else
1970     {
1971         handle = (LPDWORD)ptr;
1972         header->flags |= 1;
1973     }
1974
1975
1976     /* Convert handle to requested output type */
1977     Local32_FromHandle( header, type, &addr, handle, ptr );
1978     return addr;
1979 }
1980
1981 /***********************************************************************
1982  *           Local32ReAlloc   (KERNEL.210)
1983  */
1984 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1985                              DWORD size, DWORD flags )
1986 {
1987     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1988     LPDWORD handle;
1989     LPBYTE ptr;
1990
1991     if (!addr)
1992         return Local32Alloc16( heap, size, type, flags );
1993
1994     /* Retrieve handle and pointer */
1995     Local32_ToHandle( header, type, addr, &handle, &ptr );
1996     if (!handle) return FALSE;
1997
1998     /* Reallocate memory block */
1999     ptr = HeapReAlloc( header->heap, 
2000                        (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, 
2001                        ptr, size );
2002     if (!ptr) return 0;
2003
2004     /* Modify handle */
2005     if (type >= 0)
2006         *handle = ptr - header->base;
2007     else
2008         handle = (LPDWORD)ptr;
2009
2010     /* Convert handle to requested output type */
2011     Local32_FromHandle( header, type, &addr, handle, ptr );
2012     return addr;
2013 }
2014
2015 /***********************************************************************
2016  *           Local32Free   (KERNEL.211)
2017  */
2018 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2019 {
2020     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2021     LPDWORD handle;
2022     LPBYTE ptr;
2023
2024     /* Retrieve handle and pointer */
2025     Local32_ToHandle( header, type, addr, &handle, &ptr );
2026     if (!handle) return FALSE;
2027
2028     /* Free handle if necessary */
2029     if (type >= 0)
2030     {
2031         int offset = (LPBYTE)handle - (LPBYTE)header;
2032         int page   = offset >> 12;
2033
2034         /* Return handle slot to page free list */
2035         if (header->freeListSize[page]++ == 0)
2036             header->freeListFirst[page] = header->freeListLast[page]  = offset;
2037         else
2038             *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2039             header->freeListLast[page] = offset;
2040
2041         *handle = 0;
2042
2043         /* Shrink handle table when possible */
2044         while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2045         {
2046             if ( VirtualFree( (LPBYTE)header + 
2047                               (header->limit & ~(HTABLE_PAGESIZE-1)),
2048                               HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2049                 break;
2050
2051             header->limit -= HTABLE_PAGESIZE;
2052             header->freeListFirst[page] = 0xffff;
2053             page--;
2054         }
2055     }
2056
2057     /* Free memory */
2058     return HeapFree( header->heap, 0, ptr );
2059 }
2060
2061 /***********************************************************************
2062  *           Local32Translate   (KERNEL.213)
2063  */
2064 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2065 {
2066     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2067     LPDWORD handle;
2068     LPBYTE ptr;
2069
2070     Local32_ToHandle( header, type1, addr, &handle, &ptr );
2071     if (!handle) return 0;
2072
2073     Local32_FromHandle( header, type2, &addr, handle, ptr );
2074     return addr;
2075 }
2076
2077 /***********************************************************************
2078  *           Local32Size   (KERNEL.214)
2079  */
2080 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2081 {
2082     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2083     LPDWORD handle;
2084     LPBYTE ptr;
2085
2086     Local32_ToHandle( header, type, addr, &handle, &ptr );
2087     if (!handle) return 0;
2088
2089     return HeapSize( header->heap, 0, ptr );
2090 }
2091
2092 /***********************************************************************
2093  *           Local32ValidHandle   (KERNEL.215)
2094  */
2095 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2096 {
2097     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2098     LPDWORD handle;
2099     LPBYTE ptr;
2100
2101     Local32_ToHandle( header, 0, addr, &handle, &ptr );
2102     return handle != NULL;
2103 }
2104
2105 /***********************************************************************
2106  *           Local32GetSegment   (KERNEL.229)
2107  */
2108 WORD WINAPI Local32GetSegment16( HANDLE heap )
2109 {
2110     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2111     return header->segment;
2112 }
2113
2114 /***********************************************************************
2115  *           Local32_GetHeap
2116  */
2117 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2118 {
2119     WORD selector = GlobalHandleToSel16( handle );
2120     DWORD base  = GetSelectorBase( selector ); 
2121     DWORD limit = GetSelectorLimit16( selector ); 
2122
2123     /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2124        it this way ... */
2125
2126     if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2127         return (LOCAL32HEADER *)base;
2128
2129     base  += 0x10000;
2130     limit -= 0x10000;
2131
2132     if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2133         return (LOCAL32HEADER *)base;
2134
2135     return NULL;
2136 }
2137
2138 /***********************************************************************
2139  *           Local32Info   (KERNEL.444)  (TOOLHELP.84)
2140  */
2141 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2142 {
2143     SUBHEAP *heapPtr;
2144     LPBYTE ptr;
2145     int i;
2146
2147     LOCAL32HEADER *header = Local32_GetHeap( handle );
2148     if ( !header ) return FALSE;
2149
2150     if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2151         return FALSE;
2152
2153     heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2154     pLocal32Info->dwMemReserved = heapPtr->size;
2155     pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2156     pLocal32Info->dwTotalFree = 0L;
2157     pLocal32Info->dwLargestFreeBlock = 0L;
2158
2159     /* Note: Local32 heaps always have only one subheap! */
2160     ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2161     while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2162     {
2163         if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2164         {
2165             ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2166             DWORD size = (pArena->size & ARENA_SIZE_MASK);
2167             ptr += sizeof(*pArena) + size;
2168
2169             pLocal32Info->dwTotalFree += size;
2170             if ( size > pLocal32Info->dwLargestFreeBlock )
2171                 pLocal32Info->dwLargestFreeBlock = size;
2172         }
2173         else
2174         {
2175             ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2176             DWORD size = (pArena->size & ARENA_SIZE_MASK);
2177             ptr += sizeof(*pArena) + size;
2178         }
2179     }
2180
2181     pLocal32Info->dwcFreeHandles = 0;
2182     for ( i = 0; i < HTABLE_NPAGES; i++ )
2183     {
2184         if ( header->freeListFirst[i] == 0xffff ) break;
2185         pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2186     }
2187     pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2188
2189     return TRUE;
2190 }
2191
2192 /***********************************************************************
2193  *           Local32First   (KERNEL.445)  (TOOLHELP.85)
2194  */
2195 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2196 {
2197     FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2198     return FALSE;
2199 }
2200
2201 /***********************************************************************
2202  *           Local32Next   (KERNEL.446)  (TOOLHELP.86)
2203  */
2204 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2205 {
2206     FIXME("(%p): stub!\n", pLocal32Entry );
2207     return FALSE;
2208 }
2209