iProgramInCpp2

task switching thingy

Oct 17th, 2021
931
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. typedef struct CPUSaveState
  4. {
  5.     int eax, ebx, ecx, edx,
  6.         esi, edi, ebp, eip,
  7.         cs, eflags, esp, ss;
  8. } CPUSaveState;
  9.  
  10.  
  11.     // To initialize the task, setting up ESP, EBP, EIP and EAX (where we pass in the pTask pointer for future use)
  12.     // Move that to the end of the allocated stack space, because stack grows towards zero, instead of towards end of memory
  13.     pTask->m_cpuState.esp = ((int)pTask->m_allocatedStack + C_STACK_BYTES_PER_TASK) & 0xF0;//align to 4 bits
  14.     pTask->m_cpuState.ebp = ((int)pTask->m_allocatedStack + C_STACK_BYTES_PER_TASK) & 0xF0;//align to 4 bits
  15.     pTask->m_cpuState.eip =  (int)KeTaskInitialFunc;
  16.     pTask->m_cpuState.eax =  (int)pTask;
  17.    
  18.     pTask->m_cpuState.esp -= sizeof (CPUSaveState);
  19.     memcpy ((void*)pTask->m_cpuState.esp, &pTask->m_cpuState, sizeof(CPUSaveState));
  20.     pTask->m_cpuState.esp += 32;//7*4, stops at EIP
  21.  
  22.     // To allocate the stack
  23.     void* pStack = malloc (C_STACK_BYTES_PER_TASK);//32768 bytes
  24.     if (pStack)
  25.     {
  26.         //...
  27.         pTask->m_allocatedStack = pStack;
  28.     }
  29.  
  30.  
  31. // This restores the task
  32. void RestoreStandardTask(CPUSaveState* pSaveState, Task* pTask)
  33. {
  34.     LogMsg("(restoring cpu registers)");
  35.     memcpy (pSaveState, &pTask->m_cpuState, sizeof(CPUSaveState));
  36.     LogMsg("(note: EIP : 0x%x)", pSaveState->eip);
  37.     LogMsg("(informing kernel of the new task)");
  38.     StartedNewTask(pSaveState);
  39.         // we should not return
  40. }
  41.  
  42.  
  43. // Second part, in assembly
  44. StartedNewTask:
  45.     ; hack, but we will use EAX for now. Might change in the future. TODO!
  46.     mov esp, eax
  47.    
  48.     ; restore the registers now
  49.     pop eax
  50.     pop ebx
  51.     pop ecx
  52.     pop edx
  53.     pop esi
  54.     pop edi
  55.     pop ebp
  56.     sti
  57.     ; and do a regular return
  58.     iretd```
RAW Paste Data