diff --git a/docs/save-states.md b/docs/save-states.md new file mode 100644 index 0000000..35e4016 --- /dev/null +++ b/docs/save-states.md @@ -0,0 +1,108 @@ +# Save states + +BozoEngine saves the whole running game to a file and loads it back, in the same process or a new one, so a port +can come back to the same frame later (to test a scene, to debug, or for players). A loaded state goes on exactly as +the saved run did: a headless run of Jade Cocoon 2 saved at frame 9000 and loaded in a new process has the same EE RAM +1500 frames later as the run that never stopped. + +## What is saved + +A state is taken at the dispatcher's **safe point**, the top of `Dispatcher::run`'s loop. No guest code is on the +host stack there: every thread's registers are in its kernel frame, and no out-call, override or native IOP code is +running. Requests (`FreeHost::requestSave` / `requestLoad`, from any thread) wait for the next safe point. + +| Part | Section | Code | +| --- | --- | --- | +| EE RAM, scratchpad, VU0 data | `memory` | `Dispatcher::serialize` | +| Dispatcher clocks, counters, COP0 | `dispatcher` | `Dispatcher::serialize` | +| Threads and their frames, ready queues, semaphores, handlers, queued handlers, vblanks, deadlines | `kernel` | `Kernel::serialize` | +| Heap, pad, memory cards (in memory), CD, VU0 image, I/O, MPEG, SIF, timers, library continuations | `libraries` | `libs/libraries_state.cpp` | +| Frame count, last frame's clock | `host` | `FreeHost::serializeAll` | +| Whatever a port adds | its own name | `state::Sections` | + +The native IOP host (`native::irx::CompiledLibraries`) has `serialize` too: IOP memory, tasks and their registers, +semaphores, event flags, timers, events, frame listeners, the RPC servers IOP code registered, the mixer (voices, +reverb, sound memory) and libsd. A port that owns one adds it to its section (see below). + +What a port or host sets up once is **not** saved: overrides, callbacks, paths, switches, IRX images and bindings. The +loading run must be set up the same way (same build, same command line apart from the state options). A file +records a game tag (`FreeOptions::gameTag`) and a format version; a section that reads a different number of bytes +than was written fails the load with its name. + +## Continuations and deadlines are data + +Lambdas cannot be written to a file. Library code that leaves work for later passes a `libs::Resume` instead, a kind +plus four words: + +```cpp +l.waitVblank(token, -1, Resume{kResumeCdStreamRead, {n}}); +l.queueHandler(h, Resume{kResumeTimerHandlerEnd, {slot, tag, id}}); +l.scheduleDeadline(key, cycle, kDeadlineDelayDue, {thread, 0, 0}); +``` + +The kind picks a function from the libraries' table (`libraries.h`, `ResumeKind`, `NativeDeadlineKind`). A port adds +its own kinds from `kPortResumeKinds` / `kPortDeadlineKinds` with `Libraries::addResumeKind` / `addDeadlineKind`. +The `std::function` overloads still work, but while one is pending the state cannot be saved (a save waits and says +why). + +## Using it in a port + +```cpp +bozo::host::FreeOptions options; +options.gameTag = "SLUS-12345"; // a state loads only into the game that wrote it +options.loadState = "..."; // load before the first frame +options.loadStateFrame = 0; // or when this many frames have ended +options.saveState = "..."; // save when saveStateFrame frames have ended +options.saveStateFrame = 2000; +bozo::host::FreeHost host(options); + +// The port's own state: what it registered at run time, what it keeps about guest data. +host.stateSections()->add({"myport", + [&](bozo::state::Archive &a) { + myIop->serialize(a); // a native IOP host, if the port has one + bozo::state::fields(a, myCounter, myMap); // the port's own fields + if (a.loading()) + myTextureCache.clear(); // anything decoded from the old guest memory + }, + [] { return myIop->unsaveable(); }}); // optional: why it cannot be saved right now + +// Window builds: F5 save, F7 load, F6 / Shift+F6 pick the slot (0-9), and a "Save states" tab in F2. +game.saveState = [&](int slot) { host.requestSave(bozo::app::stateSlotPath(slot)); }; +game.loadState = [&](int slot) { host.requestLoad(bozo::app::stateSlotPath(slot)); }; +host.onStateMessage = [](bool, const std::string &m) { bozo::app::notify(m); }; +``` + +A port's section walks its fields with `bozo::state::fields` (scalars, enums, strings, `std::vector`, `deque`, +`map`, `unordered_map`, `set`, `array`, C arrays, `pair`, `unique_ptr`, and any struct with an `io(Archive &, T &)` +next to it). `state::pod` writes a trivially copyable struct with no pointers as its bytes. + +Things a port must think about: + +- **Run-time registrations.** Anything the game made the port register (a SIF RPC server bridged to EE code, a + callback) must be kept as data in the section and registered again on load, after dropping the ones of the run + being replaced (a load can happen mid-run, from F7). +- **Caches of guest data.** Textures, meshes or pictures keyed by guest addresses are stale after a load: clear them. +- **Facts the game told the port once.** If the port noted something as the game loaded it (where a resource sits), + save it: the loaded state will not tell it again. + +## Not covered yet + +- The 989SND driver (`libs::SndDriver` with its engine) and a playing movie (the decoder): a save waits, with the + reason, until they are idle. +- Recorded and pinned runs (`--out`, the reference harness): their records do not follow a load. + +A failed load in the middle of a run puts the state back as it was (the runtime saves itself first); a failed load +before the first frame ends the run. + +## Checking a port + +Headless runs are deterministic, so a state can be checked against a run that never stopped: + +``` +game --headless --frames 3000 --save-state s.state --save-state-at 2000 --dump-ram a.bin +game --headless --frames 3000 --load-state s.state --dump-ram b.bin # a new process +game --headless --frames 3000 --load-state s.state --load-state-at 2500 --dump-ram c.bin # a load mid-run +``` + +`a.bin`, `b.bin` and `c.bin` must be identical. `tests/runtime/state_tests.cpp` covers the archive, the files and a +dispatcher saved and loaded. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 704ac7e..e138030 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3,6 +3,7 @@ # per-frame reference record (bozo/reference.h); the native libraries (bozo/libs/). add_library(bozo_runtime_core STATIC core/runtime_core.cpp + core/state.cpp ee/kernel.cpp ee/dispatcher.cpp harness/reference.cpp) @@ -23,10 +24,13 @@ target_compile_options(bozo_audio PRIVATE -Wall -Wextra -ffp-contract=off) add_library(bozo_libs STATIC native/compiled_libraries.cpp libs/libraries.cpp + libs/libraries_state.cpp + audio/audio_state.cpp libs/libc.cpp libs/libm.cpp libs/gs.cpp libs/pad.cpp + libs/pad2.cpp libs/timer.cpp libs/mc.cpp libs/cd.cpp diff --git a/runtime/app/panel.cpp b/runtime/app/panel.cpp index 9f62fbe..f901af8 100644 --- a/runtime/app/panel.cpp +++ b/runtime/app/panel.cpp @@ -13,6 +13,7 @@ #include "bozo/app/input_bindings.h" #include "bozo/app/settings_tabs.h" #include "bozo/app/video_settings.h" +#include "bozo/app/window.h" #include @@ -21,9 +22,12 @@ #include "imgui_impl_sdl3.h" #include +#include +#include #include #include #include +#include #include #include #include @@ -32,6 +36,11 @@ namespace bozo::app { + namespace + { + void drawNotice(); + } + struct Panel::Impl { SDL_Window *window = nullptr; @@ -133,8 +142,11 @@ namespace bozo::app binding.source == input::Source::MouseMove; if (!(mouse && ImGui::GetIO().WantCaptureMouse)) { + // config() takes the same (non-recursive) mutex: fetched before the lock, as the other callers do. + // Under the lock it threw "resource deadlock would occur" at the first input after Add. + input::Config &config = input::config(); std::lock_guard lock(input::configMutex()); - std::vector &list = input::config().players[m.controlsPlayer].actions[m.bindingAction]; + std::vector &list = config.players[m.controlsPlayer].actions[m.bindingAction]; if (std::find(list.begin(), list.end(), binding) == list.end()) list.push_back(binding); m.bindingAction = -1; @@ -170,10 +182,111 @@ namespace bozo::app m.drawSettings(); if (m.overlay) m.drawOverlay(); + drawNotice(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } + // ---- Notices (notify): a save state's result, bottom left for a few seconds ---- + + namespace + { + std::mutex s_noticeMutex; + std::string s_notice; + std::chrono::steady_clock::time_point s_noticeAt; + + void drawNotice() + { + std::string text; + { + std::lock_guard lock(s_noticeMutex); + if (s_notice.empty() || std::chrono::steady_clock::now() - s_noticeAt > std::chrono::seconds(4)) + return; + text = s_notice; + } + const ImGuiViewport *viewport = ImGui::GetMainViewport(); + const float pad = 10.0f * ImGui::GetStyle().FontScaleDpi; + ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x + pad, viewport->WorkPos.y + viewport->WorkSize.y - pad), + ImGuiCond_Always, ImVec2(0.0f, 1.0f)); + ImGui::SetNextWindowBgAlpha(0.55f); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | + ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoInputs; + if (ImGui::Begin("##notice", nullptr, flags)) + ImGui::TextUnformatted(text.c_str()); + ImGui::End(); + } + } + + void notify(const std::string &text) + { + std::lock_guard lock(s_noticeMutex); + s_notice = text; + s_noticeAt = std::chrono::steady_clock::now(); + } + + std::string stateSlotPath(int slot) + { + std::filesystem::path dir = userDirectory().empty() ? std::filesystem::path("states") : userDirectory() / "states"; + std::error_code ec; + std::filesystem::create_directories(dir, ec); + return (dir / ("slot" + std::to_string(slot) + ".state")).string(); + } + + std::string stateSlotSummary(int slot) + { + const std::filesystem::path path = stateSlotPath(slot); + std::error_code ec; + const auto written = std::filesystem::last_write_time(path, ec); + if (ec) + return "Slot " + std::to_string(slot) + ": empty"; + const auto system = std::chrono::clock_cast(written); + const std::time_t t = std::chrono::system_clock::to_time_t(system); + char when[32] = ""; + if (const std::tm *local = std::localtime(&t)) + std::strftime(when, sizeof when, "%Y-%m-%d %H:%M", local); + return "Slot " + std::to_string(slot) + ": saved " + when; + } + + namespace + { + std::atomic s_stateSlot{0}; + } + int stateSlot() { return s_stateSlot.load(std::memory_order_relaxed); } + void setStateSlot(int slot) { s_stateSlot.store(((slot % kStateSlots) + kStateSlots) % kStateSlots); } + + void registerStateTab(std::function save, std::function load) + { + ui::registerTab("Save states", [save, load] { + ImGui::TextDisabled("F5 saves the selected slot, F7 loads it, F6 / Shift+F6 selects the next / previous."); + ImGui::Separator(); + for (int slot = 0; slot < kStateSlots; ++slot) + { + ImGui::PushID(slot); + const std::string summary = stateSlotSummary(slot); + if (ImGui::RadioButton(summary.c_str(), stateSlot() == slot)) + setStateSlot(slot); + ImGui::SameLine(ImGui::GetContentRegionAvail().x - 120.0f * ImGui::GetStyle().FontScaleDpi); + if (ImGui::Button("Save")) + { + setStateSlot(slot); + save(slot); + } + ImGui::SameLine(); + ImGui::BeginDisabled(summary.ends_with(": empty")); + if (ImGui::Button("Load")) + { + setStateSlot(slot); + load(slot); + } + ImGui::EndDisabled(); + ImGui::PopID(); + } + ImGui::Separator(); + ImGui::TextDisabled("Files: %s", std::filesystem::path(stateSlotPath(0)).parent_path().string().c_str()); + }); + } + // ---- F3: the frame rate counter ---- void Panel::Impl::drawOverlay() diff --git a/runtime/app/window.cpp b/runtime/app/window.cpp index 76e11d0..b301c44 100644 --- a/runtime/app/window.cpp +++ b/runtime/app/window.cpp @@ -196,6 +196,8 @@ namespace bozo::app Panel panel; if (options.panel) panel.init(window, context); + if (game.saveState && game.loadState) + registerStateTab(game.saveState, game.loadState); GameThread thread; thread.game = &game; @@ -284,7 +286,16 @@ namespace bozo::app quit = true; else if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) { - if (event.key.scancode == SDL_SCANCODE_F8 && sequenceLeft == 0) + if (event.key.scancode == SDL_SCANCODE_F5 && game.saveState) + game.saveState(stateSlot()); + else if (event.key.scancode == SDL_SCANCODE_F7 && game.loadState) + game.loadState(stateSlot()); + else if (event.key.scancode == SDL_SCANCODE_F6 && game.saveState) + { + setStateSlot(stateSlot() + ((event.key.mod & SDL_KMOD_SHIFT) ? -1 : 1)); + notify(stateSlotSummary(stateSlot())); + } + else if (event.key.scancode == SDL_SCANCODE_F8 && sequenceLeft == 0) sequenceLeft = -1; // starts at this present else if (event.key.scancode == SDL_SCANCODE_F9) { diff --git a/runtime/audio/audio_state.cpp b/runtime/audio/audio_state.cpp new file mode 100644 index 0000000..29c7a84 --- /dev/null +++ b/runtime/audio/audio_state.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +// Save states of the native mixer and libsd (bozo/state.h). Built into bozo_libs, which has the archive. +#include "bozo/audio/libsd.h" +#include "bozo/audio/mixer.h" +#include "bozo/state.h" + +namespace bozo::audio +{ + using state::fields; + using state::pod; + + void Mixer::serialize(state::Archive &a, const uint8_t *inputBase, size_t inputBytes) + { + std::scoped_lock lock(m_mutex, m_queueMutex, m_digestMutex); + a.begin("mixer"); + pod(a, m_stats); + fields(a, m_clocked, m_clockStarted, m_samplesMade, m_memory, m_digestHash, m_digestCount); + for (Group &g : m_groups) + { + for (Voice &v : g.voices) + pod(a, v); + fields(a, g.ended, g.dry, g.wet, g.mix); + for (Volume &v : g.master) + pod(a, v); + for (Volume &v : g.effect) + pod(a, v); + pod(a, g.reverb); + Input &in = g.input; + uint64_t offset = ~0ull; + if (!a.loading() && in.memory) + { + if (!inputBase || in.memory < inputBase || in.memory >= inputBase + inputBytes) + throw state::Error("save state: a mixer input plays from memory outside the IOP's"); + offset = static_cast(in.memory - inputBase); + } + fields(a, offset, in.samples, in.position, in.playing, in.loop, in.volume); + if (a.loading()) + { + if (offset != ~0ull && (!inputBase || offset >= inputBytes)) + throw state::Error("save state: a mixer input outside the IOP's memory"); + in.memory = offset == ~0ull ? nullptr : inputBase + offset; + } + } + a.end(); + if (a.loading()) + { + // What was mixed for the host belongs to the old state. + m_queueRead = m_queueFill = 0; + } + } + + void Libsd::serialize(state::Archive &a) + { + a.begin("libsd"); + State &s = m_state; + fields(a, s.params, s.switches, s.addresses, s.coreAttributes, s.transferAddress, s.irqCallback, s.blockBuffer, + s.blockSize, s.halves, s.halvesPending, s.effectEnd); + for (Callback &c : s.transCallback) + pod(a, c); + for (Callback &c : s.transHandler) + pod(a, c); + for (auto &e : s.effect) + pod(a, e); + a.end(); + } +} diff --git a/runtime/core/runtime_core.cpp b/runtime/core/runtime_core.cpp index 3ee1751..becefd7 100644 --- a/runtime/core/runtime_core.cpp +++ b/runtime/core/runtime_core.cpp @@ -70,10 +70,21 @@ namespace bozo (count && !functions) || (resumeCount && !resume)) throw std::invalid_argument("invalid native module registration"); modules_.push_back({start, end, resident, std::move(identity), functions, count, resume, resumeCount}); + modulesLow_ = std::min(modulesLow_, start); + modulesHigh_ = std::max(modulesHigh_, end); + lastModule_ = nullptr; // the vector may have moved } const FunctionTable::Module *FunctionTable::moduleAt(uint32_t address, bool &reserved) const { + if (address < modulesLow_ || address >= modulesHigh_) + return nullptr; + if (const Module *last = lastModule_; last && address >= last->start && address < last->end && + std::memcmp(last->resident, last->identity.data(), last->identity.size()) == 0) + { + reserved = true; + return last; + } const Module *active = nullptr; for (const Module &module : modules_) { @@ -86,6 +97,8 @@ namespace bozo throw std::runtime_error("ambiguous native module identity"); active = &module; } + if (active) + lastModule_ = active; return active; } diff --git a/runtime/core/state.cpp b/runtime/core/state.cpp new file mode 100644 index 0000000..3c00465 --- /dev/null +++ b/runtime/core/state.cpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: MIT +// Save state archives and files (bozo/state.h). +#include "bozo/state.h" + +#include + +namespace bozo::state +{ + namespace + { + constexpr char kMagic[8] = {'B', 'O', 'Z', 'O', 'S', 'A', 'V', 'E'}; + constexpr uint32_t kVersion = 1; + } + + void Archive::raw(void *p, size_t n) + { + if (!n) + return; + if (!loading_) + { + const auto *b = static_cast(p); + data_.insert(data_.end(), b, b + n); + return; + } + const size_t limit = open_.empty() ? data_.size() : open_.back().second; + if (n > limit - pos_) + throw Error("save state: section " + (open_.empty() ? std::string("") : open_.back().first) + + " ends before its fields"); + std::memcpy(p, data_.data() + pos_, n); + pos_ += n; + } + + void Archive::begin(const char *name) + { + std::string n = name; + io(*this, n); + if (loading_ && n != name) + throw Error("save state: expected section " + std::string(name) + ", found " + n); + uint64_t size = 0; + const size_t at = loading_ ? pos_ : data_.size(); + raw(&size, sizeof size); + if (!loading_) + open_.emplace_back(name, at); + else + { + if (size > data_.size() - pos_) + throw Error("save state: section " + n + " runs past the file"); + open_.emplace_back(name, pos_ + size); + } + } + + void Archive::end() + { + if (open_.empty()) + throw Error("save state: a section ended twice"); + const auto [name, at] = open_.back(); + open_.pop_back(); + if (!loading_) + { + const uint64_t size = data_.size() - at - sizeof(uint64_t); + std::memcpy(data_.data() + at, &size, sizeof size); + } + else if (pos_ != at) + throw Error("save state: section " + name + " has " + std::to_string(at - pos_) + + " bytes its reader did not take (a different build wrote it?)"); + } + + void writeFile(const std::string &path, const std::string &game, const Archive &a) + { + const std::string temp = path + ".tmp"; + std::FILE *f = std::fopen(temp.c_str(), "wb"); + if (!f) + throw Error("save state: cannot write " + temp); + Archive header; + std::string tag = game; + uint32_t version = kVersion; + header.raw(const_cast(kMagic), sizeof kMagic); + io(header, version); + io(header, tag); + const bool ok = std::fwrite(header.data().data(), 1, header.data().size(), f) == header.data().size() && + std::fwrite(a.data().data(), 1, a.data().size(), f) == a.data().size(); + if (std::fclose(f) != 0 || !ok) + { + std::remove(temp.c_str()); + throw Error("save state: cannot write " + temp); + } + std::remove(path.c_str()); + if (std::rename(temp.c_str(), path.c_str()) != 0) + throw Error("save state: cannot rename " + temp + " to " + path); + } + + Archive readFile(const std::string &path, const std::string &game) + { + std::FILE *f = std::fopen(path.c_str(), "rb"); + if (!f) + throw Error("save state: cannot open " + path); + std::vector bytes; + uint8_t buffer[1 << 16]; + for (size_t n; (n = std::fread(buffer, 1, sizeof buffer, f)) != 0;) + bytes.insert(bytes.end(), buffer, buffer + n); + std::fclose(f); + Archive header(std::move(bytes)); + char magic[sizeof kMagic]; + header.raw(magic, sizeof magic); + if (std::memcmp(magic, kMagic, sizeof kMagic) != 0) + throw Error("save state: " + path + " is not a save state"); + uint32_t version = 0; + std::string tag; + io(header, version); + io(header, tag); + if (version != kVersion) + throw Error("save state: " + path + " has format " + std::to_string(version) + ", this build reads " + + std::to_string(kVersion)); + if (tag != game) + throw Error("save state: " + path + " is for " + tag + ", not " + game); + // The rest, as an archive of its own. + std::vector rest; + const size_t used = sizeof kMagic + sizeof version + sizeof(uint64_t) + tag.size(); + rest.assign(header.data().begin() + static_cast(used), header.data().end()); + return Archive(std::move(rest)); + } +} diff --git a/runtime/ee/dispatcher.cpp b/runtime/ee/dispatcher.cpp index c427338..08993cc 100644 --- a/runtime/ee/dispatcher.cpp +++ b/runtime/ee/dispatcher.cpp @@ -705,6 +705,12 @@ namespace bozo::ee { for (;;) { + if (safePointDue.load(std::memory_order_relaxed)) + { + safePointDue.store(false, std::memory_order_relaxed); + if (safePoint) + safePoint(); + } kernel_.setOrigin(kOriginEvents); if (pinned) while (eventDue(nullptr, cycle_)) @@ -1143,3 +1149,30 @@ namespace bozo::ee } } } + +namespace bozo::ee +{ + std::string Dispatcher::unsaveable() const + { + if (inGuest_ || current_ || outcallDepth_ || syscall_ || rt_.stopDeferred || stopJump_) + return "guest code is running (not at the dispatcher's safe point)"; + return kernel_.unsaveable(); + } + + void Dispatcher::serialize(state::Archive &a) + { + if (const std::string why = unsaveable(); !why.empty()) + throw state::Error("save state: " + why); + a.begin("memory"); + a.raw(rt_.memory.flat(), kFlatBytes); + a.end(); + a.begin("dispatcher"); + state::fields(a, rt_.cop0Status, osdConfig, osdConfig2, cycle_, pccr_, pcr_, perfSince_, epc_, errorEpc_, + heapStart_, heapSize_, gsImr_, vsyncFlag_, vsyncCsr_, syncVCallback_, syncVGp_, syncVAtVblank_, + framesCompleted_, checkpoints_, sliceStart_, timerPending_, outcallCheckpoints_, recentPcs_, + recentNext_, lastThread_, lastDepth_, lastHandlerEnded_, started_, deferredPc_, dispatches, stops, + handlersRun, jumps); + a.end(); + kernel_.serialize(a); + } +} diff --git a/runtime/ee/kernel.cpp b/runtime/ee/kernel.cpp index a8e30df..22098e4 100644 --- a/runtime/ee/kernel.cpp +++ b/runtime/ee/kernel.cpp @@ -995,3 +995,88 @@ namespace bozo::ee vblankEnd(); } } + +namespace bozo::ee +{ + void Kernel::scheduleNative(uint32_t key, uint64_t cycle, uint32_t kind, std::array args, + std::function fn) + { + scheduleNative(key, cycle, std::move(fn)); + deadlines_[key].nativeKind = kind; + deadlines_[key].nativeArgs = args; + } + + // ---- Save states ---- + void io(state::Archive &a, QueuedHandler &h) + { + state::fields(a, h.kind, h.pc, h.a, h.gp, h.sp, h.ra, h.aHigh, h.completion, h.sequence, h.tag); + } + void io(state::Archive &a, Frame &f) + { + state::pod(a, f.ctx); + state::pod(a, f.last); + state::fields(a, f.status, f.ran, f.parkedStack, f.kind, f.pc, f.a, f.gp, f.sp, f.ra, f.completion, f.sequence, + f.tag); + } + void io(state::Archive &a, Thread &t) + { + state::fields(a, t.id, t.state, t.priority, t.initPriority, t.entry, t.stack, t.stackSize, t.gp, t.attr, t.option, + t.arg, t.waitReason, t.waitObject, t.flagBits, t.flagMode, t.waitToken, t.fixedResult, + t.waitCompletion, t.completionDue, t.wakeupCount, t.pseudo, t.handlerSlot, t.frames); + } + void io(state::Archive &a, InterruptHandler &h) + { + state::fields(a, h.id, h.cause, h.pc, h.arg, h.gp, h.sp, h.enabled); + } + void io(state::Archive &a, Semaphore &s) + { + state::fields(a, s.id, s.count, s.max, s.init, s.attr, s.option, s.waiters); + } + + std::string Kernel::unsaveable() const + { + if (depth_) + return "inside a kernel operation"; + for (const auto &[key, d] : deadlines_) + if (d.native && !d.nativeKind) + return "a native deadline (key 0x" + std::to_string(key) + ") has no saveable kind"; + return {}; + } + + void Kernel::serialize(state::Archive &a) + { + a.begin("kernel"); + state::fields(a, vblankHandler_, origin_, originCall_, threads_, ready_, readyMask_, running_, switchRequested_, + picks_, nextPseudo_, handlerSlots_, ownedHandlerStacks_, nextThreadId_, nextSemaId_, + nextIntcHandler_, nextDmacHandler_, semas_, intc_, dmac_, nextHandlerId_, intcMask_, dmacMask_, + intcPending_, dmacPending_, queued_, sequence_, vblankCount_, fieldCycles_, lines_, nextStart_, + nextEnd_); + uint64_t n = state::count(a, deadlines_.size()); + if (!a.loading()) + for (auto &[key, d] : deadlines_) + { + uint32_t k = key; + state::fields(a, k, d.cycle, d.handler, d.nativeKind, d.nativeArgs); + } + else + { + deadlines_.clear(); + for (uint64_t i = 0; i < n; ++i) + { + uint32_t key = 0; + Deadline d; + state::fields(a, key, d.cycle, d.handler, d.nativeKind, d.nativeArgs); + if (d.nativeKind) + { + if (!nativeRebuild) + throw state::Error("save state: a native deadline but no rebuilder"); + d.native = nativeRebuild(d.nativeKind, d.nativeArgs); + if (!d.native) + throw state::Error("save state: unknown native deadline kind " + std::to_string(d.nativeKind)); + } + deadlines_[key] = std::move(d); + } + } + a.end(); + } +} diff --git a/runtime/host/free_host.cpp b/runtime/host/free_host.cpp index 0b273d4..b54f982 100644 --- a/runtime/host/free_host.cpp +++ b/runtime/host/free_host.cpp @@ -138,6 +138,7 @@ namespace bozo::host std::memcpy(&entry, elf.bytes().data() + 24, 4); d.boot(entry, 0x1FFFFF0u); d.kernel().useOwnedHandlerStacks(); + d.safePoint = [this] { atSafePoint(); }; if (!opt_.out.empty()) { reference::Header h; @@ -154,6 +155,8 @@ namespace bozo::host uint64_t FreeHost::run() { + if (!opt_.loadState.empty() && !opt_.loadStateFrame) + requestLoad(opt_.loadState); startSoundWatcher(); try { @@ -339,6 +342,15 @@ namespace bozo::host } if (soundDue_.load(std::memory_order_relaxed)) stallSound(ctx); + if (opt_.advanceLibrariesWhileStalled && opt_.sound && libs_.audioProvider) + { + const uint64_t at = ctx ? d_->now(ctx) : d_->now(), quarter = d_->kernel().field() / 4; + if (at - lastFrameCycle_ > d_->kernel().field() && at - lastStallAdvance_ >= quarter) + { + lastStallAdvance_ = at; + libs_.audioProvider(at); + } + } if (!opt_.stallFields) return; const uint64_t now = d_->now(ctx); @@ -565,6 +577,13 @@ namespace bozo::host libs_.framesEnded = static_cast(stats_.frames); det::frameCounter().store(stats_.frames, std::memory_order_relaxed); d_->frameCompleted(); + if (!opt_.saveState.empty() && stats_.frames == opt_.saveStateFrame) + requestSave(opt_.saveState); + if (!opt_.loadState.empty() && opt_.loadStateFrame && stats_.frames == opt_.loadStateFrame) + { + requestLoad(opt_.loadState); + opt_.loadStateFrame = 0; // once (the loaded state may pass this frame again) + } if (onFrame) onFrame(frame, ctx); if (opt_.frames && stats_.frames >= opt_.frames) @@ -579,3 +598,145 @@ namespace bozo::host } } } + +namespace bozo::host +{ + // ---- Save states ---- + void FreeHost::requestSave(const std::string &path) + { + { + std::lock_guard lock(stateMutex_); + saveTo_ = path; + saveWaiting_.clear(); + } + if (d_) + d_->safePointDue.store(true, std::memory_order_relaxed); + } + + void FreeHost::requestLoad(const std::string &path) + { + { + std::lock_guard lock(stateMutex_); + loadFrom_ = path; + } + if (d_) + d_->safePointDue.store(true, std::memory_order_relaxed); + } + + std::string FreeHost::unsaveable() + { + if (insideDepth_) + return "a port override is running"; + if (std::string why = d_->unsaveable(); !why.empty()) + return why; + if (std::string why = libs_.unsaveable(); !why.empty()) + return why; + for (const state::Section &s : sections_.all()) + if (s.unsaveable) + if (std::string why = s.unsaveable(); !why.empty()) + return s.name + ": " + why; + return {}; + } + + void FreeHost::serializeAll(state::Archive &a) + { + d_->serialize(a); + libs_.serialize(a); + a.begin("host"); + state::fields(a, stats_.frames, lastFrameCycle_); + a.end(); + for (state::Section &s : sections_.all()) + { + a.begin(s.name.c_str()); + s.serialize(a); + a.end(); + } + if (!a.atEnd() && a.loading()) + throw state::Error("save state: the file has sections this runtime does not know"); + if (a.loading()) + { + framesEnded_.store(stats_.frames, std::memory_order_relaxed); + libs_.framesEnded = static_cast(stats_.frames); + det::frameCounter().store(stats_.frames, std::memory_order_relaxed); + audio_.clear(); + render::Renderer::instance().takeFrameDraws(); + frameEndNs_.store(steadyNs(), std::memory_order_relaxed); + } + } + + void FreeHost::atSafePoint() + { + std::string save, load; + { + std::lock_guard lock(stateMutex_); + std::swap(save, saveTo_); + std::swap(load, loadFrom_); + } + auto report = [this](bool ok, const std::string &message) { + if (onStateMessage) + onStateMessage(ok, message); + else + std::fprintf(stderr, "[state] %s\n", message.c_str()); + }; + if (!load.empty()) + { + state::Archive backup; + bool backedUp = false; + try + { + state::Archive file = state::readFile(load, opt_.gameTag); + if (unsaveable().empty()) + { + serializeAll(backup); + backedUp = true; + } + serializeAll(file); + report(true, std::format("loaded {} (frame {})", load, stats_.frames)); + } + catch (const std::exception &e) + { + if (backedUp) + { + state::Archive restore(backup.data()); + serializeAll(restore); + report(false, std::format("{}; the state was put back as it was", e.what())); + } + else + { + // Nothing to go back to (a run that loads before its first frame): the run ends. + report(false, e.what()); + endReason_ = std::string("FAULT: ") + e.what(); + throw ee::EndRun{}; + } + } + } + if (!save.empty()) + { + if (const std::string why = unsaveable(); !why.empty()) + { + // Tried again at the next safe point. + std::lock_guard lock(stateMutex_); + if (saveTo_.empty()) + saveTo_ = save; + if (saveWaiting_ != why) + { + saveWaiting_ = why; + report(false, std::format("save to {} waits: {}", save, why)); + } + d_->safePointDue.store(true, std::memory_order_relaxed); + return; + } + try + { + state::Archive a; + serializeAll(a); + state::writeFile(save, opt_.gameTag, a); + report(true, std::format("saved {} (frame {}, {} MB)", save, stats_.frames, a.data().size() >> 20)); + } + catch (const std::exception &e) + { + report(false, e.what()); + } + } + } +} diff --git a/runtime/include/bozo/app/panel.h b/runtime/include/bozo/app/panel.h index 0446a3a..ab3e47b 100644 --- a/runtime/include/bozo/app/panel.h +++ b/runtime/include/bozo/app/panel.h @@ -12,6 +12,8 @@ // user folder. #pragma once +#include + #include struct SDL_Window; @@ -19,6 +21,12 @@ union SDL_Event; namespace bozo::app { + // Save states in the panel: the slot F5 / F7 use (F6 picks it) and the settings' "Save states" tab (each slot: + // when it was saved, Save, Load), registered by the window when the game has save states. + int stateSlot(); + void setStateSlot(int slot); + void registerStateTab(std::function save, std::function load); + class Panel { public: diff --git a/runtime/include/bozo/app/window.h b/runtime/include/bozo/app/window.h index 0a2277a..4ee7327 100644 --- a/runtime/include/bozo/app/window.h +++ b/runtime/include/bozo/app/window.h @@ -48,8 +48,20 @@ namespace bozo::app std::function run; // the game thread's body: runs until the game ends (its exit code) std::function stop; // any thread: asks the game to end std::function framesEnded; // any thread: the game frames ended so far + // Save states (bozo/state.h), from the window's thread, by slot (0-9): F6 / Shift+F6 picks the slot, F5 saves + // it, F7 loads it (unset: no keys). A FreeHost port sets them to requestSave / requestLoad of stateSlotPath(slot). + std::function saveState, loadState; }; + // A save state slot's file: the user folder's states/slotN.state (made when missing), or the current folder's + // when there is no user folder. + std::string stateSlotPath(int slot); + constexpr int kStateSlots = 10; + // "Slot 3: saved 2026-11-18 14:02" or "Slot 3: empty". + std::string stateSlotSummary(int slot); + // A short line shown over the game for a few seconds (any thread): a save state's result. + void notify(const std::string &text); + // Opens the window, runs the game on its own thread (a 256 MB stack: recompiled code nests deeply), presents until // the window closes or the game ends, then ends the game and closes. Returns the game's exit code (3 when the // window or its context could not be made). diff --git a/runtime/include/bozo/audio/libsd.h b/runtime/include/bozo/audio/libsd.h index e00db0b..15b5f4d 100644 --- a/runtime/include/bozo/audio/libsd.h +++ b/runtime/include/bozo/audio/libsd.h @@ -94,6 +94,7 @@ namespace bozo::audio // The transfer-end delay (IOP cycles) after a transfer or an input half. static constexpr uint32_t kTransferDelay = 2000u; + void serialize(state::Archive &a); // the settings and callbacks (audio_state.cpp) private: void sync(); diff --git a/runtime/include/bozo/audio/mixer.h b/runtime/include/bozo/audio/mixer.h index 69161c4..baa193e 100644 --- a/runtime/include/bozo/audio/mixer.h +++ b/runtime/include/bozo/audio/mixer.h @@ -27,6 +27,11 @@ #include #include +namespace bozo::state +{ + class Archive; +} + namespace bozo::audio { class PortStream; @@ -138,6 +143,9 @@ namespace bozo::audio int voicesPlaying = 0; }; Stats stats(); + // Save states (bozo/state.h; audio_state.cpp): voices, effects, sound memory. An input playing from host + // memory is saved as its offset from `inputBase` (the IOP memory it plays from). + void serialize(state::Archive &a, const uint8_t *inputBase, size_t inputBytes); private: struct Volume diff --git a/runtime/include/bozo/ee/dispatcher.h b/runtime/include/bozo/ee/dispatcher.h index 4df2ee6..b83e6ed 100644 --- a/runtime/include/bozo/ee/dispatcher.h +++ b/runtime/include/bozo/ee/dispatcher.h @@ -14,7 +14,9 @@ #include "bozo/ee/kernel.h" #include "bozo/runtime.h" +#include #include +#include #include #include #include @@ -125,6 +127,14 @@ namespace bozo::ee // The main thread starts at `entry` with sp `sp`; the dispatcher then runs until the host ends the run. void boot(uint32_t entry, uint32_t sp); + // Save states (bozo/state.h): `safePoint` runs at the top of the dispatch loop once `safePointDue` is set (from + // any thread). There no guest code is on the host stack: every thread's registers are in its kernel frame, so + // the state can be saved or replaced there. + std::function safePoint; + std::atomic safePointDue{false}; + // The dispatcher's state with the kernel's and guest memory. Only at the safe point. + void serialize(state::Archive &a); + std::string unsaveable() const; void run(); // ---- The native frame boundary (kernel.md section 2) ---- @@ -180,10 +190,12 @@ namespace bozo::ee bool insideOutcall() const { return outcallDepth_ != 0; } // Guest code an override runs on a context of its own (a copy: TMB's TMB_KILL_ENEMIES calls the game's // vehicleTakeHit on one) is not the thread's: it cannot stop or leave (nothing would run it on from its pc), - // so it runs to its return, no event taken and no stop made there (kernel.md section 3b). + // so it runs to its return, no event taken and no stop made there (kernel.md section 3b). Outside guest code + // (a host's out-call between threads: JC2's IOP modules calling the game's RPC handler as the IOP's clock is + // brought up) no thread's context is running, so every context an out-call runs is its own. bool ownContext(const R5900Context *ctx) const { - return outcallDepth_ && inGuest_ && currentFrame_ && ctx != ¤tFrame_->ctx; + return outcallDepth_ && (!inGuest_ || !currentFrame_ || ctx != ¤tFrame_->ctx); } // Leave guest code at `pc`: inside an out-call deferred (returns), else stop (does not return). void leave(R5900Context *ctx, uint32_t pc); diff --git a/runtime/include/bozo/ee/kernel.h b/runtime/include/bozo/ee/kernel.h index 824afa7..5d59f67 100644 --- a/runtime/include/bozo/ee/kernel.h +++ b/runtime/include/bozo/ee/kernel.h @@ -6,6 +6,8 @@ // contexts the kernel keeps for every thread and stacked handler. #pragma once +#include "bozo/state.h" + #include "bozo/context.h" #include "bozo/context_words.h" @@ -15,6 +17,7 @@ #include #include #include +#include #include namespace bozo::ee @@ -185,6 +188,9 @@ namespace bozo::ee uint64_t sequence = 0, tag = 0; }; + // Save states: a queued handler's fields (kernel.cpp). + void io(state::Archive &a, QueuedHandler &h); + struct InterruptHandler { int32_t id = 0; @@ -335,6 +341,16 @@ namespace bozo::ee bool cancelDeadline(uint32_t key); // The same deadline for native code: `fn` runs with the cycle it was due at, when events are taken. void scheduleNative(uint32_t key, uint64_t cycle, std::function fn); + // The same, saveable: `kind` and `args` say what `fn` does, so a loaded state rebuilds it (nativeRebuild). + // A deadline made without a kind keeps the runtime from saving its state while it is pending. + void scheduleNative(uint32_t key, uint64_t cycle, uint32_t kind, std::array args, + std::function fn); + using NativeRebuild = std::function(uint32_t kind, const std::array &)>; + NativeRebuild nativeRebuild; + // Save states (bozo/state.h): every field, at a dispatcher safe point. Loading replaces the kernel's state. + void serialize(state::Archive &a); + // Why the state cannot be saved now (empty: it can). + std::string unsaveable() const; // SetAlarm / ReleaseAlarm on the deadlines above: `due` is an absolute EE cycle; the handler runs as // handler(id, the horizontal blank count at `due`, arg). Returns the alarm's id (at most kAlarms pending), // -1 when every one is pending. ReleaseAlarm returns 0 while it is pending, else -1. @@ -397,7 +413,14 @@ namespace bozo::ee uint64_t fieldCycles_ = 0; uint32_t lines_ = 525; uint64_t nextStart_ = 0, nextEnd_ = 0; - struct Deadline { uint64_t cycle; QueuedHandler handler; std::function native; }; + struct Deadline + { + uint64_t cycle = 0; + QueuedHandler handler; + std::function native; + uint32_t nativeKind = 0; // 0: none, or a native deadline that cannot be saved + std::array nativeArgs{}; + }; std::map deadlines_; }; } diff --git a/runtime/include/bozo/host/free_host.h b/runtime/include/bozo/host/free_host.h index 372cb01..c13c02b 100644 --- a/runtime/include/bozo/host/free_host.h +++ b/runtime/include/bozo/host/free_host.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -45,9 +46,20 @@ namespace bozo::host // free mode), the frame's samples to onAudio and to the record's sound field. Off: the mixer runs only as the // driver's commands bring it up (nothing is output). bool sound = true; + // While no game frame ends (a game busy-waiting for its sound library before its first frame: The Third Age + // waits for EA's driver to answer a command), the watchdog brings the libraries' engine up to the EE clock, a + // few times a field. Off: only at frame ends (and, in real time with an output, at the sound watcher's stalls). + bool advanceLibrariesWhileStalled = false; // Optional native game-frame duration. Ports with host-paced frames can charge their logical // clock here instead of running a console timer/device loop. Zero keeps explicit port accounting. uint64_t framePeriodCycles = 0; + // Save states (bozo/state.h): load one before the first frame; save one when `saveStateFrame` frames have + // ended. `gameTag` names the game in the files (a state loads only into the game that wrote it). + std::string loadState; + uint32_t loadStateFrame = 0; // load it when this many frames have ended instead (0: before the first frame) + std::string saveState; + uint32_t saveStateFrame = 0; + std::string gameTag = "game"; }; inline constexpr uint32_t kCop0ConditionSite = 0xFFFFFFFFu; @@ -97,6 +109,15 @@ namespace bozo::host uint64_t framesEnded() const { return framesEnded_.load(std::memory_order_relaxed); } libs::Libraries &libraries() override { return libs_; } + // ---- Save states (bozo/state.h) ---- + // Asked from any thread (a hotkey); done at the dispatcher's next safe point. A save waits there until the + // state can be saved (a movie, IOP code running); a load that fails puts the state back as it was. + void requestSave(const std::string &path); + void requestLoad(const std::string &path); + state::Sections *stateSections() override { return §ions_; } + // What became of each request (default: printed to stderr). + std::function onStateMessage; + // ee::Host void libraryCall(ee::Dispatcher &, R5900Context *ctx, uint32_t target) override; void vu0Microprogram(ee::Dispatcher &, R5900Context *ctx, uint32_t address) override; @@ -134,6 +155,7 @@ namespace bozo::host // Ends the run when no frame ended for opt_.stallFields fields (a wait that never ends), saying where. void watchdog(R5900Context *ctx); uint64_t lastFrameCycle_ = 0; + uint64_t lastStallAdvance_ = 0; // advanceLibrariesWhileStalled: the EE cycle of the last advance void endFrame(R5900Context *ctx); void frameSound(uint64_t &hash, uint32_t &count); std::vector audio_; @@ -165,6 +187,13 @@ namespace bozo::host bool writing_ = false; std::string endReason_; libs::ScriptInput padScript_; + state::Sections sections_; + std::mutex stateMutex_; + std::string saveTo_, loadFrom_; + std::string saveWaiting_; // why the pending save waits (reported once) + void atSafePoint(); + std::string unsaveable(); + void serializeAll(state::Archive &a); std::atomic stopRequested_{false}; std::atomic framesEnded_{0}; }; diff --git a/runtime/include/bozo/libs/cd.h b/runtime/include/bozo/libs/cd.h index 16171c6..a267802 100644 --- a/runtime/include/bozo/libs/cd.h +++ b/runtime/include/bozo/libs/cd.h @@ -16,6 +16,7 @@ namespace bozo::libs // reference/tmb/README.md, the Midtown Suburbs freeze). constexpr uint64_t kSectorCycles = 114400; constexpr uint64_t kSeekCycles = 29491200; // 100 ms + constexpr uint32_t kReadDoneKey = 0x84000000u; // the kernel deadline a timed read's callback waits on // The game's disc: an ISO 9660 image of 2048-byte sectors (the user's own copy of the game). class DiscImage @@ -60,6 +61,10 @@ namespace bozo::libs // Native SDK completion registration; no private SDK worker/semaphores. uint32_t callback = 0, callbackGp = 0, callbackStack = 0; bool callbackConfigured = false; + // Off (the reference's timing): sceCdRead charges the drive's time to its caller and queues the callback as + // it returns. On: sceCdRead returns at once and the callback runs when the drive's time has passed, as on a + // PS2; the caller's other threads run meanwhile (JC2's menu clears a pointer the read's callback then sets). + bool timedCompletion = false; // The stream (sceCdStInit / sceCdStStart / sceCdStRead / sceCdStStop). uint32_t ringSectors = 0, banks = 0, iopBuffer = 0; diff --git a/runtime/include/bozo/libs/libraries.h b/runtime/include/bozo/libs/libraries.h index 9d37f36..0f6af94 100644 --- a/runtime/include/bozo/libs/libraries.h +++ b/runtime/include/bozo/libs/libraries.h @@ -14,6 +14,7 @@ #include "bozo/libs/sif.h" #include "bozo/libs/snd.h" #include "bozo/libs/timer.h" +#include "bozo/state.h" #include #include @@ -35,7 +36,7 @@ namespace bozo::libs kLibc = 1u << 0, // memcpy, memset, the string functions, sprintf/printf, malloc/free, rand/srand kLibm = 1u << 1, // sqrt and the float sine/cosine kernels kGs = 1u << 2, // the GS library (display and draw environments, uploads, syncs) - kPad = 1u << 3, // libpad + kPad = 1u << 3, // libpad, libpad2 and libvib kMc = 1u << 4, // libmc kCd = 1u << 5, // libcdvd: sectors and the stream from the disc image kVu0 = 1u << 6, // TMB's VU0 microprograms (VCALLMS) @@ -74,6 +75,34 @@ namespace bozo::libs class Libraries; using Handler = void (*)(Libraries &, Guest &); + // A library continuation that save states can keep (bozo/state.h): which one (a kind from the libraries' table) + // and its arguments. Kinds below kPortResumeKinds are BozoEngine's; a port adds its own from there + // (Libraries::addResumeKind). + struct Resume + { + uint32_t kind = 0; + std::array a{}; + }; + using ResumeFunction = void (*)(Libraries &, Guest &, const Resume &); + enum ResumeKind : uint32_t + { + kResumeNone = 0, + kResumeCdStreamRead = 1, // a[0]: the sectors asked for + kResumeMpegRelease = 2, // a[0]: the heap entry + kResumeMpegNodataEnd = 3, // a[0]: the waiting thread, a[1]: the entry, a[2]: 1 work area (no release), 2 SDK callback + kResumeMpegGetPicture = 4, // a[0]: rgb, a[1]: mbcount + kResumeMpegDeliver = 5, // a[0]: rgb, a[1]: mbcount + kResumeTimerHandlerEnd = 6, // a[0]: slot, a[1]: tag, a[2]: id + kPortResumeKinds = 0x1000, + }; + // Native kernel deadlines (ee::Kernel::scheduleNative) the libraries make, by kind. + enum NativeDeadlineKind : uint32_t + { + kDeadlineTimerFire = 1, // args: slot, tag + kDeadlineDelayDue = 2, // args: thread + kPortDeadlineKinds = 0x1000, + }; + struct Function { const char *name; // the game's symbol (a leading "ps2_" in a log's name is ignored) @@ -123,6 +152,7 @@ namespace bozo::libs uint32_t largestFree() const; uint32_t totalFree() const; size_t blocks() const { return used_.size(); } + void serialize(state::Archive &a); private: std::map free_; // address -> bytes @@ -149,7 +179,7 @@ namespace bozo::libs Libraries(); // The runtime the libraries serve (the kernel's operations, the heap's start). - void attach(ee::Dispatcher &d) { d_ = &d; } + void attach(ee::Dispatcher &d); ee::Dispatcher *dispatcher() { return d_; } // The native function for a symbol name, or nullptr. @@ -190,8 +220,24 @@ namespace bozo::libs // A handler queued by a library; `end` (if any) is its completion, run as it returns (origin handler-end). void queueHandler(const ee::QueuedHandler &h, std::function end); std::function takeHandlerEnd(uint64_t sequence); + // The same with saveable continuations (kind kResumeNone: none). + void waitVblank(uint64_t token, int32_t fixedResult, const Resume &then); + void waitFor(uint32_t reason, uint32_t object, uint64_t token, int32_t fixedResult, const Resume &then); + void queueHandler(const ee::QueuedHandler &h, const Resume &end); + // A port's continuation kinds (from kPortResumeKinds) and native deadline kinds (from kPortDeadlineKinds). + void addResumeKind(uint32_t kind, ResumeFunction f); + using DeadlineFunction = void (*)(Libraries &, const std::array &args, uint64_t due); + void addDeadlineKind(uint32_t kind, DeadlineFunction f); + // A kernel deadline the libraries can save: `f` (of kind `kind`) runs with `args` when it is due. + void scheduleDeadline(uint32_t key, uint64_t cycle, uint32_t kind, std::array args); Pin pin; + // ---- Save states (bozo/state.h) ---- + // Every library's state. Why it cannot be saved now (empty: it can): a continuation with no saveable kind, + // a movie playing, the 989SND driver (not covered yet). + std::string unsaveable() const; + void serialize(state::Archive &a); + // ---- VU0 microprograms ---- // The native program at `pc` of the image VU0 holds (null if none): it runs on the calling context's VU0 state // and VU0's data memory. @@ -211,6 +257,7 @@ namespace bozo::libs // turn it into DMA controller registers or execute a hardware environment. std::array dmaEnvironment{}; MpegState mpeg; + MpegOptions mpegOptions; SifState sif; TimerState timers; SndDriver snd; @@ -237,8 +284,16 @@ namespace bozo::libs ee::Dispatcher *d_ = nullptr; std::vector functions_; std::unordered_map byName_; - std::map> continuations_; - std::map> handlerEnds_; + struct Pending + { + std::function run; + Resume resume; // kind kResumeNone with `run` set: not saveable + }; + Pending pending(const Resume &r); + std::map continuations_; + std::map handlerEnds_; + std::map resumeKinds_; + std::map deadlineKinds_; }; // Each library's functions (libc.cpp, libm.cpp, gs.cpp, pad.cpp, mc.cpp). @@ -247,11 +302,18 @@ namespace bozo::libs void addGs(std::vector &out); void addDma(std::vector &out); void addPad(std::vector &out); + void addPad2(std::vector &out); void addMc(std::vector &out); void addCd(std::vector &out); void addMpeg(std::vector &out); // nothing without a video decoder (FFmpeg) void addSif(std::vector &out); void addTimer(std::vector &out); + // The libraries' continuations and deadlines by kind (cd.cpp, mpeg.cpp, timer.cpp). + void cdResume(Libraries &l, Guest &g, const Resume &r); + void mpegResume(Libraries &l, Guest &g, const Resume &r); + void timerResume(Libraries &l, Guest &g, const Resume &r); + void timerDeadline(Libraries &l, const std::array &args, uint64_t due); + void delayDeadline(Libraries &l, const std::array &args, uint64_t due); // Sectors of the game's disc (the CD library's image, opened on first use): false when there is none. bool discRead(Libraries &l, uint32_t lbn, uint32_t count, uint8_t *out); diff --git a/runtime/include/bozo/libs/mc.h b/runtime/include/bozo/libs/mc.h index aa5625c..918b014 100644 --- a/runtime/include/bozo/libs/mc.h +++ b/runtime/include/bozo/libs/mc.h @@ -3,6 +3,8 @@ // docs/specs/libraries.md section 7. #pragma once +#include "bozo/state.h" + #include #include #include @@ -27,6 +29,7 @@ namespace bozo::libs uint16_t attributes = 0; McDate created, modified; std::vector data; + uint64_t order = 0; // creation sequence: a card lists a directory in the order its entries were made }; // A formatted, empty card; `hostDirectory` non-empty: its files live there (loaded now, written as they @@ -37,7 +40,8 @@ namespace bozo::libs // Paths are the card's ("BASCUS-97101/icon.sys"), without a leading slash. Entry *find(const std::string &path); bool exists(const std::string &path) { return find(path) != nullptr; } - // The entries directly inside a directory ("" for the root), in name order. + // The entries directly inside a directory ("" for the root), in creation order (a game may count on it: + // JC2's slot list reads entry slot + 6 after icon.sys and three icons). std::vector list(const std::string &directory) const; Entry &create(const std::string &path, bool directory, const McDate &date); void changed(const std::string &path); // written back to the host file @@ -45,10 +49,12 @@ namespace bozo::libs void rename(const std::string &from, const std::string &to); void erase(); // every entry, on the host as well uint32_t freeClusters() const; + void serialize(state::Archive &a); // the entries (the host folder stays the runtime's) private: std::map entries_; std::string host_; + uint64_t next_ = 0; }; struct McState diff --git a/runtime/include/bozo/libs/mpeg.h b/runtime/include/bozo/libs/mpeg.h index 7cbc78d..7a768d9 100644 --- a/runtime/include/bozo/libs/mpeg.h +++ b/runtime/include/bozo/libs/mpeg.h @@ -59,6 +59,25 @@ namespace bozo::libs virtual void samples(const int16_t *frames, size_t count, int64_t pts) { (void)frames, (void)count, (void)pts; } }; + // How libmpeg answers a game: by default as TMB's reference build does (its sceMpeg layout, results and pacing). + // A port whose game uses libmpeg the SDK's way (The Third Age: sceMpegAddBs from a Nodata callback, its own + // pacing) sets them; they survive sceMpegCreate. + struct MpegOptions + { + // The reference's layout: sceMpegCreate writes its sceMpeg and work area (with TMB's addresses) and takes a + // block and each callback's data from the game's heap, sceMpegReset clears TMB's static word, and the results + // are the reference's. Off: libmpeg writes nothing outside the work area the game gave sceMpegCreate (the + // Nodata callback's 32-byte data is its first bytes), and the results are the SDK's (sceMpegCreate and + // sceMpegDelete 1, sceMpegAddCallback the previous callback). + bool referenceLayout = true; + // sceMpegGetPicture holds each picture until its two fields are due; off, a game that paces itself gets it at + // once and sceMpegIsEnd answers from the stream alone. + bool paced = true; + // The Nodata callback as the SDK calls it: (mp, callback data, the data given to sceMpegAddCallback); a 0 it + // returns ends the input (the pictures left come out, then sceMpegIsEnd answers 1). + bool sdkNodata = false; + }; + // One sceMpeg (TMB plays one movie at a time). struct MpegState { @@ -92,6 +111,7 @@ namespace bozo::libs uint32_t starts = 0; // picture starts and sequence ends whole in the stream so far uint32_t pictureStarts = 0; // picture starts alone bool sequenceEnd = false; + bool inputEnded = false; // the Nodata callback said there is no more input (MpegOptions::sdkNodata) bool headerOpen = false; std::vector cuts; // where each coded picture's data (with its headers) begins size_t sent = 0; // coded pictures given to the decoder diff --git a/runtime/include/bozo/libs/pad.h b/runtime/include/bozo/libs/pad.h index 9d88804..11ed03c 100644 --- a/runtime/include/bozo/libs/pad.h +++ b/runtime/include/bozo/libs/pad.h @@ -110,5 +110,12 @@ namespace bozo::libs bool multitap = false; // Whether sceMtapPortOpen finds a multitap in port 1 (a port or the settings can unplug it). bool multitapAttached = true; + // libpad2 (pad2.cpp): its sockets, by number, each on a port and slot. + struct Pad2Socket + { + int32_t port = 0, slot = 0; + }; + std::map pad2Sockets; + int32_t pad2Next = 0; }; } diff --git a/runtime/include/bozo/libs/sif.h b/runtime/include/bozo/libs/sif.h index f087dc8..c4f9d58 100644 --- a/runtime/include/bozo/libs/sif.h +++ b/runtime/include/bozo/libs/sif.h @@ -4,6 +4,8 @@ // allocator handed out (989SND's banks and buffers come from it too). #pragma once +#include "bozo/state.h" + #include #include #include @@ -35,6 +37,7 @@ namespace bozo::libs uint32_t blockAt(uint32_t address) const; uint32_t largestFree() const; uint32_t totalFree() const; + void serialize(state::Archive &a); private: std::map free_; // start -> bytes @@ -69,6 +72,10 @@ namespace bozo::libs // memory as much as ours (a level's heap reaches 0x1f10000 and overwrites it), so a call finds its server here. std::map bound; uint32_t sreg[32] = {}; + // The IOP side's 32 software registers, as compiled modules read and write them (sifcmd sceSifGetSreg 6, + // sceSifSetSreg 7). The SDK's set-sreg system command (0x80000001: index at +0x10, value at +0x14 of the packet) + // writes the other side's: a module's sceSifSendCmd sets sreg above; a port answering the EE's sets this one. + uint32_t iopSreg[32] = {}; uint32_t dmaId = 0; // the last SIF DMA transfer's id (sceSifSetDma: 1, 2, ...) uint32_t modules = 0; // modules loaded since the IOP's reboot (their ids are 1, 2, ...) IopHeap heap; diff --git a/runtime/include/bozo/native/compiled_libraries.h b/runtime/include/bozo/native/compiled_libraries.h index 51fd80a..b7722af 100644 --- a/runtime/include/bozo/native/compiled_libraries.h +++ b/runtime/include/bozo/native/compiled_libraries.h @@ -41,6 +41,13 @@ namespace bozo::native::irx // Deliver already completed native audio jobs at linked-call safe points. // Opt in before execution; existing ports retain their callback schedule. void useReadyAudioCompletions(); + // With ready completions, also deliver them when an import call returns, not only a linked function: a routine + // that starts a libsd transfer and then polls its completion flag in a loop with no call in it sees the flag. + // Opt in before execution (it implies useReadyAudioCompletions); ports without it keep their schedule. + void useReadyAudioCompletionsAfterImports(); + // The work a root call (a module's start, a callback) may do before it counts as stuck: 1,000,000 by default. A + // module whose start legitimately does more (EA's AUDIOPF clears its large buffers byte by byte) raises it. + void setRootCallBudget(uint64_t budget); // Map linked frame listeners to actual native game-frame completions. // Opt in before execution; no display interrupt or frame period is generated. void useNativeFrameCallbacks(); @@ -63,6 +70,10 @@ namespace bozo::native::irx // stack, opaque module handle, device address or freed block. std::span allocatedBuffer(uint32_t address,uint32_t bytes); uint64_t nativeCalls() const; + // Save states (bozo/state.h): the IOP's memory, tasks, kernel objects, sound mixer and libsd, at the EE + // dispatcher's safe point (no native task running). The images and bindings are set up again by the port. + std::string unsaveable() const; + void serialize(state::Archive &a); private: struct Impl; diff --git a/runtime/include/bozo/port.h b/runtime/include/bozo/port.h index 073222e..de89b71 100644 --- a/runtime/include/bozo/port.h +++ b/runtime/include/bozo/port.h @@ -11,6 +11,7 @@ #pragma once #include "bozo/runtime.h" +#include "bozo/state.h" #include #include @@ -107,6 +108,8 @@ namespace bozo::port // that calls the original (calling the guest code there would run the game's own library, which the // reference never did). False when nothing native answers there. virtual bool callLibrary(Runtime *rt, R5900Context *ctx, uint32_t address) = 0; + // Where a port adds its own part of a save state (bozo/state.h); null when the host has no save states. + virtual state::Sections *stateSections() { return nullptr; } }; // ---- What overrides use while they run -------------------------------------------------------------------------- diff --git a/runtime/include/bozo/render/mesh_draw.h b/runtime/include/bozo/render/mesh_draw.h index a76815f..896b2f3 100644 --- a/runtime/include/bozo/render/mesh_draw.h +++ b/runtime/include/bozo/render/mesh_draw.h @@ -39,6 +39,7 @@ namespace bozo::render bool setsAlpha = false, setsTest = false, setsZbuf = false, setsTex0 = false; uint64_t alpha = 0, test = 0; bool depthMasked = false; + bool clampU = false, clampV = false; // the batch's CLAMP (WMS / WMT region clamp): set per batch, not kept std::shared_ptr texture; std::vector vertices; // triangles, three vertices each }; diff --git a/runtime/include/bozo/runtime.h b/runtime/include/bozo/runtime.h index ef8ceb5..685c7e6 100644 --- a/runtime/include/bozo/runtime.h +++ b/runtime/include/bozo/runtime.h @@ -87,7 +87,13 @@ namespace bozo void addModule(uint32_t start, uint32_t end, const uint8_t *resident, std::vector identity, const BozoFunctionEntry *functions, size_t count, const BozoResumeEntry *resume, size_t resumeCount); - void clearModules() { modules_.clear(); } + void clearModules() + { + modules_.clear(); + modulesLow_ = ~0u; + modulesHigh_ = 0; + lastModule_ = nullptr; + } private: const BozoFunctionEntry *table_ = nullptr; @@ -106,6 +112,10 @@ namespace bozo size_t resumeCount; }; std::vector modules_; + // Lookups are made on every call: the span all modules cover (outside it, no module is asked) and the module found + // last (asked first: a module's code calls into itself far more than elsewhere). + uint32_t modulesLow_ = ~0u, modulesHigh_ = 0; + mutable const Module *lastModule_ = nullptr; const Module *moduleAt(uint32_t address, bool &reserved) const; }; diff --git a/runtime/include/bozo/state.h b/runtime/include/bozo/state.h new file mode 100644 index 0000000..4e29b69 --- /dev/null +++ b/runtime/include/bozo/state.h @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT +// Save states: one archive that writes or reads the runtime's whole state at a dispatcher safe point (no guest code on +// the host stack: every thread's registers are in its kernel frame). One function per component walks its fields in a +// fixed order for both directions; a file is a header, then named sections whose sizes are checked as they are read. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bozo::state +{ + class Error : public std::runtime_error + { + public: + using std::runtime_error::runtime_error; + }; + + class Archive + { + public: + // A writer, or a reader of `data` (a whole file). + Archive() = default; + explicit Archive(std::vector data) : data_(std::move(data)), loading_(true) {} + + bool loading() const { return loading_; } + void raw(void *p, size_t n); + // A named section: begin and end bracket its fields (sections nest). Reading checks the name and that the + // fields took exactly the bytes written. + void begin(const char *name); + void end(); + const std::vector &data() const { return data_; } + bool atEnd() const { return pos_ == data_.size(); } + + private: + std::vector data_; + size_t pos_ = 0; + bool loading_ = false; + std::vector> open_; // name, where its size word is (writing) or its end (reading) + }; + + // A part of the state a port or a library host keeps outside the engine's own (its native hosts, its registrations + // with the libraries, its caches of guest data). `serialize` walks its fields both ways; after a load it also + // drops anything derived from the old state. `unsaveable` (optional) says why the state cannot be saved now. + struct Section + { + std::string name; + std::function serialize; + std::function unsaveable; + }; + class Sections + { + public: + void add(Section s) + { + for (const Section &other : sections_) + if (other.name == s.name) + throw std::invalid_argument("save state section " + s.name + " added twice"); + sections_.push_back(std::move(s)); + } + std::vector
&all() { return sections_; } + + private: + std::vector
sections_; + }; + + // Whole files: a header (magic, format version, the game's tag) then the archive's bytes. + void writeFile(const std::string &path, const std::string &game, const Archive &a); + Archive readFile(const std::string &path, const std::string &game); + + // ---- Field walkers ---------------------------------------------------------------------------------------------- + // Scalars and enums as their bytes; containers as a count then their elements; every other type by an io() found + // by argument-dependent lookup in its own namespace. + template + requires(std::is_arithmetic_v || std::is_enum_v) + void io(Archive &a, T &v) + { + a.raw(&v, sizeof v); + } + inline void io(Archive &a, bool &v) + { + uint8_t b = v ? 1 : 0; + a.raw(&b, 1); + v = b != 0; + } + // A trivially copyable struct with no pointers inside, as its bytes. + template void pod(Archive &a, T &v) + { + static_assert(std::is_trivially_copyable_v); + a.raw(&v, sizeof v); + } + + inline uint64_t count(Archive &a, size_t n) + { + uint64_t c = n; + a.raw(&c, sizeof c); + if (a.loading() && c > (1ull << 32)) + throw Error("save state: a container count is out of range"); + return c; + } + + inline void io(Archive &a, std::string &s) + { + const uint64_t n = count(a, s.size()); + if (a.loading()) + s.resize(n); + a.raw(s.data(), n); + } + template void io(Archive &a, T (&v)[N]); + template void io(Archive &a, std::array &v); + template void io(Archive &a, std::vector &v); + template void io(Archive &a, std::deque &v); + template void io(Archive &a, std::set &v); + template void io(Archive &a, std::map &m); + template void io(Archive &a, std::unordered_map &m); + template void io(Archive &a, std::pair &p); + template void io(Archive &a, std::unique_ptr &p); + + template void fields(Archive &a, T &...v) { (io(a, v), ...); } + + template void io(Archive &a, T (&v)[N]) + { + if constexpr (std::is_arithmetic_v) + a.raw(v, sizeof v); + else + for (auto &e : v) + io(a, e); + } + template void io(Archive &a, std::array &v) + { + if constexpr (std::is_arithmetic_v) + a.raw(v.data(), sizeof(T) * N); + else + for (auto &e : v) + io(a, e); + } + template void io(Archive &a, std::vector &v) + { + const uint64_t n = count(a, v.size()); + if (a.loading()) + v.resize(n); + if constexpr (std::is_arithmetic_v && !std::is_same_v) + a.raw(v.data(), sizeof(T) * n); + else + for (auto &e : v) + io(a, e); + } + template void io(Archive &a, std::deque &v) + { + const uint64_t n = count(a, v.size()); + if (a.loading()) + v.resize(n); + for (auto &e : v) + io(a, e); + } + template void io(Archive &a, std::set &v) + { + const uint64_t n = count(a, v.size()); + if (!a.loading()) + { + for (T e : v) + io(a, e); + return; + } + v.clear(); + for (uint64_t i = 0; i < n; ++i) + { + T e{}; + io(a, e); + v.insert(std::move(e)); + } + } + template void io(Archive &a, std::map &m) + { + const uint64_t n = count(a, m.size()); + if (!a.loading()) + { + for (auto &[k, v] : m) + { + K key = k; + io(a, key); + io(a, v); + } + return; + } + m.clear(); + for (uint64_t i = 0; i < n; ++i) + { + K key{}; + io(a, key); + io(a, m[key]); + } + } + // Written in key order, so the same state always gives the same bytes. + template void io(Archive &a, std::unordered_map &m) + { + if (!a.loading()) + { + std::map sorted(m.begin(), m.end()); + io(a, sorted); + return; + } + std::map sorted; + io(a, sorted); + m.clear(); + for (auto &[k, v] : sorted) + m.emplace(k, std::move(v)); + } + template void io(Archive &a, std::pair &p) + { + io(a, p.first); + io(a, p.second); + } + template void io(Archive &a, std::unique_ptr &p) + { + bool present = p != nullptr; + io(a, present); + if (a.loading()) + p = present ? std::make_unique() : nullptr; + if (p) + io(a, *p); + } +} diff --git a/runtime/libs/cd.cpp b/runtime/libs/cd.cpp index bc18985..9f03652 100644 --- a/runtime/libs/cd.cpp +++ b/runtime/libs/cd.cpp @@ -235,7 +235,7 @@ namespace bozo::libs h.gp = cd.callbackGp; h.sp = cd.callbackStack; h.a[0] = 4; - l.queueHandler(h, {}); + l.queueHandler(h, Resume{}); } g.ret(1); } @@ -288,16 +288,20 @@ namespace bozo::libs CdState &cd = l.cd; cd.error = ok ? 0 : -1; cd.readBytes=ok?n*kSectorBytes:0; - g.cycles = l.callCycles(static_cast(n) * kSectorCycles); - cd.readEnd = l.now(g) + g.cycles; + const uint64_t drive = static_cast(n) * kSectorCycles; + g.cycles = l.callCycles(cd.timedCompletion ? 0 : drive); + cd.readEnd = l.now(g) + (cd.timedCompletion ? g.cycles + drive : g.cycles); if(ok && cd.callback) { if(!l.dispatcher()) throw std::runtime_error("CD callback requires native dispatcher"); ee::QueuedHandler h;h.kind=ee::kInvokeLibraryCall;h.pc=cd.callback; h.gp=cd.callbackGp;h.sp=cd.callbackStack;h.a[0]=1; // SCECdFuncRead - // The existing native read returns after charging its full - // read duration; this callback cannot execute inside that call. - l.queueHandler(h,{}); + if(cd.timedCompletion) + l.dispatcher()->kernel().scheduleDeadline(kReadDoneKey, cd.readEnd, h); + else + // The read returns after charging its full duration; this callback cannot execute inside that + // call. + l.queueHandler(h, Resume{}); } g.ret(ok ? 1 : 0); } @@ -433,13 +437,7 @@ namespace bozo::libs cd.pendingSectors = n - now; cd.pendingBuffer = to + now * kSectorBytes; cd.pendingError = errorAt; - l.waitVblank(token, -1, [n](Libraries &l2, Guest &g2) { - CdState &c = l2.cd; - c.advance(l2.now(g2)); - deliver(l2, g2, c.pendingSectors, c.pendingBuffer, c.pendingError); - c.pendingSectors = 0; - g2.ret(static_cast(n)); - }); + l.waitVblank(token, -1, Resume{kResumeCdStreamRead, {n}}); return; } deliver(l, g, mode == 1 ? n : static_cast(available), to, errorAt); @@ -517,6 +515,16 @@ namespace bozo::libs } } + // A blocking stream read's end, as its thread resumes: the rest of the sectors, then the count asked for. + void cdResume(Libraries &l, Guest &g, const Resume &r) + { + CdState &c = l.cd; + c.advance(l.now(g)); + deliver(l, g, c.pendingSectors, c.pendingBuffer, c.pendingError); + c.pendingSectors = 0; + g.ret(static_cast(r.a[0])); + } + void addCd(std::vector &out) { out.push_back({"sceFsInit", kCd, fsInit}); diff --git a/runtime/libs/libraries.cpp b/runtime/libs/libraries.cpp index 1e1f31e..6444ef9 100644 --- a/runtime/libs/libraries.cpp +++ b/runtime/libs/libraries.cpp @@ -4,6 +4,7 @@ #include "bozo/ee/dispatcher.h" #include +#include namespace bozo::libs { @@ -234,6 +235,7 @@ namespace bozo::libs addGs(functions_); addDma(functions_); addPad(functions_); + addPad2(functions_); addMc(functions_); addCd(functions_); addMpeg(functions_); @@ -241,6 +243,82 @@ namespace bozo::libs addTimer(functions_); for (size_t i = 0; i < functions_.size(); ++i) byName_[functions_[i].name] = i; + resumeKinds_[kResumeCdStreamRead] = cdResume; + resumeKinds_[kResumeMpegRelease] = mpegResume; + resumeKinds_[kResumeMpegNodataEnd] = mpegResume; + resumeKinds_[kResumeMpegGetPicture] = mpegResume; + resumeKinds_[kResumeMpegDeliver] = mpegResume; + resumeKinds_[kResumeTimerHandlerEnd] = timerResume; + deadlineKinds_[kDeadlineTimerFire] = timerDeadline; + deadlineKinds_[kDeadlineDelayDue] = delayDeadline; + } + + void Libraries::attach(ee::Dispatcher &d) + { + d_ = &d; + d.kernel().nativeRebuild = [this](uint32_t kind, const std::array &args) { + std::function fn; + if (const auto f = deadlineKinds_.find(kind); f != deadlineKinds_.end()) + fn = [this, f = f->second, args](uint64_t due) { f(*this, args, due); }; + return fn; + }; + } + + void Libraries::addResumeKind(uint32_t kind, ResumeFunction f) + { + if (kind < kPortResumeKinds || !f || !resumeKinds_.emplace(kind, f).second) + throw std::invalid_argument("a port's continuation kind must be new and at least kPortResumeKinds"); + } + + void Libraries::addDeadlineKind(uint32_t kind, DeadlineFunction f) + { + if (kind < kPortDeadlineKinds || !f || !deadlineKinds_.emplace(kind, f).second) + throw std::invalid_argument("a port's deadline kind must be new and at least kPortDeadlineKinds"); + } + + void Libraries::scheduleDeadline(uint32_t key, uint64_t cycle, uint32_t kind, std::array args) + { + const auto f = deadlineKinds_.find(kind); + if (f == deadlineKinds_.end()) + throw std::invalid_argument("unknown native deadline kind"); + d_->kernel().scheduleNative(key, cycle, kind, args, + [this, f = f->second, args](uint64_t due) { f(*this, args, due); }); + } + + Libraries::Pending Libraries::pending(const Resume &r) + { + const auto f = resumeKinds_.find(r.kind); + if (f == resumeKinds_.end()) + throw std::invalid_argument("unknown library continuation kind " + std::to_string(r.kind)); + return {[f = f->second, r](Libraries &l, Guest &g) { f(l, g, r); }, r}; + } + + void Libraries::waitVblank(uint64_t token, int32_t fixedResult, const Resume &then) + { + ee::Kernel &k = d_->kernel(); + const int32_t id = k.running(); + const bool completion = then.kind != kResumeNone; + if (completion) + continuations_[id] = pending(then); + k.block(id, ee::kWaitVblank, 0, static_cast(fixedResult), 0, completion, token, fixedResult); + } + + void Libraries::waitFor(uint32_t reason, uint32_t object, uint64_t token, int32_t fixedResult, const Resume &then) + { + ee::Kernel &k = d_->kernel(); + const int32_t id = k.running(); + const bool completion = then.kind != kResumeNone; + if (completion) + continuations_[id] = pending(then); + k.block(id, reason, object, 0, 0, completion, token, fixedResult); + } + + void Libraries::queueHandler(const ee::QueuedHandler &h, const Resume &end) + { + ee::Kernel &k = d_->kernel(); + k.queue(h); + if (end.kind != kResumeNone) + handlerEnds_[k.sequence()] = pending(end); } const Function *Libraries::find(const std::string &name) const @@ -285,7 +363,7 @@ namespace bozo::libs const int32_t id = k.running(); const bool completion = static_cast(then); if (completion) - continuations_[id] = std::move(then); + continuations_[id] = {std::move(then), {}}; k.block(id, ee::kWaitVblank, 0, static_cast(fixedResult), 0, completion, token, fixedResult); } @@ -296,7 +374,7 @@ namespace bozo::libs const int32_t id = k.running(); const bool completion = static_cast(then); if (completion) - continuations_[id] = std::move(then); + continuations_[id] = {std::move(then), {}}; k.block(id, reason, object, 0, 0, completion, token, fixedResult); } @@ -305,7 +383,7 @@ namespace bozo::libs ee::Kernel &k = d_->kernel(); k.queue(h); if (end) - handlerEnds_[k.sequence()] = std::move(end); + handlerEnds_[k.sequence()] = {std::move(end), {}}; } std::function Libraries::takeHandlerEnd(uint64_t sequence) @@ -313,7 +391,7 @@ namespace bozo::libs auto it = handlerEnds_.find(sequence); if (it == handlerEnds_.end()) return {}; - auto c = std::move(it->second); + auto c = std::move(it->second.run); handlerEnds_.erase(it); return c; } @@ -323,7 +401,7 @@ namespace bozo::libs auto it = continuations_.find(thread); if (it == continuations_.end()) return {}; - auto c = std::move(it->second); + auto c = std::move(it->second.run); continuations_.erase(it); return c; } diff --git a/runtime/libs/libraries_state.cpp b/runtime/libs/libraries_state.cpp new file mode 100644 index 0000000..88cac1c --- /dev/null +++ b/runtime/libs/libraries_state.cpp @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT +// Save states of the native libraries (bozo/state.h): every library's state, field by field. What a port or the +// host sets up once (callbacks, paths, switches) is not saved: a loading runtime was set up the same way. +#include "bozo/ee/dispatcher.h" +#include "bozo/libs/libraries.h" + +namespace bozo::libs +{ + using state::fields; + using state::io; + using state::pod; + + void Heap::serialize(state::Archive &a) { fields(a, free_, used_, end_); } + void IopHeap::serialize(state::Archive &a) { fields(a, free_, used_); } + + void io(state::Archive &a, McDate &d) { fields(a, d.second, d.minute, d.hour, d.day, d.month, d.year); } + void io(state::Archive &a, McCard::Entry &e) { fields(a, e.directory, e.attributes, e.created, e.modified, e.data, e.order); } + void McCard::serialize(state::Archive &a) { fields(a, entries_, next_); } + + void io(state::Archive &a, CdState::File &f) { fields(a, f.sector, f.bytes, f.position); } + void io(state::Archive &a, McState::Open &o) { fields(a, o.port, o.path, o.position, o.mode); } + void io(state::Archive &a, MpegState::Callback &c) { fields(a, c.function, c.data, c.gp, c.set); } + void io(state::Archive &a, MpegState::DueCallback &c) { fields(a, c.handler, c.entry); } + void io(state::Archive &a, TimerState::Counter &c) + { + fields(a, c.tag, c.running, c.armed, c.start, c.count, c.compare, c.handler, c.arg, c.gp, c.alarm, c.hostDue); + } + void io(state::Archive &a, Resume &r) { fields(a, r.kind, r.a); } + void io(state::Archive &a, PadState::Pad2Socket &s) { fields(a, s.port, s.slot); } + + std::string Libraries::unsaveable() const + { + for (const auto &[thread, p] : continuations_) + if (p.resume.kind == kResumeNone) + return "thread " + std::to_string(thread) + " waits with a library continuation that cannot be saved"; + for (const auto &[sequence, p] : handlerEnds_) + if (p.resume.kind == kResumeNone) + return "a queued handler has a library completion that cannot be saved"; + if (mpeg.decoder || !mpeg.decoded.empty()) + return "a movie is playing"; + if (snd.engine || !snd.banks.empty() || !snd.handles.empty()) + return "the 989SND driver's state is not covered by save states yet"; + return {}; + } + + void Libraries::serialize(state::Archive &a) + { + if (const std::string why = unsaveable(); !why.empty()) + throw state::Error("save state: " + why); + a.begin("libraries"); + heap.serialize(a); + fields(a, rand.state, framesEnded, dmaEnvironment); + a.begin("waits"); + uint64_t n = state::count(a, continuations_.size()); + if (!a.loading()) + for (auto &[thread, p] : continuations_) + { + int32_t t = thread; + fields(a, t, p.resume); + } + else + { + continuations_.clear(); + for (uint64_t i = 0; i < n; ++i) + { + int32_t t = 0; + Resume r; + fields(a, t, r); + continuations_[t] = pending(r); + } + } + n = state::count(a, handlerEnds_.size()); + if (!a.loading()) + for (auto &[sequence, p] : handlerEnds_) + { + uint64_t s = sequence; + fields(a, s, p.resume); + } + else + { + handlerEnds_.clear(); + for (uint64_t i = 0; i < n; ++i) + { + uint64_t s = 0; + Resume r; + fields(a, s, r); + handlerEnds_[s] = pending(r); + } + } + a.end(); + + a.begin("pad"); + for (auto &port : pad.ports) + for (auto &slot : port) + pod(a, slot); + fields(a, pad.initialized, pad.reads, pad.socketReads, pad.multitap, pad.multitapAttached, pad.pad2Sockets, pad.pad2Next); + a.end(); + + a.begin("mc"); + for (McCard &c : mc.cards) + c.serialize(a); + fields(a, mc.formatted, mc.slotMask, mc.date, mc.known, mc.unformatted, mc.pending, mc.function, mc.result, + mc.files, mc.nextDescriptor, mc.currentDirectory, mc.directoryCursor); + a.end(); + + a.begin("cd"); + fields(a, cd.files, cd.nextFile, cd.initialized, cd.error, cd.readEnd, cd.readBytes, cd.callback, cd.callbackGp, + cd.callbackStack, cd.callbackConfigured, cd.ringSectors, cd.banks, cd.iopBuffer, cd.streaming, + cd.streamLbn, cd.delivered, cd.produced, cd.producedAt, cd.paused, cd.pendingSectors, cd.pendingBuffer, + cd.pendingError); + a.end(); + + a.begin("vu0"); + fields(a, vu0.image, vu0.hierarchyHigh); + a.end(); + + a.begin("io"); + pod(a, io); + a.end(); + + a.begin("mpeg"); + MpegState &m = mpeg; + fields(a, m.active, m.mp, m.work, m.size, m.block, m.callbacks, m.strCallbacks, m.callbacksAdded, m.consumed, + m.pending, m.pendingAt, m.ring, m.ringSize, m.ringBias, m.linearBase, m.programEnd, m.aborted, m.es, + m.scanned, m.starts, m.pictureStarts, m.sequenceEnd, m.headerOpen, m.cuts, m.sent, m.flushed, + m.callbacksDue, m.waiting, m.delivered, m.base, m.lastShown, m.firstPictureNs, m.soundHeader, + m.soundCarry, m.inputEnded); + pod(a, m.sound); + a.end(); + + a.begin("sif"); + fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules, sif.iopSreg); + sif.heap.serialize(a); + a.end(); + + a.begin("timers"); + TimerState &t = timers; + fields(a, t.counters, t.alarms, t.used, t.serial, t.initialized, t.prescale, t.systemRunning, t.systemStart, + t.systemStopped, t.inHandler, t.delays); + a.end(); + a.end(); + if (a.loading()) + portStream.clear(); // sound already mixed for the host belongs to the old state + } +} diff --git a/runtime/libs/mc.cpp b/runtime/libs/mc.cpp index f466dbc..aee8df9 100644 --- a/runtime/libs/mc.cpp +++ b/runtime/libs/mc.cpp @@ -7,6 +7,11 @@ #include #include #include +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#endif namespace bozo::libs { @@ -18,6 +23,18 @@ namespace bozo::libs constexpr uint16_t kAttrDirectory = 0x80a3; // as the reference reports "." and ".." constexpr uint16_t kAttrFile = 0x8497; // read, write, execute, closed, file, exists (not in the logs) + // A host file's creation time (Windows keeps one), else its write time: the card order of a kept card. + int64_t creationTime(const fs::path &p) + { +#ifdef _WIN32 + WIN32_FILE_ATTRIBUTE_DATA data; + if (GetFileAttributesExW(p.wstring().c_str(), GetFileExInfoStandard, &data)) + return static_cast(uint64_t(data.ftCreationTime.dwHighDateTime) << 32 | data.ftCreationTime.dwLowDateTime); +#endif + std::error_code ec; + return static_cast(fs::last_write_time(p, ec).time_since_epoch().count()); + } + std::string normalize(const std::string &name) { std::string n = name; @@ -328,6 +345,9 @@ namespace bozo::libs { const uint32_t at = it->second.position, size = g.arg(2); const uint32_t n = at < e->data.size() ? std::min(size, static_cast(e->data.size()) - at) : 0; + if (std::getenv("BOZO_TRACE_MC")) + std::fprintf(stderr, "[mc] read fd=%d at=%u size=%u buffer=%x ra=%x\n", static_cast(g.arg(0)), at, + size, g.arg(1), g.context()->r[31].uw[0]); if (n) g.write(g.arg(1), e->data.data() + at, n); it->second.position += n; @@ -541,17 +561,38 @@ namespace bozo::libs return; std::error_code ec; fs::create_directories(host_, ec); - // Load what the host folder holds (a card kept across runs). + // Load what the host folder holds (a card kept across runs), in the order its files were created (their + // creation time where the host keeps one, else their write time; then their name). + struct Found + { + std::string path; + fs::path host; + int64_t created = 0; + bool directory = false; + }; + std::vector found; for (auto it = fs::recursive_directory_iterator(host_, ec); !ec && it != fs::recursive_directory_iterator(); it.increment(ec)) { - const std::string path = fs::relative(it->path(), host_, ec).generic_string(); - Entry &e = entries_[path]; + Found f; + f.path = fs::relative(it->path(), host_, ec).generic_string(); + f.host = it->path(); + f.directory = it->is_directory(ec); + f.created = creationTime(it->path()); + found.push_back(std::move(f)); + } + std::stable_sort(found.begin(), found.end(), [](const Found &a, const Found &b) { + return a.created != b.created ? a.created < b.created : a.path < b.path; + }); + for (const Found &f : found) + { + Entry &e = entries_[f.path]; e.created = e.modified = date; - e.directory = it->is_directory(ec); + e.directory = f.directory; e.attributes = e.directory ? kAttrDirectory : kAttrFile; + e.order = ++next_; if (!e.directory) { - std::ifstream in(it->path(), std::ios::binary); + std::ifstream in(f.host, std::ios::binary); e.data.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); } } @@ -565,17 +606,23 @@ namespace bozo::libs std::vector McCard::list(const std::string &directory) const { - std::vector out; + std::vector> found; for (const auto &[path, e] : entries_) if (parentOf(path) == directory) - out.push_back(path); + found.emplace_back(e.order, path); + std::sort(found.begin(), found.end()); + std::vector out; + for (auto &f : found) + out.push_back(std::move(f.second)); return out; } McCard::Entry &McCard::create(const std::string &path, bool directory, const McDate &date) { Entry &e = entries_[path]; + const uint64_t order = e.order ? e.order : ++next_; // a file made again keeps its place e = Entry{}; + e.order = order; e.directory = directory; e.created = e.modified = date; return e; diff --git a/runtime/libs/mpeg.cpp b/runtime/libs/mpeg.cpp index 29ec256..370ef6a 100644 --- a/runtime/libs/mpeg.cpp +++ b/runtime/libs/mpeg.cpp @@ -93,7 +93,7 @@ namespace bozo::libs s.scanned = i; } - bool ended(const MpegState &s) { return s.sequenceEnd || s.programEnd; } + bool ended(const MpegState &s) { return s.sequenceEnd || s.programEnd || s.inputEnded; } // Whether display picture k can be decoded: its data and the next picture's are whole (the decoder holds one // picture back), or the stream has ended and its data is whole. @@ -284,8 +284,9 @@ namespace bozo::libs // ---- The functions ---- - // sceMpegInit(): 0. - void init(Libraries &, Guest &g) { g.ret(0); } + // sceMpegInit(): 0 (the SDK's 1 off the reference layout). Nothing is reset: a game may call it from its Nodata + // callback, in the middle of a stream. + void init(Libraries &l, Guest &g) { g.ret(l.mpegOptions.referenceLayout ? 0 : 1); } // sceMpegCreate(mp, work, size): the sceMpeg and its work area as the reference sets them, 0x600 bytes from the // game's heap; returns work + 0x118. @@ -298,8 +299,15 @@ namespace bozo::libs s.mp = mp; s.work = work; s.size = size; - s.block = l.gameHeap().allocate(0x600); s.decoder = makeVideoDecoder(); + if (!l.mpegOptions.referenceLayout) + { + if (l.movieSound) + l.movieSound->start(); + g.ret(1); + return; + } + s.block = l.gameHeap().allocate(0x600); const uint32_t table[9] = {0x171A50, 0x171C58, 0x171CC0, 0x171D28, 0x171D90, 0x171AB8, 0x171B20, 0x171B88, 0x171BF0}; g.write32(0x1717BC, mp); g.write(0x171800, table, sizeof(table)); @@ -325,7 +333,7 @@ namespace bozo::libs g.retU(work + 0x118); } - // sceMpegDelete(mp): 0. + // sceMpegDelete(mp): 0 (the SDK's 1 off the reference layout). void destroy(Libraries &l, Guest &g) { MpegState &s = state(l); @@ -334,14 +342,15 @@ namespace bozo::libs s.decoded.clear(); if (l.movieSound) l.movieSound->stop(); - g.ret(0); + g.ret(l.mpegOptions.referenceLayout ? 0 : 1); } // sceMpegReset(mp): the picture count and libmpeg's static word at 0x171904 cleared (no result). - void reset(Libraries &, Guest &g) + void reset(Libraries &l, Guest &g) { g.write32(g.arg(0) + 8, 0); - g.write32(0x171904, 0); + if (l.mpegOptions.referenceLayout) + g.write32(0x171904, 0); } // sceMpegAddCallback(mp, type, function, data): how many callbacks are set (1, 2, ...). @@ -349,9 +358,33 @@ namespace bozo::libs { MpegState &s = state(l); const uint32_t type = g.arg(1); + const uint32_t previous = type < 8 ? s.callbacks[type].function : 0; if (type < 8) s.callbacks[type] = {g.arg(2), g.arg(3), g.context()->r[28].uw[0], true}; - g.ret(static_cast(++s.callbacksAdded)); + ++s.callbacksAdded; + if (l.mpegOptions.referenceLayout) + g.ret(static_cast(s.callbacksAdded)); + else + g.retU(previous); // the SDK's: the callback the type had + } + + // sceMpegAddBs(mp, data, bytes): coded video for the decoder, as the game reads it (no program stream). The + // SDK sends ((bytes + 19) >> 4) << 4 bytes to the IPU, so as many are taken. 1. + void addBs(Libraries &l, Guest &g) + { + MpegState &s = state(l); + const uint32_t data = g.arg(1), bytes = ((g.arg(2) + 19u) >> 4) << 4; + const size_t at = s.es.size(); + s.es.resize(at + bytes); + for (uint32_t k = 0; k < bytes; ++k) + s.es[at + k] = g.read8(data + k); + scan(s); + if (s.waiting && available(s, s.delivered)) + { + l.dispatcher()->kernel().wake(s.waiting, 0, true, ee::kWaitMpeg); + s.waiting = 0; + } + g.ret(1); } // sceMpegAddStrCallback(mp, type, channel, function, data): 0. @@ -418,7 +451,7 @@ namespace bozo::libs for (const MpegState::DueCallback &c : s.callbacksDue) { const uint32_t entry = c.entry; - l.queueHandler(c.handler, [entry](Libraries &l2, Guest &) { l2.gameHeap().release(entry); }); + l.queueHandler(c.handler, Resume{kResumeMpegRelease, {entry}}); } s.callbacksDue.clear(); g.ret(static_cast(taken)); @@ -434,6 +467,12 @@ namespace bozo::libs void isEnd(Libraries &l, Guest &g) { const MpegState &s = state(l); + if (!l.mpegOptions.paced) + { + // The game paces itself: the end once the input has ended and every picture has gone out. + g.ret(s.aborted || (ended(s) && s.flushed && s.decoded.empty() && s.delivered >= s.pictureStarts) ? 1 : 0); + return; + } const uint64_t endsAt = s.base + static_cast(kFieldsPerPicture) * s.pictureStarts; // A last picture the game took late (after its two fields' slot: base + 2 x its number) is still on screen: // 0 until an empty delivery has counted one more slot. @@ -505,7 +544,9 @@ namespace bozo::libs if (!available(s, s.delivered)) { const uint8_t data[32] = {static_cast(kCbNodata)}; - const uint32_t entry = l.gameHeap().allocate(0x20); + const bool reference = l.mpegOptions.referenceLayout, sdk = l.mpegOptions.sdkNodata; + // The callback's data: from the game's heap (the reference's), or the work area's first bytes. + const uint32_t entry = reference ? l.gameHeap().allocate(0x20) : s.work; g.write(entry, data, 32); const MpegState::Callback &cb = s.callbacks[kCbNodata]; ee::QueuedHandler h; @@ -513,30 +554,27 @@ namespace bozo::libs h.pc = cb.function; h.a[0] = s.mp; h.a[1] = entry; + if (sdk) + h.a[2] = cb.data; h.gp = cb.gp; h.completion = true; const int32_t thread = k.running(); - // Its end wakes the thread, unless a demux already did. - l.queueHandler(h, [thread, entry](Libraries &l2, Guest &) { - l2.gameHeap().release(entry); - MpegState &s2 = state(l2); - if (s2.waiting == thread) - { - s2.waiting = 0; - l2.dispatcher()->kernel().wake(thread, 0, true, ee::kWaitMpeg); - } - }); + // Its end wakes the thread, unless a demux already did. With the SDK's callback, a 0 it returns ends the + // input. a[2] flags (0 keeps the reference's behaviour): 1 the entry is the work area (nothing to + // release), 2 the SDK's callback (its 0 ends the input). + const uint32_t flags = (reference ? 0u : 1u) | (sdk ? 2u : 0u); + l.queueHandler(h, Resume{kResumeMpegNodataEnd, {static_cast(thread), entry, flags}}); l.io.ipuDemand = true; // the IPU's input was taken (libraries.md section 11) s.waiting = thread; - l.waitFor(ee::kWaitMpeg, 1, s.mp, 0, [rgb, mbcount](Libraries &l2, Guest &g2) { getPictureOn(l2, g2, rgb, mbcount); }); + l.waitFor(ee::kWaitMpeg, 1, s.mp, 0, Resume{kResumeMpegGetPicture, {rgb, mbcount}}); return; } - if (s.delivered > 0 && !(ended(s) && s.delivered >= s.pictureStarts)) // the empty delivery is not paced + if (l.mpegOptions.paced && s.delivered > 0 && !(ended(s) && s.delivered >= s.pictureStarts)) // the empty delivery is not paced { const uint64_t due = s.base + kFieldsPerPicture * s.delivered; if (k.vblankCount() <= due) { - l.waitVblank(due, -1, [rgb, mbcount](Libraries &l2, Guest &g2) { deliver(l2, g2, rgb, mbcount); }); + l.waitVblank(due, -1, Resume{kResumeMpegDeliver, {rgb, mbcount}}); return; } } @@ -548,6 +586,38 @@ namespace bozo::libs void videoCallback(Libraries &, Guest &g) { g.ret(1); } } + // The movie library's continuations (libraries.h ResumeKind). + void mpegResume(Libraries &l, Guest &g, const Resume &r) + { + switch (r.kind) + { + case kResumeMpegRelease: + l.gameHeap().release(r.a[0]); + break; + case kResumeMpegNodataEnd: + { + const int32_t thread = static_cast(r.a[0]); + if (!(r.a[2] & 1u)) + l.gameHeap().release(r.a[1]); + MpegState &s = state(l); + if ((r.a[2] & 2u) && g.context()->r[2].uw[0] == 0) + s.inputEnded = true; + if (s.waiting == thread) + { + s.waiting = 0; + l.dispatcher()->kernel().wake(thread, 0, true, ee::kWaitMpeg); + } + break; + } + case kResumeMpegGetPicture: + getPictureOn(l, g, r.a[0], r.a[1]); + break; + case kResumeMpegDeliver: + deliver(l, g, r.a[0], r.a[1]); + break; + } + } + void addMpeg(std::vector &out) { if (!haveVideoDecoder()) @@ -559,6 +629,7 @@ namespace bozo::libs out.push_back({"sceMpegAddCallback", kMpeg, addCallback}); out.push_back({"sceMpegAddStrCallback", kMpeg, addStrCallback}); out.push_back({"sceMpegDemuxPssRing", kMpeg, demux}); + out.push_back({"sceMpegAddBs", kMpeg, addBs}); out.push_back({"sceMpegGetPicture", kMpeg, getPicture}); out.push_back({"sceMpegIsEnd", kMpeg, isEnd}); out.push_back({"videoCallback__FP7sceMpegP16sceMpegCbDataStrPv", kMpeg, videoCallback}); diff --git a/runtime/libs/pad2.cpp b/runtime/libs/pad2.cpp new file mode 100644 index 0000000..e3e9e1f --- /dev/null +++ b/runtime/libs/pad2.cpp @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 The Bozos. +// libpad2 and libvib over libdbc, as a game on a later SDK reads its DualShock 2 controllers (The Third Age): sockets +// on a port and slot, a state, a button profile, the pad data, the button info, the vibration profile and the motors. +// The controllers are libpad's (pad.cpp): the same ports, players and input source. libdbc's own calls (the DBCMAN +// driver's RPC) are not reached once these are native; sceDbcInit/sceDbcEnd answer for a game that calls them itself. +// +// The pad data scePad2Read writes is the DualShock 2's report without libpad's two-byte header: the buttons (two bytes, +// active low, libpad's bit order), the sticks (RX, RY, LX, LY) and the twelve pressures in the controller's order +// (right, left, up, down, triangle, circle, cross, square, L1, R1, L2, R2). The button profile is the DualShock 2's: +// four bytes, every button id 0..31 present. +#include "bozo/libs/libraries.h" + +#include + +namespace bozo::libs +{ + namespace + { + constexpr uint16_t kPad2PressureOrder[12] = {kPadRight, kPadLeft, kPadUp, kPadDown, kPadTriangle, kPadCircle, + kPadCross, kPadSquare, kPadL1, kPadR1, kPadL2, kPadR2}; + constexpr uint32_t kPad2DataBytes = 18; + + const PadState::Pad2Socket *socket(Libraries &l, uint32_t number) + { + const auto it = l.pad.pad2Sockets.find(static_cast(number)); + return it == l.pad.pad2Sockets.end() ? nullptr : &it->second; + } + + // A socket's controller, as libpad answers the same port and slot: the pads in ports 1 and 2 are always there; + // a multitap slot has one when its player has an input. + PadInputState controller(Libraries &l, const PadState::Pad2Socket &s, int &player) + { + PadInputState st; + player = padPlayer(s.port, s.slot, l.pad.multitap); + if (player >= 0 && l.pad.input) + l.pad.input->read(l.framesEnded, player, st); + st.connected = (s.slot == 0 && (s.port == 0 || s.port == 1)) || (player >= 0 && st.connected); + return st; + } + + void dbcInit(Libraries &, Guest &g) { g.ret(1); } + void dbcEnd(Libraries &, Guest &g) { g.ret(1); } + + // scePad2Init(mode), scePad2End(): 1. + void init(Libraries &, Guest &g) { g.ret(1); } + void end(Libraries &l, Guest &g) + { + l.pad.pad2Sockets.clear(); + g.ret(1); + } + + // scePad2CreateSocket(param, buffer): param {flag, port, slot, number, name[16]} (words, then the name); a + // null param is port 0, slot 0. The buffer (64-byte aligned, -1 otherwise as the library prints) is not used. + // Returns the socket's number. + void createSocket(Libraries &l, Guest &g) + { + if (g.arg(1) & 0x3fu) + { + g.ret(-1); + return; + } + PadState::Pad2Socket s; + if (const uint32_t param = g.arg(0)) + { + s.port = static_cast(g.read32(param + 4)); + s.slot = static_cast(g.read32(param + 8)); + } + const int32_t number = l.pad.pad2Next++; + l.pad.pad2Sockets[number] = s; + g.ret(number); + } + + // scePad2DeleteSocket(socket): 1, a socket that is not there -1. + void deleteSocket(Libraries &l, Guest &g) + { + g.ret(l.pad.pad2Sockets.erase(static_cast(g.arg(0))) ? 1 : -1); + } + + // scePad2GetState(socket): 1 with a controller (the game reads then), 0 without (it resets the port). + void getState(Libraries &l, Guest &g) + { + const auto *s = socket(l, g.arg(0)); + int player = -1; + g.ret(s && controller(l, *s, player).connected ? 1 : 0); + } + + // scePad2GetButtonProfile(socket, profile): the DualShock 2's, four bytes with every id 0..31; their count, or + // -1 without a controller. + void getButtonProfile(Libraries &l, Guest &g) + { + const auto *s = socket(l, g.arg(0)); + int player = -1; + if (!s || !controller(l, *s, player).connected) + { + g.ret(-1); + return; + } + const uint8_t profile[4] = {0xff, 0xff, 0xff, 0xff}; + g.write(g.arg(1), profile, sizeof(profile)); + g.ret(4); + } + + // scePad2Read(socket, data): the 18-byte report; its size, or -1 without a controller. + void read(Libraries &l, Guest &g) + { + const auto *s = socket(l, g.arg(0)); + int player = -1; + const PadInputState st = s ? controller(l, *s, player) : PadInputState{}; + if (!s || !st.connected) + { + g.ret(-1); + return; + } + ++l.pad.reads; + if (s->port >= 0 && s->port < 2 && s->slot >= 0 && s->slot < 4) + ++l.pad.socketReads[static_cast(s->port)][static_cast(s->slot)]; + uint8_t d[kPad2DataBytes] = {}; + const uint16_t released = static_cast(~st.buttons); + d[0] = static_cast(released); + d[1] = static_cast(released >> 8); + d[2] = st.rx; + d[3] = st.ry; + d[4] = st.lx; + d[5] = st.ly; + // The input's pressures are in libpad's order; each goes to its button's place in the controller's. + for (int i = 0; i < 12; ++i) + { + const auto from = std::find(std::begin(kPadPressureOrder), std::end(kPadPressureOrder), kPad2PressureOrder[i]); + d[6 + i] = st.pressure[static_cast(from - std::begin(kPadPressureOrder))]; + } + g.write(g.arg(1), d, sizeof(d)); + g.ret(static_cast(sizeof(d))); + } + + // scePad2GetButtonInfo(socket, data, id): ids 0..15 the buttons (1 pressed, the data active low), 16..31 the + // sticks and pressures (data[id - 14]); -1 for any other id. + void getButtonInfo(Libraries &, Guest &g) + { + const uint32_t data = g.arg(1), id = g.arg(2); + if (id < 16) + g.ret((g.read8(data + id / 8) >> (id % 8)) & 1u ? 0 : 1); + else if (id < 32) + g.ret(g.read8(data + id - 14)); + else + g.ret(-1); + } + + // sceVibGetProfile(socket, profile): the DualShock 2's motors, one byte 0x03 (bit 0 the small one, bit 1 the + // large one); 1, or -1 without a controller. + void vibGetProfile(Libraries &l, Guest &g) + { + const auto *s = socket(l, g.arg(0)); + int player = -1; + if (!s || !controller(l, *s, player).connected) + { + g.ret(-1); + return; + } + g.write8(g.arg(1), 0x03); + g.ret(1); + } + + // sceVibSetActParam(socket, profile size, profile, data size, data): the motors, packed as libvib packs them + // (data[0] bit 0 the small motor on or off, then eight bits of the large motor's level); 1. + void vibSetActParam(Libraries &l, Guest &g) + { + const auto *s = socket(l, g.arg(0)); + int player = -1; + if (s && controller(l, *s, player).connected && player >= 0 && l.pad.input && g.arg(3) >= 2) + { + const uint32_t data = g.arg(4); + const uint8_t b0 = g.read8(data), b1 = g.read8(data + 1); + l.pad.input->rumble(player, (b0 & 1u) != 0, static_cast((b0 >> 1) | ((b1 & 1u) << 7))); + } + g.ret(1); + } + } + + void addPad2(std::vector &out) + { + out.push_back({"sceDbcInit", kPad, dbcInit}); + out.push_back({"sceDbcEnd", kPad, dbcEnd}); + out.push_back({"scePad2Init", kPad, init}); + out.push_back({"scePad2End", kPad, end}); + out.push_back({"scePad2CreateSocket", kPad, createSocket}); + out.push_back({"scePad2DeleteSocket", kPad, deleteSocket}); + out.push_back({"scePad2GetState", kPad, getState}); + out.push_back({"scePad2GetButtonProfile", kPad, getButtonProfile}); + out.push_back({"scePad2Read", kPad, read}); + out.push_back({"scePad2GetButtonInfo", kPad, getButtonInfo}); + out.push_back({"sceVibGetProfile", kPad, vibGetProfile}); + out.push_back({"sceVibSetActParam", kPad, vibSetActParam}); + } +} diff --git a/runtime/libs/sif.cpp b/runtime/libs/sif.cpp index 84271d1..2f1e67b 100644 --- a/runtime/libs/sif.cpp +++ b/runtime/libs/sif.cpp @@ -152,7 +152,7 @@ namespace bozo::libs ee::QueuedHandler handler; handler.kind=ee::kInvokeRpcCallback; handler.pc=callback; handler.a[0]=g.arg(8); handler.gp=g.context()->r[28].uw[0]; - l.queueHandler(handler,{}); + l.queueHandler(handler, Resume{}); } g.ret(0); return; } diff --git a/runtime/libs/timer.cpp b/runtime/libs/timer.cpp index 6cc98e0..b9be61b 100644 --- a/runtime/libs/timer.cpp +++ b/runtime/libs/timer.cpp @@ -53,8 +53,8 @@ namespace bozo::libs if (t.hostClock && c.hostDue > t.hostClock()) { const auto left = static_cast(c.hostDue - t.hostClock()); - l.dispatcher()->kernel().scheduleNative(kCounterKeys | slot, due + left * (kEeHz / 1000) / 1000000, - [&l, slot, tag](uint64_t at) { fire(l, slot, tag, at); }); + l.scheduleDeadline(kCounterKeys | slot, due + left * (kEeHz / 1000) / 1000000, kDeadlineTimerFire, + {slot, tag, 0}); return; } const int32_t id = idOf(slot, c); @@ -72,29 +72,7 @@ namespace bozo::libs h.gp = c.gp; h.completion = true; t.inHandler = id; - l.queueHandler(h, [slot, tag, id](Libraries &l2, Guest &g) { - TimerState &s = l2.timers; - if (s.inHandler == id) - s.inHandler = -1; - TimerState::Counter &counter = s.counters[slot]; - if (counter.tag != tag) - return; - const uint64_t r = g.context()->r[2].ud[0]; - if (r == ~0ull || (r == 0 && counter.alarm >= 0)) - { - if (counter.alarm >= 0) - s.alarms[static_cast(counter.alarm)] = -1; - counter = {}; - --s.used; - } - else if (r == 0) - counter.armed = false; - else - { - counter.compare += std::max(r, kMinimumPeriod); - arm(l2, slot, l2.now(g)); - } - }); + l.queueHandler(h, Resume{kResumeTimerHandlerEnd, {slot, tag, static_cast(id)}}); } void arm(Libraries &l, uint32_t slot, uint64_t cycle) @@ -109,8 +87,7 @@ namespace bozo::libs const uint64_t left = c.compare > count ? c.compare - count : 0; const uint32_t tag = c.tag; c.hostDue = t.hostClock ? t.hostClock() + static_cast(static_cast(left) * 1e9 / kBusHz) : 0; - k.scheduleNative(kCounterKeys | slot, cycle + left * 2, - [&l, slot, tag](uint64_t at) { fire(l, slot, tag, at); }); + l.scheduleDeadline(kCounterKeys | slot, cycle + left * 2, kDeadlineTimerFire, {slot, tag, 0}); } void release(Libraries &l, uint32_t slot) @@ -429,8 +406,8 @@ namespace bozo::libs if (t.hostClock && d->second > t.hostClock()) { const auto left = static_cast(d->second - t.hostClock()); - k.scheduleNative(kDelayKeys | static_cast(thread), due + left * (kEeHz / 1000) / 1000000, - [&l, thread](uint64_t at) { delayDue(l, thread, at); }); + l.scheduleDeadline(kDelayKeys | static_cast(thread), due + left * (kEeHz / 1000) / 1000000, + kDeadlineDelayDue, {static_cast(thread), 0, 0}); return; } t.delays.erase(d); @@ -453,8 +430,8 @@ namespace bozo::libs l.timers.delays[thread] = l.timers.hostClock ? l.timers.hostClock() + static_cast(microseconds * 1000) : 0; k.block(thread, ee::kWaitDelay, 0, 0, 0, false, 0, 0); - k.scheduleNative(kDelayKeys | static_cast(thread), l.now(g) + microseconds * kEeHz / 1000000, - [&l, thread](uint64_t at) { delayDue(l, thread, at); }); + l.scheduleDeadline(kDelayKeys | static_cast(thread), l.now(g) + microseconds * kEeHz / 1000000, + kDeadlineDelayDue, {static_cast(thread), 0, 0}); g.ret(0); } @@ -477,6 +454,40 @@ namespace bozo::libs return std::min(left, static_cast(static_cast(to - from) * 1e9 / kEeHz)); } + // A counter handler's end (its v0: stop, keep or re-arm the counter). + void timerResume(Libraries &l, Guest &g, const Resume &r) + { + const uint32_t slot = r.a[0], tag = r.a[1]; + const int32_t id = static_cast(r.a[2]); + TimerState &s = l.timers; + if (s.inHandler == id) + s.inHandler = -1; + TimerState::Counter &counter = s.counters[slot]; + if (counter.tag != tag) + return; + const uint64_t v0 = g.context()->r[2].ud[0]; + if (v0 == ~0ull || (v0 == 0 && counter.alarm >= 0)) + { + if (counter.alarm >= 0) + s.alarms[static_cast(counter.alarm)] = -1; + counter = {}; + --s.used; + } + else if (v0 == 0) + counter.armed = false; + else + { + counter.compare += std::max(v0, kMinimumPeriod); + arm(l, slot, l.now(g)); + } + } + + void timerDeadline(Libraries &l, const std::array &args, uint64_t due) { fire(l, args[0], args[1], due); } + void delayDeadline(Libraries &l, const std::array &args, uint64_t due) + { + delayDue(l, static_cast(args[0]), due); + } + void addTimer(std::vector &out) { for (const auto &[name, handler] : std::initializer_list>{ diff --git a/runtime/native/compiled_libraries.cpp b/runtime/native/compiled_libraries.cpp index 60ede67..8ac1d8a 100644 --- a/runtime/native/compiled_libraries.cpp +++ b/runtime/native/compiled_libraries.cpp @@ -109,7 +109,8 @@ namespace bozo::native::irx bool readyDisc = false; }; std::deque events; - bool readyAudioCompletions = false, deliveringReadyAudio = false; + bool readyAudioCompletions = false, deliveringReadyAudio = false, readyAudioAfterImports = false; + uint64_t rootCallBudget = 1000000; bool nativeDiscFiles = false, deliveringReadyDisc = false; uint64_t discRequestSerial = 0; std::set discRequests; // Actual host read/copy invocations only. @@ -137,6 +138,39 @@ namespace bozo::native::irx }; std::map eventFlags; int32_t nextEventFlag = 1; + // The RPC servers IOP code registered (sceSifRegisterRpc): kept as data so a loaded state registers them again. + struct RpcServer + { + uint32_t function = 0, buffer = 0, gp = 0; + int32_t owner = 0; + }; + std::map rpcServers; + void registerServer(uint32_t id, const RpcServer &server) + { + rpcServers[id] = server; + libraries.sif.servers[id] = [this, function = server.function, buffer = server.buffer, gp = server.gp, + ownerTask = server.owner](libs::Libraries &, libs::Guest &guest, + const libs::NativeRpcRequest &request) + { + syncEe(libraries.now(guest)); + copy(buffer, guest.in(request.send, request.sendBytes), request.sendBytes); + const uint32_t reply = serve(ownerTask, function, gp, request.command, buffer, request.sendBytes); + if (request.receiveBytes) + { + try + { + guest.write(request.receive, memory.data() + physical(reply, request.receiveBytes), + request.receiveBytes); + } + catch (const std::runtime_error &error) + { + throw std::runtime_error(std::format("{}; RPC command {} handler 0x{:x} returned 0x{:x}", + error.what(), request.command, function, reply)); + } + } + runReady(); + }; + } explicit Impl(libs::Libraries &l, uint32_t start) : libraries(l), heapStart(start), libsd(mixer, *this) { if (start >= 0x180000) @@ -258,7 +292,7 @@ namespace bozo::native::irx { ram = o.memory.data(); ramSize = static_cast(o.memory.size()); - budget = 1000000; + budget = o.rootCallBudget; } uint8_t read8(uint32_t a) override { return owner.memory[owner.physical(a, 1)]; } uint16_t read16(uint32_t a) override @@ -302,6 +336,8 @@ namespace bozo::native::irx cpu.gpr[4], cpu.gpr[5])); } cpu.pc = cpu.gpr[31]; + if (owner.readyAudioAfterImports) + owner.deliverReadyAudio(); owner.deliverReadyDisc(); if (owner.current && owner.tasks.at(owner.current).waiting) return false; @@ -462,7 +498,11 @@ namespace bozo::native::irx } void runReady() { - if (!exclusions.empty()) return; + // Inside a running task (it called the EE, and the EE's handler called back here, an IOP RPC or a SIF + // transfer bringing the IOP's clock up): that task waits for its reply on a PS2, and the loop running it + // takes the ready tasks once it yields. Running them here would enter tasks nested, the caller itself too + // (it is not waiting), on its live state. + if (!exclusions.empty() || current) return; for (unsigned pass = 0; pass < 32; ++pass) { bool ran = false; @@ -499,7 +539,13 @@ namespace bozo::native::irx if (!ran) return; } - throw std::runtime_error("native library tasks made no blocking progress"); + { + std::string still; + for (const auto &[id, task] : tasks) + if (!task.done && !task.waiting) + still += std::format(" task {} at 0x{:x} (ra 0x{:x})", id, task.cpu.pc, task.cpu.gpr[31]); + throw std::runtime_error("native library tasks made no blocking progress:" + still); + } } void service(Environment &env, const Import &import); // The SDK's printf family on 32-bit arguments: argument slot k is a0-a3, then the caller's stack from sp + 16. @@ -1359,10 +1405,19 @@ namespace bozo::native::irx return; } // native callbacks are only delivered at safe points } - if (lib == "vblank" && n == 5) + // WaitNonVblank (7): there is no display, so never a vblank to wait out: it returns at once. Jade Cocoon 2's + // M2SOUND calls it. + if (lib == "vblank" && n == 7) + { + ret(); + return; + } + // WaitVblankStart (4), WaitVblankEnd (5) and WaitVblank (6): the task waits for the next native frame tick (no + // display: the start and the end of a vblank are the same tick). Jade Cocoon 2's IMODEMAN.IRX polls on 4. + if (lib == "vblank" && (n == 4 || n == 5 || n == 6)) { if (!current) - throw std::runtime_error("native root WaitVblankEnd"); + throw std::runtime_error("native root vblank wait"); if (!exclusions.empty()) throw std::runtime_error("native frame wait with callbacks excluded"); auto &t = tasks.at(current); t.waiting = true; @@ -1533,9 +1588,38 @@ namespace bozo::native::irx } if (lib == "sifcmd") { + // sceSifInitCmd (4) and sceSifExitCmd (5): there is no command transport to start or stop. + if (n == 4 || n == 5) + { + ret(); + return; + } + // sceSifGetSreg (6) and sceSifSetSreg (7, returns the old value): the IOP side's software registers. + if (n == 6) + { + ret(libraries.sif.iopSreg[a0 & 31u]); + return; + } + if (n == 7) + { + const uint32_t old = libraries.sif.iopSreg[a0 & 31u]; + libraries.sif.iopSreg[a0 & 31u] = a1; + ret(old); + return; + } if (n == 12 || n == 13) { if (a2<16 || a2>112) {ret();return;} + // The set-sreg system command: writes the EE's software register at once (the packet's index at +0x10, + // its value at +0x14). The SDK returns a nonzero transfer id. + if (a0 == 0x80000001u) + { + if (a2 < 0x18 || uint64_t(a1) + a2 > memory.size()) + throw std::runtime_error("native set-sreg packet is outside owned storage"); + libraries.sif.sreg[read(a1 + 0x10) & 31u] = read(a1 + 0x14); + ret(++transferSerial); + return; + } if (a0&0x80000000u) throw std::runtime_error("native user messages do not process system commands"); if (!libraries.sif.receiveCommand) throw std::runtime_error("native EE user-message receiver is not installed"); const auto destination=read(c.gpr[29]+16),suppliedExtra=read(c.gpr[29]+20); @@ -1592,27 +1676,7 @@ namespace bozo::native::irx { const uint32_t function = a2, buffer = a3, gp = c.gpr[28]; const int32_t ownerTask = logicalTask(); - libraries.sif.servers[a1] = [this, function, buffer, gp, ownerTask](libs::Libraries &, libs::Guest &guest, - const libs::NativeRpcRequest &request) - { - syncEe(libraries.now(guest)); - copy(buffer, guest.in(request.send, request.sendBytes), request.sendBytes); - const uint32_t reply = serve(ownerTask, function, gp, request.command, buffer, request.sendBytes); - if (request.receiveBytes) - { - try - { - guest.write(request.receive, memory.data() + physical(reply, request.receiveBytes), - request.receiveBytes); - } - catch (const std::runtime_error &error) - { - throw std::runtime_error(std::format("{}; RPC command {} handler 0x{:x} returned 0x{:x}", - error.what(), request.command, function, reply)); - } - } - runReady(); - }; + registerServer(a1, {function, buffer, gp, ownerTask}); write(a0 + 0x20, a1); write(a0 + 0x28, a2); write(a0 + 0x2c, a3); @@ -1622,6 +1686,7 @@ namespace bozo::native::irx if (n == 15) { const auto found = libraries.sif.eeServers.find(a1); + if (std::getenv("BOZO_NATIVE_IRX_TRACE")) std::fprintf(stderr, "[native-irx:sif] bind EE service 0x%x (client 0x%x, ra 0x%x)\n", a1, a0, c.gpr[31]); write(a0 + 0x24, a1 && found != libraries.sif.eeServers.end() ? a1 : 0); ret(); return; @@ -1721,6 +1786,23 @@ namespace bozo::native::irx std::copy(clock,clock+8,memory.begin()+physical(a0,8)); ret(1);return; } + // sceCdSearchFile (10): the sceCdlFILE record (sector, byte length, name[16], date[8]) from the image's + // ISO directory, as the EE library's sceCdSearchFile writes it; 0 when the file is not there. + if(n==10) + { + auto &disc=libraries.cd.disc;std::string error; + if(!disc.isOpen() && !disc.open(libraries.cd.imagePath,error)){ret(0);return;} + const std::string name=string(a1); + uint32_t lbn=0,bytes=0; + if(!disc.findFile(name,lbn,bytes)){ret(0);return;} + uint8_t record[32]={}; + std::memcpy(record,&lbn,4);std::memcpy(record+4,&bytes,4); + const auto slash=name.find_last_of("/\\"); + const auto leaf=name.substr(slash==std::string::npos?0:slash+1); + std::memcpy(record+8,leaf.data(),std::min(16,leaf.size())); + copy(a0,record,sizeof(record)); + ret(1);return; + } if(n==37) { const bool admitted=std::any_of(images.begin(),images.end(),[&](const auto &image){ @@ -1922,6 +2004,17 @@ namespace bozo::native::irx throw std::runtime_error("native audio completion policy must be installed before execution"); p.readyAudioCompletions = true; } + void CompiledLibraries::setRootCallBudget(uint64_t budget) + { + if (!budget) + throw std::runtime_error("native root call budget must be positive"); + impl_->rootCallBudget = budget; + } + void CompiledLibraries::useReadyAudioCompletionsAfterImports() + { + useReadyAudioCompletions(); + impl_->readyAudioAfterImports = true; + } void CompiledLibraries::useNativeFrameCallbacks() { auto &p = *impl_; @@ -1985,6 +2078,7 @@ namespace bozo::native::irx p.eventFlags.clear(); p.started.clear(); p.libraries.sif.servers.clear(); + p.rpcServers.clear(); p.libraries.sif.bound.clear(); p.nextStack = 0x1fe000; p.invokeDepth = 0; @@ -2027,3 +2121,114 @@ namespace bozo::native::irx } uint64_t CompiledLibraries::nativeCalls() const { return impl_->calls; } } // namespace bozo::native::irx + +namespace bozo::native::irx +{ + // ---- Save states ---- + std::string CompiledLibraries::unsaveable() const + { + const auto &p = *impl_; + if (p.current || p.invokeDepth || !p.exclusions.empty() || p.deliveringReadyAudio || p.deliveringReadyDisc || + p.deliveringFrames) + return "native IOP code is running"; + return {}; + } + + void CompiledLibraries::serialize(state::Archive &a) + { + using state::fields; + using state::pod; + if (const std::string why = unsaveable(); !why.empty()) + throw state::Error("save state: " + why); + auto &p = *impl_; + using Impl = CompiledLibraries::Impl; + a.begin("iop"); + fields(a, p.memory, p.cycle, p.eeOrigin, p.calls, p.origin, p.started, p.nextTask, p.callbackTask, + p.deferredTarget, p.transferSerial, p.nextStack, p.nextTimer, p.readyAudioCompletions, + p.discRequestSerial, p.discRequests, p.discError, p.discCallback, p.discCallbackGp, + p.completedFrames, p.frameListenerSerial, p.commandBuffer, p.commandCapacity, p.commandSerial, + p.nextSema, p.nextEventFlag); + p.heap.serialize(a); + // Tasks + uint64_t n = state::count(a, p.tasks.size()); + auto task = [&](Impl::Task &t) { + pod(a, t.cpu); + pod(a, t.parked); + fields(a, t.waiting, t.done, t.started, t.attr, t.option, t.entry, t.stack, t.stackBytes, t.initialPriority, + t.priority, t.wakeups, t.waitingSema, t.waitingFlag, t.flagPattern, t.flagMode, t.flagResult, + t.sleeping, t.due, t.serving, t.replied, t.reply); + }; + if (!a.loading()) + for (auto &[id, t] : p.tasks) + { + int32_t k = id; + fields(a, k); + task(t); + } + else + { + p.tasks.clear(); + for (uint64_t i = 0; i < n; ++i) + { + int32_t k = 0; + fields(a, k); + task(p.tasks[k]); + } + } + auto interrupt = [&](Impl::Interrupt &i) { fields(a, i.function, i.argument, i.gp, i.enabled); }; + auto each = [&](auto &map, auto &&walk) { + using Map = std::remove_reference_t; + uint64_t c = state::count(a, map.size()); + if (!a.loading()) + for (auto &[key, value] : map) + { + typename Map::key_type k = key; + fields(a, k); + walk(value); + } + else + { + map.clear(); + for (uint64_t i = 0; i < c; ++i) + { + typename Map::key_type k{}; + fields(a, k); + walk(map[k]); + } + } + }; + each(p.interrupts, interrupt); + each(p.timers, [&](Impl::Timer &t) { + fields(a, t.compare, t.mode, t.cause, t.rate, t.prescale, t.due, t.configured, t.direct, t.alarm, t.revision); + interrupt(t.handler); + }); + each(p.frameListeners, [&](Impl::FrameListener &f) { + interrupt(f.callback); + fields(a, f.priority, f.order); + }); + each(p.commandHandlers, interrupt); + each(p.semas, [&](Impl::Sema &s) { fields(a, s.count, s.initial, s.max, s.attr, s.option, s.waiting); }); + each(p.eventFlags, [&](Impl::EventFlag &f) { fields(a, f.attr, f.option, f.initial, f.bits, f.waiting); }); + n = state::count(a, p.events.size()); + if (a.loading()) + p.events.resize(n); + for (auto &e : p.events) + fields(a, e.due, e.function, e.a0, e.a1, e.gp, e.readyAudio, e.ownedBuffer, e.readyDisc); + if (a.loading()) // the servers this run's IOP code registered are dropped first + for (const auto &[id, server] : p.rpcServers) + p.libraries.sif.servers.erase(id); + each(p.rpcServers, [&](Impl::RpcServer &r) { fields(a, r.function, r.buffer, r.gp, r.owner); }); + if (a.loading()) + { + p.current = 0; + p.invokeDepth = 0; + p.exclusions.clear(); + const auto servers = p.rpcServers; + for (const auto &[id, server] : servers) + p.registerServer(id, server); + } + p.mixer.serialize(a, p.memory.data(), p.memory.size()); + p.libsd.serialize(a); + a.end(); + } +} diff --git a/runtime/render/mesh_draw.cpp b/runtime/render/mesh_draw.cpp index 7f44a26..747cb43 100644 --- a/runtime/render/mesh_draw.cpp +++ b/runtime/render/mesh_draw.cpp @@ -161,6 +161,8 @@ namespace bozo::render Material material; material.textured = batch.textured && batch.texture != nullptr; material.tex0 = batch.tex0; + material.clampU = batch.clampU; + material.clampV = batch.clampV; material.blend = batch.blended ? meshBlend(gs.alpha) : Material::Blend::Opaque; material.depthWrite = !gs.depthMasked; const uint32_t atst = (gs.test >> 1) & 7u, aref = (gs.test >> 4) & 0xffu; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 58d6bc2..42e81e7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -364,6 +364,13 @@ if(MINGW) endif() add_test(NAME library_user_commands COMMAND bozo-library-command-tests) set_tests_properties(library_user_commands PROPERTIES TIMEOUT 10) +add_executable(bozo-library-sreg-tests native/library_sreg_tests.cpp) +target_link_libraries(bozo-library-sreg-tests PRIVATE bozo_libs) +if(MINGW) + target_link_options(bozo-library-sreg-tests PRIVATE -static) +endif() +add_test(NAME library_sregs COMMAND bozo-library-sreg-tests) +set_tests_properties(library_sregs PROPERTIES TIMEOUT 10) add_executable(bozo-library-allocation-tests native/library_allocation_tests.cpp) target_link_libraries(bozo-library-allocation-tests PRIVATE bozo_libs) if(MINGW) @@ -399,3 +406,11 @@ if(MINGW) endif() add_test(NAME library_heap_queries COMMAND bozo-library-heap-queries-tests) set_tests_properties(library_heap_queries PROPERTIES TIMEOUT 10) + +# Save states (bozo/state.h): archives, files, a dispatcher saved and loaded. +add_executable(bozo-state-tests runtime/state_tests.cpp) +target_link_libraries(bozo-state-tests PRIVATE bozo_runtime_core) +if(MINGW) + target_link_options(bozo-state-tests PRIVATE -static) +endif() +add_test(NAME state COMMAND bozo-state-tests) diff --git a/tests/libs/cd_callback_tests.cpp b/tests/libs/cd_callback_tests.cpp index cb89493..cfedc30 100644 --- a/tests/libs/cd_callback_tests.cpp +++ b/tests/libs/cd_callback_tests.cpp @@ -81,6 +81,18 @@ int main() { host.l.cd.readEnd=0; check(call("sceCdCallback",{0})==0x155004 && host.l.cd.callback==0); check(call("sceCdCallback",{0x155000})==0); + // Timed completion: the read returns without the drive's time and its callback waits on a kernel deadline at + // the read's end, not on the handler queue. + host.l.cd.timedCompletion=true; + { + c.r[4].uw[0]=22;c.r[5].uw[0]=1;c.r[6].uw[0]=0x110000; + libs::Guest g(d.runtime(),&c);const uint64_t before=host.l.now(g); + host.l.find("sceCdRead")->handler(host.l,g); + check(c.r[2].sw[0]==1 && g.cycles(m.rt->memory.ram()+0x120000+32),"one"),0); m.call("sceMcGetDir",{0,0,0x110000,1,2,0x120000}); eq("listing terminates",m.result(),0); + // Creation order, not name order: a card lists "b" made before "a" first, and a file made again keeps its place. + m.libs.mc.card(0).create("ORDER",true,m.libs.mc.date); + m.libs.mc.card(0).create("ORDER/b",false,m.libs.mc.date); + m.libs.mc.card(0).create("ORDER/a",false,m.libs.mc.date); + m.libs.mc.card(0).create("ORDER/b",false,m.libs.mc.date); + const auto ordered=m.libs.mc.card(0).list("ORDER"); + eq("listing in creation order",ordered.size()==2&&ordered[0]=="ORDER/b"&&ordered[1]=="ORDER/a",1); m.string(0x110000,".."); m.call("sceMcChdir",{0,0,0x110000,0});eq("parent directory",m.result(),0); eq("parent restored root",m.libs.mc.currentDirectory[0].empty(),1); @@ -541,6 +548,97 @@ static void padCalls() eq("req name", std::strcmp(reinterpret_cast(m.rt->memory.ram() + 0x100300), "BUSY"), 0); } +// libpad2 and libvib (pad2.cpp): sockets on libpad's controllers, the 18-byte report, the profile and the motors. +static void pad2Calls() +{ + struct Recorder final : bozo::libs::PadInput + { + void read(uint32_t, int player, bozo::libs::PadInputState &out) override + { + out = bozo::libs::PadInputState{}; + out.connected = player == 0; + if (player != 0) + return; + out.buttons = bozo::libs::kPadCross | bozo::libs::kPadR1 | bozo::libs::kPadSelect; + out.lx = 0x10; + out.ry = 0xF0; + for (int i = 0; i < 12; ++i) + out.pressure[static_cast(i)] = (out.buttons & bozo::libs::kPadPressureOrder[i]) ? 0xC8 : 0x00; + } + void rumble(int player, bool small, uint8_t large) override { last = {player, small, large}; } + struct { int player = -1; bool small = false; uint8_t large = 0; } last; + } input; + Machine m; + m.libs.pad.input = &input; + eq("dbc init", m.call("sceDbcInit", {}), 1); + eq("pad2 init", m.call("scePad2Init", {0}), 1); + auto words = [&](uint32_t at, std::initializer_list values) + { + for (uint32_t v : values) { std::memcpy(m.rt->memory.ram() + at, &v, 4); at += 4; } + }; + words(0x100000, {2, 0, 0, 0x5A5A}); // flag, port 0, slot 0, an uninitialised number + words(0x100040, {2, 1, 0, 0}); // port 1 + eq("unaligned buffer", m.call("scePad2CreateSocket", {0x100000, 0x100204}), -1); + const int32_t first = m.call("scePad2CreateSocket", {0x100000, 0x100200}); + const int32_t second = m.call("scePad2CreateSocket", {0x100040, 0x100300}); + eq("socket numbers", first >= 0 && second >= 0 && first != second, 1); + eq("a connected pad is stable", m.call("scePad2GetState", {static_cast(first)}), 1); + eq("port 2's pad is there, idle", m.call("scePad2GetState", {static_cast(second)}), 1); + eq("no such socket", m.call("scePad2GetState", {99}), 0); + eq("profile size", m.call("scePad2GetButtonProfile", {static_cast(first), 0x100400}), 4); + eq("every button id", m.rt->memory.ram()[0x100400] & m.rt->memory.ram()[0x100403], 0xFF); + eq("report size", m.call("scePad2Read", {static_cast(first), 0x100500}), 18); + const uint8_t *d = m.rt->memory.ram() + 0x100500; + eq("buttons active low, SELECT bit 0", d[0], 0xFE); + eq("R1 and CROSS clear in the second byte", d[1], 0xFF & ~((bozo::libs::kPadR1 | bozo::libs::kPadCross) >> 8)); + eq("sticks RX RY LX LY", d[2] == 0x80 && d[3] == 0xF0 && d[4] == 0x10 && d[5] == 0x80, 1); + eq("cross pressure in the controller's place (byte 12)", d[12], 0xC8); + eq("R1 pressure after L1 (byte 15)", d[15], 0xC8); + eq("L2 pressure (byte 16)", d[16], 0x00); + eq("button info: cross (id 14) pressed", m.call("scePad2GetButtonInfo", {0, 0x100500, 14}), 1); + eq("button info: start (id 3) released", m.call("scePad2GetButtonInfo", {0, 0x100500, 3}), 0); + eq("button info: LX (id 18)", m.call("scePad2GetButtonInfo", {0, 0x100500, 18}), 0x10); + eq("button info: no id 32", m.call("scePad2GetButtonInfo", {0, 0x100500, 32}), -1); + eq("vibration profile", m.call("sceVibGetProfile", {static_cast(first), 0x100600}), 1); + eq("two motors", m.rt->memory.ram()[0x100600], 3); + m.rt->memory.ram()[0x100700] = 0x01 | (0x55 << 1); // small on, large 0xD5's low seven bits + m.rt->memory.ram()[0x100701] = 0x01; // large bit 7 + eq("motors set", m.call("sceVibSetActParam", {static_cast(first), 1, 0x100600, 2, 0x100700}), 1); + eq("rumble to player 1", input.last.player == 0 && input.last.small && input.last.large == 0xD5, 1); + eq("delete", m.call("scePad2DeleteSocket", {static_cast(first)}), 1); + eq("deleted socket has no pad", m.call("scePad2Read", {static_cast(first), 0x100500}), -1); + eq("end", m.call("scePad2End", {}), 1); + eq("dbc end", m.call("sceDbcEnd", {}), 1); +// libmpeg off the reference layout (MpegOptions, a game on the SDK's model): the SDK's results, nothing written outside +// the work area, sceMpegAddBs taking ((bytes + 19) >> 4) << 4 bytes of coded video, sceMpegIsEnd from the stream alone. +static void mpegSdkModel() +{ + Machine m; + m.libs.mpegOptions.referenceLayout = false; + m.libs.mpegOptions.paced = false; + m.libs.mpegOptions.sdkNodata = true; + const uint32_t tmbWord = 0x1717BC; + std::memset(m.rt->memory.ram() + tmbWord, 0xAB, 4); + eq("init (SDK)", m.call("sceMpegInit", {}), 1); + eq("create (SDK)", m.call("sceMpegCreate", {0x100000, 0x110000, 0x122800}), 1); + eq("no write to TMB's address", m.rt->memory.ram()[tmbWord], 0xAB); + eq("first callback: none before", m.call("sceMpegAddCallback", {0x100000, 1, 0x1BE698, 0x200000}), 0); + eq("again: the previous one", m.call("sceMpegAddCallback", {0x100000, 1, 0x1BE6A0, 0x200000}), 0x1BE698); + // A sequence header and a picture start, 0xFB0 bytes given: 0xFC0 taken, as the SDK sends to the IPU. + uint8_t *bs = m.rt->memory.ram() + 0x120000; + std::memset(bs, 0, 0x1000); + const uint8_t seq[] = {0, 0, 1, 0xB3}, pic[] = {0, 0, 1, 0x00}; + std::memcpy(bs, seq, 4); + std::memcpy(bs + 0x40, pic, 4); + eq("add bs", m.call("sceMpegAddBs", {0x100000, 0x120000, 0xFB0}), 1); + eq("rounded up to 16 with the 19", m.libs.mpeg.es.size(), 0xFC0); + eq("its picture counted", m.libs.mpeg.pictureStarts, 1); + eq("not the end while input may come", m.call("sceMpegIsEnd", {0x100000}), 0); + m.call("sceMpegReset", {0x100000}); + eq("reset leaves TMB's static word alone", m.rt->memory.ram()[0x171904], 0); + eq("delete (SDK)", m.call("sceMpegDelete", {0x100000}), 1); +} + static void cardCalls() { Machine m; @@ -758,6 +856,8 @@ static void debugCalls() int main() { padCalls(); + pad2Calls(); + mpegSdkModel(); cardCalls(); dmaCalls(); sifCalls(); diff --git a/tests/native/library_sreg_tests.cpp b/tests/native/library_sreg_tests.cpp new file mode 100644 index 0000000..8628b1d --- /dev/null +++ b/tests/native/library_sreg_tests.cpp @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MIT +// sifcmd's software registers on both sides (sceSifGetSreg 6, sceSifSetSreg 7, a module's set-sreg system command), +// sceSifInitCmd/sceSifExitCmd (4/5), cdvdman's constant answers under native disc files (sceCdInit 4, sceCdDiskReady +// 13, sceCdMmode 75), the root call budget, and ready audio completions delivered when an import returns. +#include "bozo/native/compiled_libraries.h" +#include +#include +#include +using namespace bozo::native::irx; +namespace { +void check(bool ok){if(!ok)throw std::runtime_error("native software register assertion failed");} +void placeholder(Env &){throw std::runtime_error("unbound software register fixture");} +const Entry entries[]={{0x14000,placeholder},{0x14010,placeholder},{0x14020,placeholder}}; +const Registration registration("sreg",0x5e6,0x14000,0x400,entries,3); +uint32_t call(Env &e,uint32_t fn,uint32_t a=0,uint32_t b=0,uint32_t c=0,uint32_t d=0){ + e.cpu.gpr[4]=a;e.cpu.gpr[5]=b;e.cpu.gpr[6]=c;e.cpu.gpr[7]=d;e.cpu.gpr[31]=0x14004; + check(e.call(fn,0x14004));return e.cpu.gpr[2]; +} +Image image(){ + return {"sreg",0x5e6,0x14000,0x14000,0x12345678,std::vector(0x400), + {{0x14300,"sifcmd",4},{0x14308,"sifcmd",5},{0x14310,"sifcmd",6},{0x14318,"sifcmd",7},{0x14320,"sifcmd",12}, + {0x14328,"cdvdman",4},{0x14330,"cdvdman",13},{0x14338,"cdvdman",75}},{},false}; +} +// Registers, commands and constant answers, all inside the module's start (a root call). +void registers(){ + bozo::libs::Libraries libraries;CompiledLibraries host{libraries,0x20000}; + host.addImage(image());host.useNativeDiscFiles(); + libraries.sif.iopSreg[0x1f]=0x7000; // what the EE side wrote (a port answering its set-sreg) + host.bindNative(0x14000,[&](Env &e){ + const auto caller=e.cpu.gpr[31]; + check(call(e,0x14300)==0 && call(e,0x14308)==0); + check(call(e,0x14310,0x1f)==0x7000 && call(e,0x14310,0x3f)==0x7000); // the index wraps at 32 + check(call(e,0x14318,0x1e,0x1234)==0 && call(e,0x14318,0x1e,0x5678)==0x1234 && libraries.sif.iopSreg[0x1e]==0x5678); + // set-sreg to the EE: index at +0x10, value at +0x14 of a 0x18-byte packet; a nonzero id comes back. + e.w32(0x14200+0x10,0x1d);e.w32(0x14200+0x14,0xabcd); + e.cpu.gpr[7]=0;e.w32(e.cpu.gpr[29]+16,0);e.w32(e.cpu.gpr[29]+20,0); + check(call(e,0x14320,0x80000001u,0x14200,0x18)!=0 && libraries.sif.sreg[0x1d]==0xabcd); + bool rejected=false;try{call(e,0x14320,0x80000001u,0x14200,0x10);}catch(const std::runtime_error &){rejected=true;} + check(rejected && libraries.sif.sreg[0x1d]==0xabcd); + check(call(e,0x14328,0)==1 && call(e,0x14330,0)==2 && call(e,0x14338,2)==1); + e.cpu.pc=caller; + }); + check(host.startImage("sreg")==1); +} +// A start that does more work than the default root call allows fails, and succeeds once the budget is raised. +void budget(){ + for(bool raised:{false,true}){ + bozo::libs::Libraries libraries;CompiledLibraries host{libraries,0x20000}; + host.addImage(image());if(raised)host.setRootCallBudget(5000000); + host.bindNative(0x14000,[](Env &e){ + const auto caller=e.cpu.gpr[31];call(e,0x14010);e.cpu.pc=caller; + }); + host.bindNative(0x14010,[](Env &e){ + for(unsigned i=0;i<3000000;++i)e.tick(1); + e.cpu.pc=e.expired()?0x14010:e.cpu.gpr[31]; + }); + bool failed=false;try{host.startImage("sreg");}catch(const std::runtime_error &){failed=true;} + check(failed!=raised); + } + bozo::libs::Libraries libraries;CompiledLibraries host{libraries,0x20000};bool rejected=false; + try{host.setRootCallBudget(0);}catch(const std::runtime_error &){rejected=true;}check(rejected); +} +// A libsd transfer's completion callback: after the import returns with the import-time policy, only after a linked +// function returns with the plain one. +void afterImports(){ + for(bool atImports:{false,true}){ + bozo::libs::Libraries libraries;CompiledLibraries host{libraries,0x20000}; + Image i=image();i.imports={{0x14300,"libsd",4},{0x14308,"libsd",26},{0x14310,"libsd",17}}; + host.addImage(i); + if(atImports)host.useReadyAudioCompletionsAfterImports();else host.useReadyAudioCompletions(); + unsigned completions=0;bool seenAtImport=false; + host.bindNative(0x14020,[&](Env &e){++completions;e.cpu.pc=e.cpu.gpr[31];}); + host.bindNative(0x14000,[&](Env &e){ + const auto caller=e.cpu.gpr[31];call(e,0x14300);call(e,0x14308,0,0x14020,0); + for(unsigned b=0;b<64;++b)e.w8(0x14100+b,uint8_t(b)); + e.w32(e.cpu.gpr[29]+16,64); + check(call(e,0x14310,0,0,0x14100,0x1000)==64); + seenAtImport=completions==1; // a call-free poll would see the flag here + e.cpu.pc=caller; + }); + check(host.startImage("sreg")==1 && seenAtImport==atImports); + host.advanceTo(100000);check(completions==1); + } +} +} +int main(){try{ + registers();budget();afterImports(); + std::puts("native sregs both ways/set-sreg/init-exit/cdvdman constants/root budget/import-time audio completions passed");return 0; +}catch(const std::exception &e){std::fprintf(stderr,"%s\n",e.what());return 1;}} diff --git a/tests/runtime/state_tests.cpp b/tests/runtime/state_tests.cpp new file mode 100644 index 0000000..d193732 --- /dev/null +++ b/tests/runtime/state_tests.cpp @@ -0,0 +1,211 @@ +// Save states (bozo/state.h): the archive's walkers and sections, the file header, and a kernel and dispatcher saved +// then loaded into a second runtime (which then saves the same bytes). +#include "bozo/ee/dispatcher.h" +#include "bozo/state.h" + +#include +#include +#include + +using namespace bozo; + +namespace +{ + int failures = 0; + void check(bool v, const char *what) + { + if (!v) + { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } + } + template bool throws(F f) + { + try + { + f(); + } + catch (const state::Error &) + { + return true; + } + return false; + } + + struct Point + { + int32_t x = 0; + std::string name; + }; + void io(state::Archive &a, Point &p) { state::fields(a, p.x, p.name); } + + struct NullHost final : ee::Host + { + void libraryCall(ee::Dispatcher &, R5900Context *, uint32_t) override {} + void vu0Microprogram(ee::Dispatcher &, R5900Context *, uint32_t) override {} + void ioRead(ee::Dispatcher &, R5900Context *, uint32_t, uint32_t, uint64_t[2]) override {} + void ioWrite(ee::Dispatcher &, R5900Context *, uint32_t, uint32_t, const uint64_t[2]) override {} + void fault(ee::Dispatcher &, R5900Context *, const std::string &s) override { throw std::runtime_error(s); } + }; + + void archives() + { + state::Archive w; + std::map> m{{3, {{1, "a"}, {2, "bc"}}}, {9, {}}}; + std::unordered_map> u{{5, {1, 2}}, {-1, {7}}}; + std::array arr{1, 2, 3}; + uint32_t c[2][2] = {{1, 2}, {3, 4}}; + std::set names{"x", "y"}; + std::unique_ptr some = std::make_unique(Point{7, "seven"}), none; + bool flag = true; + uint8_t b = 42; + w.begin("outer"); + state::fields(w, m, u, arr, c, names, some, none, flag); + w.begin("inner"); + state::fields(w, b); + w.end(); + w.end(); + + state::Archive r(w.data()); + std::map> m2; + std::unordered_map> u2; + std::array arr2{}; + uint32_t c2[2][2] = {}; + std::set names2; + std::unique_ptr some2, none2 = std::make_unique(); + bool flag2 = false; + uint8_t b2 = 0; + r.begin("outer"); + state::fields(r, m2, u2, arr2, c2, names2, some2, none2, flag2); + r.begin("inner"); + state::fields(r, b2); + r.end(); + r.end(); + check(r.atEnd(), "reader at the end"); + check(m2.size() == 2 && m2[3].size() == 2 && m2[3][1].name == "bc" && m2[9].empty(), "map of vectors of structs"); + check(u2 == u, "unordered map"); + check(arr2 == arr && c2[1][0] == 3, "arrays"); + check(names2 == names, "set"); + check(some2 && some2->x == 7 && some2->name == "seven" && !none2, "unique_ptr"); + check(flag2 && b2 == 42, "scalars"); + + // The same state always gives the same bytes (unordered maps in key order). + state::Archive w2; + w2.begin("outer"); + state::fields(w2, m2, u2, arr2, c2, names2, some2, none2, flag2); + w2.begin("inner"); + state::fields(w2, b2); + w2.end(); + w2.end(); + check(w2.data() == w.data(), "written again: the same bytes"); + + // A reader that names another section, leaves fields unread, or reads past a section fails. + check(throws([&] { + state::Archive x(w.data()); + x.begin("other"); + }), + "wrong section name"); + check(throws([&] { + state::Archive x(w.data()); + x.begin("outer"); + x.end(); + }), + "fields left unread"); + check(throws([&] { + state::Archive x(w.data()); + x.begin("outer"); + std::vector big(1 << 20); + x.raw(big.data(), big.size()); + }), + "reading past a section"); + } + + void files() + { + const std::string path = (std::filesystem::temp_directory_path() / "bozo_state_test.state").string(); + state::Archive w; + uint32_t v = 0xC0FFEE; + w.begin("s"); + state::fields(w, v); + w.end(); + state::writeFile(path, "GAME-1", w); + state::Archive r = state::readFile(path, "GAME-1"); + uint32_t v2 = 0; + r.begin("s"); + state::fields(r, v2); + r.end(); + check(v2 == v && r.atEnd(), "file round trip"); + check(throws([&] { state::readFile(path, "GAME-2"); }), "another game's file"); + check(throws([&] { state::readFile(path + ".missing", "GAME-1"); }), "a missing file"); + std::filesystem::remove(path); + } + + void runtimes() + { + NullHost h1, h2; + ee::Dispatcher d1(h1), d2(h2); + d1.boot(0x100000, 0x1FFFFF0u); + ee::Kernel &k = d1.kernel(); + const int32_t t = k.createThread(0x100100, 0x1000000, 0x4000, 10, 0x123456, 0, 0); + k.startThread(t, 77, false); + const int32_t s = k.createSema(0, 4, 0, 0); + k.signalSema(s, false); + k.setAlarm(123456, 0x100200, 9, 0x123456, false); + k.addHandler(false, 2, 0x100300, 0, 5, 0x123456, 0); + d1.runtime().memory.ram()[0x1234] = 0x5A; + d1.runtime().memory.scratchpad()[7] = 0xA5; + + state::Archive a; + d1.serialize(a); + state::Archive r(a.data()); + d2.serialize(r); + check(r.atEnd(), "dispatcher state read whole"); + check(d2.runtime().memory.ram()[0x1234] == 0x5A && d2.runtime().memory.scratchpad()[7] == 0xA5, "memory"); + check(d2.kernel().thread(t) && d2.kernel().thread(t)->priority == 10 && + d2.kernel().thread(t)->frames[0]->ctx.r[4].uw[0] == 77, + "a thread and its context"); + check(d2.kernel().nextEvent() == d1.kernel().nextEvent(), "deadlines and vblanks"); + state::Archive again; + d2.serialize(again); + check(again.data() == a.data(), "the loaded runtime saves the same bytes"); + + // A native deadline with no kind cannot be saved; one with a kind is rebuilt by nativeRebuild. + k.scheduleNative(0x77000001u, 1000, [](uint64_t) {}); + check(!d1.unsaveable().empty(), "an opaque native deadline is unsaveable"); + k.cancelDeadline(0x77000001u); + int fired = 0; + k.scheduleNative(0x77000002u, 10, 5, {1, 2, 3}, [](uint64_t) {}); + d2.kernel().nativeRebuild = [&](uint32_t kind, const std::array &args) { + std::function fn; + if (kind == 5 && args[2] == 3) + fn = [&](uint64_t) { ++fired; }; + return fn; + }; + state::Archive b; + d1.serialize(b); + state::Archive rb(b.data()); + d2.serialize(rb); + d2.kernel().processEvents(10); + check(fired == 1, "a native deadline rebuilt from its kind runs"); + } +} + +int main() +{ + try + { + archives(); + files(); + runtimes(); + } + catch (const std::exception &e) + { + std::fprintf(stderr, "FAIL: %s\n", e.what()); + return 1; + } + if (failures) + return 1; + std::printf("state tests passed\n"); + return 0; +} diff --git a/tools/native_irx/recompile.py b/tools/native_irx/recompile.py index 0999a23..ebc1a85 100644 --- a/tools/native_irx/recompile.py +++ b/tools/native_irx/recompile.py @@ -285,7 +285,8 @@ def after_return(target): def find_functions(module, exports, imports, extra=()): code_end = module.base + module.size - seeds = {module.entry} | set(exports) | pointer_seeds(module) | set(extra) + guessed = pointer_seeds(module) + seeds = {module.entry} | set(exports) | guessed | set(extra) functions = {} while True: bounds = sorted(seeds) @@ -309,6 +310,22 @@ def find_functions(module, exports, imports, extra=()): fn = functions.get(start) if fn and any(addr >= limit for addr in fn.insns): del functions[start] + # pointer_seeds guesses from data words: a word that happens to hold an address right after a function's end is + # taken for a pointer to a leaf. A guess that is not code (it cannot be recompiled) and that no recompiled function + # calls is data, not a function: it is left out instead of failing the module (Jade Cocoon 2's IMODEMAN.IRX, + # 0x84c10 at base 0x6a100). The entry, the exports and --entry addresses are never dropped. + certain = {module.entry} | set(exports) | set(extra) + while True: + called = set() + for fn in functions.values(): + if not fn.unsafe: + called |= set(fn.calls) + dropped = [start for start, fn in functions.items() + if fn.unsafe and start in guessed and start not in certain and start not in called] + if not dropped: + break + for start in dropped: + del functions[start] return functions