mirror of
https://github.com/TheBozos/BozoEngine.git
synced 2026-12-01 12:53:50 -10:00
Save states: the whole runtime saved and loaded at the dispatcher's safe point
A state is taken at the top of Dispatcher::run's loop, where no guest code is on the host stack: memory, the dispatcher, the kernel (threads, frames, queues, deadlines), every library's state, the native IOP host (memory, tasks, kernel objects, RPC servers, mixer, libsd) and sections ports add (state::Sections). Parked library lambdas become data: Resume records and native deadline kinds, rebuilt from tables on load; ports can add their own kinds. FreeHost serves requestSave / requestLoad from any thread, rolls back a failed load, and takes FreeOptions (gameTag, loadState[Frame], saveState[Frame]). Windows get ten slots: F5 save, F7 load, F6 / Shift+F6 select, and a Save states tab in F2. 989SND's engine and a playing movie are not covered: a save waits, saying why. docs/save-states.md tells a port how to use and check it; tests/runtime/state_tests.cpp covers the archive, files and a dispatcher round trip. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
9261dfd626
commit
b73692ed37
31 files changed
+1768
-84
No files matched your search
@@ -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.
|
||||
@@ -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,6 +24,8 @@ 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
|
||||
|
||||
@@ -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 <SDL3/SDL.h>
|
||||
|
||||
@@ -21,9 +22,12 @@
|
||||
#include "imgui_impl_sdl3.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <numeric>
|
||||
@@ -32,6 +36,11 @@
|
||||
|
||||
namespace bozo::app
|
||||
{
|
||||
namespace
|
||||
{
|
||||
void drawNotice();
|
||||
}
|
||||
|
||||
struct Panel::Impl
|
||||
{
|
||||
SDL_Window *window = nullptr;
|
||||
@@ -170,10 +179,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<std::chrono::system_clock>(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<int> 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<void(int)> save, std::function<void(int)> 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()
|
||||
|
||||
+12
-1
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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<uint64_t>(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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// Save state archives and files (bozo/state.h).
|
||||
#include "bozo/state.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
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<const uint8_t *>(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("<file>") : 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<char *>(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<uint8_t> 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<uint8_t> rest;
|
||||
const size_t used = sizeof kMagic + sizeof version + sizeof(uint64_t) + tag.size();
|
||||
rest.assign(header.data().begin() + static_cast<std::ptrdiff_t>(used), header.data().end());
|
||||
return Archive(std::move(rest));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<uint32_t, 3> args,
|
||||
std::function<void(uint64_t)> 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();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
@@ -565,6 +568,13 @@ namespace bozo::host
|
||||
libs_.framesEnded = static_cast<uint32_t>(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 +589,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<uint32_t>(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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@
|
||||
// user folder.
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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<void(int)> save, std::function<void(int)> load);
|
||||
|
||||
class Panel
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -48,8 +48,20 @@ namespace bozo::app
|
||||
std::function<int()> run; // the game thread's body: runs until the game ends (its exit code)
|
||||
std::function<void()> stop; // any thread: asks the game to end
|
||||
std::function<uint64_t()> 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<void(int slot)> 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).
|
||||
|
||||
@@ -93,6 +93,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();
|
||||
|
||||
@@ -27,6 +27,11 @@
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
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
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
#include "bozo/ee/kernel.h"
|
||||
#include "bozo/runtime.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -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<void()> safePoint;
|
||||
std::atomic<bool> 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) ----
|
||||
|
||||
@@ -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 <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<void(uint64_t)> 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<uint32_t, 3> args,
|
||||
std::function<void(uint64_t)> fn);
|
||||
using NativeRebuild = std::function<std::function<void(uint64_t)>(uint32_t kind, const std::array<uint32_t, 3> &)>;
|
||||
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<void(uint64_t)> native; };
|
||||
struct Deadline
|
||||
{
|
||||
uint64_t cycle = 0;
|
||||
QueuedHandler handler;
|
||||
std::function<void(uint64_t)> native;
|
||||
uint32_t nativeKind = 0; // 0: none, or a native deadline that cannot be saved
|
||||
std::array<uint32_t, 3> nativeArgs{};
|
||||
};
|
||||
std::map<uint32_t, Deadline> deadlines_;
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
@@ -48,6 +49,13 @@ namespace bozo::host
|
||||
// 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 +105,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<void(bool ok, const std::string &message)> onStateMessage;
|
||||
|
||||
// ee::Host
|
||||
void libraryCall(ee::Dispatcher &, R5900Context *ctx, uint32_t target) override;
|
||||
void vu0Microprogram(ee::Dispatcher &, R5900Context *ctx, uint32_t address) override;
|
||||
@@ -165,6 +182,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<bool> stopRequested_{false};
|
||||
std::atomic<uint64_t> framesEnded_{0};
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "bozo/libs/sif.h"
|
||||
#include "bozo/libs/snd.h"
|
||||
#include "bozo/libs/timer.h"
|
||||
#include "bozo/state.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
@@ -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<uint32_t, 4> 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 heap entry
|
||||
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<uint32_t, uint32_t> 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<void(Libraries &, Guest &)> end);
|
||||
std::function<void(Libraries &, Guest &)> 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<uint32_t, 3> &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<uint32_t, 3> 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.
|
||||
@@ -237,8 +283,16 @@ namespace bozo::libs
|
||||
ee::Dispatcher *d_ = nullptr;
|
||||
std::vector<Function> functions_;
|
||||
std::unordered_map<std::string, size_t> byName_;
|
||||
std::map<int32_t, std::function<void(Libraries &, Guest &)>> continuations_;
|
||||
std::map<uint64_t, std::function<void(Libraries &, Guest &)>> handlerEnds_;
|
||||
struct Pending
|
||||
{
|
||||
std::function<void(Libraries &, Guest &)> run;
|
||||
Resume resume; // kind kResumeNone with `run` set: not saveable
|
||||
};
|
||||
Pending pending(const Resume &r);
|
||||
std::map<int32_t, Pending> continuations_;
|
||||
std::map<uint64_t, Pending> handlerEnds_;
|
||||
std::map<uint32_t, ResumeFunction> resumeKinds_;
|
||||
std::map<uint32_t, DeadlineFunction> deadlineKinds_;
|
||||
};
|
||||
|
||||
// Each library's functions (libc.cpp, libm.cpp, gs.cpp, pad.cpp, mc.cpp).
|
||||
@@ -252,6 +306,12 @@ namespace bozo::libs
|
||||
void addMpeg(std::vector<Function> &out); // nothing without a video decoder (FFmpeg)
|
||||
void addSif(std::vector<Function> &out);
|
||||
void addTimer(std::vector<Function> &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<uint32_t, 3> &args, uint64_t due);
|
||||
void delayDeadline(Libraries &l, const std::array<uint32_t, 3> &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);
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// docs/specs/libraries.md section 7.
|
||||
#pragma once
|
||||
|
||||
#include "bozo/state.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
@@ -47,6 +49,7 @@ 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<std::string, Entry> entries_;
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
// allocator handed out (989SND's banks and buffers come from it too).
|
||||
#pragma once
|
||||
|
||||
#include "bozo/state.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
@@ -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<uint32_t, uint32_t> free_; // start -> bytes
|
||||
|
||||
@@ -63,6 +63,10 @@ namespace bozo::native::irx
|
||||
// stack, opaque module handle, device address or freed block.
|
||||
std::span<uint8_t> 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;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "bozo/runtime.h"
|
||||
#include "bozo/state.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
@@ -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 --------------------------------------------------------------------------
|
||||
|
||||
@@ -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 <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<uint8_t> 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<uint8_t> &data() const { return data_; }
|
||||
bool atEnd() const { return pos_ == data_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> data_;
|
||||
size_t pos_ = 0;
|
||||
bool loading_ = false;
|
||||
std::vector<std::pair<std::string, size_t>> 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<void(Archive &)> serialize;
|
||||
std::function<std::string()> 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<Section> &all() { return sections_; }
|
||||
|
||||
private:
|
||||
std::vector<Section> 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 <class T>
|
||||
requires(std::is_arithmetic_v<T> || std::is_enum_v<T>)
|
||||
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 <class T> void pod(Archive &a, T &v)
|
||||
{
|
||||
static_assert(std::is_trivially_copyable_v<T>);
|
||||
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 <class T, size_t N> void io(Archive &a, T (&v)[N]);
|
||||
template <class T, size_t N> void io(Archive &a, std::array<T, N> &v);
|
||||
template <class T> void io(Archive &a, std::vector<T> &v);
|
||||
template <class T> void io(Archive &a, std::deque<T> &v);
|
||||
template <class T> void io(Archive &a, std::set<T> &v);
|
||||
template <class K, class V> void io(Archive &a, std::map<K, V> &m);
|
||||
template <class K, class V> void io(Archive &a, std::unordered_map<K, V> &m);
|
||||
template <class A, class B> void io(Archive &a, std::pair<A, B> &p);
|
||||
template <class T> void io(Archive &a, std::unique_ptr<T> &p);
|
||||
|
||||
template <class... T> void fields(Archive &a, T &...v) { (io(a, v), ...); }
|
||||
|
||||
template <class T, size_t N> void io(Archive &a, T (&v)[N])
|
||||
{
|
||||
if constexpr (std::is_arithmetic_v<T>)
|
||||
a.raw(v, sizeof v);
|
||||
else
|
||||
for (auto &e : v)
|
||||
io(a, e);
|
||||
}
|
||||
template <class T, size_t N> void io(Archive &a, std::array<T, N> &v)
|
||||
{
|
||||
if constexpr (std::is_arithmetic_v<T>)
|
||||
a.raw(v.data(), sizeof(T) * N);
|
||||
else
|
||||
for (auto &e : v)
|
||||
io(a, e);
|
||||
}
|
||||
template <class T> void io(Archive &a, std::vector<T> &v)
|
||||
{
|
||||
const uint64_t n = count(a, v.size());
|
||||
if (a.loading())
|
||||
v.resize(n);
|
||||
if constexpr (std::is_arithmetic_v<T> && !std::is_same_v<T, bool>)
|
||||
a.raw(v.data(), sizeof(T) * n);
|
||||
else
|
||||
for (auto &e : v)
|
||||
io(a, e);
|
||||
}
|
||||
template <class T> void io(Archive &a, std::deque<T> &v)
|
||||
{
|
||||
const uint64_t n = count(a, v.size());
|
||||
if (a.loading())
|
||||
v.resize(n);
|
||||
for (auto &e : v)
|
||||
io(a, e);
|
||||
}
|
||||
template <class T> void io(Archive &a, std::set<T> &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 <class K, class V> void io(Archive &a, std::map<K, V> &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 <class K, class V> void io(Archive &a, std::unordered_map<K, V> &m)
|
||||
{
|
||||
if (!a.loading())
|
||||
{
|
||||
std::map<K, V> sorted(m.begin(), m.end());
|
||||
io(a, sorted);
|
||||
return;
|
||||
}
|
||||
std::map<K, V> sorted;
|
||||
io(a, sorted);
|
||||
m.clear();
|
||||
for (auto &[k, v] : sorted)
|
||||
m.emplace(k, std::move(v));
|
||||
}
|
||||
template <class A, class B> void io(Archive &a, std::pair<A, B> &p)
|
||||
{
|
||||
io(a, p.first);
|
||||
io(a, p.second);
|
||||
}
|
||||
template <class T> void io(Archive &a, std::unique_ptr<T> &p)
|
||||
{
|
||||
bool present = p != nullptr;
|
||||
io(a, present);
|
||||
if (a.loading())
|
||||
p = present ? std::make_unique<T>() : nullptr;
|
||||
if (p)
|
||||
io(a, *p);
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -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);
|
||||
}
|
||||
@@ -301,7 +301,7 @@ namespace bozo::libs
|
||||
else
|
||||
// The read returns after charging its full duration; this callback cannot execute inside that
|
||||
// call.
|
||||
l.queueHandler(h,{});
|
||||
l.queueHandler(h, Resume{});
|
||||
}
|
||||
g.ret(ok ? 1 : 0);
|
||||
}
|
||||
@@ -437,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<int32_t>(n));
|
||||
});
|
||||
l.waitVblank(token, -1, Resume{kResumeCdStreamRead, {n}});
|
||||
return;
|
||||
}
|
||||
deliver(l, g, mode == 1 ? n : static_cast<uint32_t>(available), to, errorAt);
|
||||
@@ -521,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<int32_t>(r.a[0]));
|
||||
}
|
||||
|
||||
void addCd(std::vector<Function> &out)
|
||||
{
|
||||
out.push_back({"sceFsInit", kCd, fsInit});
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "bozo/ee/dispatcher.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace bozo::libs
|
||||
{
|
||||
@@ -241,6 +242,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<uint32_t, 3> &args) {
|
||||
std::function<void(uint64_t)> 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<uint32_t, 3> 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<uint32_t>(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 +362,7 @@ namespace bozo::libs
|
||||
const int32_t id = k.running();
|
||||
const bool completion = static_cast<bool>(then);
|
||||
if (completion)
|
||||
continuations_[id] = std::move(then);
|
||||
continuations_[id] = {std::move(then), {}};
|
||||
k.block(id, ee::kWaitVblank, 0, static_cast<uint32_t>(fixedResult), 0, completion, token, fixedResult);
|
||||
}
|
||||
|
||||
@@ -296,7 +373,7 @@ namespace bozo::libs
|
||||
const int32_t id = k.running();
|
||||
const bool completion = static_cast<bool>(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 +382,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<void(Libraries &, Guest &)> Libraries::takeHandlerEnd(uint64_t sequence)
|
||||
@@ -313,7 +390,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 +400,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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// 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); }
|
||||
|
||||
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);
|
||||
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);
|
||||
pod(a, m.sound);
|
||||
a.end();
|
||||
|
||||
a.begin("sif");
|
||||
fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules);
|
||||
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
|
||||
}
|
||||
}
|
||||
+33
-12
@@ -418,7 +418,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<int32_t>(taken));
|
||||
@@ -517,18 +517,10 @@ namespace bozo::libs
|
||||
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);
|
||||
}
|
||||
});
|
||||
l.queueHandler(h, Resume{kResumeMpegNodataEnd, {static_cast<uint32_t>(thread), entry}});
|
||||
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
|
||||
@@ -536,7 +528,7 @@ namespace bozo::libs
|
||||
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 +540,35 @@ 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<int32_t>(r.a[0]);
|
||||
l.gameHeap().release(r.a[1]);
|
||||
MpegState &s = state(l);
|
||||
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<Function> &out)
|
||||
{
|
||||
if (!haveVideoDecoder())
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+42
-31
@@ -53,8 +53,8 @@ namespace bozo::libs
|
||||
if (t.hostClock && c.hostDue > t.hostClock())
|
||||
{
|
||||
const auto left = static_cast<uint64_t>(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<size_t>(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<uint32_t>(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<int64_t>(static_cast<double>(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<uint64_t>(d->second - t.hostClock());
|
||||
k.scheduleNative(kDelayKeys | static_cast<uint32_t>(thread), due + left * (kEeHz / 1000) / 1000000,
|
||||
[&l, thread](uint64_t at) { delayDue(l, thread, at); });
|
||||
l.scheduleDeadline(kDelayKeys | static_cast<uint32_t>(thread), due + left * (kEeHz / 1000) / 1000000,
|
||||
kDeadlineDelayDue, {static_cast<uint32_t>(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<int64_t>(microseconds * 1000) : 0;
|
||||
k.block(thread, ee::kWaitDelay, 0, 0, 0, false, 0, 0);
|
||||
k.scheduleNative(kDelayKeys | static_cast<uint32_t>(thread), l.now(g) + microseconds * kEeHz / 1000000,
|
||||
[&l, thread](uint64_t at) { delayDue(l, thread, at); });
|
||||
l.scheduleDeadline(kDelayKeys | static_cast<uint32_t>(thread), l.now(g) + microseconds * kEeHz / 1000000,
|
||||
kDeadlineDelayDue, {static_cast<uint32_t>(thread), 0, 0});
|
||||
g.ret(0);
|
||||
}
|
||||
|
||||
@@ -477,6 +454,40 @@ namespace bozo::libs
|
||||
return std::min<int64_t>(left, static_cast<int64_t>(static_cast<double>(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<int32_t>(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<size_t>(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<uint32_t, 3> &args, uint64_t due) { fire(l, args[0], args[1], due); }
|
||||
void delayDeadline(Libraries &l, const std::array<uint32_t, 3> &args, uint64_t due)
|
||||
{
|
||||
delayDue(l, static_cast<int32_t>(args[0]), due);
|
||||
}
|
||||
|
||||
void addTimer(std::vector<Function> &out)
|
||||
{
|
||||
for (const auto &[name, handler] : std::initializer_list<std::pair<const char *, Handler>>{
|
||||
|
||||
@@ -137,6 +137,39 @@ namespace bozo::native::irx
|
||||
};
|
||||
std::map<int32_t, EventFlag> 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<uint32_t, RpcServer> 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)
|
||||
@@ -1611,27 +1644,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);
|
||||
@@ -2005,6 +2018,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;
|
||||
@@ -2047,3 +2061,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<decltype(map)>;
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -399,3 +399,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)
|
||||
@@ -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 <cstdio>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
|
||||
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 <class F> 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<uint32_t, std::vector<Point>> m{{3, {{1, "a"}, {2, "bc"}}}, {9, {}}};
|
||||
std::unordered_map<int, std::deque<uint16_t>> u{{5, {1, 2}}, {-1, {7}}};
|
||||
std::array<uint64_t, 3> arr{1, 2, 3};
|
||||
uint32_t c[2][2] = {{1, 2}, {3, 4}};
|
||||
std::set<std::string> names{"x", "y"};
|
||||
std::unique_ptr<Point> some = std::make_unique<Point>(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<uint32_t, std::vector<Point>> m2;
|
||||
std::unordered_map<int, std::deque<uint16_t>> u2;
|
||||
std::array<uint64_t, 3> arr2{};
|
||||
uint32_t c2[2][2] = {};
|
||||
std::set<std::string> names2;
|
||||
std::unique_ptr<Point> some2, none2 = std::make_unique<Point>();
|
||||
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<uint8_t> 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<uint32_t, 3> &args) {
|
||||
std::function<void(uint64_t)> 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;
|
||||
}
|
||||
Reference in new issue
Block a user