Fixed a bug in RtlDestroyHeap, that will cause a page fault, if more than one subheap...
[reactos.git] / reactos / lib / ntdll / rtl / heap.c
index 25763ad..0dc64b2 100644 (file)
@@ -5,6 +5,13 @@
  * Copyright 1998 Ulrich Weigand
  */
 
+
+/* Note: the heap data structures are based on what Pietrek describes in his
+ * book 'Windows 95 System Programming Secrets'. The layout is not exactly
+ * the same, but could be easily adapted if it turns out some programs
+ * require it.
+ */
+
 #include <string.h>
 #include <ddk/ntddk.h>
 #include <ntdll/rtl.h>
 #define NDEBUG
 #include <ntdll/ntdll.h>
 
-CRITICAL_SECTION ProcessHeapsLock;
+#define DPRINTF DPRINT
+#define ERR DPRINT
+#define SetLastError(x)
+#define WARN DPRINT
+#define TRACE DPRINT
+#define WARN_ON(x) (1)
+
+#undef assert
+#ifdef NDEBUG
+#define TRACE_ON(x) (0)
+#define assert(x)
+#else
+#define TRACE_ON(x) (1)
+#define assert(x)
+#endif
+
+
+static CRITICAL_SECTION RtlpProcessHeapsListLock;
 
-/* Note: the heap data structures are based on what Pietrek describes in his
- * book 'Windows 95 System Programming Secrets'. The layout is not exactly
- * the same, but could be easily adapted if it turns out some programs
- * require it.
- */
 
 typedef struct tagARENA_INUSE
 {
     DWORD  size;                    /* Block size; must be the first field */
     WORD   threadId;                /* Allocating thread id */
     WORD   magic;                   /* Magic number */
-    DWORD  callerEIP;               /* EIP of caller upon allocation */
+    void  *callerEIP;               /* EIP of caller upon allocation */
 } ARENA_INUSE;
 
 typedef struct tagARENA_FREE
@@ -48,6 +67,9 @@ typedef struct tagARENA_FREE
 #define ARENA_INUSE_FILLER     0x55
 #define ARENA_FREE_FILLER      0xaa
 
+#define QUIET                  1           /* Suppress messages  */
+#define NOISY                  0           /* Report all errors  */
+
 #define HEAP_NB_FREE_LISTS   4   /* Number of free lists */
 
 /* Max size of the blocks on the free lists */
@@ -73,7 +95,7 @@ typedef struct tagSUBHEAP
     struct tagHEAP     *heap;       /* Main heap structure */
     DWORD               magic;      /* Magic number */
     WORD                selector;   /* Selector for HEAP_WINE_SEGPTR heaps */
-} SUBHEAP;
+} SUBHEAP, *PSUBHEAP;
 
 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
 
@@ -85,36 +107,50 @@ typedef struct tagHEAP
     CRITICAL_SECTION critSection;   /* Critical section for serialization */
     DWORD            flags;         /* Heap flags */
     DWORD            magic;         /* Magic number */
-} HEAP;
+    void            *private;       /* Private pointer for the user of the heap */
+} HEAP, *PHEAP;
 
 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
 
 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
 #define HEAP_MIN_BLOCK_SIZE  (8+sizeof(ARENA_FREE))  /* Min. heap block size */
+#define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
+
+
+static BOOL HEAP_IsRealArena( HANDLE heap, DWORD flags, LPCVOID block, BOOL quiet );
+
+#ifdef __GNUC__
+#define GET_EIP()    (__builtin_return_address(0))
+#define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
+#else
+#define GET_EIP()    0
+#define SET_EIP(ptr) /* nothing */
+#endif  /* __GNUC__ */
 
 
 /***********************************************************************
  *           HEAP_Dump
  */
-void HEAP_Dump( HEAP *heap )
+void
+HEAP_Dump(PHEAP heap)
 {
     int i;
     SUBHEAP *subheap;
     char *ptr;
 
-    DPRINT( "Heap: %08lx\n", (DWORD)heap );
-    DPRINT( "Next: %08lx  Sub-heaps: %08lx",
+    DPRINTF( "Heap: %08lx\n", (DWORD)heap );
+    DPRINTF( "Next: %08lx  Sub-heaps: %08lx",
          (DWORD)heap->next, (DWORD)&heap->subheap );
     subheap = &heap->subheap;
     while (subheap->next)
     {
-        DPRINT( " -> %08lx", (DWORD)subheap->next );
+        DPRINTF( " -> %08lx", (DWORD)subheap->next );
         subheap = subheap->next;
     }
 
-    DPRINT( "\nFree lists:\n Block   Stat   Size    Id\n" );
+    DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
-        DPRINT( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
+        DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
              (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
              heap->freeList[i].arena.threadId,
              (DWORD)heap->freeList[i].arena.prev,
@@ -124,17 +160,17 @@ void HEAP_Dump( HEAP *heap )
     while (subheap)
     {
         DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
-        DPRINT( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
+        DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
              (DWORD)subheap, subheap->size, subheap->commitSize );
        
-        DPRINT( "\n Block   Stat   Size    Id\n" );
+        DPRINTF( "\n Block   Stat   Size    Id\n" );
         ptr = (char*)subheap + subheap->headerSize;
         while (ptr < (char *)subheap + subheap->size)
         {
             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
             {
                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
-                DPRINT( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
+                DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
                      (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
                      pArena->threadId, (DWORD)pArena->prev,
                      (DWORD)pArena->next);
@@ -145,7 +181,7 @@ void HEAP_Dump( HEAP *heap )
             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
             {
                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
-                DPRINT( "%08lx Used %08lx %04x back=%08lx EIP=%08lx\n",
+                DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
                      (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
                      pArena->threadId, *((DWORD *)pArena - 1),
                      pArena->callerEIP );
@@ -156,7 +192,7 @@ void HEAP_Dump( HEAP *heap )
             else
             {
                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
-                DPRINT( "%08lx used %08lx %04x EIP=%08lx\n",
+                DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
                      (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
                      pArena->threadId, pArena->callerEIP );
                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
@@ -164,7 +200,7 @@ void HEAP_Dump( HEAP *heap )
                 usedSize += pArena->size & ARENA_SIZE_MASK;
             }
         }
-        DPRINT( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
+        DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
              subheap->size, subheap->commitSize, freeSize, usedSize,
              arenaSize, (arenaSize * 100) / subheap->size );
         subheap = subheap->next;
@@ -178,23 +214,19 @@ void HEAP_Dump( HEAP *heap )
  *     Pointer to the heap
  *     NULL: Failure
  */
-static HEAP *HEAP_GetPtr(
-             HANDLE heap /* [in] Handle to the heap */
-{
+static PHEAP
+HEAP_GetPtr(HANDLE heap) /* [in] Handle to the heap */
+{
     HEAP *heapPtr = (HEAP *)heap;
     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
     {
-        DbgPrint(heap, "Invalid heap %08x!\n", heap );
-       for(;;);
-//        SetLastError( ERROR_INVALID_HANDLE );
+        ERR("Invalid heap %08x!\n", heap );
         return NULL;
     }
-    if (!RtlValidateHeap( heap, 0, NULL ))
+    if (TRACE_ON(heap) && !HEAP_IsRealArena( heap, 0, NULL, NOISY ))
     {
         HEAP_Dump( heapPtr );
-        DbgPrint("NTDLL:%s:%d: assertion failed\n",__FILE__,__LINE__);
-       for(;;);
-//        SetLastError( ERROR_INVALID_HANDLE );
+        assert( FALSE );
         return NULL;
     }
     return heapPtr;
@@ -206,7 +238,9 @@ static HEAP *HEAP_GetPtr(
  *
  * Insert a free block into the free list.
  */
-static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
+static VOID
+HEAP_InsertFreeBlock(PHEAP heap,
+                    ARENA_FREE *pArena)
 {
     FREE_LIST_ENTRY *pEntry = heap->freeList;
     while (pEntry->size < pArena->size) pEntry++;
@@ -226,10 +260,10 @@ static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
  *     Pointer: Success
  *     NULL: Failure
  */
-static SUBHEAP *HEAP_FindSubHeap(
-                HEAP *heap, /* [in] Heap pointer */
-                LPCVOID ptr /* [in] Address */
-{
+static PSUBHEAP
+HEAP_FindSubHeap(HEAP *heap,  /* [in] Heap pointer */
+                LPCVOID ptr) /* [in] Address */
+{
     SUBHEAP *sub = &heap->subheap;
     while (sub)
     {
@@ -246,32 +280,42 @@ static SUBHEAP *HEAP_FindSubHeap(
  *
  * Make sure the heap storage is committed up to (not including) ptr.
  */
-static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
+static inline BOOL
+HEAP_Commit(SUBHEAP *subheap,
+           void *ptr,
+           DWORD flags)
 {
-   DWORD size = (DWORD)((char *)ptr - (char *)subheap);
-   ULONG commitsize;
-   PVOID address;
-   NTSTATUS Status;
+    DWORD size = (DWORD)((char *)ptr - (char *)subheap);
+    NTSTATUS Status;
+    PVOID address;
+    ULONG commitsize;
    
-   size = (size + 0xfff) & 0xfffff000;  /* Align size on a page boundary */
-   if (size > subheap->size) size = subheap->size;
-   if (size <= subheap->commitSize) return TRUE;
-   commitsize = size - subheap->commitSize;
-   address = (PVOID)((char *)subheap + subheap->commitSize);
-   Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
-                                   &address,
-                                   0,
-                                   &commitsize,
-                                   MEM_COMMIT,
-                                   PAGE_EXECUTE_READWRITE);
-   if (!NT_SUCCESS(Status))
-     {
-       DbgPrint("ZwAllocateVirtualMemory failed\n");
-       for(;;);
-       return(FALSE);
-     }
-   subheap->commitSize = size;
-   return TRUE;
+    size = (size + COMMIT_MASK) & ~COMMIT_MASK;
+    if (size > subheap->size) size = subheap->size;
+    if (size <= subheap->commitSize) return TRUE;
+   
+    address = (PVOID)((char *)subheap + subheap->commitSize);
+    commitsize = size - subheap->commitSize;
+
+    if (!(flags & HEAP_NO_VALLOC))
+      {
+       Status = NtAllocateVirtualMemory(NtCurrentProcess(),
+                                        &address,
+                                        0,
+                                        &commitsize,
+                                        MEM_COMMIT,
+                                        PAGE_EXECUTE_READWRITE);
+       if (!NT_SUCCESS(Status))
+         {
+           WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
+                 size - subheap->commitSize,
+                 (DWORD)((char *)subheap + subheap->commitSize),
+                 (DWORD)subheap->heap );
+           return FALSE;
+         }
+      }
+    subheap->commitSize = size;
+    return TRUE;
 }
 
 
@@ -280,30 +324,34 @@ static BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
  *
  * If possible, decommit the heap storage from (including) 'ptr'.
  */
-static BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
+static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr, DWORD flags )
 {
     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
-   PVOID freebase;
-   ULONG freesize;
-   NTSTATUS Status;
-   
-    size = (size + 0xfff) & 0xfffff000;  /* Align size on a page boundary */
+    PVOID address;
+    ULONG decommitsize;
+    NTSTATUS Status;
+    /* round to next block and add one full block */
+    size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
     if (size >= subheap->commitSize) return TRUE;
-   freebase = (PVOID)((char *)subheap + size);
-   freesize = subheap->commitSize - size;
-   Status = ZwFreeVirtualMemory(NtCurrentProcess(), 
-                               &freebase,
-                               &freesize,
-                               MEM_DECOMMIT);
-     if (!NT_SUCCESS(Status))
-     {
-        DbgPrint("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
-                 subheap->commitSize - size,
-                 (DWORD)((char *)subheap + size),
-                 (DWORD)subheap->heap );
-       for(;;);
-        return FALSE;
-    }
+   
+    address = (PVOID)((char *)subheap + size);
+    decommitsize = subheap->commitSize - size;
+
+    if (!(flags & HEAP_NO_VALLOC))
+      {
+       Status = ZwFreeVirtualMemory(NtCurrentProcess(),
+                                    &address,
+                                    &decommitsize,
+                                    MEM_DECOMMIT);
+       if (!NT_SUCCESS(Status));
+       {
+         WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
+              subheap->commitSize - size,
+              (DWORD)((char *)subheap + size),
+              (DWORD)subheap->heap );
+         return FALSE;
+       }
+      }
     subheap->commitSize = size;
     return TRUE;
 }
@@ -322,11 +370,12 @@ static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
     /* Create a free arena */
 
     pFree = (ARENA_FREE *)ptr;
+    pFree->threadId = (DWORD)NtCurrentTeb()->Cid.UniqueThread;
     pFree->magic = ARENA_FREE_MAGIC;
 
     /* If debugging, erase the freed block content */
 
-    if (1) // DEBUGGING
+    if (TRACE_ON(heap))
     {
         char *pEnd = (char *)ptr + size;
         if (pEnd > (char *)subheap + subheap->commitSize)
@@ -345,7 +394,7 @@ static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
         pNext->next->prev = pNext->prev;
         pNext->prev->next = pNext->next;
         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
-        if (1) // DEBUGGING
+        if (TRACE_ON(heap))
             memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
     }
 
@@ -371,7 +420,8 @@ static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
  * Turn an in-use block into a free block. Can also decommit the end of
  * the heap, and possibly even free the sub-heap altogether.
  */
-static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
+static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena,
+                                    DWORD flags)
 {
     ARENA_FREE *pFree;
     DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
@@ -409,13 +459,18 @@ static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
         if (pPrev) pPrev->next = subheap->next;
         /* Free the memory */
         subheap->magic = 0;
-        ZwFreeVirtualMemory(NtCurrentProcess(), (PVOID*)&subheap, 0, MEM_RELEASE );
+       if (!(flags & HEAP_NO_VALLOC))
+         {
+           ULONG dummySize = 0;
+           ZwFreeVirtualMemory(NtCurrentProcess(),
+                               (PVOID*)&subheap,
+                               &dummySize,
+                               MEM_RELEASE);
+         }
         return;
     }
     
     /* Decommit the end of the heap */
-
-    HEAP_Decommit( subheap, pFree + 1 );
 }
 
 
@@ -447,31 +502,33 @@ static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
                                 DWORD commitSize, DWORD totalSize )
 {
-   SUBHEAP *subheap = (SUBHEAP *)address;
-   FREE_LIST_ENTRY *pEntry;
-   int i;
-   NTSTATUS Status;
+    SUBHEAP *subheap = (SUBHEAP *)address;
+    WORD selector = 0;
+    FREE_LIST_ENTRY *pEntry;
+    int i;
+    NTSTATUS Status;
    
     /* Commit memory */
-
-   Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
-                                   &address, 
-                                   0,
-                                   (PULONG)&commitSize, 
-                                   MEM_COMMIT, 
-                                   PAGE_EXECUTE_READWRITE);
-   if (!NT_SUCCESS(Status))
-    {
-        DbgPrint("Could not commit %08lx bytes for sub-heap %08lx\n",
-                   commitSize, (DWORD)address );
-       for(;;);
-        return FALSE;
-    }
-
+    if (!(flags & HEAP_NO_VALLOC))
+      {
+       Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
+                                        &address,
+                                        0,
+                                        (PULONG)&commitSize,
+                                        MEM_COMMIT,
+                                        PAGE_EXECUTE_READWRITE);
+       if (!NT_SUCCESS(Status))
+         {
+           WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
+                commitSize, (DWORD)address );
+           return FALSE;
+         }
+      }
 
     /* Fill the sub-heap structure */
 
     subheap->heap       = heap;
+    subheap->selector   = selector;
     subheap->size       = totalSize;
     subheap->commitSize = commitSize;
     subheap->magic      = SUBHEAP_MAGIC;
@@ -512,7 +569,7 @@ static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
 
         RtlInitializeCriticalSection( &heap->critSection );
     }
+
     /* Create the first free block */
 
     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize, 
@@ -527,38 +584,52 @@ static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
  * Create a sub-heap of the given size.
  * If heap == NULL, creates a main heap.
  */
-static SUBHEAP *HEAP_CreateSubHeap(PVOID BaseAddress,
-                                  HEAP *heap, 
-                                  DWORD flags,
-                                  DWORD commitSize, 
-                                  DWORD totalSize )
+static SUBHEAP *HEAP_CreateSubHeap(PVOID BaseAddress,  
+                                  HEAP *heap, DWORD flags, 
+                                   DWORD commitSize, DWORD totalSize )
 {
     LPVOID address;
+    NTSTATUS Status;
    
     /* Round-up sizes on a 64K boundary */
 
-   totalSize  = (totalSize + 0xffff) & 0xffff0000;
-   commitSize = (commitSize + 0xffff) & 0xffff0000;
-   if (!commitSize) commitSize = 0x10000;
-   if (totalSize < commitSize) totalSize = commitSize;
-
-    /* Allocate the memory block */
-   
-   address = BaseAddress;
-   ZwAllocateVirtualMemory(NtCurrentProcess(),
-                          &address,
-                          0,
-                          (PULONG)&totalSize,
-                          MEM_RESERVE, 
-                          PAGE_EXECUTE_READWRITE);
+    totalSize  = (totalSize + 0xffff) & 0xffff0000;
+    commitSize = (commitSize + 0xffff) & 0xffff0000;
+    if (!commitSize) commitSize = 0x10000;
+    if (totalSize < commitSize) totalSize = commitSize;
+
+    /* Allocate the memory block */    
+    address = BaseAddress;
+    if (!(flags & HEAP_NO_VALLOC))
+      {
+       Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
+                                        &address,
+                                        0,
+                                        (PULONG)&totalSize,
+                                        MEM_RESERVE | MEM_COMMIT,
+                                        PAGE_EXECUTE_READWRITE);
+       if (!NT_SUCCESS(Status))
+         {
+           WARN("Could not VirtualAlloc %08lx bytes\n",
+                 totalSize );
+           return NULL;
+         }
+      }
 
     /* Initialize subheap */
 
     if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address, 
                            address, flags, commitSize, totalSize ))
     {
-        ZwFreeVirtualMemory(NtCurrentProcess(), address, 0, MEM_RELEASE );
-        return NULL;
+      if (!(flags & HEAP_NO_VALLOC))
+       {
+         ULONG dummySize = 0;
+         ZwFreeVirtualMemory(NtCurrentProcess(),
+                             address,
+                             &dummySize,
+                             MEM_RELEASE);
+         return NULL;
+       }
     }
 
     return (SUBHEAP *)address;
@@ -588,7 +659,8 @@ static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
         {
             subheap = HEAP_FindSubHeap( heap, pArena );
             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
-                                               + size + HEAP_MIN_BLOCK_SIZE))
+                                               + size + HEAP_MIN_BLOCK_SIZE,
+                             heap->flags))
                 return NULL;
             *ppSubHeap = subheap;
             return pArena;
@@ -601,7 +673,7 @@ static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
 
     if (!(heap->flags & HEAP_GROWABLE))
     {
-        DbgPrint("Not enough space in heap %08lx for %08lx bytes\n",
+        WARN("Not enough space in heap %08lx for %08lx bytes\n",
                  (DWORD)heap, size );
         return NULL;
     }
@@ -610,7 +682,7 @@ static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
                                         max( HEAP_DEF_SIZE, size ) )))
         return NULL;
 
-    DPRINT("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
+    TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
                 (DWORD)subheap, size, (DWORD)heap );
 
     *ppSubHeap = subheap;
@@ -646,58 +718,52 @@ static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
     /* Check magic number */
     if (pArena->magic != ARENA_FREE_MAGIC)
     {
-        DbgPrint("Heap %08lx: invalid free arena magic for %08lx (%x)\n",
-                 (DWORD)subheap->heap, (DWORD)pArena, &pArena->magic );
-       for(;;);
+        ERR("Heap %08lx: invalid free arena magic for %08lx\n",
+                 (DWORD)subheap->heap, (DWORD)pArena );
         return FALSE;
     }
     /* Check size flags */
     if (!(pArena->size & ARENA_FLAG_FREE) ||
         (pArena->size & ARENA_FLAG_PREV_FREE))
     {
-        DbgPrint("Heap %08lx: bad flags %lx for free arena %08lx\n",
+        ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
-       for(;;);
     }
     /* Check arena size */
     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
     {
-        DbgPrint("Heap %08lx: bad size %08lx for free arena %08lx\n",
+        ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check that next pointer is valid */
     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
     {
-        DbgPrint("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
+        ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check that next arena is free */
     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
         (pArena->next->magic != ARENA_FREE_MAGIC))
     { 
-        DPRINT("Heap %08lx: next arena %08lx invalid for %08lx\n", 
+        ERR("Heap %08lx: next arena %08lx invalid for %08lx\n", 
                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
         return FALSE;
     }
     /* Check that prev pointer is valid */
     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
     {
-        DbgPrint("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
+        ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check that prev arena is free */
     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
         (pArena->prev->magic != ARENA_FREE_MAGIC))
     { 
-        DbgPrint("Heap %08lx: prev arena %08lx invalid for %08lx\n", 
+        ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n", 
                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check that next block has PREV_FREE flag */
@@ -706,19 +772,17 @@ static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
         if (!(*(DWORD *)((char *)(pArena + 1) +
             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
         {
-            DbgPrint("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
+            ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
                      (DWORD)subheap->heap, (DWORD)pArena );
-          for(;;);
             return FALSE;
         }
         /* Check next block back pointer */
         if (*((ARENA_FREE **)((char *)(pArena + 1) +
             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
         {
-            DbgPrint("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
+            ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
                      (DWORD)subheap->heap, (DWORD)pArena,
                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
-          for(;;);
             return FALSE;
         }
     }
@@ -729,40 +793,45 @@ static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
 /***********************************************************************
  *           HEAP_ValidateInUseArena
  */
-static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
+static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
 {
     char *heapEnd = (char *)subheap + subheap->size;
 
     /* Check magic number */
     if (pArena->magic != ARENA_INUSE_MAGIC)
     {
-        DbgPrint("Heap %08lx: invalid in-use arena magic for %08lx (%x)\n",
-                 (DWORD)subheap->heap, (DWORD)pArena, &pArena->magic );
-       for(;;);
+        if (quiet == NOISY) {
+        ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
+                 (DWORD)subheap->heap, (DWORD)pArena );
+            if (TRACE_ON(heap))
+               HEAP_Dump( subheap->heap );
+        }  else if (WARN_ON(heap)) {
+            WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
+                 (DWORD)subheap->heap, (DWORD)pArena );
+            if (TRACE_ON(heap))
+               HEAP_Dump( subheap->heap );
+        }
         return FALSE;
     }
     /* Check size flags */
     if (pArena->size & ARENA_FLAG_FREE) 
     {
-        DbgPrint("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
+        ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
-       for(;;);
     }
     /* Check arena size */
     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
     {
-        DbgPrint("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
+        ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check next arena PREV_FREE flag */
     if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
         (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
     {
-        DbgPrint("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
+        ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
                  (DWORD)subheap->heap, (DWORD)pArena );
-       for(;;);
         return FALSE;
     }
     /* Check prev free arena */
@@ -772,26 +841,23 @@ static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena )
         /* Check prev pointer */
         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
         {
-            DbgPrint("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
+            ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
-          for(;;);
             return FALSE;
         }
         /* Check that prev arena is free */
         if (!(pPrev->size & ARENA_FLAG_FREE) ||
             (pPrev->magic != ARENA_FREE_MAGIC))
         { 
-            DbgPrint("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
+            ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
-          for(;;);
             return FALSE;
         }
         /* Check that prev arena is really the previous block */
         if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
         {
-            DbgPrint("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
+            ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
-          for(;;);
             return FALSE;
         }
     }
@@ -823,11 +889,105 @@ int HEAP_IsInsideHeap(
 
     if (!heapPtr) return 0;
     flags |= heapPtr->flags;
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlLockHeap( heap );
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
     ret = (((subheap = HEAP_FindSubHeap( heapPtr, ptr )) != NULL) &&
            (((char *)ptr >= (char *)subheap + subheap->headerSize
                               + sizeof(ARENA_INUSE))));
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
+    return ret;
+}
+
+
+
+
+/***********************************************************************
+ *           HEAP_IsRealArena  [Internal]
+ * Validates a block is a valid arena.
+ *
+ * RETURNS
+ *     TRUE: Success
+ *     FALSE: Failure
+ */
+static BOOL HEAP_IsRealArena(
+              HANDLE heap,   /* [in] Handle to the heap */
+              DWORD flags,   /* [in] Bit flags that control access during operation */
+              LPCVOID block, /* [in] Optional pointer to memory block to validate */
+              BOOL quiet     /* [in] Flag - if true, HEAP_ValidateInUseArena
+                              *             does not complain    */
+) {
+    SUBHEAP *subheap;
+    HEAP *heapPtr = (HEAP *)(heap);
+    BOOL ret = TRUE;
+
+    if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
+    {
+        ERR("Invalid heap %08x!\n", heap );
+        return FALSE;
+    }
+
+    flags &= HEAP_NO_SERIALIZE;
+    flags |= heapPtr->flags;
+    /* calling HeapLock may result in infinite recursion, so do the critsect directly */
+    if (!(flags & HEAP_NO_SERIALIZE))
+        RtlEnterCriticalSection( &heapPtr->critSection );
+
+    if (block)
+    {
+        /* Only check this single memory block */
+
+        /* The following code is really HEAP_IsInsideHeap   *
+         * with serialization already done.                 */
+        if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
+            ((char *)block < (char *)subheap + subheap->headerSize
+                              + sizeof(ARENA_INUSE)))
+        {
+            if (quiet == NOISY) 
+           {
+                ERR("Heap %08lx: block %08lx is not inside heap\n",
+                     (DWORD)heap, (DWORD)block );
+           }
+            else if (WARN_ON(heap)) 
+           {
+                WARN("Heap %08lx: block %08lx is not inside heap\n",
+                     (DWORD)heap, (DWORD)block );
+           }
+            ret = FALSE;
+        } else
+            ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
+
+        if (!(flags & HEAP_NO_SERIALIZE))
+            RtlLeaveCriticalSection( &heapPtr->critSection );
+        return ret;
+    }
+
+    subheap = &heapPtr->subheap;
+    while (subheap && ret)
+    {
+        char *ptr = (char *)subheap + subheap->headerSize;
+        while (ptr < (char *)subheap + subheap->size)
+        {
+            if (*(DWORD *)ptr & ARENA_FLAG_FREE)
+            {
+                if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
+                    ret = FALSE;
+                    break;
+                }
+                ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
+            }
+            else
+            {
+                if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
+                    ret = FALSE;
+                    break;
+                }
+                ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
+            }
+        }
+        subheap = subheap->next;
+    }
+
+    if (!(flags & HEAP_NO_SERIALIZE))
+       RtlLeaveCriticalSection( &heapPtr->critSection );
     return ret;
 }
 
@@ -838,38 +998,40 @@ int HEAP_IsInsideHeap(
  *     Handle of heap: Success
  *     NULL: Failure
  */
-HANDLE STDCALL RtlCreateHeap(ULONG flags,
-                            PVOID BaseAddress, 
-                            ULONG initialSize,
-                            ULONG maxSize, 
-                            PVOID Unknown,
-                            PRTL_HEAP_DEFINITION Definition) 
+HANDLE STDCALL
+RtlCreateHeap(ULONG flags,
+             PVOID BaseAddress,
+             ULONG initialSize,
+             ULONG maxSize,
+             PVOID Unknown,
+             PRTL_HEAP_DEFINITION Definition)
 {
-   SUBHEAP *subheap;
-   
-   /* Allocate the heap block */
-   
-   DPRINT("RtlCreateHeap(flags %x, BaseAddress %x, initialSize %x, "
-         "maxSize %x\n)",flags,BaseAddress,initialSize, maxSize);
+    SUBHEAP *subheap;
+    ULONG i;
    
+    /* Allocate the heap block */
+
     if (!maxSize)
     {
         maxSize = HEAP_DEF_SIZE;
         flags |= HEAP_GROWABLE;
     }
-    if (!(subheap = HEAP_CreateSubHeap(BaseAddress,
-                                      NULL, 
-                                      flags, 
-                                      initialSize, 
-                                      maxSize)))
+    if (!(subheap = HEAP_CreateSubHeap( BaseAddress, NULL, flags, initialSize, maxSize )))
     {
-//        SetLastError( ERROR_OUTOFMEMORY );
-       DbgPrint("RtlCreateHeap() = %x\n",0);
         return 0;
     }
 
-   DPRINT("RtlCreateHeap() = %x\n",subheap);
-   
+   RtlEnterCriticalSection (&RtlpProcessHeapsListLock);
+   for (i = 0; i < NtCurrentPeb ()->NumberOfHeaps; i++)
+     {
+       if (NtCurrentPeb ()->ProcessHeaps[i] == NULL)
+         {
+            NtCurrentPeb()->ProcessHeaps[i] = (PVOID)subheap;
+            break;
+         }
+     }
+   RtlLeaveCriticalSection (&RtlpProcessHeapsListLock);
+
     return (HANDLE)subheap;
 }
 
@@ -879,21 +1041,45 @@ HANDLE STDCALL RtlCreateHeap(ULONG flags,
  *     TRUE: Success
  *     FALSE: Failure
  */
-BOOL STDCALL RtlDestroyHeap(
-              HANDLE heap /* [in] Handle of heap */
-{
+BOOL STDCALL
+RtlDestroyHeap(HANDLE heap) /* [in] Handle of heap */
+{
     HEAP *heapPtr = HEAP_GetPtr( heap );
     SUBHEAP *subheap;
-
-    DPRINT("%08x\n", heap );
+    ULONG i, flags;
+   
+    TRACE("%08x\n", heap );
     if (!heapPtr) return FALSE;
 
+   RtlEnterCriticalSection (&RtlpProcessHeapsListLock);
+   for (i = 0; i < NtCurrentPeb ()->NumberOfHeaps; i++)
+     {
+       if (NtCurrentPeb ()->ProcessHeaps[i] == heap)
+         {
+            NtCurrentPeb()->ProcessHeaps[i] = NULL;
+            break;
+         }
+     }
+   RtlLeaveCriticalSection (&RtlpProcessHeapsListLock);
+   
     RtlDeleteCriticalSection( &heapPtr->critSection );
     subheap = &heapPtr->subheap;
+    // We must save the flags. The first subheap is located after 
+    // the heap structure. If we release the first subheap, 
+    // we release also the heap structure.
+    flags = heapPtr->flags;
     while (subheap)
     {
         SUBHEAP *next = subheap->next;
-        ZwFreeVirtualMemory(NtCurrentProcess(), (PVOID*)&subheap, 0, MEM_RELEASE );
+
+       if (!(flags & HEAP_NO_VALLOC))
+         {
+           ULONG dummySize = 0;
+           ZwFreeVirtualMemory(NtCurrentProcess(),
+                               (PVOID*)&subheap,
+                               &dummySize,
+                               MEM_RELEASE);
+         }
         subheap = next;
     }
     return TRUE;
@@ -906,32 +1092,22 @@ BOOL STDCALL RtlDestroyHeap(
  *     Pointer to allocated memory block
  *     NULL: Failure
  */
-PVOID STDCALL RtlAllocateHeap(
-              HANDLE heap, /* [in] Handle of private heap block */
-                            ULONG flags,   /* [in] Heap allocation control flags */
-              ULONG size     /* [in] Number of bytes to allocate */
-{
+PVOID STDCALL
+RtlAllocateHeap(HANDLE heap,   /* [in] Handle of private heap block */
+                ULONG flags,   /* [in] Heap allocation control flags */
+                ULONG size)    /* [in] Number of bytes to allocate */
+{
     ARENA_FREE *pArena;
     ARENA_INUSE *pInUse;
     SUBHEAP *subheap;
-    HEAP *heapPtr = NULL;
+    HEAP *heapPtr = HEAP_GetPtr( heap );
 
     /* Validate the parameters */
 
+    if (!heapPtr) return NULL;
     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
-    flags |= ((HEAP*)heap)->flags;
-    if (!(flags & HEAP_NO_SERIALIZE))
-     {
-       RtlLockHeap(heap);
-     }
-    heapPtr = HEAP_GetPtr(heap);
-    if (heapPtr == NULL)
-     {
-       if (!(flags & HEAP_NO_SERIALIZE))
-         {
-            RtlUnlockHeap(heap);
-         }
-     }
+    flags |= heapPtr->flags;
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
     size = (size + 3) & ~3;
     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
 
@@ -939,10 +1115,9 @@ PVOID STDCALL RtlAllocateHeap(
 
     if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
     {
-        DPRINT("(%08x,%08lx,%08lx): returning NULL\n",
+        TRACE("(%08x,%08lx,%08lx): returning NULL\n",
                   heap, flags, size  );
-        if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
-//        SetLastError( ERROR_COMMITMENT_LIMIT );
+        if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
         return NULL;
     }
 
@@ -956,20 +1131,22 @@ PVOID STDCALL RtlAllocateHeap(
     pInUse = (ARENA_INUSE *)pArena;
     pInUse->size      = (pInUse->size & ~ARENA_FLAG_FREE)
                         + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
-    pInUse->callerEIP = *((DWORD *)&heap - 1);  /* hack hack */
-//    pInUse->threadId  = GetCurrentTask();
+    pInUse->callerEIP = GET_EIP();
+    pInUse->threadId  = (DWORD)NtCurrentTeb()->Cid.UniqueThread;
     pInUse->magic     = ARENA_INUSE_MAGIC;
 
     /* Shrink the block */
 
     HEAP_ShrinkBlock( subheap, pInUse, size );
 
-    if (flags & HEAP_ZERO_MEMORY) memset( pInUse + 1, 0, size );
-    else if (1) memset( pInUse + 1, ARENA_INUSE_FILLER, size ); //DEBUGGING
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
+    if (flags & HEAP_ZERO_MEMORY)
+        memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
+    else if (TRACE_ON(heap))
+        memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
+
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
 
-    DPRINT("(%08x,%08lx,%08lx): returning %08lx\n",
+    TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
                   heap, flags, size, (DWORD)(pInUse + 1) );
     return (LPVOID)(pInUse + 1);
 }
@@ -988,35 +1165,25 @@ BOOLEAN STDCALL RtlFreeHeap(
 ) {
     ARENA_INUSE *pInUse;
     SUBHEAP *subheap;
-    HEAP *heapPtr = NULL;
+    HEAP *heapPtr = HEAP_GetPtr( heap );
 
     /* Validate the parameters */
 
-    flags &= HEAP_NO_SERIALIZE;
-    flags |= ((HEAP*)heap)->flags;
-    if (!(flags & HEAP_NO_SERIALIZE)) 
-     {
-       RtlLockHeap( heap );
-     }
-    heapPtr = HEAP_GetPtr(heap);
-    if (heapPtr == NULL)
-     {
-       if (!(flags & HEAP_NO_SERIALIZE))
-         {
-            RtlUnlockHeap(heap);
-         }
-       return(FALSE);
-     }
-    if (!ptr)
+    if (!heapPtr) return FALSE;
+    if (!ptr)  /* Freeing a NULL ptr is doesn't indicate an error in Win2k */
     {
-       DPRINT("(%08x,%08lx,%08lx): asked to free NULL\n",
+       WARN("(%08x,%08lx,%08lx): asked to free NULL\n",
                    heap, flags, (DWORD)ptr );
+       return TRUE;
     }
-    if (!ptr || !RtlValidateHeap( heap, HEAP_NO_SERIALIZE, ptr ))
+
+    flags &= HEAP_NO_SERIALIZE;
+    flags |= heapPtr->flags;
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
+    if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
     {
-        if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
-//        SetLastError( ERROR_INVALID_PARAMETER );
-        DPRINT("(%08x,%08lx,%08lx): returning FALSE\n",
+        if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
+        TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
                       heap, flags, (DWORD)ptr );
         return FALSE;
     }
@@ -1025,12 +1192,11 @@ BOOLEAN STDCALL RtlFreeHeap(
 
     pInUse  = (ARENA_INUSE *)ptr - 1;
     subheap = HEAP_FindSubHeap( heapPtr, pInUse );
-    HEAP_MakeInUseBlockFree( subheap, pInUse );
+    HEAP_MakeInUseBlockFree( subheap, pInUse, heapPtr->flags );
 
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
-/*    SetLastError( 0 ); */
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
 
-    DPRINT("(%08x,%08lx,%08lx): returning TRUE\n",
+    TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
                   heap, flags, (DWORD)ptr );
     return TRUE;
 }
@@ -1041,19 +1207,13 @@ BOOLEAN STDCALL RtlFreeHeap(
  * RETURNS
  *     Pointer to reallocated memory block
  *     NULL: Failure
- *
- * REVISIONS
- *     Renamed RtlReAllocateHeap as in NT
  */
-LPVOID
-STDCALL
-RtlReAllocateHeap (
-       HANDLE  heap,   /* [in] Handle of heap block */
-       DWORD   flags,  /* [in] Heap reallocation flags */
-       LPVOID  ptr,    /* [in] Address of memory to reallocate */
-       DWORD   size    /* [in] Number of bytes to reallocate */
-       )
-{
+LPVOID STDCALL RtlReAllocateHeap(
+              HANDLE heap, /* [in] Handle of heap block */
+              DWORD flags,   /* [in] Heap reallocation flags */
+              LPVOID ptr,    /* [in] Address of memory to reallocate */
+              DWORD size     /* [in] Number of bytes to reallocate */
+) {
     ARENA_INUSE *pArena;
     DWORD oldSize;
     HEAP *heapPtr;
@@ -1070,12 +1230,11 @@ RtlReAllocateHeap (
     size = (size + 3) & ~3;
     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
 
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlLockHeap( heap );
-    if (!RtlValidateHeap( heap, HEAP_NO_SERIALIZE, ptr ))
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
+    if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
     {
-        if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
-//        SetLastError( ERROR_INVALID_PARAMETER );
-        DPRINT("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
+        if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
+        TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
                       heap, flags, (DWORD)ptr, size );
         return NULL;
     }
@@ -1083,7 +1242,8 @@ RtlReAllocateHeap (
     /* Check if we need to grow the block */
 
     pArena = (ARENA_INUSE *)ptr - 1;
-//    pArena->threadId = GetCurrentTask();
+    pArena->threadId = (DWORD)NtCurrentTeb()->Cid.UniqueThread;
+
     subheap = HEAP_FindSubHeap( heapPtr, pArena );
     oldSize = (pArena->size & ARENA_SIZE_MASK);
     if (size > oldSize)
@@ -1099,10 +1259,10 @@ RtlReAllocateHeap (
             pFree->prev->next = pFree->next;
             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
-                                               + size + HEAP_MIN_BLOCK_SIZE))
+                                               + size + HEAP_MIN_BLOCK_SIZE,
+                             heapPtr->flags))
             {
-                if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
-//                SetLastError( ERROR_OUTOFMEMORY );
+                if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
                 return NULL;
             }
             HEAP_ShrinkBlock( subheap, pArena, size );
@@ -1116,8 +1276,7 @@ RtlReAllocateHeap (
             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
                 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
             {
-                if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
- //               SetLastError( ERROR_OUTOFMEMORY );
+                if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
                 return NULL;
             }
 
@@ -1128,14 +1287,14 @@ RtlReAllocateHeap (
             pInUse = (ARENA_INUSE *)pNew;
             pInUse->size     = (pInUse->size & ~ARENA_FLAG_FREE)
                                + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
-//            pInUse->threadId = GetCurrentTask();
+           pInUse->threadId = (DWORD)NtCurrentTeb()->Cid.UniqueThread;
             pInUse->magic    = ARENA_INUSE_MAGIC;
             HEAP_ShrinkBlock( newsubheap, pInUse, size );
             memcpy( pInUse + 1, pArena + 1, oldSize );
 
             /* Free the previous block */
 
-            HEAP_MakeInUseBlockFree( subheap, pArena );
+            HEAP_MakeInUseBlockFree( subheap, pArena, flags );
             subheap = newsubheap;
             pArena  = pInUse;
         }
@@ -1149,17 +1308,17 @@ RtlReAllocateHeap (
         if (flags & HEAP_ZERO_MEMORY)
             memset( (char *)(pArena + 1) + oldSize, 0,
                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
-        else if (1) // DEBUGGING
+        else if (TRACE_ON(heap))
             memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
     }
 
     /* Return the new arena */
 
-    pArena->callerEIP = *((DWORD *)&heap - 1);  /* hack hack */
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
+    pArena->callerEIP = GET_EIP();
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
 
-    DPRINT("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
+    TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
                   heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
     return (LPVOID)(pArena + 1);
 }
@@ -1170,6 +1329,7 @@ RtlReAllocateHeap (
  */
 DWORD STDCALL RtlCompactHeap( HANDLE heap, DWORD flags )
 {
+    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
     return 0;
 }
 
@@ -1214,7 +1374,7 @@ BOOL STDCALL RtlUnlockHeap(
  *           HeapSize   (KERNEL32.341)
  * RETURNS
  *     Size in bytes of allocated memory
- *     0: Failure
+ *     0xffffffff: Failure
  */
 DWORD STDCALL RtlSizeHeap(
              HANDLE heap, /* [in] Handle of heap */
@@ -1227,10 +1387,10 @@ DWORD STDCALL RtlSizeHeap(
     if (!heapPtr) return FALSE;
     flags &= HEAP_NO_SERIALIZE;
     flags |= heapPtr->flags;
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlLockHeap( heap );
-    if (!RtlValidateHeap( heap, HEAP_NO_SERIALIZE, ptr ))
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
+    if (!HEAP_IsRealArena( heap, HEAP_NO_SERIALIZE, ptr, QUIET ))
     {
-//        SetLastError( ERROR_INVALID_PARAMETER );
+        SetLastError( ERROR_INVALID_PARAMETER );
         ret = 0xffffffff;
     }
     else
@@ -1238,9 +1398,9 @@ DWORD STDCALL RtlSizeHeap(
         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
         ret = pArena->size & ARENA_SIZE_MASK;
     }
-    if (!(flags & HEAP_NO_SERIALIZE)) RtlUnlockHeap( heap );
+    if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
 
-    DPRINT("(%08x,%08lx,%08lx): returning %08lx\n",
+    TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
                   heap, flags, (DWORD)ptr, ret );
     return ret;
 }
@@ -1262,139 +1422,219 @@ BOOL STDCALL RtlValidateHeap(
               DWORD flags,   /* [in] Bit flags that control access during operation */
               PVOID block  /* [in] Optional pointer to memory block to validate */
 ) {
-    SUBHEAP *subheap;
-    HEAP *heapPtr = (HEAP *)(heap);
 
-    if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
+    return HEAP_IsRealArena( heap, flags, block, QUIET );
+}
+
+
+/***********************************************************************
+ *           HeapWalk   (KERNEL32.344)
+ * Enumerates the memory blocks in a specified heap.
+ * See HEAP_Dump() for info on heap structure.
+ *
+ * TODO
+ *   - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
+ *     PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
+ *
+ * RETURNS
+ *     TRUE: Success
+ *     FALSE: Failure
+ */
+#if 0
+BOOL STDCALL HeapWalk(
+              HANDLE heap,               /* [in]  Handle to heap to enumerate */
+              LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
+) {
+    HEAP *heapPtr = HEAP_GetPtr(heap);
+    SUBHEAP *sub, *currentheap = NULL;
+    BOOL ret = FALSE;
+    char *ptr;
+    int region_index = 0;
+
+    if (!heapPtr || !entry)
     {
-        DPRINT("Invalid heap %08x!\n", heap );
-        return FALSE;
+       SetLastError(ERROR_INVALID_PARAMETER);
+       return FALSE;
     }
 
-    if (block)
+    if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
+
+    /* set ptr to the next arena to be examined */
+
+    if (!entry->lpData) /* first call (init) ? */
     {
-        /* Only check this single memory block */
-        if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
-            ((char *)block < (char *)subheap + subheap->headerSize
-                              + sizeof(ARENA_INUSE)))
-        {
-            DPRINT("Heap %08lx: block %08lx is not inside heap\n",
-                     (DWORD)heap, (DWORD)block );
-            return FALSE;
-        }
-        return HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1 );
+       TRACE("begin walking of heap 0x%08x.\n", heap);
+       /*HEAP_Dump(heapPtr);*/
+       currentheap = &heapPtr->subheap;
+       ptr = (char*)currentheap + currentheap->headerSize;
     }
+    else
+    {
+       ptr = entry->lpData;
+       sub = &heapPtr->subheap;
+       while (sub)
+       {
+           if (((char *)ptr >= (char *)sub) &&
+               ((char *)ptr < (char *)sub + sub->size))
+           {
+               currentheap = sub;
+               break;
+           }
+           sub = sub->next;
+           region_index++;
+       }
+       if (currentheap == NULL)
+       {
+           ERR("no matching subheap found, shouldn't happen !\n");
+           SetLastError(ERROR_NO_MORE_ITEMS);
+           goto HW_end;
+       }
 
-    subheap = &heapPtr->subheap;
-    while (subheap)
+       ptr += entry->cbData; /* point to next arena */
+       if (ptr > (char *)currentheap + currentheap->size - 1)
+       {   /* proceed with next subheap */
+           if (!(currentheap = currentheap->next))
+           {  /* successfully finished */
+               TRACE("end reached.\n");
+               SetLastError(ERROR_NO_MORE_ITEMS);
+               goto HW_end;
+           }
+           ptr = (char*)currentheap + currentheap->headerSize;
+       }
+    }
+
+    entry->wFlags = 0;
+    if (*(DWORD *)ptr & ARENA_FLAG_FREE)
     {
-        char *ptr = (char *)subheap + subheap->headerSize;
-        while (ptr < (char *)subheap + subheap->size)
-        {
-            if (*(DWORD *)ptr & ARENA_FLAG_FREE)
-            {
-                if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr ))
-                    return FALSE;
-                ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
-            }
-            else
-            {
-                if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr ))
-                    return FALSE;
-                ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
-            }
-        }
-        subheap = subheap->next;
+       ARENA_FREE *pArena = (ARENA_FREE *)ptr;
+
+       /*TRACE("free, magic: %04x\n", pArena->magic);*/
+
+       entry->lpData = pArena + 1;
+       entry->cbData = pArena->size & ARENA_SIZE_MASK;
+       entry->cbOverhead = sizeof(ARENA_FREE);
+       entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
     }
-    return TRUE;
+    else
+    {
+       ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
+
+       /*TRACE("busy, magic: %04x\n", pArena->magic);*/
+       
+       entry->lpData = pArena + 1;
+       entry->cbData = pArena->size & ARENA_SIZE_MASK;
+       entry->cbOverhead = sizeof(ARENA_INUSE);
+       entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
+       /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
+       and PROCESS_HEAP_ENTRY_DDESHARE yet */
+    }
+
+    entry->iRegionIndex = region_index;
+
+    /* first element of heap ? */
+    if (ptr == (char *)(currentheap + currentheap->headerSize))
+    {
+       entry->wFlags |= PROCESS_HEAP_REGION;
+       entry->Foo.Region.dwCommittedSize = currentheap->commitSize;
+       entry->Foo.Region.dwUnCommittedSize =
+               currentheap->size - currentheap->commitSize;
+       entry->Foo.Region.lpFirstBlock = /* first valid block */
+               currentheap + currentheap->headerSize;
+       entry->Foo.Region.lpLastBlock  = /* first invalid block */
+               currentheap + currentheap->size;
+    }
+    ret = TRUE;
+
+HW_end:
+    if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
+
+    return ret;
 }
+#endif
 
-HANDLE STDCALL RtlGetProcessHeap(VOID)
+
+HANDLE STDCALL
+RtlGetProcessHeap(VOID)
 {
    DPRINT("RtlGetProcessHeap()\n");
    return (HANDLE)NtCurrentPeb()->ProcessHeap;
 }
 
 VOID
-RtlpInitProcessHeaps (PPEB Peb)
+RtlInitializeHeapManager(VOID)
 {
-       Peb->NumberOfHeaps = 0;
-       Peb->MaximumNumberOfHeaps = (PAGESIZE - sizeof(PPEB)) / sizeof(HANDLE);
-       Peb->ProcessHeaps = (PVOID)Peb + sizeof(PEB);
-
-       RtlInitializeCriticalSection (&ProcessHeapsLock);
+   PPEB Peb;
+   
+   Peb = NtCurrentPeb();
+   
+   Peb->NumberOfHeaps = 0;
+   Peb->MaximumNumberOfHeaps = (PAGESIZE - sizeof(PEB)) / sizeof(HANDLE);
+   Peb->ProcessHeaps = (PVOID)Peb + sizeof(PEB);
+   
+   RtlInitializeCriticalSection(&RtlpProcessHeapsListLock);
 }
 
 
-NTSTATUS
-STDCALL
-RtlEnumProcessHeaps (
-       DWORD STDCALL(*func)(void*,LONG),
-       LONG    lParam
-       )
+NTSTATUS STDCALL
+RtlEnumProcessHeaps(DWORD STDCALL(*func)(void*,LONG),
+                   LONG lParam)
 {
-       NTSTATUS Status = STATUS_SUCCESS;
-       ULONG i;
+   NTSTATUS Status = STATUS_SUCCESS;
+   ULONG i;
 
-       RtlEnterCriticalSection (&ProcessHeapsLock);
+   RtlEnterCriticalSection(&RtlpProcessHeapsListLock);
 
-       for (i = 0; i < NtCurrentPeb ()->NumberOfHeaps; i++)
-       {
-               Status = func (NtCurrentPeb ()->ProcessHeaps[i],lParam);
-               if(!NT_SUCCESS(Status))
-                       break;
-       }
+   for (i = 0; i < NtCurrentPeb()->NumberOfHeaps; i++)
+     {
+       Status = func(NtCurrentPeb()->ProcessHeaps[i],lParam);
+       if (!NT_SUCCESS(Status))
+         break;
+     }
 
-       RtlLeaveCriticalSection (&ProcessHeapsLock);
+   RtlLeaveCriticalSection(&RtlpProcessHeapsListLock);
 
-       return Status;
+   return Status;
 }
 
 
-ULONG
-STDCALL
-RtlGetProcessHeaps (
-       ULONG   HeapCount,
-       HANDLE  *HeapArray
-       )
+ULONG STDCALL
+RtlGetProcessHeaps(ULONG HeapCount,
+                  HANDLE *HeapArray)
 {
-       ULONG Result = 0;
+   ULONG Result = 0;
 
-       RtlEnterCriticalSection (&ProcessHeapsLock);
+   RtlEnterCriticalSection(&RtlpProcessHeapsListLock);
 
-       if (NtCurrentPeb ()->NumberOfHeaps <= HeapCount)
-       {
-               Result = NtCurrentPeb ()->NumberOfHeaps;
-               memmove (HeapArray,
-                        NtCurrentPeb ()->ProcessHeaps,
-                        Result * sizeof(HANDLE));
-       }
+   if (NtCurrentPeb()->NumberOfHeaps <= HeapCount)
+     {
+       Result = NtCurrentPeb()->NumberOfHeaps;
+       memmove(HeapArray,
+               NtCurrentPeb()->ProcessHeaps,
+               Result * sizeof(HANDLE));
+     }
 
-       RtlLeaveCriticalSection (&ProcessHeapsLock);
+   RtlLeaveCriticalSection (&RtlpProcessHeapsListLock);
 
-       return Result;
+   return Result;
 }
 
 
-BOOLEAN
-STDCALL
-RtlValidateProcessHeaps (
-       VOID
-       )
+BOOLEAN STDCALL
+RtlValidateProcessHeaps(VOID)
 {
-       HANDLE Heaps[128];
-       BOOLEAN Result = TRUE;
-       ULONG HeapCount;
-       ULONG i;
+   HANDLE Heaps[128];
+   BOOLEAN Result = TRUE;
+   ULONG HeapCount;
+   ULONG i;
 
-       HeapCount = RtlGetProcessHeaps (128, Heaps);
-       for (i = 0; i < HeapCount; i++)
-       {
-               if (!RtlValidateHeap (Heaps[i], 0, NULL))
-                       Result = FALSE;
-       }
+   HeapCount = RtlGetProcessHeaps(128, Heaps);
+   for (i = 0; i < HeapCount; i++)
+     {
+       if (!RtlValidateHeap(Heaps[i], 0, NULL))
+         Result = FALSE;
+     }
 
-       return Result;
+   return Result;
 }
 
 /* EOF */