~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/ntdll/heap.c

Version: ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~ [ wine-1.0-rc5 ] ~ [ wine-1.0-rc4 ] ~ [ wine-1.0-rc3 ] ~ [ wine-1.0-rc2 ] ~ [ wine-1.0-rc1 ] ~ [ wine-0.9.61 ] ~ [ wine-0.9.60 ] ~ [ wine-0.9.59 ] ~ [ wine-0.9.58 ] ~ [ wine-0.9.57 ] ~ [ wine-0.9.56 ] ~ [ wine-0.9.55 ] ~ [ wine-0.9.54 ] ~ [ wine-0.9.53 ] ~ [ wine-0.9.52 ] ~ [ wine-0.9.51 ] ~ [ wine-0.9.50 ] ~ [ wine-0.9.49 ] ~ [ wine-0.9.48 ] ~ [ wine-0.9.47 ] ~ [ wine-0.9.46 ] ~ [ wine-0.9.45 ] ~ [ wine-0.9.44 ] ~ [ wine-0.9.43 ] ~ [ wine-0.9.42 ] ~ [ wine-0.9.41 ] ~ [ wine-0.9.40 ] ~ [ wine-0.9.39 ] ~ [ wine-0.9.38 ] ~ [ wine-0.9.37 ] ~ [ wine-0.9.36 ] ~ [ wine-0.9.35 ] ~ [ wine-0.9.34 ] ~ [ wine-0.9.33 ] ~ [ wine-0.9.32 ] ~ [ wine-0.9.31 ] ~ [ wine-0.9.30 ] ~ [ wine-0.9.29 ] ~ [ wine-0.9.28 ] ~ [ wine-0.9.27 ] ~ [ wine-0.9.26 ] ~ [ wine-0.9.25 ] ~ [ wine-0.9.24 ] ~ [ wine-0.9.23 ] ~ [ wine-0.9.22 ] ~ [ wine-0.9.21 ] ~ [ wine-0.9.20 ] ~ [ wine-0.9.19 ] ~ [ wine-0.9.18 ] ~ [ wine-0.9.17 ] ~ [ wine-0.9.16 ] ~ [ wine-0.9.15 ] ~ [ wine-0.9.14 ] ~ [ wine-0.9.13 ] ~ [ wine-0.9.12 ] ~ [ wine-0.9.11 ] ~ [ wine-0.9.10 ] ~ [ wine-0.9.9 ] ~ [ wine-0.9.8 ] ~ [ wine-0.9.7 ] ~ [ wine-0.9.6 ] ~ [ wine-0.9.5 ] ~ [ wine-0.9.4 ] ~ [ wine-0.9.3 ] ~ [ wine-0.9.2 ] ~ [ wine-0.9.1 ] ~ [ wine-0.9 ] ~ [ wine20050930 ] ~ [ wine20050830 ] ~ [ wine20050725 ] ~ [ wine20050628 ] ~ [ wine20050524 ] ~ [ wine20050419 ] ~ [ wine20050310 ] ~ [ wine20050211 ] ~ [ wine20050111 ] ~ [ wine20041201 ] ~ [ wine20041019 ] ~ [ wine20040914 ] ~ [ wine20040813 ] ~ [ wine20040716 ] ~ [ wine20040615 ] ~ [ wine20040505 ] ~ [ wine20040408 ] ~ [ wine20040309 ] ~ [ wine20040213 ] ~ [ wine20040121 ] ~ [ wine20031212 ] ~ [ wine20031118 ] ~ [ wine20031016 ] ~ [ wine20030911 ] ~ [ wine20030813 ] ~ [ wine20030709 ] ~ [ wine20030618 ] ~ [ wine20030508 ] ~ [ wine20030408 ] ~ [ wine20030318 ] ~ [ wine20030219 ] ~ [ wine20030115 ] ~ [ wine20021219 ] ~ [ wine20021125 ] ~ [ wine20021031 ] ~ [ wine20021007 ] ~ [ wine20020904 ] ~ [ wine20020804 ] ~ [ wine20020710 ] ~ [ wine20020605 ] ~ [ wine20020509 ] ~ [ wine20020411 ] ~ [ wine20020310 ] ~ [ wine20020228 ] ~ [ wine20011226 ] ~ [ wine20011108 ] ~ [ wine20011004 ] ~ [ wine20010824 ] ~ [ wine20010731 ] ~ [ wine20010629 ] ~ [ wine20010510 ] ~ [ wine20010418 ] ~ [ wine20010326 ] ~ [ wine20010305 ] ~ [ wine20010216 ] ~ [ wine20010112 ] ~ [ wine20001222 ] ~ [ wine20001202 ] ~ [ wine20001026 ] ~ [ wine20001002 ] ~ [ wine20000909 ] ~ [ wine20000821 ] ~ [ wine20000801 ] ~ [ wine20000716 ] ~ [ wine20000326 ] ~ [ wine20000227 ] ~ [ wine20000130 ] ~ [ wine20000109 ] ~

  1 /*
  2  * Win32 heap functions
  3  *
  4  * Copyright 1996 Alexandre Julliard
  5  * Copyright 1998 Ulrich Weigand
  6  *
  7  * This library is free software; you can redistribute it and/or
  8  * modify it under the terms of the GNU Lesser General Public
  9  * License as published by the Free Software Foundation; either
 10  * version 2.1 of the License, or (at your option) any later version.
 11  *
 12  * This library is distributed in the hope that it will be useful,
 13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 15  * Lesser General Public License for more details.
 16  *
 17  * You should have received a copy of the GNU Lesser General Public
 18  * License along with this library; if not, write to the Free Software
 19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 20  */
 21 
 22 #include "config.h"
 23 
 24 #include <assert.h>
 25 #include <stdlib.h>
 26 #include <stdarg.h>
 27 #include <stdio.h>
 28 #include <string.h>
 29 #ifdef HAVE_VALGRIND_MEMCHECK_H
 30 #include <valgrind/memcheck.h>
 31 #endif
 32 
 33 #define NONAMELESSUNION
 34 #define NONAMELESSSTRUCT
 35 #include "ntstatus.h"
 36 #define WIN32_NO_STATUS
 37 #include "windef.h"
 38 #include "winnt.h"
 39 #include "winternl.h"
 40 #include "wine/list.h"
 41 #include "wine/debug.h"
 42 #include "wine/server.h"
 43 
 44 WINE_DEFAULT_DEBUG_CHANNEL(heap);
 45 
 46 /* Note: the heap data structures are loosely based on what Pietrek describes in his
 47  * book 'Windows 95 System Programming Secrets', with some adaptations for
 48  * better compatibility with NT.
 49  */
 50 
 51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
 52  * that there is no unaligned accesses to structure fields.
 53  */
 54 
 55 typedef struct tagARENA_INUSE
 56 {
 57     DWORD  size;                    /* Block size; must be the first field */
 58     DWORD  magic : 24;              /* Magic number */
 59     DWORD  unused_bytes : 8;        /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
 60 } ARENA_INUSE;
 61 
 62 typedef struct tagARENA_FREE
 63 {
 64     DWORD                 size;     /* Block size; must be the first field */
 65     DWORD                 magic;    /* Magic number */
 66     struct list           entry;    /* Entry in free list */
 67 } ARENA_FREE;
 68 
 69 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
 70 #define ARENA_FLAG_PREV_FREE   0x00000002
 71 #define ARENA_SIZE_MASK        (~3)
 72 #define ARENA_INUSE_MAGIC      0x455355        /* Value for arena 'magic' field */
 73 #define ARENA_FREE_MAGIC       0x45455246      /* Value for arena 'magic' field */
 74 
 75 #define ARENA_INUSE_FILLER     0x55
 76 #define ARENA_FREE_FILLER      0xaa
 77 
 78 #define ALIGNMENT              8   /* everything is aligned on 8 byte boundaries */
 79 #define ROUND_SIZE(size)       (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
 80 
 81 #define QUIET                  1           /* Suppress messages  */
 82 #define NOISY                  0           /* Report all errors  */
 83 
 84 /* minimum data size (without arenas) of an allocated block */
 85 /* make sure that it's larger than a free list entry */
 86 #define HEAP_MIN_DATA_SIZE    (2 * sizeof(struct list))
 87 /* minimum size that must remain to shrink an allocated block */
 88 #define HEAP_MIN_SHRINK_SIZE  (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
 89 
 90 /* Max size of the blocks on the free lists */
 91 static const SIZE_T HEAP_freeListSizes[] =
 92 {
 93     0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
 94 };
 95 #define HEAP_NB_FREE_LISTS  (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
 96 
 97 typedef struct
 98 {
 99     ARENA_FREE  arena;
100 } FREE_LIST_ENTRY;
101 
102 struct tagHEAP;
103 
104 typedef struct tagSUBHEAP
105 {
106     void               *base;       /* Base address of the sub-heap memory block */
107     SIZE_T              size;       /* Size of the whole sub-heap */
108     SIZE_T              commitSize; /* Committed size of the sub-heap */
109     struct list         entry;      /* Entry in sub-heap list */
110     struct tagHEAP     *heap;       /* Main heap structure */
111     DWORD               headerSize; /* Size of the heap header */
112     DWORD               magic;      /* Magic number */
113 } SUBHEAP;
114 
115 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
116 
117 typedef struct tagHEAP
118 {
119     DWORD            unknown[3];
120     DWORD            flags;         /* Heap flags */
121     DWORD            force_flags;   /* Forced heap flags for debugging */
122     SUBHEAP          subheap;       /* First sub-heap */
123     struct list      entry;         /* Entry in process heap list */
124     struct list      subheap_list;  /* Sub-heap list */
125     DWORD            magic;         /* Magic number */
126     RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
127     FREE_LIST_ENTRY  freeList[HEAP_NB_FREE_LISTS];  /* Free lists */
128 } HEAP;
129 
130 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
131 
132 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
133 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
134 
135 static HEAP *processHeap;  /* main process heap */
136 
137 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
138 
139 /* mark a block of memory as free for debugging purposes */
140 static inline void mark_block_free( void *ptr, SIZE_T size )
141 {
142     if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
143 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
144     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
145 #elif defined( VALGRIND_MAKE_NOACCESS)
146     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
147 #endif
148 }
149 
150 /* mark a block of memory as initialized for debugging purposes */
151 static inline void mark_block_initialized( void *ptr, SIZE_T size )
152 {
153 #if defined(VALGRIND_MAKE_MEM_DEFINED)
154     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
155 #elif defined(VALGRIND_MAKE_READABLE)
156     VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
157 #endif
158 }
159 
160 /* mark a block of memory as uninitialized for debugging purposes */
161 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
162 {
163 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
164     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
165 #elif defined(VALGRIND_MAKE_WRITABLE)
166     VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
167 #endif
168     if (TRACE_ON(heap) || WARN_ON(heap))
169     {
170         memset( ptr, ARENA_INUSE_FILLER, size );
171 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
172         VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
173 #elif defined(VALGRIND_MAKE_WRITABLE)
174         /* make it uninitialized to valgrind again */
175         VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
176 #endif
177     }
178 }
179 
180 /* clear contents of a block of memory */
181 static inline void clear_block( void *ptr, SIZE_T size )
182 {
183     mark_block_initialized( ptr, size );
184     memset( ptr, 0, size );
185 }
186 
187 /* notify that a new block of memory has been allocated for debugging purposes */
188 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
189 {
190 #ifdef VALGRIND_MALLOCLIKE_BLOCK
191     VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
192 #endif
193 }
194 
195 /* notify that a block of memory has been freed for debugging purposes */
196 static inline void notify_free( void *ptr )
197 {
198 #ifdef VALGRIND_FREELIKE_BLOCK
199     VALGRIND_FREELIKE_BLOCK( ptr, 0 );
200 #endif
201 }
202 
203 /* locate a free list entry of the appropriate size */
204 /* size is the size of the whole block including the arena header */
205 static inline unsigned int get_freelist_index( SIZE_T size )
206 {
207     unsigned int i;
208 
209     size -= sizeof(ARENA_FREE);
210     for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
211     return i;
212 }
213 
214 /* get the memory protection type to use for a given heap */
215 static inline ULONG get_protection_type( DWORD flags )
216 {
217     return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
218 }
219 
220 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
221 {
222     0, 0, NULL,  /* will be set later */
223     { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
224       0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
225 };
226 
227 
228 /***********************************************************************
229  *           HEAP_Dump
230  */
231 static void HEAP_Dump( HEAP *heap )
232 {
233     int i;
234     SUBHEAP *subheap;
235     char *ptr;
236 
237     DPRINTF( "Heap: %p\n", heap );
238     DPRINTF( "Next: %p  Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
239     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
240 
241     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
242     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
243         DPRINTF( "%p free %08lx prev=%p next=%p\n",
244                  &heap->freeList[i].arena, HEAP_freeListSizes[i],
245                  LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
246                  LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
247 
248     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
249     {
250         SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
251         DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
252                  subheap, subheap->base, subheap->size, subheap->commitSize );
253 
254         DPRINTF( "\n Block    Arena   Stat   Size    Id\n" );
255         ptr = (char *)subheap->base + subheap->headerSize;
256         while (ptr < (char *)subheap->base + subheap->size)
257         {
258             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
259             {
260                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
261                 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
262                          pArena, pArena->magic,
263                          pArena->size & ARENA_SIZE_MASK,
264                          LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
265                          LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
266                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
267                 arenaSize += sizeof(ARENA_FREE);
268                 freeSize += pArena->size & ARENA_SIZE_MASK;
269             }
270             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
271             {
272                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
273                 DPRINTF( "%p %08x Used %08x back=%p\n",
274                         pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
275                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
276                 arenaSize += sizeof(ARENA_INUSE);
277                 usedSize += pArena->size & ARENA_SIZE_MASK;
278             }
279             else
280             {
281                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
282                 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
283                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
284                 arenaSize += sizeof(ARENA_INUSE);
285                 usedSize += pArena->size & ARENA_SIZE_MASK;
286             }
287         }
288         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
289               subheap->size, subheap->commitSize, freeSize, usedSize,
290               arenaSize, (arenaSize * 100) / subheap->size );
291     }
292 }
293 
294 
295 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
296 {
297     WORD rem_flags;
298     TRACE( "Dumping entry %p\n", entry );
299     TRACE( "lpData\t\t: %p\n", entry->lpData );
300     TRACE( "cbData\t\t: %08x\n", entry->cbData);
301     TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
302     TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
303     TRACE( "WFlags\t\t: ");
304     if (entry->wFlags & PROCESS_HEAP_REGION)
305         TRACE( "PROCESS_HEAP_REGION ");
306     if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
307         TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
308     if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
309         TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
310     if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
311         TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
312     if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
313         TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
314     rem_flags = entry->wFlags &
315         ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
316           PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
317           PROCESS_HEAP_ENTRY_DDESHARE);
318     if (rem_flags)
319         TRACE( "Unknown %08x", rem_flags);
320     TRACE( "\n");
321     if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
322         && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
323     {
324         /* Treat as block */
325         TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
326     }
327     if (entry->wFlags & PROCESS_HEAP_REGION)
328     {
329         TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
330         TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
331         TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
332         TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
333     }
334 }
335 
336 /***********************************************************************
337  *           HEAP_GetPtr
338  * RETURNS
339  *      Pointer to the heap
340  *      NULL: Failure
341  */
342 static HEAP *HEAP_GetPtr(
343              HANDLE heap /* [in] Handle to the heap */
344 ) {
345     HEAP *heapPtr = (HEAP *)heap;
346     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
347     {
348         ERR("Invalid heap %p!\n", heap );
349         return NULL;
350     }
351     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
352     {
353         HEAP_Dump( heapPtr );
354         assert( FALSE );
355         return NULL;
356     }
357     return heapPtr;
358 }
359 
360 
361 /***********************************************************************
362  *           HEAP_InsertFreeBlock
363  *
364  * Insert a free block into the free list.
365  */
366 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
367 {
368     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
369     if (last)
370     {
371         /* insert at end of free list, i.e. before the next free list entry */
372         pEntry++;
373         if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
374         list_add_before( &pEntry->arena.entry, &pArena->entry );
375     }
376     else
377     {
378         /* insert at head of free list */
379         list_add_after( &pEntry->arena.entry, &pArena->entry );
380     }
381     pArena->size |= ARENA_FLAG_FREE;
382 }
383 
384 
385 /***********************************************************************
386  *           HEAP_FindSubHeap
387  * Find the sub-heap containing a given address.
388  *
389  * RETURNS
390  *      Pointer: Success
391  *      NULL: Failure
392  */
393 static SUBHEAP *HEAP_FindSubHeap(
394                 const HEAP *heap, /* [in] Heap pointer */
395                 LPCVOID ptr ) /* [in] Address */
396 {
397     SUBHEAP *sub;
398     LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
399         if (((const char *)ptr >= (const char *)sub->base) &&
400             ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
401             return sub;
402     return NULL;
403 }
404 
405 
406 /***********************************************************************
407  *           HEAP_Commit
408  *
409  * Make sure the heap storage is committed for a given size in the specified arena.
410  */
411 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
412 {
413     void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
414     SIZE_T size = (char *)ptr - (char *)subheap->base;
415     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
416     if (size > subheap->size) size = subheap->size;
417     if (size <= subheap->commitSize) return TRUE;
418     size -= subheap->commitSize;
419     ptr = (char *)subheap->base + subheap->commitSize;
420     if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
421                                  &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
422     {
423         WARN("Could not commit %08lx bytes at %p for heap %p\n",
424                  size, ptr, subheap->heap );
425         return FALSE;
426     }
427     subheap->commitSize += size;
428     return TRUE;
429 }
430 
431 
432 /***********************************************************************
433  *           HEAP_Decommit
434  *
435  * If possible, decommit the heap storage from (including) 'ptr'.
436  */
437 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
438 {
439     void *addr;
440     SIZE_T decommit_size;
441     SIZE_T size = (char *)ptr - (char *)subheap->base;
442 
443     /* round to next block and add one full block */
444     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
445     if (size >= subheap->commitSize) return TRUE;
446     decommit_size = subheap->commitSize - size;
447     addr = (char *)subheap->base + size;
448 
449     if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
450     {
451         WARN("Could not decommit %08lx bytes at %p for heap %p\n",
452              decommit_size, (char *)subheap->base + size, subheap->heap );
453         return FALSE;
454     }
455     subheap->commitSize -= decommit_size;
456     return TRUE;
457 }
458 
459 
460 /***********************************************************************
461  *           HEAP_CreateFreeBlock
462  *
463  * Create a free block at a specified address. 'size' is the size of the
464  * whole block, including the new arena.
465  */
466 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
467 {
468     ARENA_FREE *pFree;
469     char *pEnd;
470     BOOL last;
471 
472     /* Create a free arena */
473     mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
474     pFree = (ARENA_FREE *)ptr;
475     pFree->magic = ARENA_FREE_MAGIC;
476 
477     /* If debugging, erase the freed block content */
478 
479     pEnd = (char *)ptr + size;
480     if (pEnd > (char *)subheap->base + subheap->commitSize)
481         pEnd = (char *)subheap->base + subheap->commitSize;
482     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
483 
484     /* Check if next block is free also */
485 
486     if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
487         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
488     {
489         /* Remove the next arena from the free list */
490         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
491         list_remove( &pNext->entry );
492         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
493         mark_block_free( pNext, sizeof(ARENA_FREE) );
494     }
495 
496     /* Set the next block PREV_FREE flag and pointer */
497 
498     last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
499     if (!last)
500     {
501         DWORD *pNext = (DWORD *)((char *)ptr + size);
502         *pNext |= ARENA_FLAG_PREV_FREE;
503         mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
504         *((ARENA_FREE **)pNext - 1) = pFree;
505     }
506 
507     /* Last, insert the new block into the free list */
508 
509     pFree->size = size - sizeof(*pFree);
510     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
511 }
512 
513 
514 /***********************************************************************
515  *           HEAP_MakeInUseBlockFree
516  *
517  * Turn an in-use block into a free block. Can also decommit the end of
518  * the heap, and possibly even free the sub-heap altogether.
519  */
520 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
521 {
522     ARENA_FREE *pFree;
523     SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
524 
525     /* Check if we can merge with previous block */
526 
527     if (pArena->size & ARENA_FLAG_PREV_FREE)
528     {
529         pFree = *((ARENA_FREE **)pArena - 1);
530         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
531         /* Remove it from the free list */
532         list_remove( &pFree->entry );
533     }
534     else pFree = (ARENA_FREE *)pArena;
535 
536     /* Create a free block */
537 
538     HEAP_CreateFreeBlock( subheap, pFree, size );
539     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
540     if ((char *)pFree + size < (char *)subheap->base + subheap->size)
541         return;  /* Not the last block, so nothing more to do */
542 
543     /* Free the whole sub-heap if it's empty and not the original one */
544 
545     if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
546         (subheap != &subheap->heap->subheap))
547     {
548         SIZE_T size = 0;
549         void *addr = subheap->base;
550         /* Remove the free block from the list */
551         list_remove( &pFree->entry );
552         /* Remove the subheap from the list */
553         list_remove( &subheap->entry );
554         /* Free the memory */
555         subheap->magic = 0;
556         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
557         return;
558     }
559 
560     /* Decommit the end of the heap */
561 
562     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
563 }
564 
565 
566 /***********************************************************************
567  *           HEAP_ShrinkBlock
568  *
569  * Shrink an in-use block.
570  */
571 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
572 {
573     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
574     {
575         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
576                               (pArena->size & ARENA_SIZE_MASK) - size );
577         /* assign size plus previous arena flags */
578         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
579     }
580     else
581     {
582         /* Turn off PREV_FREE flag in next block */
583         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
584         if (pNext < (char *)subheap->base + subheap->size)
585             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
586     }
587 }
588 
589 /***********************************************************************
590  *           HEAP_InitSubHeap
591  */
592 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
593                                   SIZE_T commitSize, SIZE_T totalSize )
594 {
595     SUBHEAP *subheap;
596     FREE_LIST_ENTRY *pEntry;
597     int i;
598 
599     /* Commit memory */
600 
601     if (flags & HEAP_SHARED)
602         commitSize = totalSize;  /* always commit everything in a shared heap */
603     if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
604                                  &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
605     {
606         WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
607         return NULL;
608     }
609 
610     if (heap)
611     {
612         /* If this is a secondary subheap, insert it into list */
613 
614         subheap = (SUBHEAP *)address;
615         subheap->base       = address;
616         subheap->heap       = heap;
617         subheap->size       = totalSize;
618         subheap->commitSize = commitSize;
619         subheap->magic      = SUBHEAP_MAGIC;
620         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
621         list_add_head( &heap->subheap_list, &subheap->entry );
622     }
623     else
624     {
625         /* If this is a primary subheap, initialize main heap */
626 
627         heap = (HEAP *)address;
628         heap->flags         = flags;
629         heap->magic         = HEAP_MAGIC;
630         list_init( &heap->subheap_list );
631 
632         subheap = &heap->subheap;
633         subheap->base       = address;
634         subheap->heap       = heap;
635         subheap->size       = totalSize;
636         subheap->commitSize = commitSize;
637         subheap->magic      = SUBHEAP_MAGIC;
638         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
639         list_add_head( &heap->subheap_list, &subheap->entry );
640 
641         /* Build the free lists */
642 
643         list_init( &heap->freeList[0].arena.entry );
644         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
645         {
646             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
647             pEntry->arena.magic = ARENA_FREE_MAGIC;
648             if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
649         }
650 
651         /* Initialize critical section */
652 
653         if (!processHeap)  /* do it by hand to avoid memory allocations */
654         {
655             heap->critSection.DebugInfo      = &process_heap_critsect_debug;
656             heap->critSection.LockCount      = -1;
657             heap->critSection.RecursionCount = 0;
658             heap->critSection.OwningThread   = 0;
659             heap->critSection.LockSemaphore  = 0;
660             heap->critSection.SpinCount      = 0;
661             process_heap_critsect_debug.CriticalSection = &heap->critSection;
662         }
663         else
664         {
665             RtlInitializeCriticalSection( &heap->critSection );
666             heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
667         }
668 
669         if (flags & HEAP_SHARED)
670         {
671             /* let's assume that only one thread at a time will try to do this */
672             HANDLE sem = heap->critSection.LockSemaphore;
673             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
674 
675             NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
676                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
677             heap->critSection.LockSemaphore = sem;
678             RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
679             heap->critSection.DebugInfo = NULL;
680         }
681     }
682 
683     /* Create the first free block */
684 
685     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
686                           subheap->size - subheap->headerSize );
687 
688     return subheap;
689 }
690 
691 /***********************************************************************
692  *           HEAP_CreateSubHeap
693  *
694  * Create a sub-heap of the given size.
695  * If heap == NULL, creates a main heap.
696  */
697 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
698                                     SIZE_T commitSize, SIZE_T totalSize )
699 {
700     LPVOID address = base;
701     SUBHEAP *ret;
702 
703     /* round-up sizes on a 64K boundary */
704     totalSize  = (totalSize + 0xffff) & 0xffff0000;
705     commitSize = (commitSize + 0xffff) & 0xffff0000;
706     if (!commitSize) commitSize = 0x10000;
707     if (totalSize < commitSize) totalSize = commitSize;
708 
709     if (!address)
710     {
711         /* allocate the memory block */
712         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
713                                      MEM_RESERVE, get_protection_type( flags ) ))
714         {
715             WARN("Could not allocate %08lx bytes\n", totalSize );
716             return NULL;
717         }
718     }
719 
720     /* Initialize subheap */
721 
722     if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
723     {
724         SIZE_T size = 0;
725         if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
726     }
727     return ret;
728 }
729 
730 
731 /***********************************************************************
732  *           HEAP_FindFreeBlock
733  *
734  * Find a free block at least as large as the requested size, and make sure
735  * the requested size is committed.
736  */
737 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
738                                        SUBHEAP **ppSubHeap )
739 {
740     SUBHEAP *subheap;
741     struct list *ptr;
742     SIZE_T total_size;
743     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
744 
745     /* Find a suitable free list, and in it find a block large enough */
746 
747     ptr = &pEntry->arena.entry;
748     while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
749     {
750         ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
751         SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
752                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
753         if (arena_size >= size)
754         {
755             subheap = HEAP_FindSubHeap( heap, pArena );
756             if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
757             *ppSubHeap = subheap;
758             return pArena;
759         }
760     }
761 
762     /* If no block was found, attempt to grow the heap */
763 
764     if (!(heap->flags & HEAP_GROWABLE))
765     {
766         WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
767         return NULL;
768     }
769     /* make sure that we have a big enough size *committed* to fit another
770      * last free arena in !
771      * So just one heap struct, one first free arena which will eventually
772      * get used, and a second free arena that might get assigned all remaining
773      * free space in HEAP_ShrinkBlock() */
774     total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
775     if (total_size < size) return NULL;  /* overflow */
776 
777     if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
778                                         max( HEAP_DEF_SIZE, total_size ) )))
779         return NULL;
780 
781     TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
782             subheap, total_size, heap );
783 
784     *ppSubHeap = subheap;
785     return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
786 }
787 
788 
789 /***********************************************************************
790  *           HEAP_IsValidArenaPtr
791  *
792  * Check that the pointer is inside the range possible for arenas.
793  */
794 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
795 {
796     int i;
797     const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
798     if (!subheap) return FALSE;
799     if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
800     if (subheap != &heap->subheap) return FALSE;
801     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
802         if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
803     return FALSE;
804 }
805 
806 
807 /***********************************************************************
808  *           HEAP_ValidateFreeArena
809  */
810 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
811 {
812     ARENA_FREE *prev, *next;
813     char *heapEnd = (char *)subheap->base + subheap->size;
814 
815     /* Check for unaligned pointers */
816     if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
817     {
818         ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
819         return FALSE;
820     }
821 
822     /* Check magic number */
823     if (pArena->magic != ARENA_FREE_MAGIC)
824     {
825         ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
826         return FALSE;
827     }
828     /* Check size flags */
829     if (!(pArena->size & ARENA_FLAG_FREE) ||
830         (pArena->size & ARENA_FLAG_PREV_FREE))
831     {
832         ERR("Heap %p: bad flags %08x for free arena %p\n",
833             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
834         return FALSE;
835     }
836     /* Check arena size */
837     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
838     {
839         ERR("Heap %p: bad size %08x for free arena %p\n",
840             subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
841         return FALSE;
842     }
843     /* Check that next pointer is valid */
844     next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
845     if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
846     {
847         ERR("Heap %p: bad next ptr %p for arena %p\n",
848             subheap->heap, next, pArena );
849         return FALSE;
850     }
851     /* Check that next arena is free */
852     if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
853     {
854         ERR("Heap %p: next arena %p invalid for %p\n",
855             subheap->heap, next, pArena );
856         return FALSE;
857     }
858     /* Check that prev pointer is valid */
859     prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
860     if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
861     {
862         ERR("Heap %p: bad prev ptr %p for arena %p\n",
863             subheap->heap, prev, pArena );
864         return FALSE;
865     }
866     /* Check that prev arena is free */
867     if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
868     {
869         /* this often means that the prev arena got overwritten
870          * by a memory write before that prev arena */
871         ERR("Heap %p: prev arena %p invalid for %p\n",
872             subheap->heap, prev, pArena );
873         return FALSE;
874     }
875     /* Check that next block has PREV_FREE flag */
876     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
877     {
878         if (!(*(DWORD *)((char *)(pArena + 1) +
879             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
880         {
881             ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
882                 subheap->heap, pArena );
883             return FALSE;
884         }
885         /* Check next block back pointer */
886         if (*((ARENA_FREE **)((char *)(pArena + 1) +
887             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
888         {
889             ERR("Heap %p: arena %p has wrong back ptr %p\n",
890                 subheap->heap, pArena,
891                 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
892             return FALSE;
893         }
894     }
895     return TRUE;
896 }
897 
898 
899 /***********************************************************************
900  *           HEAP_ValidateInUseArena
901  */
902 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
903 {
904     const char *heapEnd = (const char *)subheap->base + subheap->size;
905 
906     /* Check for unaligned pointers */
907     if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
908     {
909         if ( quiet == NOISY )
910         {
911             ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
912             if ( TRACE_ON(heap) )
913                 HEAP_Dump( subheap->heap );
914         }
915         else if ( WARN_ON(heap) )
916         {
917             WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
918             if ( TRACE_ON(heap) )
919                 HEAP_Dump( subheap->heap );
920         }
921         return FALSE;
922     }
923 
924     /* Check magic number */
925     if (pArena->magic != ARENA_INUSE_MAGIC)
926     {
927         if (quiet == NOISY) {
928             ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
929             if (TRACE_ON(heap))
930                HEAP_Dump( subheap->heap );
931         }  else if (WARN_ON(heap)) {
932             WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
933             if (TRACE_ON(heap))
934                HEAP_Dump( subheap->heap );
935         }
936         return FALSE;
937     }
938     /* Check size flags */
939     if (pArena->size & ARENA_FLAG_FREE)
940     {
941         ERR("Heap %p: bad flags %08x for in-use arena %p\n",
942             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
943         return FALSE;
944     }
945     /* Check arena size */
946     if ((const char *)(pArena + 1) + (pArena->size &