Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ jobs:
esp_idf_version: ${{ env.IDF_VERSION }}
target: esp32p4
path: '.'
# the updater (ota_1) first: the emulator's build adds it to flash_args
# / flasher_args.json, so USB updates have an app to reboot into
command: 'idf.py -C updater build && idf.py build'

- name: Zip up firmware binaries
run: |
zip -j -r firmware-binaries.zip build/tab5-emu.bin build/bootloader/bootloader.bin build/partition_table/partition-table.bin build/flash_args build/flasher_args.json
zip -j -r firmware-binaries.zip build/tab5-emu.bin build/bootloader/bootloader.bin build/partition_table/partition-table.bin build/ota_data_initial.bin build/updater/tab5-emu-updater.bin build/flash_args build/flasher_args.json

- name: Upload Build Outputs
uses: actions/upload-artifact@v4
Expand Down
17 changes: 16 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ set(GAME_COMPONENTS
set(
COMPONENTS
main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer
${GAME_COMPONENTS} tab5-emu gui menu rom_info statistics
${GAME_COMPONENTS} tab5-emu gui menu rom_info statistics settings devlink
CACHE STRING
"List of components to include"
FORCE
Expand All @@ -82,3 +82,18 @@ set(
project(tab5-emu)

set(CMAKE_CXX_STANDARD 23)

# 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.
set(UPDATER_BIN "${CMAKE_CURRENT_LIST_DIR}/updater/build/tab5-emu-updater.bin")
if(EXISTS "${UPDATER_BIN}")
# (a copy in the build dir: flash_args lists it next to the others, and a
# rebuilt updater reconfigures this)
configure_file("${UPDATER_BIN}" "${CMAKE_BINARY_DIR}/updater/tab5-emu-updater.bin" COPYONLY)
partition_table_get_partition_info(updater_offset "--partition-type app --partition-subtype ota_1" "offset")
esptool_py_flash_target_image(flash updater "${updater_offset}" "${CMAKE_BINARY_DIR}/updater/tab5-emu-updater.bin")
else()
message(WARNING "no updater image (${UPDATER_BIN}): build it with idf.py -C updater build, then reconfigure, "
"or OTA updates and rollback have no updater to boot")
endif()
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,14 @@ git clone --recurse-submodules=components/jk/OpenJKDF2 \
https://github.com/esp-cpp/tab5-emu
cd tab5-emu
idf.py set-target esp32p4
idf.py -C updater build # once: the updater app, which goes in ota_1
idf.py build flash monitor
```

The updater (`updater/`) is what over-USB updates (`tools/emulink`) reboot
into, and what a bad update rolls back to; with it built first, `idf.py
flash` writes it along with the emulator.

(Do not recurse into the engine's own submodules; they are desktop-only
dependencies.)

Expand Down Expand Up @@ -251,10 +256,12 @@ expect a reboot whenever the console re-enumerates (after the USB drive).

Settings > "USB drive" exposes the SD card as a USB mass storage device on
the USB-C port, so ROMs, boxart and game data can be copied without pulling
the card. While the drive is on the serial console is off (the Tab5's
USB-C carries the P4's full-speed USB PHY, which the console and the USB
device controller share) and the launcher cannot start games; switch it off
(eject first) to get the card, the console and the ROM list back.
the card. The console and the USB link stay up meanwhile (all three are
functions of one composite USB device), but nothing on the Tab5 can use the
card, so the launcher cannot start games. Ejecting the drive on the PC does
not hand it back by itself: eject it there, then switch "USB drive" off to
get the card and the updated ROM list back. `emulink drive on` / `emulink
drive off` do the same from a script (drive off ejects it first on macOS).

## License

Expand Down
10 changes: 10 additions & 0 deletions components/devlink/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
idf_component_register(
INCLUDE_DIRS "include"
SRC_DIRS "src"
PRIV_REQUIRES esp_system
REQUIRES app_update coredump dispatcher monitor system tab5-emu)
# the two-slot OTA service: off on the Tab5, whose app does not fit twice (an
# update goes through the updater app in ota_1, see updater/)
target_compile_definitions(${COMPONENT_LIB} PUBLIC DEVLINK_HAS_OTA=0)
# keep the last panic's reason across the reset (DevLink::last_panic())
target_link_options(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=esp_panic_handler" "-Wl,--wrap=panic_abort")
7 changes: 7 additions & 0 deletions components/devlink/idf_component.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## IDF Component Manager Manifest File
dependencies:
idf: '>=6.0'
espp/coredump: '>=1.4.2'
espp/dispatcher: '>=1.4.2'
espp/monitor: '>=1.4.2'
espp/system: '>=1.4.2'
112 changes: 112 additions & 0 deletions components/devlink/include/devlink.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#pragma once

#include <memory>
#include <string>

#include "coredump.hpp"
#include "coredump_service.hpp"
#include "dispatcher_worker.hpp"
#include "monitor_service.hpp"
#include "system_service.hpp"

#include <esp_heap_caps.h>
#include <esp_system.h>

#include "box-emu.hpp"

/// Check the heap around every flash-touching request (debugging aid).
#ifndef DEVLINK_HEAP_CHECK
#define DEVLINK_HEAP_CHECK 0
#endif
#if DEVLINK_HAS_OTA
#include "ota.hpp"
#include "ota_service.hpp"
#endif

/// A module whose requests touch the flash (erase / write / read), run under
/// the launcher's LVGL lock. While the flash is busy the cache is off and only
/// interrupt handlers placed in internal RAM run; the display's SPI "transfer
/// done" interrupt is one and calls into LVGL (flash / PSRAM): a screen update
/// finishing during an OTA erase panics (esp-box-emu). LVGL waits for its
/// transfers before it lets go of the lock, so none is in flight meanwhile.
template <espp::DispatcherModuleConcept Module> class FlashGuarded {
public:
explicit FlashGuarded(Module &module) : module_(module) {}
uint8_t module_id() const { return module_.module_id(); }
espp::DispatcherModuleInfo module_info() const { return module_.module_info(); }
void handle(const espp::stream_frame::Frame &frame) {
std::lock_guard<std::recursive_mutex> lk(BoxEmu::lvgl_mutex());
#if DEVLINK_HEAP_CHECK
if (!heap_caps_check_integrity_all(true)) abort_corrupt("before", frame);
#endif
module_.handle(frame);
#if DEVLINK_HEAP_CHECK
if (!heap_caps_check_integrity_all(true)) abort_corrupt("after", frame);
#endif
}

protected:
#if DEVLINK_HEAP_CHECK
[[noreturn]] static void abort_corrupt(const char *when, const espp::stream_frame::Frame &frame) {
static char msg[80];
const bool internal_ok = heap_caps_check_integrity(MALLOC_CAP_INTERNAL, false);
const bool psram_ok = heap_caps_check_integrity(MALLOC_CAP_SPIRAM, false);
snprintf(msg, sizeof(msg), "heap corrupt %s request: internal %s, psram %s (frame @%p)", when,
internal_ok ? "ok" : "BAD", psram_ok ? "ok" : "BAD", (const void *)&frame);
esp_system_abort(msg);
}
#endif
Module &module_;
};

/// The framed services on the composite USB device's vendor interface, one
/// espp::DispatcherWorker routing them (shared by esp-box-emu and tab5-emu):
///
/// | module | service | host tool |
/// |--------|-------------------------------------------|--------------------------|
/// | 0 | OTA (DEVLINK_HAS_OTA: a two-slot layout) | espp_ota, emulink ota |
/// | 4 | core dump of the last crash | espp_coredump, emulink |
/// | 7 | system info, reboot, ROM download mode | emulink reboot |
/// | 8 | heap / task monitor | the espp Device Hub |
/// | 0x20 | test control (registered by the app) | emulink |
///
/// The device answers discovery, so the hosted espp web consoles find them.
class DevLink {
public:
struct Config {
std::string device_name; ///< advertised through discovery
std::string firmware; ///< firmware version, advertised through discovery
};

explicit DevLink(const Config &config);
~DevLink();

/// Register an application module (e.g. the test control service).
template <espp::DispatcherModuleConcept Module> void register_module(Module &module) {
worker_->register_module(module);
}

/// Send one frame to the host (serialized; all or nothing).
static void send(std::span<const uint8_t> frame);

/// The running image booted after an update and has not been confirmed
/// yet: confirm it (call once the app is up). No-op otherwise.
static void mark_app_valid();

/// After a panic reset: what it was ("reason (detail) at PC on core N"),
/// kept in RTC memory (no core dump needed); "" otherwise.
static std::string last_panic();

protected:
std::unique_ptr<espp::DispatcherWorker> worker_;
espp::CoreDump core_dump_;
std::unique_ptr<espp::CoreDumpService> core_dump_service_;
std::unique_ptr<FlashGuarded<espp::CoreDumpService>> core_dump_guarded_;
std::unique_ptr<espp::SystemService> system_service_;
std::unique_ptr<espp::MonitorService> monitor_service_;
#if DEVLINK_HAS_OTA
std::unique_ptr<espp::Ota> ota_;
std::unique_ptr<espp::OtaService> ota_service_;
std::unique_ptr<FlashGuarded<espp::OtaService>> ota_guarded_;
#endif
};
165 changes: 165 additions & 0 deletions components/devlink/src/devlink.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
#include "devlink.hpp"

#include <algorithm>
#include <cstring>
#include <iterator>

#include <esp_attr.h>
#include <esp_ota_ops.h>
#include <sdkconfig.h>
#if CONFIG_IDF_TARGET_ARCH_XTENSA
#include <esp_cpu_utils.h>
#endif
#include <esp_debug_helpers.h>
#include <esp_private/panic_internal.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>

#include "box-emu.hpp"

void DevLink::send(std::span<const uint8_t> frame) { BoxEmu::get().vendor_write(frame); }

DevLink::DevLink(const Config &config) {
auto &emu = BoxEmu::get();
worker_ = std::make_unique<espp::DispatcherWorker>(espp::DispatcherWorker::Config{
.send = &DevLink::send,
.on_overflow =
[this]() {
#if DEVLINK_HAS_OTA
if (ota_service_) ota_service_->on_rx_overflow();
#endif
},
// ~3.5 KB used at the high-water mark (file transfers, core dump reads);
// internal RAM, since the core dump service reads the flash
.task_config = {.name = "devlink", .stack_size_bytes = 6144},
});
core_dump_service_ = std::make_unique<espp::CoreDumpService>(core_dump_, espp::CoreDumpService::Config{
.send = &DevLink::send,
});
system_service_ = std::make_unique<espp::SystemService>(espp::SystemService::Config{
.send = &DevLink::send,
.on_reboot_request =
[](espp::SystemService::RebootKind kind) {
if (kind == espp::SystemService::RebootKind::Bootloader) {
BoxEmu::get().usb_prepare_for_rom_download();
}
return true;
},
});
monitor_service_ = std::make_unique<espp::MonitorService>(espp::MonitorService::Config{
.send = &DevLink::send,
});
core_dump_guarded_ = std::make_unique<FlashGuarded<espp::CoreDumpService>>(*core_dump_service_);
worker_->register_module(*core_dump_guarded_);
worker_->register_module(*system_service_);
worker_->register_module(*monitor_service_);
#if DEVLINK_HAS_OTA
ota_ = std::make_unique<espp::Ota>(espp::Ota::Config{});
ota_service_ = std::make_unique<espp::OtaService>(*ota_, espp::OtaService::Config{
.send = &DevLink::send,
});
ota_guarded_ = std::make_unique<FlashGuarded<espp::OtaService>>(*ota_service_);
worker_->register_module(*ota_guarded_);
#endif
worker_->serve_discovery(config.device_name, config.firmware);
emu.set_vendor_rx([this](std::span<const uint8_t> data) { worker_->push(data); });
}

DevLink::~DevLink() { BoxEmu::get().set_vendor_rx(nullptr); }

void DevLink::mark_app_valid() {
esp_ota_img_states_t state;
const esp_partition_t *running = esp_ota_get_running_partition();
if (running && esp_ota_get_state_partition(running, &state) == ESP_OK && state == ESP_OTA_IMG_PENDING_VERIFY) {
esp_ota_mark_app_valid_cancel_rollback();
fmt::print("devlink: the updated firmware is up; marked valid\n");
}
}

// The last panic, kept across the reset in RTC memory: a crash in the middle of
// a flash operation (an OTA erase) cannot write its core dump, and the console
// is the USB CDC port, which dies with the chip. The wrappers run in the panic
// path (possibly with the cache off): IRAM, and only plain byte copies.
namespace {
struct LastPanic {
uint32_t magic;
uint32_t addr;
int32_t core;
int32_t exception;
char reason[64];
char detail[96];
char task[16];
uint32_t backtrace[20]; // Xtensa: the abort()'s caller chain
};
constexpr uint32_t kPanicMagic = 0x50414e43; // "PANC"
RTC_NOINIT_ATTR LastPanic s_last_panic;
DRAM_ATTR volatile bool s_aborting = false;
IRAM_ATTR void copy_str(char *dst, size_t n, const char *src) {
size_t i = 0;
if (src) {
for (; i + 1 < n && src[i]; ++i) dst[i] = src[i];
}
dst[i] = 0;
}
} // namespace

extern "C" void __real_esp_panic_handler(panic_info_t *info);
extern "C" IRAM_ATTR void __wrap_esp_panic_handler(panic_info_t *info) {
// an abort() gets here too (panic_abort() traps): keep its message
if (s_aborting) {
__real_esp_panic_handler(info);
return;
}
s_last_panic.magic = kPanicMagic;
s_last_panic.addr = (uint32_t)info->addr;
s_last_panic.core = info->core;
s_last_panic.exception = (int32_t)info->exception;
copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), info->reason);
copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), info->description);
TaskHandle_t t = xTaskGetCurrentTaskHandle();
copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?");
std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0);
__real_esp_panic_handler(info);
}

extern "C" void __real_panic_abort(const char *details);
IRAM_ATTR void note_task_and_backtrace() {
TaskHandle_t t = xTaskGetCurrentTaskHandle();
copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?");
std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0);
#if CONFIG_IDF_TARGET_ARCH_XTENSA
esp_backtrace_frame_t frame{};
esp_backtrace_get_start(&frame.pc, &frame.sp, &frame.next_pc);
for (int i = 0; i < 20; ++i) {
s_last_panic.backtrace[i] = esp_cpu_process_stack_pc(frame.pc);
if (!esp_backtrace_get_next_frame(&frame)) break;
}
#endif
}

extern "C" IRAM_ATTR void __wrap_panic_abort(const char *details) {
s_aborting = true;
note_task_and_backtrace();
s_last_panic.magic = kPanicMagic;
s_last_panic.addr = 0;
s_last_panic.core = -1;
s_last_panic.exception = -1;
copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), "abort");
copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), details);
__real_panic_abort(details);
}

std::string DevLink::last_panic() {
if (esp_reset_reason() != ESP_RST_PANIC || s_last_panic.magic != kPanicMagic) {
return "";
}
s_last_panic.reason[sizeof(s_last_panic.reason) - 1] = 0;
s_last_panic.detail[sizeof(s_last_panic.detail) - 1] = 0;
s_last_panic.task[sizeof(s_last_panic.task) - 1] = 0;
std::string bt;
for (auto pc : s_last_panic.backtrace) {
if (pc) bt += fmt::format(" {:#010x}", pc);
}
return fmt::format("{} ({}) at {:#010x} on core {} in task '{}'{}{}", s_last_panic.reason, s_last_panic.detail,
s_last_panic.addr, s_last_panic.core, s_last_panic.task, bt.empty() ? "" : "; backtrace", bt);
}
6 changes: 4 additions & 2 deletions components/gba/include/gba.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
void reset_gba_core();
/// The ROM is read from the file (gpSP pages large ROMs from disk)
void init_gba(const std::string &rom_path);
void load_gba(std::string_view save_path);
void save_gba(std::string_view save_path);
/// false: no such state, or the core rejected it
bool load_gba(std::string_view save_path);
/// false: the core could not serialize, or the file was not written
bool save_gba(std::string_view save_path);
void run_gba_rom();
void deinit_gba();
std::span<uint8_t> get_gba_video_buffer();
Loading
Loading