From f197453a15a3130ca62b8ccbb6af65a78942d9e5 Mon Sep 17 00:00:00 2001
From: Davids Paskevics <davip00@mi.fu-berlin.de>
Date: Mon, 22 May 2023 18:23:47 +0200
Subject: [PATCH] Work around qemu not (yet) setting the stack pointer

---
 esp32c3/build.mk               |  2 +-
 esp32c3/emulator_workarounds.S | 12 ++++++++++++
 esp32c3/link.ld                |  2 +-
 3 files changed, 14 insertions(+), 2 deletions(-)
 create mode 100644 esp32c3/emulator_workarounds.S

diff --git a/esp32c3/build.mk b/esp32c3/build.mk
index cef0409..35da63d 100644
--- a/esp32c3/build.mk
+++ b/esp32c3/build.mk
@@ -12,7 +12,7 @@ CWD         ?= $(realpath $(CURDIR))
 FLASH_ADDR  ?= 0  # 2nd stage bootloader flash offset
 DOCKER      ?= docker run -it --rm -v $(CWD):$(CWD) -v $(MDK):$(MDK) -w $(CWD) mdashnet/riscv
 TOOLCHAIN   ?= $(DOCKER) riscv-none-elf
-SRCS        ?= $(MDK)/$(ARCH)/boot.c $(SOURCES)
+SRCS        ?= $(MDK)/$(ARCH)/boot.c $(MDK)/$(ARCH)/emulator_workarounds.S $(SOURCES)
 
 build: $(PROG).bin
 
diff --git a/esp32c3/emulator_workarounds.S b/esp32c3/emulator_workarounds.S
new file mode 100644
index 0000000..044a84a
--- /dev/null
+++ b/esp32c3/emulator_workarounds.S
@@ -0,0 +1,12 @@
+//; In the current state of our emulator, it doesn't run a proper boot ROM.
+//; This function does some minor fixups (setting stack pointer etc.)
+//; and runs the MDK init function.
+.section .text
+.align 2
+.global emulator_workarounds
+emulator_workarounds:
+//; Not sure if this is the best address for the stack
+//; FIXME: This should be set to a range specified in the linker script
+li sp, 0x40384400
+//; Jump to MDK's real setup function
+j _reset
diff --git a/esp32c3/link.ld b/esp32c3/link.ld
index b086c87..9abbd07 100644
--- a/esp32c3/link.ld
+++ b/esp32c3/link.ld
@@ -5,7 +5,7 @@ MEMORY {
 }
 
 _eram = ORIGIN(dram) + LENGTH(dram);
-ENTRY(_reset)
+ENTRY(emulator_workarounds)
 
 SECTIONS {
   .text     : { *(.text) *(.text*) } > iram
-- 
GitLab