Skip to content

Commit 4a364ac

Browse files
authored
Fix stack misalignment issue on saved thread state
When saving the thread state, the code did not account for the five registers (eip, cs, eflags, sp, ss) that the CPU automatically pushes to the stack as part of the interrupt. Since the registers are pushed to the stack before the pushad in `isr_common_stub`, the saved esp value is incorrect and offset by 20 bytes. This is why each thread context switch resulted in one thread's stack position being shifted by -0x14. The ultimate consequence of this was a crash after the thread stacks grew downwards far enough to interfere with the kernel stack. The fix is simple: we can just add 20 to the saved esp value in `save_thread_state` to compensate for this offset.
1 parent 646fbac commit 4a364ac

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

OperatingSystem/source/threading/scheduler.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ void scheduler::thread_exit()
9090
static void save_thread_state(const interrupts::interrupt_frame& frame)
9191
{
9292
current_thread_state->regs = frame.regs;
93+
// shift the stack position by 20 bytes to compensate for the five DWORD registers (eip, cs, eflags, sp, ss) the CPU put on the stack
94+
current_thread_state->regs.esp += 20;
9395
current_thread_state->eip = frame.eip;
9496
current_thread_state->eflags = frame.eflags;
9597
}
@@ -148,4 +150,4 @@ static void context_switch(interrupts::interrupt_frame& frame)
148150

149151
// set the function that will be called after the IRET
150152
frame.eip = (dword)restore_thread_state;
151-
}
153+
}

0 commit comments

Comments
 (0)