diff --git a/CMakeLists.txt b/CMakeLists.txt index 27efb1b..de5d2ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -123,6 +123,40 @@ project(tab5-emu) set(CMAKE_CXX_STANDARD 23) +# Executing from flash, .ext_ram.data (components/tab5-emu/ext_ram_data.ld) +# is PSRAM, which the image cannot hold: after linking, its bytes go into the +# flash array tab5_ext_ram_data_image and the section becomes NOBITS, before +# the .bin is made from the ELF +if(NOT CONFIG_SPIRAM_XIP_FROM_PSRAM) + idf_build_get_property(python PYTHON) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME}.elf POST_BUILD + COMMAND ${python} ${CMAKE_CURRENT_LIST_DIR}/tools/ext_ram_data_image.py $ + # likewise the game cores' code overlay (components/tab5-emu/overlay.ld), + # and check that only the carts reach into it + COMMAND ${python} ${CMAKE_CURRENT_LIST_DIR}/tools/overlay_image.py $ + ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.map + COMMENT "Storing .ext_ram.data and the core code overlay in flash" + VERBATIM) +endif() + +# Executing from flash, LVGL and the GUI (they draw in software: from flash +# the launcher redraws visibly) run from PSRAM instead: their code and +# read-only data go to .tab5_res (tools/bss_to_psram.py --psram-code, +# components/tab5-emu/overlay.ld), filled from flash at boot. Done on the +# archives just before the link (a POST_BUILD step can only be added in the +# component's own directory, and LVGL is a managed component); renaming an +# archive whose sections are renamed already does nothing. +if(NOT CONFIG_SPIRAM_XIP_FROM_PSRAM) + foreach(component lvgl__lvgl emu-ui gui menu) + idf_component_get_property(lib ${component} COMPONENT_LIB) + add_custom_command(TARGET ${CMAKE_PROJECT_NAME}.elf PRE_LINK + COMMAND ${python} ${CMAKE_CURRENT_LIST_DIR}/tools/bss_to_psram.py + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --no-bss --psram-code + COMMENT "Moving ${component}'s code to PSRAM" + VERBATIM) + endforeach() +endif() + # 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/components/darkforces/CMakeLists.txt b/components/darkforces/CMakeLists.txt index ae56e68..bbe1999 100644 --- a/components/darkforces/CMakeLists.txt +++ b/components/darkforces/CMakeLists.txt @@ -104,8 +104,15 @@ target_link_libraries(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=free" "-Wl,--wrap=r # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(darkforces overlay_args "^(__wrap_|df_|espbox_pool_|_ZN10TFE_Memory)" "^_ZN12_GLOBAL__N_1L[0-9]+(inBlock|liveHeader|poolAllocLocked|poolFreeLocked|noteOverflow|censusVisit|dfAlloc|dfFree|dfRealloc)E") add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the darkforces core's .bss and .data to PSRAM" VERBATIM) diff --git a/components/doom/CMakeLists.txt b/components/doom/CMakeLists.txt index 75d3fe3..964f23f 100644 --- a/components/doom/CMakeLists.txt +++ b/components/doom/CMakeLists.txt @@ -24,8 +24,15 @@ target_compile_options(${COMPONENT_LIB} PRIVATE # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(doom overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the doom core's .bss and .data to PSRAM" VERBATIM) diff --git a/components/gba/CMakeLists.txt b/components/gba/CMakeLists.txt index f4c93f2..703db68 100644 --- a/components/gba/CMakeLists.txt +++ b/components/gba/CMakeLists.txt @@ -29,9 +29,13 @@ target_compile_definitions(${COMPONENT_LIB} PRIVATE __LIBRETRO__ ROM_BUFFER_SIZE target_compile_options(${COMPONENT_LIB} PRIVATE -O3 -fno-strict-aliasing -fjump-tables -ftree-switch-conversion -msmall-data-limit=0 -include ${CMAKE_CURRENT_LIST_DIR}/gpsp/retro_inline.h -Wno-error -w -Wno-error=incompatible-pointer-types -Wno-error=int-conversion -Wno-error=implicit-function-declaration -Wno-error=discarded-qualifiers) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(gba overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} --keep reg,reg_mode,spsr,cpu_ticks,io_registers,oam_ram,palette_ram,palette_ram_converted,oam_update_count COMMENT "Moving the GBA core's .bss to PSRAM" VERBATIM) diff --git a/components/gbc/CMakeLists.txt b/components/gbc/CMakeLists.txt index 6bb8737..42e5787 100644 --- a/components/gbc/CMakeLists.txt +++ b/components/gbc/CMakeLists.txt @@ -13,9 +13,16 @@ target_compile_definitions(${COMPONENT_LIB} PRIVATE GNUBOY_NO_MINIZIP GNUBOY_NO_ # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(gbc overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the gbc core's .bss and .data to PSRAM" VERBATIM) # globals other cores in this firmware define too (the box doesn't build diff --git a/components/genesis/CMakeLists.txt b/components/genesis/CMakeLists.txt index 9e25c64..30f1dd5 100644 --- a/components/genesis/CMakeLists.txt +++ b/components/genesis/CMakeLists.txt @@ -34,8 +34,12 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-unused-const-variable -Wno- -Wno-error=array-bounds -Wno-error=maybe-uninitialized -Wno-error=address -Wno-error=misleading-indentation) # target_compile_definitions(${COMPONENT_LIB} PRIVATE GWENESIS_AUDIO_ACCURATE=0 BUILD_TABLES=0 TABLES_FULL=0) target_compile_definitions(${COMPONENT_LIB} PRIVATE GWENESIS_AUDIO_ACCURATE=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(genesis overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} COMMENT "Moving the Genesis core's .bss to PSRAM" VERBATIM) diff --git a/components/gui/CMakeLists.txt b/components/gui/CMakeLists.txt index 9b8e4f7..70df3f4 100644 --- a/components/gui/CMakeLists.txt +++ b/components/gui/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register( INCLUDE_DIRS "include" SRC_DIRS "src" - REQUIRES lvgl emu-ui timer logger rom_info settings tab5-emu app_update esp_app_format) + REQUIRES lvgl emu-ui timer logger rom_info settings tab5-emu app_update esp_app_format esp_driver_jpeg) diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp index 1c39361..533b99f 100644 --- a/components/gui/include/gui.hpp +++ b/components/gui/include/gui.hpp @@ -106,8 +106,11 @@ class Gui { void on_volume(const std::vector &data); void on_battery(const std::vector &data); - /// Decode a JPEG on the SD card into a new RGB565 draw buffer (nullptr if it cannot) - lv_draw_buf_t *decode_image(const std::string &path); + /// Decode a JPEG on the SD card into a new RGB565 draw buffer (nullptr if + /// it cannot), scaled to fit a box x box square (box > 0) + lv_draw_buf_t *decode_image(const std::string &path, int box = 0); + lv_draw_buf_t *decode_jpeg_hw(const std::string &path, int box); + static lv_draw_buf_t *fit_image(const uint8_t *src, int w, int h, int stride, int box); const void *cover(size_t index); const void *console_art(const std::string &key); diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp index a3d4caf..1d61551 100644 --- a/components/gui/src/gui.cpp +++ b/components/gui/src/gui.cpp @@ -4,9 +4,15 @@ #include #include +#include +#include +#include #include #include +#include + +#include "driver/jpeg_decode.h" #include "lvgl_private.h" // (lv_image_decoder_dsc_t) @@ -353,6 +359,11 @@ Gui::Snapshot Gui::snapshot() { return shot; } +// emu-ui's launcher shows the cover in a 360 px square (LV_IMAGE_ALIGN_CONTAIN). +// Scaled to fit it once, here, LVGL draws the cover as it is rather than +// scaling it in software on every redraw. +constexpr int kCoverBox = 360; + // The selected game's boxart, decoded once per selection (the launcher has // already let go of the previous one). const void *Gui::cover(size_t index) { @@ -361,7 +372,7 @@ const void *Gui::cover(size_t index) { boxart_buf_ = nullptr; } if (index < rom_infos_.size() && !rom_infos_[index].boxart_path.empty()) { - boxart_buf_ = decode_image(rom_infos_[index].boxart_path); + boxart_buf_ = decode_image(rom_infos_[index].boxart_path, kCoverBox); } return boxart_buf_; } @@ -378,11 +389,205 @@ const void *Gui::console_art(const std::string &key) { return buf; } -// LVGL's JPEG decoder (TJPGD) only yields the image block by block, and LVGL -// cannot scale a block-decoded image, so decode it into a full RGB565 buffer -// here and show that. The POSIX fs driver is registered as 'S:' and passes -// the rest of the path through unchanged. -lv_draw_buf_t *Gui::decode_image(const std::string &path) { +namespace { + +// The P4's JPEG decoder (made on first use; nullptr if it cannot be) +jpeg_decoder_handle_t jpeg_engine() { + static jpeg_decoder_handle_t engine = nullptr; + static bool tried = false; + if (!tried) { + tried = true; + jpeg_decode_engine_cfg_t cfg{}; + cfg.timeout_ms = 500; + if (jpeg_new_decoder_engine(&cfg, &engine) != ESP_OK) engine = nullptr; + } + return engine; +} + +// The frame header of a baseline JPEG in memory: the offset of its height +// (then width) field and its MCU size; -1 if there is none (progressive...) +int find_frame_header(const uint8_t *d, size_t n, int &mcu_w, int &mcu_h) { + size_t i = 2; // (after SOI) + while (i + 4 <= n) { + if (d[i] != 0xFF) return -1; + const uint8_t m = d[i + 1]; + if (m == 0xFF) { // fill byte + i++; + continue; + } + if (m == 0x01 || (m >= 0xD0 && m <= 0xD7)) { + i += 2; + continue; + } + const size_t len = (d[i + 2] << 8) | d[i + 3]; + if (m == 0xC0 || m == 0xC1) { + // P Y(2) X(2) Nf, then per component: id, Hi:Vi, Tq; the decoder's MCU + // is the first component's sampling factors x 8 + if (len < 11 || i + 2 + len > n) return -1; + const int h = d[i + 11] >> 4, v = d[i + 11] & 0x0f; + if (!h || !v) return -1; + mcu_w = 8 * h; + mcu_h = 8 * v; + return static_cast(i + 5); + } + if (m == 0xDA || m == 0xD9 || (m >= 0xC2 && m <= 0xCF && m != 0xC4 && m != 0xC8 && m != 0xCC)) { + return -1; // a scan first, or not baseline + } + i += 2 + len; + } + return -1; +} + +struct FreeDeleter { + void operator()(void *p) const { free(p); } +}; + +} // namespace + +// A new RGB565 draw buffer of `src` (rows `stride` bytes apart), scaled +// (bilinear) to fit a box x box square with its longer side box long, or as +// it is (box 0) +lv_draw_buf_t *Gui::fit_image(const uint8_t *src, int w, int h, int stride, int box) { + int dw = w, dh = h; + if (box > 0) { + if (w >= h) { + dw = box; + dh = std::max(1, (h * box + w / 2) / w); + } else { + dh = box; + dw = std::max(1, (w * box + h / 2) / h); + } + } + auto *out = lv_draw_buf_create(dw, dh, LV_COLOR_FORMAT_RGB565, LV_STRIDE_AUTO); + if (!out) return nullptr; + if (dw == w && dh == h) { + for (int y = 0; y < h; y++) memcpy(out->data + y * out->header.stride, src + y * stride, w * 2); + return out; + } + // Separable bilinear: each source row is interpolated across once (into a + // two-row cache in internal RAM), then output rows blend two of those. The + // pixels spread as 0x07E0F81F (green, red, blue, with room above each) so + // one multiply weighs all three, with 5 bit weights. + const int32_t step_x = (w << 16) / dw, step_y = (h << 16) / dh; + auto src_pos = [](int i, int32_t step, int n) { + return std::clamp(i * step + step / 2 - 0x8000, 0, (n - 1) << 16); + }; + constexpr uint32_t kMask = 0x07E0F81Fu; + auto spread = [](uint32_t c) { return (c | (c << 16)) & kMask; }; + // per output column: the two source columns and the weight of the second + const size_t bytes = static_cast(dw) * (2 * sizeof(uint32_t) + 2 * sizeof(uint16_t) + 1); + std::unique_ptr scratch( + static_cast(heap_caps_malloc(bytes, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT))); + if (!scratch) scratch.reset(static_cast(malloc(bytes))); + if (!scratch) { + lv_draw_buf_destroy(out); + return nullptr; + } + auto *row_a = reinterpret_cast(scratch.get()); + auto *row_b = row_a + dw; + auto *xa = reinterpret_cast(row_b + dw); + auto *xb = xa + dw; + auto *wx = reinterpret_cast(xb + dw); + for (int x = 0; x < dw; x++) { + const int32_t sx = src_pos(x, step_x, w); + xa[x] = sx >> 16; + xb[x] = std::min(xa[x] + 1, w - 1); + wx[x] = (sx >> 11) & 31; + } + auto across = [&](int sy, uint32_t *dst) { + const auto *r = reinterpret_cast(src + sy * stride); + for (int x = 0; x < dw; x++) { + const uint32_t f = wx[x]; + dst[x] = ((spread(r[xa[x]]) * (32 - f) + spread(r[xb[x]]) * f) >> 5) & kMask; + } + }; + int have_a = -1, have_b = -1; // the source rows in row_a / row_b + for (int y = 0; y < dh; y++) { + const int32_t sy = src_pos(y, step_y, h); + const int y0 = sy >> 16, y1 = std::min(y0 + 1, h - 1); + if (have_a != y0) { + if (have_b == y0) { + std::swap(row_a, row_b); + std::swap(have_a, have_b); + } else { + across(y0, row_a); + have_a = y0; + } + } + if (have_b != y1) { + across(y1, row_b); + have_b = y1; + } + const uint32_t f = (sy >> 11) & 31; + auto *row = reinterpret_cast(out->data + y * out->header.stride); + for (int x = 0; x < dw; x++) { + const uint32_t c = ((row_a[x] * (32 - f) + row_b[x] * f) >> 5) & kMask; + row[x] = static_cast(c | (c >> 16)); + } + } + return out; +} + +// A baseline JPEG through the P4's JPEG decoder, straight to RGB565: a cover +// decoded and scaled takes ~30 ms, where LVGL's software decoder took ~75 ms +// for the decode alone. nullptr if it cannot (decode_image() then falls back +// to LVGL's). +lv_draw_buf_t *Gui::decode_jpeg_hw(const std::string &path, int box) { + auto *engine = jpeg_engine(); + if (!engine) return nullptr; + FILE *f = fopen(path.c_str(), "rb"); + if (!f) return nullptr; + fseek(f, 0, SEEK_END); + const long size = ftell(f); + fseek(f, 0, SEEK_SET); + if (size < 4) { + fclose(f); + return nullptr; + } + jpeg_decode_memory_alloc_cfg_t in_cfg{.buffer_direction = JPEG_DEC_ALLOC_INPUT_BUFFER}; + size_t in_capacity = 0; + std::unique_ptr in(static_cast(jpeg_alloc_decoder_mem(size, &in_cfg, &in_capacity))); + const bool read = in && fread(in.get(), 1, size, f) == static_cast(size); + fclose(f); + if (!read) return nullptr; + // The decoder refuses a picture whose width x height is not a multiple of + // 8 (two in five of the covers here), though it decodes whole MCUs anyway: + // give the frame header the MCU-rounded size (the same MCUs, so the same + // scan) and crop the result back. + int mcu_w = 8, mcu_h = 8; + const int sof = find_frame_header(in.get(), size, mcu_w, mcu_h); + if (sof < 0) return nullptr; + uint8_t *dims = in.get() + sof; + const int h = (dims[0] << 8) | dims[1], w = (dims[2] << 8) | dims[3]; + if (!w || !h) return nullptr; + const int pw = (w + mcu_w - 1) / mcu_w * mcu_w, ph = (h + mcu_h - 1) / mcu_h * mcu_h; + dims[0] = ph >> 8; + dims[1] = ph & 0xff; + dims[2] = pw >> 8; + dims[3] = pw & 0xff; + jpeg_decode_memory_alloc_cfg_t out_cfg{.buffer_direction = JPEG_DEC_ALLOC_OUTPUT_BUFFER}; + size_t out_capacity = 0; + std::unique_ptr out( + static_cast(jpeg_alloc_decoder_mem(static_cast(pw) * ph * 2, &out_cfg, &out_capacity))); + if (!out) return nullptr; + jpeg_decode_cfg_t cfg{}; + cfg.output_format = JPEG_DECODE_OUT_FORMAT_RGB565; + cfg.rgb_order = JPEG_DEC_RGB_ELEMENT_ORDER_BGR; // (little-endian RGB565, as LVGL's) + cfg.conv_std = JPEG_YUV_RGB_CONV_STD_BT601; + uint32_t out_size = 0; + if (jpeg_decoder_process(engine, &cfg, in.get(), size, out.get(), out_capacity, &out_size) != ESP_OK || + out_size != static_cast(pw) * ph * 2) { + return nullptr; + } + return fit_image(out.get(), w, h, pw * 2, box); +} + +// The P4's decoder first; else LVGL's JPEG decoder (TJPGD), which only yields +// the image block by block (and LVGL cannot scale a block-decoded image), so +// it is decoded into a full RGB565 buffer here. The POSIX fs driver is +// registered as 'S:' and passes the rest of the path through unchanged. +lv_draw_buf_t *Gui::decode_image(const std::string &path, int box) { + if (auto *hw = decode_jpeg_hw(path, box)) return hw; const std::string src = "S:" + path; lv_image_decoder_dsc_t dsc{}; if (lv_image_decoder_open(&dsc, src.c_str(), nullptr) != LV_RESULT_OK) { @@ -421,6 +626,11 @@ lv_draw_buf_t *Gui::decode_image(const std::string &path) { } } lv_image_decoder_close(&dsc); - logger_.info("image '{}': {}x{}", path, w, h); + logger_.info("image '{}': {}x{} (software decoder)", path, w, h); + if (box > 0) { + auto *fitted = fit_image(out->data, w, h, out->header.stride, box); + lv_draw_buf_destroy(out); + out = fitted; + } return out; } diff --git a/components/jk/CMakeLists.txt b/components/jk/CMakeLists.txt index bb36b6c..ef48b4d 100644 --- a/components/jk/CMakeLists.txt +++ b/components/jk/CMakeLists.txt @@ -129,9 +129,13 @@ endif() if(CONFIG_JK_ENGINE) # The engine has ~1.4 MB of static state; move it out of internal SRAM into # PSRAM by renaming the archive's .bss sections (see ../../tools/bss_to_psram.py). + # executing from flash, the core's code is part of the PSRAM code overlay + # (components/tab5-emu/overlay.ld) + include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) + tab5_overlay_args(jk overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} COMMENT "Moving the engine's .bss to PSRAM" VERBATIM) endif() diff --git a/components/mgs/CMakeLists.txt b/components/mgs/CMakeLists.txt index 3734882..072c4db 100644 --- a/components/mgs/CMakeLists.txt +++ b/components/mgs/CMakeLists.txt @@ -123,6 +123,24 @@ if(CONFIG_MGS_ENGINE) set_property(SOURCE ${SRC_PSYQ} APPEND PROPERTY COMPILE_OPTIONS "-include;${PSYZ}/include/common.h;-include;stdio.h") + # Executing from flash, the game's .data (and its SECTION(".mgs.sdata") / + # (".mgs.data") small data) cannot stay in .flash.rodata (read-only there): + # it goes to .ext_ram.data, tagged so components/tab5-emu/ext_ram_data.ld + # can bracket it with _mgs_data_* / _mgs_sdata_* (the .bss stays ldgen's) + if(NOT CONFIG_SPIRAM_XIP_FROM_PSRAM) + # executing from flash, the core's code is part of the PSRAM code overlay + # (components/tab5-emu/overlay.ld) + include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) + tab5_overlay_args(mgs overlay_args "^_ZN3mgs13release_arenaEv" "^Mgs_ArenaRelease$") + add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD + COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + --no-bss --data --data-into=ext_ram:mgs_data + --also-data=.mgs.data:mgs_sdata --also-data=.mgs.sdata:mgs_sdata + COMMENT "Moving the MGS game's .data to .ext_ram.data (PSRAM)" + VERBATIM) + endif() + # Where the game's statics go (PSRAM for .bss, the PSRAM-XIP .rodata for # .data) and the symbols that bracket them are linker.lf's business; # -msmall-data-limit=0 above because nothing in PSRAM may be addressed diff --git a/components/mgs/linker.lf b/components/mgs/linker.lf index a0cbeb7..6cf1cc1 100644 --- a/components/mgs/linker.lf +++ b/components/mgs/linker.lf @@ -23,25 +23,38 @@ entries: .mgs.sdata+ .mgs.data+ +# +# Executing from flash (no CONFIG_SPIRAM_XIP_FROM_PSRAM) .flash.rodata is +# flash, read-only: the .data is renamed into .ext_ram.data instead +# (CMakeLists.txt, tools/bss_to_psram.py), and components/tab5-emu/ +# ext_ram_data.ld places it in PSRAM and defines _mgs_data_* / _mgs_sdata_*. [scheme:mgs_statics] entries: bss -> extern_ram common -> extern_ram extram_bss -> extern_ram mgs_sbss -> extern_ram - data -> flash_rodata - mgs_sdata -> flash_rodata + if SPIRAM_XIP_FROM_PSRAM = y: + data -> flash_rodata + mgs_sdata -> flash_rodata [mapping:mgs] archive: libmgs.a entries: - * (mgs_statics); - bss -> extern_ram SURROUND(mgs_bss), - common -> extern_ram SURROUND(mgs_common), - extram_bss -> extern_ram SURROUND(mgs_xbss), - mgs_sbss -> extern_ram SURROUND(mgs_sbss), - data -> flash_rodata SURROUND(mgs_data), - mgs_sdata -> flash_rodata SURROUND(mgs_sdata) + if SPIRAM_XIP_FROM_PSRAM = y: + * (mgs_statics); + bss -> extern_ram SURROUND(mgs_bss), + common -> extern_ram SURROUND(mgs_common), + extram_bss -> extern_ram SURROUND(mgs_xbss), + mgs_sbss -> extern_ram SURROUND(mgs_sbss), + data -> flash_rodata SURROUND(mgs_data), + mgs_sdata -> flash_rodata SURROUND(mgs_sdata) + else: + * (mgs_statics); + bss -> extern_ram SURROUND(mgs_bss), + common -> extern_ram SURROUND(mgs_common), + extram_bss -> extern_ram SURROUND(mgs_xbss), + mgs_sbss -> extern_ram SURROUND(mgs_sbss) # the cart-side glue owns the reset itself (the .data snapshot, the # lifecycle state) and must survive it: default placement mgs (default) diff --git a/components/msx/CMakeLists.txt b/components/msx/CMakeLists.txt index 530e974..ad5a511 100644 --- a/components/msx/CMakeLists.txt +++ b/components/msx/CMakeLists.txt @@ -25,9 +25,16 @@ set_source_files_properties(${c_sources} PROPERTIES COMPILE_FLAGS "-include msxf # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(msx overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the msx core's .bss and .data to PSRAM" VERBATIM) # globals other cores in this firmware define too (the box doesn't build diff --git a/components/nes/CMakeLists.txt b/components/nes/CMakeLists.txt index 0bfaa8e..897bd4e 100644 --- a/components/nes/CMakeLists.txt +++ b/components/nes/CMakeLists.txt @@ -12,8 +12,15 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-char-subscripts -Wno-attrib # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(nes overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the nes core's .bss and .data to PSRAM" VERBATIM) diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index e47e046..c2e773e 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -31,3 +31,15 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0 -Wno-error -w) + +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld); its statics are placed by linker.lf +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(pico8 overlay_args) +if(overlay_args) + add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD + COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --no-bss ${overlay_args} + COMMENT "Moving the PICO-8 core's code into the PSRAM code overlay" + VERBATIM) +endif() diff --git a/components/scummvm/CMakeLists.txt b/components/scummvm/CMakeLists.txt index 327a13d..c7b77f1 100644 --- a/components/scummvm/CMakeLists.txt +++ b/components/scummvm/CMakeLists.txt @@ -22,9 +22,16 @@ target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0 ) # static state in PSRAM like the other cores (see tools/bss_to_psram.py) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(scummvm overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving ScummVM's .bss and .data to PSRAM" VERBATIM) # ScummVM's allocations: PSRAM, and a game's own arena (backends/platform/esp32/esp32-alloc.cpp) diff --git a/components/sms/CMakeLists.txt b/components/sms/CMakeLists.txt index 9dd1c2b..0eac225 100644 --- a/components/sms/CMakeLists.txt +++ b/components/sms/CMakeLists.txt @@ -14,8 +14,15 @@ target_compile_definitions(${COMPONENT_LIB} PRIVATE LSB_FIRST=1) # linker script has no ldgen placeholder for external RAM); no gp-relative # small data then target_compile_options(${COMPONENT_LIB} PRIVATE -msmall-data-limit=0) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(sms overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ --data + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} + # .data to PSRAM: via .rodata where XIP copies it into PSRAM (writable), + # else into .ext_ram.data (filled at boot from flash; see the script) + --data --data-into=$,rodata,ext_ram> COMMENT "Moving the sms core's .bss and .data to PSRAM" VERBATIM) diff --git a/components/snes/CMakeLists.txt b/components/snes/CMakeLists.txt index 42af551..d5e8b6b 100644 --- a/components/snes/CMakeLists.txt +++ b/components/snes/CMakeLists.txt @@ -15,9 +15,13 @@ target_compile_definitions(${COMPONENT_LIB} PRIVATE USE_BLARGG_APU LOAD_FROM_MEM # PSRAM section after the archive is built); no gp-relative small data then target_compile_options(${COMPONENT_LIB} PRIVATE -O2 -fno-strict-aliasing -fjump-tables -ftree-switch-conversion -msmall-data-limit=0 -Wno-error -w -Wno-error=incompatible-pointer-types -Wno-error=int-conversion -Wno-error=implicit-function-declaration -Wno-error=discarded-qualifiers) +# executing from flash, the core's code is part of the PSRAM code overlay +# (components/tab5-emu/overlay.ld) +include(${CMAKE_CURRENT_LIST_DIR}/../../tools/overlay.cmake) +tab5_overlay_args(snes overlay_args) add_custom_command(TARGET ${COMPONENT_LIB} POST_BUILD COMMAND ${PYTHON} ${CMAKE_CURRENT_LIST_DIR}/../../tools/bss_to_psram.py - ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ + ${CMAKE_OBJDUMP} ${CMAKE_OBJCOPY} $ ${overlay_args} --keep CPU,ICPU,PPU,IPPU,Settings COMMENT "Moving the SNES core's .bss to PSRAM (CPU / PPU state stays internal)" VERBATIM) diff --git a/components/tab5-emu/CMakeLists.txt b/components/tab5-emu/CMakeLists.txt index e398d50..51b9137 100644 --- a/components/tab5-emu/CMakeLists.txt +++ b/components/tab5-emu/CMakeLists.txt @@ -35,3 +35,14 @@ idf_component_register( # LVGL's custom allocator lives in src/lv_mem_core_psram.c; liblvgl is linked # after this library, so pull the object in explicitly target_link_libraries(${COMPONENT_LIB} INTERFACE "-u lv_mem_init") + +# Executing from flash (no XIP from PSRAM), the cores' initialised data lives in +# the PSRAM section .ext_ram.data: place it (ext_ram_data.ld) and pull in the +# constructor that fills it at boot (src/ext_ram_data.c); the root +# CMakeLists.txt stores its contents in flash after linking +if(NOT CONFIG_SPIRAM_XIP_FROM_PSRAM) + target_linker_script(${COMPONENT_LIB} INTERFACE "${CMAKE_CURRENT_LIST_DIR}/ext_ram_data.ld") + # and the game cores' code overlay (overlay.ld, src/overlay.c), after it + target_linker_script(${COMPONENT_LIB} INTERFACE "${CMAKE_CURRENT_LIST_DIR}/overlay.ld") + target_link_libraries(${COMPONENT_LIB} INTERFACE "-u tab5_ext_ram_data_init") +endif() diff --git a/components/tab5-emu/ext_ram_data.ld b/components/tab5-emu/ext_ram_data.ld new file mode 100644 index 0000000..2e7ba0b --- /dev/null +++ b/components/tab5-emu/ext_ram_data.ld @@ -0,0 +1,45 @@ +/* Initialised data in PSRAM, for builds that execute from flash (no + * CONFIG_SPIRAM_XIP_FROM_PSRAM). The cores' .data is renamed .ext_ram.data* + * (tools/bss_to_psram.py --data-into=ext_ram) so internal RAM does not hold + * it; with XIP from PSRAM it goes into the (then writable) .rodata instead. + * + * The linker resolves every reference to these PSRAM addresses. The section + * cannot be loaded by the bootloader (the image has no PSRAM segments), so + * tools/ext_ram_data_image.py copies the linked, relocated bytes into + * tab5_ext_ram_data_image (.rodata, flash) and marks this section NOBITS; + * src/ext_ram_data.c copies them in before any constructor runs. + * + * It follows the other PSRAM sections in ext_ram_seg (.ext_ram.bss, then + * .ext_ram_noinit). IDF keeps [bss start, noinit end) out of the PSRAM heap + * (esp_psram.c, CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY), so the end of + * the noinit range is moved past this section below (a later assignment in a + * linker script wins). Only [bss start, bss end) is zeroed at boot; the memory + * test skips the noinit range. (INSERT AFTER .ext_ram.bss would be neater, but + * IDF links with --enable-non-contiguous-regions, which INSERT does not + * support.) */ +SECTIONS +{ + .ext_ram.data : ALIGN(16) + { + _ext_ram_data_start = ABSOLUTE(.); + /* Metal Gear Solid resets its statics between launches from a snapshot + * (components/mgs/src/mgs.cpp) and saves them in save states; its glue + * (mgs.cpp, mgs_platform.cpp: the config, the SD root) is outside the + * brackets. Inside a section list EXCLUDE_FILE covers only the pattern + * right after it, hence twice. */ + _mgs_data_start = ABSOLUTE(.); + *libmgs.a:(EXCLUDE_FILE(*libmgs.a:mgs.* *libmgs.a:mgs_platform.*) .ext_ram.data.mgs_data + EXCLUDE_FILE(*libmgs.a:mgs.* *libmgs.a:mgs_platform.*) .ext_ram.data.mgs_data.*) + _mgs_data_end = ABSOLUTE(.); + _mgs_sdata_start = ABSOLUTE(.); + *libmgs.a:(EXCLUDE_FILE(*libmgs.a:mgs.* *libmgs.a:mgs_platform.*) .ext_ram.data.mgs_sdata + EXCLUDE_FILE(*libmgs.a:mgs.* *libmgs.a:mgs_platform.*) .ext_ram.data.mgs_sdata.*) + _mgs_sdata_end = ABSOLUTE(.); + *(.ext_ram.data .ext_ram.data.*) + . = ALIGN(16); + _ext_ram_data_end = ABSOLUTE(.); + } > ext_ram_seg +} +/* (the heap starts after the reserved range: see above) */ +_ext_ram_noinit_end = _ext_ram_data_end; +ASSERT(_ext_ram_data_start >= _ext_ram_bss_end, ".ext_ram.data must follow .ext_ram.bss in PSRAM") diff --git a/components/tab5-emu/include/overlay.h b/components/tab5-emu/include/overlay.h new file mode 100644 index 0000000..3e5fc7b --- /dev/null +++ b/components/tab5-emu/include/overlay.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// Make a game core's code runnable: in builds that execute from flash, the +/// cores share one PSRAM code overlay (overlay.ld) and this copies the named +/// core's code into it (if it is not the one there already) and, on the +/// core's first load, runs its static constructors. Call it before any of +/// the core's code runs (its cart's constructor) and only while no other +/// core's code runs. With XIP from PSRAM every core is always there and this +/// does nothing. +/// +/// `core` is the overlay member's name: gba, snes, genesis, doom, nes, gbc, +/// sms, msx, pico8, jk, darkforces, mgs or scummvm. Returns false for any +/// other name. +bool tab5_overlay_load(const char *core); + +/// The core whose code is in the overlay now ("" for none; always "" with XIP +/// from PSRAM). +const char *tab5_overlay_loaded(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/tab5-emu/include/tab5-emu.hpp b/components/tab5-emu/include/tab5-emu.hpp index 01d1403..f614718 100644 --- a/components/tab5-emu/include/tab5-emu.hpp +++ b/components/tab5-emu/include/tab5-emu.hpp @@ -381,6 +381,7 @@ class Tab5Emu : public espp::BaseComponent { uint32_t off_x, off_y; ///< panel (native) offset of the centered picture }; Layout layout() const; + int rotation_{0}; // the LVGL display rotation, read in native_size() /// Convert staging rect [x0,x0+tw)x[y0,y0+th) into the tile buffer void convert_tile(const void *frame, const void *overlay, size_t ov_r0, size_t ov_r1, size_t x0, size_t y0, size_t tw, size_t th); diff --git a/components/tab5-emu/overlay.ld b/components/tab5-emu/overlay.ld new file mode 100644 index 0000000..b4c3c2a --- /dev/null +++ b/components/tab5-emu/overlay.ld @@ -0,0 +1,134 @@ +/* The game cores' code overlay, for builds that execute from flash (no + * CONFIG_SPIRAM_XIP_FROM_PSRAM): code from flash is slow, and a copy of all + * of it in PSRAM (what XIP from PSRAM does) costs over 12 MB. Only one game + * runs at a time, so every core's code is linked at the same PSRAM address + * and the one a game needs is copied there when it launches + * (src/overlay.c, tab5_overlay_load()); the PSRAM this costs is the largest + * core's code. + * + * tools/bss_to_psram.py --overlay= renames a core archive's code + * (.text*) to .tab5_ovl.* and its static constructors (.init_array) to + * .tab5_ovl_ctors., which run on the core's first load instead of at + * boot. Shared template code stays in flash (see the script). + * + * Linked bytes: the bootloader can only load an image's flash and internal + * RAM segments, so tools/overlay_image.py (after linking) copies each + * overlay member's (and .tab5_res's) linked, relocated bytes into its slot of + * .flash.tab5_ovl_store (below, + * part of the image's rodata segment, so the boot-time SHA-256 covers it) and + * marks the member NOBITS, and checks that nothing outside a core calls into + * the overlay. + * + * NOCROSSREFS: a link error if one core's code references another's. The + * OVERLAY must be the last allocated output section in ext_ram_seg (a + * section after it would get its load address moved past the members). */ +SECTIONS +{ + /* Code that is not a game core's but needs PSRAM's speed (LVGL and the + * GUI, which draw in software: from flash the launcher redraws visibly). + * bss_to_psram.py --psram-code renames it .tab5_res*; it is filled from its + * flash slot at boot (src/ext_ram_data.c, before the other constructors) + * and stays. */ + .tab5_res ALIGN(128) : + { + _tab5_res_start = ABSOLUTE(.); + *(.tab5_res .tab5_res.*) + . = ALIGN(128); + _tab5_res_end = ABSOLUTE(.); + } > ext_ram_seg + + OVERLAY ALIGN(128) : NOCROSSREFS + { + .tab5_ovl.gba { *(.tab5_ovl.gba.*) . = ALIGN(128); } + .tab5_ovl.snes { *(.tab5_ovl.snes.*) . = ALIGN(128); } + .tab5_ovl.genesis { *(.tab5_ovl.genesis.*) . = ALIGN(128); } + .tab5_ovl.doom { *(.tab5_ovl.doom.*) . = ALIGN(128); } + .tab5_ovl.nes { *(.tab5_ovl.nes.*) . = ALIGN(128); } + .tab5_ovl.gbc { *(.tab5_ovl.gbc.*) . = ALIGN(128); } + .tab5_ovl.sms { *(.tab5_ovl.sms.*) . = ALIGN(128); } + .tab5_ovl.msx { *(.tab5_ovl.msx.*) . = ALIGN(128); } + .tab5_ovl.pico8 { *(.tab5_ovl.pico8.*) . = ALIGN(128); } + .tab5_ovl.jk { *(.tab5_ovl.jk.*) . = ALIGN(128); } + .tab5_ovl.darkforces { *(.tab5_ovl.darkforces.*) . = ALIGN(128); } + .tab5_ovl.mgs { *(.tab5_ovl.mgs.*) . = ALIGN(128); } + .tab5_ovl.scummvm { *(.tab5_ovl.scummvm.*) . = ALIGN(128); } + } > ext_ram_seg + _tab5_ovl_start = ADDR(.tab5_ovl.gba); + /* after an OVERLAY, . is its start plus its largest member */ + _tab5_ovl_end = ALIGN(., 128); + + /* Flash: each core's constructor table, then a slot per core for its code + * (filled after linking). Directly after .flash.tdata, in the same rodata + * segment of the image (.flash.tbss does not advance the location). The + * BYTE() makes the section PROGBITS; it must not be aligned itself (the + * gap would break the assert below). */ + .flash.tab5_ovl_store : + { + _tab5_ovl_store_start = ABSOLUTE(.); + BYTE(0x4f) + . = ALIGN(16); _tab5_res_lma = ABSOLUTE(.); . += SIZEOF(.tab5_res); + . = ALIGN(4); _tab5_ovl_ctors_gba_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.gba .tab5_ovl_ctors.gba.*)) _tab5_ovl_ctors_gba_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_snes_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.snes .tab5_ovl_ctors.snes.*)) _tab5_ovl_ctors_snes_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_genesis_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.genesis .tab5_ovl_ctors.genesis.*)) _tab5_ovl_ctors_genesis_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_doom_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.doom .tab5_ovl_ctors.doom.*)) _tab5_ovl_ctors_doom_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_nes_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.nes .tab5_ovl_ctors.nes.*)) _tab5_ovl_ctors_nes_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_gbc_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.gbc .tab5_ovl_ctors.gbc.*)) _tab5_ovl_ctors_gbc_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_sms_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.sms .tab5_ovl_ctors.sms.*)) _tab5_ovl_ctors_sms_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_msx_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.msx .tab5_ovl_ctors.msx.*)) _tab5_ovl_ctors_msx_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_pico8_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.pico8 .tab5_ovl_ctors.pico8.*)) _tab5_ovl_ctors_pico8_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_jk_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.jk .tab5_ovl_ctors.jk.*)) _tab5_ovl_ctors_jk_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_darkforces_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.darkforces .tab5_ovl_ctors.darkforces.*)) _tab5_ovl_ctors_darkforces_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_mgs_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.mgs .tab5_ovl_ctors.mgs.*)) _tab5_ovl_ctors_mgs_end = ABSOLUTE(.); + . = ALIGN(4); _tab5_ovl_ctors_scummvm_start = ABSOLUTE(.); + KEEP(*(.tab5_ovl_ctors.scummvm .tab5_ovl_ctors.scummvm.*)) _tab5_ovl_ctors_scummvm_end = ABSOLUTE(.); + . = ALIGN(16); _tab5_ovl_gba_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.gba); + . = ALIGN(16); _tab5_ovl_snes_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.snes); + . = ALIGN(16); _tab5_ovl_genesis_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.genesis); + . = ALIGN(16); _tab5_ovl_doom_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.doom); + . = ALIGN(16); _tab5_ovl_nes_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.nes); + . = ALIGN(16); _tab5_ovl_gbc_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.gbc); + . = ALIGN(16); _tab5_ovl_sms_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.sms); + . = ALIGN(16); _tab5_ovl_msx_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.msx); + . = ALIGN(16); _tab5_ovl_pico8_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.pico8); + . = ALIGN(16); _tab5_ovl_jk_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.jk); + . = ALIGN(16); _tab5_ovl_darkforces_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.darkforces); + . = ALIGN(16); _tab5_ovl_mgs_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.mgs); + . = ALIGN(16); _tab5_ovl_scummvm_lma = ABSOLUTE(.); . += SIZEOF(.tab5_ovl.scummvm); + . = ALIGN(16); + _tab5_ovl_store_end = ABSOLUTE(.); + } > flash_rodata_seg + ASSERT(ADDR(.flash.tab5_ovl_store) == ADDR(.flash.tdata) + SIZEOF(.flash.tdata), + "the overlay store must directly follow .flash.tdata (one rodata segment)") +} +_tab5_ovl_gba_size = SIZEOF(.tab5_ovl.gba); +_tab5_ovl_snes_size = SIZEOF(.tab5_ovl.snes); +_tab5_ovl_genesis_size = SIZEOF(.tab5_ovl.genesis); +_tab5_ovl_doom_size = SIZEOF(.tab5_ovl.doom); +_tab5_ovl_nes_size = SIZEOF(.tab5_ovl.nes); +_tab5_ovl_gbc_size = SIZEOF(.tab5_ovl.gbc); +_tab5_ovl_sms_size = SIZEOF(.tab5_ovl.sms); +_tab5_ovl_msx_size = SIZEOF(.tab5_ovl.msx); +_tab5_ovl_pico8_size = SIZEOF(.tab5_ovl.pico8); +_tab5_ovl_jk_size = SIZEOF(.tab5_ovl.jk); +_tab5_ovl_darkforces_size = SIZEOF(.tab5_ovl.darkforces); +_tab5_ovl_mgs_size = SIZEOF(.tab5_ovl.mgs); +_tab5_ovl_scummvm_size = SIZEOF(.tab5_ovl.scummvm); +/* the MMU driver keeps the virtual addresses up to here (the store's) */ +_rodata_reserved_end = _tab5_ovl_store_end; +/* keep [PSRAM bss start, overlay end) out of the PSRAM heap (esp_psram.c; a + * later assignment wins, see ext_ram_data.ld) */ +_ext_ram_noinit_end = _tab5_ovl_end; +ASSERT(_tab5_res_start >= _ext_ram_data_end, ".tab5_res must follow .ext_ram.data in PSRAM") +ASSERT(_tab5_ovl_start >= _tab5_res_end, "the code overlay must follow .tab5_res in PSRAM") diff --git a/components/tab5-emu/src/ext_ram_data.c b/components/tab5-emu/src/ext_ram_data.c new file mode 100644 index 0000000..5f946c1 --- /dev/null +++ b/components/tab5-emu/src/ext_ram_data.c @@ -0,0 +1,45 @@ +// The initial contents of .ext_ram.data (components/tab5-emu/ext_ram_data.ld) +// for builds that execute from flash: the cores' initialised data lives in +// PSRAM, which the bootloader cannot load, so a copy of it is kept in flash +// and put in place here, before the C++ constructors (some of which write it). +#include +#include + +#include "sdkconfig.h" +#include "esp_cache.h" + +#if !CONFIG_SPIRAM_XIP_FROM_PSRAM + +// Room for the copy: tools/ext_ram_data_image.py writes the linked bytes of +// .ext_ram.data here after linking, and fails the build if they do not fit +// (66 KB in November 2026: the Metal Gear Solid game's 42 KB and the other +// cores' 24 KB). A nonzero initializer keeps it in .rodata, i.e. in the image. +#define EXT_RAM_DATA_IMAGE_BYTES (96 * 1024) +__attribute__((aligned(16), used)) const uint8_t tab5_ext_ram_data_image[EXT_RAM_DATA_IMAGE_BYTES] = {0xa5}; + +extern uint8_t _ext_ram_data_start[], _ext_ram_data_end[]; +extern uint8_t _tab5_res_start[], _tab5_res_end[]; +extern const uint8_t _tab5_res_lma[]; + +// 101: the first priority applications may use, so before every default +// constructor (.init_array is sorted by priority, sections.ld); PSRAM is +// mapped and its heap set up before any constructor runs (startup.c) +__attribute__((constructor(101), used)) void tab5_ext_ram_data_init(void) { + const uint8_t *src = tab5_ext_ram_data_image; + // the compiler must not use what it believes the array holds: its contents + // are written into the image after compiling + __asm__ volatile("" : "+r"(src)); + memcpy(_ext_ram_data_start, src, (size_t)(_ext_ram_data_end - _ext_ram_data_start)); + // and the code that runs from PSRAM for good (.tab5_res: LVGL, the GUI; + // components/tab5-emu/overlay.ld), from its slot in the overlay store. It + // was written through the data cache: write it back and drop every cached + // line of it, so instruction fetches (either core) see it. + const size_t res = (size_t)(_tab5_res_end - _tab5_res_start); + if (res) { + memcpy(_tab5_res_start, _tab5_res_lma, res); + esp_cache_msync(_tab5_res_start, res, ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_INVALIDATE); + __asm__ volatile("fence.i" ::: "memory"); + } +} + +#endif diff --git a/components/tab5-emu/src/overlay.c b/components/tab5-emu/src/overlay.c new file mode 100644 index 0000000..b31e65d --- /dev/null +++ b/components/tab5-emu/src/overlay.c @@ -0,0 +1,127 @@ +// The game cores' code overlay (overlay.ld, include/overlay.h): executing +// from flash, every core's code is linked at one PSRAM address and the one a +// game needs is copied there from its slot in flash when it launches. +#include "overlay.h" + +#include +#include +#include + +#include "sdkconfig.h" + +#if CONFIG_SPIRAM_XIP_FROM_PSRAM + +bool tab5_overlay_load(const char *core) { + (void)core; + return true; +} + +const char *tab5_overlay_loaded(void) { return ""; } + +#else + +#include "esp_cache.h" +#include "esp_log.h" +#include "esp_timer.h" + +static const char *TAG = "overlay"; + +typedef void (*ctor_fn)(void); + +// linker symbols (overlay.ld): the shared PSRAM range, and per core its slot +// in flash, its code size (the symbol's value) and its constructor table +extern uint8_t _tab5_ovl_start[], _tab5_ovl_end[]; +#define TAB5_OVL_SYMBOLS(name) \ + extern const uint8_t _tab5_ovl_##name##_lma[]; \ + extern const char _tab5_ovl_##name##_size[]; \ + extern const ctor_fn _tab5_ovl_ctors_##name##_start[], _tab5_ovl_ctors_##name##_end[]; +TAB5_OVL_SYMBOLS(gba) +TAB5_OVL_SYMBOLS(snes) +TAB5_OVL_SYMBOLS(genesis) +TAB5_OVL_SYMBOLS(doom) +TAB5_OVL_SYMBOLS(nes) +TAB5_OVL_SYMBOLS(gbc) +TAB5_OVL_SYMBOLS(sms) +TAB5_OVL_SYMBOLS(msx) +TAB5_OVL_SYMBOLS(pico8) +TAB5_OVL_SYMBOLS(jk) +TAB5_OVL_SYMBOLS(darkforces) +TAB5_OVL_SYMBOLS(mgs) +TAB5_OVL_SYMBOLS(scummvm) + +typedef struct { + const char *name; + const uint8_t *lma; + size_t size; + const ctor_fn *ctors, *ctors_end; +} member_t; + +#define TAB5_OVL_MEMBER(n) \ + {#n, _tab5_ovl_##n##_lma, (size_t)(uintptr_t)_tab5_ovl_##n##_size, _tab5_ovl_ctors_##n##_start, \ + _tab5_ovl_ctors_##n##_end} + +static int s_loaded = -1; +static uint16_t s_constructed; // bit per member: its constructors have run + +static int find(const char *core, member_t *out) { + const member_t members[] = { + TAB5_OVL_MEMBER(gba), TAB5_OVL_MEMBER(snes), TAB5_OVL_MEMBER(genesis), TAB5_OVL_MEMBER(doom), + TAB5_OVL_MEMBER(nes), TAB5_OVL_MEMBER(gbc), TAB5_OVL_MEMBER(sms), TAB5_OVL_MEMBER(msx), + TAB5_OVL_MEMBER(pico8), TAB5_OVL_MEMBER(jk), TAB5_OVL_MEMBER(darkforces), TAB5_OVL_MEMBER(mgs), + TAB5_OVL_MEMBER(scummvm), + }; + _Static_assert(sizeof(members) / sizeof(members[0]) <= 8 * sizeof(s_constructed), "one bit per member"); + for (int i = 0; i < (int)(sizeof(members) / sizeof(members[0])); i++) { + if (strcmp(core, members[i].name) == 0) { + *out = members[i]; + return i; + } + } + return -1; +} + +static const char *s_loaded_name = ""; + +bool tab5_overlay_load(const char *core) { + member_t m; + const int i = find(core, &m); + if (i < 0) { + ESP_LOGE(TAG, "no core '%s' in the overlay", core); + return false; + } + if (i == s_loaded) { + return true; + } + const size_t capacity = (size_t)(_tab5_ovl_end - _tab5_ovl_start); + if (m.size > capacity) { // the linker makes the range the largest member's size + ESP_LOGE(TAG, "%s: %u bytes of code, more than the overlay's %u", core, (unsigned)m.size, (unsigned)capacity); + return false; + } + const int64_t t0 = esp_timer_get_time(); + s_loaded = -1; + s_loaded_name = ""; + memcpy(_tab5_ovl_start, m.lma, m.size); + // the code was written through the data cache: write it back to PSRAM, and + // drop every cached line of the whole range (both cores' instruction caches + // included, which may still hold the previous core's code) + esp_cache_msync(_tab5_ovl_start, capacity, + ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_INVALIDATE | ESP_CACHE_MSYNC_FLAG_UNALIGNED); + __asm__ volatile("fence.i" ::: "memory"); + s_loaded = i; + s_loaded_name = m.name; + const int64_t t1 = esp_timer_get_time(); + if (!(s_constructed & (1u << i))) { + // the core's static constructors, once per boot (its data persists) + s_constructed |= 1u << i; + for (const ctor_fn *c = m.ctors; c < m.ctors_end; c++) { + (*c)(); + } + } + ESP_LOGI(TAG, "%s: %u KB of code loaded in %lld ms (%u constructors)", core, (unsigned)(m.size / 1024), + (t1 - t0) / 1000, (unsigned)(m.ctors_end - m.ctors)); + return true; +} + +const char *tab5_overlay_loaded(void) { return s_loaded_name; } + +#endif diff --git a/components/tab5-emu/src/tab5-emu.cpp b/components/tab5-emu/src/tab5-emu.cpp index 8ff276c..8603f2f 100644 --- a/components/tab5-emu/src/tab5-emu.cpp +++ b/components/tab5-emu/src/tab5-emu.cpp @@ -1,5 +1,7 @@ #include "tab5-emu.hpp" +#include "esp_attr.h" + #include #include #include @@ -761,6 +763,7 @@ void Tab5Emu::native_size(size_t width, size_t height, int pitch) { native_width_ = width; native_height_ = height; native_pitch_ = pitch > 0 ? pitch : width; + rotation_ = lv_display_get_rotation(lv_display_get_default()); logger_.info("native size: {}x{} (pitch {})", native_width_, native_height_, native_pitch_); } @@ -771,7 +774,7 @@ void Tab5Emu::overlay_size(size_t width, size_t height, int pitch) { logger_.info("overlay size: {}x{} (pitch {})", overlay_width_, overlay_height_, overlay_pitch_); } -size_t Tab5Emu::staging_scale() const { +IRAM_ATTR size_t Tab5Emu::staging_scale() const { // overlays are only supported on paletted frames if (!has_palette() || overlay_width_ == 0 || overlay_height_ == 0 || native_height_ == 0) { return 1; @@ -808,7 +811,7 @@ void Tab5Emu::clear_screen() { esp_cache_msync(fb, dpi_fb_bytes_, ESP_CACHE_MSYNC_FLAG_DIR_C2M); } -void Tab5Emu::push_frame(const void *frame, const void *overlay, size_t overlay_row_begin, +IRAM_ATTR void Tab5Emu::push_frame(const void *frame, const void *overlay, size_t overlay_row_begin, size_t overlay_row_end) { if (!video_queue_) { return; @@ -822,7 +825,7 @@ void Tab5Emu::push_frame(const void *frame, const void *overlay, size_t overlay_ xQueueOverwrite(video_queue_, &vf); } -bool Tab5Emu::frame_slot_free() const { +IRAM_ATTR bool Tab5Emu::frame_slot_free() const { return video_queue_ == nullptr || uxQueueMessagesWaiting(video_queue_) == 0; } @@ -834,7 +837,7 @@ Tab5Emu::VideoStats Tab5Emu::video_stats(bool reset) { return stats; } -void Tab5Emu::wait_frame() { +IRAM_ATTR void Tab5Emu::wait_frame() { if (frame_done_) { xSemaphoreTake(frame_done_, pdMS_TO_TICKS(100)); } @@ -859,11 +862,12 @@ bool Tab5Emu::ensure_tile_buffer() { return true; } -Tab5Emu::Layout Tab5Emu::layout() const { +IRAM_ATTR Tab5Emu::Layout Tab5Emu::layout() const { Layout lo{}; // the LVGL rotation the GUI configured; the BSP's flush uses the identical // LVGL->PPA mapping, so the game frames come out the same way up as the GUI - auto rotation = lv_display_get_rotation(lv_display_get_default()); + // (read when the game set its frame size: not LVGL code every frame) + const auto rotation = static_cast(rotation_); lo.angle = PPA_SRM_ROTATION_ANGLE_0; lo.swap = false; switch (rotation) { @@ -899,7 +903,7 @@ Tab5Emu::Layout Tab5Emu::layout() const { return lo; } -bool Tab5Emu::blit_tile(const Layout &lo, size_t x0, size_t y0, size_t tw, size_t th) { +IRAM_ATTR bool Tab5Emu::blit_tile(const Layout &lo, size_t x0, size_t y0, size_t tw, size_t th) { auto fb = dpi_frame_buffer(); if (!fb || !ppa_client_) { return false; @@ -957,7 +961,7 @@ bool Tab5Emu::blit_tile(const Layout &lo, size_t x0, size_t y0, size_t tw, size_ return true; } -bool Tab5Emu::video_task_callback(std::mutex &m, std::condition_variable &cv, bool &task_notified) { +IRAM_ATTR bool Tab5Emu::video_task_callback(std::mutex &m, std::condition_variable &cv, bool &task_notified) { VideoFrame vf{nullptr, nullptr, 0, 0}; if (xQueueReceive(video_queue_, &vf, portMAX_DELAY) != pdTRUE) { return false; @@ -1019,7 +1023,7 @@ bool Tab5Emu::video_task_callback(std::mutex &m, std::condition_variable &cv, bo // tw). The staging frame is the native frame upscaled by staging_scale() // (nearest neighbour) with the overlay drawn 1:1 on top, centered, palette // index 0 transparent. -void Tab5Emu::convert_tile(const void *frame, const void *overlay, size_t ov_r0, size_t ov_r1, size_t x0, size_t y0, +IRAM_ATTR void Tab5Emu::convert_tile(const void *frame, const void *overlay, size_t ov_r0, size_t ov_r1, size_t x0, size_t y0, size_t tw, size_t th) { const size_t k = staging_scale(); const size_t sw = staging_width(); diff --git a/docs/PLAN.md b/docs/PLAN.md index c65f8a2..060e83d 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -176,6 +176,53 @@ the game's. `Tab5Emu::display_size()` picks original/fit/fill scaling. grows the data region, so this needs a custom placement plus disabling the PMP I/D split), or a RISC-V dynarec for gpSP (none exists). +## Code placement: execute from flash, cores in a PSRAM overlay (2026-11-19) + +Until 2026-11 the firmware ran with `CONFIG_SPIRAM_XIP_FROM_PSRAM`: all of +`.text` and `.rodata` (12.7 MB) copied into PSRAM at boot. After the emu-ui +launcher and #23 that left too little PSRAM for Jedi Knight's first level +("Could not load level!"). Now code executes from flash (80 MHz QIO, which +needs chip rev v0.1+), and the game cores' code and tables, which need the +speed, share one PSRAM overlay: every core is linked at the same address and +the running game's core is copied there from flash when it launches. + +- `tools/bss_to_psram.py --overlay= --overlay-rodata` renames a core + archive's `.text*` and `.rodata.` to `.tab5_ovl.*`, and its + `.init_array` to `.tab5_ovl_ctors.`; `components/tab5-emu/overlay.ld` + links the members in one `OVERLAY` (NOCROSSREFS) after `.ext_ram.data`, + with a slot per core in `.flash.tab5_ovl_store` (in the image's rodata + segment, so the boot SHA covers it). +- `tools/overlay_image.py` (post-link) copies each member's bytes into its + slot, marks the PSRAM sections NOBITS, and fails the build if code or data + outside a core reaches into the overlay (only the carts in main.cpp, the + loader and a core's own code may). +- `tab5_overlay_load(core)` (components/tab5-emu/src/overlay.c) copies the + code in, syncs the caches (both cores' I-caches) and runs the core's + static constructors on its first load. `make_cart` calls it before the + cart's constructor; `app_main` loads ScummVM for `scummvm_prepare()`. +- Stays in flash although it comes from a core archive: shared template code + (`std::`, `__gnu_cxx::`, `fmt::`, `espp::`: the linker keeps one copy of each + for the whole firmware and it may be a core's), Dark Forces' allocator + (`--wrap=free,realloc` makes it everyone's free()), `mgs::release_arena` + (called on every launch), merged strings and constants. TPM's 3.2 MB + bundle is not in the overlay (it loses 0-2% from flash). +- LVGL, emu-ui, the GUI and the menu draw in software and redrew visibly + from flash, so their code and read-only data run from PSRAM too, for good: + `bss_to_psram.py --psram-code` (applied to those archives just before the + link, in the root CMakeLists.txt) renames them `.tab5_res*`, filled from + its flash slot at boot by the constructor that fills `.ext_ram.data`. +- Cost: 1.1 MB of PSRAM (the largest member, MGS) plus 0.7 MB (`.tab5_res`) + instead of 12.7 MB; 18.1 MB free at the launcher instead of 7.3 MB. Measured (core fps / presented, + PSRAM XIP -> flash -> overlay): Genesis 99/59.7 -> 77/43.5 -> 91/59.6, + GBA 95 -> 82 -> 90 (59.7 presented), SNES 70 -> 58 -> 67, + Doom 99 -> 78 -> 94.5, MGS 9.3 -> 7.8 -> 8.7 presented, + JK level 1 12.5 -> 14.2 presented (it does not load with PSRAM XIP). + NES, GBC, PICO-8, DF, TPM and ScummVM are within a few percent either way. +- Not handled: a core task that outlives its game would run the next core's + code (MGS's logger leaks its task if stdout blocks it for 200 ms at quit); + with every core at one address, a panic backtrace inside the overlay needs + the loaded core's name (`tab5_overlay_loaded()`) to be read. + ## Internal RAM policy (2026-09-20) Internal RAM (~440 KB DIRAM, ~150 KB free after link) is the constraint, diff --git a/main/carts.hpp b/main/carts.hpp index a313f1f..13e4855 100644 --- a/main/carts.hpp +++ b/main/carts.hpp @@ -2,6 +2,8 @@ #include +#include "overlay.h" + #include "darkforces_cart.hpp" #include "doom_cart.hpp" #include "gba_cart.hpp" @@ -17,6 +19,44 @@ #include "snes_cart.hpp" #include "tpm_cart.hpp" +// The member of the game cores' code overlay a platform's cart runs (see +// overlay.h; nullptr: its code is always there) +inline const char *overlay_core(Emulator platform) { + switch (platform) { + case Emulator::JEDI_KNIGHT: + return "jk"; + case Emulator::MGS: + return "mgs"; + case Emulator::GBA: + return "gba"; + case Emulator::SNES: + return "snes"; + case Emulator::SEGA_GENESIS: + case Emulator::SEGA_MEGA_DRIVE: + return "genesis"; + case Emulator::PICO8: + return "pico8"; + case Emulator::NES: + return "nes"; + case Emulator::GAMEBOY: + case Emulator::GAMEBOY_COLOR: + return "gbc"; + case Emulator::SEGA_MASTER_SYSTEM: + case Emulator::SEGA_GAME_GEAR: + return "sms"; + case Emulator::MSX: + return "msx"; + case Emulator::DOOM: + return "doom"; + case Emulator::DARK_FORCES: + return "darkforces"; + case Emulator::SCUMMVM: + return "scummvm"; + default: + return nullptr; + } +} + inline std::unique_ptr make_cart(const RomInfo &info) { #if defined(ENABLE_MGS) if (info.platform != Emulator::MGS) { @@ -34,6 +74,10 @@ inline std::unique_ptr make_cart(const RomInfo &info) { heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); #endif + // its core's code, before the cart's constructor runs any of it + if (const char *core = overlay_core(info.platform); core && !tab5_overlay_load(core)) { + return nullptr; + } switch (info.platform) { case Emulator::JEDI_KNIGHT: return std::make_unique(Cart::Config{ diff --git a/main/main.cpp b/main/main.cpp index 0603141..76a46ab 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -25,6 +25,7 @@ #include "devlink.hpp" #include "gui.hpp" #include "heap_utils.hpp" +#include "overlay.h" #include "remote_control.hpp" #include "rom_info.hpp" #include "settings.hpp" @@ -113,6 +114,8 @@ extern "C" void app_main(void) { #if defined(ENABLE_SCUMMVM) // now, while the PSRAM heap is empty: its long-lived allocations sit at // the start instead of between the big blocks the games want + // (its code is part of the cores' overlay: load it for this) + tab5_overlay_load("scummvm"); scummvm_prepare(); #endif diff --git a/sdkconfig.defaults b/sdkconfig.defaults index b5c59db..eaca4e1 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -3,7 +3,10 @@ CONFIG_IDF_TARGET="esp32p4" # Tab5 ships an older ESP32-P4 silicon revision (< v3); ESP-IDF >= 6.0 needs # this to accept it. CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y -CONFIG_ESP32P4_REV_MIN_0=y +# v0.1 or later (the Tab5's is v1.3): v0.0 cannot run the flash at 80 MHz, +# and the firmware executes from flash (see the PSRAM section below) +CONFIG_ESP32P4_REV_MIN_1=y +CONFIG_ESPTOOLPY_FLASHFREQ_80M=y CONFIG_IDF_EXPERIMENTAL_FEATURES=y CONFIG_COMPILER_OPTIMIZATION_PERF=y @@ -46,7 +49,14 @@ CONFIG_M5STACK_TAB5_AUDIO_TASK_STACK_SIZE=8192 # PSRAM: 32 MB hex PSRAM on the Tab5; the game engine heap lives here. CONFIG_SPIRAM=y CONFIG_SPIRAM_SPEED_200M=y -CONFIG_SPIRAM_XIP_FROM_PSRAM=y +# Code executes from flash, not from a copy in PSRAM (CONFIG_SPIRAM_XIP_FROM_PSRAM, +# which costs 12.7 MB of PSRAM: all of .text and .rodata). The game cores' +# code and tables, which need the speed, share one PSRAM overlay instead: +# only the running game's core is there (components/tab5-emu/overlay.ld, +# about 1.1 MB). The cores' initialised data lives in PSRAM (.ext_ram.data, +# components/tab5-emu/ext_ram_data.ld), kept out of the heap with the noinit +# range. +CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY=y CONFIG_SPIRAM_USE_MALLOC=y # Every plain malloc / new goes to PSRAM first, whatever its size (as on the # box): internal RAM is the scarce resource on the P4 (SD DMA buffers, USB, @@ -60,10 +70,11 @@ CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=131072 CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y # the game engine's static state is mapped to PSRAM (components/jk/linker.lf) CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY=y -# The MGS core keeps the game's initialized data in the PSRAM-XIP .rodata -# (tools/bss_to_psram.py --data); the PMP rules memory protection installs -# make that range read-only and are locked, so protection is off. Nothing -# untrusted runs here, and it is only the IRAM/DRAM W^X split that is lost. +# Memory protection is off: the cores' code runs from PSRAM (the overlay, +# which the loader writes), and with protection on the PMP keeps PSRAM from +# executing (and, with XIP from PSRAM, keeps the cores' data in .rodata +# read-only). Nothing untrusted runs here; it is only the W^X split that is +# lost. CONFIG_ESP_SYSTEM_MEMPROT=n CONFIG_CACHE_L2_CACHE_256KB=y CONFIG_CACHE_L2_CACHE_LINE_128B=y diff --git a/tools/bss_to_psram.py b/tools/bss_to_psram.py index 5da0fcb..936168f 100644 --- a/tools/bss_to_psram.py +++ b/tools/bss_to_psram.py @@ -5,56 +5,194 @@ template has no ldgen placeholder for external RAM, so this is done on the object level instead of with a linker fragment. -usage: bss_to_psram.py [--keep name,name,...] [--data] +usage: bss_to_psram.py [--keep name,name,...] + [--data [--data-into=rodata|ext_ram[:TAG]]] + [--also-data=PREFIX:TAG ...] [--no-bss] + [--overlay=NAME [--overlay-rodata] [--overlay-keep=REGEX ...]] + [--psram-code] --keep: symbols (section suffixes) that stay in internal RAM, e.g. a core's hottest state - --data: also move the initialized data (.data/.data.*/.sdata*) to PSRAM. - Only valid with CONFIG_SPIRAM_XIP_FROM_PSRAM: the sections are - renamed into .rodata.*, which that configuration copies from flash - into PSRAM at boot and maps there, so the data arrives initialized - and relocated like any other; it is writable only with - CONFIG_ESP_SYSTEM_MEMPROT off (the PMP marks .rodata read-only). + --data: also move the initialized data (.data/.data.*/.sdata*) to PSRAM: + --data-into=rodata (the default) renames them .rodata.psram_data.*. Only + valid with CONFIG_SPIRAM_XIP_FROM_PSRAM: that configuration copies + .rodata from flash into PSRAM at boot and maps it there, so the data + arrives initialized and relocated like any other; it is writable + only with CONFIG_ESP_SYSTEM_MEMPROT off (the PMP marks .rodata + read-only). Executing from flash, .rodata is flash and the first + write to it is a store access fault. + --data-into=ext_ram[:TAG] renames them .ext_ram.data[.TAG]: the + .ext_ram.data output section in PSRAM (components/tab5-emu/ + ext_ram_data.ld), filled at boot from the copy that + tools/ext_ram_data_image.py stores in flash. For builds that execute + from flash. + --also-data=PREFIX:TAG: sections whose name starts with PREFIX (e.g. a + core's own SECTION(".mgs.sdata")) are data too, renamed into + .ext_ram.data.TAG (ext_ram only) + --no-bss: leave the .bss alone (it is placed some other way, e.g. ldgen) + --overlay=NAME: the core's code (.text/.text.*) becomes .tab5_ovl.NAME*, + the core's member of the code overlay in PSRAM (builds that execute + from flash; components/tab5-emu/overlay.ld): every core is linked at + the same PSRAM address and the one a game needs is copied there when + it launches. Its static constructors (.init_array) become + .tab5_ovl_ctors.NAME, run on its first load instead of at boot. + Shared template code (std::, __gnu_cxx::, fmt::, espp::) stays in + flash: the linker keeps one copy of each for the whole firmware and + it may be this archive's. + --overlay-rodata: the core's named read-only data (.rodata.: its + tables) goes into the overlay too (merged strings and constants stay + in flash, and so does shared template data, as with the code) + --psram-code: all of the archive's code and read-only data (.text*, + .rodata*) goes to .tab5_res, PSRAM that is filled from flash at + boot and stays (components/tab5-emu/overlay.ld): for code that + runs outside the games and needs the speed (the GUI, LVGL). Not + for code that runs before the C++ constructors. + --overlay-keep=REGEX: more code that stays in flash (resident), matched + against the section name after ".text." (and after "unlikely." / + "hot." / "startup."); repeatable """ +import re +import tempfile +import os import subprocess import sys objdump, objcopy, archive = sys.argv[1:4] keep = set() data = False +data_into, data_tag = "rodata", "" +also = [] # (prefix, tag) +do_bss = True +overlay = "" +overlay_rodata = False +psram_code = False +overlay_keep = [re.compile(r"^_Z(NK?)?(St|Sa|Ss|9__gnu_cxx|3fmt|4espp)")] rest = sys.argv[4:] while rest: - if rest[0] == "--keep": + arg = rest[0] + if arg == "--keep": keep = set(rest[1].split(",")) rest = rest[2:] - elif rest[0] == "--data": + continue + if arg == "--data": data = True - rest = rest[1:] + elif arg.startswith("--data-into="): + data_into, _, data_tag = arg.split("=", 1)[1].partition(":") + if data_into not in ("rodata", "ext_ram"): + sys.exit(f"bss_to_psram: --data-into must be rodata or ext_ram, not {data_into}") + elif arg.startswith("--also-data="): + prefix, _, tag = arg.split("=", 1)[1].partition(":") + also.append((prefix, tag)) + elif arg == "--no-bss": + do_bss = False + elif arg.startswith("--overlay="): + overlay = arg.split("=", 1)[1] + elif arg == "--overlay-rodata": + overlay_rodata = True + elif arg == "--psram-code": + psram_code = True + elif arg.startswith("--overlay-keep="): + overlay_keep.append(re.compile(arg.split("=", 1)[1])) else: - sys.exit(f"bss_to_psram: unknown argument {rest[0]}") + sys.exit(f"bss_to_psram: unknown argument {arg}") + rest = rest[1:] +if also and data_into != "ext_ram": + sys.exit("bss_to_psram: --also-data needs --data-into=ext_ram") + + +def is_bss(name): + return name == ".bss" or name == ".sbss" or name.startswith(".bss.") or name.startswith(".sbss.") + + +def is_data(name): + return name == ".data" or name == ".sdata" or name.startswith(".data.") or name.startswith(".sdata.") + + +def is_text(name): + return name == ".text" or name.startswith(".text.") + + +def resident(name): + """Code or read-only data that stays in flash although its archive is an + overlay""" + fn = name.split(".", 2)[2] if name.count(".") >= 2 else "" + for sub in ("unlikely.", "hot.", "startup.", "exit."): + if fn.startswith(sub): + fn = fn[len(sub):] + break + # vtables / typeinfo (_ZTV...) and function-local statics (_ZZ...) belong + # with the code they are part of + if fn.startswith(("_ZTV", "_ZTI", "_ZTS", "_ZTT")): + fn = "_Z" + fn[4:] + elif fn.startswith("_ZZ"): + fn = "_Z" + fn[3:] + return any(k.search(fn) for k in overlay_keep) + + +MERGED = re.compile(r"\.(str\d+\.\d+|cst\d+)$") # .rodata[.].str1.4 / .cst8 + + +def is_named_rodata(name): + """.rodata., not merged strings / constants (.rodata.str1.1, + .rodata.cst8, and with -ffunction-sections the per-function pools + .rodata..str1.4 / .rodata..cst8), which shared code in the + archive may point into""" + return name.startswith(".rodata.") and not MERGED.search(name) + + +def tagged(tag): + return ".ext_ram.data" + (f".{tag}" if tag else "") + + out = subprocess.run([objdump, "-h", archive], check=True, capture_output=True, text=True).stdout -names = set() +renames = {} # old name -> new name for line in out.splitlines(): parts = line.split() - if len(parts) > 2 and parts[0].isdigit(): - name = parts[1] - if name == ".bss" or name == ".sbss" or name.startswith(".bss.") or name.startswith(".sbss."): - if name.count(".") >= 2 and name.split(".", 2)[2] in keep: - continue - names.add(name) - elif data and (name == ".data" or name == ".sdata" or name.startswith(".data.") or name.startswith(".sdata.")): - names.add(name) -if not names: - sys.exit(0) -args = [objcopy] -moved_data = 0 -for name in sorted(names): + if len(parts) <= 2 or not parts[0].isdigit(): + continue + name = parts[1] suffix = name.split(".", 2)[2] if name.count(".") >= 2 else "" - if name.startswith(".data") or name.startswith(".sdata"): - args += ["--rename-section", f"{name}=.rodata.psram_data" + (f".{suffix}" if suffix else "")] - moved_data += 1 + if do_bss and is_bss(name): + if suffix in keep: + continue + renames[name] = ".ext_ram.bss" + (f".{suffix}" if suffix else "") + elif psram_code and (is_text(name) or name == ".rodata" or name.startswith(".rodata.")): + renames[name] = f".tab5_res{name}" + elif overlay and is_text(name): + if not resident(name): + renames[name] = f".tab5_ovl.{overlay}{name}" + elif overlay and overlay_rodata and is_named_rodata(name): + if not resident(name): + renames[name] = f".tab5_ovl.{overlay}{name}" + elif overlay and (name == ".init_array" or name.startswith(".init_array.")): + renames[name] = f".tab5_ovl_ctors.{overlay}{name[len('.init_array'):]}" + elif data and is_data(name): + if data_into == "rodata": + renames[name] = ".rodata.psram_data" + (f".{suffix}" if suffix else "") + else: + renames[name] = tagged(data_tag) + name else: - args += ["--rename-section", f"{name}=.ext_ram.bss" + (f".{suffix}" if suffix else "")] -args.append(archive) -subprocess.run(args, check=True) -print(f"bss_to_psram: moved {len(names) - moved_data} bss sections of {archive} to .ext_ram.bss" - + (f", {moved_data} data sections to .rodata (PSRAM-XIP)" if moved_data else "")) + for prefix, tag in also: + if name.startswith(prefix): + renames[name] = tagged(tag) + name + break +if not renames: + sys.exit(0) +# 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) +moved_bss = sum(1 for n in renames.values() if n.startswith(".ext_ram.bss")) +moved_text = sum(1 for n in renames.values() if n.startswith(".tab5_ovl.")) +moved_ctors = sum(1 for n in renames.values() if n.startswith(".tab5_ovl_ctors.")) +moved_res = sum(1 for n in renames.values() if n.startswith(".tab5_res")) +moved_data = len(renames) - moved_bss - moved_text - moved_ctors - moved_res +where = ".rodata (PSRAM-XIP)" if data_into == "rodata" else ".ext_ram.data" +print(f"bss_to_psram: moved {moved_bss} bss sections of {archive} to .ext_ram.bss" + + (f", {moved_data} data sections to {where}" if moved_data else "") + + (f", {moved_text} code sections to the {overlay} overlay ({moved_ctors} constructor tables)" + if overlay else "") + + (f", {moved_res} code / read-only data sections to PSRAM (.tab5_res)" if moved_res else "")) diff --git a/tools/ext_ram_data_image.py b/tools/ext_ram_data_image.py new file mode 100644 index 0000000..0c9b898 --- /dev/null +++ b/tools/ext_ram_data_image.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Store the PSRAM section .ext_ram.data in flash (builds that execute from +flash; see components/tab5-emu/ext_ram_data.ld). + +usage: ext_ram_data_image.py + +The linker placed .ext_ram.data (the cores' initialised data) in PSRAM and +resolved every reference to it there, but the bootloader can only load an +image's flash and internal-RAM segments. This copies the section's linked, +relocated bytes into the flash array tab5_ext_ram_data_image +(components/tab5-emu/src/ext_ram_data.c copies them into PSRAM before the +constructors run) and changes the section to NOBITS, so elf2image leaves it +out of the image. Run on the ELF after linking and before elf2image; running +it again is harmless (a NOBITS section is left alone). +""" +import struct +import sys + +SHT_NOBITS = 8 +path = sys.argv[1] +elf = bytearray(open(path, "rb").read()) +if elf[:4] != b"\x7fELF" or elf[4] != 1 or elf[5] != 1: + sys.exit(f"ext_ram_data_image: {path} is not a little-endian ELF32") +(shoff,) = struct.unpack_from(" size: + sys.exit(f"ext_ram_data_image: .ext_ram.data is {len(data)} bytes, more than the {size} bytes of " + "tab5_ext_ram_data_image: raise EXT_RAM_DATA_IMAGE_BYTES in components/tab5-emu/src/ext_ram_data.c") +holder = sections[shndx] +if holder[1] == SHT_NOBITS or not (holder[3] <= value and value + size <= holder[3] + holder[5]): + sys.exit(f"ext_ram_data_image: tab5_ext_ram_data_image is not in a loaded section ({names[shndx]})") +file_off = holder[4] + (value - holder[3]) +elf[file_off : file_off + len(data)] = data +struct.pack_into(" [keep-regex ...]): the bss_to_psram.py +# arguments that put a game core's code into the PSRAM code overlay +# (components/tab5-emu/overlay.ld) when the firmware executes from flash, plus +# any code that has to stay in flash (--overlay-keep; see the script). Empty +# with XIP from PSRAM, where all code is in PSRAM anyway. +function(tab5_overlay_args core out) + set(args "") + if(NOT CONFIG_SPIRAM_XIP_FROM_PSRAM) + list(APPEND args "--overlay=${core}" "--overlay-rodata") + foreach(keep ${ARGN}) + list(APPEND args "--overlay-keep=${keep}") + endforeach() + endif() + set(${out} "${args}" PARENT_SCOPE) +endfunction() diff --git a/tools/overlay_image.py b/tools/overlay_image.py new file mode 100644 index 0000000..d7139cd --- /dev/null +++ b/tools/overlay_image.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +"""Store the game cores' code overlay in flash and check that nothing else +uses it (builds that execute from flash; see components/tab5-emu/overlay.ld). + +usage: overlay_image.py [--report] + +1. Each overlay member .tab5_ovl. (linked at the shared PSRAM address) + is copied into its slot in .flash.tab5_ovl_store (symbol + _tab5_ovl__lma) and changed to NOBITS, so elf2image leaves the PSRAM + sections out of the image; likewise .tab5_res (resident PSRAM code, + _tab5_res_lma). Running it again is harmless. +2. Checks, which fail the build: code that is not in the overlay must not + reach into it, because only one core's code is there at a time (or none): + - no boot-time constructor (.flash.init_array) points into the overlay; + - resident code: every call / jump / address taken / load / store into the + overlay range (auipc or lui followed by jalr / addi / a load or store + on the same register) must be in + the carts (main.cpp, which load their core before using it), the loader + (overlay.c), or a core's own resident code that only that core uses: its + internal-RAM code (IRAM_ATTR and the like), or code it keeps in flash + that is local or, per the linker's cross-reference table, referenced + only from its own archive; + - resident data: every word that is the address of an overlay function + (or table) must belong to a core archive (its own jump tables, vtables, callbacks). + A finding names the resident function and the overlay code it reaches; + the usual fix is to keep that code in flash (bss_to_psram.py + --overlay-keep in the core's CMakeLists.txt). + --report prints the allowed references too. +""" +import bisect +import re +import shutil +import struct +import subprocess +import sys +from array import array + +SHT_PROGBITS, SHT_NOBITS = 1, 8 +SHF_WRITE, SHF_ALLOC, SHF_EXECINSTR = 0x1, 0x2, 0x4 +CORES = ("gba", "snes", "genesis", "doom", "nes", "gbc", "sms", "msx", "pico8", "jk", "darkforces", "mgs", "scummvm") +CART_FILES = ("libmain.a(main.cpp.obj)",) + +elf_path, map_path = sys.argv[1], sys.argv[2] +report = "--report" in sys.argv[3:] +elf = bytearray(open(elf_path, "rb").read()) +(shoff,) = struct.unpack_from(" (value, size, shndx) +funcs = [] # (value, size, name, bind) of functions, for naming addresses +objects = [] # data object addresses +for off in range(symtab[4], symtab[4] + symtab[5], 16): + st_name, value, size, info, other, shndx = struct.unpack_from("> 4)) + elif info & 0xF == 1 and size: # STT_OBJECT + objects.append(value) +funcs.sort() + + +def sym(name): + if name not in symbols: + sys.exit(f"overlay_image: {name} is not linked (is components/tab5-emu/overlay.ld in the link?)") + return symbols[name][0] + + +def holder(addr): + """the loaded section that holds addr: (index, file offset)""" + for i, s in enumerate(secs): + # (the store is INIT_ARRAY: it also holds the constructor tables) + if s[1] not in (0, SHT_NOBITS) and s[2] & SHF_ALLOC and s[3] <= addr < s[3] + s[5]: + return i, s[4] + addr - s[3] + return None, None + + +ovl_start, ovl_end = sym("_tab5_ovl_start"), sym("_tab5_ovl_end") +ovl_objects = [v for v in objects if ovl_start <= v < ovl_end] + +# 1. store (the overlay members, and .tab5_res: PSRAM code filled at boot) +def slot_of(name): + return "_tab5_res_lma" if name == ".tab5_res" else f"_tab5_ovl_{name[len('.tab5_ovl.'):]}_lma" + + +stored = 0 +for i, name in enumerate(names): + if not (name.startswith(".tab5_ovl.") or name == ".tab5_res") or secs[i][1] != SHT_PROGBITS: + continue + core = name[len(".tab5_ovl.") :] if name != ".tab5_res" else "resident PSRAM code" + size = secs[i][5] + if size: + lma = sym(slot_of(name)) + hi, foff = holder(lma) + if hi is None or names[hi] != ".flash.tab5_ovl_store" or lma + size > secs[hi][3] + secs[hi][5]: + sys.exit(f"overlay_image: the {core} slot at {lma:#x} is not inside .flash.tab5_ovl_store") + elf[foff : foff + size] = elf[secs[i][4] : secs[i][4] + size] + stored += size + struct.pack_into(" 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 = None +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, size = int(m.group(2), 16), int(m.group(3), 16) + if size and addr: + inputs.append((addr, size, 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 +else: + cref = len(lines) +current = None +for line in lines[cref + 3 :]: + if not line.strip(): + continue + if line[0] != " ": + current, _, file = line.rstrip().rpartition(" ") + current = current.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): + """(file, input section) of a resident address (the overlay members overlap: not for those)""" + 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 "?", "?" + + +resident_funcs = [f for f in funcs if not ovl_start <= f[0] < ovl_end] +resident_starts = [f[0] for f in resident_funcs] + + +def func_at(addr): + """the resident function at addr (they do not overlap)""" + j = bisect.bisect_right(resident_starts, addr) - 1 + if j >= 0 and addr < resident_funcs[j][0] + resident_funcs[j][1]: + return resident_funcs[j] + return None + + +ovl_funcs = [f for f in funcs if ovl_start <= f[0] < ovl_end] +# where an overlay function or table (with --overlay-rodata) starts +ovl_func_starts = {f[0] for f in ovl_funcs} | {v for v in ovl_objects} + + +def overlay_names(addr): + """the overlay symbols at addr (one per core whose code has a function there)""" + return sorted({n for v, s, n, b in ovl_funcs if v <= addr < v + s})[:4] + + +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(names_): + tool = shutil.which("riscv32-esp-elf-c++filt") or shutil.which("c++filt") + todo = [n for n in names_ if n not in demangled] + if not todo: + return + out = subprocess.run([tool], input="\n".join(todo), capture_output=True, text=True).stdout.split("\n") if tool else todo + for n, d in zip(todo, out): + demangled[n] = d + + +problems, allowed = [], [] +in_ovl = lambda a: ovl_start <= a < ovl_end + +# 2a. boot-time constructors +ia = names.index(".flash.init_array") if ".flash.init_array" in names else None +if ia is not None: + s = secs[ia] + for (w,) in struct.iter_unpack("> 7) & 31] = (((addr if op == 0x17 else 0) + (ins & 0xFFFFF000)) & 0xFFFFFFFF, addr) + elif ((op == 0x67 or op == 0x13) and not (ins >> 12) & 7) or op == 0x03 or op == 0x07: + # jalr / addi / loads (integer, FP): imm[11:0] at bit 20 + r = recent.pop((ins >> 15) & 31, None) + if r: + addr = base + 2 * k + imm = ins >> 20 + target = (r[0] + (imm - 4096 if imm & 2048 else imm)) & 0xFFFFFFFF + if addr - r[1] <= 256 and ovl_start <= target < ovl_end: + hits.append((r[1], target)) + elif op == 0x23 or op == 0x27: # stores: imm split + r = recent.get((ins >> 15) & 31) + if r: + addr = base + 2 * k + imm = ((ins >> 25) << 5) | ((ins >> 7) & 31) + target = (r[0] + (imm - 4096 if imm & 2048 else imm)) & 0xFFFFFFFF + if addr - r[1] <= 256 and ovl_start <= target < ovl_end: + hits.append((r[1], target)) + k += 2 + +callers = {} +for at, target in hits: + callers.setdefault(func_at(at), []).append((at, target)) +demangle([f[2] for f in callers if f]) +for f, targets in callers.items(): + at, target = targets[0] + file, sec = attribute(at) + core = core_of(file) + name = f[2] if f else f"{at:#x}" + what = (f"code: {name} [{file} {sec}] -> {target:#x} ({' / '.join(overlay_names(target))})" + + (f" and {len(targets) - 1} more" if len(targets) > 1 else "")) + # (ext_ram_data.c: .tab5_res's end, which is where the overlay starts) + if file.endswith(CART_FILES) or file.endswith(("(overlay.c.obj)", "(ext_ram_data.c.obj)")): + ok = True + elif core is None: + ok = False + elif not sec.startswith(".text"): + ok = True # the core's code in internal RAM + elif f is None or f[3] == 0: + ok = True # local: only its own object (the core's) calls it + else: + users = refs.get(demangled.get(f[2], f[2])) + ok = users is not None and all(core_of(u) == core for u in users) + if not ok: + what += f"; used by {', '.join(sorted({u for u in (users or ['?']) if core_of(u) != core})[:3])}" + (allowed if ok else problems).append(what) + +# 2c. resident data: addresses of overlay functions (the PSRAM data's +# initial copy in flash is attributed to its .ext_ram.data address) +img = symbols.get("tab5_ext_ram_data_image") +ext_start = symbols.get("_ext_ram_data_start", (0,))[0] +for i, s in enumerate(secs): + if (s[1] == 0 or not (s[2] & SHF_ALLOC) or in_ovl(s[3]) or names[i] == ".flash.tab5_ovl_store" + or (s[2] & SHF_EXECINSTR and not s[2] & SHF_WRITE and i != res_i)): + continue + data = section_bytes(i) if s[1] != SHT_NOBITS or i == res_i else None + if not data: + continue + words = array("I") + words.frombytes(data[: len(data) & ~3]) + for o in [o for o, w in enumerate(words) if w in ovl_func_starts]: + w = words[o] + addr = s[3] + 4 * o + if img and img[0] <= addr < img[0] + img[1]: + addr = ext_start + addr - img[0] + file, sec = attribute(addr) + if core_of(file) and not report: + allowed.append(None) # (named only when printed: naming is slow) + continue + what = f"data: {sec} [{file}] @{addr:#x} -> {w:#x} ({' / '.join(overlay_names(w))})" + (allowed if core_of(file) else problems).append(what) + +if report: + for a in allowed: + print("overlay_image: allowed", a) +if problems: + for p in sorted(set(problems)): + print("overlay_image: ERROR", p) + sys.exit(f"overlay_image: {len(set(problems))} references into the core overlay from code that is not in it " + "(see the script's docstring)") +print(f"overlay_image: checked: {len(allowed)} functions / tables reach into the overlay, all the carts', " + "the loader's or the cores' own")