diff --git a/CMakeLists.txt b/CMakeLists.txt index 1258eb2a..c22249f9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,7 +101,7 @@ set(EMULATOR_COMPONENTS set( COMPONENTS - "main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer ${EMULATOR_COMPONENTS} box-emu gui menu settings emulink" + "main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer ${EMULATOR_COMPONENTS} core_overlay box-emu gui menu settings emulink" CACHE STRING "List of components to include" FORCE @@ -111,6 +111,16 @@ project(esp-box-emu) set(CMAKE_CXX_STANDARD 20) +# The game cores' code overlay (components/core_overlay): after linking, the +# cores' relocated code goes into its flash store (before the .bin is made from +# the ELF), and nothing resident may reach into the overlay +idf_build_get_property(python PYTHON) +add_custom_command(TARGET ${CMAKE_PROJECT_NAME}.elf POST_BUILD + COMMAND ${python} ${CMAKE_CURRENT_LIST_DIR}/components/core_overlay/tools/core_overlay.py image ${CMAKE_OBJCOPY} + $ ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.map + COMMENT "Storing the game cores' code overlay in flash" + VERBATIM) + # The updater app (updater/) belongs in ota_1 (see partitions.csv): build it # first (idf.py -C updater build) and `idf.py flash`, flash_args and # flasher_args.json (the release package) put it there with the emulator. diff --git a/README.md b/README.md index 7d671afc..438034c1 100644 --- a/README.md +++ b/README.md @@ -366,6 +366,14 @@ captured play session doubles as a profile: block above a threshold (labelled with the task whose stack it is), each registered heap region's used/free/largest, and every task's stack high-water mark (`stack_free_min`, repeated at quit after a full play session). +- `core_overlay: CORE: N KB of code loaded in N ms (N KB of PSRAM, N constructors)` + / `core_overlay: CORE: unloaded` — the game cores' code overlay + (`components/core_overlay`): every core's code is linked at one address and + only the running core's is in PSRAM (the rest of the firmware's code is + copied into PSRAM at boot), so the other cores' ~1.5 MB of code stays in + flash. The build prints the store and each core's code size + (`core_overlay: N KB of core code stored in flash ...`) and fails if + resident code or data reaches into the overlay. - `[genesis mem] NAME: N bytes -> INTERNAL|PSRAM` — where each big emulator buffer landed (the Genesis gets noticeably slower when its hot buffers fall back to PSRAM). diff --git a/components/core_overlay/CMakeLists.txt b/components/core_overlay/CMakeLists.txt new file mode 100644 index 00000000..15d16a45 --- /dev/null +++ b/components/core_overlay/CMakeLists.txt @@ -0,0 +1,32 @@ +# The game cores' code overlay (overlay.ld, include/core_overlay.h): the code +# of the cores that are not running stays in flash; the one a game needs is +# copied into PSRAM when it launches. +idf_component_register( + SRCS "src/core_overlay.c" "src/store.c" + INCLUDE_DIRS "include" + PRIV_REQUIRES esp_mm esp_hw_support hal spi_flash heap log esp_timer freertos) + +# The flash store's size (src/store.c) from the cores' archives, after their +# code was renamed into the overlay (core_overlay_archive(), POST_BUILD) +set(cores nes gbc sms msx genesis doom darkforces pico8) +idf_build_get_property(python PYTHON) +idf_build_get_property(build_components BUILD_COMPONENTS) +set(libs "") +set(archives "") +foreach(core ${cores}) + if(core IN_LIST build_components) + idf_component_get_property(lib ${core} COMPONENT_LIB) + list(APPEND libs ${lib}) + list(APPEND archives "$") + endif() +endforeach() +set(size_h "${CMAKE_CURRENT_BINARY_DIR}/core_ovl_store_size.h") +add_custom_command(OUTPUT "${size_h}" + COMMAND ${python} "${CMAKE_CURRENT_LIST_DIR}/tools/core_overlay.py" size ${CMAKE_OBJCOPY} "${size_h}" ${archives} + DEPENDS ${libs} "${CMAKE_CURRENT_LIST_DIR}/tools/core_overlay.py" + COMMENT "Sizing the core code overlay's flash store" + VERBATIM) +target_sources(${COMPONENT_LIB} PRIVATE "${size_h}") +target_include_directories(${COMPONENT_LIB} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") + +target_linker_script(${COMPONENT_LIB} INTERFACE "${CMAKE_CURRENT_LIST_DIR}/overlay.ld") diff --git a/components/core_overlay/include/core_overlay.h b/components/core_overlay/include/core_overlay.h new file mode 100644 index 00000000..91175cd0 --- /dev/null +++ b/components/core_overlay/include/core_overlay.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// The game cores' code overlay (overlay.ld): every core's code is linked at +/// one instruction-bus address and the core a game needs is copied there, +/// into PSRAM, when it launches; the other cores' code stays in flash. +/// +/// Make a game core's code runnable: maps a PSRAM block the size of the +/// core's code at the overlay address, copies the core's code into it from +/// flash and, on the core's first load, runs its static constructors. Call it +/// before any of the core's code runs (before its cart is made) and only +/// while no other core's code runs; a core that is loaded already stays (any +/// other is unloaded first). +/// +/// `core` is the overlay member's name: nes, gbc, sms, msx, genesis, doom, +/// darkforces or pico8. Returns false for any other name, or when the PSRAM +/// for the code cannot be had. +bool core_overlay_load(const char *core); + +/// Unmap the loaded core's code and free its PSRAM (after its cart is gone: +/// nothing of the core may run any more, no task, callback or interrupt). +void core_overlay_unload(void); + +/// The core whose code is loaded ("" for none). +const char *core_overlay_loaded(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/core_overlay/overlay.ld b/components/core_overlay/overlay.ld new file mode 100644 index 00000000..9286cb21 --- /dev/null +++ b/components/core_overlay/overlay.ld @@ -0,0 +1,110 @@ +/* The game cores' code overlay (include/core_overlay.h): only one game runs at + * a time, so every core's code is linked at the same instruction-bus address + * and the one a game needs is copied into PSRAM there when it launches + * (src/core_overlay.c). The rest of the firmware's code is copied into PSRAM + * at boot as before (CONFIG_SPIRAM_FETCH_INSTRUCTIONS); the cores that are not + * running are in flash only. + * + * tools/core_overlay.py rename (POST_BUILD of each core's library) renames a + * core archive's code to .core_ovl..* and its constructor tables to + * .core_ovl_ctors_*. A member holds its constructor table first (run on + * the core's first load), then its code; literals stay in front of the code + * that loads them (each object's .literal.* precede its .text.*). + * + * Linked bytes: the bootloader only loads an image's flash and internal RAM + * segments, so after linking tools/core_overlay.py image copies each member's + * relocated bytes into the flash store (src/store.c, in .flash.rodata), marks + * the member NOBITS, and checks that nothing resident reaches into the + * overlay. NOCROSSREFS: a link error if one core's code references another's. + * + * 0x43800000 (MMU linear page 384) is far above everything IDF maps at boot + * (flash .text and .rodata, then all of the PSRAM) and anything mapped later + * (src/core_overlay.c map_window()); its data-bus alias (0x3D800000) is never + * used. */ +MEMORY +{ + core_ovl_seg (RX) : org = 0x43800000, len = 0x800000 +} + +SECTIONS +{ + OVERLAY : NOCROSSREFS + { + .core_ovl.nes + { + _core_ovl_ctors_nes_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_nes.*))) KEEP(*(.core_ovl_ctors_nes)) + _core_ovl_ctors_nes_end = ABSOLUTE(.); + *(.core_ovl.nes.*) + . = ALIGN(16); + } + .core_ovl.gbc + { + _core_ovl_ctors_gbc_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_gbc.*))) KEEP(*(.core_ovl_ctors_gbc)) + _core_ovl_ctors_gbc_end = ABSOLUTE(.); + *(.core_ovl.gbc.*) + . = ALIGN(16); + } + .core_ovl.sms + { + _core_ovl_ctors_sms_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_sms.*))) KEEP(*(.core_ovl_ctors_sms)) + _core_ovl_ctors_sms_end = ABSOLUTE(.); + *(.core_ovl.sms.*) + . = ALIGN(16); + } + .core_ovl.msx + { + _core_ovl_ctors_msx_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_msx.*))) KEEP(*(.core_ovl_ctors_msx)) + _core_ovl_ctors_msx_end = ABSOLUTE(.); + *(.core_ovl.msx.*) + . = ALIGN(16); + } + .core_ovl.genesis + { + _core_ovl_ctors_genesis_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_genesis.*))) KEEP(*(.core_ovl_ctors_genesis)) + _core_ovl_ctors_genesis_end = ABSOLUTE(.); + *(.core_ovl.genesis.*) + . = ALIGN(16); + } + .core_ovl.doom + { + _core_ovl_ctors_doom_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_doom.*))) KEEP(*(.core_ovl_ctors_doom)) + _core_ovl_ctors_doom_end = ABSOLUTE(.); + *(.core_ovl.doom.*) + . = ALIGN(16); + } + .core_ovl.darkforces + { + _core_ovl_ctors_darkforces_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_darkforces.*))) KEEP(*(.core_ovl_ctors_darkforces)) + _core_ovl_ctors_darkforces_end = ABSOLUTE(.); + *(.core_ovl.darkforces.*) + . = ALIGN(16); + } + .core_ovl.pico8 + { + _core_ovl_ctors_pico8_start = ABSOLUTE(.); + KEEP(*(SORT(.core_ovl_ctors_pico8.*))) KEEP(*(.core_ovl_ctors_pico8)) + _core_ovl_ctors_pico8_end = ABSOLUTE(.); + *(.core_ovl.pico8.*) + . = ALIGN(16); + } + } > core_ovl_seg + _core_ovl_start = ADDR(.core_ovl.nes); + /* after an OVERLAY, . is its start plus its largest member */ + _core_ovl_end = ALIGN(., 16); +} +_core_ovl_nes_size = SIZEOF(.core_ovl.nes); +_core_ovl_gbc_size = SIZEOF(.core_ovl.gbc); +_core_ovl_sms_size = SIZEOF(.core_ovl.sms); +_core_ovl_msx_size = SIZEOF(.core_ovl.msx); +_core_ovl_genesis_size = SIZEOF(.core_ovl.genesis); +_core_ovl_doom_size = SIZEOF(.core_ovl.doom); +_core_ovl_darkforces_size = SIZEOF(.core_ovl.darkforces); +_core_ovl_pico8_size = SIZEOF(.core_ovl.pico8); +ASSERT(_core_ovl_start % 0x10000 == 0, "the core overlay must start on an MMU page") diff --git a/components/core_overlay/project_include.cmake b/components/core_overlay/project_include.cmake new file mode 100644 index 00000000..0cc8d8bd --- /dev/null +++ b/components/core_overlay/project_include.cmake @@ -0,0 +1,28 @@ +# core_overlay_archive( [keep-regex ...]): in a game core's component +# CMakeLists.txt, after idf_component_register(): put the core's code into the +# code overlay (overlay.ld; tools/core_overlay.py rename, POST_BUILD of the +# component's library). keep-regex: code that stays resident although it is in +# the core's archive (matched against the function name; see the script). +set(CORE_OVERLAY_TOOL "${CMAKE_CURRENT_LIST_DIR}/tools/core_overlay.py") + +function(core_overlay_archive core) + idf_build_get_property(python PYTHON) + set(keep "") + foreach(k ${ARGN}) + list(APPEND keep "--keep=${k}") + endforeach() + add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD + COMMAND ${python} ${CORE_OVERLAY_TOOL} rename ${CMAKE_OBJCOPY} $ ${core} ${keep} + COMMENT "Moving the ${core} core's code into the code overlay" + VERBATIM) + core_overlay_rebuild_on(${CORE_OVERLAY_TOOL}) +endfunction() + +# core_overlay_rebuild_on(): a POST_BUILD step of a library has no inputs (and +# LINK_DEPENDS does not reach a static library's archive step): rebuild the calling +# component's library when changes, by making one of its objects depend on it +function(core_overlay_rebuild_on file) + get_target_property(sources ${COMPONENT_LIB} SOURCES) + list(GET sources 0 first) + set_property(SOURCE ${first} APPEND PROPERTY OBJECT_DEPENDS ${file}) +endfunction() diff --git a/components/core_overlay/src/core_overlay.c b/components/core_overlay/src/core_overlay.c new file mode 100644 index 00000000..660747ac --- /dev/null +++ b/components/core_overlay/src/core_overlay.c @@ -0,0 +1,214 @@ +// The game cores' code overlay (overlay.ld, include/core_overlay.h): every +// core's code is linked at one instruction-bus address; the core a game needs +// is copied from its slot in the flash store (src/store.c) into a PSRAM block +// that is mapped at that address for the game. +// +// The ESP32-S3's MMU entry for a page serves the instruction bus (0x42...) and +// the data bus (0x3C...) alike, and a PSRAM page can be mapped at two +// addresses: the block comes from the PSRAM heap (its data-bus address is +// where the code is written) and map_window() maps the same pages at the +// overlay address, executable. Written through the data cache, the code is +// written back to PSRAM and the instruction cache (one, for both CPUs) drops +// the overlay range before the code runs. +#include "core_overlay.h" + +#include +#include +#include + +#include "sdkconfig.h" + +#include "esp_attr.h" +#include "esp_cache.h" +#include "esp_heap_caps.h" +#include "esp_log.h" +#include "esp_mmu_map.h" +#include "esp_private/cache_utils.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "hal/cache_ll.h" +#include "hal/mmu_hal.h" + +static const char *TAG = "core_overlay"; + +#define PAGE 0x10000u +#define MAGIC 0x4C564F43u // "COVL" (tools/core_overlay.py) + +typedef void (*ctor_fn)(void); + +// linker symbols (overlay.ld): the overlay range, and per core its code size +// (the symbol's value) and its constructor table (at the overlay address) +extern uint8_t _core_ovl_start[], _core_ovl_end[]; +#define CORE_OVL_SYMBOLS(name) \ + extern const char _core_ovl_##name##_size[]; \ + extern const ctor_fn _core_ovl_ctors_##name##_start[], _core_ovl_ctors_##name##_end[]; +CORE_OVL_SYMBOLS(nes) +CORE_OVL_SYMBOLS(gbc) +CORE_OVL_SYMBOLS(sms) +CORE_OVL_SYMBOLS(msx) +CORE_OVL_SYMBOLS(genesis) +CORE_OVL_SYMBOLS(doom) +CORE_OVL_SYMBOLS(darkforces) +CORE_OVL_SYMBOLS(pico8) + +extern const uint8_t core_ovl_store[]; + +typedef struct { + uint32_t offset, size; +} store_entry_t; + +typedef struct { + uint32_t magic, count; + store_entry_t entry[]; +} store_header_t; + +typedef struct { + const char *name; + size_t size; + const ctor_fn *ctors, *ctors_end; +} member_t; + +#define CORE_OVL_MEMBER(n) \ + {#n, (size_t)(uintptr_t)_core_ovl_##n##_size, _core_ovl_ctors_##n##_start, _core_ovl_ctors_##n##_end} + +// the store header's order (tools/core_overlay.py CORES) +static const member_t s_members[] = { + CORE_OVL_MEMBER(nes), CORE_OVL_MEMBER(gbc), CORE_OVL_MEMBER(sms), CORE_OVL_MEMBER(msx), + CORE_OVL_MEMBER(genesis), CORE_OVL_MEMBER(doom), CORE_OVL_MEMBER(darkforces), CORE_OVL_MEMBER(pico8), +}; +#define NUM_MEMBERS (int)(sizeof(s_members) / sizeof(s_members[0])) + +static int s_loaded = -1; +static uint8_t *s_data; // the PSRAM block (data-bus view) +static void *s_code; // its executable mapping at the overlay address +static size_t s_mapped; // bytes mapped +static uint32_t s_constructed; // bit per member: its constructors have run + +// Map [vaddr, vaddr + size) to the PSRAM at paddr (map) or unmap it, the way +// IDF's own MMU driver does it: with the caches and the other CPU stopped, so +// from internal RAM (mmu_hal is there too). Not through esp_mmu_map_virt(): +// IDF 6.0, which CI builds with, does not have it. The driver does not track +// the window; it lies far above everything the firmware maps (overlay.ld). +// Returns the bytes mapped. +static IRAM_ATTR NOINLINE_ATTR uint32_t map_window(uint32_t vaddr, uint32_t paddr, uint32_t size, bool map) { + uint32_t done = size; + spi_flash_disable_interrupts_caches_and_other_cpu(); + if (map) { + mmu_hal_map_region(0, MMU_TARGET_PSRAM0, vaddr, paddr, size, &done); + const cache_bus_mask_t bus = cache_ll_l1_get_bus(0, vaddr, size); + cache_ll_l1_enable_bus(0, bus); +#if !(CONFIG_FREERTOS_UNICORE || CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE) + cache_ll_l1_enable_bus(1, bus); +#endif + } else { + mmu_hal_unmap_region(0, vaddr, size); + } + spi_flash_enable_interrupts_caches_and_other_cpu(); + return done; +} + +bool core_overlay_load(const char *core) { + int i = 0; + while (i < NUM_MEMBERS && strcmp(core, s_members[i].name) != 0) { + i++; + } + if (i == NUM_MEMBERS) { + ESP_LOGE(TAG, "no core '%s' in the overlay", core); + return false; + } + if (i == s_loaded) { + return true; + } + core_overlay_unload(); + const member_t *m = &s_members[i]; + const store_header_t *h = (const store_header_t *)core_ovl_store; + if (h->magic != MAGIC || (int)h->count != NUM_MEMBERS || h->entry[i].size != m->size) { + ESP_LOGE(TAG, "%s: the flash store does not hold its code (was tools/core_overlay.py image run?)", core); + return false; + } + if (m->size > (size_t)((uintptr_t)_core_ovl_end - (uintptr_t)_core_ovl_start)) { + ESP_LOGE(TAG, "%s: %u bytes of code, more than the overlay's range", core, (unsigned)m->size); + return false; + } + if (m->size == 0) { + s_loaded = i; + return true; + } + const int64_t t0 = esp_timer_get_time(); + const size_t mapped = (m->size + PAGE - 1) & ~(PAGE - 1); + uint8_t *data = heap_caps_aligned_alloc(PAGE, mapped, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!data) { + ESP_LOGE(TAG, "%s: no %u KB of PSRAM for its code (largest free block %u KB)", core, (unsigned)(mapped / 1024), + (unsigned)(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + return false; + } + // the heap's PSRAM is one linear mapping: the block's pages are consecutive + esp_paddr_t paddr = 0, page_paddr = 0; + mmu_target_t target, page_target; + bool linear = esp_mmu_vaddr_to_paddr(data, &paddr, &target) == ESP_OK && target == MMU_TARGET_PSRAM0; + for (size_t off = PAGE; linear && off < mapped; off += PAGE) { + linear = esp_mmu_vaddr_to_paddr(data + off, &page_paddr, &page_target) == ESP_OK && + page_target == MMU_TARGET_PSRAM0 && page_paddr == paddr + off; + } + void *code = (void *)_core_ovl_start; + const uint32_t window = (uint32_t)(uintptr_t)code; + if (!linear || map_window(window, paddr, mapped, true) != mapped) { + ESP_LOGE(TAG, "%s: cannot map its PSRAM block at %p (%s)", core, code, + linear ? "the MMU mapped less" : "not one linear PSRAM range"); + if (linear) { + map_window(window, 0, mapped, false); + } + heap_caps_free(data); + return false; + } + memcpy(data, core_ovl_store + h->entry[i].offset, m->size); + // written through the data cache: write it back to PSRAM; then drop the + // overlay range from the instruction cache (it may hold another core's code) + esp_cache_msync(data, mapped, ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_TYPE_DATA); + esp_cache_msync(code, mapped, ESP_CACHE_MSYNC_FLAG_DIR_M2C | ESP_CACHE_MSYNC_FLAG_TYPE_INST); + __asm__ volatile("isync" ::: "memory"); + s_data = data; + s_code = code; + s_mapped = mapped; + s_loaded = i; + const int64_t t1 = esp_timer_get_time(); + unsigned ctors = 0; + if (!(s_constructed & (1u << i))) { + // the core's static constructors, once per boot (its data persists); the + // table is part of the code, read through the data-bus view + s_constructed |= 1u << i; + const uint8_t *table = data + ((uintptr_t)m->ctors - (uintptr_t)_core_ovl_start); + ctors = (unsigned)(m->ctors_end - m->ctors); + for (unsigned k = 0; k < ctors; k++) { + ctor_fn fn; + memcpy(&fn, table + k * sizeof(fn), sizeof(fn)); + fn(); + } + } + ESP_LOGI(TAG, "%s: %u KB of code loaded in %lld ms (%u KB of PSRAM, %u constructors)", core, + (unsigned)(m->size / 1024), (t1 - t0) / 1000, (unsigned)(mapped / 1024), ctors); + return true; +} + +void core_overlay_unload(void) { + if (s_code) { + // A core's helper task that deletes itself signals its owner just before + // vTaskDelete() (the Genesis sound task, Dark Forces' MIDI thread): its + // last few instructions still run from the overlay. Give it the time to + // get there before the code goes away. + vTaskDelay(pdMS_TO_TICKS(20)); + // drop the code from the instruction cache too, so that anything of the + // core that still runs faults instead of running it + esp_cache_msync(s_code, s_mapped, ESP_CACHE_MSYNC_FLAG_DIR_M2C | ESP_CACHE_MSYNC_FLAG_TYPE_INST); + map_window((uint32_t)(uintptr_t)s_code, 0, s_mapped, false); + heap_caps_free(s_data); + ESP_LOGI(TAG, "%s: unloaded (%u KB of PSRAM freed)", s_members[s_loaded].name, (unsigned)(s_mapped / 1024)); + } + s_code = NULL; + s_data = NULL; + s_mapped = 0; + s_loaded = -1; +} + +const char *core_overlay_loaded(void) { return s_loaded >= 0 ? s_members[s_loaded].name : ""; } diff --git a/components/core_overlay/src/store.c b/components/core_overlay/src/store.c new file mode 100644 index 00000000..81eef809 --- /dev/null +++ b/components/core_overlay/src/store.c @@ -0,0 +1,10 @@ +// The flash store of the game cores' code overlay (overlay.ld): a header and +// every core's linked code, written into this array after linking by +// tools/core_overlay.py image. Its size (core_ovl_store_size.h) is computed +// before the link from the cores' archives (an upper bound: the link drops +// unused code). In .flash.rodata, so the image's SHA-256 covers it. +#include + +#include "core_ovl_store_size.h" + +__attribute__((section(".rodata.core_ovl_store"), aligned(16))) const uint8_t core_ovl_store[CORE_OVL_STORE_SIZE] = {0}; diff --git a/components/core_overlay/tools/core_overlay.py b/components/core_overlay/tools/core_overlay.py new file mode 100644 index 00000000..baa85aff --- /dev/null +++ b/components/core_overlay/tools/core_overlay.py @@ -0,0 +1,434 @@ +#!/usr/bin/env python3 +"""The game cores' code overlay (see ../overlay.ld and ../include/core_overlay.h). + +Every core's code is linked at one instruction-bus address and the core a game +needs is copied into PSRAM there when it launches, so the code of the cores +that are not running is in flash only (the rest of the firmware is copied into +PSRAM at boot, CONFIG_SPIRAM_FETCH_INSTRUCTIONS). Three steps: + + core_overlay.py rename [--keep=REGEX ...] + (POST_BUILD of a core's library, core_overlay_archive() in + ../project_include.cmake) renames the archive's code (.literal*, + .text*) to .core_ovl..* and its constructor tables (.ctors*) to + .core_ovl_ctors_*, which run on the core's first load instead of + at boot. What stays resident (normal .flash.text): + - COMDAT groups (inline functions, template instances): the linker + keeps one copy for the whole firmware, which may be this archive's + while other code uses it; + - code whose name (after .text. / .literal. and unlikely. / hot. / + startup. / exit.) matches a --keep regex: code the rest of the + firmware calls although it is in a core's archive (e.g. Dark Forces' + firmware-wide free() wrapper). + Running it again does nothing (the renamed sections match nothing). + + core_overlay.py size ... + writes CORE_OVL_STORE_SIZE: what the flash store (src/store.c, in + .flash.rodata) needs for every renamed archive's overlay code, an upper + bound of the linked size (the link drops unused functions). + + core_overlay.py image [--report] + (POST_BUILD of the app, before the .bin is made) copies each linked, + relocated member .core_ovl. into the flash store behind a header + (magic, then per core in CORES order its offset in the store and its + size), marks the members NOBITS so elf2image leaves the instruction-bus + sections out of the image, and checks that nothing resident reaches + into the overlay, because only one core's code is there at a time (or + none): + - no boot-time constructor points into the overlay; + - every resident word that is the address of an overlay function (on + Xtensa every reference from resident code is one: a literal for + l32r, as calls cannot reach from 0x42... to 0x438...) is in the carts + (main.cpp, which load the core first), the loader, or the same core's + archive: its data (jump tables, vtables), its internal-RAM code, or + resident code of its own that is local or that only its own archive + references (the linker's cross-reference table). + A finding names the resident code and the overlay function it reaches; + the usual fix is a --keep regex for that function. + Last, the members' part of the map goes to .core_overlay.map: in the + map they are output sections at one address with load addresses of their + own, which idf.py size (esp-idf-size) cannot parse, and the code they hold + is in the flash store, which the map counts (.flash.rodata). +""" +import bisect +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +from array import array + +# the order of the store header's entries (src/core_overlay.c has the same) +CORES = ("nes", "gbc", "sms", "msx", "genesis", "doom", "darkforces", "pico8") +MAGIC = 0x4C564F43 # "COVL" +CART_FILES = ("libmain.a(main.cpp.obj)",) +LOADER_ARCHIVE = "libcore_overlay.a(" + + +def tool(objcopy, name): + """another binutils program next to objcopy (xtensa-esp32s3-elf-objcopy -> ...-readelf)""" + path = re.sub(r"objcopy(\.exe)?$", name + r"\1", objcopy) + return path if os.path.exists(path) or shutil.which(path) else name + + +def align(value, to): + return (value + to - 1) // to * to if to > 1 else value + + +SECTION = re.compile(r"^\s*\[\s*\d+\]\s+(\S+)\s+(\S+)\s+[0-9a-f]+\s+[0-9a-f]+\s+([0-9a-f]+)\s+[0-9a-f]+\s+([A-Za-z]*)\s+\d+\s+\d+\s+(\d+)\s*$") + + +def archive_sections(objcopy, archive): + """(member, name, size, flags, alignment) of every section in the archive""" + out = subprocess.run([tool(objcopy, "readelf"), "-S", "-W", archive], check=True, capture_output=True, + text=True).stdout + member = None + for line in out.splitlines(): + if line.startswith("File: "): + member = line[6:].strip() + continue + m = SECTION.match(line) + if m: + yield member, m.group(1), int(m.group(3), 16), m.group(4), int(m.group(5)) + + +CODE = re.compile(r"^\.(literal|text)(\..*)?$") +CTORS = re.compile(r"^\.ctors(\..*)?$") + + +def function_of(name): + """the function a code section holds (.text.foo / .literal.unlikely.foo -> foo), or ''""" + parts = name.split(".", 2) + fn = parts[2] if len(parts) == 3 else "" + for sub in ("unlikely.", "hot.", "startup.", "exit."): + if fn.startswith(sub): + return fn[len(sub):] + return fn + + +def rename(objcopy, archive, core, keeps): + keep = [re.compile(k) for k in keeps] + grouped, names = set(), set() + for _, name, _, flags, _ in archive_sections(objcopy, archive): + names.add(name) + if "G" in flags: + grouped.add(name) + renames = {} + for name in names: + if name in grouped: + continue # COMDAT: may be the copy the whole firmware uses + if CODE.match(name): + fn = function_of(name) + if fn and any(k.search(fn) for k in keep): + continue + renames[name] = f".core_ovl.{core}{name}" + elif CTORS.match(name): + # .ctors.NNNNN holds init_priority 65535 - NNNNN (IDF orders them with + # SORT_BY_INIT_PRIORITY, which decodes only the .ctors name): name the + # table by the priority itself, so overlay.ld's SORT by name is priority order + suffix = name[len(".ctors"):] + if re.fullmatch(r"\.\d{5}", suffix): + suffix = f".{65535 - int(suffix[1:]):05d}" + renames[name] = f".core_ovl_ctors_{core}{suffix}" + if not renames: + return + # the options in a response file: a big core has tens of thousands of sections + with tempfile.NamedTemporaryFile("w", suffix=".rsp", delete=False) as rsp: + for old in sorted(renames): + rsp.write(f"--rename-section {old}={renames[old]}\n") + try: + subprocess.run([objcopy, f"@{rsp.name}", archive], check=True) + finally: + os.unlink(rsp.name) + ctors = sum(1 for n in renames.values() if n.startswith(".core_ovl_ctors_")) + print(f"core_overlay: moved {len(renames) - ctors} code sections of {os.path.basename(archive)} into the " + f"{core} overlay ({ctors} constructor tables); {len(grouped & {n for n in names if CODE.match(n)})} " + "COMDAT code sections stay resident") + + +def overlay_size(objcopy, archive): + """the core and the bytes its renamed sections take (each at its alignment)""" + core, total = None, 0 + for _, name, size, _, al in archive_sections(objcopy, archive): + m = re.match(r"^\.core_ovl(?:\.|_ctors_)([a-z0-9]+)", name) + if m and size: + core = m.group(1) + total = align(total, max(al, 1)) + size + return core, total + + +def header_size(): + return align(8 + 8 * len(CORES), 16) + + +def size(objcopy, out, archives): + total = header_size() + parts = [] + for a in archives: + core, n = overlay_size(objcopy, a) + if core: + total += align(n, 16) + parts.append(f"{core} {n // 1024} KB") + text = ("// generated by components/core_overlay/tools/core_overlay.py size: the flash store\n" + f"// for the cores' code overlay ({', '.join(parts)}, before the link drops unused code)\n" + f"#define CORE_OVL_STORE_SIZE {total}u\n") + if not os.path.exists(out) or open(out).read() != text: + open(out, "w").write(text) + print(f"core_overlay: the flash store takes {total // 1024} KB ({', '.join(parts)})") + + +SHT_PROGBITS, SHT_NOBITS = 1, 8 +SHF_WRITE, SHF_ALLOC, SHF_EXECINSTR = 0x1, 0x2, 0x4 + + +def image(objcopy, elf_path, map_path, report): + elf = bytearray(open(elf_path, "rb").read()) + (shoff,) = struct.unpack_from(" (value, size, shndx, bind) + funcs = [] # (value, size, name, bind, shndx) + for off in range(symtab[4], symtab[4] + symtab[5], 16): + st_name, value, sz, info, _, shndx = struct.unpack_from("> 4)) + if info & 0xF == 2 and sz: # STT_FUNC + funcs.append((value, sz, name, info >> 4, shndx)) + funcs.sort() + + def sym(name): + if name not in symbols: + sys.exit(f"core_overlay: {name} is not linked (is components/core_overlay/overlay.ld in the link?)") + return symbols[name] + + ovl_start, ovl_end = sym("_core_ovl_start")[0], sym("_core_ovl_end")[0] + in_ovl = lambda a: ovl_start <= a < ovl_end + store_addr, store_size, store_shndx, _ = sym("core_ovl_store") + store_sec = secs[store_shndx] + store_off = store_sec[4] + store_addr - store_sec[3] + + # 1. the store: header, then each member at 16-byte alignment + member_index = {f".core_ovl.{c}": i for i, c in enumerate(CORES)} + (magic,) = struct.unpack_from(" store_size: + sys.exit(f"core_overlay: the overlay code ({at + s[5]} B so far) does not fit the {store_size} B " + "flash store (src/store.c; the size step under-counted)") + elf[store_off + at: store_off + at + s[5]] = elf[s[4]: s[4] + s[5]] + entries[member_index[name]] = (at, s[5]) + at = align(at + s[5], 16) + hdr = struct.pack(" [(core, name)] + for v, sz, n, b, shndx in ovl_funcs: + ovl_targets.setdefault(v, []).append((member_of_shndx.get(shndx, "?"), n)) + + # the map: input sections (start, size, file, section), and the + # cross-reference table (demangled symbol -> the files that reference it) + inputs, refs = [], {} + lines = open(map_path, errors="replace").read().split("\n") + start = next(i for i, l in enumerate(lines) if l.startswith("Linker script and memory map")) + pending, cref = None, len(lines) + row = re.compile(r"^ (\S+)?\s+0x([0-9a-f]+)\s+0x([0-9a-f]+) (\S.*)$") + for k in range(start, len(lines)): + line = lines[k] + if line.startswith("Cross Reference Table"): + cref = k + break + m = row.match(line) + if m: + sec = m.group(1) or pending + addr, sz = int(m.group(2), 16), int(m.group(3), 16) + if sz and addr and not in_ovl(addr): + inputs.append((addr, sz, m.group(4).strip(), sec or "")) + pending = None + elif line.startswith(" ") and not line.startswith(" ") and len(line.split()) == 1: + pending = line.strip() + else: + pending = None + # a symbol line ends with the file that defines it, unless the (demangled) + # name is too long: then the file is on the next, indented line + current = None + file_at_end = re.compile(r"^(.*\S)\s+(\S+\.(?:a\(\S+\)|obj|o))$") + for line in lines[cref + 3:]: + if not line.strip(): + continue + if line[0] != " ": + m = file_at_end.match(line.rstrip()) + current = m.group(1).strip() if m else line.strip() + refs[current] = [] # (the first file defines it) + elif current is not None: + refs[current].append(line.strip()) + inputs.sort() + input_starts = [x[0] for x in inputs] + + def attribute(addr): + j = bisect.bisect_right(input_starts, addr) - 1 + if j >= 0 and inputs[j][0] <= addr < inputs[j][0] + inputs[j][1]: + return inputs[j][2], inputs[j][3] + return "?", "?" + + def core_of(file): + for c in CORES: + if f"/lib{c}.a(" in file or file.startswith(f"lib{c}.a("): + return c + return None + + demangled = {} + + def demangle(todo): + todo = [n for n in todo if n not in demangled] + if not todo: + return + out = subprocess.run([tool(objcopy, "c++filt")], input="\n".join(todo), capture_output=True, + text=True).stdout.split("\n") + for n, d in zip(todo, out): + demangled[n] = d or n + + local = {n for v, sz, n, b, s in funcs if b == 0} + problems, allowed = [], [] + + def describe(target): + return " / ".join(f"{c}:{n}" for c, n in ovl_targets.get(target, [])[:3]) + + # 2a. boot-time constructors and init functions + for lo, hi in (("__preinit_array_start", "__init_array_end"),): + a, b = sym(lo)[0], sym(hi)[0] + for i, s in enumerate(secs): + if s[1] != SHT_NOBITS and s[3] <= a < s[3] + s[5]: + for (w,) in struct.iter_unpack(" {describe(target)}" + + (f" and {len(targets) - 1} more" if len(targets) > 1 else "")) + if file.endswith(CART_FILES) or LOADER_ARCHIVE in file: + ok = True + elif core is None: + ok = False + elif any(t >= ovl_start + member_size.get(core, 0) for _, t in targets): + # (every core's code starts at the overlay's start, so another core + # may have a function at the same address, and a core's tables may + # point into its functions, computed gotos: only a target past this + # core's code is surely another core's) + ok, what = False, what + "; another core's code" + elif not CODE.match(sec): + ok = True # the core's own data, or its internal-RAM code + else: + fn = function_of(sec) + if not fn: + ok, what = False, what + "; resident code of unknown function" + elif fn in local: + ok = True # only its own object calls it + else: + # (the map's names are mangled; a constructor's / destructor's + # COMDAT group is named C5 / D5 after the C1 C2 / D1 D2 it holds) + variants = [fn] + [re.sub(r"([CD])5E", rf"\g<1>{k}E", fn, count=1) for k in "12"] + users = next((refs[v] for v in variants if v in refs), refs.get(demangled.get(fn, fn))) + ok = users is not None and all(core_of(u) == core for u in users) + if not ok: + others = sorted({u for u in (users or ["?"]) if core_of(u) != core}) + what += f"; used by {', '.join(others[:3])}" + (allowed if ok else problems).append(what) + + if report: + for a in allowed: + print("core_overlay: allowed", a) + if problems: + for p in sorted(set(problems)): + print("core_overlay: ERROR", p) + sys.exit(f"core_overlay: {len(set(problems))} references into the core overlay from resident code or " + "data that may run while another core (or none) is loaded (see the script's docstring)") + print(f"core_overlay: checked: {len(allowed)} resident places reach into the overlay, all the carts', the " + "loader's or the cores' own") + + +def split_map(map_path): + """move the overlay members' output sections (and the overlay's symbol + assignments after them) from the map into .core_overlay.map""" + lines = open(map_path, errors="replace").read().split("\n") + start = next((i for i, l in enumerate(lines) if l.startswith(".core_ovl.")), None) + if start is None: + return # (done already) + end = next((i for i in range(start + 1, len(lines)) + if lines[i] and lines[i][0] not in " \t" and not lines[i].startswith(".core_ovl.")), len(lines)) + root, _ = os.path.splitext(map_path) + open(root + ".core_overlay.map", "w").write("\n".join(lines[start:end]) + "\n") + open(map_path, "w").write("\n".join(lines[:start] + lines[end:])) + print(f"core_overlay: the overlay's {end - start} map lines moved to {os.path.basename(root)}.core_overlay.map") + + +def main(argv): + if len(argv) < 2: + sys.exit(__doc__) + cmd, args = argv[1], argv[2:] + if cmd == "rename": + objcopy, archive, core = args[:3] + if core not in CORES: + sys.exit(f"core_overlay: unknown core {core} (CORES: {', '.join(CORES)})") + rename(objcopy, archive, core, [a.split("=", 1)[1] for a in args[3:] if a.startswith("--keep=")]) + elif cmd == "size": + size(args[0], args[1], args[2:]) + elif cmd == "image": + image(args[0], args[1], args[2], "--report" in args[3:]) + split_map(args[2]) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/components/darkforces/CMakeLists.txt b/components/darkforces/CMakeLists.txt index c019ee89..94f06af7 100644 --- a/components/darkforces/CMakeLists.txt +++ b/components/darkforces/CMakeLists.txt @@ -101,3 +101,11 @@ add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMENT "Redirecting Dark Forces allocations to the ROM block" VERBATIM) target_link_libraries(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=free" "-Wl,--wrap=realloc") + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while a game runs. The allocator stays resident: the firmware-wide free() / +# realloc() wrappers above run all the time, and the std:: template copies the +# rest of the firmware links from this library call its operator new (df_new). +core_overlay_archive(darkforces + "^(__wrap_|df_|espbox_pool_|_ZN10TFE_Memory)" + "^_ZN12_GLOBAL__N_1L[0-9]+(inBlock|liveHeader|poolAllocLocked|poolFreeLocked|noteOverflow|censusVisit|dfAlloc|dfFree|dfRealloc|sessionMagic)E") diff --git a/components/doom/CMakeLists.txt b/components/doom/CMakeLists.txt index f83725f6..633da2bc 100644 --- a/components/doom/CMakeLists.txt +++ b/components/doom/CMakeLists.txt @@ -20,3 +20,7 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -DHAVE_CONFIG_H -O2 ) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(doom) diff --git a/components/gbc/CMakeLists.txt b/components/gbc/CMakeLists.txt index 9b604016..0c16d961 100644 --- a/components/gbc/CMakeLists.txt +++ b/components/gbc/CMakeLists.txt @@ -10,3 +10,7 @@ idf_component_register( target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-misleading-indentation -Wno-implicit-fallthrough -Wno-unused-function -Wno-unused-variable $<$:-Wno-discarded-qualifiers>) target_compile_definitions(${COMPONENT_LIB} PRIVATE GNUBOY_NO_MINIZIP GNUBOY_NO_SCREENSHOT IS_LITTLE_ENDIAN) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(gbc) diff --git a/components/genesis/CMakeLists.txt b/components/genesis/CMakeLists.txt index 441c1692..30f09648 100644 --- a/components/genesis/CMakeLists.txt +++ b/components/genesis/CMakeLists.txt @@ -28,3 +28,7 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-unused-const-variable -Wno- # M68K_OVERCLOCK_SHIFT: the 68000 clock setting (genesis_set_cpu_percent()); # M68K_IDLE_SKIP: skip the 68000's wait-for-frame loops (see m68k_run()) target_compile_definitions(${COMPONENT_LIB} PRIVATE GWENESIS_AUDIO_ACCURATE=0 M68K_OVERCLOCK_SHIFT=8 M68K_IDLE_SKIP) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(genesis) diff --git a/components/msx/CMakeLists.txt b/components/msx/CMakeLists.txt index 0db4cf48..afcbda72 100644 --- a/components/msx/CMakeLists.txt +++ b/components/msx/CMakeLists.txt @@ -22,3 +22,17 @@ target_compile_options(${COMPONENT_LIB} PRIVATE ) file(GLOB_RECURSE c_sources "${CMAKE_CURRENT_SOURCE_DIR}/${FM}/src/*.c") set_source_files_properties(${c_sources} PROPERTIES COMPILE_FLAGS "-include msxfix.h") + +# The globals another core in this firmware defines too, renamed in this +# library (its glue included). PatchZ80: the Genesis core's Z80 has a stub of +# that name, and the linker resolved fMSX's call (the ED FE disk BIOS patch +# trap) to it, so fMSX's own (fMSX/Patch.c) was never linked. +add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD + COMMAND ${CMAKE_OBJCOPY} --redefine-syms=${CMAKE_CURRENT_LIST_DIR}/symbol_renames.syms $ + COMMENT "Renaming the globals another core also defines" + VERBATIM) +core_overlay_rebuild_on(${CMAKE_CURRENT_LIST_DIR}/symbol_renames.syms) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(msx) diff --git a/components/msx/symbol_renames.syms b/components/msx/symbol_renames.syms new file mode 100644 index 00000000..674af47e --- /dev/null +++ b/components/msx/symbol_renames.syms @@ -0,0 +1 @@ +PatchZ80 fmsx_PatchZ80 diff --git a/components/nes/CMakeLists.txt b/components/nes/CMakeLists.txt index a9fdd24e..9d0d747c 100644 --- a/components/nes/CMakeLists.txt +++ b/components/nes/CMakeLists.txt @@ -8,3 +8,7 @@ idf_component_register( REQUIRES "box-emu" "statistics" "shared_memory" ) target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-char-subscripts -Wno-attributes -Wno-implicit-fallthrough -Wno-unused-function -Wno-unused-variable $<$:-std=gnu17> $<$:-Wno-discarded-qualifiers>) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(nes) diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index e0976cce..044ca79f 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -29,3 +29,7 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -O2 -Wno-error -w) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(pico8) diff --git a/components/sms/CMakeLists.txt b/components/sms/CMakeLists.txt index 5e59a074..12efe683 100644 --- a/components/sms/CMakeLists.txt +++ b/components/sms/CMakeLists.txt @@ -10,3 +10,7 @@ idf_component_register( # target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-char-subscripts -Wno-attributes -Wno-implicit-fallthrough -Wno-unused-function -Wno-unused-variable -Wno-discarded-qualifiers) target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-unused-const-variable $<$:-std=gnu17> $<$:-Wno-discarded-qualifiers> $<$:-Wno-error=address-of-packed-member>) target_compile_definitions(${COMPONENT_LIB} PRIVATE LSB_FIRST=1) + +# Its code goes into the code overlay (components/core_overlay): in PSRAM only +# while one of its games runs +core_overlay_archive(sms) diff --git a/main/carts.hpp b/main/carts.hpp index c2dec9bf..31bb42f0 100644 --- a/main/carts.hpp +++ b/main/carts.hpp @@ -2,6 +2,7 @@ #include +#include "core_overlay.h" #include "display.hpp" #include "darkforces_cart.hpp" @@ -13,7 +14,39 @@ #include "pico8_cart.hpp" #include "sms_cart.hpp" +// The code overlay member (components/core_overlay) of a platform's core. +inline const char *overlay_core(Emulator platform) { + switch (platform) { + case Emulator::GAMEBOY: + case Emulator::GAMEBOY_COLOR: + return "gbc"; + case Emulator::NES: + return "nes"; + case Emulator::SEGA_MASTER_SYSTEM: + case Emulator::SEGA_GAME_GEAR: + return "sms"; + case Emulator::SEGA_GENESIS: + case Emulator::SEGA_MEGA_DRIVE: + return "genesis"; + case Emulator::MSX: + return "msx"; + case Emulator::DOOM: + return "doom"; + case Emulator::DARK_FORCES: + return "darkforces"; + case Emulator::PICO8: + return "pico8"; + default: + return nullptr; + } +} + std::unique_ptr make_cart(const RomInfo& info, std::shared_ptr> display) { + // the core's code first (only one core's code is in PSRAM at a time; the + // caller unloads it when the cart is gone) + if (const char *core = overlay_core(info.platform); !core || !core_overlay_load(core)) { + return nullptr; + } switch (info.platform) { case Emulator::GAMEBOY: case Emulator::GAMEBOY_COLOR: diff --git a/main/main.cpp b/main/main.cpp index e47d8e7d..e3eaeda5 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -220,6 +220,8 @@ extern "C" void app_main(void) { logger.error("Failed to create cart!"); } } + // the core's code out of PSRAM (components/core_overlay), with its cart gone + core_overlay_unload(); // Only the task lines matter here (stack high-water marks after a full // play session); the block threshold is set so no block line prints. // The census goes last so its `[mem] delta phase=quit` line marks the