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