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