selph
selph
发布于 2021-10-30 / 577 阅读
0
0

Windows 进程系统初始化过程分析--基于Windows XP源码

进程系统的初始化函数:PspInitPhase0(位于XP源码:NT/base/ntos/ps/psinit.c),主要内容如下:

  • 获取系统类型进行属性设置
  • 初始化所有回调(线程、进程、模块)
  • 创建进程idle并初始化
  • 初始化并创建各个对象(线程,进程,作业)
  • 初始化作业相关内容
  • 初始化工作线程,删除内核栈
  • 创建系统进程
  • 给系统进程和idle进程命名
  • 创建初始化线程(第一个线程,系统线程)

主要就是进行各种初始化操作,然后创建了0和4号进程,还有4号进程里的初始化线程

PspInitPhase0

BOOLEAN
PspInitPhase0(
    IN PLOADER_PARAMETER_BLOCK LoaderBlock)

/*++

Routine Description:

    This routine performs phase 0 process structure initialization.
    During this phase, the initial system process, phase 1 initialization
    thread, and reaper threads are created. All object types and other
    process structures are created and initialized.
    这个程序执行了0号进程结构的初始化
    在此阶段,创建初始进程系统,1号线程和reaper线程(idle线程?)
    初始化和创建所有的对象类型和进程结构


Arguments:

    None.

Return Value:

    TRUE - Initialization was successful.

    FALSE - Initialization Failed.

--*/

{

    UNICODE_STRING NameString;
    OBJECT_ATTRIBUTES ObjectAttributes;
    OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
    HANDLE ThreadHandle;
    PETHREAD Thread;
    MM_SYSTEMSIZE SystemSize;
    ULONG i;
#if DBG
    NTSTATUS Status;
#endif
    // 获取系统类型 MM_SYSTEMSIZE 里定义了三种系统类型
    // 12Mb  is small
    // 12-19 is medium
    // > 19  is large
    // 根据物理内存的大小进行初始化进行区分
    SystemSize = MmQuerySystemSize();
    PspDefaultPagefileLimit = (ULONG)-1;

#ifdef _WIN64
    if (sizeof(TEB) > 8192 || sizeof(PEB) > 4096)
    {
#else
    if (sizeof(TEB) > 4096 || sizeof(PEB) > 4096)
    {
#endif
        KeBugCheckEx(PROCESS_INITIALIZATION_FAILED, 99, sizeof(TEB), sizeof(PEB), 99);
    }

    switch (SystemSize)
    {
        //typedef enum _MM_SYSTEM_SIZE {
        //    MmSmallSystem,
        //    MmMediumSystem,
        //    MmLargeSystem
        //} MM_SYSTEMSIZE;

    case MmMediumSystem: // 中型系统
        PsMinimumWorkingSet += 10;
        PsMaximumWorkingSet += 100;
        break;

    case MmLargeSystem: // 大型系统
        PsMinimumWorkingSet += 30;
        PsMaximumWorkingSet += 300;
        break;

    case MmSmallSystem: // 小型系统
    default:
        break;
    }

    //
    // Initialize all the callback structures
    // 初始化回调结构

    // 加载线程回调
    for (i = 0; i < PSP_MAX_CREATE_THREAD_NOTIFY; i++)
    {
        ExInitializeCallBack(&PspCreateThreadNotifyRoutine[i]);
    }

    // 加载进程回调
    for (i = 0; i < PSP_MAX_CREATE_PROCESS_NOTIFY; i++)
    {
        ExInitializeCallBack(&PspCreateProcessNotifyRoutine[i]);
    }

    // 加载模块回调
    for (i = 0; i < PSP_MAX_LOAD_IMAGE_NOTIFY; i++)
    {
        ExInitializeCallBack(&PspLoadImageNotifyRoutine[i]);
    }

    // 加载进程时间片表
    PsChangeQuantumTable(FALSE, PsRawPrioritySeparation);

    //
    // Quotas grow as needed automatically
    //

    //    if ( !PspDefaultPagedLimit ) {
    //        PspDefaultPagedLimit = 0;
    //        }
    //    if ( !PspDefaultNonPagedLimit ) {
    //        PspDefaultNonPagedLimit = 0;
    //        }
    // 额外设置,操作系统没使用
    if (PspDefaultNonPagedLimit == 0 && PspDefaultPagedLimit == 0)
    {
        PspDoingGiveBacks = TRUE;
    }
    else
    {
        PspDoingGiveBacks = FALSE;
    }

    // 默认分页/非分页大小
    PspDefaultPagedLimit *= PSP_1MB;
    PspDefaultNonPagedLimit *= PSP_1MB;

    if (PspDefaultPagefileLimit != -1)
    {
        PspDefaultPagefileLimit *= PSP_1MB;
    }

    //
    // Initialize active process list head and mutex
    // 初始化活动进程链表

    InitializeListHead(&PsActiveProcessHead);
    ExInitializeFastMutex(&PspActiveProcessMutex);

    //
    // Initialize the process security fields lock
    // 初始化进程安全锁

    // Idle进程:系统空闲进程
    PsIdleProcess = PsGetCurrentProcess();  // 获取当前EPROCESS

    // 初始化进程锁
    PspInitializeProcessLock(PsIdleProcess);
    // 初始化RundownProtect
    ExInitializeRundownProtection(&PsIdleProcess->RundownProtect);
    // 线程链表初始化
    InitializeListHead(&PsIdleProcess->ThreadListHead);

    // 修改Idle进程的内核时间,清空
    PsIdleProcess->Pcb.KernelTime = 0;
    PsIdleProcess->Pcb.KernelTime = 0;

    //
    // Initialize the shutdown thread pointer
    // 线程指空
    PspShutdownThread = NULL;

    //
    // Initialize the common fields of the Object Type Prototype record
    // 初始对象属性

    RtlZeroMemory(&ObjectTypeInitializer, sizeof(ObjectTypeInitializer));
    ObjectTypeInitializer.Length = sizeof(ObjectTypeInitializer);
    ObjectTypeInitializer.InvalidAttributes = OBJ_OPENLINK;
    ObjectTypeInitializer.SecurityRequired = TRUE;
    ObjectTypeInitializer.PoolType = NonPagedPool;
    ObjectTypeInitializer.InvalidAttributes = OBJ_PERMANENT |
                                              OBJ_EXCLUSIVE |
                                              OBJ_OPENIF;

    //
    // Create Object types for Thread and Process Objects.
    // 初始化Process对象类型

    RtlInitUnicodeString(&NameString, L"Process");
    ObjectTypeInitializer.DefaultPagedPoolCharge = PSP_PROCESS_PAGED_CHARGE;
    ObjectTypeInitializer.DefaultNonPagedPoolCharge = PSP_PROCESS_NONPAGED_CHARGE;
    ObjectTypeInitializer.DeleteProcedure = PspProcessDelete;
    ObjectTypeInitializer.ValidAccessMask = PROCESS_ALL_ACCESS;
    ObjectTypeInitializer.GenericMapping = PspProcessMapping;
    // 创建对象Object(_OBJECT_TYPE)
    if (!NT_SUCCESS(ObCreateObjectType(&NameString,
                                       &ObjectTypeInitializer,
                                       (PSECURITY_DESCRIPTOR)NULL,
                                       &PsProcessType)))
    {
        return FALSE;
    }

    // 初始化线程对象类型
    RtlInitUnicodeString(&NameString, L"Thread");
    ObjectTypeInitializer.DefaultPagedPoolCharge = PSP_THREAD_PAGED_CHARGE;
    ObjectTypeInitializer.DefaultNonPagedPoolCharge = PSP_THREAD_NONPAGED_CHARGE;
    ObjectTypeInitializer.DeleteProcedure = PspThreadDelete;
    ObjectTypeInitializer.ValidAccessMask = THREAD_ALL_ACCESS;
    ObjectTypeInitializer.GenericMapping = PspThreadMapping;
    // 创建对象
    if (!NT_SUCCESS(ObCreateObjectType(&NameString,
                                       &ObjectTypeInitializer,
                                       (PSECURITY_DESCRIPTOR)NULL,
                                       &PsThreadType)))
    {
        return FALSE;
    }

    // 初始化作业对象类型
    RtlInitUnicodeString(&NameString, L"Job");
    ObjectTypeInitializer.DefaultPagedPoolCharge = 0;
    ObjectTypeInitializer.DefaultNonPagedPoolCharge = sizeof(EJOB);
    ObjectTypeInitializer.DeleteProcedure = PspJobDelete;
    ObjectTypeInitializer.CloseProcedure = PspJobClose;
    ObjectTypeInitializer.ValidAccessMask = JOB_OBJECT_ALL_ACCESS;
    ObjectTypeInitializer.GenericMapping = PspJobMapping;
    ObjectTypeInitializer.InvalidAttributes = 0;
    // 创建对象
    if (!NT_SUCCESS(ObCreateObjectType(&NameString,
                                       &ObjectTypeInitializer,
                                       (PSECURITY_DESCRIPTOR)NULL,
                                       &PsJobType)))
    {
        return FALSE;
    }

    //
    // Initialize job list head and mutex
    //
    // 初始化作业结构
    PspInitializeJobStructures();
    // 初始化链表,工作集(和作业相关)
    InitializeListHead(&PspWorkingSetChangeHead.Links);
    // 初始化互斥量
    ExInitializeFastMutex(&PspWorkingSetChangeHead.Lock);

    //
    // Initialize CID handle table.
    //
    // N.B. The CID handle table is removed from the handle table list so
    //      it will not be enumerated for object handle queries.
    //
    // 创建句柄表,这个句柄表里只有进程句柄和线程句柄
    PspCidTable = ExCreateHandleTable(NULL);
    if (PspCidTable == NULL)
    {
        return FALSE;
    }

    //
    // Set PID and TID reuse to strict FIFO. This isn't absolutely needed but
    // it makes tracking audits easier.
    // 初始化调度相关
    ExSetHandleTableStrictFIFO(PspCidTable);

    ExRemoveHandleTable(PspCidTable);

#if defined(i386)

    //
    // Ldt Initialization
    //

    if (!NT_SUCCESS(PspLdtInitialize()))
    {
        return FALSE;
    }

    //
    // Vdm support Initialization
    //

    if (!NT_SUCCESS(PspVdmInitialize()))
    {
        return FALSE;
    }

#endif

    //
    // Initialize Reaper Data Structures
    //

    PsReaperList = NULL;
    PsReaperActive = FALSE;
    // 初始化工作线程,删除内核栈
    ExInitializeWorkItem(&PsReaperWorkItem, PspReaper, NULL);

    //
    // Get a pointer to the system access token.
    // This token is used by the boot process, so we can take the pointer
    // from there.
    // 建立启动访问令牌

    PspBootAccessToken = ExFastRefGetObject(PsIdleProcess->Token);
    // 设置默认的对象属性
    InitializeObjectAttributes(&ObjectAttributes,
                               NULL,
                               0,
                               NULL,
                               NULL);
    // 创建进程,系统进程
    if (!NT_SUCCESS(PspCreateProcess(&PspInitialSystemProcessHandle,
                                     PROCESS_ALL_ACCESS,
                                     &ObjectAttributes,
                                     NULL,
                                     0,
                                     NULL,
                                     NULL,
                                     NULL,
                                     0)))
    {
        return FALSE;
    }
    // 通过进程句柄获取进程对象
    if (!NT_SUCCESS(ObReferenceObjectByHandle(
            PspInitialSystemProcessHandle,
            0L,
            PsProcessType,
            KernelMode,
            (PVOID *)&PsInitialSystemProcess,
            NULL)))
    {

        return FALSE;
    }
    // 字符串拷贝,进程名,ID0,4的进程在这里有了名字
    strcpy((char *)&PsIdleProcess->ImageFileName[0], "Idle");
    strcpy((char *)&PsInitialSystemProcess->ImageFileName[0], "System");

    //
    // The system process can allocate resources, and its name may be queried by
    // NtQueryInfomationProcess and various audits.  We must explicitly allocate memory
    // for this field of the System EPROCESS, and initialize it appropriately.  In this
    // case, appropriate initialization means zeroing the memory.
    //
    // 分配存储进程文件路径的内存
    PsInitialSystemProcess->SeAuditProcessCreationInfo.ImageFileName = ExAllocatePoolWithTag(
        PagedPool,
        sizeof(OBJECT_NAME_INFORMATION),
        'aPeS');

    if (PsInitialSystemProcess->SeAuditProcessCreationInfo.ImageFileName != NULL)
    {
        RtlZeroMemory(
            PsInitialSystemProcess->SeAuditProcessCreationInfo.ImageFileName,
            sizeof(OBJECT_NAME_INFORMATION));
    }
    else
    {
        return FALSE;
    }

    //
    // Phase 1 System initialization
    // 创建的第一个线程,在system进程下的,idle下没线程的

    if (!NT_SUCCESS(PsCreateSystemThread(
            &ThreadHandle,
            THREAD_ALL_ACCESS,
            &ObjectAttributes,
            0L,
            NULL,
            Phase1Initialization,
            (PVOID)LoaderBlock)))
    {
        return FALSE;
    }

    // 线程句柄获取线程对象
    if (!NT_SUCCESS(ObReferenceObjectByHandle(
            ThreadHandle,
            0L,
            PsThreadType,
            KernelMode,
            (PVOID *)&Thread,
            NULL)))
    {

        return FALSE;
    }

    ZwClose(ThreadHandle);

//
// On checked systems install an image callout routine
//
#if DBG

    Status = PsSetLoadImageNotifyRoutine(PspImageNotifyTest);
    if (!NT_SUCCESS(Status))
    {
        return FALSE;
    }

#endif

    return TRUE;
}

评论