进程线程创建过程
一、進程創建過程
所有進程都通過 PspCreateProcess 函數創建,包括 System 進程。它被三個函數調用,分別是NtCreateProcessEx、PsCreateSystemProcess 和 PspInitPhase0 。
NtCreateProcessEx 是 CreateProcess 的內核服務;
PspInitPhase0 函數是系統初始化早期調用的,它創建了 System 進程,System 進程的句柄保存在全局變量 PspInitialSystemProcessHandle 中,EPROCESS 保存在 PsInitialSystemProcess 中;
PsCreateSystemProcess 是用來創建系統進程的,它創建的進程都是 PsInitialSystemProcess 的子進程。
PspCreateProcess 的大致流程在136-140頁分析了。這里簡單介紹一下,完整代碼放在文末。
- 創建進程對象
- 初始化進程對象
- 初始化內存區對象 SectionObject
- 初始化調試端口
- 初始化異常端口
- 創建進程地址空間
- 初始化進程基本優先級,CPU親和性,頁目錄基址,超空間頁幀號
- 初始化進程安全屬性(從父進程復制令牌)
- 設置優先級類別
- 初始化句柄表
- 初始化進程地址空間
- 創建進程ID
- 審計此次進程創建行為
- 作業相關操作
- 創建或復制PEB
- 新進程對象插入 PsActiveProcessHead 鏈表
- 新進程對象插入當前進程句柄表
- 計算新進程的基本優先級和時限重置值
- 設置進程訪問權限,當前進程句柄可訪問,允許進程終止
- 設置進程創建時間
PspCreateProcess 創建了進程,此時進程中的代碼還沒運行起來,進程還是死的,因為此時還沒有線程,接下來介紹線程的創建過程。
二、線程創建過程
NtCreateThread 和 PsCreateSystemThread 函數會調用 PspCreateThread ,分別用于創建用戶線程和系統線程。
下面簡單概括 PspCreateThread 創建線程的工作,可能有遺漏或錯誤。
- 獲取當前CPU模式
- 獲取進程對象
- 創建線程對象并初始化為0
- 設置父進程
- 創建CID
- 初始化線程結構的部分屬性
- 初始化定時器鏈表
- 如果是用戶線程,創建并初始化TEB,用 ThreadConatext 初始化R0 R3的入口點
- 如果是系統線程,用 StartRoutine 初始化R0入口點
- 不管是用戶線程還是內核線程,都調用 KeInitThread 初始化 Header, WaitBlock, ServiceTable, APC,定時器,內核棧等屬性
- 進程的活動線程計數加1
- 新線程加入進程的線程鏈表
- 調用 KeStartThread 初始化剩余的域,主要是和調度相關的優先級、時限、CPU親和性等
- 如果是該進程的第一個線程,則觸發該進程的創建通知
- 工作集相關的操作
- 線程對象的引用計數加2,一個針對當前的創建操作,一個針對要返回的線程句柄
- 如果 CreateSuspended 為真,指示新線程立即被掛起
- 根據指定的期望訪問權限,調用 SeCreateAccessStateEx 創建一個訪問狀態結構
- 把新線程對象插入到當前進程的句柄表
- 設置輸出參數 ThreadHandle
- 設置輸出參數 ClientId
- 設置線程創建時間
- 設置線程訪問權限
- 新線程加入就緒鏈表,等待調度;或者此時進程不在內存中,設置新線程狀態為轉移
- 引用計數減1
PspCreateThread 函數返回后,新線程隨時可以被調度執行。
三、創建進程的全貌
進程創建后才創建線程,但是 PspCreateProcess 函數中根本沒有創建線程的動作,也沒有打開進程可執行映像文件的代碼。在WRK中,我們看不到完整的進程創建過程,這是不行的!下面從 CreateProcess 函數調用開始,分析進程創建的全過程。
實際上,0環的東西已經分析過了,我們只需要分析3環 CreateProcessW 進0環之前干了啥就行。
CreateProcessW 本身沒干啥,而是調用了 CreateProcessInternalW 函數,源碼見文末。
CreateProcessInternalW 函數在 base\win32\client\process.c,總共 2582 行C代碼,我看不懂,主要是不知道怎么把文件名轉化成 SectionHandle 的,代碼實在太多了,而且有很多看不懂的操作。
BOOL WINAPI CreateProcessInternalW(HANDLE hUserToken,LPCWSTR lpApplicationName,LPWSTR lpCommandLine,LPSECURITY_ATTRIBUTES lpProcessAttributes,LPSECURITY_ATTRIBUTES lpThreadAttributes,BOOL bInheritHandles,DWORD dwCreationFlags,LPVOID lpEnvironment,LPCWSTR lpCurrentDirectory,LPSTARTUPINFOW lpStartupInfo,LPPROCESS_INFORMATION lpProcessInformation,PHANDLE hRestrictedUserToken)CreateProcessInternalW 打開指定的可執行文件,并創建一個內存區對象,注意,內存區對象并沒有被映射到內存中(由于目標進程尚未創建,不可能完成內存映射),但它確實是打開了。
接下來就是調用 ntdll 的 NtCreateProcessEx,通過系統調用,CPU模式變成內核模式,進入0環 KiSystemService / KiFastCallEntry 分發函數,然后調用執行體的 NtCreateProcessEx 函數。
接下來的工作我們先前已經分析過了,這里再次過一遍。NtCreateProcessEx 函數執行前面介紹的進程創建邏輯,包括創建并初始化 EPROCESS 對象,創建初始的進程地址空間,創建和初始化句柄表,設置 EPROCESS KPROCESS 的各種屬性,如進程優先級,安全屬性,創建時間等。到這里,執行體層的進程對象已經建立,進程地址空間已經初始化,PEB也已初始化。
接下來是創建線程,首先需要構造一個棧,和一個上下文環境。棧的大小通過映像文件獲得,創建線程通過 ntdll 的 NtCreateThread 調用執行體的 NtCreateThread 完成,具體工作就是先前介紹過的,包括創建并初始化 ETHREAD,生成線程ID,建立TEB和設置線程安全性。
進程的第一個線程啟動函數是 kernel32 的 BaseProcessStart ,這里創建的線程并不會立即執行,而是要等進程完全初始化后才執行。
到此為止,從內核角度來看,進程對象和第一個線程對象已經建立起來了,但是對子系統而言,進程創建才剛剛開始。kernel32 給windows子系統發送一個消息,消息中包括進程和線程的句柄、進程創建者的ID等必要信息。windows子系統 csrss.exe 接收到此消息,執行以下操作:
- 保留一份句柄
- 設定新進程的優先級類別
- 在子系統中分配一個內部進程塊
- 設置新進程的異常端口,從而子系統可以接收到該進程中發生的異常
- 對于被調試進程,設置它的調試端口,從而子系統可以接收到該進程的調試事件
- 分配并初始化一個內部線程塊,并插入到進程的線程列表中
- 窗口會話中的進程計數加1
- 設置進程的停機級別位默認級別
- 將新進程插入到子系統的進程列表中
- 分配并初始化一塊內存供子系統的內核模式部分使用(W32PROCESS結構)
- 顯示應用程序啟動光標
到此為止,進程環境已經建好,其線程將要使用的資源也分配好了,windows子系統已經知道并登記了此進程和線程。所以,初始線程被恢復執行,余下部分的初始化工作是在初始線程在新進程環境中完成的。在內核中,新線程啟動的例程是 KiThreadStartup 函數,這是在 PspCreateThread 函數中調用 KeInitThread 時,KeInitThread 函數又調用 KiInitializeContextThread 函數來設置的。
cPublicProc _KiThreadStartup ,1 xor ebx,ebx ; clear registers xor esi,esi ; xor edi,edi ; xor ebp,ebp ; LowerIrql APC_LEVEL ; KeLowerIrql(APC_LEVEL) pop eax ; (eax)->SystemRoutine call eax ; SystemRoutine(StartRoutine, StartContext) pop ecx ; (ecx) = UserContextFlag or ecx, ecx jz short kits10 ; No user context, go bugcheck mov ebp,esp ; (bp) -> TrapFrame holding UserContext jmp _KiServiceExit2 kits10: stdCall _KeBugCheck, <NO_USER_MODE_CONTEXT> stdENDP _KiThreadStartupKiThreadStartup 函數首先將 IRQL 降低到 APC_LEVEL,然后調用系統初始的線程函數 PspUserThreadStartup (PspCreateThread 函數在調用KeInitThread 時指定的,如果是創建系統線程,這里就是 PspSystemThreadStartup 函數)。線程啟動函數被作為一個參數傳遞給 PspUserThreadStartup ,此處應是 kernel32 的 BaseProcessStart。
PspUserThreadStartup 函數設置異步函數調用APC機制,基本流程如下:
-
獲得當前線程和進程對象。
-
是否由于創建過程中出錯而需要終止本線程。
-
如果需要,通知調試器。
-
如果這是進程中的第一個線程,則判斷系統是否支持應用程序預取的特性,如果
是,則通知緩存管理器預取可執行映像文件中的頁面(見2 106 行的CcPfBeginAppLaunch
調用)。所謂應用程序預取,是指將該進程上一次啟動的前10 s 內引用到的頁面直接讀
入到內存中。 -
然后,PspUserThreadStartup 把一個用戶模式APC 插入到線程的用戶APC 隊列中,
此APC 例程是在全局變量PspSystemDll 中指定的,指向ntdll.dll 的LdrInitializeThunk 函數。 -
接下來填充系統范圍的一個Cookie 值。
PspUserThreadStartup 返回后,KiThreadStartup 函數返回到用戶模式,此時,PspUserThreadStartup 插入的APC 被交付,于是 LdrInitializeThunk 函數被調用,這是映像加載器(image loader)的初始化函數,完成加載器,堆管理器等初始化工作,然后加載必要的dll,并調用它們的入口函數。最后,當 LdrInitializeThunk 返回到用戶模式 APC 分發器時,該線程開始在用戶模式下執行,調用應用程序指定的線程啟動函數,此啟動函數的地址已經在APC交付時被壓到用戶棧中。
至此,進程創建完畢,開始執行用戶空間中的代碼。
本文涉及的函數源碼
PspCreateProcess
NTSTATUS PspCreateProcess(OUT PHANDLE ProcessHandle,IN ACCESS_MASK DesiredAccess,IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,IN HANDLE ParentProcess OPTIONAL,IN ULONG Flags,IN HANDLE SectionHandle OPTIONAL,IN HANDLE DebugPort OPTIONAL,IN HANDLE ExceptionPort OPTIONAL,IN ULONG JobMemberLevel)/*++Routine Description:This routine creates and initializes a process object. It implements thefoundation for NtCreateProcess and for system initialization processcreation.這個函數創建并初始化一個進程對象。NtCreateProcess 會調用它;系統進程初始化也會調用它。Arguments:ProcessHandle - Returns the handle for the new process.輸出參數,返回新進程句柄DesiredAccess - Supplies the desired access modes to the new process.期望對新進程的訪問權限ObjectAttributes - Supplies the object attributes of the new process.新進程的對象屬性ParentProcess - Supplies a handle to the process' parent process. If thisparameter is not specified, then the process has no parentand is created using the system address space.指定父進程句柄。如果未指定,說明沒有父進程,那就是用系統地址空間創建進程。Flags - Process creation flags進程創建標志SectionHandle - Supplies a handle to a section object to be used to createthe process' address space. If this parameter is notspecified, then the address space is simply a clone of theparent process' address space.提供一個內存區對象句柄用來創建進程地址空間。如果此參數未指定,則簡單地復制父進程的地址空間。DebugPort - Supplies a handle to a port object that will be used as theprocess' debug port.調試端口句柄ExceptionPort - Supplies a handle to a port object that will be used as theprocess' exception port.異常端口句柄JobMemberLevel - Level for a create process in a jobset工作集等級 --*/{NTSTATUS Status;PEPROCESS Process;PEPROCESS CurrentProcess;PEPROCESS Parent;PETHREAD CurrentThread;KAFFINITY Affinity;KPRIORITY BasePriority;PVOID SectionObject;PVOID ExceptionPortObject;PVOID DebugPortObject;ULONG WorkingSetMinimum, WorkingSetMaximum;HANDLE LocalProcessHandle;KPROCESSOR_MODE PreviousMode;INITIAL_PEB InitialPeb;BOOLEAN CreatePeb;ULONG_PTR DirectoryTableBase[2];BOOLEAN AccessCheck;BOOLEAN MemoryAllocated;PSECURITY_DESCRIPTOR SecurityDescriptor;SECURITY_SUBJECT_CONTEXT SubjectContext;NTSTATUS accesst;NTSTATUS SavedStatus;ULONG ImageFileNameSize;HANDLE_TABLE_ENTRY CidEntry;PEJOB Job;PPEB Peb;AUX_ACCESS_DATA AuxData;PACCESS_STATE AccessState;ACCESS_STATE LocalAccessState;BOOLEAN UseLargePages;SCHAR QuantumReset; #if defined(_WIN64)INITIAL_PEB32 InitialPeb32; #endifPAGED_CODE();// 獲取當前線程、CPU模式、當前進程CurrentThread = PsGetCurrentThread ();PreviousMode = KeGetPreviousModeByThread(&CurrentThread->Tcb);CurrentProcess = PsGetCurrentProcessByThread (CurrentThread);CreatePeb = FALSE;UseLargePages = FALSE;DirectoryTableBase[0] = 0;DirectoryTableBase[1] = 0;Peb = NULL;//// Reject bogus create parameters for future expansion// 如果 Flags 里的保留位被置1,就是非法參數if (Flags&~PROCESS_CREATE_FLAGS_LEGAL_MASK) {return STATUS_INVALID_PARAMETER;}//// Parent// 檢查有無指定父進程// if (ARGUMENT_PRESENT (ParentProcess)) {// 如果指定了父進程句柄,就獲取它的EPROCESSStatus = ObReferenceObjectByHandle (ParentProcess,PROCESS_CREATE_PROCESS,PsProcessType,PreviousMode,&Parent,NULL);if (!NT_SUCCESS (Status)) {return Status;}// 工作集相關if (JobMemberLevel != 0 && Parent->Job == NULL) {ObDereferenceObject (Parent);return STATUS_INVALID_PARAMETER;}// 繼承父進程的CPU親和性Affinity = Parent->Pcb.Affinity;// 用全局變量初始化工作集最大最小值WorkingSetMinimum = PsMinimumWorkingSet;WorkingSetMaximum = PsMaximumWorkingSet;} else {// 沒有父進程Parent = NULL;Affinity = KeActiveProcessors;WorkingSetMinimum = PsMinimumWorkingSet;WorkingSetMaximum = PsMaximumWorkingSet;}//// Create the process object// 創建進程對象 EPROCESS//Status = ObCreateObject (PreviousMode,PsProcessType,ObjectAttributes,PreviousMode,NULL,sizeof (EPROCESS),0,0,&Process);if (!NT_SUCCESS (Status)) {goto exit_and_deref_parent;}//// The process object is created set to NULL. Errors// That occur after this step cause the process delete// routine to be entered.// EPROCESS 數據清零。此后發生的錯誤會導致調用進程刪除函數//// Teardown actions that occur in the process delete routine// do not need to be performed inline.//RtlZeroMemory (Process, sizeof(EPROCESS));ExInitializeRundownProtection (&Process->RundownProtect);PspInitializeProcessLock (Process);InitializeListHead (&Process->ThreadListHead);#if defined(_WIN64)if (Flags & PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE) {PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_OVERRIDE_ADDRESS_SPACE);}#endifPspInheritQuota (Process, Parent);ObInheritDeviceMap (Process, Parent);if (Parent != NULL) {Process->DefaultHardErrorProcessing = Parent->DefaultHardErrorProcessing;Process->InheritedFromUniqueProcessId = Parent->UniqueProcessId;} else {Process->DefaultHardErrorProcessing = PROCESS_HARDERROR_DEFAULT;Process->InheritedFromUniqueProcessId = NULL;}//// Section//if (ARGUMENT_PRESENT (SectionHandle)) {// 如果指定了內存區對象句柄參數 SectionHandle,就獲取內存區對象Status = ObReferenceObjectByHandle (SectionHandle,SECTION_MAP_EXECUTE,MmSectionObjectType,PreviousMode,&SectionObject,NULL);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}} else {// SectionHandle 參數為NULL,要看父進程是不是 System 進程SectionObject = NULL;if (Parent != PsInitialSystemProcess) {// 如果父進程不是 System 進程 ,那么內存區對象繼承自父進程//// Fetch the section pointer from the parent process// as we will be cloning. Since the section pointer// is removed at last thread exit we need to protect against// process exit here to be safe.//if (ExAcquireRundownProtection (&Parent->RundownProtect)) {SectionObject = Parent->SectionObject;if (SectionObject != NULL) {ObReferenceObject (SectionObject);}ExReleaseRundownProtection (&Parent->RundownProtect);}if (SectionObject == NULL) {Status = STATUS_PROCESS_IS_TERMINATING;goto exit_and_deref;}}// 如果父進程是 System 進程,那么 SectionObject 就是 NULL}// 內存區對象 SectionObject 初始化完成(如果是NULL則表示父進程是System進程)Process->SectionObject = SectionObject;//// DebugPort// 調試端口初始化if (ARGUMENT_PRESENT (DebugPort)) {Status = ObReferenceObjectByHandle (DebugPort,DEBUG_PROCESS_ASSIGN,DbgkDebugObjectType,PreviousMode,&DebugPortObject,NULL);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}Process->DebugPort = DebugPortObject;if (Flags&PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT) {PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_NO_DEBUG_INHERIT);}} else {if (Parent != NULL) {DbgkCopyProcessDebugPort (Process, Parent);}}//// ExceptionPort// 異常端口初始化if (ARGUMENT_PRESENT (ExceptionPort)) {Status = ObReferenceObjectByHandle (ExceptionPort,0,LpcPortObjectType,PreviousMode,&ExceptionPortObject,NULL);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}Process->ExceptionPort = ExceptionPortObject;}Process->ExitStatus = STATUS_PENDING;//// Clone parent's object table.// If no parent (booting) then use the current object table created in// ObInitSystem.//// 創建進程地址空間if (Parent != NULL) {// 如果有父進程//// Calculate address space//// If Parent == PspInitialSystem//// 創建一個全新的地址空間,這個函數有三個版本,wrk選 procx86.c 的if (!MmCreateProcessAddressSpace (WorkingSetMinimum,Process,&DirectoryTableBase[0])) {Status = STATUS_INSUFFICIENT_RESOURCES;goto exit_and_deref;}} else {// 如果沒有父進程// 復制當前進程的句柄表Process->ObjectTable = CurrentProcess->ObjectTable;//// Initialize the Working Set Mutex and address creation mutex// for this "hand built" process.// Normally, the call to MmInitializeAddressSpace initializes the// working set mutex, however, in this case, we have already initialized// the address space and we are now creating a second process using// the address space of the idle thread.//// 使用空閑線程的地址空間Status = MmInitializeHandBuiltProcess (Process, &DirectoryTableBase[0]);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}}// 進程地址空間初始化完成PS_SET_BITS (&Process->Flags, PS_PROCESS_FLAGS_HAS_ADDRESS_SPACE);Process->Vm.MaximumWorkingSetSize = WorkingSetMaximum;// 初始化進程基礎優先級,CPU親和性,頁目錄基址,超空間的頁幀號KeInitializeProcess (&Process->Pcb,NORMAL_BASE_PRIORITY,Affinity,&DirectoryTableBase[0],(BOOLEAN)(Process->DefaultHardErrorProcessing & PROCESS_HARDERROR_ALIGNMENT_BIT));//// Initialize the security fields of the process// The parent may be null exactly once (during system init).// Thereafter, a parent is always required so that we have a// security context to duplicate for the new process.//// 函數初始化新進程的安全屬性,主要是從父進程復制一個令牌Status = PspInitializeProcessSecurity (Parent, Process);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}// 設置新進程優先級類別Process->PriorityClass = PROCESS_PRIORITY_CLASS_NORMAL;if (Parent != NULL) {// 拷貝父進程的優先級類別if (Parent->PriorityClass == PROCESS_PRIORITY_CLASS_IDLE ||Parent->PriorityClass == PROCESS_PRIORITY_CLASS_BELOW_NORMAL) {Process->PriorityClass = Parent->PriorityClass;}//// if address space creation worked, then when going through// delete, we will attach. Of course, attaching means that the kprocess// must be initialized, so we delay the object stuff till here.// 如果地址空間已創建,// 初始化進程句柄表。如果指定父進程,則拷貝所有設置了繼承屬性的句柄,句柄計數加一Status = ObInitProcess ((Flags&PROCESS_CREATE_FLAGS_INHERIT_HANDLES) ? Parent : NULL,Process);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}} else {Status = MmInitializeHandBuiltProcess2 (Process);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}}Status = STATUS_SUCCESS;SavedStatus = STATUS_SUCCESS;//// Initialize the process address space// The address space has four possibilities// 初始化進程地址空間,有4種可能性//// 1 - Boot Process. Address space is initialized during// MmInit. Parent is not specified.// 引導進程,這種情況不在這里初始化地址空間,而是在 MmInitSystem 函數初始化//// 2 - System Process. Address space is a virgin address// space that only maps system space. Process is same// as PspInitialSystemProcess.// System 進程。地址空間未使用,映射到系統空間。//// 3 - User Process (Cloned Address Space). Address space// is cloned from the specified process.// 用戶進程(克隆父進程地址空間)//// 4 - User Process (New Image Address Space). Address space// is initialized so that it maps the specified section.// 用戶進程(新地址空間鏡像)//if (SectionHandle != NULL) {//// User Process (New Image Address Space). Don't specify Process to// clone, just SectionObject.//// Passing in the 4th parameter as below lets the EPROCESS struct contain its image file name, provided that// appropriate audit settings are enabled. Memory is allocated inside of MmInitializeProcessAddressSpace// and pointed to by ImageFileName, so that must be freed in the process deletion routine (PspDeleteProcess())//// 新進程指定了內存區對象,調用 MmInitializeProcessAddressSpace 函數初始化進程地址空間//Status = MmInitializeProcessAddressSpace (Process,NULL,SectionObject,&Flags,&(Process->SeAuditProcessCreationInfo.ImageFileName));if (!NT_SUCCESS (Status)) {goto exit_and_deref;}//// In order to support relocating executables, the proper status// (STATUS_IMAGE_NOT_AT_BASE) must be returned, so save it here.//SavedStatus = Status;CreatePeb = TRUE;UseLargePages = ((Flags & PROCESS_CREATE_FLAGS_LARGE_PAGES) != 0 ? TRUE : FALSE);} else if (Parent != NULL) {if (Parent != PsInitialSystemProcess) {Process->SectionBaseAddress = Parent->SectionBaseAddress;//// User Process ( Cloned Address Space ). Don't specify section to// map, just Process to clone.//// 指定了父進程,父進程不是 System 進程,調用 MmInitializeProcessAddressSpace // 根據父進程初始化地址空間//Status = MmInitializeProcessAddressSpace (Process,Parent,NULL,&Flags,NULL);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}CreatePeb = TRUE;UseLargePages = ((Flags & PROCESS_CREATE_FLAGS_LARGE_PAGES) != 0 ? TRUE : FALSE);//// A cloned process isn't started from an image file, so we give it the name// of the process of which it is a clone, provided the original has a name.//if (Parent->SeAuditProcessCreationInfo.ImageFileName != NULL) {ImageFileNameSize = sizeof(OBJECT_NAME_INFORMATION) +Parent->SeAuditProcessCreationInfo.ImageFileName->Name.MaximumLength;Process->SeAuditProcessCreationInfo.ImageFileName =ExAllocatePoolWithTag (PagedPool,ImageFileNameSize,'aPeS');if (Process->SeAuditProcessCreationInfo.ImageFileName != NULL) {RtlCopyMemory (Process->SeAuditProcessCreationInfo.ImageFileName,Parent->SeAuditProcessCreationInfo.ImageFileName,ImageFileNameSize);//// The UNICODE_STRING in the process is self contained, so calculate the// offset for the buffer.//Process->SeAuditProcessCreationInfo.ImageFileName->Name.Buffer =(PUSHORT)(((PUCHAR) Process->SeAuditProcessCreationInfo.ImageFileName) +sizeof(UNICODE_STRING));} else {Status = STATUS_INSUFFICIENT_RESOURCES;goto exit_and_deref;}}} else {//// System Process. Don't specify Process to clone or section to map//// 沒有指定內存區對象,但父進程是System進程//Flags &= ~PROCESS_CREATE_FLAGS_ALL_LARGE_PAGE_FLAGS;Status = MmInitializeProcessAddressSpace (Process,NULL,NULL,&Flags,NULL);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}//// In case the image file name of this system process is ever queried, we give// a zero length UNICODE_STRING.//Process->SeAuditProcessCreationInfo.ImageFileName =ExAllocatePoolWithTag (PagedPool,sizeof(OBJECT_NAME_INFORMATION),'aPeS');if (Process->SeAuditProcessCreationInfo.ImageFileName != NULL) {RtlZeroMemory (Process->SeAuditProcessCreationInfo.ImageFileName,sizeof(OBJECT_NAME_INFORMATION));} else {Status = STATUS_INSUFFICIENT_RESOURCES;goto exit_and_deref;}}}//// Create the process ID//// 創建進程ID,方法是調用 ExCreateHandle 在System 進程句柄表中存一個句柄// 句柄值就是PID//CidEntry.Object = Process;CidEntry.GrantedAccess = 0;Process->UniqueProcessId = ExCreateHandle (PspCidTable, &CidEntry);if (Process->UniqueProcessId == NULL) {Status = STATUS_INSUFFICIENT_RESOURCES;goto exit_and_deref;}ExSetHandleTableOwner (Process->ObjectTable, Process->UniqueProcessId);//// Audit the process creation.// 審計此次進程創建行為if (SeDetailedAuditingWithToken (NULL)) {SeAuditProcessCreation (Process);}//// See if the parent has a job. If so reference the job// and add the process in.//// 作業相關,本書不分析if (Parent) {Job = Parent->Job;if (Job != NULL && !(Job->LimitFlags & JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)) {if (Flags&PROCESS_CREATE_FLAGS_BREAKAWAY) {if (!(Job->LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)) {Status = STATUS_ACCESS_DENIED;} else {Status = STATUS_SUCCESS;}} else {Status = PspGetJobFromSet (Job, JobMemberLevel, &Process->Job);if (NT_SUCCESS (Status)) {PACCESS_TOKEN Token, NewToken;Job = Process->Job;Status = PspAddProcessToJob (Job, Process);//// Duplicate a new process token if one is specified for the job//Token = Job->Token;if (Token != NULL) {Status = SeSubProcessToken (Token,&NewToken,FALSE,Job->SessionId);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}SeAssignPrimaryToken (Process, NewToken); ObDereferenceObject (NewToken); }}}if (!NT_SUCCESS (Status)) {goto exit_and_deref;}}}// 對于通過映像內存區對象創建的進程,創建一個PEB// 對于進程拷貝(fork)的情景,則使用繼承的PEBif (Parent && CreatePeb) {//// For processes created w/ a section,// a new "virgin" PEB is created. Otherwise,// for forked processes, uses inherited PEB// with an updated mutant.//RtlZeroMemory (&InitialPeb, FIELD_OFFSET(INITIAL_PEB, Mutant));InitialPeb.Mutant = (HANDLE)(-1);InitialPeb.ImageUsesLargePages = (BOOLEAN) UseLargePages;if (SectionHandle != NULL) {Status = MmCreatePeb (Process, &InitialPeb, &Process->Peb);if (!NT_SUCCESS (Status)) {Process->Peb = NULL;goto exit_and_deref;}Peb = Process->Peb;} else {SIZE_T BytesCopied;InitialPeb.InheritedAddressSpace = TRUE;Process->Peb = Parent->Peb;MmCopyVirtualMemory (CurrentProcess,&InitialPeb,Process,Process->Peb,sizeof (INITIAL_PEB),KernelMode,&BytesCopied);#if defined(_WIN64)if (Process->Wow64Process != NULL) {RtlZeroMemory (&InitialPeb32, FIELD_OFFSET(INITIAL_PEB32, Mutant));InitialPeb32.Mutant = -1;InitialPeb32.InheritedAddressSpace = TRUE;InitialPeb32.ImageUsesLargePages = (BOOLEAN) UseLargePages;MmCopyVirtualMemory (CurrentProcess,&InitialPeb32,Process,Process->Wow64Process->Wow64,sizeof (INITIAL_PEB32),KernelMode,&BytesCopied);} #endif}}Peb = Process->Peb;//// Add the process to the global list of processes.// 新進程對象插入到全局活動進程鏈表 PsActiveProcessHeadPspLockProcessList (CurrentThread);InsertTailList (&PsActiveProcessHead, &Process->ActiveProcessLinks);PspUnlockProcessList (CurrentThread);AccessState = NULL;if (!PsUseImpersonationToken) {AccessState = &LocalAccessState;Status = SeCreateAccessStateEx (NULL,(Parent == NULL || Parent != PsInitialSystemProcess)?PsGetCurrentProcessByThread (CurrentThread) :PsInitialSystemProcess,AccessState,&AuxData,DesiredAccess,&PsProcessType->TypeInfo.GenericMapping);if (!NT_SUCCESS (Status)) {goto exit_and_deref;}}//// Insert the object. Once we do this is reachable from the outside world via// open by name. Open by ID is still disabled. Since its reachable// somebody might create a thread in the process and cause// rundown.//// 新進程對象插入到當前進程句柄表中Status = ObInsertObject (Process,AccessState,DesiredAccess,1, // bias the refcnt by one for future process manipulationsNULL,&LocalProcessHandle);if (AccessState != NULL) {SeDeleteAccessState (AccessState);}if (!NT_SUCCESS (Status)) {goto exit_and_deref_parent;}//// Compute the base priority and quantum reset values for the process and// set the memory priority.//ASSERT(IsListEmpty(&Process->ThreadListHead) == TRUE);// 計算新進程的基本優先級和時限重置值BasePriority = PspComputeQuantumAndPriority(Process,PsProcessPriorityBackground,&QuantumReset);Process->Pcb.BasePriority = (SCHAR)BasePriority;Process->Pcb.QuantumReset = QuantumReset;//// As soon as a handle to the process is accessible, allow the process to// be deleted.//// 設置進程訪問權限,當前進程句柄可訪問,允許進程終止Process->GrantedAccess = PROCESS_TERMINATE;if (Parent && Parent != PsInitialSystemProcess) {Status = ObGetObjectSecurity (Process,&SecurityDescriptor,&MemoryAllocated);if (!NT_SUCCESS (Status)) {ObCloseHandle (LocalProcessHandle, PreviousMode);goto exit_and_deref;}//// Compute the subject security context//SubjectContext.ProcessAuditId = Process;SubjectContext.PrimaryToken = PsReferencePrimaryToken(Process);SubjectContext.ClientToken = NULL;AccessCheck = SeAccessCheck (SecurityDescriptor,&SubjectContext,FALSE,MAXIMUM_ALLOWED,0,NULL,&PsProcessType->TypeInfo.GenericMapping,PreviousMode,&Process->GrantedAccess,&accesst);PsDereferencePrimaryTokenEx (Process, SubjectContext.PrimaryToken);ObReleaseObjectSecurity (SecurityDescriptor,MemoryAllocated);if (!AccessCheck) {Process->GrantedAccess = 0;}//// It does not make any sense to create a process that can not// do anything to itself.// Note: Changes to this set of bits should be reflected in psquery.c// code, in PspSetPrimaryToken.//Process->GrantedAccess |= (PROCESS_VM_OPERATION |PROCESS_VM_READ |PROCESS_VM_WRITE |PROCESS_QUERY_INFORMATION |PROCESS_TERMINATE |PROCESS_CREATE_THREAD |PROCESS_DUP_HANDLE |PROCESS_CREATE_PROCESS |PROCESS_SET_INFORMATION |STANDARD_RIGHTS_ALL |PROCESS_SET_QUOTA);} else {Process->GrantedAccess = PROCESS_ALL_ACCESS;}// 設置進程創建時間KeQuerySystemTime (&Process->CreateTime);try {if (Peb != NULL && CurrentThread->Tcb.Teb != NULL) {((PTEB)(CurrentThread->Tcb.Teb))->NtTib.ArbitraryUserPointer = Peb;}*ProcessHandle = LocalProcessHandle;} except (EXCEPTION_EXECUTE_HANDLER) {NOTHING;}if (SavedStatus != STATUS_SUCCESS) {Status = SavedStatus;}exit_and_deref:ObDereferenceObject (Process);exit_and_deref_parent:if (Parent != NULL) {ObDereferenceObject (Parent);}return Status; }PspCreateThread
NTSTATUS PspCreateThread(OUT PHANDLE ThreadHandle,IN ACCESS_MASK DesiredAccess,IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,IN HANDLE ProcessHandle,IN PEPROCESS ProcessPointer,OUT PCLIENT_ID ClientId OPTIONAL,IN PCONTEXT ThreadContext OPTIONAL,IN PINITIAL_TEB InitialTeb OPTIONAL,IN BOOLEAN CreateSuspended,IN PKSTART_ROUTINE StartRoutine OPTIONAL,IN PVOID StartContext)/*++Routine Description:This routine creates and initializes a thread object. It implements thefoundation for NtCreateThread and for PsCreateSystemThread.Arguments:ThreadHandle - Returns the handle for the new thread.輸出參數,返回新線程句柄DesiredAccess - Supplies the desired access modes to the new thread.期望的新線程訪問權限ObjectAttributes - Supplies the object attributes of the new thread.指定新線程對象的屬性ProcessHandle - Supplies a handle to the process that the thread is beingcreated within.新線程將運行在此進程的環境中ProcessPointer僅當創建系統線程時,此參數指向 System進程 PsInitialSystemProcess其他情況下都是NULLClientId - Returns the CLIENT_ID of the new thread.返回新線程的CIDThreadContext - Supplies a pointer to a context frame that represents theinitial user-mode context for a user-mode thread. The absenceof this parameter indicates that a system thread is beingcreated.用戶線程執行環境;如果是NULL,則表示創建系統線程InitialTeb - Supplies the contents of certain fields for the new threadsTEB. This parameter is only examined if both a trap andexception frame were specified.用戶線程初始化TEB結構CreateSuspended - Supplies a value that controls whether or not a user-modethread is created in a suspended state.是否掛起這個用戶線程StartRoutine - Supplies the address of the system thread start routine.系統線程啟動函數StartContext - Supplies context for a system thread start routine.系統線程啟動函數執行環境--*/{HANDLE_TABLE_ENTRY CidEntry;NTSTATUS Status;PETHREAD Thread;PETHREAD CurrentThread;PEPROCESS Process;PTEB Teb;KPROCESSOR_MODE PreviousMode;HANDLE LocalThreadHandle;BOOLEAN AccessCheck;BOOLEAN MemoryAllocated;PSECURITY_DESCRIPTOR SecurityDescriptor;SECURITY_SUBJECT_CONTEXT SubjectContext;NTSTATUS accesst;LARGE_INTEGER CreateTime;ULONG OldActiveThreads;PEJOB Job;AUX_ACCESS_DATA AuxData;PACCESS_STATE AccessState;ACCESS_STATE LocalAccessState;PAGED_CODE();// 當前線程CurrentThread = PsGetCurrentThread ();// 當前CPU模式if (StartRoutine != NULL) {// 如果指定了 StartRoutine ,就是創建系統線程PreviousMode = KernelMode;} else {// 如果未指定 StartRoutine,就通過當前線程判斷PreviousMode = KeGetPreviousModeByThread (&CurrentThread->Tcb);}Teb = NULL;Thread = NULL;Process = NULL;// 獲取進程對象,存儲到局部變量 Processif (ProcessHandle != NULL) {// 如果指定了 ProcessHandle,就通過 ProcessHandle 獲取進程對象//// Process object reference count is biased by one for each thread.// This accounts for the pointer given to the kernel that remains// in effect until the thread terminates (and becomes signaled)//Status = ObReferenceObjectByHandle (ProcessHandle,PROCESS_CREATE_THREAD,PsProcessType,PreviousMode,&Process,NULL);} else {if (StartRoutine != NULL) {// 如果 ProcessHandle 是 NULL,且指定了 StartRoutine ,說明是System進程要創建系統線程ObReferenceObject (ProcessPointer);Process = ProcessPointer;Status = STATUS_SUCCESS;} else {// 否則,返回錯誤Status = STATUS_INVALID_HANDLE;}}if (!NT_SUCCESS (Status)) {return Status;}//// If the previous mode is user and the target process is the system// process, then the operation cannot be performed.//// 如果是用戶模式,父進程卻是System進程,就返回錯誤if ((PreviousMode != KernelMode) && (Process == PsInitialSystemProcess)) {ObDereferenceObject (Process);return STATUS_INVALID_HANDLE;}// 創建 ETHREAD 并清零Status = ObCreateObject (PreviousMode,PsThreadType,ObjectAttributes,PreviousMode,NULL,sizeof(ETHREAD),0,0,&Thread);if (!NT_SUCCESS (Status)) {ObDereferenceObject (Process);return Status;}RtlZeroMemory (Thread, sizeof (ETHREAD));//// Initialize rundown protection for cross thread TEB refs etc.//// 初始化 RundownProtectExInitializeRundownProtection (&Thread->RundownProtect);//// Assign this thread to the process so that from now on// we don't have to dereference in error paths.//// 設置新線程的父進程Thread->ThreadsProcess = Process;// 創建CIDThread->Cid.UniqueProcess = Process->UniqueProcessId; CidEntry.Object = Thread;CidEntry.GrantedAccess = 0;Thread->Cid.UniqueThread = ExCreateHandle (PspCidTable, &CidEntry);if (Thread->Cid.UniqueThread == NULL) {ObDereferenceObject (Thread);return (STATUS_INSUFFICIENT_RESOURCES);}//// Initialize Mm//Thread->ReadClusterSize = MmReadClusterSize;//// Initialize LPC//KeInitializeSemaphore (&Thread->LpcReplySemaphore, 0L, 1L);InitializeListHead (&Thread->LpcReplyChain);//// Initialize Io//InitializeListHead (&Thread->IrpList);//// Initialize Registry//InitializeListHead (&Thread->PostBlockList);//// Initialize the thread lock//PspInitializeThreadLock (Thread);// 初始化定時器鏈表KeInitializeSpinLock (&Thread->ActiveTimerListLock);InitializeListHead (&Thread->ActiveTimerListHead);// 獲得進程的 RundownProtect 鎖,防止創建過程中進程被停掉(rundown)// 直到線程被插入到進程的線程鏈表中,才能解鎖if (!ExAcquireRundownProtection (&Process->RundownProtect)) {ObDereferenceObject (Thread);return STATUS_PROCESS_IS_TERMINATING;}if (ARGUMENT_PRESENT (ThreadContext)) {//// User-mode thread. Create TEB etc// 如果 ThreadContext 不空,說明是創建用戶線程// 于是創建TEB,并用 InitialTeb 初始化Status = MmCreateTeb (Process, InitialTeb, &Thread->Cid, &Teb);if (!NT_SUCCESS (Status)) {ExReleaseRundownProtection (&Process->RundownProtect);ObDereferenceObject (Thread);return Status;}try {//// Initialize kernel thread object for user mode thread.//// 用 ThreadContext 的 Eip 初始化 StartAddressThread->StartAddress = (PVOID)CONTEXT_TO_PROGRAM_COUNTER(ThreadContext);#if defined(_AMD64_)Thread->Win32StartAddress = (PVOID)ThreadContext->Rdx;#elif defined(_X86_)// 用 ThreadContext 的 Eax 初始化 Win32StartAddressThread->Win32StartAddress = (PVOID)ThreadContext->Eax;#else#error "no target architecture"#endif} except (EXCEPTION_EXECUTE_HANDLER) {Status = GetExceptionCode();}// 根據進程對象的信息初始化線程的一些屬性// 包括 Header, WaitBlock, ServiceTable, APC,定時器,內核棧等if (NT_SUCCESS (Status)) {Status = KeInitThread (&Thread->Tcb,NULL,PspUserThreadStartup,(PKSTART_ROUTINE)NULL,Thread->StartAddress,ThreadContext,Teb,&Process->Pcb);}} else {Teb = NULL;//// Set the system thread bit thats kept for all time// 設置系統線程標志位//PS_SET_BITS (&Thread->CrossThreadFlags, PS_CROSS_THREAD_FLAGS_SYSTEM);//// Initialize kernel thread object for kernel mode thread.//// 設置系統線程啟動地址 StartRoutineThread->StartAddress = (PKSTART_ROUTINE) StartRoutine;// 初始化線程Status = KeInitThread (&Thread->Tcb,NULL,PspSystemThreadStartup,StartRoutine,StartContext,NULL,NULL,&Process->Pcb);}if (!NT_SUCCESS (Status)) {if (Teb != NULL) {MmDeleteTeb(Process, Teb);}ExReleaseRundownProtection (&Process->RundownProtect);ObDereferenceObject (Thread);return Status;}// 鎖住進程,確保不是在退出或終止過程中PspLockProcessExclusive (Process, CurrentThread);//// Process is exiting or has had delete process called// We check the calling threads termination status so we// abort any thread creates while ExitProcess is being called --// but the call is blocked only if the new thread would be created// in the terminating thread's process.//if ((Process->Flags&PS_PROCESS_FLAGS_PROCESS_DELETE) != 0 ||(((CurrentThread->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_TERMINATED) != 0) &&(ThreadContext != NULL) &&(THREAD_TO_PROCESS(CurrentThread) == Process))) {PspUnlockProcessExclusive (Process, CurrentThread);KeUninitThread (&Thread->Tcb);if (Teb != NULL) {MmDeleteTeb(Process, Teb);}ExReleaseRundownProtection (&Process->RundownProtect);ObDereferenceObject(Thread);return STATUS_PROCESS_IS_TERMINATING;}// 進程的活動線程計數加一OldActiveThreads = Process->ActiveThreads++;// 新線程加入進程的線程鏈表InsertTailList (&Process->ThreadListHead, &Thread->ThreadListEntry);// 初始化剩余的域,尤其是和調度相關的,比如優先級、時限設置、CPU親和性等KeStartThread (&Thread->Tcb);// 此時線程可以被調度執行了PspUnlockProcessExclusive (Process, CurrentThread);ExReleaseRundownProtection (&Process->RundownProtect);//// Failures that occur after this point cause the thread to// go through PspExitThread//// 如果是該進程的第一個線程,觸發該進程的創建通知if (OldActiveThreads == 0) {PERFINFO_PROCESS_CREATE (Process);if (PspCreateProcessNotifyRoutineCount != 0) {ULONG i;PEX_CALLBACK_ROUTINE_BLOCK CallBack;PCREATE_PROCESS_NOTIFY_ROUTINE Rtn;for (i=0; i<PSP_MAX_CREATE_PROCESS_NOTIFY; i++) {CallBack = ExReferenceCallBackBlock (&PspCreateProcessNotifyRoutine[i]);if (CallBack != NULL) {Rtn = (PCREATE_PROCESS_NOTIFY_ROUTINE) ExGetCallBackBlockRoutine (CallBack);Rtn (Process->InheritedFromUniqueProcessId,Process->UniqueProcessId,TRUE);ExDereferenceCallBackBlock (&PspCreateProcessNotifyRoutine[i],CallBack);}}}}//// If the process has a job with a completion port,// AND if the process is really considered to be in the Job, AND// the process has not reported, report in//// This should really be done in add process to job, but can't// in this path because the process's ID isn't assigned until this point// in time//Job = Process->Job;if (Job != NULL && Job->CompletionPort &&!(Process->JobStatus & (PS_JOB_STATUS_NOT_REALLY_ACTIVE|PS_JOB_STATUS_NEW_PROCESS_REPORTED))) {PS_SET_BITS (&Process->JobStatus, PS_JOB_STATUS_NEW_PROCESS_REPORTED);KeEnterCriticalRegionThread (&CurrentThread->Tcb);ExAcquireResourceSharedLite (&Job->JobLock, TRUE);if (Job->CompletionPort != NULL) {IoSetIoCompletion (Job->CompletionPort,Job->CompletionKey,(PVOID)Process->UniqueProcessId,STATUS_SUCCESS,JOB_OBJECT_MSG_NEW_PROCESS,FALSE);}ExReleaseResourceLite (&Job->JobLock);KeLeaveCriticalRegionThread (&CurrentThread->Tcb);}PERFINFO_THREAD_CREATE(Thread, InitialTeb);//// Notify registered callout routines of thread creation.//if (PspCreateThreadNotifyRoutineCount != 0) {ULONG i;PEX_CALLBACK_ROUTINE_BLOCK CallBack;PCREATE_THREAD_NOTIFY_ROUTINE Rtn;for (i = 0; i < PSP_MAX_CREATE_THREAD_NOTIFY; i++) {CallBack = ExReferenceCallBackBlock (&PspCreateThreadNotifyRoutine[i]);if (CallBack != NULL) {Rtn = (PCREATE_THREAD_NOTIFY_ROUTINE) ExGetCallBackBlockRoutine (CallBack);Rtn (Thread->Cid.UniqueProcess,Thread->Cid.UniqueThread,TRUE);ExDereferenceCallBackBlock (&PspCreateThreadNotifyRoutine[i],CallBack);}}}//// Reference count of thread is biased once for itself and once for the handle if we create it.//// 線程對象的引用計數加2,一個針對當前的創建操作,一個針對要返回的線程句柄ObReferenceObjectEx (Thread, 2);// 如果 CreateSuspended ,指示新線程立即被掛起if (CreateSuspended) {try {KeSuspendThread (&Thread->Tcb);} except ((GetExceptionCode () == STATUS_SUSPEND_COUNT_EXCEEDED)?EXCEPTION_EXECUTE_HANDLER :EXCEPTION_CONTINUE_SEARCH) {}//// If deletion was started after we suspended then wake up the thread//if (Thread->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_TERMINATED) {KeForceResumeThread (&Thread->Tcb);}}// 根據指定的期望訪問權限,調用 SeCreateAccessStateEx 創建一個訪問狀態結構 AccessState = NULL;if (!PsUseImpersonationToken) {AccessState = &LocalAccessState;Status = SeCreateAccessStateEx (NULL,ARGUMENT_PRESENT (ThreadContext)?PsGetCurrentProcessByThread (CurrentThread) : Process,AccessState,&AuxData,DesiredAccess,&PsThreadType->TypeInfo.GenericMapping);if (!NT_SUCCESS (Status)) {PS_SET_BITS (&Thread->CrossThreadFlags,PS_CROSS_THREAD_FLAGS_DEADTHREAD);if (CreateSuspended) {(VOID) KeResumeThread (&Thread->Tcb);}KeReadyThread (&Thread->Tcb);ObDereferenceObjectEx (Thread, 2);return Status;}}// 把新線程對象插入到當前進程的句柄表Status = ObInsertObject (Thread,AccessState,DesiredAccess,0,NULL,&LocalThreadHandle);if (AccessState != NULL) {SeDeleteAccessState (AccessState);}if (!NT_SUCCESS (Status)) {//// The insert failed. Terminate the thread.////// This trick is used so that Dbgk doesn't report// events for dead threads//PS_SET_BITS (&Thread->CrossThreadFlags,PS_CROSS_THREAD_FLAGS_DEADTHREAD);if (CreateSuspended) {KeResumeThread (&Thread->Tcb);}} else {try {// 設置輸出參數 ThreadHandle*ThreadHandle = LocalThreadHandle;// 設置輸出參數 ClientId if (ARGUMENT_PRESENT (ClientId)) {*ClientId = Thread->Cid;}} except(EXCEPTION_EXECUTE_HANDLER) {PS_SET_BITS (&Thread->CrossThreadFlags,PS_CROSS_THREAD_FLAGS_DEADTHREAD);if (CreateSuspended) {(VOID) KeResumeThread (&Thread->Tcb);}KeReadyThread (&Thread->Tcb);ObDereferenceObject (Thread);ObCloseHandle (LocalThreadHandle, PreviousMode);return GetExceptionCode();}}// 設置線程創建時間KeQuerySystemTime(&CreateTime);ASSERT ((CreateTime.HighPart & 0xf0000000) == 0);PS_SET_THREAD_CREATE_TIME(Thread, CreateTime);// 設置線程訪問權限if ((Thread->CrossThreadFlags&PS_CROSS_THREAD_FLAGS_DEADTHREAD) == 0) {Status = ObGetObjectSecurity (Thread,&SecurityDescriptor,&MemoryAllocated);if (!NT_SUCCESS (Status)) {//// This trick us used so that Dbgk doesn't report// events for dead threads//PS_SET_BITS (&Thread->CrossThreadFlags,PS_CROSS_THREAD_FLAGS_DEADTHREAD);if (CreateSuspended) {KeResumeThread(&Thread->Tcb);}KeReadyThread (&Thread->Tcb);ObDereferenceObject (Thread);ObCloseHandle (LocalThreadHandle, PreviousMode);return Status;}//// Compute the subject security context//SubjectContext.ProcessAuditId = Process;SubjectContext.PrimaryToken = PsReferencePrimaryToken(Process);SubjectContext.ClientToken = NULL;AccessCheck = SeAccessCheck (SecurityDescriptor,&SubjectContext,FALSE,MAXIMUM_ALLOWED,0,NULL,&PsThreadType->TypeInfo.GenericMapping,PreviousMode,&Thread->GrantedAccess,&accesst);PsDereferencePrimaryTokenEx (Process, SubjectContext.PrimaryToken);ObReleaseObjectSecurity (SecurityDescriptor,MemoryAllocated);if (!AccessCheck) {Thread->GrantedAccess = 0;}Thread->GrantedAccess |= (THREAD_TERMINATE | THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION);} else {Thread->GrantedAccess = THREAD_ALL_ACCESS;}// 新線程加入就緒鏈表,等待調度;或者此時進程不在內存中,設置新線程狀態為轉移KeReadyThread (&Thread->Tcb);// 引用計數減一ObDereferenceObject (Thread);return Status; }CreateProcessW
BOOL WINAPI CreateProcessW(LPCWSTR lpApplicationName,LPWSTR lpCommandLine,LPSECURITY_ATTRIBUTES lpProcessAttributes,LPSECURITY_ATTRIBUTES lpThreadAttributes,BOOL bInheritHandles,DWORD dwCreationFlags,LPVOID lpEnvironment,LPCWSTR lpCurrentDirectory,LPSTARTUPINFOW lpStartupInfo,LPPROCESS_INFORMATION lpProcessInformation) {return CreateProcessInternalW(NULL, // Create new process with the token on the creator processlpApplicationName,lpCommandLine,lpProcessAttributes,lpThreadAttributes,bInheritHandles,dwCreationFlags,lpEnvironment,lpCurrentDirectory,lpStartupInfo,lpProcessInformation,NULL // Do not return the restricted token); }結束
總結
- 上一篇: 使用SEH实现跳转
- 下一篇: 进程句柄表初始化,扩展,插入删除句柄源码