foxygit / fake-08-xbox360 Log in
commit f3d8cb8d306d03f1063d4f81b52305d4d0cd1c8d
Author:     mrfox <jens.se@icloud.com>
AuthorDate: Wed Nov 25 16:43:36 2026 +0100
Commit:     mrfox <jens.se@icloud.com>
CommitDate: Wed Nov 25 16:43:36 2026 +0100

    xex: FAKE-08 as a native XEX (no sound yet)

    platform/xex/source/XexHost.cpp is the libxenon host's logic on the XEX
    runtime: video through xex_video (60 fps paced by the flips, timer for
    other rates, perf overlay), four controllers through XamInputGetState,
    carts from p8carts next to the XEX / USB / HDD, settings and saves next
    to the XEX, exit through the Guide's Xbox Home or Back+Start. Sound
    comes with step 4.

    Also: the time base runs at 49.875 MHz (xsdk's measurement), not the
    50 MHz the kernel reports; xex-link is patched for a 1 MB main stack and
    the hello test probes the stack depth.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 platform/xex/Makefile                |  41 ++-
 platform/xex/README.md               |  34 ++-
 platform/xex/fake08.toml             |   4 +
 platform/xex/runtime/sys.c           |   8 +-
 platform/xex/source/XexHost.cpp      | 560 +++++++++++++++++++++++++++++++++++
 platform/xex/tests/hello/main.cpp    |  25 +-
 platform/xex/tools/build-xex-link.sh |   8 +-
 7 files changed, 670 insertions(+), 10 deletions(-)

diff --git a/platform/xex/Makefile b/platform/xex/Makefile
index e63f5b5..c69749f 100644
--- a/platform/xex/Makefile
+++ b/platform/xex/Makefile
@@ -31,10 +31,47 @@ RUNTIME_OBJ := $(patsubst %,$(BUILD)/%.o,$(RUNTIME_SRC))

 TESTS := hello fs video

-.PHONY: all tests runtime clean
-all: tests
+#---------------------------------------------------------------------------------
+# FAKE-08: the emulator core (../../source, ../../libs) and source/XexHost.cpp
+#---------------------------------------------------------------------------------
+CORE_DIRS   := ../../source ../../libs/z8lua ../../libs/utf8-util ../../libs/lodepng \
+               ../../libs/simpleini ../../libs/miniz
+CORE_SRC    := $(foreach d,$(CORE_DIRS),$(wildcard $(d)/*.c) $(wildcard $(d)/*.cpp))
+CORE_OBJ    := $(patsubst ../../%,$(BUILD)/fake08/core/%.o,$(CORE_SRC))
+FAKE08_OBJ  := $(CORE_OBJ) $(BUILD)/fake08/XexHost.cpp.o
+APP_VERSION ?= dev
+# z8lua's .c files are C++ (fix32 math, throw/catch for Lua errors).
+# libxenon's headers come last, for the console font only.
+FAKE08_FLAGS := $(MACH) -O2 -g -Wall -Wno-sign-compare -Wno-attributes -ffunction-sections -fdata-sections \
+                $(INCLUDES) $(foreach d,$(CORE_DIRS),-I$(d)) -idirafter $(DEVKITXENON)/usr/include \
+                -D__XEX__ -DMINIZ_NO_TIME -DVER_STR=\"$(APP_VERSION)\" -std=gnu++17
+
+.PHONY: all tests runtime fake08 clean
+all: tests fake08
 runtime: $(RUNTIME_OBJ)
 tests: $(foreach t,$(TESTS),$(BUILD)/tests/$(t)/default.xex)
+fake08: $(BUILD)/fake08/default.xex
+
+$(BUILD)/fake08/core/%.c.o: ../../%.c
+	@mkdir -p $(dir $@)
+	@echo [$(notdir $<)]
+	@$(CXX) -x c++ $(FAKE08_FLAGS) -MMD -MP -c $< -o $@
+$(BUILD)/fake08/core/%.cpp.o: ../../%.cpp
+	@mkdir -p $(dir $@)
+	@echo [$(notdir $<)]
+	@$(CXX) $(FAKE08_FLAGS) -MMD -MP -c $< -o $@
+$(BUILD)/fake08/XexHost.cpp.o: source/XexHost.cpp
+	@mkdir -p $(dir $@)
+	@echo [$(notdir $<)]
+	@$(CXX) $(FAKE08_FLAGS) -MMD -MP -c $< -o $@
+
+$(BUILD)/fake08/app.elf: $(FAKE08_OBJ) $(RUNTIME_OBJ) runtime/link.ld
+	@mkdir -p $(dir $@)
+	@echo linking $@
+	@$(CXX) $(LDFLAGS) -Wl,-Map,$(@:.elf=.map) -o $@ $(filter %.o,$^) $(LIBS)
+
+$(BUILD)/fake08/default.xex: $(BUILD)/fake08/app.elf fake08.toml
+	@$(XEX_LINK) $< $@ --manifest fake08.toml

 $(BUILD)/%.S.o: %.S
 	@mkdir -p $(dir $@)
diff --git a/platform/xex/README.md b/platform/xex/README.md
index a6f08f0..2178aa8 100644
--- a/platform/xex/README.md
+++ b/platform/xex/README.md
@@ -32,7 +32,8 @@ From the repository root:
     docker run --rm -v $PWD:/build_dir -w /build_dir free60/libxenon:latest \
       bash -lc 'make xex'

-Output: `platform/xex/build/tests/<name>/default.xex`. The ELF next to it
+Output: `platform/xex/build/fake08/default.xex` (FAKE-08) and
+`platform/xex/build/tests/<name>/default.xex`. The ELF next to it
 (`app.elf`) has the symbols for `xenon-addr2line`.

 The test programs also run in Xenia Canary
@@ -40,6 +41,29 @@ The test programs also run in Xenia Canary
 DbgPrint output shows up in the log. Xenia mounts the XEX's folder
 read-only, so file writes only work on a console.

+## FAKE-08
+
+Copy `build/fake08/default.xex` into a folder of its own (for example
+`Hdd1:\Apps\FAKE-08\`) and add it to Aurora. Carts are read from the
+first `p8carts` folder found: next to the XEX, then `usb0:`-`usb2:`, then
+the hard disk root (`Hdd1:\p8carts`); without one, `p8carts` is created
+next to the XEX. Settings, saves (`cdata`) and `pico.log` go to a `fake08`
+folder next to the XEX.
+
+| Controller | |
+|---|---|
+| D-pad / left stick | arrows |
+| A, Y / B, X | O / X (swapped with the "button layout" setting) |
+| Start | pause menu |
+| Back | cycle screen sizes |
+| Xbox button | Guide; Xbox Home leaves to Aurora |
+| Back+Start | quit (some dashboard plugins use it for screenshots) |
+
+Controllers 2-4 are players 2-4. Sound is not implemented yet.
+
+The source is `source/XexHost.cpp`, the same logic as the libxenon host
+(`platform/xenon/source/XenonHost.cpp`) on this platform's runtime.
+
 ## Runtime

 - **Paths:** `game:/...` (folder of the XEX), `usb0:`-`usb2:`
@@ -48,7 +72,11 @@ read-only, so file writes only work on a console.
 - **Files:** `open/read/write/lseek/close/stat/fstat/unlink/mkdir`,
   `opendir/readdir/closedir` (stdio and iostreams work on top).
 - **Time:** `gettimeofday` (KeQuerySystemTime), `clock()/times()` (time
-  base), `xex_sleep_ms`, `usleep`.
+  base), `xex_sleep_ms`, `usleep`. The time base runs at 49.875 MHz, not the
+  50 MHz `KeQueryPerformanceFrequency` reports; `xex_timebase_freq()` gives
+  the real rate.
+- **Stack:** 1 MB for the main thread (`tools/build-xex-link.sh` patches
+  xex-link's 256 KB).
 - **Heap:** a 96 MB `.bss` arena (`XEX_HEAP_SIZE`).
 - **Exit:** returning from `main`/`exit()` calls `XamLoaderTerminateTitle`,
   which goes back to the dashboard.
@@ -71,6 +99,6 @@ read-only, so file writes only work on a console.

 | Test | Checks |
 |---|---|
-| `tests/hello` | static constructors, C++ exceptions, `std::regex`, notifications, exit to dashboard |
+| `tests/hello` | static constructors, C++ exceptions, `std::regex`, an 896 KB deep stack (progress in `game:/stack-test.txt`), notifications, exit to dashboard |
 | `tests/fs` | time, `clock()`, directory listing, write/append/read/seek/stat/mkdir/remove on every device; writes `game:/fs-test-report.txt` |
 | `tests/video` | CPU-drawn frames at 60 fps through the title's own GPU ring, controller input (d-pad moves a square, A/B/X/Y colour it); a row of 16 boxes lights up with the pressed buttons and every controller change is logged to `game:/video-log.txt`; exits after 60 s (not while the Guide shows) or on Back+Start; the Xbox button opens the Guide, whose Xbox Home leaves |
diff --git a/platform/xex/fake08.toml b/platform/xex/fake08.toml
new file mode 100644
index 0000000..956925f
--- /dev/null
+++ b/platform/xex/fake08.toml
@@ -0,0 +1,4 @@
+# FAKE-08 as a native XEX (see README.md)
+title_id = 0x46383038   # "F808"
+load_address = 0x82000000
+module_flags = ["TITLE"]
diff --git a/platform/xex/runtime/sys.c b/platform/xex/runtime/sys.c
index 26cbf3a..1c58663 100644
--- a/platform/xex/runtime/sys.c
+++ b/platform/xex/runtime/sys.c
@@ -79,9 +79,11 @@ uint64_t xex_timebase(void)

 uint64_t xex_timebase_freq(void)
 {
-    static uint64_t freq;
-    if (!freq) freq = KeQueryPerformanceFrequency();
-    return freq ? freq : 49875000ull;
+    /* The time base runs at the CPU clock / 64 = 49.875 MHz, while
+     * KeQueryPerformanceFrequency reports 50 MHz (measured by xsdk against
+     * the 60 Hz display: docs/HARDWARE.md, "The time base runs at 49.875
+     * MHz"). Xenia runs it at 50 MHz, so times there read 0.25% long. */
+    return 49875000ull;
 }

 void xex_sleep_ms(unsigned ms)
diff --git a/platform/xex/source/XexHost.cpp b/platform/xex/source/XexHost.cpp
new file mode 100644
index 0000000..fdf0fc7
--- /dev/null
+++ b/platform/xex/source/XexHost.cpp
@@ -0,0 +1,560 @@
+/*
+ * Xbox 360 host for FAKE-08 as a native XEX (started from Aurora/FSD, runs
+ * under the dashboard; no XDK). Shares its logic with the libxenon host
+ * (platform/xenon/source/XenonHost.cpp); the hardware access goes through
+ * this platform's runtime instead:
+ *   - video: xex_video (own GPU ring, VdSwap, two tiled front buffers, the
+ *     Guide shows over the game),
+ *   - input: XamInputGetState for four controllers,
+ *   - files: game:/ (the XEX's folder), usb0:-usb2:, hdd:,
+ *   - time: the CPU time base (49.875 MHz).
+ * Audio is not implemented yet (step 4: the kernel's XAudio render driver).
+ *
+ * Exit: Xbox button -> Xbox Home in the Guide, or Back+Start.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+#include <string>
+#include <vector>
+
+#include "../../../source/host.h"
+#include "../../../source/hostVmShared.h"
+#include "../../../source/nibblehelpers.h"
+#include "../../../source/logger.h"
+#include "../../../source/filehelpers.h"
+
+#include "xex_runtime.h"
+#include "xex_video.h"
+#include "xex_input.h"
+
+// 8x16 console font from libxenon (headers of the free60/libxenon image)
+#include <console/font_8x16.h>
+
+using namespace std;
+
+static const int PicoScreenWidth = 128;
+static const int PicoScreenHeight = 128;
+
+// ---------------------------------------------------------------------------
+// Video
+// ---------------------------------------------------------------------------
+
+static bool videoOk = false;
+static int fbWidth = 0, fbHeight = 0;     // displayed window
+static int fbPitch = 0;                   // surface width (tiled indexing)
+static int fbOriginX = 0, fbOriginY = 0;  // window inside the surface
+
+// Destination rectangle inside the window
+static int destX = 0, destY = 0, destW = 0, destH = 0;
+static std::vector<uint8_t> xMap, yMap;   // dest pixel -> source pixel
+static int clearFrames = 2;               // both front buffers need clearing
+
+static uint32_t frameRgb[PicoScreenWidth * PicoScreenHeight];
+
+static const uint32_t OpaqueBlack = 0x000000ffu;   // opaque black (B, G, R, A)
+
+static inline int tiledIndex(int x, int y) {
+    return xex_video_tiled_index(fbOriginX + x, fbOriginY + y, fbPitch);
+}
+
+static inline uint32_t fbColor(const Color &c) {
+    return xex_video_rgb(c.Red, c.Green, c.Blue);
+}
+
+static bool fbInit() {
+    if (xex_video_init() != 0) {
+        Logger_Write("video init failed: %s\n", xex_video_error());
+        return false;
+    }
+    // A frame tells the window; xex_video_begin also returns the back buffer.
+    xex_frame f = xex_video_begin();
+    fbWidth = f.window_width;
+    fbHeight = f.window_height;
+    fbPitch = f.pitch;
+    fbOriginX = f.window_x;
+    fbOriginY = f.window_y;
+    Logger_Write("video: %dx%d window at %d,%d, pitch %d\n", fbWidth, fbHeight, fbOriginX, fbOriginY, fbPitch);
+    return true;
+}
+
+static void setDestRect(int w, int h) {
+    if (w > fbWidth) w = fbWidth;
+    if (h > fbHeight) h = fbHeight;
+    destW = w;
+    destH = h;
+    destX = (fbWidth - w) / 2;
+    destY = (fbHeight - h) / 2;
+
+    xMap.resize(destW);
+    yMap.resize(destH);
+    for (int i = 0; i < destW; i++) xMap[i] = (uint8_t)(i * PicoScreenWidth / destW);
+    for (int i = 0; i < destH; i++) yMap[i] = (uint8_t)(i * PicoScreenHeight / destH);
+    clearFrames = 2;
+}
+
+static void _changeStretch(StretchOption s) {
+    int intScale = fbHeight / PicoScreenHeight;
+    if (intScale < 1) intScale = 1;
+
+    switch (s) {
+        case PixelPerfect:
+            setDestRect(PicoScreenWidth, PicoScreenHeight);
+            break;
+        case StretchToFit:
+            setDestRect(fbHeight, fbHeight);
+            break;
+        case StretchToFill:
+            setDestRect(fbWidth, fbHeight);
+            break;
+        case FourByThreeVertPerfect:
+            setDestRect(intScale * PicoScreenHeight * 4 / 3, intScale * PicoScreenHeight);
+            break;
+        case FourByThreeStretch:
+            setDestRect(fbHeight * 4 / 3, fbHeight);
+            break;
+        case PixelPerfectStretch:
+        default:
+            setDestRect(intScale * PicoScreenWidth, intScale * PicoScreenHeight);
+            break;
+    }
+}
+
+// Applies drawMode (screen stretch/flip/rotate pokes) while converting to fb colors.
+static inline void srcCoord(uint8_t drawMode, int x, int y, int &sx, int &sy) {
+    switch (drawMode) {
+        case 1:   sx = x >> 1; sy = y; break;                 // horizontal stretch
+        case 2:   sx = x; sy = y >> 1; break;                 // vertical stretch
+        case 3:   sx = x >> 1; sy = y >> 1; break;            // both
+        case 129: sx = 127 - x; sy = y; break;                // flip h
+        case 130: sx = x; sy = 127 - y; break;                // flip v
+        case 131: sx = 127 - x; sy = 127 - y; break;          // flip both
+        case 133: sx = y; sy = 127 - x; break;                // rotate 90 cw
+        case 134: sx = 127 - x; sy = 127 - y; break;          // rotate 180
+        case 135: sx = 127 - y; sy = x; break;                // rotate 270 cw
+        default:  sx = x; sy = y; break;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Timing: the CPU time base. At 60 fps the display paces the loop (one flip
+// per refresh); other rates use the timer.
+// ---------------------------------------------------------------------------
+
+static uint64_t tbFreq = 49875000ull;
+static uint64_t lastFrameTb = 0;
+static uint64_t targetFrameTb = 49875000ull / 60;
+static bool vsyncMode = true;
+
+static inline uint64_t now() { return xex_timebase(); }
+
+// ---------------------------------------------------------------------------
+// Storage
+// ---------------------------------------------------------------------------
+
+static bool dirExists(const std::string &path) {
+    DIR *d = opendir(path.c_str());
+    if (d) { closedir(d); return true; }
+    return false;
+}
+
+// Carts: a p8carts folder next to the XEX, else on a USB drive or the hard
+// disk. Settings, saves and the log stay next to the XEX (game:/fake08).
+static std::string findCartDirectory() {
+    static const char *const roots[] = {"game:/", "usb0:/", "usb1:/", "usb2:/", "hdd:/"};
+    for (const char *root : roots) {
+        std::string dir = std::string(root) + "p8carts";
+        if (dirExists(dir)) return dir;
+    }
+    std::string dir = "game:/p8carts";
+    mkdir(dir.c_str(), 0777);
+    return dir;
+}
+
+// ---------------------------------------------------------------------------
+// Performance overlay (settings -> dev -> performance overlay), drawn in the
+// border left of the game image; numbers refresh once per second.
+// ---------------------------------------------------------------------------
+
+static bool perfOverlay = false;   // mirrors the 'perfoverlay' setting
+static uint64_t perfLastDrawEnd = 0;
+static uint64_t perfSleepTb = 0;
+static uint64_t perfLastFrame = 0;
+static uint64_t perfWindowStart = 0;
+static uint64_t perfLogStart = 0;
+struct PerfAcc { uint64_t sum, max; void add(uint64_t v){ sum += v; if (v > max) max = v; } };
+static PerfAcc accEmu = {0,0}, accBlit = {0,0}, accWait = {0,0};
+static int perfFrames = 0, perfSlow = 0;
+static char perfLines[5][24] = {"", "", "", "", ""};
+
+static inline double tbToMs(uint64_t tb) { return (double)tb * 1000.0 / (double)tbFreq; }
+
+static void drawText(uint32_t *pixels, int px, int py, const char *str) {
+    const uint32_t white = xex_video_rgb(255, 255, 255);
+    for (; *str; str++, px += 8) {
+        const unsigned char *glyph = &fontdata_8x16[(unsigned char)*str * 16];
+        for (int gy = 0; gy < 16; gy++) {
+            unsigned char bits = glyph[gy];
+            for (int gx = 0; gx < 8; gx++) {
+                pixels[tiledIndex(px + gx, py + gy)] = (bits & (0x80 >> gx)) ? white : OpaqueBlack;
+            }
+        }
+    }
+}
+
+// Drawn every frame: the two front buffers alternate.
+static void drawPerfOverlay(uint32_t *pixels) {
+    const int widthChars = 20, lines = 5;
+    const int w = widthChars * 8;
+    if (destX < w + 4) return;                   // no room beside the image
+    const int x = (destX - w) / 2;               // centred in the left border
+    const int y = 8;
+    char blank[widthChars + 1];
+    memset(blank, ' ', widthChars); blank[widthChars] = 0;
+    for (int i = 0; i < lines; i++) {
+        drawText(pixels, x, y + i * 16, blank);
+        if (perfOverlay) drawText(pixels, x, y + i * 16, perfLines[i]);
+    }
+}
+
+static void perfFrameDone(uint64_t emuTb, uint64_t waitTb, uint64_t blitTb, uint64_t t) {
+    accEmu.add(emuTb); accWait.add(waitTb); accBlit.add(blitTb);
+    perfFrames++;
+    // "slow": more than 1.5 refresh periods since the last frame
+    if (perfLastFrame && (t - perfLastFrame) > (tbFreq / 60) * 3 / 2) perfSlow++;
+    perfLastFrame = t;
+
+    if (t - perfWindowStart >= tbFreq) {
+        int n = perfFrames ? perfFrames : 1;
+        snprintf(perfLines[0], 24, "%s %dfps slow %d", vsyncMode ? "vsync" : "timer", perfFrames, perfSlow);
+        snprintf(perfLines[1], 24, "emu  %5.1f/%5.1f", tbToMs(accEmu.sum / n), tbToMs(accEmu.max));
+        snprintf(perfLines[2], 24, "blit %5.1f/%5.1f", tbToMs(accBlit.sum / n), tbToMs(accBlit.max));
+        snprintf(perfLines[3], 24, "wait %5.1f/%5.1f", tbToMs(accWait.sum / n), tbToMs(accWait.max));
+        snprintf(perfLines[4], 24, "%dx%d %dx%d", fbWidth, fbHeight, destW, destH);
+        if (t - perfLogStart >= 5 * tbFreq) {
+            Logger_Write("perf: %s | %s | %s | %s | %s (avg/max ms)\n", perfLines[0], perfLines[1], perfLines[2], perfLines[3], perfLines[4]);
+            perfLogStart = t;
+        }
+        accEmu = {0,0}; accBlit = {0,0}; accWait = {0,0};
+        perfFrames = 0; perfSlow = 0;
+        perfWindowStart = t;
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Host
+// ---------------------------------------------------------------------------
+
+Host::Host(int windowWidth, int windowHeight) {
+    std::string base = "game:/fake08";
+    mkdir(base.c_str(), 0777);
+    mkdir((base + "/cdata").c_str(), 0777);
+
+    hasControllerSettings = true;
+    saveSettingsOnChange = true;
+    hasPerfOverlay = true;
+
+    _logFilePrefix = base + "/";
+    _cartDirectory = findCartDirectory();
+}
+
+void Host::setPlatformParams(
+    int windowWidth,
+    int windowHeight,
+    uint32_t sdlWindowFlags,
+    uint32_t sdlRendererFlags,
+    uint32_t sdlPixelFormat,
+    std::string logFilePrefix,
+    std::string customBiosLua,
+    std::string cartDirectory) {}
+
+void Host::oneTimeSetup(Audio *audio) {
+    Logger_Write("FAKE-08 for Xbox 360 (XEX), carts in %s\n", _cartDirectory.c_str());
+    videoOk = fbInit();
+    if (!videoOk) {
+        xex_notify("FAKE-08: video init failed");
+        quit = 1;
+        return;
+    }
+
+    stretch = PixelPerfectStretch;
+    currKDown = 0;
+    currKHeld = 0;
+
+    loadSettingsIni();
+    _changeStretch(stretch);
+
+    scaleX = destW / (float)PicoScreenWidth;
+    scaleY = destH / (float)PicoScreenHeight;
+    mouseOffsetX = destX;
+    mouseOffsetY = destY;
+
+    lastFrameTb = now();
+}
+
+void Host::oneTimeCleanup() {
+    saveSettingsIni();
+    // Returning from main ends the title (XamLoaderTerminateTitle), which
+    // goes back to Aurora; the video runtime gives the GPU back at exit.
+}
+
+void Host::setTargetFps(int targetFps) {
+    if (targetFps <= 0) targetFps = 60;
+    targetFrameTb = tbFreq / targetFps;
+    vsyncMode = targetFps == 60;
+}
+
+void Host::changeStretch() {
+    if (stretchKeyPressed && resizekey == YesResize) {
+        switch (stretch) {
+            case PixelPerfectStretch:    stretch = PixelPerfect; break;
+            case PixelPerfect:           stretch = StretchToFit; break;
+            case StretchToFit:           stretch = StretchToFill; break;
+            case StretchToFill:          stretch = FourByThreeVertPerfect; break;
+            case FourByThreeVertPerfect: stretch = FourByThreeStretch; break;
+            default:                     stretch = PixelPerfectStretch; break;
+        }
+        forceStretch(stretch);
+    }
+}
+
+void Host::forceStretch(StretchOption newStretch) {
+    _changeStretch(newStretch);
+    stretch = newStretch;
+    scaleX = destW / (float)PicoScreenWidth;
+    scaleY = destH / (float)PicoScreenHeight;
+    mouseOffsetX = destX;
+    mouseOffsetY = destY;
+}
+
+// Maps one controller to PICO-8 button bits (without the pause button).
+static uint8_t padToButtons(const xex_pad &c, int layout, int stickThreshold) {
+    uint8_t held = 0;
+    if ((c.buttons & XEX_PAD_LEFT)  || c.lx < -stickThreshold) held |= P8_KEY_LEFT;
+    if ((c.buttons & XEX_PAD_RIGHT) || c.lx >  stickThreshold) held |= P8_KEY_RIGHT;
+    if ((c.buttons & XEX_PAD_UP)    || c.ly >  stickThreshold) held |= P8_KEY_UP;
+    if ((c.buttons & XEX_PAD_DOWN)  || c.ly < -stickThreshold) held |= P8_KEY_DOWN;
+    // Layout 0 (PICO-8 default): A/Y = O, B/X = X. Layout 1 swaps them.
+    uint8_t bottomKey = layout == 1 ? P8_KEY_X : P8_KEY_O;
+    uint8_t rightKey  = layout == 1 ? P8_KEY_O : P8_KEY_X;
+    if (c.buttons & (XEX_PAD_A | XEX_PAD_Y)) held |= bottomKey;
+    if (c.buttons & (XEX_PAD_B | XEX_PAD_X)) held |= rightKey;
+    return held;
+}
+
+// Debounce releases (setting "button debounce"): a button only counts as
+// released after it has read "up" for releaseFrames consecutive polls.
+// Presses register immediately.
+static uint8_t debounceButtons(uint8_t held, uint8_t prevHeld, uint8_t upCount[8], int releaseFrames) {
+    uint8_t debounced = 0;
+    for (int i = 0; i < 8; i++) {
+        uint8_t bit = (uint8_t)(1 << i);
+        if (held & bit) {
+            upCount[i] = 0;
+            debounced |= bit;
+        } else if ((prevHeld & bit) && ++upCount[i] < releaseFrames) {
+            debounced |= bit;   // still treat as held until release is stable
+        }
+    }
+    return debounced;
+}
+
+InputState_t Host::scanInput() {
+    static const int DeadzoneThresholds[3] = {8000, 16000, 24000};
+    const int stickThreshold = DeadzoneThresholds[(deadzone >= 0 && deadzone <= 2) ? deadzone : 1];
+    const int releaseFrames = ((debounce >= 0 && debounce <= 3) ? debounce : 1) + 1;
+
+    static uint8_t upCount[4][8] = {};
+    static uint8_t extraHeld[3] = {0, 0, 0};
+
+    // Player 1 (port 0) also drives the system buttons. While the Guide is
+    // open XAM keeps the controllers, which then read as released.
+    xex_pad c;
+    xex_input_get(0, &c);
+
+    uint8_t held = padToButtons(c, btnlayout, stickThreshold);
+    bool start = c.buttons & XEX_PAD_START;
+    bool back = c.buttons & XEX_PAD_BACK;
+    if (start) held |= P8_KEY_PAUSE;
+
+    static bool backWasDown = false;
+    stretchKeyPressed = back && !backWasDown && !start;
+    backWasDown = back;
+
+    // BACK + START quits to Aurora (some dashboard plugins take this combo
+    // for screenshots; the Guide's Xbox Home always works)
+    if (back && start) quit = 1;
+
+    uint8_t debounced = debounceButtons(held, currKHeld, upCount[0], releaseFrames);
+    currKDown = debounced & ~currKHeld;
+    currKHeld = debounced;
+
+    InputState_t state{
+        currKDown,
+        currKHeld,
+        0, 0, 0
+    };
+
+    // Players 2-4 (ports 1-3). Disconnected controllers read as all zero.
+    for (int p = 0; p < 3; p++) {
+        xex_pad pc;
+        xex_input_get(p + 1, &pc);
+        uint8_t ph = debounceButtons(padToButtons(pc, btnlayout, stickThreshold),
+                                     extraHeld[p], upCount[p + 1], releaseFrames);
+        state.extraKDown[p] = ph & ~extraHeld[p];
+        state.extraKHeld[p] = ph;
+        extraHeld[p] = ph;
+    }
+
+    return state;
+}
+
+bool Host::shouldQuit() {
+    // never end by ourselves while the Guide shows (XAM would wait for a
+    // swap that never comes); Xbox Home ends the title from there anyway
+    return quit > 0 && !xex_video_guide_visible();
+}
+
+void Host::waitForTargetFps() {
+    // At 60 fps drawFrame() waits for the previous flip, which paces the loop.
+    if (vsyncMode) return;
+
+    uint64_t t = now();
+    uint64_t elapsed = t - lastFrameTb;
+    if (elapsed < targetFrameTb) {
+        uint64_t remaining = targetFrameTb - elapsed;
+        unsigned ms = (unsigned)(remaining * 1000 / tbFreq);
+        if (ms > 1) xex_sleep_ms(ms - 1);           // kernel sleep, then spin
+        while (now() - lastFrameTb < targetFrameTb) {}
+        perfSleepTb += remaining;
+        lastFrameTb += targetFrameTb;
+    } else {
+        // Running behind: don't try to catch up with a burst of frames
+        lastFrameTb = t;
+    }
+}
+
+void Host::drawFrame(uint8_t *picoFb, uint8_t *screenPaletteMap, uint8_t drawMode) {
+    if (!videoOk) return;
+
+    perfOverlay = perfoverlay == 1;
+    uint64_t tbStart = now();
+    uint64_t emuTb = perfLastDrawEnd ? (tbStart - perfLastDrawEnd - perfSleepTb) : 0;
+    perfSleepTb = 0;
+
+    // 1. palette lookup + drawMode transform into a 128x128 RGB buffer
+    uint32_t pal[16];
+    for (int i = 0; i < 16; i++) {
+        pal[i] = fbColor(_paletteColors[screenPaletteMap[i] & 0x8f]);
+    }
+    for (int y = 0; y < PicoScreenHeight; y++) {
+        for (int x = 0; x < PicoScreenWidth; x++) {
+            int sx, sy;
+            srcCoord(drawMode, x, y, sx, sy);
+            frameRgb[y * PicoScreenWidth + x] = pal[getPixelNibble(sx, sy, picoFb)];
+        }
+    }
+
+    // 2. the back buffer, once the previous flip is on screen (at 60 fps
+    //    this wait is the frame pacing)
+    uint64_t tbWaitStart = now();
+    xex_frame f = xex_video_begin();
+    uint32_t *pixels = f.pixels;
+    uint64_t tbBlitStart = now();
+
+    if (clearFrames > 0) {
+        for (int y = 0; y < fbHeight; y++)
+            for (int x = 0; x < fbWidth; x++) pixels[tiledIndex(x, y)] = OpaqueBlack;
+        clearFrames--;
+    }
+
+    // 3. nearest-neighbour scale into the tiled back buffer
+    for (int dy = 0; dy < destH; dy++) {
+        const uint32_t *srcRow = &frameRgb[yMap[dy] * PicoScreenWidth];
+        int y = destY + dy;
+        for (int dx = 0; dx < destW; dx++) {
+            pixels[tiledIndex(destX + dx, y)] = srcRow[xMap[dx]];
+        }
+    }
+    drawPerfOverlay(pixels);
+
+    // 4. flip at the next vertical blank
+    xex_video_present();
+
+    uint64_t tbEnd = now();
+    perfFrameDone(emuTb + (tbWaitStart - tbStart), tbBlitStart - tbWaitStart, tbEnd - tbBlitStart, tbBlitStart);
+    perfLastDrawEnd = now();
+}
+
+// Audio: not implemented yet (step 4). The core runs without sound.
+bool Host::shouldFillAudioBuff() {
+    return false;
+}
+
+void *Host::getAudioBufferPointer() {
+    return nullptr;
+}
+
+size_t Host::getAudioBufferSize() {
+    return 0;
+}
+
+void Host::playFilledAudioBuffer() {
+}
+
+bool Host::shouldRunMainLoop() {
+    return !quit;
+}
+
+vector<string> Host::listcarts() {
+    vector<string> carts;
+
+    DIR *dir = opendir(_cartDirectory.c_str());
+    if (dir != NULL) {
+        struct dirent *ent;
+        while ((ent = readdir(dir)) != NULL) {
+            if (isCartFile(ent->d_name)) {
+                carts.push_back(_cartDirectory + "/" + ent->d_name);
+            }
+        }
+        closedir(dir);
+    }
+
+    return carts;
+}
+
+const char *Host::logFilePrefix() {
+    return _logFilePrefix.c_str();
+}
+
+std::string Host::customBiosLua() {
+    // The BIOS runs a cart with X: that is B in layout 0 and A in layout 1.
+    return "cartpath = \"" + _cartDirectory + "/\"\n"
+           "selectbtn = \"" + std::string(btnlayout == 1 ? "a" : "b") + "\"\n"
+           "pausebtn = \"start\"\n"
+           "exitbtn = \"xbox button > home\"\n"
+           "sizebtn = \"back to cycle screen sizes\"";
+}
+
+std::string Host::getCartDirectory() {
+    return _cartDirectory;
+}
+
+std::vector<std::string> Host::listdirs() {
+    std::vector<std::string> dirs;
+
+    DIR *dir = opendir(_cartDirectory.c_str());
+    if (dir != NULL) {
+        struct dirent *ent;
+        while ((ent = readdir(dir)) != NULL) {
+            if (ent->d_name[0] == '.') continue;
+            std::string fullPath = _cartDirectory + "/" + ent->d_name;
+            if (dirExists(fullPath)) dirs.push_back(ent->d_name);
+        }
+        closedir(dir);
+    }
+
+    return dirs;
+}
diff --git a/platform/xex/tests/hello/main.cpp b/platform/xex/tests/hello/main.cpp
index 5b3da3a..95d3d8f 100644
--- a/platform/xex/tests/hello/main.cpp
+++ b/platform/xex/tests/hello/main.cpp
@@ -1,5 +1,6 @@
 // Runtime check 1: C++ runtime in a GCC-built XEX (static constructor,
-// exception, std::regex), reported with guide notifications.
+// exception, std::regex, a 896 KB deep stack), reported with guide
+// notifications.
 #include <string>
 #include <regex>
 #include <stdexcept>
@@ -13,6 +14,24 @@ struct StaticInit {
 };
 static StaticInit g_static;

+// Stack probe: recurses in 32 KB frames, logging each 64 KB to
+// game:/stack-test.txt, so a crash shows how deep the main thread's stack
+// goes (xex-link asks for 1 MB).
+static void stackLog(int kb) {
+    if (FILE *f = fopen("game:/stack-test.txt", "a")) {
+        fprintf(f, "stack %d KB ok\n", kb);
+        fclose(f);
+    }
+}
+
+static int __attribute__((noinline)) stackDepth(int kb, int limitKb) {
+    volatile char frame[32 * 1024];
+    for (unsigned i = 0; i < sizeof(frame); i += 512) frame[i] = (char)kb;
+    if (kb % 64 == 0) stackLog(kb);
+    int r = kb >= limitKb ? kb : stackDepth(kb + 32, limitKb);
+    return r + frame[0] - (char)kb;   // keeps the frame live
+}
+
 int main(int, char **) {
     std::string result = "GCC XEX ok:";
     result += g_static.value == 42 ? " ctor" : " CTOR-FAIL";
@@ -30,6 +49,10 @@ int main(int, char **) {
     bool re = std::regex_search(s, m, std::regex("#include\\s+([a-z.]+)")) && m[1] == "foo.lua";
     result += re ? " regex" : " REGEX-FAIL";

+    remove("game:/stack-test.txt");
+    int deepest = stackDepth(32, 896);
+    result += deepest >= 896 ? " stack896K" : " STACK-FAIL";
+
     printf("hello: %s\n", result.c_str());
     xex_notify("Hello from FAKE-08 XEX (GCC)");
     xex_sleep_ms(3000);
diff --git a/platform/xex/tools/build-xex-link.sh b/platform/xex/tools/build-xex-link.sh
index f990063..d35c80d 100755
--- a/platform/xex/tools/build-xex-link.sh
+++ b/platform/xex/tools/build-xex-link.sh
@@ -15,7 +15,13 @@ if [ ! -d "$SRC/.git" ]; then
 fi
 cd "$SRC"
 git fetch -q origin
-git checkout -q "$XENON_FORGE_COMMIT"
+git checkout -q -f "$XENON_FORGE_COMMIT"
+
+# Main thread stack: 1 MB instead of 256 KB (Lua and the emulator core
+# recurse deeper than 256 KB allows; xsdk also gives titles 1 MB).
+sed -i 's/w32(&mut headers, 0x40000); \/\/ SizeOfStackReserve/w32(\&mut headers, 0x100000); \/\/ SizeOfStackReserve/' \
+    src/crates/xex-link/src/pe.rs
+grep -q '0x100000); // SizeOfStackReserve' src/crates/xex-link/src/pe.rs

 rustup target add x86_64-unknown-linux-musl
 cargo build --release -p xex-link --target x86_64-unknown-linux-musl