From 8b757079f0e3355d3c011dfb2db864e8f9fb79bb Mon Sep 17 00:00:00 2001
From: Jeremy Soller <jackpot51@gmail.com>
Date: Tue, 6 Sep 2022 15:16:30 -0600
Subject: [PATCH] Allow thunk to set ES

---
 asm/x86-unknown-none/thunk.asm | 26 ++++++++++++++++++++------
 src/os/bios/thunk.rs           | 10 +++++-----
 2 files changed, 25 insertions(+), 11 deletions(-)

diff --git a/asm/x86-unknown-none/thunk.asm b/asm/x86-unknown-none/thunk.asm
index 16a3597..4423132 100644
--- a/asm/x86-unknown-none/thunk.asm
+++ b/asm/x86-unknown-none/thunk.asm
@@ -107,10 +107,17 @@ USE16
     mov ss, eax
 
     ; set stack
-    mov esp, 0x7C00 - 16
-
-    ; load registers
-    popad
+    mov esp, 0x7C00 - 64
+
+    ; load registers and ES
+    pop es
+    pop edi
+    pop esi
+    pop ebp
+    pop ebx
+    pop edx
+    pop ecx
+    pop eax
 
     ; enable interrupts
     sti
@@ -121,8 +128,15 @@ USE16
     ; disable interrupts
     cli
 
-    ; save registers
-    pushad
+    ; save registers and ES
+    push eax
+    push ecx
+    push edx
+    push ebx
+    push ebp
+    push esi
+    push edi
+    push es
 
     ; load gdt (BIOS sometimes overwrites this)
     lgdt [gdtr]
diff --git a/src/os/bios/thunk.rs b/src/os/bios/thunk.rs
index 8fa4125..118f8f8 100644
--- a/src/os/bios/thunk.rs
+++ b/src/os/bios/thunk.rs
@@ -3,13 +3,13 @@ use core::ptr;
 use super::THUNK_STACK_ADDR;
 
 #[allow(dead_code)]
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, Debug)]
 #[repr(packed)]
 pub struct ThunkData {
+    pub es: u16,
     pub edi: u32,
     pub esi: u32,
     pub ebp: u32,
-    esp: u32,
     pub ebx: u32,
     pub edx: u32,
     pub ecx: u32,
@@ -19,10 +19,10 @@ pub struct ThunkData {
 impl ThunkData {
     pub fn new() -> Self {
         Self {
+            es: 0,
             edi: 0,
             esi: 0,
             ebp: 0,
-            esp: THUNK_STACK_ADDR as u32,
             ebx: 0,
             edx: 0,
             ecx: 0,
@@ -31,11 +31,11 @@ impl ThunkData {
     }
 
     pub unsafe fn save(&self) {
-        ptr::write((THUNK_STACK_ADDR - 16) as *mut ThunkData, *self);
+        ptr::write((THUNK_STACK_ADDR - 64) as *mut ThunkData, *self);
     }
 
     pub unsafe fn load(&mut self) {
-        *self = ptr::read((THUNK_STACK_ADDR - 16) as *const ThunkData);
+        *self = ptr::read((THUNK_STACK_ADDR - 64) as *const ThunkData);
     }
 
     pub unsafe fn with(&mut self, f: extern "C" fn()) {
-- 
GitLab