server: A thread's affinity is restricted to the process affinity.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 #include <valgrind/memcheck.h>
32 #endif
33
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "windef.h"
39 #include "winnt.h"
40 #include "winternl.h"
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46
47 /* Note: the heap data structures are loosely based on what Pietrek describes in his
48  * book 'Windows 95 System Programming Secrets', with some adaptations for
49  * better compatibility with NT.
50  */
51
52 typedef struct tagARENA_INUSE
53 {
54     DWORD  size;                    /* Block size; must be the first field */
55     DWORD  magic : 24;              /* Magic number */
56     DWORD  unused_bytes : 8;        /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
57 } ARENA_INUSE;
58
59 typedef struct tagARENA_FREE
60 {
61     DWORD                 size;     /* Block size; must be the first field */
62     DWORD                 magic;    /* Magic number */
63     struct list           entry;    /* Entry in free list */
64 } ARENA_FREE;
65
66 typedef struct
67 {
68     struct list           entry;      /* entry in heap large blocks list */
69     SIZE_T                data_size;  /* size of user data */
70     SIZE_T                block_size; /* total size of virtual memory block */
71     DWORD                 pad[2];     /* padding to ensure 16-byte alignment of data */
72     DWORD                 size;       /* fields for compatibility with normal arenas */
73     DWORD                 magic;      /* these must remain at the end of the structure */
74 } ARENA_LARGE;
75
76 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
77 #define ARENA_FLAG_PREV_FREE   0x00000002
78 #define ARENA_SIZE_MASK        (~3)
79 #define ARENA_LARGE_SIZE       0xfedcba90  /* magic value for 'size' field in large blocks */
80
81 /* Value for arena 'magic' field */
82 #define ARENA_INUSE_MAGIC      0x455355
83 #define ARENA_FREE_MAGIC       0x45455246
84 #define ARENA_LARGE_MAGIC      0x6752614c
85
86 #define ARENA_INUSE_FILLER     0x55
87 #define ARENA_FREE_FILLER      0xaa
88
89 /* everything is aligned on 8 byte boundaries (16 for Win64) */
90 #define ALIGNMENT              (2*sizeof(void*))
91 #define LARGE_ALIGNMENT        16  /* large blocks have stricter alignment */
92 #define ARENA_OFFSET           (ALIGNMENT - sizeof(ARENA_INUSE))
93
94 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
95
96 #define ROUND_SIZE(size)       ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
97
98 #define QUIET                  1           /* Suppress messages  */
99 #define NOISY                  0           /* Report all errors  */
100
101 /* minimum data size (without arenas) of an allocated block */
102 /* make sure that it's larger than a free list entry */
103 #define HEAP_MIN_DATA_SIZE    ROUND_SIZE(2 * sizeof(struct list))
104 /* minimum size that must remain to shrink an allocated block */
105 #define HEAP_MIN_SHRINK_SIZE  (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
106 /* minimum size to start allocating large blocks */
107 #define HEAP_MIN_LARGE_BLOCK_SIZE  0x7f000
108
109 /* Max size of the blocks on the free lists */
110 static const SIZE_T HEAP_freeListSizes[] =
111 {
112     0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
113 };
114 #define HEAP_NB_FREE_LISTS  (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
115
116 typedef union
117 {
118     ARENA_FREE  arena;
119     void       *alignment[4];
120 } FREE_LIST_ENTRY;
121
122 struct tagHEAP;
123
124 typedef struct tagSUBHEAP
125 {
126     void               *base;       /* Base address of the sub-heap memory block */
127     SIZE_T              size;       /* Size of the whole sub-heap */
128     SIZE_T              min_commit; /* Minimum committed size */
129     SIZE_T              commitSize; /* Committed size of the sub-heap */
130     struct list         entry;      /* Entry in sub-heap list */
131     struct tagHEAP     *heap;       /* Main heap structure */
132     DWORD               headerSize; /* Size of the heap header */
133     DWORD               magic;      /* Magic number */
134 } SUBHEAP;
135
136 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
137
138 typedef struct tagHEAP
139 {
140     DWORD            unknown[3];
141     DWORD            flags;         /* Heap flags */
142     DWORD            force_flags;   /* Forced heap flags for debugging */
143     SUBHEAP          subheap;       /* First sub-heap */
144     struct list      entry;         /* Entry in process heap list */
145     struct list      subheap_list;  /* Sub-heap list */
146     struct list      large_list;    /* Large blocks list */
147     SIZE_T           grow_size;     /* Size of next subheap for growing heap */
148     DWORD            magic;         /* Magic number */
149     RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
150     FREE_LIST_ENTRY *freeList;      /* Free lists */
151 } HEAP;
152
153 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
154
155 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
156 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
157
158 static HEAP *processHeap;  /* main process heap */
159
160 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
161
162 /* mark a block of memory as free for debugging purposes */
163 static inline void mark_block_free( void *ptr, SIZE_T size )
164 {
165     if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
166 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
167     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
168 #elif defined( VALGRIND_MAKE_NOACCESS)
169     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
170 #endif
171 }
172
173 /* mark a block of memory as initialized for debugging purposes */
174 static inline void mark_block_initialized( void *ptr, SIZE_T size )
175 {
176 #if defined(VALGRIND_MAKE_MEM_DEFINED)
177     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
178 #elif defined(VALGRIND_MAKE_READABLE)
179     VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
180 #endif
181 }
182
183 /* mark a block of memory as uninitialized for debugging purposes */
184 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
185 {
186 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
187     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
188 #elif defined(VALGRIND_MAKE_WRITABLE)
189     VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
190 #endif
191     if (TRACE_ON(heap) || WARN_ON(heap))
192     {
193         memset( ptr, ARENA_INUSE_FILLER, size );
194 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
195         VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
196 #elif defined(VALGRIND_MAKE_WRITABLE)
197         /* make it uninitialized to valgrind again */
198         VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
199 #endif
200     }
201 }
202
203 /* clear contents of a block of memory */
204 static inline void clear_block( void *ptr, SIZE_T size )
205 {
206     mark_block_initialized( ptr, size );
207     memset( ptr, 0, size );
208 }
209
210 /* notify that a new block of memory has been allocated for debugging purposes */
211 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
212 {
213 #ifdef VALGRIND_MALLOCLIKE_BLOCK
214     VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
215 #endif
216 }
217
218 /* notify that a block of memory has been freed for debugging purposes */
219 static inline void notify_free( void const *ptr )
220 {
221 #ifdef VALGRIND_FREELIKE_BLOCK
222     VALGRIND_FREELIKE_BLOCK( ptr, 0 );
223 #endif
224 }
225
226 static void subheap_notify_free_all(SUBHEAP const *subheap)
227 {
228 #ifdef VALGRIND_FREELIKE_BLOCK
229     char const *ptr = (char const *)subheap->base + subheap->headerSize;
230
231     if (!RUNNING_ON_VALGRIND) return;
232
233     while (ptr < (char const *)subheap->base + subheap->size)
234     {
235         if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
236         {
237             ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
238             if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
239             ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
240         }
241         else
242         {
243             ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
244             if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
245             notify_free(pArena + 1);
246             ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
247         }
248     }
249 #endif
250 }
251
252 /* locate a free list entry of the appropriate size */
253 /* size is the size of the whole block including the arena header */
254 static inline unsigned int get_freelist_index( SIZE_T size )
255 {
256     unsigned int i;
257
258     size -= sizeof(ARENA_FREE);
259     for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
260     return i;
261 }
262
263 /* get the memory protection type to use for a given heap */
264 static inline ULONG get_protection_type( DWORD flags )
265 {
266     return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
267 }
268
269 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
270 {
271     0, 0, NULL,  /* will be set later */
272     { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
273       0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
274 };
275
276
277 /***********************************************************************
278  *           HEAP_Dump
279  */
280 static void HEAP_Dump( HEAP *heap )
281 {
282     unsigned int i;
283     SUBHEAP *subheap;
284     char *ptr;
285
286     DPRINTF( "Heap: %p\n", heap );
287     DPRINTF( "Next: %p  Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
288     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
289
290     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
291     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
292         DPRINTF( "%p free %08lx prev=%p next=%p\n",
293                  &heap->freeList[i].arena, HEAP_freeListSizes[i],
294                  LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
295                  LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
296
297     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
298     {
299         SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
300         DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
301                  subheap, subheap->base, subheap->size, subheap->commitSize );
302
303         DPRINTF( "\n Block    Arena   Stat   Size    Id\n" );
304         ptr = (char *)subheap->base + subheap->headerSize;
305         while (ptr < (char *)subheap->base + subheap->size)
306         {
307             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
308             {
309                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
310                 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
311                          pArena, pArena->magic,
312                          pArena->size & ARENA_SIZE_MASK,
313                          LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
314                          LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
315                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
316                 arenaSize += sizeof(ARENA_FREE);
317                 freeSize += pArena->size & ARENA_SIZE_MASK;
318             }
319             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
320             {
321                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
322                 DPRINTF( "%p %08x Used %08x back=%p\n",
323                         pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
324                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
325                 arenaSize += sizeof(ARENA_INUSE);
326                 usedSize += pArena->size & ARENA_SIZE_MASK;
327             }
328             else
329             {
330                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
331                 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
332                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
333                 arenaSize += sizeof(ARENA_INUSE);
334                 usedSize += pArena->size & ARENA_SIZE_MASK;
335             }
336         }
337         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
338               subheap->size, subheap->commitSize, freeSize, usedSize,
339               arenaSize, (arenaSize * 100) / subheap->size );
340     }
341 }
342
343
344 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
345 {
346     WORD rem_flags;
347     TRACE( "Dumping entry %p\n", entry );
348     TRACE( "lpData\t\t: %p\n", entry->lpData );
349     TRACE( "cbData\t\t: %08x\n", entry->cbData);
350     TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
351     TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
352     TRACE( "WFlags\t\t: ");
353     if (entry->wFlags & PROCESS_HEAP_REGION)
354         TRACE( "PROCESS_HEAP_REGION ");
355     if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
356         TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
357     if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
358         TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
359     if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
360         TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
361     if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
362         TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
363     rem_flags = entry->wFlags &
364         ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
365           PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
366           PROCESS_HEAP_ENTRY_DDESHARE);
367     if (rem_flags)
368         TRACE( "Unknown %08x", rem_flags);
369     TRACE( "\n");
370     if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
371         && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
372     {
373         /* Treat as block */
374         TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
375     }
376     if (entry->wFlags & PROCESS_HEAP_REGION)
377     {
378         TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
379         TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
380         TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
381         TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
382     }
383 }
384
385 /***********************************************************************
386  *           HEAP_GetPtr
387  * RETURNS
388  *      Pointer to the heap
389  *      NULL: Failure
390  */
391 static HEAP *HEAP_GetPtr(
392              HANDLE heap /* [in] Handle to the heap */
393 ) {
394     HEAP *heapPtr = heap;
395     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
396     {
397         ERR("Invalid heap %p!\n", heap );
398         return NULL;
399     }
400     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
401     {
402         HEAP_Dump( heapPtr );
403         assert( FALSE );
404         return NULL;
405     }
406     return heapPtr;
407 }
408
409
410 /***********************************************************************
411  *           HEAP_InsertFreeBlock
412  *
413  * Insert a free block into the free list.
414  */
415 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
416 {
417     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
418     if (last)
419     {
420         /* insert at end of free list, i.e. before the next free list entry */
421         pEntry++;
422         if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
423         list_add_before( &pEntry->arena.entry, &pArena->entry );
424     }
425     else
426     {
427         /* insert at head of free list */
428         list_add_after( &pEntry->arena.entry, &pArena->entry );
429     }
430     pArena->size |= ARENA_FLAG_FREE;
431 }
432
433
434 /***********************************************************************
435  *           HEAP_FindSubHeap
436  * Find the sub-heap containing a given address.
437  *
438  * RETURNS
439  *      Pointer: Success
440  *      NULL: Failure
441  */
442 static SUBHEAP *HEAP_FindSubHeap(
443                 const HEAP *heap, /* [in] Heap pointer */
444                 LPCVOID ptr ) /* [in] Address */
445 {
446     SUBHEAP *sub;
447     LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
448         if ((ptr >= sub->base) &&
449             ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
450             return sub;
451     return NULL;
452 }
453
454
455 /***********************************************************************
456  *           HEAP_Commit
457  *
458  * Make sure the heap storage is committed for a given size in the specified arena.
459  */
460 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
461 {
462     void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
463     SIZE_T size = (char *)ptr - (char *)subheap->base;
464     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
465     if (size > subheap->size) size = subheap->size;
466     if (size <= subheap->commitSize) return TRUE;
467     size -= subheap->commitSize;
468     ptr = (char *)subheap->base + subheap->commitSize;
469     if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
470                                  &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
471     {
472         WARN("Could not commit %08lx bytes at %p for heap %p\n",
473                  size, ptr, subheap->heap );
474         return FALSE;
475     }
476     subheap->commitSize += size;
477     return TRUE;
478 }
479
480
481 /***********************************************************************
482  *           HEAP_Decommit
483  *
484  * If possible, decommit the heap storage from (including) 'ptr'.
485  */
486 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
487 {
488     void *addr;
489     SIZE_T decommit_size;
490     SIZE_T size = (char *)ptr - (char *)subheap->base;
491
492     /* round to next block and add one full block */
493     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
494     size = max( size, subheap->min_commit );
495     if (size >= subheap->commitSize) return TRUE;
496     decommit_size = subheap->commitSize - size;
497     addr = (char *)subheap->base + size;
498
499     if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
500     {
501         WARN("Could not decommit %08lx bytes at %p for heap %p\n",
502              decommit_size, (char *)subheap->base + size, subheap->heap );
503         return FALSE;
504     }
505     subheap->commitSize -= decommit_size;
506     return TRUE;
507 }
508
509
510 /***********************************************************************
511  *           HEAP_CreateFreeBlock
512  *
513  * Create a free block at a specified address. 'size' is the size of the
514  * whole block, including the new arena.
515  */
516 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
517 {
518     ARENA_FREE *pFree;
519     char *pEnd;
520     BOOL last;
521
522     /* Create a free arena */
523     mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
524     pFree = ptr;
525     pFree->magic = ARENA_FREE_MAGIC;
526
527     /* If debugging, erase the freed block content */
528
529     pEnd = (char *)ptr + size;
530     if (pEnd > (char *)subheap->base + subheap->commitSize)
531         pEnd = (char *)subheap->base + subheap->commitSize;
532     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
533
534     /* Check if next block is free also */
535
536     if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
537         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
538     {
539         /* Remove the next arena from the free list */
540         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
541         list_remove( &pNext->entry );
542         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
543         mark_block_free( pNext, sizeof(ARENA_FREE) );
544     }
545
546     /* Set the next block PREV_FREE flag and pointer */
547
548     last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
549     if (!last)
550     {
551         DWORD *pNext = (DWORD *)((char *)ptr + size);
552         *pNext |= ARENA_FLAG_PREV_FREE;
553         mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
554         *((ARENA_FREE **)pNext - 1) = pFree;
555     }
556
557     /* Last, insert the new block into the free list */
558
559     pFree->size = size - sizeof(*pFree);
560     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
561 }
562
563
564 /***********************************************************************
565  *           HEAP_MakeInUseBlockFree
566  *
567  * Turn an in-use block into a free block. Can also decommit the end of
568  * the heap, and possibly even free the sub-heap altogether.
569  */
570 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
571 {
572     ARENA_FREE *pFree;
573     SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
574
575     /* Check if we can merge with previous block */
576
577     if (pArena->size & ARENA_FLAG_PREV_FREE)
578     {
579         pFree = *((ARENA_FREE **)pArena - 1);
580         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
581         /* Remove it from the free list */
582         list_remove( &pFree->entry );
583     }
584     else pFree = (ARENA_FREE *)pArena;
585
586     /* Create a free block */
587
588     HEAP_CreateFreeBlock( subheap, pFree, size );
589     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
590     if ((char *)pFree + size < (char *)subheap->base + subheap->size)
591         return;  /* Not the last block, so nothing more to do */
592
593     /* Free the whole sub-heap if it's empty and not the original one */
594
595     if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
596         (subheap != &subheap->heap->subheap))
597     {
598         SIZE_T size = 0;
599         void *addr = subheap->base;
600         /* Remove the free block from the list */
601         list_remove( &pFree->entry );
602         /* Remove the subheap from the list */
603         list_remove( &subheap->entry );
604         /* Free the memory */
605         subheap->magic = 0;
606         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
607         return;
608     }
609
610     /* Decommit the end of the heap */
611
612     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
613 }
614
615
616 /***********************************************************************
617  *           HEAP_ShrinkBlock
618  *
619  * Shrink an in-use block.
620  */
621 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
622 {
623     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
624     {
625         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
626                               (pArena->size & ARENA_SIZE_MASK) - size );
627         /* assign size plus previous arena flags */
628         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
629     }
630     else
631     {
632         /* Turn off PREV_FREE flag in next block */
633         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
634         if (pNext < (char *)subheap->base + subheap->size)
635             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
636     }
637 }
638
639
640 /***********************************************************************
641  *           allocate_large_block
642  */
643 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
644 {
645     ARENA_LARGE *arena;
646     SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
647     LPVOID address = NULL;
648
649     if (block_size < size) return NULL;  /* overflow */
650     if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
651                                  &block_size, MEM_COMMIT, get_protection_type( flags ) ))
652     {
653         WARN("Could not allocate block for %08lx bytes\n", size );
654         return NULL;
655     }
656     arena = address;
657     arena->data_size = size;
658     arena->block_size = block_size;
659     arena->size = ARENA_LARGE_SIZE;
660     arena->magic = ARENA_LARGE_MAGIC;
661     list_add_tail( &heap->large_list, &arena->entry );
662     return arena + 1;
663 }
664
665
666 /***********************************************************************
667  *           free_large_block
668  */
669 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
670 {
671     ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
672     LPVOID address = arena;
673     SIZE_T size = 0;
674
675     list_remove( &arena->entry );
676     NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
677 }
678
679
680 /***********************************************************************
681  *           realloc_large_block
682  */
683 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
684 {
685     ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
686     void *new_ptr;
687
688     if (arena->block_size - sizeof(*arena) >= size)
689     {
690         /* FIXME: we could remap zero-pages instead */
691         if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
692             memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
693         arena->data_size = size;
694         return ptr;
695     }
696     if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
697     if (!(new_ptr = allocate_large_block( heap, flags, size )))
698     {
699         WARN("Could not allocate block for %08lx bytes\n", size );
700         return NULL;
701     }
702     memcpy( new_ptr, ptr, arena->data_size );
703     free_large_block( heap, flags, ptr );
704     return new_ptr;
705 }
706
707
708 /***********************************************************************
709  *           find_large_block
710  */
711 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
712 {
713     ARENA_LARGE *arena;
714
715     LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
716         if (ptr == arena + 1) return arena;
717
718     return NULL;
719 }
720
721
722 /***********************************************************************
723  *           validate_large_arena
724  */
725 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
726 {
727     if ((ULONG_PTR)arena % getpagesize())
728     {
729         if (quiet == NOISY)
730         {
731             ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
732             if (TRACE_ON(heap)) HEAP_Dump( heap );
733         }
734         else if (WARN_ON(heap))
735         {
736             WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
737             if (TRACE_ON(heap)) HEAP_Dump( heap );
738         }
739         return FALSE;
740     }
741     if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
742     {
743         if (quiet == NOISY)
744         {
745             ERR( "Heap %p: invalid large arena %p values %x/%x\n",
746                  heap, arena, arena->size, arena->magic );
747             if (TRACE_ON(heap)) HEAP_Dump( heap );
748         }
749         else if (WARN_ON(heap))
750         {
751             WARN( "Heap %p: invalid large arena %p values %x/%x\n",
752                   heap, arena, arena->size, arena->magic );
753             if (TRACE_ON(heap)) HEAP_Dump( heap );
754         }
755         return FALSE;
756     }
757     return TRUE;
758 }
759
760
761 /***********************************************************************
762  *           HEAP_CreateSubHeap
763  */
764 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
765                                     SIZE_T commitSize, SIZE_T totalSize )
766 {
767     SUBHEAP *subheap;
768     FREE_LIST_ENTRY *pEntry;
769     unsigned int i;
770
771     if (!address)
772     {
773         /* round-up sizes on a 64K boundary */
774         totalSize  = (totalSize + 0xffff) & 0xffff0000;
775         commitSize = (commitSize + 0xffff) & 0xffff0000;
776         if (!commitSize) commitSize = 0x10000;
777         totalSize = min( totalSize, 0xffff0000 );  /* don't allow a heap larger than 4Gb */
778         if (totalSize < commitSize) totalSize = commitSize;
779         if (flags & HEAP_SHARED) commitSize = totalSize;  /* always commit everything in a shared heap */
780
781         /* allocate the memory block */
782         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
783                                      MEM_RESERVE, get_protection_type( flags ) ))
784         {
785             WARN("Could not allocate %08lx bytes\n", totalSize );
786             return NULL;
787         }
788         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
789                                      &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
790         {
791             WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
792             return NULL;
793         }
794     }
795
796     if (heap)
797     {
798         /* If this is a secondary subheap, insert it into list */
799
800         subheap = address;
801         subheap->base       = address;
802         subheap->heap       = heap;
803         subheap->size       = totalSize;
804         subheap->min_commit = 0x10000;
805         subheap->commitSize = commitSize;
806         subheap->magic      = SUBHEAP_MAGIC;
807         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
808         list_add_head( &heap->subheap_list, &subheap->entry );
809     }
810     else
811     {
812         /* If this is a primary subheap, initialize main heap */
813
814         heap = address;
815         heap->flags         = flags;
816         heap->magic         = HEAP_MAGIC;
817         heap->grow_size     = max( HEAP_DEF_SIZE, totalSize );
818         list_init( &heap->subheap_list );
819         list_init( &heap->large_list );
820
821         subheap = &heap->subheap;
822         subheap->base       = address;
823         subheap->heap       = heap;
824         subheap->size       = totalSize;
825         subheap->min_commit = commitSize;
826         subheap->commitSize = commitSize;
827         subheap->magic      = SUBHEAP_MAGIC;
828         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
829         list_add_head( &heap->subheap_list, &subheap->entry );
830
831         /* Build the free lists */
832
833         heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
834         subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
835         list_init( &heap->freeList[0].arena.entry );
836         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
837         {
838             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
839             pEntry->arena.magic = ARENA_FREE_MAGIC;
840             if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
841         }
842
843         /* Initialize critical section */
844
845         if (!processHeap)  /* do it by hand to avoid memory allocations */
846         {
847             heap->critSection.DebugInfo      = &process_heap_critsect_debug;
848             heap->critSection.LockCount      = -1;
849             heap->critSection.RecursionCount = 0;
850             heap->critSection.OwningThread   = 0;
851             heap->critSection.LockSemaphore  = 0;
852             heap->critSection.SpinCount      = 0;
853             process_heap_critsect_debug.CriticalSection = &heap->critSection;
854         }
855         else
856         {
857             RtlInitializeCriticalSection( &heap->critSection );
858             heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
859         }
860
861         if (flags & HEAP_SHARED)
862         {
863             /* let's assume that only one thread at a time will try to do this */
864             HANDLE sem = heap->critSection.LockSemaphore;
865             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
866
867             NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
868                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
869             heap->critSection.LockSemaphore = sem;
870             RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
871             heap->critSection.DebugInfo = NULL;
872         }
873     }
874
875     /* Create the first free block */
876
877     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
878                           subheap->size - subheap->headerSize );
879
880     return subheap;
881 }
882
883
884 /***********************************************************************
885  *           HEAP_FindFreeBlock
886  *
887  * Find a free block at least as large as the requested size, and make sure
888  * the requested size is committed.
889  */
890 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
891                                        SUBHEAP **ppSubHeap )
892 {
893     SUBHEAP *subheap;
894     struct list *ptr;
895     SIZE_T total_size;
896     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
897
898     /* Find a suitable free list, and in it find a block large enough */
899
900     ptr = &pEntry->arena.entry;
901     while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
902     {
903         ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
904         SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
905                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
906         if (arena_size >= size)
907         {
908             subheap = HEAP_FindSubHeap( heap, pArena );
909             if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
910             *ppSubHeap = subheap;
911             return pArena;
912         }
913     }
914
915     /* If no block was found, attempt to grow the heap */
916
917     if (!(heap->flags & HEAP_GROWABLE))
918     {
919         WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
920         return NULL;
921     }
922     /* make sure that we have a big enough size *committed* to fit another
923      * last free arena in !
924      * So just one heap struct, one first free arena which will eventually
925      * get used, and a second free arena that might get assigned all remaining
926      * free space in HEAP_ShrinkBlock() */
927     total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
928     if (total_size < size) return NULL;  /* overflow */
929
930     if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
931                                        max( heap->grow_size, total_size ) )))
932     {
933         if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
934     }
935     else while (!subheap)  /* shrink the grow size again if we are running out of space */
936     {
937         if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
938         heap->grow_size /= 2;
939         subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
940                                       max( heap->grow_size, total_size ) );
941     }
942
943     TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
944           subheap, subheap->size, heap );
945
946     *ppSubHeap = subheap;
947     return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
948 }
949
950
951 /***********************************************************************
952  *           HEAP_IsValidArenaPtr
953  *
954  * Check that the pointer is inside the range possible for arenas.
955  */
956 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
957 {
958     unsigned int i;
959     const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
960     if (!subheap) return FALSE;
961     if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
962     if (subheap != &heap->subheap) return FALSE;
963     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
964         if (ptr == &heap->freeList[i].arena) return TRUE;
965     return FALSE;
966 }
967
968
969 /***********************************************************************
970  *           HEAP_ValidateFreeArena
971  */
972 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
973 {
974     ARENA_FREE *prev, *next;
975     char *heapEnd = (char *)subheap->base + subheap->size;
976
977     /* Check for unaligned pointers */
978     if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
979     {
980         ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
981         return FALSE;
982     }
983
984     /* Check magic number */
985     if (pArena->magic != ARENA_FREE_MAGIC)
986     {
987         ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
988         return FALSE;
989     }
990     /* Check size flags */
991     if (!(pArena->size & ARENA_FLAG_FREE) ||
992         (pArena->size & ARENA_FLAG_PREV_FREE))
993     {
994         ERR("Heap %p: bad flags %08x for free arena %p\n",
995             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
996         return FALSE;
997     }
998     /* Check arena size */
999     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1000     {
1001         ERR("Heap %p: bad size %08x for free arena %p\n",
1002             subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1003         return FALSE;
1004     }
1005     /* Check that next pointer is valid */
1006     next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1007     if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1008     {
1009         ERR("Heap %p: bad next ptr %p for arena %p\n",
1010             subheap->heap, next, pArena );
1011         return FALSE;
1012     }
1013     /* Check that next arena is free */
1014     if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1015     {
1016         ERR("Heap %p: next arena %p invalid for %p\n",
1017             subheap->heap, next, pArena );
1018         return FALSE;
1019     }
1020     /* Check that prev pointer is valid */
1021     prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1022     if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1023     {
1024         ERR("Heap %p: bad prev ptr %p for arena %p\n",
1025             subheap->heap, prev, pArena );
1026         return FALSE;
1027     }
1028     /* Check that prev arena is free */
1029     if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1030     {
1031         /* this often means that the prev arena got overwritten
1032          * by a memory write before that prev arena */
1033         ERR("Heap %p: prev arena %p invalid for %p\n",
1034             subheap->heap, prev, pArena );
1035         return FALSE;
1036     }
1037     /* Check that next block has PREV_FREE flag */
1038     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1039     {
1040         if (!(*(DWORD *)((char *)(pArena + 1) +
1041             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1042         {
1043             ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1044                 subheap->heap, pArena );
1045             return FALSE;
1046         }
1047         /* Check next block back pointer */
1048         if (*((ARENA_FREE **)((char *)(pArena + 1) +
1049             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1050         {
1051             ERR("Heap %p: arena %p has wrong back ptr %p\n",
1052                 subheap->heap, pArena,
1053                 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1054             return FALSE;
1055         }
1056     }
1057     return TRUE;
1058 }
1059
1060
1061 /***********************************************************************
1062  *           HEAP_ValidateInUseArena
1063  */
1064 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1065 {
1066     const char *heapEnd = (const char *)subheap->base + subheap->size;
1067
1068     /* Check for unaligned pointers */
1069     if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1070     {
1071         if ( quiet == NOISY )
1072         {
1073             ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1074             if ( TRACE_ON(heap) )
1075                 HEAP_Dump( subheap->heap );
1076         }
1077         else if ( WARN_ON(heap) )
1078         {
1079             WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1080             if ( TRACE_ON(heap) )
1081                 HEAP_Dump( subheap->heap );
1082         }
1083         return FALSE;
1084     }
1085
1086     /* Check magic number */
1087     if (pArena->magic != ARENA_INUSE_MAGIC)
1088     {
1089         if (quiet == NOISY) {
1090             ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1091             if (TRACE_ON(heap))
1092                HEAP_Dump( subheap->heap );
1093         }  else if (WARN_ON(heap)) {
1094             WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1095             if (TRACE_ON(heap))
1096                HEAP_Dump( subheap->heap );
1097         }
1098         return FALSE;
1099     }
1100     /* Check size flags */
1101     if (pArena->size & ARENA_FLAG_FREE)
1102     {
1103         ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1104             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1105         return FALSE;
1106     }
1107     /* Check arena size */
1108     if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1109     {
1110         ERR("Heap %p: bad size %08x for in-use arena %p\n",
1111             subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1112         return FALSE;
1113     }
1114     /* Check next arena PREV_FREE flag */
1115     if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1116         (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1117     {
1118         ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1119             subheap->heap, pArena );
1120         return FALSE;
1121     }
1122     /* Check prev free arena */
1123     if (pArena->size & ARENA_FLAG_PREV_FREE)
1124     {
1125         const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1126         /* Check prev pointer */
1127         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1128         {
1129             ERR("Heap %p: bad back ptr %p for arena %p\n",
1130                 subheap->heap, pPrev, pArena );
1131             return FALSE;
1132         }
1133         /* Check that prev arena is free */
1134         if (!(pPrev->size & ARENA_FLAG_FREE) ||
1135             (pPrev->magic != ARENA_FREE_MAGIC))
1136         {
1137             ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1138                 subheap->heap, pPrev, pArena );
1139             return FALSE;
1140         }
1141         /* Check that prev arena is really the previous block */
1142         if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1143         {
1144             ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1145                 subheap->heap, pPrev, pArena );
1146             return FALSE;
1147         }
1148     }
1149     return TRUE;
1150 }
1151
1152
1153 /***********************************************************************
1154  *           HEAP_IsRealArena  [Internal]
1155  * Validates a block is a valid arena.
1156  *
1157  * RETURNS
1158  *      TRUE: Success
1159  *      FALSE: Failure
1160  */
1161 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
1162               DWORD flags,   /* [in] Bit flags that control access during operation */
1163               LPCVOID block, /* [in] Optional pointer to memory block to validate */
1164               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
1165                               *             does not complain    */
1166 {
1167     SUBHEAP *subheap;
1168     BOOL ret = TRUE;
1169     const ARENA_LARGE *large_arena;
1170
1171     flags &= HEAP_NO_SERIALIZE;
1172     flags |= heapPtr->flags;
1173     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1174     if (!(flags & HEAP_NO_SERIALIZE))
1175         RtlEnterCriticalSection( &heapPtr->critSection );
1176
1177     if (block)  /* only check this single memory block */
1178     {
1179         const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1180
1181         if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1182             ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1183         {
1184             if (!(large_arena = find_large_block( heapPtr, block )))
1185             {
1186                 if (quiet == NOISY)
1187                     ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1188                 else if (WARN_ON(heap))
1189                     WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1190                 ret = FALSE;
1191             }
1192             else
1193                 ret = validate_large_arena( heapPtr, large_arena, quiet );
1194         } else
1195             ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1196
1197         if (!(flags & HEAP_NO_SERIALIZE))
1198             RtlLeaveCriticalSection( &heapPtr->critSection );
1199         return ret;
1200     }
1201
1202     LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1203     {
1204         char *ptr = (char *)subheap->base + subheap->headerSize;
1205         while (ptr < (char *)subheap->base + subheap->size)
1206         {
1207             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1208             {
1209                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1210                     ret = FALSE;
1211                     break;
1212                 }
1213                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1214             }
1215             else
1216             {
1217                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1218                     ret = FALSE;
1219                     break;
1220                 }
1221                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1222             }
1223         }
1224         if (!ret) break;
1225     }
1226
1227     LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1228         if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1229
1230     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1231     return ret;
1232 }
1233
1234
1235 /***********************************************************************
1236  *           RtlCreateHeap   (NTDLL.@)
1237  *
1238  * Create a new Heap.
1239  *
1240  * PARAMS
1241  *  flags      [I] HEAP_ flags from "winnt.h"
1242  *  addr       [I] Desired base address
1243  *  totalSize  [I] Total size of the heap, or 0 for a growable heap
1244  *  commitSize [I] Amount of heap space to commit
1245  *  unknown    [I] Not yet understood
1246  *  definition [I] Heap definition
1247  *
1248  * RETURNS
1249  *  Success: A HANDLE to the newly created heap.
1250  *  Failure: a NULL HANDLE.
1251  */
1252 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1253                              PVOID unknown, PRTL_HEAP_DEFINITION definition )
1254 {
1255     SUBHEAP *subheap;
1256
1257     /* Allocate the heap block */
1258
1259     if (!totalSize)
1260     {
1261         totalSize = HEAP_DEF_SIZE;
1262         flags |= HEAP_GROWABLE;
1263     }
1264
1265     if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1266
1267     /* link it into the per-process heap list */
1268     if (processHeap)
1269     {
1270         HEAP *heapPtr = subheap->heap;
1271         RtlEnterCriticalSection( &processHeap->critSection );
1272         list_add_head( &processHeap->entry, &heapPtr->entry );
1273         RtlLeaveCriticalSection( &processHeap->critSection );
1274     }
1275     else if (!addr)
1276     {
1277         processHeap = subheap->heap;  /* assume the first heap we create is the process main heap */
1278         list_init( &processHeap->entry );
1279     }
1280
1281     return subheap->heap;
1282 }
1283
1284
1285 /***********************************************************************
1286  *           RtlDestroyHeap   (NTDLL.@)
1287  *
1288  * Destroy a Heap created with RtlCreateHeap().
1289  *
1290  * PARAMS
1291  *  heap [I] Heap to destroy.
1292  *
1293  * RETURNS
1294  *  Success: A NULL HANDLE, if heap is NULL or it was destroyed
1295  *  Failure: The Heap handle, if heap is the process heap.
1296  */
1297 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1298 {
1299     HEAP *heapPtr = HEAP_GetPtr( heap );
1300     SUBHEAP *subheap, *next;
1301     ARENA_LARGE *arena, *arena_next;
1302     SIZE_T size;
1303     void *addr;
1304
1305     TRACE("%p\n", heap );
1306     if (!heapPtr) return heap;
1307
1308     if (heap == processHeap) return heap; /* cannot delete the main process heap */
1309
1310     /* remove it from the per-process list */
1311     RtlEnterCriticalSection( &processHeap->critSection );
1312     list_remove( &heapPtr->entry );
1313     RtlLeaveCriticalSection( &processHeap->critSection );
1314
1315     heapPtr->critSection.DebugInfo->Spare[0] = 0;
1316     RtlDeleteCriticalSection( &heapPtr->critSection );
1317
1318     LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1319     {
1320         list_remove( &arena->entry );
1321         size = 0;
1322         addr = arena;
1323         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1324     }
1325     LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1326     {
1327         if (subheap == &heapPtr->subheap) continue;  /* do this one last */
1328         subheap_notify_free_all(subheap);
1329         list_remove( &subheap->entry );
1330         size = 0;
1331         addr = subheap->base;
1332         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1333     }
1334     subheap_notify_free_all(&heapPtr->subheap);
1335     size = 0;
1336     addr = heapPtr->subheap.base;
1337     NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1338     return 0;
1339 }
1340
1341
1342 /***********************************************************************
1343  *           RtlAllocateHeap   (NTDLL.@)
1344  *
1345  * Allocate a memory block from a Heap.
1346  *
1347  * PARAMS
1348  *  heap  [I] Heap to allocate block from
1349  *  flags [I] HEAP_ flags from "winnt.h"
1350  *  size  [I] Size of the memory block to allocate
1351  *
1352  * RETURNS
1353  *  Success: A pointer to the newly allocated block
1354  *  Failure: NULL.
1355  *
1356  * NOTES
1357  *  This call does not SetLastError().
1358  */
1359 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1360 {
1361     ARENA_FREE *pArena;
1362     ARENA_INUSE *pInUse;
1363     SUBHEAP *subheap;
1364     HEAP *heapPtr = HEAP_GetPtr( heap );
1365     SIZE_T rounded_size;
1366
1367     /* Validate the parameters */
1368
1369     if (!heapPtr) return NULL;
1370     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1371     flags |= heapPtr->flags;
1372     rounded_size = ROUND_SIZE(size);
1373     if (rounded_size < size)  /* overflow */
1374     {
1375         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1376         return NULL;
1377     }
1378     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1379
1380     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1381
1382     if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1383     {
1384         void *ret = allocate_large_block( heap, flags, size );
1385         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1386         if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1387         notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1388         TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1389         return ret;
1390     }
1391
1392     /* Locate a suitable free block */
1393
1394     if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1395     {
1396         TRACE("(%p,%08x,%08lx): returning NULL\n",
1397                   heap, flags, size  );
1398         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1399         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1400         return NULL;
1401     }
1402
1403     /* Remove the arena from the free list */
1404
1405     list_remove( &pArena->entry );
1406
1407     /* Build the in-use arena */
1408
1409     pInUse = (ARENA_INUSE *)pArena;
1410
1411     /* in-use arena is smaller than free arena,
1412      * so we have to add the difference to the size */
1413     pInUse->size  = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1414     pInUse->magic = ARENA_INUSE_MAGIC;
1415
1416     /* Shrink the block */
1417
1418     HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1419     pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1420
1421     notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1422
1423     if (flags & HEAP_ZERO_MEMORY)
1424     {
1425         clear_block( pInUse + 1, size );
1426         mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1427     }
1428     else
1429         mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1430
1431     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1432
1433     TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1434     return pInUse + 1;
1435 }
1436
1437
1438 /***********************************************************************
1439  *           RtlFreeHeap   (NTDLL.@)
1440  *
1441  * Free a memory block allocated with RtlAllocateHeap().
1442  *
1443  * PARAMS
1444  *  heap  [I] Heap that block was allocated from
1445  *  flags [I] HEAP_ flags from "winnt.h"
1446  *  ptr   [I] Block to free
1447  *
1448  * RETURNS
1449  *  Success: TRUE, if ptr is NULL or was freed successfully.
1450  *  Failure: FALSE.
1451  */
1452 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1453 {
1454     ARENA_INUSE *pInUse;
1455     SUBHEAP *subheap;
1456     HEAP *heapPtr;
1457
1458     /* Validate the parameters */
1459
1460     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1461
1462     heapPtr = HEAP_GetPtr( heap );
1463     if (!heapPtr)
1464     {
1465         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1466         return FALSE;
1467     }
1468
1469     flags &= HEAP_NO_SERIALIZE;
1470     flags |= heapPtr->flags;
1471     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1472
1473     /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1474     notify_free( ptr );
1475
1476     /* Some sanity checks */
1477     pInUse  = (ARENA_INUSE *)ptr - 1;
1478     if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1479     {
1480         if (!find_large_block( heapPtr, ptr )) goto error;
1481         free_large_block( heapPtr, flags, ptr );
1482         goto done;
1483     }
1484     if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1485     if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1486
1487     /* Turn the block into a free block */
1488
1489     HEAP_MakeInUseBlockFree( subheap, pInUse );
1490
1491 done:
1492     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1493     TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1494     return TRUE;
1495
1496 error:
1497     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1498     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1499     TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1500     return FALSE;
1501 }
1502
1503
1504 /***********************************************************************
1505  *           RtlReAllocateHeap   (NTDLL.@)
1506  *
1507  * Change the size of a memory block allocated with RtlAllocateHeap().
1508  *
1509  * PARAMS
1510  *  heap  [I] Heap that block was allocated from
1511  *  flags [I] HEAP_ flags from "winnt.h"
1512  *  ptr   [I] Block to resize
1513  *  size  [I] Size of the memory block to allocate
1514  *
1515  * RETURNS
1516  *  Success: A pointer to the resized block (which may be different).
1517  *  Failure: NULL.
1518  */
1519 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1520 {
1521     ARENA_INUSE *pArena;
1522     HEAP *heapPtr;
1523     SUBHEAP *subheap;
1524     SIZE_T oldBlockSize, oldActualSize, rounded_size;
1525     void *ret;
1526
1527     if (!ptr) return NULL;
1528     if (!(heapPtr = HEAP_GetPtr( heap )))
1529     {
1530         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1531         return NULL;
1532     }
1533
1534     /* Validate the parameters */
1535
1536     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1537              HEAP_REALLOC_IN_PLACE_ONLY;
1538     flags |= heapPtr->flags;
1539     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1540
1541     rounded_size = ROUND_SIZE(size);
1542     if (rounded_size < size) goto oom;  /* overflow */
1543     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1544
1545     pArena = (ARENA_INUSE *)ptr - 1;
1546     if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1547     {
1548         if (!find_large_block( heapPtr, ptr )) goto error;
1549         if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1550         notify_free( ptr );
1551         notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1552         goto done;
1553     }
1554     if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1555     if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1556
1557     /* Check if we need to grow the block */
1558
1559     oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1560     oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1561     if (rounded_size > oldBlockSize)
1562     {
1563         char *pNext = (char *)(pArena + 1) + oldBlockSize;
1564
1565         if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1566         {
1567             if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1568             if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1569             notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1570             memcpy( ret, pArena + 1, oldActualSize );
1571             notify_free( pArena + 1 );
1572             HEAP_MakeInUseBlockFree( subheap, pArena );
1573             goto done;
1574         }
1575         if ((pNext < (char *)subheap->base + subheap->size) &&
1576             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1577             (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1578         {
1579             /* The next block is free and large enough */
1580             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1581             list_remove( &pFree->entry );
1582             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1583             if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1584             notify_free( pArena + 1 );
1585             HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1586             notify_alloc( pArena + 1, size, FALSE );
1587             /* FIXME: this is wrong as we may lose old VBits settings */
1588             mark_block_initialized( pArena + 1, oldActualSize );
1589         }
1590         else  /* Do it the hard way */
1591         {
1592             ARENA_FREE *pNew;
1593             ARENA_INUSE *pInUse;
1594             SUBHEAP *newsubheap;
1595
1596             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1597                 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1598                 goto oom;
1599
1600             /* Build the in-use arena */
1601
1602             list_remove( &pNew->entry );
1603             pInUse = (ARENA_INUSE *)pNew;
1604             pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1605                            + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1606             pInUse->magic = ARENA_INUSE_MAGIC;
1607             HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1608
1609             mark_block_initialized( pInUse + 1, oldActualSize );
1610             notify_alloc( pInUse + 1, size, FALSE );
1611             memcpy( pInUse + 1, pArena + 1, oldActualSize );
1612
1613             /* Free the previous block */
1614
1615             notify_free( pArena + 1 );
1616             HEAP_MakeInUseBlockFree( subheap, pArena );
1617             subheap = newsubheap;
1618             pArena  = pInUse;
1619         }
1620     }
1621     else
1622     {
1623         /* Shrink the block */
1624         notify_free( pArena + 1 );
1625         HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1626         notify_alloc( pArena + 1, size, FALSE );
1627         /* FIXME: this is wrong as we may lose old VBits settings */
1628         mark_block_initialized( pArena + 1, size );
1629     }
1630
1631     pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1632
1633     /* Clear the extra bytes if needed */
1634
1635     if (size > oldActualSize)
1636     {
1637         if (flags & HEAP_ZERO_MEMORY)
1638         {
1639             clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1640             mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1641         }
1642         else
1643             mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1644                                       (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1645     }
1646
1647     /* Return the new arena */
1648
1649     ret = pArena + 1;
1650 done:
1651     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1652     TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1653     return ret;
1654
1655 oom:
1656     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1657     if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1658     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1659     TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1660     return NULL;
1661
1662 error:
1663     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1664     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1665     TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1666     return NULL;
1667 }
1668
1669
1670 /***********************************************************************
1671  *           RtlCompactHeap   (NTDLL.@)
1672  *
1673  * Compact the free space in a Heap.
1674  *
1675  * PARAMS
1676  *  heap  [I] Heap that block was allocated from
1677  *  flags [I] HEAP_ flags from "winnt.h"
1678  *
1679  * RETURNS
1680  *  The number of bytes compacted.
1681  *
1682  * NOTES
1683  *  This function is a harmless stub.
1684  */
1685 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1686 {
1687     static BOOL reported;
1688     if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1689     return 0;
1690 }
1691
1692
1693 /***********************************************************************
1694  *           RtlLockHeap   (NTDLL.@)
1695  *
1696  * Lock a Heap.
1697  *
1698  * PARAMS
1699  *  heap  [I] Heap to lock
1700  *
1701  * RETURNS
1702  *  Success: TRUE. The Heap is locked.
1703  *  Failure: FALSE, if heap is invalid.
1704  */
1705 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1706 {
1707     HEAP *heapPtr = HEAP_GetPtr( heap );
1708     if (!heapPtr) return FALSE;
1709     RtlEnterCriticalSection( &heapPtr->critSection );
1710     return TRUE;
1711 }
1712
1713
1714 /***********************************************************************
1715  *           RtlUnlockHeap   (NTDLL.@)
1716  *
1717  * Unlock a Heap.
1718  *
1719  * PARAMS
1720  *  heap  [I] Heap to unlock
1721  *
1722  * RETURNS
1723  *  Success: TRUE. The Heap is unlocked.
1724  *  Failure: FALSE, if heap is invalid.
1725  */
1726 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1727 {
1728     HEAP *heapPtr = HEAP_GetPtr( heap );
1729     if (!heapPtr) return FALSE;
1730     RtlLeaveCriticalSection( &heapPtr->critSection );
1731     return TRUE;
1732 }
1733
1734
1735 /***********************************************************************
1736  *           RtlSizeHeap   (NTDLL.@)
1737  *
1738  * Get the actual size of a memory block allocated from a Heap.
1739  *
1740  * PARAMS
1741  *  heap  [I] Heap that block was allocated from
1742  *  flags [I] HEAP_ flags from "winnt.h"
1743  *  ptr   [I] Block to get the size of
1744  *
1745  * RETURNS
1746  *  Success: The size of the block.
1747  *  Failure: -1, heap or ptr are invalid.
1748  *
1749  * NOTES
1750  *  The size may be bigger than what was passed to RtlAllocateHeap().
1751  */
1752 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1753 {
1754     SIZE_T ret;
1755     HEAP *heapPtr = HEAP_GetPtr( heap );
1756
1757     if (!heapPtr)
1758     {
1759         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1760         return ~0UL;
1761     }
1762     flags &= HEAP_NO_SERIALIZE;
1763     flags |= heapPtr->flags;
1764     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1765     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1766     {
1767         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1768         ret = ~0UL;
1769     }
1770     else
1771     {
1772         const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1773         if (pArena->size == ARENA_LARGE_SIZE)
1774         {
1775             const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1776             ret = large_arena->data_size;
1777         }
1778         else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1779     }
1780     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1781
1782     TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1783     return ret;
1784 }
1785
1786
1787 /***********************************************************************
1788  *           RtlValidateHeap   (NTDLL.@)
1789  *
1790  * Determine if a block is a valid allocation from a heap.
1791  *
1792  * PARAMS
1793  *  heap  [I] Heap that block was allocated from
1794  *  flags [I] HEAP_ flags from "winnt.h"
1795  *  ptr   [I] Block to check
1796  *
1797  * RETURNS
1798  *  Success: TRUE. The block was allocated from heap.
1799  *  Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1800  */
1801 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1802 {
1803     HEAP *heapPtr = HEAP_GetPtr( heap );
1804     if (!heapPtr) return FALSE;
1805     return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1806 }
1807
1808
1809 /***********************************************************************
1810  *           RtlWalkHeap    (NTDLL.@)
1811  *
1812  * FIXME
1813  *  The PROCESS_HEAP_ENTRY flag values seem different between this
1814  *  function and HeapWalk(). To be checked.
1815  */
1816 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1817 {
1818     LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1819     HEAP *heapPtr = HEAP_GetPtr(heap);
1820     SUBHEAP *sub, *currentheap = NULL;
1821     NTSTATUS ret;
1822     char *ptr;
1823     int region_index = 0;
1824
1825     if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1826
1827     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1828
1829     /* FIXME: enumerate large blocks too */
1830
1831     /* set ptr to the next arena to be examined */
1832
1833     if (!entry->lpData) /* first call (init) ? */
1834     {
1835         TRACE("begin walking of heap %p.\n", heap);
1836         currentheap = &heapPtr->subheap;
1837         ptr = (char*)currentheap->base + currentheap->headerSize;
1838     }
1839     else
1840     {
1841         ptr = entry->lpData;
1842         LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1843         {
1844             if ((ptr >= (char *)sub->base) &&
1845                 (ptr < (char *)sub->base + sub->size))
1846             {
1847                 currentheap = sub;
1848                 break;
1849             }
1850             region_index++;
1851         }
1852         if (currentheap == NULL)
1853         {
1854             ERR("no matching subheap found, shouldn't happen !\n");
1855             ret = STATUS_NO_MORE_ENTRIES;
1856             goto HW_end;
1857         }
1858
1859         if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1860         {
1861             ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1862             ptr += pArena->size & ARENA_SIZE_MASK;
1863         }
1864         else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1865         {
1866             ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1867             ptr += pArena->size & ARENA_SIZE_MASK;
1868         }
1869         else
1870             ptr += entry->cbData; /* point to next arena */
1871
1872         if (ptr > (char *)currentheap->base + currentheap->size - 1)
1873         {   /* proceed with next subheap */
1874             struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1875             if (!next)
1876             {  /* successfully finished */
1877                 TRACE("end reached.\n");
1878                 ret = STATUS_NO_MORE_ENTRIES;
1879                 goto HW_end;
1880             }
1881             currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1882             ptr = (char *)currentheap->base + currentheap->headerSize;
1883         }
1884     }
1885
1886     entry->wFlags = 0;
1887     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1888     {
1889         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1890
1891         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1892
1893         entry->lpData = pArena + 1;
1894         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1895         entry->cbOverhead = sizeof(ARENA_FREE);
1896         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1897     }
1898     else
1899     {
1900         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1901
1902         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1903
1904         entry->lpData = pArena + 1;
1905         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1906         entry->cbOverhead = sizeof(ARENA_INUSE);
1907         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1908         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1909         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1910     }
1911
1912     entry->iRegionIndex = region_index;
1913
1914     /* first element of heap ? */
1915     if (ptr == (char *)currentheap->base + currentheap->headerSize)
1916     {
1917         entry->wFlags |= PROCESS_HEAP_REGION;
1918         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1919         entry->u.Region.dwUnCommittedSize =
1920                 currentheap->size - currentheap->commitSize;
1921         entry->u.Region.lpFirstBlock = /* first valid block */
1922                 (char *)currentheap->base + currentheap->headerSize;
1923         entry->u.Region.lpLastBlock  = /* first invalid block */
1924                 (char *)currentheap->base + currentheap->size;
1925     }
1926     ret = STATUS_SUCCESS;
1927     if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1928
1929 HW_end:
1930     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1931     return ret;
1932 }
1933
1934
1935 /***********************************************************************
1936  *           RtlGetProcessHeaps    (NTDLL.@)
1937  *
1938  * Get the Heaps belonging to the current process.
1939  *
1940  * PARAMS
1941  *  count [I] size of heaps
1942  *  heaps [O] Destination array for heap HANDLE's
1943  *
1944  * RETURNS
1945  *  Success: The number of Heaps allocated by the process.
1946  *  Failure: 0.
1947  */
1948 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1949 {
1950     ULONG total = 1;  /* main heap */
1951     struct list *ptr;
1952
1953     RtlEnterCriticalSection( &processHeap->critSection );
1954     LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1955     if (total <= count)
1956     {
1957         *heaps++ = processHeap;
1958         LIST_FOR_EACH( ptr, &processHeap->entry )
1959             *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1960     }
1961     RtlLeaveCriticalSection( &processHeap->critSection );
1962     return total;
1963 }