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