4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
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.
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.
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
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap
);
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
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.
57 typedef struct tagARENA_INUSE
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) */
64 typedef struct tagARENA_FREE
66 DWORD size
; /* Block size; must be the first field */
67 DWORD magic
; /* Magic number */
68 struct list entry
; /* Entry in free list */
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 */
77 #define ARENA_INUSE_FILLER 0x55
78 #define ARENA_FREE_FILLER 0xaa
80 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
81 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
83 #define QUIET 1 /* Suppress messages */
84 #define NOISY 0 /* Report all errors */
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))
92 /* Max size of the blocks on the free lists */
93 static const DWORD HEAP_freeListSizes
[] =
95 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
97 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
106 typedef struct tagSUBHEAP
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 */
116 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
118 typedef struct tagHEAP
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 */
128 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
130 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
131 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
133 static HEAP
*processHeap
; /* main process heap */
135 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
137 /* mark a block of memory as free for debugging purposes */
138 static inline void mark_block_free( void *ptr
, SIZE_T size
)
140 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
141 #ifdef VALGRIND_MAKE_NOACCESS
142 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
146 /* mark a block of memory as initialized for debugging purposes */
147 static inline void mark_block_initialized( void *ptr
, SIZE_T size
)
149 #ifdef VALGRIND_MAKE_READABLE
150 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
154 /* mark a block of memory as uninitialized for debugging purposes */
155 static inline void mark_block_uninitialized( void *ptr
, SIZE_T size
)
157 #ifdef VALGRIND_MAKE_WRITABLE
158 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
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
));
170 /* clear contents of a block of memory */
171 static inline void clear_block( void *ptr
, SIZE_T size
)
173 mark_block_initialized( ptr
, size
);
174 memset( ptr
, 0, size
);
177 /* locate a free list entry of the appropriate size */
178 /* size is the size of the whole block including the arena header */
179 static inline unsigned int get_freelist_index( SIZE_T size
)
183 size
-= sizeof(ARENA_FREE
);
184 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
188 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
190 0, 0, NULL
, /* will be set later */
191 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
192 0, 0, { (DWORD_PTR
)(__FILE__
": main process heap section") }
196 /***********************************************************************
199 static void HEAP_Dump( HEAP
*heap
)
205 DPRINTF( "Heap: %p\n", heap
);
206 DPRINTF( "Next: %p Sub-heaps: %p",
207 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
208 subheap
= &heap
->subheap
;
209 while (subheap
->next
)
211 DPRINTF( " -> %p", subheap
->next
);
212 subheap
= subheap
->next
;
215 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
216 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
217 DPRINTF( "%p free %08x prev=%p next=%p\n",
218 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
219 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
220 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
222 subheap
= &heap
->subheap
;
225 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
226 DPRINTF( "\n\nSub-heap %p: size=%08x committed=%08x\n",
227 subheap
, subheap
->size
, subheap
->commitSize
);
229 DPRINTF( "\n Block Stat Size Id\n" );
230 ptr
= (char*)subheap
+ subheap
->headerSize
;
231 while (ptr
< (char *)subheap
+ subheap
->size
)
233 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
235 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
236 DPRINTF( "%p free %08x prev=%p next=%p\n",
237 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
238 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
239 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
240 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
241 arenaSize
+= sizeof(ARENA_FREE
);
242 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
244 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
246 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
247 DPRINTF( "%p Used %08x back=%p\n",
248 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
249 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
250 arenaSize
+= sizeof(ARENA_INUSE
);
251 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
255 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
256 DPRINTF( "%p used %08x\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
257 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
258 arenaSize
+= sizeof(ARENA_INUSE
);
259 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
262 DPRINTF( "\nTotal: Size=%08x Committed=%08x Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
263 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
264 arenaSize
, (arenaSize
* 100) / subheap
->size
);
265 subheap
= subheap
->next
;
270 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
273 TRACE( "Dumping entry %p\n", entry
);
274 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
275 TRACE( "cbData\t\t: %08x\n", entry
->cbData
);
276 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
277 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
278 TRACE( "WFlags\t\t: ");
279 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
280 TRACE( "PROCESS_HEAP_REGION ");
281 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
282 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
283 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
284 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
285 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
286 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
287 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
288 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
289 rem_flags
= entry
->wFlags
&
290 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
291 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
292 PROCESS_HEAP_ENTRY_DDESHARE
);
294 TRACE( "Unknown %08x", rem_flags
);
296 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
297 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
300 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->u
.Block
.hMem
);
302 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
304 TRACE( "Region.dwCommittedSize\t:%08x\n",entry
->u
.Region
.dwCommittedSize
);
305 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry
->u
.Region
.dwUnCommittedSize
);
306 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->u
.Region
.lpFirstBlock
);
307 TRACE( "Region.lpLastBlock\t:%p\n",entry
->u
.Region
.lpLastBlock
);
311 /***********************************************************************
314 * Pointer to the heap
317 static HEAP
*HEAP_GetPtr(
318 HANDLE heap
/* [in] Handle to the heap */
320 HEAP
*heapPtr
= (HEAP
*)heap
;
321 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
323 ERR("Invalid heap %p!\n", heap
);
326 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
328 HEAP_Dump( heapPtr
);
336 /***********************************************************************
337 * HEAP_InsertFreeBlock
339 * Insert a free block into the free list.
341 static inline void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
343 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
346 /* insert at end of free list, i.e. before the next free list entry */
348 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
349 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
353 /* insert at head of free list */
354 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
356 pArena
->size
|= ARENA_FLAG_FREE
;
360 /***********************************************************************
362 * Find the sub-heap containing a given address.
368 static SUBHEAP
*HEAP_FindSubHeap(
369 const HEAP
*heap
, /* [in] Heap pointer */
370 LPCVOID ptr
/* [in] Address */
372 const SUBHEAP
*sub
= &heap
->subheap
;
375 if (((const char *)ptr
>= (const char *)sub
) &&
376 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
383 /***********************************************************************
386 * Make sure the heap storage is committed for a given size in the specified arena.
388 static inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
390 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
391 SIZE_T size
= (char *)ptr
- (char *)subheap
;
392 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
393 if (size
> subheap
->size
) size
= subheap
->size
;
394 if (size
<= subheap
->commitSize
) return TRUE
;
395 size
-= subheap
->commitSize
;
396 ptr
= (char *)subheap
+ subheap
->commitSize
;
397 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
398 &size
, MEM_COMMIT
, PAGE_READWRITE
))
400 WARN("Could not commit %08lx bytes at %p for heap %p\n",
401 size
, ptr
, subheap
->heap
);
404 subheap
->commitSize
+= size
;
409 /***********************************************************************
412 * If possible, decommit the heap storage from (including) 'ptr'.
414 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
417 SIZE_T decommit_size
;
418 SIZE_T size
= (char *)ptr
- (char *)subheap
;
420 /* round to next block and add one full block */
421 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
422 if (size
>= subheap
->commitSize
) return TRUE
;
423 decommit_size
= subheap
->commitSize
- size
;
424 addr
= (char *)subheap
+ size
;
426 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
428 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
429 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
432 subheap
->commitSize
-= decommit_size
;
437 /***********************************************************************
438 * HEAP_CreateFreeBlock
440 * Create a free block at a specified address. 'size' is the size of the
441 * whole block, including the new arena.
443 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
449 /* Create a free arena */
450 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
451 pFree
= (ARENA_FREE
*)ptr
;
452 pFree
->magic
= ARENA_FREE_MAGIC
;
454 /* If debugging, erase the freed block content */
456 pEnd
= (char *)ptr
+ size
;
457 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
458 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
460 /* Check if next block is free also */
462 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
463 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
465 /* Remove the next arena from the free list */
466 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
467 list_remove( &pNext
->entry
);
468 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
469 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
472 /* Set the next block PREV_FREE flag and pointer */
474 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
477 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
478 *pNext
|= ARENA_FLAG_PREV_FREE
;
479 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
480 *((ARENA_FREE
**)pNext
- 1) = pFree
;
483 /* Last, insert the new block into the free list */
485 pFree
->size
= size
- sizeof(*pFree
);
486 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
490 /***********************************************************************
491 * HEAP_MakeInUseBlockFree
493 * Turn an in-use block into a free block. Can also decommit the end of
494 * the heap, and possibly even free the sub-heap altogether.
496 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
499 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
501 /* Check if we can merge with previous block */
503 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
505 pFree
= *((ARENA_FREE
**)pArena
- 1);
506 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
507 /* Remove it from the free list */
508 list_remove( &pFree
->entry
);
510 else pFree
= (ARENA_FREE
*)pArena
;
512 /* Create a free block */
514 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
515 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
516 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
517 return; /* Not the last block, so nothing more to do */
519 /* Free the whole sub-heap if it's empty and not the original one */
521 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
522 (subheap
!= &subheap
->heap
->subheap
))
525 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
526 /* Remove the free block from the list */
527 list_remove( &pFree
->entry
);
528 /* Remove the subheap from the list */
529 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
530 if (pPrev
) pPrev
->next
= subheap
->next
;
531 /* Free the memory */
533 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
537 /* Decommit the end of the heap */
539 if (!(subheap
->heap
->flags
& HEAP_SHARED
)) HEAP_Decommit( subheap
, pFree
+ 1 );
543 /***********************************************************************
546 * Shrink an in-use block.
548 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
550 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
552 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
553 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
554 /* assign size plus previous arena flags */
555 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
559 /* Turn off PREV_FREE flag in next block */
560 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
561 if (pNext
< (char *)subheap
+ subheap
->size
)
562 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
566 /***********************************************************************
569 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
570 SIZE_T commitSize
, SIZE_T totalSize
)
573 FREE_LIST_ENTRY
*pEntry
;
578 if (flags
& HEAP_SHARED
)
579 commitSize
= totalSize
; /* always commit everything in a shared heap */
580 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
581 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
583 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
587 /* Fill the sub-heap structure */
589 subheap
= (SUBHEAP
*)address
;
590 subheap
->heap
= heap
;
591 subheap
->size
= totalSize
;
592 subheap
->commitSize
= commitSize
;
593 subheap
->magic
= SUBHEAP_MAGIC
;
595 if ( subheap
!= (SUBHEAP
*)heap
)
597 /* If this is a secondary subheap, insert it into list */
599 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
600 subheap
->next
= heap
->subheap
.next
;
601 heap
->subheap
.next
= subheap
;
605 /* If this is a primary subheap, initialize main heap */
607 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
608 subheap
->next
= NULL
;
610 heap
->magic
= HEAP_MAGIC
;
612 /* Build the free lists */
614 list_init( &heap
->freeList
[0].arena
.entry
);
615 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
617 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
618 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
619 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
622 /* Initialize critical section */
624 if (!processHeap
) /* do it by hand to avoid memory allocations */
626 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
627 heap
->critSection
.LockCount
= -1;
628 heap
->critSection
.RecursionCount
= 0;
629 heap
->critSection
.OwningThread
= 0;
630 heap
->critSection
.LockSemaphore
= 0;
631 heap
->critSection
.SpinCount
= 0;
632 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
634 else RtlInitializeCriticalSection( &heap
->critSection
);
636 if (flags
& HEAP_SHARED
)
638 /* let's assume that only one thread at a time will try to do this */
639 HANDLE sem
= heap
->critSection
.LockSemaphore
;
640 if (!sem
) NtCreateSemaphore( &sem
, SEMAPHORE_ALL_ACCESS
, NULL
, 0, 1 );
642 NtDuplicateObject( NtCurrentProcess(), sem
, NtCurrentProcess(), &sem
, 0, 0,
643 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
644 heap
->critSection
.LockSemaphore
= sem
;
648 /* Create the first free block */
650 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
651 subheap
->size
- subheap
->headerSize
);
656 /***********************************************************************
659 * Create a sub-heap of the given size.
660 * If heap == NULL, creates a main heap.
662 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
663 SIZE_T commitSize
, SIZE_T totalSize
)
665 LPVOID address
= base
;
667 /* round-up sizes on a 64K boundary */
668 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
669 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
670 if (!commitSize
) commitSize
= 0x10000;
671 if (totalSize
< commitSize
) totalSize
= commitSize
;
675 /* allocate the memory block */
676 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
677 MEM_RESERVE
, PAGE_READWRITE
))
679 WARN("Could not allocate %08lx bytes\n", totalSize
);
684 /* Initialize subheap */
686 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
687 address
, flags
, commitSize
, totalSize
))
690 if (!base
) NtFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
694 return (SUBHEAP
*)address
;
698 /***********************************************************************
701 * Find a free block at least as large as the requested size, and make sure
702 * the requested size is committed.
704 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
705 SUBHEAP
**ppSubHeap
)
709 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
711 /* Find a suitable free list, and in it find a block large enough */
713 ptr
= &pEntry
->arena
.entry
;
714 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
716 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
717 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
718 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
719 if (arena_size
>= size
)
721 subheap
= HEAP_FindSubHeap( heap
, pArena
);
722 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
723 *ppSubHeap
= subheap
;
728 /* If no block was found, attempt to grow the heap */
730 if (!(heap
->flags
& HEAP_GROWABLE
))
732 WARN("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
735 /* make sure that we have a big enough size *committed* to fit another
736 * last free arena in !
737 * So just one heap struct, one first free arena which will eventually
738 * get used, and a second free arena that might get assigned all remaining
739 * free space in HEAP_ShrinkBlock() */
740 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
741 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
742 max( HEAP_DEF_SIZE
, size
) )))
745 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
746 subheap
, size
, heap
);
748 *ppSubHeap
= subheap
;
749 return (ARENA_FREE
*)(subheap
+ 1);
753 /***********************************************************************
754 * HEAP_IsValidArenaPtr
756 * Check that the pointer is inside the range possible for arenas.
758 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
761 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
762 if (!subheap
) return FALSE
;
763 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
764 if (subheap
!= &heap
->subheap
) return FALSE
;
765 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
766 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
771 /***********************************************************************
772 * HEAP_ValidateFreeArena
774 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
776 ARENA_FREE
*prev
, *next
;
777 char *heapEnd
= (char *)subheap
+ subheap
->size
;
779 /* Check for unaligned pointers */
780 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
782 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
786 /* Check magic number */
787 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
789 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
792 /* Check size flags */
793 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
794 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
796 ERR("Heap %p: bad flags %08x for free arena %p\n",
797 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
800 /* Check arena size */
801 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
803 ERR("Heap %p: bad size %08x for free arena %p\n",
804 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
807 /* Check that next pointer is valid */
808 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
809 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
811 ERR("Heap %p: bad next ptr %p for arena %p\n",
812 subheap
->heap
, next
, pArena
);
815 /* Check that next arena is free */
816 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
818 ERR("Heap %p: next arena %p invalid for %p\n",
819 subheap
->heap
, next
, pArena
);
822 /* Check that prev pointer is valid */
823 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
824 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
826 ERR("Heap %p: bad prev ptr %p for arena %p\n",
827 subheap
->heap
, prev
, pArena
);
830 /* Check that prev arena is free */
831 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
833 /* this often means that the prev arena got overwritten
834 * by a memory write before that prev arena */
835 ERR("Heap %p: prev arena %p invalid for %p\n",
836 subheap
->heap
, prev
, pArena
);
839 /* Check that next block has PREV_FREE flag */
840 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
842 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
843 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
845 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
846 subheap
->heap
, pArena
);
849 /* Check next block back pointer */
850 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
851 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
853 ERR("Heap %p: arena %p has wrong back ptr %p\n",
854 subheap
->heap
, pArena
,
855 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
863 /***********************************************************************
864 * HEAP_ValidateInUseArena
866 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
868 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
870 /* Check for unaligned pointers */
871 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
873 if ( quiet
== NOISY
)
875 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
876 if ( TRACE_ON(heap
) )
877 HEAP_Dump( subheap
->heap
);
879 else if ( WARN_ON(heap
) )
881 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
882 if ( TRACE_ON(heap
) )
883 HEAP_Dump( subheap
->heap
);
888 /* Check magic number */
889 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
891 if (quiet
== NOISY
) {
892 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
894 HEAP_Dump( subheap
->heap
);
895 } else if (WARN_ON(heap
)) {
896 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
898 HEAP_Dump( subheap
->heap
);
902 /* Check size flags */
903 if (pArena
->size
& ARENA_FLAG_FREE
)
905 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
906 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
909 /* Check arena size */
910 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
912 ERR("Heap %p: bad size %08x for in-use arena %p\n",
913 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
916 /* Check next arena PREV_FREE flag */
917 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
918 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
920 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
921 subheap
->heap
, pArena
);
924 /* Check prev free arena */
925 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
927 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
928 /* Check prev pointer */
929 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
931 ERR("Heap %p: bad back ptr %p for arena %p\n",
932 subheap
->heap
, pPrev
, pArena
);
935 /* Check that prev arena is free */
936 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
937 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
939 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
940 subheap
->heap
, pPrev
, pArena
);
943 /* Check that prev arena is really the previous block */
944 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
946 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
947 subheap
->heap
, pPrev
, pArena
);
955 /***********************************************************************
956 * HEAP_IsRealArena [Internal]
957 * Validates a block is a valid arena.
963 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
964 DWORD flags
, /* [in] Bit flags that control access during operation */
965 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
966 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
967 * does not complain */
972 flags
&= HEAP_NO_SERIALIZE
;
973 flags
|= heapPtr
->flags
;
974 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
975 if (!(flags
& HEAP_NO_SERIALIZE
))
976 RtlEnterCriticalSection( &heapPtr
->critSection
);
980 /* Only check this single memory block */
982 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
983 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
984 + sizeof(ARENA_INUSE
)))
987 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
988 else if (WARN_ON(heap
))
989 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
992 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
994 if (!(flags
& HEAP_NO_SERIALIZE
))
995 RtlLeaveCriticalSection( &heapPtr
->critSection
);
999 subheap
= &heapPtr
->subheap
;
1000 while (subheap
&& ret
)
1002 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1003 while (ptr
< (char *)subheap
+ subheap
->size
)
1005 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1007 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1011 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1015 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1019 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1022 subheap
= subheap
->next
;
1025 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1030 /***********************************************************************
1031 * RtlCreateHeap (NTDLL.@)
1033 * Create a new Heap.
1036 * flags [I] HEAP_ flags from "winnt.h"
1037 * addr [I] Desired base address
1038 * totalSize [I] Total size of the heap, or 0 for a growable heap
1039 * commitSize [I] Amount of heap space to commit
1040 * unknown [I] Not yet understood
1041 * definition [I] Heap definition
1044 * Success: A HANDLE to the newly created heap.
1045 * Failure: a NULL HANDLE.
1047 HANDLE WINAPI
RtlCreateHeap( ULONG flags
, PVOID addr
, SIZE_T totalSize
, SIZE_T commitSize
,
1048 PVOID unknown
, PRTL_HEAP_DEFINITION definition
)
1052 /* Allocate the heap block */
1056 totalSize
= HEAP_DEF_SIZE
;
1057 flags
|= HEAP_GROWABLE
;
1060 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
))) return 0;
1062 /* link it into the per-process heap list */
1065 HEAP
*heapPtr
= subheap
->heap
;
1066 RtlEnterCriticalSection( &processHeap
->critSection
);
1067 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1068 RtlLeaveCriticalSection( &processHeap
->critSection
);
1072 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1073 list_init( &processHeap
->entry
);
1076 return (HANDLE
)subheap
;
1080 /***********************************************************************
1081 * RtlDestroyHeap (NTDLL.@)
1083 * Destroy a Heap created with RtlCreateHeap().
1086 * heap [I] Heap to destroy.
1089 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1090 * Failure: The Heap handle, if heap is the process heap.
1092 HANDLE WINAPI
RtlDestroyHeap( HANDLE heap
)
1094 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1097 TRACE("%p\n", heap
);
1098 if (!heapPtr
) return heap
;
1100 if (heap
== processHeap
) return heap
; /* cannot delete the main process heap */
1102 /* remove it from the per-process list */
1103 RtlEnterCriticalSection( &processHeap
->critSection
);
1104 list_remove( &heapPtr
->entry
);
1105 RtlLeaveCriticalSection( &processHeap
->critSection
);
1107 RtlDeleteCriticalSection( &heapPtr
->critSection
);
1108 subheap
= &heapPtr
->subheap
;
1111 SUBHEAP
*next
= subheap
->next
;
1113 void *addr
= subheap
;
1114 NtFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1121 /***********************************************************************
1122 * RtlAllocateHeap (NTDLL.@)
1124 * Allocate a memory block from a Heap.
1127 * heap [I] Heap to allocate block from
1128 * flags [I] HEAP_ flags from "winnt.h"
1129 * size [I] Size of the memory block to allocate
1132 * Success: A pointer to the newly allocated block
1136 * This call does not SetLastError().
1138 PVOID WINAPI
RtlAllocateHeap( HANDLE heap
, ULONG flags
, SIZE_T size
)
1141 ARENA_INUSE
*pInUse
;
1143 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1144 SIZE_T rounded_size
;
1146 /* Validate the parameters */
1148 if (!heapPtr
) return NULL
;
1149 flags
&= HEAP_GENERATE_EXCEPTIONS
| HEAP_NO_SERIALIZE
| HEAP_ZERO_MEMORY
;
1150 flags
|= heapPtr
->flags
;
1151 rounded_size
= ROUND_SIZE(size
);
1152 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1154 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterCriticalSection( &heapPtr
->critSection
);
1155 /* Locate a suitable free block */
1157 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1159 TRACE("(%p,%08x,%08lx): returning NULL\n",
1160 heap
, flags
, size
);
1161 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1162 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1166 /* Remove the arena from the free list */
1168 list_remove( &pArena
->entry
);
1170 /* Build the in-use arena */
1172 pInUse
= (ARENA_INUSE
*)pArena
;
1174 /* in-use arena is smaller than free arena,
1175 * so we have to add the difference to the size */
1176 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1177 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1179 /* Shrink the block */
1181 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1182 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1184 if (flags
& HEAP_ZERO_MEMORY
)
1185 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1187 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1189 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1191 TRACE("(%p,%08x,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1192 return (LPVOID
)(pInUse
+ 1);
1196 /***********************************************************************
1197 * RtlFreeHeap (NTDLL.@)
1199 * Free a memory block allocated with RtlAllocateHeap().
1202 * heap [I] Heap that block was allocated from
1203 * flags [I] HEAP_ flags from "winnt.h"
1204 * ptr [I] Block to free
1207 * Success: TRUE, if ptr is NULL or was freed successfully.
1210 BOOLEAN WINAPI
RtlFreeHeap( HANDLE heap
, ULONG flags
, PVOID ptr
)
1212 ARENA_INUSE
*pInUse
;
1216 /* Validate the parameters */
1218 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1220 heapPtr
= HEAP_GetPtr( heap
);
1223 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1227 flags
&= HEAP_NO_SERIALIZE
;
1228 flags
|= heapPtr
->flags
;
1229 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterCriticalSection( &heapPtr
->critSection
);
1231 /* Some sanity checks */
1233 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1234 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
))) goto error
;
1235 if ((char *)pInUse
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1236 if (!HEAP_ValidateInUseArena( subheap
, pInUse
, QUIET
)) goto error
;
1238 /* Turn the block into a free block */
1240 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1242 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1244 TRACE("(%p,%08x,%p): returning TRUE\n", heap
, flags
, ptr
);
1248 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1249 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1250 TRACE("(%p,%08x,%p): returning FALSE\n", heap
, flags
, ptr
);
1255 /***********************************************************************
1256 * RtlReAllocateHeap (NTDLL.@)
1258 * Change the size of a memory block allocated with RtlAllocateHeap().
1261 * heap [I] Heap that block was allocated from
1262 * flags [I] HEAP_ flags from "winnt.h"
1263 * ptr [I] Block to resize
1264 * size [I] Size of the memory block to allocate
1267 * Success: A pointer to the resized block (which may be different).
1270 PVOID WINAPI
RtlReAllocateHeap( HANDLE heap
, ULONG flags
, PVOID ptr
, SIZE_T size
)
1272 ARENA_INUSE
*pArena
;
1275 SIZE_T oldSize
, rounded_size
;
1277 if (!ptr
) return NULL
;
1278 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1280 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1284 /* Validate the parameters */
1286 flags
&= HEAP_GENERATE_EXCEPTIONS
| HEAP_NO_SERIALIZE
| HEAP_ZERO_MEMORY
|
1287 HEAP_REALLOC_IN_PLACE_ONLY
;
1288 flags
|= heapPtr
->flags
;
1289 rounded_size
= ROUND_SIZE(size
);
1290 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1292 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterCriticalSection( &heapPtr
->critSection
);
1294 pArena
= (ARENA_INUSE
*)ptr
- 1;
1295 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, pArena
))) goto error
;
1296 if ((char *)pArena
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1297 if (!HEAP_ValidateInUseArena( subheap
, pArena
, QUIET
)) goto error
;
1299 /* Check if we need to grow the block */
1301 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1302 if (rounded_size
> oldSize
)
1304 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1305 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1306 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1307 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1309 /* The next block is free and large enough */
1310 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1311 list_remove( &pFree
->entry
);
1312 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1313 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1315 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1316 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1317 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1320 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1322 else /* Do it the hard way */
1325 ARENA_INUSE
*pInUse
;
1326 SUBHEAP
*newsubheap
;
1328 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1329 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1331 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1332 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1333 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1337 /* Build the in-use arena */
1339 list_remove( &pNew
->entry
);
1340 pInUse
= (ARENA_INUSE
*)pNew
;
1341 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1342 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1343 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1344 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1345 mark_block_initialized( pInUse
+ 1, oldSize
);
1346 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1348 /* Free the previous block */
1350 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1351 subheap
= newsubheap
;
1355 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1357 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1359 /* Clear the extra bytes if needed */
1361 if (rounded_size
> oldSize
)
1363 if (flags
& HEAP_ZERO_MEMORY
)
1364 clear_block( (char *)(pArena
+ 1) + oldSize
,
1365 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1367 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1368 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1371 /* Return the new arena */
1373 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1375 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1376 return (LPVOID
)(pArena
+ 1);
1379 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1380 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1381 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1386 /***********************************************************************
1387 * RtlCompactHeap (NTDLL.@)
1389 * Compact the free space in a Heap.
1392 * heap [I] Heap that block was allocated from
1393 * flags [I] HEAP_ flags from "winnt.h"
1396 * The number of bytes compacted.
1399 * This function is a harmless stub.
1401 ULONG WINAPI
RtlCompactHeap( HANDLE heap
, ULONG flags
)
1408 /***********************************************************************
1409 * RtlLockHeap (NTDLL.@)
1414 * heap [I] Heap to lock
1417 * Success: TRUE. The Heap is locked.
1418 * Failure: FALSE, if heap is invalid.
1420 BOOLEAN WINAPI
RtlLockHeap( HANDLE heap
)
1422 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1423 if (!heapPtr
) return FALSE
;
1424 RtlEnterCriticalSection( &heapPtr
->critSection
);
1429 /***********************************************************************
1430 * RtlUnlockHeap (NTDLL.@)
1435 * heap [I] Heap to unlock
1438 * Success: TRUE. The Heap is unlocked.
1439 * Failure: FALSE, if heap is invalid.
1441 BOOLEAN WINAPI
RtlUnlockHeap( HANDLE heap
)
1443 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1444 if (!heapPtr
) return FALSE
;
1445 RtlLeaveCriticalSection( &heapPtr
->critSection
);
1450 /***********************************************************************
1451 * RtlSizeHeap (NTDLL.@)
1453 * Get the actual size of a memory block allocated from a Heap.
1456 * heap [I] Heap that block was allocated from
1457 * flags [I] HEAP_ flags from "winnt.h"
1458 * ptr [I] Block to get the size of
1461 * Success: The size of the block.
1462 * Failure: -1, heap or ptr are invalid.
1465 * The size may be bigger than what was passed to RtlAllocateHeap().
1467 SIZE_T WINAPI
RtlSizeHeap( HANDLE heap
, ULONG flags
, PVOID ptr
)
1470 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1474 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1477 flags
&= HEAP_NO_SERIALIZE
;
1478 flags
|= heapPtr
->flags
;
1479 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterCriticalSection( &heapPtr
->critSection
);
1480 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1482 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1487 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1488 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1490 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1492 TRACE("(%p,%08x,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1497 /***********************************************************************
1498 * RtlValidateHeap (NTDLL.@)
1500 * Determine if a block is a valid allocation from a heap.
1503 * heap [I] Heap that block was allocated from
1504 * flags [I] HEAP_ flags from "winnt.h"
1505 * ptr [I] Block to check
1508 * Success: TRUE. The block was allocated from heap.
1509 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1511 BOOLEAN WINAPI
RtlValidateHeap( HANDLE heap
, ULONG flags
, LPCVOID ptr
)
1513 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1514 if (!heapPtr
) return FALSE
;
1515 return HEAP_IsRealArena( heapPtr
, flags
, ptr
, QUIET
);
1519 /***********************************************************************
1520 * RtlWalkHeap (NTDLL.@)
1523 * The PROCESS_HEAP_ENTRY flag values seem different between this
1524 * function and HeapWalk(). To be checked.
1526 NTSTATUS WINAPI
RtlWalkHeap( HANDLE heap
, PVOID entry_ptr
)
1528 LPPROCESS_HEAP_ENTRY entry
= entry_ptr
; /* FIXME */
1529 HEAP
*heapPtr
= HEAP_GetPtr(heap
);
1530 SUBHEAP
*sub
, *currentheap
= NULL
;
1533 int region_index
= 0;
1535 if (!heapPtr
|| !entry
) return STATUS_INVALID_PARAMETER
;
1537 if (!(heapPtr
->flags
& HEAP_NO_SERIALIZE
)) RtlEnterCriticalSection( &heapPtr
->critSection
);
1539 /* set ptr to the next arena to be examined */
1541 if (!entry
->lpData
) /* first call (init) ? */
1543 TRACE("begin walking of heap %p.\n", heap
);
1544 currentheap
= &heapPtr
->subheap
;
1545 ptr
= (char*)currentheap
+ currentheap
->headerSize
;
1549 ptr
= entry
->lpData
;
1550 sub
= &heapPtr
->subheap
;
1553 if (((char *)ptr
>= (char *)sub
) &&
1554 ((char *)ptr
< (char *)sub
+ sub
->size
))
1562 if (currentheap
== NULL
)
1564 ERR("no matching subheap found, shouldn't happen !\n");
1565 ret
= STATUS_NO_MORE_ENTRIES
;
1569 ptr
+= entry
->cbData
; /* point to next arena */
1570 if (ptr
> (char *)currentheap
+ currentheap
->size
- 1)
1571 { /* proceed with next subheap */
1572 if (!(currentheap
= currentheap
->next
))
1573 { /* successfully finished */
1574 TRACE("end reached.\n");
1575 ret
= STATUS_NO_MORE_ENTRIES
;
1578 ptr
= (char*)currentheap
+ currentheap
->headerSize
;
1583 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1585 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
1587 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1589 entry
->lpData
= pArena
+ 1;
1590 entry
->cbData
= pArena
->size
& ARENA_SIZE_MASK
;
1591 entry
->cbOverhead
= sizeof(ARENA_FREE
);
1592 entry
->wFlags
= PROCESS_HEAP_UNCOMMITTED_RANGE
;
1596 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
1598 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1600 entry
->lpData
= pArena
+ 1;
1601 entry
->cbData
= pArena
->size
& ARENA_SIZE_MASK
;
1602 entry
->cbOverhead
= sizeof(ARENA_INUSE
);
1603 entry
->wFlags
= PROCESS_HEAP_ENTRY_BUSY
;
1604 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1605 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1608 entry
->iRegionIndex
= region_index
;
1610 /* first element of heap ? */
1611 if (ptr
== (char *)(currentheap
+ currentheap
->headerSize
))
1613 entry
->wFlags
|= PROCESS_HEAP_REGION
;
1614 entry
->u
.Region
.dwCommittedSize
= currentheap
->commitSize
;
1615 entry
->u
.Region
.dwUnCommittedSize
=
1616 currentheap
->size
- currentheap
->commitSize
;
1617 entry
->u
.Region
.lpFirstBlock
= /* first valid block */
1618 currentheap
+ currentheap
->headerSize
;
1619 entry
->u
.Region
.lpLastBlock
= /* first invalid block */
1620 currentheap
+ currentheap
->size
;
1622 ret
= STATUS_SUCCESS
;
1623 if (TRACE_ON(heap
)) HEAP_DumpEntry(entry
);
1626 if (!(heapPtr
->flags
& HEAP_NO_SERIALIZE
)) RtlLeaveCriticalSection( &heapPtr
->critSection
);
1631 /***********************************************************************
1632 * RtlGetProcessHeaps (NTDLL.@)
1634 * Get the Heaps belonging to the current process.
1637 * count [I] size of heaps
1638 * heaps [O] Destination array for heap HANDLE's
1641 * Success: The number of Heaps allocated by the process.
1644 ULONG WINAPI
RtlGetProcessHeaps( ULONG count
, HANDLE
*heaps
)
1646 ULONG total
= 1; /* main heap */
1649 RtlEnterCriticalSection( &processHeap
->critSection
);
1650 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1653 *heaps
++ = processHeap
;
1654 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1655 *heaps
++ = LIST_ENTRY( ptr
, HEAP
, entry
);
1657 RtlLeaveCriticalSection( &processHeap
->critSection
);