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