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