Calculate the size of BI_BITFIELDS dib sections via the width and
[wine] / dlls / ntdll / heap.c
1 /*
2  * Win32 heap functions
3  *
4  * Copyright 1996 Alexandre Julliard
5  * Copyright 1998 Ulrich Weigand
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
32
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "ntstatus.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winreg.h"
39 #include "winternl.h"
40 #include "wine/winbase16.h"
41 #include "winerror.h"
42 #include "winnt.h"
43 #include "thread.h"
44 #include "wine/debug.h"
45 #include "winternl.h"
46 #include "wine/server_protocol.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(heap);
49
50 /* Note: the heap data structures are based on what Pietrek describes in his
51  * book 'Windows 95 System Programming Secrets'. The layout is not exactly
52  * the same, but could be easily adapted if it turns out some programs
53  * require it.
54  */
55
56 typedef struct tagARENA_INUSE
57 {
58     DWORD  size;                    /* Block size; must be the first field */
59     DWORD  magic;                   /* Magic number */
60 } ARENA_INUSE;
61
62 typedef struct tagARENA_FREE
63 {
64     DWORD                 size;     /* Block size; must be the first field */
65     DWORD                 magic;    /* Magic number */
66     struct tagARENA_FREE *next;     /* Next free arena */
67     struct tagARENA_FREE *prev;     /* Prev free arena */
68 } ARENA_FREE;
69
70 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
71 #define ARENA_FLAG_PREV_FREE   0x00000002
72 #define ARENA_SIZE_MASK        (~3)
73 #define ARENA_INUSE_MAGIC      0x44455355      /* Value for arena 'magic' field */
74 #define ARENA_FREE_MAGIC       0x45455246      /* Value for arena 'magic' field */
75
76 #define ARENA_INUSE_FILLER     0x55
77 #define ARENA_FREE_FILLER      0xaa
78
79 #define ALIGNMENT              8   /* everything is aligned on 8 byte boundaries */
80 #define ROUND_SIZE(size)       (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
81
82 #define QUIET                  1           /* Suppress messages  */
83 #define NOISY                  0           /* Report all errors  */
84
85 #define HEAP_NB_FREE_LISTS   4   /* Number of free lists */
86
87 /* Max size of the blocks on the free lists */
88 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
89 {
90     0x20, 0x80, 0x200, ~0UL
91 };
92
93 typedef struct
94 {
95     DWORD       size;
96     ARENA_FREE  arena;
97 } FREE_LIST_ENTRY;
98
99 struct tagHEAP;
100
101 typedef struct tagSUBHEAP
102 {
103     DWORD               size;       /* Size of the whole sub-heap */
104     DWORD               commitSize; /* Committed size of the sub-heap */
105     DWORD               headerSize; /* Size of the heap header */
106     struct tagSUBHEAP  *next;       /* Next sub-heap */
107     struct tagHEAP     *heap;       /* Main heap structure */
108     DWORD               magic;      /* Magic number */
109 } SUBHEAP;
110
111 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
112
113 typedef struct tagHEAP
114 {
115     SUBHEAP          subheap;       /* First sub-heap */
116     struct tagHEAP  *next;          /* Next heap for this process */
117     CRITICAL_SECTION critSection;   /* Critical section for serialization */
118     FREE_LIST_ENTRY  freeList[HEAP_NB_FREE_LISTS];  /* Free lists */
119     DWORD            flags;         /* Heap flags */
120     DWORD            magic;         /* Magic number */
121 } HEAP;
122
123 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
124
125 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
126 #define HEAP_MIN_BLOCK_SIZE  (8+sizeof(ARENA_FREE))  /* Min. heap block size */
127 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
128
129 static HANDLE processHeap;  /* main process heap */
130
131 static HEAP *firstHeap;     /* head of secondary heaps list */
132
133 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
134
135 /* SetLastError for ntdll */
136 inline static void set_status( NTSTATUS status )
137 {
138     NtCurrentTeb()->LastErrorValue = RtlNtStatusToDosError( status );
139 }
140
141 /* mark a block of memory as free for debugging purposes */
142 static inline void mark_block_free( void *ptr, size_t size )
143 {
144     if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
145 #ifdef VALGRIND_MAKE_NOACCESS
146     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
147 #endif
148 }
149
150 /* mark a block of memory as initialized for debugging purposes */
151 static inline void mark_block_initialized( void *ptr, size_t size )
152 {
153 #ifdef VALGRIND_MAKE_READABLE
154     VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
155 #endif
156 }
157
158 /* mark a block of memory as uninitialized for debugging purposes */
159 static inline void mark_block_uninitialized( void *ptr, size_t size )
160 {
161 #ifdef VALGRIND_MAKE_WRITABLE
162     VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
163 #endif
164     if (TRACE_ON(heap))
165     {
166         memset( ptr, ARENA_INUSE_FILLER, size );
167 #ifdef VALGRIND_MAKE_WRITABLE
168         /* make it uninitialized to valgrind again */
169         VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
170 #endif
171     }
172 }
173
174 /* clear contents of a block of memory */
175 static inline void clear_block( void *ptr, size_t size )
176 {
177     mark_block_initialized( ptr, size );
178     memset( ptr, 0, size );
179 }
180
181 /***********************************************************************
182  *           HEAP_Dump
183  */
184 void HEAP_Dump( HEAP *heap )
185 {
186     int i;
187     SUBHEAP *subheap;
188     char *ptr;
189
190     DPRINTF( "Heap: %08lx\n", (DWORD)heap );
191     DPRINTF( "Next: %08lx  Sub-heaps: %08lx",
192           (DWORD)heap->next, (DWORD)&heap->subheap );
193     subheap = &heap->subheap;
194     while (subheap->next)
195     {
196         DPRINTF( " -> %08lx", (DWORD)subheap->next );
197         subheap = subheap->next;
198     }
199
200     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
201     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
202         DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
203               (DWORD)&heap->freeList[i].arena, heap->freeList[i].size,
204               (DWORD)heap->freeList[i].arena.prev,
205               (DWORD)heap->freeList[i].arena.next );
206
207     subheap = &heap->subheap;
208     while (subheap)
209     {
210         DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
211         DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
212               (DWORD)subheap, subheap->size, subheap->commitSize );
213
214         DPRINTF( "\n Block   Stat   Size    Id\n" );
215         ptr = (char*)subheap + subheap->headerSize;
216         while (ptr < (char *)subheap + subheap->size)
217         {
218             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
219             {
220                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
221                 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
222                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
223                       (DWORD)pArena->prev, (DWORD)pArena->next);
224                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
225                 arenaSize += sizeof(ARENA_FREE);
226                 freeSize += pArena->size & ARENA_SIZE_MASK;
227             }
228             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
229             {
230                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
231                 DPRINTF( "%08lx Used %08lx back=%08lx\n",
232                          (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
233                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
234                 arenaSize += sizeof(ARENA_INUSE);
235                 usedSize += pArena->size & ARENA_SIZE_MASK;
236             }
237             else
238             {
239                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
240                 DPRINTF( "%08lx used %08lx\n",
241                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
242                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
243                 arenaSize += sizeof(ARENA_INUSE);
244                 usedSize += pArena->size & ARENA_SIZE_MASK;
245             }
246         }
247         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
248               subheap->size, subheap->commitSize, freeSize, usedSize,
249               arenaSize, (arenaSize * 100) / subheap->size );
250         subheap = subheap->next;
251     }
252 }
253
254
255 /***********************************************************************
256  *           HEAP_GetPtr
257  * RETURNS
258  *      Pointer to the heap
259  *      NULL: Failure
260  */
261 static HEAP *HEAP_GetPtr(
262              HANDLE heap /* [in] Handle to the heap */
263 ) {
264     HEAP *heapPtr = (HEAP *)heap;
265     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
266     {
267         ERR("Invalid heap %p!\n", heap );
268         return NULL;
269     }
270     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
271     {
272         HEAP_Dump( heapPtr );
273         assert( FALSE );
274         return NULL;
275     }
276     return heapPtr;
277 }
278
279
280 /***********************************************************************
281  *           HEAP_InsertFreeBlock
282  *
283  * Insert a free block into the free list.
284  */
285 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
286 {
287     FREE_LIST_ENTRY *pEntry = heap->freeList;
288     while (pEntry->size < pArena->size) pEntry++;
289     if (last)
290     {
291         /* insert at end of free list, i.e. before the next free list entry */
292         pEntry++;
293         if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
294         pArena->prev       = pEntry->arena.prev;
295         pArena->prev->next = pArena;
296         pArena->next       = &pEntry->arena;
297         pEntry->arena.prev = pArena;
298     }
299     else
300     {
301         /* insert at head of free list */
302         pArena->next       = pEntry->arena.next;
303         pArena->next->prev = pArena;
304         pArena->prev       = &pEntry->arena;
305         pEntry->arena.next = pArena;
306     }
307     pArena->size |= ARENA_FLAG_FREE;
308 }
309
310
311 /***********************************************************************
312  *           HEAP_FindSubHeap
313  * Find the sub-heap containing a given address.
314  *
315  * RETURNS
316  *      Pointer: Success
317  *      NULL: Failure
318  */
319 static SUBHEAP *HEAP_FindSubHeap(
320                 HEAP *heap, /* [in] Heap pointer */
321                 LPCVOID ptr /* [in] Address */
322 ) {
323     SUBHEAP *sub = &heap->subheap;
324     while (sub)
325     {
326         if (((char *)ptr >= (char *)sub) &&
327             ((char *)ptr < (char *)sub + sub->size)) return sub;
328         sub = sub->next;
329     }
330     return NULL;
331 }
332
333
334 /***********************************************************************
335  *           HEAP_Commit
336  *
337  * Make sure the heap storage is committed up to (not including) ptr.
338  */
339 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
340 {
341     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
342     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
343     if (size > subheap->size) size = subheap->size;
344     if (size <= subheap->commitSize) return TRUE;
345     size -= subheap->commitSize;
346     if (NtAllocateVirtualMemory( GetCurrentProcess(), &ptr, (char *)subheap + subheap->commitSize,
347                                  &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
348     {
349         WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
350                  size, (DWORD)((char *)subheap + subheap->commitSize),
351                  (DWORD)subheap->heap );
352         return FALSE;
353     }
354     subheap->commitSize += size;
355     return TRUE;
356 }
357
358
359 /***********************************************************************
360  *           HEAP_Decommit
361  *
362  * If possible, decommit the heap storage from (including) 'ptr'.
363  */
364 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
365 {
366     void *addr;
367     ULONG decommit_size;
368
369     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
370     /* round to next block and add one full block */
371     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
372     if (size >= subheap->commitSize) return TRUE;
373     decommit_size = subheap->commitSize - size;
374     addr = (char *)subheap + size;
375
376     if (NtFreeVirtualMemory( GetCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
377     {
378         WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
379                  decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
380         return FALSE;
381     }
382     subheap->commitSize -= decommit_size;
383     return TRUE;
384 }
385
386
387 /***********************************************************************
388  *           HEAP_CreateFreeBlock
389  *
390  * Create a free block at a specified address. 'size' is the size of the
391  * whole block, including the new arena.
392  */
393 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
394 {
395     ARENA_FREE *pFree;
396     char *pEnd;
397     BOOL last;
398
399     /* Create a free arena */
400     mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
401     pFree = (ARENA_FREE *)ptr;
402     pFree->magic = ARENA_FREE_MAGIC;
403
404     /* If debugging, erase the freed block content */
405
406     pEnd = (char *)ptr + size;
407     if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
408     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
409
410     /* Check if next block is free also */
411
412     if (((char *)ptr + size < (char *)subheap + subheap->size) &&
413         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
414     {
415         /* Remove the next arena from the free list */
416         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
417         pNext->next->prev = pNext->prev;
418         pNext->prev->next = pNext->next;
419         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
420         mark_block_free( pNext, sizeof(ARENA_FREE) );
421     }
422
423     /* Set the next block PREV_FREE flag and pointer */
424
425     last = ((char *)ptr + size >= (char *)subheap + subheap->size);
426     if (!last)
427     {
428         DWORD *pNext = (DWORD *)((char *)ptr + size);
429         *pNext |= ARENA_FLAG_PREV_FREE;
430         mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
431         *(ARENA_FREE **)(pNext - 1) = pFree;
432     }
433
434     /* Last, insert the new block into the free list */
435
436     pFree->size = size - sizeof(*pFree);
437     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
438 }
439
440
441 /***********************************************************************
442  *           HEAP_MakeInUseBlockFree
443  *
444  * Turn an in-use block into a free block. Can also decommit the end of
445  * the heap, and possibly even free the sub-heap altogether.
446  */
447 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
448 {
449     ARENA_FREE *pFree;
450     DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
451
452     /* Check if we can merge with previous block */
453
454     if (pArena->size & ARENA_FLAG_PREV_FREE)
455     {
456         pFree = *((ARENA_FREE **)pArena - 1);
457         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
458         /* Remove it from the free list */
459         pFree->next->prev = pFree->prev;
460         pFree->prev->next = pFree->next;
461     }
462     else pFree = (ARENA_FREE *)pArena;
463
464     /* Create a free block */
465
466     HEAP_CreateFreeBlock( subheap, pFree, size );
467     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
468     if ((char *)pFree + size < (char *)subheap + subheap->size)
469         return;  /* Not the last block, so nothing more to do */
470
471     /* Free the whole sub-heap if it's empty and not the original one */
472
473     if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
474         (subheap != &subheap->heap->subheap))
475     {
476         ULONG size = 0;
477         SUBHEAP *pPrev = &subheap->heap->subheap;
478         /* Remove the free block from the list */
479         pFree->next->prev = pFree->prev;
480         pFree->prev->next = pFree->next;
481         /* Remove the subheap from the list */
482         while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
483         if (pPrev) pPrev->next = subheap->next;
484         /* Free the memory */
485         subheap->magic = 0;
486         NtFreeVirtualMemory( GetCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
487         return;
488     }
489
490     /* Decommit the end of the heap */
491
492     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
493 }
494
495
496 /***********************************************************************
497  *           HEAP_ShrinkBlock
498  *
499  * Shrink an in-use block.
500  */
501 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
502 {
503     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
504     {
505         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
506                               (pArena->size & ARENA_SIZE_MASK) - size );
507         /* assign size plus previous arena flags */
508         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
509     }
510     else
511     {
512         /* Turn off PREV_FREE flag in next block */
513         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
514         if (pNext < (char *)subheap + subheap->size)
515             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
516     }
517 }
518
519 /***********************************************************************
520  *           HEAP_InitSubHeap
521  */
522 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
523                                 DWORD commitSize, DWORD totalSize )
524 {
525     SUBHEAP *subheap;
526     FREE_LIST_ENTRY *pEntry;
527     int i;
528
529     /* Commit memory */
530
531     if (flags & HEAP_SHARED)
532         commitSize = totalSize;  /* always commit everything in a shared heap */
533     if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, address,
534                                  &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
535     {
536         WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
537         return FALSE;
538     }
539
540     /* Fill the sub-heap structure */
541
542     subheap = (SUBHEAP *)address;
543     subheap->heap       = heap;
544     subheap->size       = totalSize;
545     subheap->commitSize = commitSize;
546     subheap->magic      = SUBHEAP_MAGIC;
547
548     if ( subheap != (SUBHEAP *)heap )
549     {
550         /* If this is a secondary subheap, insert it into list */
551
552         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
553         subheap->next       = heap->subheap.next;
554         heap->subheap.next  = subheap;
555     }
556     else
557     {
558         /* If this is a primary subheap, initialize main heap */
559
560         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
561         subheap->next       = NULL;
562         heap->next          = NULL;
563         heap->flags         = flags;
564         heap->magic         = HEAP_MAGIC;
565
566         /* Build the free lists */
567
568         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
569         {
570             pEntry->size       = HEAP_freeListSizes[i];
571             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
572             pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
573                                  &heap->freeList[i+1].arena : &heap->freeList[0].arena;
574             pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
575                                   &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
576             pEntry->arena.magic = ARENA_FREE_MAGIC;
577         }
578
579         /* Initialize critical section */
580
581         RtlInitializeCriticalSection( &heap->critSection );
582         if (flags & HEAP_SHARED)
583         {
584             /* let's assume that only one thread at a time will try to do this */
585             HANDLE sem = heap->critSection.LockSemaphore;
586             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
587
588             NtDuplicateObject( GetCurrentProcess(), sem, GetCurrentProcess(), &sem, 0, 0,
589                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
590             heap->critSection.LockSemaphore = sem;
591         }
592     }
593
594     /* Create the first free block */
595
596     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
597                           subheap->size - subheap->headerSize );
598
599     return TRUE;
600 }
601
602 /***********************************************************************
603  *           HEAP_CreateSubHeap
604  *
605  * Create a sub-heap of the given size.
606  * If heap == NULL, creates a main heap.
607  */
608 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
609                                     DWORD commitSize, DWORD totalSize )
610 {
611     LPVOID address = base;
612
613     /* round-up sizes on a 64K boundary */
614     totalSize  = (totalSize + 0xffff) & 0xffff0000;
615     commitSize = (commitSize + 0xffff) & 0xffff0000;
616     if (!commitSize) commitSize = 0x10000;
617     if (totalSize < commitSize) totalSize = commitSize;
618
619     if (!address)
620     {
621         /* allocate the memory block */
622         if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, NULL, &totalSize,
623                                      MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
624         {
625             WARN("Could not allocate %08lx bytes\n", totalSize );
626             return NULL;
627         }
628     }
629
630     /* Initialize subheap */
631
632     if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
633                            address, flags, commitSize, totalSize ))
634     {
635         ULONG size = 0;
636         if (!base) NtFreeVirtualMemory( GetCurrentProcess(), &address, &size, MEM_RELEASE );
637         return NULL;
638     }
639
640     return (SUBHEAP *)address;
641 }
642
643
644 /***********************************************************************
645  *           HEAP_FindFreeBlock
646  *
647  * Find a free block at least as large as the requested size, and make sure
648  * the requested size is committed.
649  */
650 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
651                                        SUBHEAP **ppSubHeap )
652 {
653     SUBHEAP *subheap;
654     ARENA_FREE *pArena;
655     FREE_LIST_ENTRY *pEntry = heap->freeList;
656
657     /* Find a suitable free list, and in it find a block large enough */
658
659     while (pEntry->size < size) pEntry++;
660     pArena = pEntry->arena.next;
661     while (pArena != &heap->freeList[0].arena)
662     {
663         DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
664                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
665         if (arena_size >= size)
666         {
667             subheap = HEAP_FindSubHeap( heap, pArena );
668             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
669                                                + size + HEAP_MIN_BLOCK_SIZE))
670                 return NULL;
671             *ppSubHeap = subheap;
672             return pArena;
673         }
674         pArena = pArena->next;
675     }
676
677     /* If no block was found, attempt to grow the heap */
678
679     if (!(heap->flags & HEAP_GROWABLE))
680     {
681         WARN("Not enough space in heap %08lx for %08lx bytes\n",
682                  (DWORD)heap, size );
683         return NULL;
684     }
685     /* make sure that we have a big enough size *committed* to fit another
686      * last free arena in !
687      * So just one heap struct, one first free arena which will eventually
688      * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
689      * might get assigned all remaining free space in HEAP_ShrinkBlock() */
690     size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
691     if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
692                                         max( HEAP_DEF_SIZE, size ) )))
693         return NULL;
694
695     TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
696                 (DWORD)subheap, size, (DWORD)heap );
697
698     *ppSubHeap = subheap;
699     return (ARENA_FREE *)(subheap + 1);
700 }
701
702
703 /***********************************************************************
704  *           HEAP_IsValidArenaPtr
705  *
706  * Check that the pointer is inside the range possible for arenas.
707  */
708 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
709 {
710     int i;
711     SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
712     if (!subheap) return FALSE;
713     if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
714     if (subheap != &heap->subheap) return FALSE;
715     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
716         if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
717     return FALSE;
718 }
719
720
721 /***********************************************************************
722  *           HEAP_ValidateFreeArena
723  */
724 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
725 {
726     char *heapEnd = (char *)subheap + subheap->size;
727
728     /* Check for unaligned pointers */
729     if ( (long)pArena % ALIGNMENT != 0 )
730     {
731         ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
732              (DWORD)subheap->heap, (DWORD)pArena );
733         return FALSE;
734     }
735
736     /* Check magic number */
737     if (pArena->magic != ARENA_FREE_MAGIC)
738     {
739         ERR("Heap %08lx: invalid free arena magic for %08lx\n",
740                  (DWORD)subheap->heap, (DWORD)pArena );
741         return FALSE;
742     }
743     /* Check size flags */
744     if (!(pArena->size & ARENA_FLAG_FREE) ||
745         (pArena->size & ARENA_FLAG_PREV_FREE))
746     {
747         ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
748                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
749     }
750     /* Check arena size */
751     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
752     {
753         ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
754                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
755         return FALSE;
756     }
757     /* Check that next pointer is valid */
758     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
759     {
760         ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
761                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
762         return FALSE;
763     }
764     /* Check that next arena is free */
765     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
766         (pArena->next->magic != ARENA_FREE_MAGIC))
767     {
768         ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
769                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
770         return FALSE;
771     }
772     /* Check that prev pointer is valid */
773     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
774     {
775         ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
776                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
777         return FALSE;
778     }
779     /* Check that prev arena is free */
780     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
781         (pArena->prev->magic != ARENA_FREE_MAGIC))
782     {
783         /* this often means that the prev arena got overwritten
784          * by a memory write before that prev arena */
785         ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
786                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
787         return FALSE;
788     }
789     /* Check that next block has PREV_FREE flag */
790     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
791     {
792         if (!(*(DWORD *)((char *)(pArena + 1) +
793             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
794         {
795             ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
796                      (DWORD)subheap->heap, (DWORD)pArena );
797             return FALSE;
798         }
799         /* Check next block back pointer */
800         if (*((ARENA_FREE **)((char *)(pArena + 1) +
801             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
802         {
803             ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
804                      (DWORD)subheap->heap, (DWORD)pArena,
805                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
806             return FALSE;
807         }
808     }
809     return TRUE;
810 }
811
812
813 /***********************************************************************
814  *           HEAP_ValidateInUseArena
815  */
816 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
817 {
818     char *heapEnd = (char *)subheap + subheap->size;
819
820     /* Check for unaligned pointers */
821     if ( (long)pArena % ALIGNMENT != 0 )
822     {
823         if ( quiet == NOISY )
824         {
825             ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
826                   (DWORD)subheap->heap, (DWORD)pArena );
827             if ( TRACE_ON(heap) )
828                 HEAP_Dump( subheap->heap );
829         }
830         else if ( WARN_ON(heap) )
831         {
832             WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
833                   (DWORD)subheap->heap, (DWORD)pArena );
834             if ( TRACE_ON(heap) )
835                 HEAP_Dump( subheap->heap );
836         }
837         return FALSE;
838     }
839
840     /* Check magic number */
841     if (pArena->magic != ARENA_INUSE_MAGIC)
842     {
843         if (quiet == NOISY) {
844         ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
845                  (DWORD)subheap->heap, (DWORD)pArena );
846             if (TRACE_ON(heap))
847                HEAP_Dump( subheap->heap );
848         }  else if (WARN_ON(heap)) {
849             WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
850                  (DWORD)subheap->heap, (DWORD)pArena );
851             if (TRACE_ON(heap))
852                HEAP_Dump( subheap->heap );
853         }
854         return FALSE;
855     }
856     /* Check size flags */
857     if (pArena->size & ARENA_FLAG_FREE)
858     {
859         ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
860                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
861         return FALSE;
862     }
863     /* Check arena size */
864     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
865     {
866         ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
867                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
868         return FALSE;
869     }
870     /* Check next arena PREV_FREE flag */
871     if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
872         (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
873     {
874         ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
875                  (DWORD)subheap->heap, (DWORD)pArena );
876         return FALSE;
877     }
878     /* Check prev free arena */
879     if (pArena->size & ARENA_FLAG_PREV_FREE)
880     {
881         ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
882         /* Check prev pointer */
883         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
884         {
885             ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
886                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
887             return FALSE;
888         }
889         /* Check that prev arena is free */
890         if (!(pPrev->size & ARENA_FLAG_FREE) ||
891             (pPrev->magic != ARENA_FREE_MAGIC))
892         {
893             ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
894                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
895             return FALSE;
896         }
897         /* Check that prev arena is really the previous block */
898         if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
899         {
900             ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
901                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
902             return FALSE;
903         }
904     }
905     return TRUE;
906 }
907
908
909 /***********************************************************************
910  *           HEAP_IsRealArena  [Internal]
911  * Validates a block is a valid arena.
912  *
913  * RETURNS
914  *      TRUE: Success
915  *      FALSE: Failure
916  */
917 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
918               DWORD flags,   /* [in] Bit flags that control access during operation */
919               LPCVOID block, /* [in] Optional pointer to memory block to validate */
920               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
921                               *             does not complain    */
922 {
923     SUBHEAP *subheap;
924     BOOL ret = TRUE;
925
926     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
927     {
928         ERR("Invalid heap %p!\n", heapPtr );
929         return FALSE;
930     }
931
932     flags &= HEAP_NO_SERIALIZE;
933     flags |= heapPtr->flags;
934     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
935     if (!(flags & HEAP_NO_SERIALIZE))
936         RtlEnterCriticalSection( &heapPtr->critSection );
937
938     if (block)
939     {
940         /* Only check this single memory block */
941
942         if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
943             ((char *)block < (char *)subheap + subheap->headerSize
944                               + sizeof(ARENA_INUSE)))
945         {
946             if (quiet == NOISY)
947                 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
948             else if (WARN_ON(heap))
949                 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
950             ret = FALSE;
951         } else
952             ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
953
954         if (!(flags & HEAP_NO_SERIALIZE))
955             RtlLeaveCriticalSection( &heapPtr->critSection );
956         return ret;
957     }
958
959     subheap = &heapPtr->subheap;
960     while (subheap && ret)
961     {
962         char *ptr = (char *)subheap + subheap->headerSize;
963         while (ptr < (char *)subheap + subheap->size)
964         {
965             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
966             {
967                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
968                     ret = FALSE;
969                     break;
970                 }
971                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
972             }
973             else
974             {
975                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
976                     ret = FALSE;
977                     break;
978                 }
979                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
980             }
981         }
982         subheap = subheap->next;
983     }
984
985     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
986     return ret;
987 }
988
989
990 /***********************************************************************
991  *           RtlCreateHeap   (NTDLL.@)
992  *
993  * Create a new Heap.
994  *
995  * PARAMS
996  *  flags      [I] HEAP_ flags from "winnt.h"
997  *  addr       [I] Desired base address
998  *  totalSize  [I] Total size of the heap, or 0 for a growable heap
999  *  commitSize [I] Amount of heap space to commit
1000  *  unknown    [I] Not yet understood
1001  *  definition [I] Heap definition
1002  *
1003  * RETURNS
1004  *  Success: A HANDLE to the newly created heap.
1005  *  Failure: a NULL HANDLE.
1006  */
1007 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1008                              PVOID unknown, PRTL_HEAP_DEFINITION definition )
1009 {
1010     SUBHEAP *subheap;
1011
1012     /* Allocate the heap block */
1013
1014     if (!totalSize)
1015     {
1016         totalSize = HEAP_DEF_SIZE;
1017         flags |= HEAP_GROWABLE;
1018     }
1019
1020     if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1021
1022     /* link it into the per-process heap list */
1023     if (processHeap)
1024     {
1025         HEAP *heapPtr = subheap->heap;
1026         RtlLockHeap( processHeap );
1027         heapPtr->next = firstHeap;
1028         firstHeap = heapPtr;
1029         RtlUnlockHeap( processHeap );
1030     }
1031     else processHeap = subheap->heap;  /* assume the first heap we create is the process main heap */
1032
1033     return (HANDLE)subheap;
1034 }
1035
1036
1037 /***********************************************************************
1038  *           RtlDestroyHeap   (NTDLL.@)
1039  *
1040  * Destroy a Heap created with RtlCreateHeap().
1041  *
1042  * PARAMS
1043  *  heap [I] Heap to destroy.
1044  *
1045  * RETURNS
1046  *  Success: A NULL HANDLE, if heap is NULL or it was destroyed
1047  *  Failure: The Heap handle, if heap is the process heap.
1048  */
1049 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1050 {
1051     HEAP *heapPtr = HEAP_GetPtr( heap );
1052     SUBHEAP *subheap;
1053
1054     TRACE("%p\n", heap );
1055     if (!heapPtr) return heap;
1056
1057     if (heap == processHeap) return heap; /* cannot delete the main process heap */
1058     else /* remove it from the per-process list */
1059     {
1060         HEAP **pptr;
1061         RtlLockHeap( processHeap );
1062         pptr = &firstHeap;
1063         while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1064         if (*pptr) *pptr = (*pptr)->next;
1065         RtlUnlockHeap( processHeap );
1066     }
1067
1068     RtlDeleteCriticalSection( &heapPtr->critSection );
1069     subheap = &heapPtr->subheap;
1070     while (subheap)
1071     {
1072         SUBHEAP *next = subheap->next;
1073         ULONG size = 0;
1074         void *addr = subheap;
1075         NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
1076         subheap = next;
1077     }
1078     return 0;
1079 }
1080
1081
1082 /***********************************************************************
1083  *           RtlAllocateHeap   (NTDLL.@)
1084  *
1085  * Allocate a memory block from a Heap.
1086  *
1087  * PARAMS
1088  *  heap  [I] Heap to allocate block from
1089  *  flags [I] HEAP_ flags from "winnt.h"
1090  *  size  [I] Size of the memory block to allocate
1091  *
1092  * RETURNS
1093  *  Success: A pointer to the newly allocated block
1094  *  Failure: NULL.
1095  *
1096  * NOTES
1097  *  This call does not SetLastError().
1098  */
1099 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1100 {
1101     ARENA_FREE *pArena;
1102     ARENA_INUSE *pInUse;
1103     SUBHEAP *subheap;
1104     HEAP *heapPtr = HEAP_GetPtr( heap );
1105
1106     /* Validate the parameters */
1107
1108     if (!heapPtr) return NULL;
1109     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1110     flags |= heapPtr->flags;
1111     size = ROUND_SIZE(size);
1112     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1113
1114     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1115     /* Locate a suitable free block */
1116
1117     if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1118     {
1119         TRACE("(%p,%08lx,%08lx): returning NULL\n",
1120                   heap, flags, size  );
1121         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1122         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1123         return NULL;
1124     }
1125
1126     /* Remove the arena from the free list */
1127
1128     pArena->next->prev = pArena->prev;
1129     pArena->prev->next = pArena->next;
1130
1131     /* Build the in-use arena */
1132
1133     pInUse = (ARENA_INUSE *)pArena;
1134
1135     /* in-use arena is smaller than free arena,
1136      * so we have to add the difference to the size */
1137     pInUse->size  = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1138     pInUse->magic = ARENA_INUSE_MAGIC;
1139
1140     /* Shrink the block */
1141
1142     HEAP_ShrinkBlock( subheap, pInUse, size );
1143
1144     if (flags & HEAP_ZERO_MEMORY)
1145         clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1146     else
1147         mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1148
1149     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1150
1151     TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1152                   heap, flags, size, (DWORD)(pInUse + 1) );
1153     return (LPVOID)(pInUse + 1);
1154 }
1155
1156
1157 /***********************************************************************
1158  *           RtlFreeHeap   (NTDLL.@)
1159  *
1160  * Free a memory block allocated with RtlAllocateHeap().
1161  *
1162  * PARAMS
1163  *  heap  [I] Heap that block was allocated from
1164  *  flags [I] HEAP_ flags from "winnt.h"
1165  *  ptr   [I] Block to free
1166  *
1167  * RETURNS
1168  *  Success: TRUE, if ptr is NULL or was freed successfully.
1169  *  Failure: FALSE.
1170  */
1171 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1172 {
1173     ARENA_INUSE *pInUse;
1174     SUBHEAP *subheap;
1175     HEAP *heapPtr = HEAP_GetPtr( heap );
1176
1177     /* Validate the parameters */
1178
1179     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1180     if (!heapPtr)
1181     {
1182         set_status( STATUS_INVALID_HANDLE );
1183         return FALSE;
1184     }
1185
1186     flags &= HEAP_NO_SERIALIZE;
1187     flags |= heapPtr->flags;
1188     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1189     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1190     {
1191         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1192         set_status( STATUS_INVALID_PARAMETER );
1193         TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1194                       heap, flags, (DWORD)ptr );
1195         return FALSE;
1196     }
1197
1198     /* Turn the block into a free block */
1199
1200     pInUse  = (ARENA_INUSE *)ptr - 1;
1201     subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1202     HEAP_MakeInUseBlockFree( subheap, pInUse );
1203
1204     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1205
1206     TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1207                   heap, flags, (DWORD)ptr );
1208     return TRUE;
1209 }
1210
1211
1212 /***********************************************************************
1213  *           RtlReAllocateHeap   (NTDLL.@)
1214  *
1215  * Change the size of a memory block allocated with RtlAllocateHeap().
1216  *
1217  * PARAMS
1218  *  heap  [I] Heap that block was allocated from
1219  *  flags [I] HEAP_ flags from "winnt.h"
1220  *  ptr   [I] Block to resize
1221  *  size  [I] Size of the memory block to allocate
1222  *
1223  * RETURNS
1224  *  Success: A pointer to the resized block (which may be different).
1225  *  Failure: NULL.
1226  */
1227 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1228 {
1229     ARENA_INUSE *pArena;
1230     DWORD oldSize;
1231     HEAP *heapPtr;
1232     SUBHEAP *subheap;
1233
1234     if (!ptr) return NULL;
1235     if (!(heapPtr = HEAP_GetPtr( heap )))
1236     {
1237         set_status( STATUS_INVALID_HANDLE );
1238         return NULL;
1239     }
1240
1241     /* Validate the parameters */
1242
1243     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1244              HEAP_REALLOC_IN_PLACE_ONLY;
1245     flags |= heapPtr->flags;
1246     size = ROUND_SIZE(size);
1247     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1248
1249     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1250     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1251     {
1252         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1253         set_status( STATUS_INVALID_PARAMETER );
1254         TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1255                       heap, flags, (DWORD)ptr, size );
1256         return NULL;
1257     }
1258
1259     /* Check if we need to grow the block */
1260
1261     pArena = (ARENA_INUSE *)ptr - 1;
1262     subheap = HEAP_FindSubHeap( heapPtr, pArena );
1263     oldSize = (pArena->size & ARENA_SIZE_MASK);
1264     if (size > oldSize)
1265     {
1266         char *pNext = (char *)(pArena + 1) + oldSize;
1267         if ((pNext < (char *)subheap + subheap->size) &&
1268             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1269             (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1270         {
1271             /* The next block is free and large enough */
1272             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1273             pFree->next->prev = pFree->prev;
1274             pFree->prev->next = pFree->next;
1275             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1276             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1277                                                + size + HEAP_MIN_BLOCK_SIZE))
1278             {
1279                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1280                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1281                 set_status( STATUS_NO_MEMORY );
1282                 return NULL;
1283             }
1284             HEAP_ShrinkBlock( subheap, pArena, size );
1285         }
1286         else  /* Do it the hard way */
1287         {
1288             ARENA_FREE *pNew;
1289             ARENA_INUSE *pInUse;
1290             SUBHEAP *newsubheap;
1291
1292             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1293                 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1294             {
1295                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1296                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1297                 set_status( STATUS_NO_MEMORY );
1298                 return NULL;
1299             }
1300
1301             /* Build the in-use arena */
1302
1303             pNew->next->prev = pNew->prev;
1304             pNew->prev->next = pNew->next;
1305             pInUse = (ARENA_INUSE *)pNew;
1306             pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1307                            + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1308             pInUse->magic = ARENA_INUSE_MAGIC;
1309             HEAP_ShrinkBlock( newsubheap, pInUse, size );
1310             mark_block_initialized( pInUse + 1, oldSize );
1311             memcpy( pInUse + 1, pArena + 1, oldSize );
1312
1313             /* Free the previous block */
1314
1315             HEAP_MakeInUseBlockFree( subheap, pArena );
1316             subheap = newsubheap;
1317             pArena  = pInUse;
1318         }
1319     }
1320     else HEAP_ShrinkBlock( subheap, pArena, size );  /* Shrink the block */
1321
1322     /* Clear the extra bytes if needed */
1323
1324     if (size > oldSize)
1325     {
1326         if (flags & HEAP_ZERO_MEMORY)
1327             clear_block( (char *)(pArena + 1) + oldSize,
1328                          (pArena->size & ARENA_SIZE_MASK) - oldSize );
1329         else
1330             mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1331                                       (pArena->size & ARENA_SIZE_MASK) - oldSize );
1332     }
1333
1334     /* Return the new arena */
1335
1336     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1337
1338     TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1339                   heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1340     return (LPVOID)(pArena + 1);
1341 }
1342
1343
1344 /***********************************************************************
1345  *           RtlCompactHeap   (NTDLL.@)
1346  *
1347  * Compact the free space in a Heap.
1348  *
1349  * PARAMS
1350  *  heap  [I] Heap that block was allocated from
1351  *  flags [I] HEAP_ flags from "winnt.h"
1352  *
1353  * RETURNS
1354  *  The number of bytes compacted.
1355  *
1356  * NOTES
1357  *  This function is a harmless stub.
1358  */
1359 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1360 {
1361     FIXME( "stub\n" );
1362     return 0;
1363 }
1364
1365
1366 /***********************************************************************
1367  *           RtlLockHeap   (NTDLL.@)
1368  *
1369  * Lock a Heap.
1370  *
1371  * PARAMS
1372  *  heap  [I] Heap to lock
1373  *
1374  * RETURNS
1375  *  Success: TRUE. The Heap is locked.
1376  *  Failure: FALSE, if heap is invalid.
1377  */
1378 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1379 {
1380     HEAP *heapPtr = HEAP_GetPtr( heap );
1381     if (!heapPtr) return FALSE;
1382     RtlEnterCriticalSection( &heapPtr->critSection );
1383     return TRUE;
1384 }
1385
1386
1387 /***********************************************************************
1388  *           RtlUnlockHeap   (NTDLL.@)
1389  *
1390  * Unlock a Heap.
1391  *
1392  * PARAMS
1393  *  heap  [I] Heap to unlock
1394  *
1395  * RETURNS
1396  *  Success: TRUE. The Heap is unlocked.
1397  *  Failure: FALSE, if heap is invalid.
1398  */
1399 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1400 {
1401     HEAP *heapPtr = HEAP_GetPtr( heap );
1402     if (!heapPtr) return FALSE;
1403     RtlLeaveCriticalSection( &heapPtr->critSection );
1404     return TRUE;
1405 }
1406
1407
1408 /***********************************************************************
1409  *           RtlSizeHeap   (NTDLL.@)
1410  *
1411  * Get the actual size of a memory block allocated from a Heap.
1412  *
1413  * PARAMS
1414  *  heap  [I] Heap that block was allocated from
1415  *  flags [I] HEAP_ flags from "winnt.h"
1416  *  ptr   [I] Block to get the size of
1417  *
1418  * RETURNS
1419  *  Success: The size of the block.
1420  *  Failure: -1, heap or ptr are invalid.
1421  *
1422  * NOTES
1423  *  The size may be bigger than what was passed to RtlAllocateHeap().
1424  */
1425 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1426 {
1427     DWORD ret;
1428     HEAP *heapPtr = HEAP_GetPtr( heap );
1429
1430     if (!heapPtr)
1431     {
1432         set_status( STATUS_INVALID_HANDLE );
1433         return (ULONG)-1;
1434     }
1435     flags &= HEAP_NO_SERIALIZE;
1436     flags |= heapPtr->flags;
1437     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1438     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1439     {
1440         set_status( STATUS_INVALID_PARAMETER );
1441         ret = (ULONG)-1;
1442     }
1443     else
1444     {
1445         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1446         ret = pArena->size & ARENA_SIZE_MASK;
1447     }
1448     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1449
1450     TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1451                   heap, flags, (DWORD)ptr, ret );
1452     return ret;
1453 }
1454
1455
1456 /***********************************************************************
1457  *           RtlValidateHeap   (NTDLL.@)
1458  *
1459  * Determine if a block is a valid alloction from a heap.
1460  *
1461  * PARAMS
1462  *  heap  [I] Heap that block was allocated from
1463  *  flags [I] HEAP_ flags from "winnt.h"
1464  *  ptr   [I] Block to check
1465  *
1466  * RETURNS
1467  *  Success: TRUE. The block was allocated from heap.
1468  *  Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1469  */
1470 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1471 {
1472     HEAP *heapPtr = HEAP_GetPtr( heap );
1473     if (!heapPtr) return FALSE;
1474     return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1475 }
1476
1477
1478 /***********************************************************************
1479  *           RtlWalkHeap    (NTDLL.@)
1480  *
1481  * FIXME
1482  *  The PROCESS_HEAP_ENTRY flag values seem different between this
1483  *  function and HeapWalk(). To be checked.
1484  */
1485 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1486 {
1487     LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1488     HEAP *heapPtr = HEAP_GetPtr(heap);
1489     SUBHEAP *sub, *currentheap = NULL;
1490     NTSTATUS ret;
1491     char *ptr;
1492     int region_index = 0;
1493
1494     FIXME( "not fully compatible\n" );
1495
1496     if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1497
1498     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1499
1500     /* set ptr to the next arena to be examined */
1501
1502     if (!entry->lpData) /* first call (init) ? */
1503     {
1504         TRACE("begin walking of heap %p.\n", heap);
1505         currentheap = &heapPtr->subheap;
1506         ptr = (char*)currentheap + currentheap->headerSize;
1507     }
1508     else
1509     {
1510         ptr = entry->lpData;
1511         sub = &heapPtr->subheap;
1512         while (sub)
1513         {
1514             if (((char *)ptr >= (char *)sub) &&
1515                 ((char *)ptr < (char *)sub + sub->size))
1516             {
1517                 currentheap = sub;
1518                 break;
1519             }
1520             sub = sub->next;
1521             region_index++;
1522         }
1523         if (currentheap == NULL)
1524         {
1525             ERR("no matching subheap found, shouldn't happen !\n");
1526             ret = STATUS_NO_MORE_ENTRIES;
1527             goto HW_end;
1528         }
1529
1530         ptr += entry->cbData; /* point to next arena */
1531         if (ptr > (char *)currentheap + currentheap->size - 1)
1532         {   /* proceed with next subheap */
1533             if (!(currentheap = currentheap->next))
1534             {  /* successfully finished */
1535                 TRACE("end reached.\n");
1536                 ret = STATUS_NO_MORE_ENTRIES;
1537                 goto HW_end;
1538             }
1539             ptr = (char*)currentheap + currentheap->headerSize;
1540         }
1541     }
1542
1543     entry->wFlags = 0;
1544     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1545     {
1546         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1547
1548         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1549
1550         entry->lpData = pArena + 1;
1551         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1552         entry->cbOverhead = sizeof(ARENA_FREE);
1553         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1554     }
1555     else
1556     {
1557         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1558
1559         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1560
1561         entry->lpData = pArena + 1;
1562         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1563         entry->cbOverhead = sizeof(ARENA_INUSE);
1564         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1565         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1566         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1567     }
1568
1569     entry->iRegionIndex = region_index;
1570
1571     /* first element of heap ? */
1572     if (ptr == (char *)(currentheap + currentheap->headerSize))
1573     {
1574         entry->wFlags |= PROCESS_HEAP_REGION;
1575         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1576         entry->u.Region.dwUnCommittedSize =
1577                 currentheap->size - currentheap->commitSize;
1578         entry->u.Region.lpFirstBlock = /* first valid block */
1579                 currentheap + currentheap->headerSize;
1580         entry->u.Region.lpLastBlock  = /* first invalid block */
1581                 currentheap + currentheap->size;
1582     }
1583     ret = STATUS_SUCCESS;
1584
1585 HW_end:
1586     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1587     return ret;
1588 }
1589
1590
1591 /***********************************************************************
1592  *           RtlGetProcessHeaps    (NTDLL.@)
1593  *
1594  * Get the Heaps belonging to the current process.
1595  *
1596  * PARAMS
1597  *  count [I] size of heaps
1598  *  heaps [O] Destination array for heap HANDLE's
1599  *
1600  * RETURNS
1601  *  Success: The number of Heaps allocated by the process.
1602  *  Failure: 0.
1603  */
1604 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1605 {
1606     DWORD total;
1607     HEAP *ptr;
1608
1609     if (!processHeap) return 0;  /* should never happen */
1610     total = 1;  /* main heap */
1611     RtlLockHeap( processHeap );
1612     for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1613     if (total <= count)
1614     {
1615         *heaps++ = (HANDLE)processHeap;
1616         for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1617     }
1618     RtlUnlockHeap( processHeap );
1619     return total;
1620 }