编程知识 cdmana.com

Context structure of windows thread (thread nature)

Windows The context structure of the thread ,struct _CONTEXT Structure is related to CPU Relevant , specific CPU Corresponding to specific CONTEXT structure .

Thread context structure

x86 type CPU Corresponding CONTEXT The structure document is as follows :

typedef struct _CONTEXT {
    DWORD ContextFlags; // This field needs to be set when querying , Indicates which other CONTEXT Structure fields .

    // Debug register group 
    DWORD   Dr0;
    DWORD   Dr1;
    DWORD   Dr2;
    DWORD   Dr3;
    DWORD   Dr6;
    DWORD   Dr7;

    FLOATING_SAVE_AREA FloatSave; // Floating point register 

    // Segment register group 
    DWORD   SegGs;
    DWORD   SegFs;
    DWORD   SegEs;
    DWORD   SegDs;

    // General data register ( Integer registers ) Group 
    DWORD   Edi;
    DWORD   Esi;
    DWORD   Ebx;
    DWORD   Edx;
    DWORD   Ecx;
    DWORD   Eax;

    // Control register group —— such as CS、BP、SP Save the base pointer and stack pointer 、 Program counter 
    DWORD   Ebp;
    DWORD   Eip;
    DWORD   SegCs;              // MUST BE SANITIZED
    DWORD   EFlags;             // MUST BE SANITIZED
    DWORD   Esp;
    DWORD   SegSs;

    BYTE    ExtendedRegisters[MAXIMUM_SUPPORTED_EXTENSION]; // Extended register group 
} CONTEXT;

Gets and sets the thread context structure

obtain CONTEXT, Thread must be suspended first ( Use API:SuspendThread), Otherwise, you get CONTEXT meaningless . And then through API:GetThreadContext Get thread CONTEXT.

 code snippet :
CONTEXT Context;
SuspendThread(hThread);// Hung thread 
Context.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(hThread, &Context);// Get thread Context
Context.Eip = 0x00010000;// modify EIP, In other words, the code currently executed has been modified , After subsequent threads are activated , Will continue at this address ( This address is for demonstration purposes , Because of this address problem , The program could crash )  
Context.ContextFlags = CONTEXT_CONTROL;     
SetThreadContext(hThread, &Context);// Set thread Context    
ResumeThread(hThread);// Thread recovery , At this point, the program starts from 0x00010000 Start running at address , The program will be abnormal 

Thread essence analysis

  • From here we know , The essence of thread is also a structure , It's just high 2g The memory of the ( In kernel space ), We have no direct access to , But it can be accessed through system calls .

  • So thread scheduling , The essence is to modify the thread CONTEXT Of EIP, That is to say eip, When 20 When the millisecond time slice runs out , Switch to another thread

版权声明
本文为[osc_ sxdofc9c]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224094617776C.html

Scroll to Top