[BASESRV-CONSRV-WINSRV]
[reactos.git] / dll / ntdll / ldr / ldrinit.c
index da065c4..5e22253 100644 (file)
@@ -10,7 +10,7 @@
 /* INCLUDES *****************************************************************/
 
 #include <ntdll.h>
-#include <win32k/callback.h>
+#include <callback.h>
 
 #define NDEBUG
 #include <debug.h>
@@ -18,8 +18,8 @@
 
 /* GLOBALS *******************************************************************/
 
-HKEY ImageExecOptionsKey;
-HKEY Wow64ExecOptionsKey;
+HANDLE ImageExecOptionsKey;
+HANDLE Wow64ExecOptionsKey;
 UNICODE_STRING ImageExecOptionsString = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options");
 UNICODE_STRING Wow64OptionsString = RTL_CONSTANT_STRING(L"");
 UNICODE_STRING NtDllString = RTL_CONSTANT_STRING(L"ntdll.dll");
@@ -48,7 +48,7 @@ LIST_ENTRY LdrpTlsList;
 ULONG LdrpNumberOfTlsEntries;
 ULONG LdrpNumberOfProcessors;
 PVOID NtDllBase;
-LARGE_INTEGER RtlpTimeout;
+extern LARGE_INTEGER RtlpTimeout;
 BOOLEAN RtlpTimeoutDisable;
 LIST_ENTRY LdrpHashTable[LDR_HASH_TABLE_ENTRIES];
 LIST_ENTRY LdrpDllNotificationList;
@@ -80,11 +80,14 @@ ULONG LdrpActiveUnloadCount;
 
 VOID RtlpInitializeVectoredExceptionHandling(VOID);
 VOID NTAPI RtlpInitDeferedCriticalSection(VOID);
-VOID RtlInitializeHeapManager(VOID);
+VOID NTAPI RtlInitializeHeapManager(VOID);
 extern BOOLEAN RtlpPageHeapEnabled;
-extern ULONG RtlpDphGlobalFlags;
+
+ULONG RtlpDisableHeapLookaside; // TODO: Move to heap.c
+ULONG RtlpShutdownProcessFlags; // TODO: Use it
 
 NTSTATUS LdrPerformRelocations(PIMAGE_NT_HEADERS NTHeaders, PVOID ImageBase);
+void actctx_init(void);
 
 #ifdef _WIN64
 #define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232ll
@@ -101,9 +104,9 @@ NTSTATUS
 NTAPI
 LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
                            IN BOOLEAN Wow64,
-                           OUT PHKEY NewKeyHandle)
+                           OUT PHANDLE NewKeyHandle)
 {
-    PHKEY RootKeyLocation;
+    PHANDLE RootKeyLocation;
     HANDLE RootKey;
     UNICODE_STRING SubKeyString;
     OBJECT_ATTRIBUTES ObjectAttributes;
@@ -121,7 +124,7 @@ LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
 
     /* Setup the object attributes */
     InitializeObjectAttributes(&ObjectAttributes,
-                               Wow64 ? 
+                               Wow64 ?
                                &Wow64OptionsString : &ImageExecOptionsString,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
@@ -142,14 +145,14 @@ LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
         /* Extract the name */
         SubKeyString = *SubKey;
         p1 = (PWCHAR)((ULONG_PTR)SubKeyString.Buffer + SubKeyString.Length);
-        while (SubKey->Length)
+        while (SubKeyString.Length)
         {
             if (p1[-1] == L'\\') break;
             p1--;
             SubKeyString.Length -= sizeof(*p1);
         }
         SubKeyString.Buffer = p1;
-        SubKeyString.Length = SubKeyString.MaximumLength - SubKeyString.Length - sizeof(WCHAR);
+        SubKeyString.Length = SubKey->Length - SubKeyString.Length;
 
         /* Setup the object attributes */
         InitializeObjectAttributes(&ObjectAttributes,
@@ -171,7 +174,7 @@ LdrOpenImageFileOptionsKey(IN PUNICODE_STRING SubKey,
  */
 NTSTATUS
 NTAPI
-LdrQueryImageFileKeyOption(IN HKEY KeyHandle,
+LdrQueryImageFileKeyOption(IN HANDLE KeyHandle,
                            IN PCWSTR ValueName,
                            IN ULONG Type,
                            OUT PVOID Buffer,
@@ -190,7 +193,7 @@ LdrQueryImageFileKeyOption(IN HKEY KeyHandle,
     if (!NT_SUCCESS(Status)) return Status;
 
     /* Query the value */
-    Status = NtQueryValueKey(KeyHandle,
+    Status = ZwQueryValueKey(KeyHandle,
                              &ValueNameString,
                              KeyValuePartialInformation,
                              KeyValueInformation,
@@ -204,20 +207,22 @@ LdrQueryImageFileKeyOption(IN HKEY KeyHandle,
         KeyValueInformation = RtlAllocateHeap(RtlGetProcessHeap(),
                                               0,
                                               KeyInfoSize);
-        if (KeyInfo == NULL)
+        if (KeyValueInformation != NULL)
+        {
+            /* Try again */
+            Status = ZwQueryValueKey(KeyHandle,
+                                     &ValueNameString,
+                                     KeyValuePartialInformation,
+                                     KeyValueInformation,
+                                     KeyInfoSize,
+                                     &ResultSize);
+            FreeHeap = TRUE;
+        }
+        else
         {
             /* Give up this time */
             Status = STATUS_NO_MEMORY;
         }
-
-        /* Try again */
-        Status = NtQueryValueKey(KeyHandle,
-                                 &ValueNameString,
-                                 KeyValuePartialInformation,
-                                 KeyValueInformation,
-                                 KeyInfoSize,
-                                 &ResultSize);
-        FreeHeap = TRUE;
     }
 
     /* Check for success */
@@ -292,9 +297,9 @@ LdrQueryImageFileKeyOption(IN HKEY KeyHandle,
                 {
                     /* OK, we know what you want... */
                     IntegerString.Buffer = (PWSTR)KeyValueInformation->Data;
-                    IntegerString.Length = KeyValueInformation->DataLength -
+                    IntegerString.Length = (USHORT)KeyValueInformation->DataLength -
                                            sizeof(WCHAR);
-                    IntegerString.MaximumLength = KeyValueInformation->DataLength;
+                    IntegerString.MaximumLength = (USHORT)KeyValueInformation->DataLength;
                     Status = RtlUnicodeStringToInteger(&IntegerString, 0, (PULONG)Buffer);
                 }
             }
@@ -324,8 +329,7 @@ LdrQueryImageFileKeyOption(IN HKEY KeyHandle,
     /* Check if buffer was in heap */
     if (FreeHeap) RtlFreeHeap(RtlGetProcessHeap(), 0, KeyValueInformation);
 
-    /* Close key and return */
-    NtClose(KeyHandle);
+    /* Return status */
     return Status;
 }
 
@@ -343,7 +347,7 @@ LdrQueryImageFileExecutionOptionsEx(IN PUNICODE_STRING SubKey,
                                     IN BOOLEAN Wow64)
 {
     NTSTATUS Status;
-    HKEY KeyHandle;
+    HANDLE KeyHandle;
 
     /* Open a handle to the key */
     Status = LdrOpenImageFileOptionsKey(SubKey, Wow64, &KeyHandle);
@@ -439,7 +443,7 @@ LdrpInitSecurityCookie(PLDR_DATA_TABLE_ENTRY LdrEntry)
 {
     PULONG_PTR Cookie;
     LARGE_INTEGER Counter;
-    //ULONG NewCookie;
+    ULONG_PTR NewCookie;
 
     /* Fetch address of the cookie */
     Cookie = LdrpFetchAddressOfSecurityCookie(LdrEntry->DllBase, LdrEntry->SizeOfImage);
@@ -447,40 +451,39 @@ LdrpInitSecurityCookie(PLDR_DATA_TABLE_ENTRY LdrEntry)
     if (Cookie)
     {
         /* Check if it's a default one */
-        if (*Cookie == DEFAULT_SECURITY_COOKIE ||
-            *Cookie == 0xBB40)
+        if ((*Cookie == DEFAULT_SECURITY_COOKIE) ||
+            (*Cookie == 0xBB40))
         {
-            /* We need to initialize it */
-
+            /* Make up a cookie from a bunch of values which may uniquely represent
+               current moment of time, environment, etc */
             NtQueryPerformanceCounter(&Counter, NULL);
-#if 0
-            GetSystemTimeAsFileTime (&systime.ft_struct);
-#ifdef _WIN64
-            cookie = systime.ft_scalar;
-#else
-            cookie = systime.ft_struct.dwLowDateTime;
-            cookie ^= systime.ft_struct.dwHighDateTime;
-#endif
 
-            cookie ^= GetCurrentProcessId ();
-            cookie ^= GetCurrentThreadId ();
-            cookie ^= GetTickCount ();
+            NewCookie = Counter.LowPart ^ Counter.HighPart;
+            NewCookie ^= (ULONG)NtCurrentTeb()->ClientId.UniqueProcess;
+            NewCookie ^= (ULONG)NtCurrentTeb()->ClientId.UniqueThread;
 
-            QueryPerformanceCounter (&perfctr);
-#ifdef _WIN64
-            cookie ^= perfctr.QuadPart;
-#else
-            cookie ^= perfctr.LowPart;
-            cookie ^= perfctr.HighPart;
-#endif
+            /* Loop like it's done in KeQueryTickCount(). We don't want to call it directly. */
+            while (SharedUserData->SystemTime.High1Time != SharedUserData->SystemTime.High2Time)
+            {
+                YieldProcessor();
+            };
 
-#ifdef _WIN64
-            cookie &= 0x0000ffffffffffffll;
-#endif
-#endif
-            *Cookie = Counter.LowPart;
+            /* Calculate the milliseconds value and xor it to the cookie */
+            NewCookie ^= Int64ShrlMod32(UInt32x32To64(SharedUserData->TickCountMultiplier, SharedUserData->TickCount.LowPart), 24) +
+                (SharedUserData->TickCountMultiplier * (SharedUserData->TickCount.High1Time << 8));
+
+            /* Make the cookie 16bit if necessary */
+            if (*Cookie == 0xBB40) NewCookie &= 0xFFFF;
+
+            /* If the result is 0 or the same as we got, just subtract one from the existing value
+               and that's it */
+            if ((NewCookie == 0) || (NewCookie == *Cookie))
+            {
+                NewCookie = *Cookie - 1;
+            }
 
-            //Cookie = NULL;
+            /* Set the new cookie value */
+            *Cookie = NewCookie;
         }
     }
 
@@ -498,23 +501,17 @@ LdrpInitializeThread(IN PCONTEXT Context)
     NTSTATUS Status;
     PVOID EntryPoint;
 
-    DPRINT("LdrpInitializeThread() called for %wZ\n",
-            &LdrpImageEntry->BaseDllName);
+    DPRINT("LdrpInitializeThread() called for %wZ (%lx/%lx)\n",
+            &LdrpImageEntry->BaseDllName,
+            NtCurrentTeb()->RealClientId.UniqueProcess,
+            NtCurrentTeb()->RealClientId.UniqueThread);
 
     /* Allocate an Activation Context Stack */
-    /* FIXME: This is a hack for Wine's actctx stuff */
     DPRINT("ActivationContextStack %p\n", NtCurrentTeb()->ActivationContextStackPointer);
-    if (!(NtCurrentTeb()->ActivationContextStackPointer))
+    Status = RtlAllocateActivationContextStack(&NtCurrentTeb()->ActivationContextStackPointer);
+    if (!NT_SUCCESS(Status))
     {
-        Status = RtlAllocateActivationContextStack((PVOID*)&NtCurrentTeb()->ActivationContextStackPointer);
-        if (NT_SUCCESS(Status))
-        {
-            DPRINT("ActivationContextStack %p\n", NtCurrentTeb()->ActivationContextStackPointer);
-            DPRINT("ActiveFrame %p\n", ((PACTIVATION_CONTEXT_STACK)NtCurrentTeb()->ActivationContextStackPointer)->ActiveFrame);
-            NtCurrentTeb()->ActivationContextStackPointer->ActiveFrame = NULL;
-        }
-        else
-            DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
+        DPRINT1("Warning: Unable to allocate ActivationContextStack\n");
     }
 
     /* Make sure we are not shutting down */
@@ -541,7 +538,7 @@ LdrpInitializeThread(IN PCONTEXT Context)
                 EntryPoint = LdrEntry->EntryPoint;
 
                 /* Check if we are ready to call it */
-                if ((EntryPoint) && 
+                if ((EntryPoint) &&
                     (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
                     (LdrEntry->Flags & LDRP_IMAGE_DLL))
                 {
@@ -569,8 +566,10 @@ LdrpInitializeThread(IN PCONTEXT Context)
                     if (!LdrpShutdownInProgress)
                     {
                         /* Call the Entrypoint */
-                        DPRINT("%wZ - Calling entry point at %x for thread attaching\n",
-                                &LdrEntry->BaseDllName, LdrEntry->EntryPoint);
+                        DPRINT("%wZ - Calling entry point at %p for thread attaching, %lx/%lx\n",
+                                &LdrEntry->BaseDllName, LdrEntry->EntryPoint,
+                                NtCurrentTeb()->RealClientId.UniqueProcess,
+                                NtCurrentTeb()->RealClientId.UniqueThread);
                         LdrpCallInitRoutine(LdrEntry->EntryPoint,
                                          LdrEntry->DllBase,
                                          DLL_THREAD_ATTACH,
@@ -627,7 +626,10 @@ LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
     PTEB OldTldTeb;
     BOOLEAN DllStatus;
 
-    DPRINT("LdrpRunInitializeRoutines() called for %wZ\n", &LdrpImageEntry->BaseDllName);
+    DPRINT("LdrpRunInitializeRoutines() called for %wZ (%lx/%lx)\n",
+        &LdrpImageEntry->BaseDllName,
+        NtCurrentTeb()->RealClientId.UniqueProcess,
+        NtCurrentTeb()->RealClientId.UniqueThread);
 
     /* Check the Loader Lock */
     LdrpEnsureLoaderLockIsHeld();
@@ -641,7 +643,7 @@ LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
             /* Allocate space for all the entries */
             LdrRootEntry = RtlAllocateHeap(RtlGetProcessHeap(),
                                            0,
-                                           Count * sizeof(LdrRootEntry));
+                                           Count * sizeof(*LdrRootEntry));
             if (!LdrRootEntry) return STATUS_NO_MEMORY;
         }
         else
@@ -687,6 +689,7 @@ LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
                 if (LdrEntry->EntryPoint)
                 {
                     /* Write in array */
+                    ASSERT(i < Count);
                     LdrRootEntry[i] = LdrEntry;
 
                     /* Display debug message */
@@ -720,7 +723,7 @@ LdrpRunInitializeRoutines(IN PCONTEXT Context OPTIONAL)
 
         /* Clear it */
         //Kernel32ProcessInitPostImportfunction = NULL;
-        UNIMPLEMENTED;
+        //UNIMPLEMENTED;
     }
 
     /* No root entry? return */
@@ -939,7 +942,7 @@ LdrShutdownProcess(VOID)
             EntryPoint = LdrEntry->EntryPoint;
 
             /* Check if we are ready to call it */
-            if (EntryPoint && 
+            if (EntryPoint &&
                 (LdrEntry->Flags & LDRP_PROCESS_ATTACH_CALLED) &&
                 LdrEntry->Flags)
             {
@@ -1212,7 +1215,7 @@ LdrpAllocateTls(VOID)
     PTEB Teb = NtCurrentTeb();
     PLIST_ENTRY NextEntry, ListHead;
     PLDRP_TLS_DATA TlsData;
-    ULONG TlsDataSize;
+    SIZE_T TlsDataSize;
     PVOID *TlsVector;
 
     /* Check if we have any entries */
@@ -1236,7 +1239,7 @@ LdrpAllocateTls(VOID)
         NextEntry = NextEntry->Flink;
 
         /* Allocate this vector */
-        TlsDataSize = TlsData->TlsDirectory.EndAddressOfRawData - 
+        TlsDataSize = TlsData->TlsDirectory.EndAddressOfRawData -
                       TlsData->TlsDirectory.StartAddressOfRawData;
         TlsVector[TlsData->TlsDirectory.Characteristics] = RtlAllocateHeap(RtlGetProcessHeap(),
                                                                            0,
@@ -1306,10 +1309,140 @@ LdrpFreeTls(VOID)
 
 NTSTATUS
 NTAPI
-LdrpInitializeExecutionOptions(PUNICODE_STRING ImagePathName, PPEB Peb, PHKEY OptionsKey)
+LdrpInitializeApplicationVerifierPackage(PUNICODE_STRING ImagePathName, PPEB Peb, BOOLEAN SystemWide, BOOLEAN ReadAdvancedOptions)
 {
-    UNIMPLEMENTED;
+    /* If global flags request DPH, perform some additional actions */
+    if (Peb->NtGlobalFlag & FLG_HEAP_PAGE_ALLOCS)
+    {
+        // TODO: Read advanced DPH flags from the registry if requested
+        if (ReadAdvancedOptions)
+        {
+            UNIMPLEMENTED;
+        }
+
+        /* Enable page heap */
+        RtlpPageHeapEnabled = TRUE;
+    }
+
+    return STATUS_SUCCESS;
+}
+
+NTSTATUS
+NTAPI
+LdrpInitializeExecutionOptions(PUNICODE_STRING ImagePathName, PPEB Peb, PHANDLE OptionsKey)
+{
+    NTSTATUS Status;
+    HANDLE KeyHandle;
+    ULONG ExecuteOptions, MinimumStackCommit = 0, GlobalFlag;
+
+    /* Return error if we were not provided a pointer where to save the options key handle */
+    if (!OptionsKey) return STATUS_INVALID_HANDLE;
+
+    /* Zero initialize the optinos key pointer */
     *OptionsKey = NULL;
+
+    /* Open the options key */
+    Status = LdrOpenImageFileOptionsKey(ImagePathName, 0, &KeyHandle);
+
+    /* Save it if it was opened successfully */
+    if (NT_SUCCESS(Status))
+        *OptionsKey = KeyHandle;
+
+    if (KeyHandle)
+    {
+        /* There are image specific options, read them starting with NXCOMPAT */
+        Status = LdrQueryImageFileKeyOption(KeyHandle,
+                                            L"ExecuteOptions",
+                                            4,
+                                            &ExecuteOptions,
+                                            sizeof(ExecuteOptions),
+                                            0);
+
+        if (NT_SUCCESS(Status))
+        {
+            /* TODO: Set execution options for the process */
+            /*
+            if (ExecuteOptions == 0)
+                ExecuteOptions = 1;
+            else
+                ExecuteOptions = 2;
+            ZwSetInformationProcess(NtCurrentProcess(),
+                                    ProcessExecuteFlags,
+                                    &ExecuteOptions,
+                                    sizeof(ULONG));*/
+
+        }
+
+        /* Check if this image uses large pages */
+        if (Peb->ImageUsesLargePages)
+        {
+            /* TODO: If it does, open large page key */
+            UNIMPLEMENTED;
+        }
+
+        /* Get various option values */
+        LdrQueryImageFileKeyOption(KeyHandle,
+                                   L"DisableHeapLookaside",
+                                   REG_DWORD,
+                                   &RtlpDisableHeapLookaside,
+                                   sizeof(RtlpDisableHeapLookaside),
+                                   NULL);
+
+        LdrQueryImageFileKeyOption(KeyHandle,
+                                   L"ShutdownFlags",
+                                   REG_DWORD,
+                                   &RtlpShutdownProcessFlags,
+                                   sizeof(RtlpShutdownProcessFlags),
+                                   NULL);
+
+        LdrQueryImageFileKeyOption(KeyHandle,
+                                   L"MinimumStackCommitInBytes",
+                                   REG_DWORD,
+                                   &MinimumStackCommit,
+                                   sizeof(MinimumStackCommit),
+                                   NULL);
+
+        /* Update PEB's minimum stack commit if it's lower */
+        if (Peb->MinimumStackCommit < MinimumStackCommit)
+            Peb->MinimumStackCommit = MinimumStackCommit;
+
+        /* Set the global flag */
+        Status = LdrQueryImageFileKeyOption(KeyHandle,
+                                            L"GlobalFlag",
+                                            REG_DWORD,
+                                            &GlobalFlag,
+                                            sizeof(GlobalFlag),
+                                            NULL);
+
+        if (NT_SUCCESS(Status))
+            Peb->NtGlobalFlag = GlobalFlag;
+        else
+            GlobalFlag = 0;
+
+        /* Call AVRF if necessary */
+        if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
+        {
+            Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
+            }
+        }
+    }
+    else
+    {
+        /* There are no image-specific options, so perform global initialization */
+        if (Peb->NtGlobalFlag & (FLG_POOL_ENABLE_TAIL_CHECK | FLG_HEAP_PAGE_ALLOCS))
+        {
+            /* Initialize app verifier package */
+            Status = LdrpInitializeApplicationVerifierPackage(ImagePathName, Peb, TRUE, FALSE);
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("AVRF: LdrpInitializeApplicationVerifierPackage failed with %08X\n", Status);
+            }
+        }
+    }
+
     return STATUS_SUCCESS;
 }
 
@@ -1337,16 +1470,16 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     PPEB Peb = NtCurrentPeb();
     BOOLEAN IsDotNetImage = FALSE;
     BOOLEAN FreeCurDir = FALSE;
-    //HKEY CompatKey;
+    //HANDLE CompatKey;
     PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
     //LPWSTR ImagePathBuffer;
     ULONG ConfigSize;
     UNICODE_STRING CurrentDirectory;
-    HKEY OptionsKey;
+    HANDLE OptionsKey;
     ULONG HeapFlags;
     PIMAGE_NT_HEADERS NtHeader;
     LPWSTR NtDllName = NULL;
-    NTSTATUS Status;
+    NTSTATUS Status, ImportStatus;
     NLSTABLEINFO NlsTable;
     PIMAGE_LOAD_CONFIG_DIRECTORY LoadConfig;
     PTEB Teb = NtCurrentTeb();
@@ -1366,8 +1499,8 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     /* Get the image path */
     ImagePath = Peb->ProcessParameters->ImagePathName.Buffer;
 
-    /* Check if it's normalized */
-    if (Peb->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_NORMALIZED)
+    /* Check if it's not normalized */
+    if (!(Peb->ProcessParameters->Flags & RTL_USER_PROCESS_PARAMETERS_NORMALIZED))
     {
         /* Normalize it*/
         ImagePath = (PWSTR)((ULONG_PTR)ImagePath + (ULONG_PTR)Peb->ProcessParameters);
@@ -1416,7 +1549,6 @@ LdrpInitializeProcess(IN PCONTEXT Context,
 
     /* Normalize the parameters */
     ProcessParameters = RtlNormalizeProcessParams(Peb->ProcessParameters);
-    ProcessParameters = Peb->ProcessParameters;
     if (ProcessParameters)
     {
         /* Save the Image and Command Line Names */
@@ -1577,7 +1709,7 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     }
 
     /* Allocate an Activation Context Stack */
-    Status = RtlAllocateActivationContextStack((PVOID *)&Teb->ActivationContextStackPointer);
+    Status = RtlAllocateActivationContextStack(&Teb->ActivationContextStackPointer);
     if (!NT_SUCCESS(Status)) return Status;
 
     // FIXME: Loader private heap is missing
@@ -1599,7 +1731,7 @@ LdrpInitializeProcess(IN PCONTEXT Context,
             /* Reset DPH if requested */
             if (RtlpPageHeapEnabled && DebugProcessHeapOnly)
             {
-                RtlpDphGlobalFlags &= ~0x40;
+                RtlpDphGlobalFlags &= ~DPH_FLAG_DLL_NOTIFY;
                 RtlpPageHeapEnabled = FALSE;
             }
         }
@@ -1809,6 +1941,9 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     InsertHeadList(&Peb->Ldr->InInitializationOrderModuleList,
                    &LdrpNtDllDataTableEntry->InInitializationOrderModuleList);
 
+    /* Initialize Wine's active context implementation for the current process */
+    actctx_init();
+
     /* Set the current directory */
     Status = RtlSetCurrentDirectory_U(&CurrentDirectory);
     if (!NT_SUCCESS(Status))
@@ -1850,17 +1985,17 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     if (NtHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
     {
         /* Load kernel32 and call BasePostImportInit... */
-        DPRINT1("Unimplemented codepath!\n");
+        DPRINT("Unimplemented codepath!\n");
     }
 
     /* Walk the IAT and load all the DLLs */
-    LdrpWalkImportDescriptor(LdrpDefaultPath.Buffer, LdrpImageEntry);
+    ImportStatus = LdrpWalkImportDescriptor(LdrpDefaultPath.Buffer, LdrpImageEntry);
 
     /* Check if relocation is needed */
     if (Peb->ImageBaseAddress != (PVOID)NtHeader->OptionalHeader.ImageBase)
     {
         DPRINT1("LDR: Performing EXE relocation\n");
-        
+
         /* Change the protection to prepare for relocation */
         ViewBase = Peb->ImageBaseAddress;
         Status = LdrpSetProtection(ViewBase, FALSE);
@@ -1878,7 +2013,7 @@ LdrpInitializeProcess(IN PCONTEXT Context,
             DPRINT1("LdrRelocateImageWithBias() failed\n");
             return Status;
         }
-        
+
         /* Check if a start context was provided */
         if (Context)
         {
@@ -1886,7 +2021,7 @@ LdrpInitializeProcess(IN PCONTEXT Context,
             UNIMPLEMENTED; // We should support this
             return STATUS_INVALID_IMAGE_FORMAT;
         }
-        
+
         /* Restore the protection */
         Status = LdrpSetProtection(ViewBase, TRUE);
         if (!NT_SUCCESS(Status)) return Status;
@@ -1905,6 +2040,9 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     /* Phase 0 is done */
     LdrpLdrDatabaseIsSetup = TRUE;
 
+    /* Check whether all static imports were properly loaded and return here */
+    if (!NT_SUCCESS(ImportStatus)) return ImportStatus;
+
     /* Initialize TLS */
     Status = LdrpInitializeTls();
     if (!NT_SUCCESS(Status))
@@ -1957,7 +2095,7 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     {
         /* Check for Application Compatibility Goo */
         //LdrQueryApplicationCompatibilityGoo(hKey);
-        DPRINT1("Querying app compat hacks is missing!\n");
+        DPRINT("Querying app compat hacks is missing!\n");
     }
 
     /*
@@ -1979,13 +2117,12 @@ LdrpInitializeProcess(IN PCONTEXT Context,
     /* Check if we have a user-defined Post Process Routine */
     if (NT_SUCCESS(Status) && Peb->PostProcessInitRoutine)
     {
-        DPRINT1("CP\n");
         /* Call it */
         Peb->PostProcessInitRoutine();
     }
 
-    ///* Close the key if we have one opened */
-    //if (hKey) NtClose(hKey);
+    /* Close the key if we have one opened */
+    if (OptionsKey) NtClose(OptionsKey);
 
     /* Return status */
     return Status;
@@ -2021,7 +2158,9 @@ LdrpInit(PCONTEXT Context,
     MEMORY_BASIC_INFORMATION MemoryBasicInfo;
     PPEB Peb = NtCurrentPeb();
 
-    DPRINT("LdrpInit()\n");
+    DPRINT("LdrpInit() %lx/%lx\n",
+        NtCurrentTeb()->RealClientId.UniqueProcess,
+        NtCurrentTeb()->RealClientId.UniqueThread);
 
     /* Check if we have a deallocation stack */
     if (!Teb->DeallocationStack)