ntdll: NtAreMappedFilesTheSame semi stub.
[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 SIZE_T 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 %08lx 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 - sizeof(ARENA_INUSE)))
399             return (SUBHEAP *)sub;
400         sub = sub->next;
401     }
402     return NULL;
403 }
404
405
406 /***********************************************************************
407  *           HEAP_Commit
408  *
409  * Make sure the heap storage is committed for a given size in the specified arena.
410  */
411 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
412 {
413     void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
414     SIZE_T size = (char *)ptr - (char *)subheap;
415     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
416     if (size > subheap->size) size = subheap->size;
417     if (size <= subheap->commitSize) return TRUE;
418     size -= subheap->commitSize;
419     ptr = (char *)subheap + subheap->commitSize;
420     if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
421                                  &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
422     {
423         WARN("Could not commit %08lx bytes at %p for heap %p\n",
424                  size, ptr, subheap->heap );
425         return FALSE;
426     }
427     subheap->commitSize += size;
428     return TRUE;
429 }
430
431
432 /***********************************************************************
433  *           HEAP_Decommit
434  *
435  * If possible, decommit the heap storage from (including) 'ptr'.
436  */
437 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
438 {
439     void *addr;
440     SIZE_T decommit_size;
441     SIZE_T size = (char *)ptr - (char *)subheap;
442
443     /* round to next block and add one full block */
444     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
445     if (size >= subheap->commitSize) return TRUE;
446     decommit_size = subheap->commitSize - size;
447     addr = (char *)subheap + size;
448
449     if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
450     {
451         WARN("Could not decommit %08lx bytes at %p for heap %p\n",
452                 decommit_size, (char *)subheap + size, subheap->heap );
453         return FALSE;
454     }
455     subheap->commitSize -= decommit_size;
456     return TRUE;
457 }
458
459
460 /***********************************************************************
461  *           HEAP_CreateFreeBlock
462  *
463  * Create a free block at a specified address. 'size' is the size of the
464  * whole block, including the new arena.
465  */
466 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
467 {
468     ARENA_FREE *pFree;
469     char *pEnd;
470     BOOL last;
471
472     /* Create a free arena */
473     mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
474     pFree = (ARENA_FREE *)ptr;
475     pFree->magic = ARENA_FREE_MAGIC;
476
477     /* If debugging, erase the freed block content */
478
479     pEnd = (char *)ptr + size;
480     if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
481     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
482
483     /* Check if next block is free also */
484
485     if (((char *)ptr + size < (char *)subheap + subheap->size) &&
486         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
487     {
488         /* Remove the next arena from the free list */
489         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
490         list_remove( &pNext->entry );
491         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
492         mark_block_free( pNext, sizeof(ARENA_FREE) );
493     }
494
495     /* Set the next block PREV_FREE flag and pointer */
496
497     last = ((char *)ptr + size >= (char *)subheap + subheap->size);
498     if (!last)
499     {
500         DWORD *pNext = (DWORD *)((char *)ptr + size);
501         *pNext |= ARENA_FLAG_PREV_FREE;
502         mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
503         *((ARENA_FREE **)pNext - 1) = pFree;
504     }
505
506     /* Last, insert the new block into the free list */
507
508     pFree->size = size - sizeof(*pFree);
509     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
510 }
511
512
513 /***********************************************************************
514  *           HEAP_MakeInUseBlockFree
515  *
516  * Turn an in-use block into a free block. Can also decommit the end of
517  * the heap, and possibly even free the sub-heap altogether.
518  */
519 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
520 {
521     ARENA_FREE *pFree;
522     SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
523
524     /* Check if we can merge with previous block */
525
526     if (pArena->size & ARENA_FLAG_PREV_FREE)
527     {
528         pFree = *((ARENA_FREE **)pArena - 1);
529         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
530         /* Remove it from the free list */
531         list_remove( &pFree->entry );
532     }
533     else pFree = (ARENA_FREE *)pArena;
534
535     /* Create a free block */
536
537     HEAP_CreateFreeBlock( subheap, pFree, size );
538     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
539     if ((char *)pFree + size < (char *)subheap + subheap->size)
540         return;  /* Not the last block, so nothing more to do */
541
542     /* Free the whole sub-heap if it's empty and not the original one */
543
544     if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
545         (subheap != &subheap->heap->subheap))
546     {
547         SIZE_T size = 0;
548         SUBHEAP *pPrev = &subheap->heap->subheap;
549         /* Remove the free block from the list */
550         list_remove( &pFree->entry );
551         /* Remove the subheap from the list */
552         while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
553         if (pPrev) pPrev->next = subheap->next;
554         /* Free the memory */
555         subheap->magic = 0;
556         NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
557         return;
558     }
559
560     /* Decommit the end of the heap */
561
562     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
563 }
564
565
566 /***********************************************************************
567  *           HEAP_ShrinkBlock
568  *
569  * Shrink an in-use block.
570  */
571 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
572 {
573     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
574     {
575         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
576                               (pArena->size & ARENA_SIZE_MASK) - size );
577         /* assign size plus previous arena flags */
578         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
579     }
580     else
581     {
582         /* Turn off PREV_FREE flag in next block */
583         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
584         if (pNext < (char *)subheap + subheap->size)
585             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
586     }
587 }
588
589 /***********************************************************************
590  *           HEAP_InitSubHeap
591  */
592 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
593                               SIZE_T commitSize, SIZE_T totalSize )
594 {
595     SUBHEAP *subheap;
596     FREE_LIST_ENTRY *pEntry;
597     int i;
598
599     /* Commit memory */
600
601     if (flags & HEAP_SHARED)
602         commitSize = totalSize;  /* always commit everything in a shared heap */
603     if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
604                                  &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
605     {
606         WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
607         return FALSE;
608     }
609
610     /* Fill the sub-heap structure */
611
612     subheap = (SUBHEAP *)address;
613     subheap->heap       = heap;
614     subheap->size       = totalSize;
615     subheap->commitSize = commitSize;
616     subheap->magic      = SUBHEAP_MAGIC;
617
618     if ( subheap != (SUBHEAP *)heap )
619     {
620         /* If this is a secondary subheap, insert it into list */
621
622         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
623         subheap->next       = heap->subheap.next;
624         heap->subheap.next  = subheap;
625     }
626     else
627     {
628         /* If this is a primary subheap, initialize main heap */
629
630         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
631         subheap->next       = NULL;
632         heap->flags         = flags;
633         heap->magic         = HEAP_MAGIC;
634
635         /* Build the free lists */
636
637         list_init( &heap->freeList[0].arena.entry );
638         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
639         {
640             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
641             pEntry->arena.magic = ARENA_FREE_MAGIC;
642             if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
643         }
644
645         /* Initialize critical section */
646
647         if (!processHeap)  /* do it by hand to avoid memory allocations */
648         {
649             heap->critSection.DebugInfo      = &process_heap_critsect_debug;
650             heap->critSection.LockCount      = -1;
651             heap->critSection.RecursionCount = 0;
652             heap->critSection.OwningThread   = 0;
653             heap->critSection.LockSemaphore  = 0;
654             heap->critSection.SpinCount      = 0;
655             process_heap_critsect_debug.CriticalSection = &heap->critSection;
656         }
657         else
658         {
659             RtlInitializeCriticalSection( &heap->critSection );
660             heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
661         }
662
663         if (flags & HEAP_SHARED)
664         {
665             /* let's assume that only one thread at a time will try to do this */
666             HANDLE sem = heap->critSection.LockSemaphore;
667             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
668
669             NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
670                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
671             heap->critSection.LockSemaphore = sem;
672             RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
673             heap->critSection.DebugInfo = NULL;
674         }
675     }
676
677     /* Create the first free block */
678
679     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
680                           subheap->size - subheap->headerSize );
681
682     return TRUE;
683 }
684
685 /***********************************************************************
686  *           HEAP_CreateSubHeap
687  *
688  * Create a sub-heap of the given size.
689  * If heap == NULL, creates a main heap.
690  */
691 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
692                                     SIZE_T commitSize, SIZE_T totalSize )
693 {
694     LPVOID address = base;
695
696     /* round-up sizes on a 64K boundary */
697     totalSize  = (totalSize + 0xffff) & 0xffff0000;
698     commitSize = (commitSize + 0xffff) & 0xffff0000;
699     if (!commitSize) commitSize = 0x10000;
700     if (totalSize < commitSize) totalSize = commitSize;
701
702     if (!address)
703     {
704         /* allocate the memory block */
705         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
706                                      MEM_RESERVE, get_protection_type( flags ) ))
707         {
708             WARN("Could not allocate %08lx bytes\n", totalSize );
709             return NULL;
710         }
711     }
712
713     /* Initialize subheap */
714
715     if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
716                            address, flags, commitSize, totalSize ))
717     {
718         SIZE_T size = 0;
719         if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
720         return NULL;
721     }
722
723     return (SUBHEAP *)address;
724 }
725
726
727 /***********************************************************************
728  *           HEAP_FindFreeBlock
729  *
730  * Find a free block at least as large as the requested size, and make sure
731  * the requested size is committed.
732  */
733 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
734                                        SUBHEAP **ppSubHeap )
735 {
736     SUBHEAP *subheap;
737     struct list *ptr;
738     SIZE_T total_size;
739     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
740
741     /* Find a suitable free list, and in it find a block large enough */
742
743     ptr = &pEntry->arena.entry;
744     while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
745     {
746         ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
747         SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
748                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
749         if (arena_size >= size)
750         {
751             subheap = HEAP_FindSubHeap( heap, pArena );
752             if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
753             *ppSubHeap = subheap;
754             return pArena;
755         }
756     }
757
758     /* If no block was found, attempt to grow the heap */
759
760     if (!(heap->flags & HEAP_GROWABLE))
761     {
762         WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
763         return NULL;
764     }
765     /* make sure that we have a big enough size *committed* to fit another
766      * last free arena in !
767      * So just one heap struct, one first free arena which will eventually
768      * get used, and a second free arena that might get assigned all remaining
769      * free space in HEAP_ShrinkBlock() */
770     total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
771     if (total_size < size) return NULL;  /* overflow */
772
773     if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
774                                         max( HEAP_DEF_SIZE, total_size ) )))
775         return NULL;
776
777     TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
778             subheap, total_size, heap );
779
780     *ppSubHeap = subheap;
781     return (ARENA_FREE *)(subheap + 1);
782 }
783
784
785 /***********************************************************************
786  *           HEAP_IsValidArenaPtr
787  *
788  * Check that the pointer is inside the range possible for arenas.
789  */
790 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
791 {
792     int i;
793     const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
794     if (!subheap) return FALSE;
795     if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
796     if (subheap != &heap->subheap) return FALSE;
797     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
798         if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
799     return FALSE;
800 }
801
802
803 /***********************************************************************
804  *           HEAP_ValidateFreeArena
805  */
806 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
807 {
808     ARENA_FREE *prev, *next;
809     char *heapEnd = (char *)subheap + subheap->size;
810
811     /* Check for unaligned pointers */
812     if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
813     {
814         ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
815         return FALSE;
816     }
817
818     /* Check magic number */
819     if (pArena->magic != ARENA_FREE_MAGIC)
820     {
821         ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
822         return FALSE;
823     }
824     /* Check size flags */
825     if (!(pArena->size & ARENA_FLAG_FREE) ||
826         (pArena->size & ARENA_FLAG_PREV_FREE))
827     {
828         ERR("Heap %p: bad flags %08x for free arena %p\n",
829             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
830         return FALSE;
831     }
832     /* Check arena size */
833     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
834     {
835         ERR("Heap %p: bad size %08x for free arena %p\n",
836             subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
837         return FALSE;
838     }
839     /* Check that next pointer is valid */
840     next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
841     if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
842     {
843         ERR("Heap %p: bad next ptr %p for arena %p\n",
844             subheap->heap, next, pArena );
845         return FALSE;
846     }
847     /* Check that next arena is free */
848     if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
849     {
850         ERR("Heap %p: next arena %p invalid for %p\n",
851             subheap->heap, next, pArena );
852         return FALSE;
853     }
854     /* Check that prev pointer is valid */
855     prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
856     if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
857     {
858         ERR("Heap %p: bad prev ptr %p for arena %p\n",
859             subheap->heap, prev, pArena );
860         return FALSE;
861     }
862     /* Check that prev arena is free */
863     if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
864     {
865         /* this often means that the prev arena got overwritten
866          * by a memory write before that prev arena */
867         ERR("Heap %p: prev arena %p invalid for %p\n",
868             subheap->heap, prev, pArena );
869         return FALSE;
870     }
871     /* Check that next block has PREV_FREE flag */
872     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
873     {
874         if (!(*(DWORD *)((char *)(pArena + 1) +
875             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
876         {
877             ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
878                 subheap->heap, pArena );
879             return FALSE;
880         }
881         /* Check next block back pointer */
882         if (*((ARENA_FREE **)((char *)(pArena + 1) +
883             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
884         {
885             ERR("Heap %p: arena %p has wrong back ptr %p\n",
886                 subheap->heap, pArena,
887                 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
888             return FALSE;
889         }
890     }
891     return TRUE;
892 }
893
894
895 /***********************************************************************
896  *           HEAP_ValidateInUseArena
897  */
898 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
899 {
900     const char *heapEnd = (const char *)subheap + subheap->size;
901
902     /* Check for unaligned pointers */
903     if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
904     {
905         if ( quiet == NOISY )
906         {
907             ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
908             if ( TRACE_ON(heap) )
909                 HEAP_Dump( subheap->heap );
910         }
911         else if ( WARN_ON(heap) )
912         {
913             WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
914             if ( TRACE_ON(heap) )
915                 HEAP_Dump( subheap->heap );
916         }
917         return FALSE;
918     }
919
920     /* Check magic number */
921     if (pArena->magic != ARENA_INUSE_MAGIC)
922     {
923         if (quiet == NOISY) {
924             ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
925             if (TRACE_ON(heap))
926                HEAP_Dump( subheap->heap );
927         }  else if (WARN_ON(heap)) {
928             WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
929             if (TRACE_ON(heap))
930                HEAP_Dump( subheap->heap );
931         }
932         return FALSE;
933     }
934     /* Check size flags */
935     if (pArena->size & ARENA_FLAG_FREE)
936     {
937         ERR("Heap %p: bad flags %08x for in-use arena %p\n",
938             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
939         return FALSE;
940     }
941     /* Check arena size */
942     if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
943     {
944         ERR("Heap %p: bad size %08x for in-use arena %p\n",
945             subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
946         return FALSE;
947     }
948     /* Check next arena PREV_FREE flag */
949     if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
950         (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
951     {
952         ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
953             subheap->heap, pArena );
954         return FALSE;
955     }
956     /* Check prev free arena */
957     if (pArena->size & ARENA_FLAG_PREV_FREE)
958     {
959         const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
960         /* Check prev pointer */
961         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
962         {
963             ERR("Heap %p: bad back ptr %p for arena %p\n",
964                 subheap->heap, pPrev, pArena );
965             return FALSE;
966         }
967         /* Check that prev arena is free */
968         if (!(pPrev->size & ARENA_FLAG_FREE) ||
969             (pPrev->magic != ARENA_FREE_MAGIC))
970         {
971             ERR("Heap %p: prev arena %p invalid for in-use %p\n",
972                 subheap->heap, pPrev, pArena );
973             return FALSE;
974         }
975         /* Check that prev arena is really the previous block */
976         if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
977         {
978             ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
979                 subheap->heap, pPrev, pArena );
980             return FALSE;
981         }
982     }
983     return TRUE;
984 }
985
986
987 /***********************************************************************
988  *           HEAP_IsRealArena  [Internal]
989  * Validates a block is a valid arena.
990  *
991  * RETURNS
992  *      TRUE: Success
993  *      FALSE: Failure
994  */
995 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
996               DWORD flags,   /* [in] Bit flags that control access during operation */
997               LPCVOID block, /* [in] Optional pointer to memory block to validate */
998               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
999                               *             does not complain    */
1000 {
1001     SUBHEAP *subheap;
1002     BOOL ret = TRUE;
1003
1004     flags &= HEAP_NO_SERIALIZE;
1005     flags |= heapPtr->flags;
1006     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1007     if (!(flags & HEAP_NO_SERIALIZE))
1008         RtlEnterCriticalSection( &heapPtr->critSection );
1009
1010     if (block)  /* only check this single memory block */
1011     {
1012         const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1013
1014         if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1015             ((const char *)arena < (char *)subheap + subheap->headerSize))
1016         {
1017             if (quiet == NOISY)
1018                 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1019             else if (WARN_ON(heap))
1020                 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1021             ret = FALSE;
1022         } else
1023             ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1024
1025         if (!(flags & HEAP_NO_SERIALIZE))
1026             RtlLeaveCriticalSection( &heapPtr->critSection );
1027         return ret;
1028     }
1029
1030     subheap = &heapPtr->subheap;
1031     while (subheap && ret)
1032     {
1033         char *ptr = (char *)subheap + subheap->headerSize;
1034         while (ptr < (char *)subheap + subheap->size)
1035         {
1036             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1037             {
1038                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1039                     ret = FALSE;
1040                     break;
1041                 }
1042                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1043             }
1044             else
1045             {
1046                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1047                     ret = FALSE;
1048                     break;
1049                 }
1050                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1051             }
1052         }
1053         subheap = subheap->next;
1054     }
1055
1056     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1057     return ret;
1058 }
1059
1060
1061 /***********************************************************************
1062  *           RtlCreateHeap   (NTDLL.@)
1063  *
1064  * Create a new Heap.
1065  *
1066  * PARAMS
1067  *  flags      [I] HEAP_ flags from "winnt.h"
1068  *  addr       [I] Desired base address
1069  *  totalSize  [I] Total size of the heap, or 0 for a growable heap
1070  *  commitSize [I] Amount of heap space to commit
1071  *  unknown    [I] Not yet understood
1072  *  definition [I] Heap definition
1073  *
1074  * RETURNS
1075  *  Success: A HANDLE to the newly created heap.
1076  *  Failure: a NULL HANDLE.
1077  */
1078 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1079                              PVOID unknown, PRTL_HEAP_DEFINITION definition )
1080 {
1081     SUBHEAP *subheap;
1082
1083     /* Allocate the heap block */
1084
1085     if (!totalSize)
1086     {
1087         totalSize = HEAP_DEF_SIZE;
1088         flags |= HEAP_GROWABLE;
1089     }
1090
1091     if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1092
1093     /* link it into the per-process heap list */
1094     if (processHeap)
1095     {
1096         HEAP *heapPtr = subheap->heap;
1097         RtlEnterCriticalSection( &processHeap->critSection );
1098         list_add_head( &processHeap->entry, &heapPtr->entry );
1099         RtlLeaveCriticalSection( &processHeap->critSection );
1100     }
1101     else
1102     {
1103         processHeap = subheap->heap;  /* assume the first heap we create is the process main heap */
1104         list_init( &processHeap->entry );
1105     }
1106
1107     return (HANDLE)subheap;
1108 }
1109
1110
1111 /***********************************************************************
1112  *           RtlDestroyHeap   (NTDLL.@)
1113  *
1114  * Destroy a Heap created with RtlCreateHeap().
1115  *
1116  * PARAMS
1117  *  heap [I] Heap to destroy.
1118  *
1119  * RETURNS
1120  *  Success: A NULL HANDLE, if heap is NULL or it was destroyed
1121  *  Failure: The Heap handle, if heap is the process heap.
1122  */
1123 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1124 {
1125     HEAP *heapPtr = HEAP_GetPtr( heap );
1126     SUBHEAP *subheap;
1127
1128     TRACE("%p\n", heap );
1129     if (!heapPtr) return heap;
1130
1131     if (heap == processHeap) return heap; /* cannot delete the main process heap */
1132
1133     /* remove it from the per-process list */
1134     RtlEnterCriticalSection( &processHeap->critSection );
1135     list_remove( &heapPtr->entry );
1136     RtlLeaveCriticalSection( &processHeap->critSection );
1137
1138     heapPtr->critSection.DebugInfo->Spare[0] = 0;
1139     RtlDeleteCriticalSection( &heapPtr->critSection );
1140     subheap = &heapPtr->subheap;
1141     while (subheap)
1142     {
1143         SUBHEAP *next = subheap->next;
1144         SIZE_T size = 0;
1145         void *addr = subheap;
1146         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1147         subheap = next;
1148     }
1149     return 0;
1150 }
1151
1152
1153 /***********************************************************************
1154  *           RtlAllocateHeap   (NTDLL.@)
1155  *
1156  * Allocate a memory block from a Heap.
1157  *
1158  * PARAMS
1159  *  heap  [I] Heap to allocate block from
1160  *  flags [I] HEAP_ flags from "winnt.h"
1161  *  size  [I] Size of the memory block to allocate
1162  *
1163  * RETURNS
1164  *  Success: A pointer to the newly allocated block
1165  *  Failure: NULL.
1166  *
1167  * NOTES
1168  *  This call does not SetLastError().
1169  */
1170 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1171 {
1172     ARENA_FREE *pArena;
1173     ARENA_INUSE *pInUse;
1174     SUBHEAP *subheap;
1175     HEAP *heapPtr = HEAP_GetPtr( heap );
1176     SIZE_T rounded_size;
1177
1178     /* Validate the parameters */
1179
1180     if (!heapPtr) return NULL;
1181     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1182     flags |= heapPtr->flags;
1183     rounded_size = ROUND_SIZE(size);
1184     if (rounded_size < size)  /* overflow */
1185     {
1186         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1187         return NULL;
1188     }
1189     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1190
1191     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1192     /* Locate a suitable free block */
1193
1194     if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1195     {
1196         TRACE("(%p,%08x,%08lx): returning NULL\n",
1197                   heap, flags, size  );
1198         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1199         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1200         return NULL;
1201     }
1202
1203     /* Remove the arena from the free list */
1204
1205     list_remove( &pArena->entry );
1206
1207     /* Build the in-use arena */
1208
1209     pInUse = (ARENA_INUSE *)pArena;
1210
1211     /* in-use arena is smaller than free arena,
1212      * so we have to add the difference to the size */
1213     pInUse->size  = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1214     pInUse->magic = ARENA_INUSE_MAGIC;
1215
1216     /* Shrink the block */
1217
1218     HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1219     pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1220
1221     notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1222
1223     if (flags & HEAP_ZERO_MEMORY)
1224         clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1225     else
1226         mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1227
1228     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1229
1230     TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1231     return (LPVOID)(pInUse + 1);
1232 }
1233
1234
1235 /***********************************************************************
1236  *           RtlFreeHeap   (NTDLL.@)
1237  *
1238  * Free a memory block allocated with RtlAllocateHeap().
1239  *
1240  * PARAMS
1241  *  heap  [I] Heap that block was allocated from
1242  *  flags [I] HEAP_ flags from "winnt.h"
1243  *  ptr   [I] Block to free
1244  *
1245  * RETURNS
1246  *  Success: TRUE, if ptr is NULL or was freed successfully.
1247  *  Failure: FALSE.
1248  */
1249 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1250 {
1251     ARENA_INUSE *pInUse;
1252     SUBHEAP *subheap;
1253     HEAP *heapPtr;
1254
1255     /* Validate the parameters */
1256
1257     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1258
1259     heapPtr = HEAP_GetPtr( heap );
1260     if (!heapPtr)
1261     {
1262         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1263         return FALSE;
1264     }
1265
1266     flags &= HEAP_NO_SERIALIZE;
1267     flags |= heapPtr->flags;
1268     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1269
1270     /* Some sanity checks */
1271
1272     pInUse  = (ARENA_INUSE *)ptr - 1;
1273     if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1274     if ((char *)pInUse < (char *)subheap + subheap->headerSize) goto error;
1275     if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1276
1277     /* Turn the block into a free block */
1278
1279     notify_free( ptr );
1280
1281     HEAP_MakeInUseBlockFree( subheap, pInUse );
1282
1283     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1284
1285     TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1286     return TRUE;
1287
1288 error:
1289     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1290     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1291     TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1292     return FALSE;
1293 }
1294
1295
1296 /***********************************************************************
1297  *           RtlReAllocateHeap   (NTDLL.@)
1298  *
1299  * Change the size of a memory block allocated with RtlAllocateHeap().
1300  *
1301  * PARAMS
1302  *  heap  [I] Heap that block was allocated from
1303  *  flags [I] HEAP_ flags from "winnt.h"
1304  *  ptr   [I] Block to resize
1305  *  size  [I] Size of the memory block to allocate
1306  *
1307  * RETURNS
1308  *  Success: A pointer to the resized block (which may be different).
1309  *  Failure: NULL.
1310  */
1311 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1312 {
1313     ARENA_INUSE *pArena;
1314     HEAP *heapPtr;
1315     SUBHEAP *subheap;
1316     SIZE_T oldSize, rounded_size;
1317
1318     if (!ptr) return NULL;
1319     if (!(heapPtr = HEAP_GetPtr( heap )))
1320     {
1321         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1322         return NULL;
1323     }
1324
1325     /* Validate the parameters */
1326
1327     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1328              HEAP_REALLOC_IN_PLACE_ONLY;
1329     flags |= heapPtr->flags;
1330     rounded_size = ROUND_SIZE(size);
1331     if (rounded_size < size)  /* overflow */
1332     {
1333         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1334         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1335         return NULL;
1336     }
1337     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1338
1339     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1340
1341     pArena = (ARENA_INUSE *)ptr - 1;
1342     if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1343     if ((char *)pArena < (char *)subheap + subheap->headerSize) goto error;
1344     if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1345
1346     /* Check if we need to grow the block */
1347
1348     oldSize = (pArena->size & ARENA_SIZE_MASK);
1349     if (rounded_size > oldSize)
1350     {
1351         char *pNext = (char *)(pArena + 1) + oldSize;
1352         if ((pNext < (char *)subheap + subheap->size) &&
1353             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1354             (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1355         {
1356             /* The next block is free and large enough */
1357             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1358             list_remove( &pFree->entry );
1359             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1360             if (!HEAP_Commit( subheap, pArena, rounded_size ))
1361             {
1362                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1363                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1364                 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1365                 return NULL;
1366             }
1367             notify_free( pArena + 1 );
1368             HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1369             notify_alloc( pArena + 1, size, FALSE );
1370             /* FIXME: this is wrong as we may lose old VBits settings */
1371             mark_block_initialized( pArena + 1, oldSize );
1372         }
1373         else  /* Do it the hard way */
1374         {
1375             ARENA_FREE *pNew;
1376             ARENA_INUSE *pInUse;
1377             SUBHEAP *newsubheap;
1378
1379             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1380                 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1381             {
1382                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1383                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1384                 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1385                 return NULL;
1386             }
1387
1388             /* Build the in-use arena */
1389
1390             list_remove( &pNew->entry );
1391             pInUse = (ARENA_INUSE *)pNew;
1392             pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1393                            + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1394             pInUse->magic = ARENA_INUSE_MAGIC;
1395             HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1396             mark_block_initialized( pInUse + 1, oldSize );
1397             notify_alloc( pInUse + 1, size, FALSE );
1398             memcpy( pInUse + 1, pArena + 1, oldSize );
1399
1400             /* Free the previous block */
1401
1402             notify_free( pArena + 1 );
1403             HEAP_MakeInUseBlockFree( subheap, pArena );
1404             subheap = newsubheap;
1405             pArena  = pInUse;
1406         }
1407     }
1408     else
1409     {
1410         /* Shrink the block */
1411         notify_free( pArena + 1 );
1412         HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1413         notify_alloc( pArena + 1, size, FALSE );
1414         /* FIXME: this is wrong as we may lose old VBits settings */
1415         mark_block_initialized( pArena + 1, size );
1416     }
1417
1418     pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1419
1420     /* Clear the extra bytes if needed */
1421
1422     if (rounded_size > oldSize)
1423     {
1424         if (flags & HEAP_ZERO_MEMORY)
1425             clear_block( (char *)(pArena + 1) + oldSize,
1426                          (pArena->size & ARENA_SIZE_MASK) - oldSize );
1427         else
1428             mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1429                                       (pArena->size & ARENA_SIZE_MASK) - oldSize );
1430     }
1431
1432     /* Return the new arena */
1433
1434     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1435
1436     TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1437     return (LPVOID)(pArena + 1);
1438
1439 error:
1440     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1441     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1442     TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1443     return NULL;
1444 }
1445
1446
1447 /***********************************************************************
1448  *           RtlCompactHeap   (NTDLL.@)
1449  *
1450  * Compact the free space in a Heap.
1451  *
1452  * PARAMS
1453  *  heap  [I] Heap that block was allocated from
1454  *  flags [I] HEAP_ flags from "winnt.h"
1455  *
1456  * RETURNS
1457  *  The number of bytes compacted.
1458  *
1459  * NOTES
1460  *  This function is a harmless stub.
1461  */
1462 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1463 {
1464     static BOOL reported;
1465     if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1466     return 0;
1467 }
1468
1469
1470 /***********************************************************************
1471  *           RtlLockHeap   (NTDLL.@)
1472  *
1473  * Lock a Heap.
1474  *
1475  * PARAMS
1476  *  heap  [I] Heap to lock
1477  *
1478  * RETURNS
1479  *  Success: TRUE. The Heap is locked.
1480  *  Failure: FALSE, if heap is invalid.
1481  */
1482 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1483 {
1484     HEAP *heapPtr = HEAP_GetPtr( heap );
1485     if (!heapPtr) return FALSE;
1486     RtlEnterCriticalSection( &heapPtr->critSection );
1487     return TRUE;
1488 }
1489
1490
1491 /***********************************************************************
1492  *           RtlUnlockHeap   (NTDLL.@)
1493  *
1494  * Unlock a Heap.
1495  *
1496  * PARAMS
1497  *  heap  [I] Heap to unlock
1498  *
1499  * RETURNS
1500  *  Success: TRUE. The Heap is unlocked.
1501  *  Failure: FALSE, if heap is invalid.
1502  */
1503 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1504 {
1505     HEAP *heapPtr = HEAP_GetPtr( heap );
1506     if (!heapPtr) return FALSE;
1507     RtlLeaveCriticalSection( &heapPtr->critSection );
1508     return TRUE;
1509 }
1510
1511
1512 /***********************************************************************
1513  *           RtlSizeHeap   (NTDLL.@)
1514  *
1515  * Get the actual size of a memory block allocated from a Heap.
1516  *
1517  * PARAMS
1518  *  heap  [I] Heap that block was allocated from
1519  *  flags [I] HEAP_ flags from "winnt.h"
1520  *  ptr   [I] Block to get the size of
1521  *
1522  * RETURNS
1523  *  Success: The size of the block.
1524  *  Failure: -1, heap or ptr are invalid.
1525  *
1526  * NOTES
1527  *  The size may be bigger than what was passed to RtlAllocateHeap().
1528  */
1529 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1530 {
1531     SIZE_T ret;
1532     HEAP *heapPtr = HEAP_GetPtr( heap );
1533
1534     if (!heapPtr)
1535     {
1536         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1537         return ~0UL;
1538     }
1539     flags &= HEAP_NO_SERIALIZE;
1540     flags |= heapPtr->flags;
1541     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1542     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1543     {
1544         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1545         ret = ~0UL;
1546     }
1547     else
1548     {
1549         const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1550         ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1551     }
1552     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1553
1554     TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1555     return ret;
1556 }
1557
1558
1559 /***********************************************************************
1560  *           RtlValidateHeap   (NTDLL.@)
1561  *
1562  * Determine if a block is a valid allocation from a heap.
1563  *
1564  * PARAMS
1565  *  heap  [I] Heap that block was allocated from
1566  *  flags [I] HEAP_ flags from "winnt.h"
1567  *  ptr   [I] Block to check
1568  *
1569  * RETURNS
1570  *  Success: TRUE. The block was allocated from heap.
1571  *  Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1572  */
1573 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1574 {
1575     HEAP *heapPtr = HEAP_GetPtr( heap );
1576     if (!heapPtr) return FALSE;
1577     return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1578 }
1579
1580
1581 /***********************************************************************
1582  *           RtlWalkHeap    (NTDLL.@)
1583  *
1584  * FIXME
1585  *  The PROCESS_HEAP_ENTRY flag values seem different between this
1586  *  function and HeapWalk(). To be checked.
1587  */
1588 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1589 {
1590     LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1591     HEAP *heapPtr = HEAP_GetPtr(heap);
1592     SUBHEAP *sub, *currentheap = NULL;
1593     NTSTATUS ret;
1594     char *ptr;
1595     int region_index = 0;
1596
1597     if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1598
1599     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1600
1601     /* set ptr to the next arena to be examined */
1602
1603     if (!entry->lpData) /* first call (init) ? */
1604     {
1605         TRACE("begin walking of heap %p.\n", heap);
1606         currentheap = &heapPtr->subheap;
1607         ptr = (char*)currentheap + currentheap->headerSize;
1608     }
1609     else
1610     {
1611         ptr = entry->lpData;
1612         sub = &heapPtr->subheap;
1613         while (sub)
1614         {
1615             if (((char *)ptr >= (char *)sub) &&
1616                 ((char *)ptr < (char *)sub + sub->size))
1617             {
1618                 currentheap = sub;
1619                 break;
1620             }
1621             sub = sub->next;
1622             region_index++;
1623         }
1624         if (currentheap == NULL)
1625         {
1626             ERR("no matching subheap found, shouldn't happen !\n");
1627             ret = STATUS_NO_MORE_ENTRIES;
1628             goto HW_end;
1629         }
1630
1631         if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1632         {
1633             ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1634             ptr += pArena->size & ARENA_SIZE_MASK;
1635         }
1636         else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1637         {
1638             ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1639             ptr += pArena->size & ARENA_SIZE_MASK;
1640         }
1641         else
1642             ptr += entry->cbData; /* point to next arena */
1643
1644         if (ptr > (char *)currentheap + currentheap->size - 1)
1645         {   /* proceed with next subheap */
1646             if (!(currentheap = currentheap->next))
1647             {  /* successfully finished */
1648                 TRACE("end reached.\n");
1649                 ret = STATUS_NO_MORE_ENTRIES;
1650                 goto HW_end;
1651             }
1652             ptr = (char*)currentheap + currentheap->headerSize;
1653         }
1654     }
1655
1656     entry->wFlags = 0;
1657     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1658     {
1659         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1660
1661         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1662
1663         entry->lpData = pArena + 1;
1664         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1665         entry->cbOverhead = sizeof(ARENA_FREE);
1666         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1667     }
1668     else
1669     {
1670         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1671
1672         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1673
1674         entry->lpData = pArena + 1;
1675         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1676         entry->cbOverhead = sizeof(ARENA_INUSE);
1677         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1678         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1679         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1680     }
1681
1682     entry->iRegionIndex = region_index;
1683
1684     /* first element of heap ? */
1685     if (ptr == (char *)(currentheap + currentheap->headerSize))
1686     {
1687         entry->wFlags |= PROCESS_HEAP_REGION;
1688         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1689         entry->u.Region.dwUnCommittedSize =
1690                 currentheap->size - currentheap->commitSize;
1691         entry->u.Region.lpFirstBlock = /* first valid block */
1692                 currentheap + currentheap->headerSize;
1693         entry->u.Region.lpLastBlock  = /* first invalid block */
1694                 currentheap + currentheap->size;
1695     }
1696     ret = STATUS_SUCCESS;
1697     if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1698
1699 HW_end:
1700     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1701     return ret;
1702 }
1703
1704
1705 /***********************************************************************
1706  *           RtlGetProcessHeaps    (NTDLL.@)
1707  *
1708  * Get the Heaps belonging to the current process.
1709  *
1710  * PARAMS
1711  *  count [I] size of heaps
1712  *  heaps [O] Destination array for heap HANDLE's
1713  *
1714  * RETURNS
1715  *  Success: The number of Heaps allocated by the process.
1716  *  Failure: 0.
1717  */
1718 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1719 {
1720     ULONG total = 1;  /* main heap */
1721     struct list *ptr;
1722
1723     RtlEnterCriticalSection( &processHeap->critSection );
1724     LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1725     if (total <= count)
1726     {
1727         *heaps++ = processHeap;
1728         LIST_FOR_EACH( ptr, &processHeap->entry )
1729             *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1730     }
1731     RtlLeaveCriticalSection( &processHeap->critSection );
1732     return total;
1733 }