/*++ * @name CsrInitializeProcessStructure * @implemented NT4 * * The CsrInitializeProcessStructure routine sets up support for CSR Processes * and CSR Threads by initializing our own CSR Root Process. * * @param None. * * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise. * * @remarks None. * *--*/ NTSTATUS NTAPI CsrInitializeProcessStructure(VOID) { NTSTATUS Status; ULONG i; /* Initialize the Lock */ Status = RtlInitializeCriticalSection(&CsrProcessLock); if (!NT_SUCCESS(Status)) return Status; /* Set up the Root Process */ CsrRootProcess = CsrAllocateProcess(); if (!CsrRootProcess) return STATUS_NO_MEMORY; /* Set up the minimal information for it */ InitializeListHead(&CsrRootProcess->ListLink); CsrRootProcess->ProcessHandle = (HANDLE)-1; CsrRootProcess->ClientId = NtCurrentTeb()->ClientId; /* Initialize the Thread Hash List */ for (i = 0; i < NUMBER_THREAD_HASH_BUCKETS; i++) InitializeListHead(&CsrThreadHashTable[i]); /* Initialize the Wait Lock */ return RtlInitializeCriticalSection(&CsrWaitListsLock); }
VOID NTAPI BaseInitializeVDM(VOID) { /* Initialize the list head */ InitializeListHead(&VDMConsoleListHead); /* Initialize the critical section */ RtlInitializeCriticalSection(&DosCriticalSection); RtlInitializeCriticalSection(&WowCriticalSection); }
VOID RtlpInitializeVectoredExceptionHandling(VOID) { InitializeListHead(&RtlpVectoredExceptionHead); RtlInitializeCriticalSection(&RtlpVectoredExceptionLock); RtlpVectoredExceptionsInstalled = 0; }
BOOLEAN InitializeInputHandle( PHANDLE_DATA HandleData, PINPUT_INFORMATION InputBuffer ) /*++ Routine Description: This routine initializes the input-specific fields of the handle data structure. Arguments: HandleData - Pointer to handle data structure. InputBuffer - Pointer to input buffer data structure. Return Value: --*/ { HandleData->InputReadData = (PINPUT_READ_HANDLE_DATA)HeapAlloc(pConHeap,MAKE_TAG( HANDLE_TAG ),sizeof(INPUT_READ_HANDLE_DATA)); if (!HandleData->InputReadData) { return FALSE; } RtlInitializeCriticalSection(&HandleData->InputReadData->ReadCountLock); HandleData->InputReadData->ReadCount = 0; HandleData->InputReadData->InputHandleFlags = 0; HandleData->Buffer.InputBuffer = InputBuffer; HandleData->Buffer.InputBuffer->RefCount++; return TRUE; }
VOID InitializeConsoleHandleTable( VOID ) /*++ Routine Description: This routine initializes the global console handle table. Arguments: none. Return Value: none. --*/ { RtlInitializeCriticalSection(&ConsoleHandleLock); RtlZeroMemory(InitialConsoleHandles, sizeof(InitialConsoleHandles)); ConsoleHandles = InitialConsoleHandles; NumberOfConsoleHandles = NELEM(InitialConsoleHandles); }
//---------------------------------------------------------------- // CImpIRestrictedProcess::RP_HelperInit() // //---------------------------------------------------------------- STDMETHODIMP CImpIRestrictedProcess::RP_HelperInit() { int iRet; WORD wVersion; WSADATA wsaData; NTSTATUS NtStatus; wVersion = MAKEWORD(1,1); iRet = WSAStartup( wVersion, &wsaData ); m_pSocketDict = new CSocketsDictionary; if (!m_pSocketDict) { return E_OUTOFMEMORY; } NtStatus = RtlInitializeCriticalSection(&m_cs); if (!NT_SUCCESS(NtStatus)) { delete m_pSocketDict; return E_UNEXPECTED; } return NOERROR; }
/* * WinObjInitGlobals * * Purpose: * * Initialize global variables. * */ BOOL WinObjInitGlobals() { SIZE_T cch; BOOL bResult = FALSE, bCond = FALSE; do { RtlSecureZeroMemory(&g_WinObj, sizeof(g_WinObj)); // // Query version info. // g_WinObj.osver.dwOSVersionInfoSize = sizeof(g_WinObj.osver); RtlGetVersion(&g_WinObj.osver); // // Remember hInstance. // g_WinObj.hInstance = GetModuleHandle(NULL); // // Create dedicated heap. // g_WinObj.Heap = RtlCreateHeap(HEAP_GROWABLE, NULL, 0, 0, NULL, NULL); if (g_WinObj.Heap == NULL) break; RtlSetHeapInformation(g_WinObj.Heap, HeapEnableTerminationOnCorruption, NULL, 0); RtlInitializeCriticalSection(&g_WinObj.Lock); // // Remember %TEMP% directory. // cch = ExpandEnvironmentStrings(L"%temp%", g_WinObj.szTempDirectory, MAX_PATH); if ((cch == 0) || (cch > MAX_PATH)) break; // // Remember Windows directory. // if (!GetWindowsDirectory(g_WinObj.szWindowsDirectory, MAX_PATH)) break; // // Remember System32 directory. // if (!GetSystemDirectory(g_WinObj.szSystemDirectory, MAX_PATH)) break; bResult = TRUE; } while (bCond); if (bResult == FALSE) { if (g_WinObj.Heap) RtlDestroyHeap(g_WinObj.Heap); } return bResult; }
VOID NTAPI RtlpInitializeVectoredExceptionHandling(VOID) { /* Initialize our two lists and the common lock */ RtlInitializeCriticalSection(&RtlpVectoredHandlerLock); InitializeListHead(&RtlpVectoredExceptionList); InitializeListHead(&RtlpVectoredContinueList); }
NTSTATUS NTAPI RpcpInitRpcServer ( VOID ) { /* Clear the reference count and initialize the critical section */ RpcpNumInstances = 0; return RtlInitializeCriticalSection((PVOID)&RpcpCriticalSection); }
/* * @implemented */ VOID WINAPI InitializeCriticalSection(OUT LPCRITICAL_SECTION lpCriticalSection) { NTSTATUS Status; /* Initialize the critical section and raise an exception if we failed */ Status = RtlInitializeCriticalSection((PVOID)lpCriticalSection); if (!NT_SUCCESS(Status)) RtlRaiseStatus(Status); }
static void mutex_real_init( pthread_mutex_t *mutex ) { CRITICAL_SECTION *critsect = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(CRITICAL_SECTION)); RtlInitializeCriticalSection(critsect); if (interlocked_cmpxchg_ptr((void**)&(((wine_mutex)mutex)->critsect),critsect,NULL) != NULL) { /* too late, some other thread already did it */ RtlDeleteCriticalSection(critsect); RtlFreeHeap(GetProcessHeap(), 0, critsect); } }
/*++ * @name CsrInitializeNtSessionList * * The CsrInitializeNtSessionList routine sets up support for CSR Sessions. * * @param None * * @return None * * @remarks None. * *--*/ NTSTATUS NTAPI CsrInitializeNtSessionList(VOID) { DPRINT("CSRSRV: %s called\n", __FUNCTION__); /* Initialize the Session List */ InitializeListHead(&CsrNtSessionList); /* Initialize the Session Lock */ return RtlInitializeCriticalSection(&CsrNtSessionLock); }
/* * @implemented */ HSEMAPHORE WINAPI EngCreateSemaphore ( VOID ) { PRTL_CRITICAL_SECTION CritSect = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(RTL_CRITICAL_SECTION)); if (!CritSect) { return NULL; } RtlInitializeCriticalSection( CritSect ); return (HSEMAPHORE)CritSect; }
NTSTATUS LsapAdtInitializeLogQueue( ) /*++ Routine Description: This function initializes the Audit Log Queue. Arguments: None. Return Values: NTSTATUS - Standard Nt Result Code Currently, STATUS_SUCCESS is always returned. --*/ { NTSTATUS Status = STATUS_SUCCESS; Status = RtlInitializeCriticalSection(&LsapAdtQueueLock); if (NT_SUCCESS(Status)) { Status = RtlInitializeCriticalSection(&LsapAdtLogFullLock); } LsapAdtLogQueue.FirstQueuedRecord = NULL; LsapAdtLogQueue.LastQueuedRecord = NULL; return(Status); }
VOID NTAPI RtlInitializeHeapManager(VOID) { PPEB Peb; /* Get PEB */ Peb = RtlGetCurrentPeb(); /* Initialize heap-related fields of PEB */ Peb->NumberOfHeaps = 0; /* Initialize the process heaps list protecting lock */ RtlInitializeCriticalSection(&RtlpProcessHeapsListLock); }
VOID WINAPI GdiProcessSetup (VOID) { hProcessHeap = GetProcessHeap(); /* map the gdi handle table to user space */ GdiHandleTable = NtCurrentTeb()->ProcessEnvironmentBlock->GdiSharedHandleTable; GdiSharedHandleTable = NtCurrentTeb()->ProcessEnvironmentBlock->GdiSharedHandleTable; GdiDevCaps = &GdiSharedHandleTable->DevCaps; CurrentProcessId = NtCurrentTeb()->ClientId.UniqueProcess; GDI_BatchLimit = (DWORD) NtCurrentTeb()->ProcessEnvironmentBlock->GdiDCAttributeList; GdiHandleCache = (PGDIHANDLECACHE)NtCurrentTeb()->ProcessEnvironmentBlock->GdiHandleBuffer; RtlInitializeCriticalSection(&semLocal); }
BOOL Init(VOID) { USERCONNECT UserCon; /* Set PEB data */ NtCurrentPeb()->KernelCallbackTable = apfnDispatch; NtCurrentPeb()->PostProcessInitRoutine = NULL; NtUserProcessConnect( NtCurrentProcess(), &UserCon, sizeof(USERCONNECT)); g_ppi = GetWin32ClientInfo()->ppi; // Snapshot PI, used as pointer only! g_ulSharedDelta = UserCon.siClient.ulSharedDelta; gpsi = SharedPtrToUser(UserCon.siClient.psi); gHandleTable = SharedPtrToUser(UserCon.siClient.aheList); gHandleEntries = SharedPtrToUser(gHandleTable->handles); RtlInitializeCriticalSection(&gcsUserApiHook); gfServerProcess = FALSE; // FIXME HAX! Used in CsrClientConnectToServer(,,,,&gfServerProcess); //CsrClientConnectToServer(L"\\Windows", 0, NULL, 0, &gfServerProcess); //ERR("1 SI 0x%x : HT 0x%x : D 0x%x\n", UserCon.siClient.psi, UserCon.siClient.aheList, g_ulSharedDelta); /* Allocate an index for user32 thread local data. */ User32TlsIndex = TlsAlloc(); if (User32TlsIndex != TLS_OUT_OF_INDEXES) { if (MessageInit()) { if (MenuInit()) { InitializeCriticalSection(&U32AccelCacheLock); GdiDllInitialize(NULL, DLL_PROCESS_ATTACH, NULL); LoadAppInitDlls(); return TRUE; } MessageCleanup(); } TlsFree(User32TlsIndex); } return FALSE; }
static void wine_cond_real_init(pthread_cond_t *cond) { wine_cond_detail *detail = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(wine_cond_detail)); detail->waiters_count = 0; detail->was_broadcast = 0; NtCreateSemaphore( &detail->sema, SEMAPHORE_ALL_ACCESS, NULL, 0, 0x7fffffff ); NtCreateEvent( &detail->waiters_done, EVENT_ALL_ACCESS, NULL, FALSE, FALSE ); RtlInitializeCriticalSection (&detail->waiters_count_lock); if (interlocked_cmpxchg_ptr((void**)&(((wine_cond)cond)->cond), detail, NULL) != NULL) { /* too late, some other thread already did it */ P_OUTPUT("FIXME:pthread_cond_init:expect troubles...\n"); NtClose(detail->sema); RtlDeleteCriticalSection(&detail->waiters_count_lock); NtClose(detail->waiters_done); RtlFreeHeap(GetProcessHeap(), 0, detail); } }
VOID NTAPI BaseSrvNLSInit(IN PBASE_STATIC_SERVER_DATA StaticData) { /* Initialize the lock */ RtlInitializeCriticalSection(&NlsCacheCriticalSection); /* Initialize the data with all F's */ pNlsRegUserInfo = &StaticData->NlsUserInfo; RtlFillMemory(&StaticData->NlsUserInfo, sizeof(StaticData->NlsUserInfo), 0xFF); /* Set empty LCID */ pNlsRegUserInfo->UserLocaleId = 0; /* Reset the cache update counter */ RtlEnterCriticalSection(&NlsCacheCriticalSection); pNlsRegUserInfo->ulCacheUpdateCount = 0; RtlLeaveCriticalSection(&NlsCacheCriticalSection); /* Get the LCID */ NtQueryDefaultLocale(0, &pNlsRegUserInfo->UserLocaleId); }
VOID InitializeCriticalSection( LPCRITICAL_SECTION lpCriticalSection ) /*++ Routine Description: A critical section object is initialized using Win32InitializeCriticalSection. Once a critical section object has been initialized threads within a single process may enter and exit critical sections using the critical section object. A critical section object may not me moved or copied. The application must also not modify the insides of the object, but must treat it as logically opaque. description-of-function. Arguments: lpCriticalSection - Supplies the address of a critical section object to be initialized. It is the callers resposibility to allocate the storage used by a critical section object. Return Value: None. --*/ { NTSTATUS Status; Status = RtlInitializeCriticalSection(lpCriticalSection); if ( !NT_SUCCESS(Status) ) { RtlRaiseStatus(Status); } }
//------------------------------------------------------------------------ // CSocketMap::Initialize() // // Initialize must be call before using a CSocketMap. Return TRUE on // success, FALSE on failure. //------------------------------------------------------------------------ BOOL CSocketMap::Initialize( DWORD dwNewMapSize ) { if (!dwNewMapSize) { return FALSE; } // If the map size has already been set, then initialize has // already been called successfully. if (!m_dwMapSize) { m_pMap = new SOCKET_MAP_ENTRY [dwNewMapSize]; if (!m_pMap) { return FALSE; } NTSTATUS Status = RtlInitializeCriticalSection(&m_cs); if (!NT_SUCCESS(Status)) { m_dwMapSize = 0; delete m_pMap; m_pMap = 0; return FALSE; } m_dwMapSize = dwNewMapSize; for (DWORD i=0; i<m_dwMapSize; i++) { m_pMap[i].hSocket = INVALID_SOCKET; m_pMap[i].pRSocket = 0; } } return TRUE; }
BOOL WINAPI BasepInitConsole(VOID) { NTSTATUS Status; PRTL_USER_PROCESS_PARAMETERS Parameters = NtCurrentPeb()->ProcessParameters; WCHAR SessionDir[256]; ULONG SessionId = NtCurrentPeb()->SessionId; BOOLEAN InServer; CONSOLE_CONNECTION_INFO ConnectInfo; ULONG ConnectInfoSize = sizeof(ConnectInfo); DPRINT("BasepInitConsole for : %wZ\n", &Parameters->ImagePathName); DPRINT("Our current console handles are: %lx, %lx, %lx %lx\n", Parameters->ConsoleHandle, Parameters->StandardInput, Parameters->StandardOutput, Parameters->StandardError); /* Initialize our global console DLL lock */ Status = RtlInitializeCriticalSection(&ConsoleLock); if (!NT_SUCCESS(Status)) return FALSE; ConsoleInitialized = TRUE; /* Do nothing if this isn't a console app... */ if (RtlImageNtHeader(GetModuleHandle(NULL))->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI) { DPRINT("Image is not a console application\n"); Parameters->ConsoleHandle = NULL; ConnectInfo.ConsoleNeeded = FALSE; // ConsoleNeeded is used for knowing whether or not this is a CUI app. ConnectInfo.ConsoleStartInfo.ConsoleTitle[0] = L'\0'; ConnectInfo.ConsoleStartInfo.AppPath[0] = L'\0'; } else { LPCWSTR ExeName; InitConsoleInfo(&ConnectInfo.ConsoleStartInfo, &Parameters->ImagePathName); /* Initialize Input EXE name */ ExeName = wcsrchr(Parameters->ImagePathName.Buffer, L'\\'); if (ExeName) SetConsoleInputExeNameW(ExeName + 1); /* Assume one is needed */ ConnectInfo.ConsoleNeeded = TRUE; /* Handle the special flags given to us by BasePushProcessParameters */ if (Parameters->ConsoleHandle == HANDLE_DETACHED_PROCESS) { /* No console to create */ DPRINT("No console to create\n"); Parameters->ConsoleHandle = NULL; ConnectInfo.ConsoleNeeded = FALSE; } else if (Parameters->ConsoleHandle == HANDLE_CREATE_NEW_CONSOLE) { /* We'll get the real one soon */ DPRINT("Creating new console\n"); Parameters->ConsoleHandle = NULL; } else if (Parameters->ConsoleHandle == HANDLE_CREATE_NO_WINDOW) { /* We'll get the real one soon */ DPRINT("Creating new invisible console\n"); Parameters->ConsoleHandle = NULL; ConnectInfo.ConsoleStartInfo.ShowWindow = SW_HIDE; } else { if (Parameters->ConsoleHandle == INVALID_HANDLE_VALUE) { Parameters->ConsoleHandle = NULL; } DPRINT("Using existing console: %x\n", Parameters->ConsoleHandle); } } /* Now use the proper console handle */ ConnectInfo.Console = Parameters->ConsoleHandle; /* Initialize the Console Ctrl Handler */ InitConsoleCtrlHandling(); ConnectInfo.CtrlDispatcher = ConsoleControlDispatcher; /* Initialize the Property Dialog Handler */ ConnectInfo.PropDispatcher = PropDialogHandler; /* Setup the right Object Directory path */ if (!SessionId) { /* Use the raw path */ wcscpy(SessionDir, WIN_OBJ_DIR); } else { /* Use the session path */ swprintf(SessionDir, L"%ws\\%ld%ws", SESSION_DIR, SessionId, WIN_OBJ_DIR); } /* Connect to the Console Server */ DPRINT("Connecting to the Console Server in BasepInitConsole...\n"); Status = CsrClientConnectToServer(SessionDir, CONSRV_SERVERDLL_INDEX, &ConnectInfo, &ConnectInfoSize, &InServer); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to connect to the Console Server (Status %lx)\n", Status); return FALSE; } /* Nothing to do for server-to-server */ if (InServer) return TRUE; /* Nothing to do if not a console app */ if (!ConnectInfo.ConsoleNeeded) return TRUE; /* We got the handles, let's set them */ if ((Parameters->ConsoleHandle = ConnectInfo.Console)) { /* If we already had some, don't use the new ones */ if (!Parameters->StandardInput) { Parameters->StandardInput = ConnectInfo.InputHandle; } if (!Parameters->StandardOutput) { Parameters->StandardOutput = ConnectInfo.OutputHandle; } if (!Parameters->StandardError) { Parameters->StandardError = ConnectInfo.ErrorHandle; } } InputWaitHandle = ConnectInfo.InputWaitHandle; DPRINT("Console setup: %lx, %lx, %lx, %lx\n", Parameters->ConsoleHandle, Parameters->StandardInput, Parameters->StandardOutput, Parameters->StandardError); return TRUE; }
/*++ * @name CsrSbCreateSession * * The CsrSbCreateSession API is called by the Session Manager whenever a new * session is created. * * @param ApiMessage * Pointer to the Session Manager API Message. * * @return TRUE in case of success, FALSE otherwise. * * @remarks The CsrSbCreateSession routine will initialize a new CSR NT * Session and allocate a new CSR Process for the subsystem process. * *--*/ BOOLEAN NTAPI CsrSbCreateSession(IN PSB_API_MSG ApiMessage) { PSB_CREATE_SESSION_MSG CreateSession = &ApiMessage->CreateSession; HANDLE hProcess, hThread; PCSR_PROCESS CsrProcess; NTSTATUS Status; KERNEL_USER_TIMES KernelTimes; PCSR_THREAD CsrThread; //PVOID ProcessData; //ULONG i; /* Save the Process and Thread Handles */ hProcess = CreateSession->ProcessInfo.ProcessHandle; hThread = CreateSession->ProcessInfo.ThreadHandle; /* Lock the Processes */ CsrAcquireProcessLock(); /* Allocate a new process */ CsrProcess = CsrAllocateProcess(); if (!CsrProcess) { /* Fail */ ApiMessage->ReturnValue = STATUS_NO_MEMORY; CsrReleaseProcessLock(); return TRUE; } /* Set the exception port */ Status = NtSetInformationProcess(hProcess, ProcessExceptionPort, &CsrApiPort, sizeof(HANDLE)); /* Check for success */ if (!NT_SUCCESS(Status)) { /* Fail the request */ CsrDeallocateProcess(CsrProcess); CsrReleaseProcessLock(); /* Strange as it seems, NTSTATUSes are actually returned */ return (BOOLEAN)STATUS_NO_MEMORY; } /* Get the Create Time */ Status = NtQueryInformationThread(hThread, ThreadTimes, &KernelTimes, sizeof(KERNEL_USER_TIMES), NULL); /* Check for success */ if (!NT_SUCCESS(Status)) { /* Fail the request */ CsrDeallocateProcess(CsrProcess); CsrReleaseProcessLock(); /* Strange as it seems, NTSTATUSes are actually returned */ return (BOOLEAN)Status; } /* Allocate a new Thread */ CsrThread = CsrAllocateThread(CsrProcess); if (!CsrThread) { /* Fail the request */ CsrDeallocateProcess(CsrProcess); CsrReleaseProcessLock(); ApiMessage->ReturnValue = STATUS_NO_MEMORY; return TRUE; } /* Setup the Thread Object */ CsrThread->CreateTime = KernelTimes.CreateTime; CsrThread->ClientId = CreateSession->ProcessInfo.ClientId; CsrThread->ThreadHandle = hThread; ProtectHandle(hThread); CsrThread->Flags = 0; /* Insert it into the Process List */ CsrInsertThread(CsrProcess, CsrThread); /* Setup Process Data */ CsrProcess->ClientId = CreateSession->ProcessInfo.ClientId; CsrProcess->ProcessHandle = hProcess; CsrProcess->NtSession = CsrAllocateNtSession(CreateSession->SessionId); /* Set the Process Priority */ CsrSetBackgroundPriority(CsrProcess); #if 0 /* Get the first data location */ ProcessData = &CsrProcess->ServerData[CSR_SERVER_DLL_MAX]; /* Loop every DLL */ for (i = 0; i < CSR_SERVER_DLL_MAX; i++) { /* Check if the DLL is loaded and has Process Data */ if (CsrLoadedServerDll[i] && CsrLoadedServerDll[i]->SizeOfProcessData) { /* Write the pointer to the data */ CsrProcess->ServerData[i] = ProcessData; /* Move to the next data location */ ProcessData = (PVOID)((ULONG_PTR)ProcessData + CsrLoadedServerDll[i]->SizeOfProcessData); } else { /* Nothing for this Process */ CsrProcess->ServerData[i] = NULL; } } #else /* HACKZ: should go in BaseSrv part of CreateCallback done in Insert below */ RtlInitializeCriticalSection(&CsrProcess->HandleTableLock); #endif /* Insert the Process */ CsrInsertProcess(NULL, NULL, CsrProcess); /* Activate the Thread */ ApiMessage->ReturnValue = NtResumeThread(hThread, NULL); /* Release lock and return */ CsrReleaseProcessLock(); return TRUE; }
BOOL WINAPI DllMain(HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { NTSTATUS Status; BASESRV_API_CONNECTINFO ConnectInfo; ULONG ConnectInfoSize = sizeof(ConnectInfo); WCHAR SessionDir[256]; DPRINT("DllMain(hInst %p, dwReason %lu)\n", hDll, dwReason); Basep8BitStringToUnicodeString = RtlAnsiStringToUnicodeString; /* Cache the PEB and Session ID */ Peb = NtCurrentPeb(); SessionId = Peb->SessionId; switch (dwReason) { case DLL_PROCESS_ATTACH: { /* Set no filter initially */ GlobalTopLevelExceptionFilter = RtlEncodePointer(NULL); /* Enable the Rtl thread pool and timer queue to use proper Win32 thread */ RtlSetThreadPoolStartFunc(BaseCreateThreadPoolThread, BaseExitThreadPoolThread); /* Register the manifest prober routine */ LdrSetDllManifestProber(BasepProbeForDllManifest); /* Don't bother us for each thread */ LdrDisableThreadCalloutsForDll((PVOID)hDll); /* Initialize default path to NULL */ RtlInitUnicodeString(&BaseDefaultPath, NULL); /* Setup the Object Directory path */ if (!SessionId) { /* Use the raw path */ wcscpy(SessionDir, WIN_OBJ_DIR); } else { /* Use the session path */ swprintf(SessionDir, L"%ws\\%ld%ws", SESSION_DIR, SessionId, WIN_OBJ_DIR); } /* Connect to the Base Server */ Status = CsrClientConnectToServer(SessionDir, BASESRV_SERVERDLL_INDEX, &ConnectInfo, &ConnectInfoSize, &BaseRunningInServerProcess); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to connect to CSR (Status %lx)\n", Status); NtTerminateProcess(NtCurrentProcess(), Status); return FALSE; } /* Get the server data */ ASSERT(Peb->ReadOnlyStaticServerData); BaseStaticServerData = Peb->ReadOnlyStaticServerData[BASESRV_SERVERDLL_INDEX]; ASSERT(BaseStaticServerData); /* Check if we are running a CSR Server */ if (!BaseRunningInServerProcess) { /* Set the termination port for the thread */ DPRINT("Creating new thread for CSR\n"); CsrNewThread(); } /* Initialize heap handle table */ BaseDllInitializeMemoryManager(); /* Set HMODULE for our DLL */ kernel32_handle = hCurrentModule = hDll; /* Set the directories */ BaseWindowsDirectory = BaseStaticServerData->WindowsDirectory; BaseWindowsSystemDirectory = BaseStaticServerData->WindowsSystemDirectory; /* Construct the default path (using the static buffer) */ _snwprintf(BaseDefaultPathBuffer, sizeof(BaseDefaultPathBuffer) / sizeof(WCHAR), L".;%wZ;%wZ\\system;%wZ;", &BaseWindowsSystemDirectory, &BaseWindowsDirectory, &BaseWindowsDirectory); BaseDefaultPath.Buffer = BaseDefaultPathBuffer; BaseDefaultPath.Length = wcslen(BaseDefaultPathBuffer) * sizeof(WCHAR); BaseDefaultPath.MaximumLength = sizeof(BaseDefaultPathBuffer); /* Use remaining part of the default path buffer for the append path */ BaseDefaultPathAppend.Buffer = (PWSTR)((ULONG_PTR)BaseDefaultPathBuffer + BaseDefaultPath.Length); BaseDefaultPathAppend.Length = 0; BaseDefaultPathAppend.MaximumLength = BaseDefaultPath.MaximumLength - BaseDefaultPath.Length; /* Initialize command line */ InitCommandLines(); /* Initialize the DLL critical section */ RtlInitializeCriticalSection(&BaseDllDirectoryLock); /* Initialize the National Language Support routines */ if (!NlsInit()) { DPRINT1("NLS Init failed\n"); return FALSE; } /* Initialize Console Support */ if (!ConDllInitialize(dwReason, SessionDir)) { DPRINT1("Failed to set up console\n"); return FALSE; } /* Initialize application certification globals */ InitializeListHead(&BasepAppCertDllsList); RtlInitializeCriticalSection(&gcsAppCert); /* Insert more dll attach stuff here! */ DllInitialized = TRUE; break; } case DLL_PROCESS_DETACH: { if (DllInitialized != FALSE) { /* Uninitialize console support */ ConDllInitialize(dwReason, NULL); /* Insert more dll detach stuff here! */ NlsUninit(); /* Delete DLL critical section */ RtlDeleteCriticalSection(&BaseDllDirectoryLock); } break; } case DLL_THREAD_ATTACH: { /* ConDllInitialize sets the current console locale for the new thread */ return ConDllInitialize(dwReason, NULL); } default: break; } return TRUE; }
NET_API_STATUS BrCreateNetwork( PUNICODE_STRING TransportName, IN BOOLEAN Wannish, IN BOOLEAN Ras, IN PUNICODE_STRING AlternateTransportName OPTIONAL ) /*++ Routine Description: This routine allocates memory to hold a network structure, and initializes all of its associated data structures. Arguments: TransportName - The name of the transport to add. Return Value: Status of operation (mostly status of allocations). --*/ { NET_API_STATUS Status; PNETWORK Network; BOOLEAN NetworkLockInitialized = FALSE; BOOLEAN MasterFlagsInitialized = FALSE; BOOLEAN BackupBrowserTimerCreated = FALSE; BOOLEAN MasterBrowserTimerCreated =FALSE; BOOLEAN AnnouncementTimerCreated = FALSE; BOOLEAN ResponseCacheLockInitialized = FALSE; // // Check to see if the transport already exists. // if ((Network = BrFindNetwork(TransportName)) != NULL) { return NERR_AlreadyExists; } // // If this transport is explicitly on our list of transports to unbind, // simply ignore the transport. // if (BrInfo.UnboundBindings != NULL) { LPTSTR_ARRAY TStrArray = BrInfo.UnboundBindings; while (!NetpIsTStrArrayEmpty(TStrArray)) { LPWSTR NewTransportName; #define NAME_PREFIX L"\\Device\\" #define NAME_PREFIX_LENGTH 8 // // The transport name in the registry is only optionally prefixed with \device\ // if ( _wcsnicmp( NAME_PREFIX, TStrArray, NAME_PREFIX_LENGTH) == 0 ) { NewTransportName = TransportName->Buffer; } else { NewTransportName = TransportName->Buffer + NAME_PREFIX_LENGTH; } if ( _wcsicmp( TStrArray, NewTransportName ) == 0 ) { dprintf(INIT, ("Binding is marked as unbound: %s (Silently ignoring)\n", TransportName->Buffer )); return NERR_Success; } TStrArray = NetpNextTStrArrayEntry(TStrArray); } } // // If this transport isn't bound to the SMB server, // don't create the transport here. // we do announcments through the SMB server. // Status = I_NetServerSetServiceBits(NULL, TransportName->Buffer, 0, TRUE); if (Status == ERROR_PATH_NOT_FOUND ) { dprintf(INIT, ("SMB Server doesn't have this transport: %s (Silently unbinding)\n", TransportName->Buffer )); return NERR_Success; } // // Create the transport. // try { Network = MIDL_user_allocate(sizeof(NETWORK)); if (Network == NULL) { try_return(Status = ERROR_NOT_ENOUGH_MEMORY); } RtlInitializeResource(&Network->Lock); NetworkLockInitialized = TRUE; Network->LockCount = 0; Network->ReferenceCount = 1; Network->Role = BrDefaultRole; Network->NumberOfFailedBackupTimers = 0; Network->NumberOfFailedPromotions = 0; Network->NumberOfPromotionEventsLogged = 0; Network->LastBackupBrowserReturned = 0; Network->LastDomainControllerBrowserReturned = 0; Network->TimeStoppedBackup = 0; Network->BackupServerList = NULL; Network->BackupDomainList = NULL; Network->TotalBackupServerListEntries = 0; Network->TotalBackupDomainListEntries = 0; Network->NetworkName.Buffer = MIDL_user_allocate(TransportName->MaximumLength); if (Network->NetworkName.Buffer == NULL) { try_return(Status = ERROR_NOT_ENOUGH_MEMORY); } Network->NetworkName.MaximumLength = TransportName->MaximumLength; RtlCopyUnicodeString(&Network->NetworkName, TransportName); Network->Flags = 0; if (ARGUMENT_PRESENT(AlternateTransportName)) { PNETWORK AlternateNetwork = BrFindNetwork(AlternateTransportName); // // If we didn't find an alternate network, or if that network // already has an alternate network, return an error. // if (AlternateNetwork == NULL || AlternateNetwork->AlternateNetwork != NULL) { try_return(Status = NERR_InternalError); } Network->Flags |= NETWORK_IPX; // // Link the two networks together. // Network->AlternateNetwork = AlternateNetwork; AlternateNetwork->AlternateNetwork = Network; } else { Network->AlternateNetwork = NULL; } // // Null terminate the network name buffer. // Network->NetworkName.Buffer[Network->NetworkName.Length/sizeof(WCHAR)] = UNICODE_NULL; RtlInitUnicodeString(&Network->MasterBrowserName, NULL); if (Wannish) { Network->Flags |= NETWORK_WANNISH; } if (Ras) { Network->Flags |= NETWORK_RAS; } Network->LastBowserServerQueried = 0; RtlInitializeCriticalSection(&Network->MasterFlagsLock); MasterFlagsInitialized = TRUE; Network->MasterFlags = 0; InitializeInterimServerList(&Network->BrowseTable, BrBrowseTableInsertRoutine, BrBrowseTableUpdateRoutine, BrBrowseTableDeleteRoutine, BrBrowseTableAgeRoutine); Network->LastBowserDomainQueried = 0; InitializeInterimServerList(&Network->DomainList, BrDomainTableInsertRoutine, BrDomainTableUpdateRoutine, BrDomainTableDeleteRoutine, BrDomainTableAgeRoutine); InitializeListHead(&Network->OtherDomainsList); Status = BrCreateTimer(&Network->BackupBrowserTimer); if (Status != NERR_Success) { try_return(Status); } BackupBrowserTimerCreated = TRUE; Status = BrCreateTimer(&Network->MasterBrowserTimer); if (Status != NERR_Success) { try_return(Status); } MasterBrowserTimerCreated = TRUE; Status = BrCreateTimer(&Network->MasterBrowserAnnouncementTimer); if (Status != NERR_Success) { try_return(Status); } AnnouncementTimerCreated = TRUE; InitializeCriticalSection(&Network->ResponseCacheLock); ResponseCacheLockInitialized = TRUE; InitializeListHead(&Network->ResponseCache); Network->TimeCacheFlushed = 0; Network->NumberOfCachedResponses = 0; Status = RtlEnterCriticalSection(&NetworkLock); if (!NT_SUCCESS(Status)) { try_return(Status = BrMapStatus(Status)); } InsertHeadList(&ServicedNetworks, &Network->NextNet); Status = RtlLeaveCriticalSection(&NetworkLock); if (!NT_SUCCESS(Status)) { InternalError(("Unable to release browser critical section\n")); } try_exit:NOTHING; } finally { if (Status != NERR_Success) { if (Network != NULL) { if (ResponseCacheLockInitialized) { DeleteCriticalSection(&Network->ResponseCacheLock); } if (MasterFlagsInitialized) { RtlDeleteCriticalSection(&Network->MasterFlagsLock); } if (NetworkLockInitialized) { RtlDeleteResource(&Network->Lock); } if (AnnouncementTimerCreated) { BrDestroyTimer(&Network->MasterBrowserAnnouncementTimer); } if (MasterBrowserTimerCreated) { BrDestroyTimer(&Network->MasterBrowserTimer); } if (BackupBrowserTimerCreated) { BrDestroyTimer(&Network->BackupBrowserTimer); } if (Network->NetworkName.Buffer != NULL) { MIDL_user_free(Network->NetworkName.Buffer); } MIDL_user_free(Network); } } } return Status; }
VOID BaseInitDefineDosDevice(VOID) { RtlInitializeCriticalSection(&BaseDefineDosDeviceCritSec); InitializeListHead(&DosDeviceHistory); }
NTSTATUS UserServerDllInitialization( PCSR_SERVER_DLL psrvdll) { CLIENT_ID ClientId; DWORD cbAllocated; NTSTATUS Status; int i; /* * Initialize a critical section structure that will be used to protect * all of the User Server's critical sections (except a few special * cases like the RIT -- see below). */ RtlInitializeCriticalSection(&gcsUserSrv); EnterCrit(); // synchronize heap calls /* * Remember WINSRV.DLL's hmodule so we can grab resources from it later. */ hModuleWin = psrvdll->ModuleHandle; psrvdll->ApiNumberBase = USERK_FIRST_API_NUMBER; psrvdll->MaxApiNumber = UserpMaxApiNumber; psrvdll->ApiDispatchTable = UserServerApiDispatchTable; psrvdll->ApiServerValidTable = UserServerApiServerValidTable; #if DBG psrvdll->ApiNameTable = UserServerApiNameTable; #else psrvdll->ApiNameTable = NULL; #endif psrvdll->PerProcessDataLength = CHANDLES * sizeof(HANDLE); psrvdll->PerThreadDataLength = 0; psrvdll->ConnectRoutine = UserClientConnect; psrvdll->DisconnectRoutine = UserClientDisconnect; psrvdll->HardErrorRoutine = UserHardError; psrvdll->ShutdownProcessRoutine = UserClientShutdown; /* * Create these events used by shutdown */ NtCreateEvent(&heventCancel, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE); NtCreateEvent(&heventCancelled, EVENT_ALL_ACCESS, NULL, NotificationEvent, FALSE); /* * Tell the base what user address to call when it is creating a process * (but before the process starts running). */ BaseSetProcessCreateNotify(NtUserNotifyProcessCreate); /* * Set up translation tables. */ InitOemXlateTables(); /* * Get timeout values from registry */ GetTimeouts(); /* * Load some strings. */ pszaSUCCESS = (LPSTR)RtlLoadStringOrError(hModuleWin, STR_SUCCESS, NULL, &cbAllocated, TRUE); pszaSYSTEM_INFORMATION = (LPSTR)RtlLoadStringOrError(hModuleWin, STR_SYSTEM_INFORMATION, NULL, &cbAllocated, TRUE); pszaSYSTEM_WARNING = (LPSTR)RtlLoadStringOrError(hModuleWin, STR_SYSTEM_WARNING, NULL, &cbAllocated, TRUE); pszaSYSTEM_ERROR = (LPSTR)RtlLoadStringOrError(hModuleWin, STR_SYSTEM_ERROR, NULL, &cbAllocated, TRUE); /* * Add marlett font and make it permanent */ i = GdiAddFontResourceW(L"marlett.ttf", AFRW_ADD_LOCAL_FONT); /* * Initialize USER */ { HANDLE hModBase; LeaveCrit(); hModBase = GetModuleHandle(TEXT("kernel32")); EnterCrit(); UserAssert(hModBase); gpfnAttachRoutine = GetProcAddress(hModBase,"BaseAttachCompleteThunk"); UserAssert(gpfnAttachRoutine); Status = NtUserInitialize(USERCURRENTVERSION, gpfnAttachRoutine); if (!NT_SUCCESS(Status)) { goto ExitUserInit; } } /* * Start registry notification thread */ Status = RtlCreateUserThread(NtCurrentProcess(), NULL, FALSE, 0, 0, 4*0x1000, (PUSER_THREAD_START_ROUTINE)NotificationThread, NULL, &hThreadNotification, &ClientId); CsrAddStaticServerThread(hThreadNotification, &ClientId, 0); ExitUserInit: LeaveCrit(); return Status; }
NTSTATUS NTAPI ConSrvNewProcess(PCSR_PROCESS SourceProcess, PCSR_PROCESS TargetProcess) { /************************************************************************** * This function is called whenever a new process (GUI or CUI) is created. * * Copy the parent's handles table here if both the parent and the child * processes are CUI. If we must actually create our proper console (and * thus do not inherit from the console handles of the parent's), then we * will clean this table in the next ConSrvConnect call. Why we are doing * this? It's because here, we still don't know whether or not we must create * a new console instead of inherit it from the parent, and, because in * ConSrvConnect we don't have any reference to the parent process anymore. **************************************************************************/ NTSTATUS Status = STATUS_SUCCESS; PCONSOLE_PROCESS_DATA TargetProcessData; /* An empty target process is invalid */ if (!TargetProcess) return STATUS_INVALID_PARAMETER; TargetProcessData = ConsoleGetPerProcessData(TargetProcess); /* Initialize the new (target) process */ RtlZeroMemory(TargetProcessData, sizeof(*TargetProcessData)); TargetProcessData->Process = TargetProcess; TargetProcessData->ConsoleHandle = NULL; TargetProcessData->ConsoleApp = FALSE; /* * The handles table gets initialized either when inheriting from * another console process, or when creating a new console. */ TargetProcessData->HandleTableSize = 0; TargetProcessData->HandleTable = NULL; RtlInitializeCriticalSection(&TargetProcessData->HandleTableLock); /* Do nothing if the source process is NULL */ if (!SourceProcess) return STATUS_SUCCESS; // SourceProcessData = ConsoleGetPerProcessData(SourceProcess); /* * If the child process is a console application and the parent process is * either a console application or just has a valid console (with a valid * handles table: this can happen if it is a GUI application having called * AllocConsole), then try to inherit handles from the parent process. */ if (TargetProcess->Flags & CsrProcessIsConsoleApp /* && SourceProcessData->ConsoleHandle != NULL */) { PCONSOLE_PROCESS_DATA SourceProcessData = ConsoleGetPerProcessData(SourceProcess); PCONSRV_CONSOLE SourceConsole; /* Validate and lock the parent's console */ if (ConSrvValidateConsole(&SourceConsole, SourceProcessData->ConsoleHandle, CONSOLE_RUNNING, TRUE)) { /* Inherit the parent's handles table */ Status = ConSrvInheritHandlesTable(SourceProcessData, TargetProcessData); if (!NT_SUCCESS(Status)) { DPRINT1("Inheriting handles table failed\n"); } /* Unlock the parent's console */ LeaveCriticalSection(&SourceConsole->Lock); } } return Status; }
NET_API_STATUS BrInitializeNetworks( VOID ) /*++ Routine Description: This function will query the NT bowser device driver to determine the list of networks that the bowser is servicing. Arguments: None. Return Value: Status of operation. --*/ { NET_API_STATUS Status; PLMDR_TRANSPORT_LIST TransportList; PLMDR_TRANSPORT_LIST TransportEntry; InitializeListHead(&ServicedNetworks); RtlInitializeCriticalSection(&NetworkLock); Status = BrGetTransportList(&TransportList); TransportEntry = TransportList; while (TransportEntry != NULL) { UNICODE_STRING TransportName; TransportName.Buffer = TransportEntry->TransportName; TransportName.Length = (USHORT)TransportEntry->TransportNameLength; // // We know the bowser sticks in a null at the end, so the max length // is the length + 1. // TransportName.MaximumLength = (USHORT)TransportEntry->TransportNameLength+sizeof(WCHAR); Status = BrCreateNetwork(&TransportName, (BOOLEAN)((TransportEntry->Flags & LMDR_TRANSPORT_WANNISH) != 0), (BOOLEAN)((TransportEntry->Flags & LMDR_TRANSPORT_RAS) != 0), NULL); if (!NT_SUCCESS(Status)) { MIDL_user_free(TransportList); return Status; } NumberOfServicedNetworks += 1; if (TransportEntry->NextEntryOffset == 0) { TransportEntry = NULL; } else { TransportEntry = (PLMDR_TRANSPORT_LIST)((PCHAR)TransportEntry+TransportEntry->NextEntryOffset); } } MIDL_user_free(TransportList); return Status; }
void TIME_Init(void) { RtlInitializeCriticalSection( &TIME_sync_cs ); CRITICAL_SECTION_NAME( &TIME_sync_cs, "TIME_sync_cs" ); }