diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2d3dd58..562bc14 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -39,6 +39,7 @@ add_library(bozo_libs STATIC libs/io.cpp libs/mpeg.cpp libs/mpeg_ffmpeg.cpp + libs/ipu_stream.cpp libs/sif.cpp libs/snd.cpp libs/snd989.cpp) @@ -165,7 +166,7 @@ else() endif() endif() if(BOZO_FFMPEG_FOUND) - set_source_files_properties(libs/mpeg_ffmpeg.cpp PROPERTIES COMPILE_DEFINITIONS BOZO_HAVE_FFMPEG) + set_source_files_properties(libs/mpeg_ffmpeg.cpp libs/ipu_stream.cpp PROPERTIES COMPILE_DEFINITIONS BOZO_HAVE_FFMPEG) message(STATUS "libmpeg: FFmpeg found (native movies)") else() if(BOZO_REQUIRE_FFMPEG) diff --git a/runtime/core/runtime_core.cpp b/runtime/core/runtime_core.cpp index becefd7..08352eb 100644 --- a/runtime/core/runtime_core.cpp +++ b/runtime/core/runtime_core.cpp @@ -69,7 +69,15 @@ namespace bozo if (start >= end || !resident || identity.empty() || identity.size() > uint64_t(end) - start || (count && !functions) || (resumeCount && !resume)) throw std::invalid_argument("invalid native module registration"); - modules_.push_back({start, end, resident, std::move(identity), functions, count, resume, resumeCount}); + uint32_t inner = end; + for (Module &other : modules_) + { + if (other.start > start && other.start < end) + inner = std::min(inner, other.start); + if (start > other.start && start < other.end) + other.inner = std::min(other.inner, start); + } + modules_.push_back({start, end, inner, resident, std::move(identity), functions, count, resume, resumeCount}); modulesLow_ = std::min(modulesLow_, start); modulesHigh_ = std::max(modulesHigh_, end); lastModule_ = nullptr; // the vector may have moved @@ -79,7 +87,7 @@ namespace bozo { if (address < modulesLow_ || address >= modulesHigh_) return nullptr; - if (const Module *last = lastModule_; last && address >= last->start && address < last->end && + if (const Module *last = lastModule_; last && address >= last->start && address < last->inner && std::memcmp(last->resident, last->identity.data(), last->identity.size()) == 0) { reserved = true; @@ -93,9 +101,11 @@ namespace bozo reserved = true; if (std::memcmp(module.resident, module.identity.data(), module.identity.size()) != 0) continue; - if (active) + // Two resident modules over the address: the higher one was loaded over the other's tail. + if (active && active->start == module.start) throw std::runtime_error("ambiguous native module identity"); - active = &module; + if (!active || module.start > active->start) + active = &module; } if (active) lastModule_ = active; diff --git a/runtime/core/state.cpp b/runtime/core/state.cpp index b5f6985..35b65b7 100644 --- a/runtime/core/state.cpp +++ b/runtime/core/state.cpp @@ -67,15 +67,17 @@ namespace bozo::state if (open_.empty()) throw Error("save state: a section ended twice"); const auto [name, at] = open_.back(); + // Checked before the section is closed: a reader that tries an older layout and rewinds (Mark) finds the + // section still open (closed first, the rewind reopened it as a nameless one ending at 0). + if (loading_ && 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?)"); 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) diff --git a/runtime/include/bozo/libs/ipu_stream.h b/runtime/include/bozo/libs/ipu_stream.h new file mode 100644 index 0000000..f7a0a82 --- /dev/null +++ b/runtime/include/bozo/libs/ipu_stream.h @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 The Bozos (boubou666 and Arzaroth). MIT licence (see LICENSE at the repository root). +// +// A game's own IPU streams, decoded natively: the ".ipu" files Sony's IPU sample format defines (header "ipum", u32 file +// size, u16 width, u16 height, u32 frame count, then the frames' IPU bitstream: intra-only MPEG macroblocks). A game +// that drives the IPU itself (BDEC/IDEC commands, the to-IPU and from-IPU DMA channels; JC2's animated textures) can +// answer its decode routine with this instead: no IPU, no DMA. FFmpeg's "ipu" parser splits the frames and its decoder +// decodes them (libavcodec, the same build as libmpeg's; without FFmpeg open() fails and the port keeps its own path). +// +// The output is what the IPU's colour conversion (CSC, RGB32) writes: per 16 x 16 macroblock, in raster order of the +// macroblocks, its 256 pixels row by row, 4 bytes R, G, B, A; or, with decodeRaster, the picture's rows. +#pragma once + +#include +#include +#include + +namespace bozo::libs +{ + class IpuStream + { + public: + IpuStream(); + ~IpuStream(); + IpuStream(const IpuStream &) = delete; + IpuStream &operator=(const IpuStream &) = delete; + + // Whether this build can decode IPU streams (FFmpeg with its "ipu" decoder and parser). + static bool available(); + + // The whole file in memory (copied). False: not an "ipum" file, or no decoder. + bool open(const uint8_t *file, size_t bytes); + bool isOpen() const; + int width() const; + int height() const; + int frames() const; // the frames found in the stream (the header's count when they can all be split) + + // Frame `index` (0-based, any order: IPU frames are intra-only) as RGB32 macroblocks (the CSC's layout above), + // width x height x 4 bytes; alpha is the value given (the CSC's 0x80 when the colour is not under the threshold). + // False: no such frame, or it did not decode (the caller keeps its previous picture). + bool decodeMacroblocks(int index, uint8_t *out, uint8_t alpha = 0x80); + // The same frame as rows of RGBA pixels (width x height x 4 bytes). + bool decodeRaster(int index, uint8_t *out, uint8_t alpha = 0x80); + + private: + struct Impl; + std::unique_ptr impl_; + }; +} diff --git a/runtime/include/bozo/libs/libraries.h b/runtime/include/bozo/libs/libraries.h index 250a14b..1fe712d 100644 --- a/runtime/include/bozo/libs/libraries.h +++ b/runtime/include/bozo/libs/libraries.h @@ -275,6 +275,10 @@ namespace bozo::libs // Optional native audio implementation. Advances to EE time and returns its sample queue. // Unset: the built-in 989SND source. Its lifetime belongs to the port. std::function audioProvider; + // Optional: told when the game starts a DMA channel by its CHCR (channel 0..9 and its registers, STR set), + // before the I/O library completes it. A port reads the transfer's source there (JC2: the GS image transfers + // in its VIF1 and GIF chains, to know which RAM went to which texture page); it must not change them. + std::function dmaStarted; MovieSoundSink *movieSound = nullptr; // the movie's sound (null: dropped) audio::PortStream portStream; IoAccess ioAccess; diff --git a/runtime/include/bozo/runtime.h b/runtime/include/bozo/runtime.h index 685c7e6..3aff4b6 100644 --- a/runtime/include/bozo/runtime.h +++ b/runtime/include/bozo/runtime.h @@ -82,7 +82,9 @@ namespace bozo void clearOverrides() { overrides_.clear(); } size_t overrideCount() const { return overrides_.size(); } // Statically compiled images sharing a guest address range. A module is callable only while the - // resident identity bytes match. The resident storage and generated tables outlive this table. + // resident identity bytes match. The resident storage and generated tables outlive this table. Modules may + // overlap (a game loads one into another's span, over its tail): where two match, the one starting higher wins, + // its header being inside the other's span means it was loaded over that part. // This selects native code; it never loads or interprets guest instructions. void addModule(uint32_t start, uint32_t end, const uint8_t *resident, std::vector identity, const BozoFunctionEntry *functions, size_t count, @@ -104,6 +106,7 @@ namespace bozo struct Module { uint32_t start, end; + uint32_t inner; // the lowest other module's start inside (start, end), else end: the fast path's limit const uint8_t *resident; std::vector identity; const BozoFunctionEntry *functions; diff --git a/runtime/include/bozo/state.h b/runtime/include/bozo/state.h index 36f36b0..5fc0fdc 100644 --- a/runtime/include/bozo/state.h +++ b/runtime/include/bozo/state.h @@ -49,6 +49,12 @@ namespace bozo::state Mark mark() const { return {pos_, open_.size()}; } // Reading: whether the next thing is the section `name` (an older layout that has no fields before it). bool nextIs(const char *name) const; + // Reading: the bytes the open section has left (an older layout, shorter by the fields added since); 0 when + // writing or with no section open. + size_t sectionLeft() const + { + return loading_ && !open_.empty() && pos_ < open_.back().second ? open_.back().second - pos_ : 0; + } void rewind(const Mark &m) { pos_ = m.pos; diff --git a/runtime/libs/io.cpp b/runtime/libs/io.cpp index 544aead..6e8b392 100644 --- a/runtime/libs/io.cpp +++ b/runtime/libs/io.cpp @@ -214,6 +214,8 @@ namespace bozo::libs c.running = false; // STR cleared: the channel stops (TMB stops channel 4 at a movie's end) else if (!c.running) { + if (l.dmaStarted) + l.dmaStarted(static_cast(ch), c); if (ch == 0) l.vu0.kick(v, c.tadr); // VIF0: the microcode image VU0 now holds if (static_cast(ch) == kFromScratchpadChannel || static_cast(ch) == kToScratchpadChannel) diff --git a/runtime/libs/ipu_stream.cpp b/runtime/libs/ipu_stream.cpp new file mode 100644 index 0000000..739feab --- /dev/null +++ b/runtime/libs/ipu_stream.cpp @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 The Bozos (boubou666 and Arzaroth). MIT licence (see LICENSE at the repository root). +// +// A game's own IPU streams (bozo/libs/ipu_stream.h): FFmpeg's "ipu" parser and decoder, built with BOZO_HAVE_FFMPEG +// like libmpeg's decoder (mpeg_ffmpeg.cpp); without FFmpeg, open() fails. +#include "bozo/libs/ipu_stream.h" + +#include +#include +#include + +#ifdef BOZO_HAVE_FFMPEG +extern "C" +{ +#include +#include +} +#endif + +namespace bozo::libs +{ + struct IpuStream::Impl + { + std::vector file; + int width = 0, height = 0; + std::vector> frames; // (offset, bytes) of each frame in `file` +#ifdef BOZO_HAVE_FFMPEG + AVCodecContext *codec = nullptr; + AVPacket *packet = nullptr; + AVFrame *frame = nullptr; + ~Impl() + { + av_frame_free(&frame); + av_packet_free(&packet); + avcodec_free_context(&codec); + } +#endif + }; + + namespace + { + uint32_t le32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24; } + uint16_t le16(const uint8_t *p) { return uint16_t(p[0] | p[1] << 8); } + uint8_t clamp8(int v) { return static_cast(std::clamp(v, 0, 255)); } + + // The IPU's colour conversion (ITU-R BT.601, video range), in 16.16 fixed point. + void yuvToRgb(int y, int cb, int cr, uint8_t *out, uint8_t alpha) + { + const int c = (y - 16) * 76309, d = cb - 128, e = cr - 128; + out[0] = clamp8((c + 104597 * e + 32768) >> 16); + out[1] = clamp8((c - 25675 * d - 53279 * e + 32768) >> 16); + out[2] = clamp8((c + 132201 * d + 32768) >> 16); + out[3] = alpha; + } + } + + IpuStream::IpuStream() = default; + IpuStream::~IpuStream() = default; + + bool IpuStream::available() + { +#ifdef BOZO_HAVE_FFMPEG + return avcodec_find_decoder(AV_CODEC_ID_IPU) != nullptr; +#else + return false; +#endif + } + + bool IpuStream::isOpen() const { return impl_ && !impl_->frames.empty(); } + int IpuStream::width() const { return impl_ ? impl_->width : 0; } + int IpuStream::height() const { return impl_ ? impl_->height : 0; } + int IpuStream::frames() const { return impl_ ? static_cast(impl_->frames.size()) : 0; } + + bool IpuStream::open(const uint8_t *file, size_t bytes) + { + impl_.reset(); +#ifdef BOZO_HAVE_FFMPEG + if (!file || bytes < 16 || std::memcmp(file, "ipum", 4) != 0) + return false; + auto impl = std::make_unique(); + const size_t size = std::min(bytes, std::max(16, le32(file + 4))); + impl->file.assign(file, file + size); + impl->width = le16(file + 8); + impl->height = le16(file + 10); + const uint32_t count = le32(file + 12); + if (impl->width <= 0 || impl->height <= 0 || (impl->width | impl->height) & 15) + return false; + + const AVCodec *decoder = avcodec_find_decoder(AV_CODEC_ID_IPU); + AVCodecParserContext *parser = av_parser_init(AV_CODEC_ID_IPU); + if (!decoder || !parser) + { + if (parser) + av_parser_close(parser); + return false; + } + impl->codec = avcodec_alloc_context3(decoder); + impl->packet = av_packet_alloc(); + impl->frame = av_frame_alloc(); + if (!impl->codec || !impl->packet || !impl->frame) + { + av_parser_close(parser); + return false; + } + impl->codec->width = impl->width; + impl->codec->height = impl->height; + impl->codec->thread_count = 1; + if (avcodec_open2(impl->codec, decoder, nullptr) < 0) + { + av_parser_close(parser); + return false; + } + + // The frames, as the parser splits the stream after the header (as FFmpeg's ipu demuxer feeds it). + const uint8_t *data = impl->file.data() + 16; + size_t left = impl->file.size() - 16, at = 16; + while (true) + { + uint8_t *out = nullptr; + int outBytes = 0; + const int used = av_parser_parse2(parser, impl->codec, &out, &outBytes, left ? data : nullptr, + static_cast(left), AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); + if (used < 0) + break; + if (outBytes > 0 && out) + { + // A frame the parser returns lies in the file (it hands back the input) or in its own buffer when it + // spans calls; find it in the file by its bytes, from where the previous one ended. + const uint8_t *found = std::search(impl->file.data() + at, impl->file.data() + impl->file.size(), out, + out + outBytes); + if (found == impl->file.data() + impl->file.size()) + break; + const size_t offset = static_cast(found - impl->file.data()); + impl->frames.emplace_back(offset, static_cast(outBytes)); + at = offset + static_cast(outBytes); + } + if (!left && outBytes <= 0) + break; + data += used; + left -= static_cast(used); + } + av_parser_close(parser); + if (impl->frames.empty()) + return false; + if (count && impl->frames.size() > count) + impl->frames.resize(count); + impl_ = std::move(impl); + return true; +#else + (void)file; + (void)bytes; + return false; +#endif + } + + bool IpuStream::decodeRaster(int index, uint8_t *out, uint8_t alpha) + { +#ifdef BOZO_HAVE_FFMPEG + if (!isOpen() || index < 0 || index >= frames() || !out) + return false; + Impl &s = *impl_; + const auto [offset, bytes] = s.frames[static_cast(index)]; + if (av_new_packet(s.packet, static_cast(bytes)) < 0) + return false; + std::memcpy(s.packet->data, s.file.data() + offset, bytes); + const int sent = avcodec_send_packet(s.codec, s.packet); + av_packet_unref(s.packet); + if (sent < 0 || avcodec_receive_frame(s.codec, s.frame) < 0) + return false; + const AVFrame &f = *s.frame; + if (f.format != AV_PIX_FMT_YUV420P || f.width < s.width || f.height < s.height) + { + av_frame_unref(s.frame); + return false; + } + for (int y = 0; y < s.height; ++y) + { + const uint8_t *py = f.data[0] + y * f.linesize[0]; + const uint8_t *pu = f.data[1] + (y / 2) * f.linesize[1]; + const uint8_t *pv = f.data[2] + (y / 2) * f.linesize[2]; + uint8_t *row = out + static_cast(y) * s.width * 4; + for (int x = 0; x < s.width; ++x) + yuvToRgb(py[x], pu[x / 2], pv[x / 2], row + x * 4, alpha); + } + av_frame_unref(s.frame); + return true; +#else + (void)index; + (void)out; + (void)alpha; + return false; +#endif + } + + bool IpuStream::decodeMacroblocks(int index, uint8_t *out, uint8_t alpha) + { + if (!isOpen() || !out) + return false; + const int w = impl_->width, h = impl_->height; + std::vector raster(static_cast(w) * h * 4); + if (!decodeRaster(index, raster.data(), alpha)) + return false; + // Macroblocks in raster order, each one's 16 rows of 16 pixels. + uint8_t *dst = out; + for (int my = 0; my < h / 16; ++my) + for (int mx = 0; mx < w / 16; ++mx) + for (int y = 0; y < 16; ++y) + { + std::memcpy(dst, raster.data() + (static_cast(my * 16 + y) * w + mx * 16) * 4, 16 * 4); + dst += 16 * 4; + } + return true; + } +} diff --git a/runtime/libs/libraries_state.cpp b/runtime/libs/libraries_state.cpp index 2c52c90..da9b576 100644 --- a/runtime/libs/libraries_state.cpp +++ b/runtime/libs/libraries_state.cpp @@ -153,7 +153,15 @@ namespace bozo::libs for (auto &port : pad.ports) for (auto &slot : port) pod(a, slot); - fields(a, pad.initialized, pad.reads, pad.socketReads, pad.multitap, pad.multitapAttached, pad.pad2Sockets, pad.pad2Next); + fields(a, pad.initialized, pad.reads, pad.socketReads, pad.multitap, pad.multitapAttached); + // A state written before libpad2's sockets were saved (67c5867) ends here: no socket is open. + if (a.loading() && a.sectionLeft() == 0) + { + pad.pad2Sockets.clear(); + pad.pad2Next = 0; + } + else + fields(a, pad.pad2Sockets, pad.pad2Next); a.end(); a.begin("mc"); @@ -161,6 +169,15 @@ namespace bozo::libs 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); + // Cards kept in a host folder stay the folder's, as a console's memory card is not part of a save state: a + // state loaded takes them back from the folder (else the state's card, its host folder unknown, kept the + // game's saves in memory only and lost them). Cards in memory (no folder) are the state's. + if (a.loading() && !mc.hostDirectory.empty()) + { + for (size_t p = 0; p < mc.cards.size(); ++p) + mc.cards[p].format(mc.hostDirectory + "/mc" + std::to_string(p), mc.date); + mc.formatted = true; + } a.end(); a.begin("cd"); @@ -184,16 +201,46 @@ namespace bozo::libs m.pending, m.pendingAt, m.ring, m.ringSize, m.ringBias, m.linearBase, m.programEnd, m.aborted, m.es, m.scanned, m.starts, m.pictureStarts, m.sequenceEnd, m.headerOpen, m.cuts, m.sent, m.flushed, m.callbacksDue, m.waiting, m.delivered, m.base, m.lastShown, m.firstPictureNs, m.soundHeader, - m.soundCarry, m.inputEnded); + m.soundCarry); + // A state written before the SDK's Nodata end (MpegOptions::sdkNodata) has the sound left: the input goes on. + if (a.loading() && a.sectionLeft() == sizeof m.sound) + m.inputEnded = false; + else + fields(a, m.inputEnded); pod(a, m.sound); a.end(); a.begin("sif"); - fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules, sif.iopSreg); - sif.heap.serialize(a); - a.end(); + fields(a, sif.rpcId, sif.bindAttempts, sif.bound, sif.sreg, sif.dmaId, sif.modules); + { + // A state written before the IOP side's software registers has the heap next: read it as such when the + // registers then leave bytes over (the section's end checks the layout), with the registers cleared. + const state::Archive::Mark mark = a.mark(); + bool older = false; + if (a.loading()) + try + { + sif.heap.serialize(a); + a.end(); + older = true; + } + catch (const state::Error &) + { + a.rewind(mark); + } + if (older) + std::fill(std::begin(sif.iopSreg), std::end(sif.iopSreg), 0u); + else + { + fields(a, sif.iopSreg); + sif.heap.serialize(a); + a.end(); + } + } - snd.serialize(a, *this); + // A state written before the 989SND driver was saved goes on with the timers: the driver stays as it is. + if (!(a.loading() && a.nextIs("timers"))) + snd.serialize(a, *this); a.begin("timers"); TimerState &t = timers; diff --git a/tests/libs/libs_tests.cpp b/tests/libs/libs_tests.cpp index df57ac3..500e59e 100644 --- a/tests/libs/libs_tests.cpp +++ b/tests/libs/libs_tests.cpp @@ -363,6 +363,35 @@ void nativeCardFlushPersistence() { std::filesystem::remove(root/"mc0"/"save"); std::filesystem::remove(root/"mc0");std::filesystem::remove(root/"mc1");std::filesystem::remove(root); } +// A card kept in a host folder is not part of a save state: loading a state takes it back from the folder, and the +// game's writes after it reach the folder (a state's card in memory had no folder and lost them). +void nativeCardStateKeepsHostFolder() { + const auto root=std::filesystem::temp_directory_path()/ + ("bozo-mc-state-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::vector saved; + { + Machine m; // the state's machine: a card in memory with a file of its own + m.call("sceMcGetInfo",{0,0,0,0,0});m.result(); + m.string(0x110000,"state-only");m.call("sceMcOpen",{0,0,0x110000,0x203});const auto fd=m.result(); + m.call("sceMcClose",{uint32_t(fd)});m.result(); + bozo::state::Archive w;m.libs.serialize(w);saved=w.data(); + } + { + std::filesystem::create_directories(root/"mc0"); + std::ofstream(root/"mc0"/"kept",std::ios::binary)<<"kept"; + } + { + Machine m;m.libs.mc.hostDirectory=root.string(); + bozo::state::Archive r(saved);m.libs.serialize(r); + eq("folder's file after a state",m.libs.mc.card(0).find("kept")!=nullptr,1); + eq("state's own card dropped",m.libs.mc.card(0).find("state-only")==nullptr,1); + m.string(0x110000,"after");m.call("sceMcOpen",{0,0,0x110000,0x203});const auto fd=m.result(); + m.string(0x111000,"x");m.call("sceMcWrite",{uint32_t(fd),0x111000,1});m.result(); + m.call("sceMcClose",{uint32_t(fd)});m.result(); + eq("write after a state on the host",std::filesystem::exists(root/"mc0"/"after"),1); + } + std::error_code ec;std::filesystem::remove_all(root,ec); +} void liveScriptInput() { const auto path=std::filesystem::temp_directory_path()/ ("bozo-live-pad-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); @@ -991,6 +1020,7 @@ int main() sifAndSnd(); memoryCard(); nativeCardFlushPersistence(); + nativeCardStateKeepsHostFolder(); heapAndRand(); cdStream(); std::printf("%s\n", g_failures ? "FAILED" : "all passed"); diff --git a/tests/runtime/runtime_tests.cpp b/tests/runtime/runtime_tests.cpp index 99b5920..f68b9da 100644 --- a/tests/runtime/runtime_tests.cpp +++ b/tests/runtime/runtime_tests.cpp @@ -102,6 +102,19 @@ int main() eq("module does not mask resident code", rt->functions.generated(0x100000) == fnA, true); rt->functions.clearModules(); + // A module loaded into another's span (JC2: a battle effect at 0x96B000 over the tail of the Arena's script at + // 0x96A800): where both are resident, the higher one owns its part, also right after the lower one was looked up. + const BozoFunctionEntry lowFns[] = {{0x300000u, fnA}, {0x300140u, fnA}}; + const BozoFunctionEntry highFns[] = {{0x300140u, fnB}}; + uint8_t lowResident[] = {5, 6}, highResident[] = {7, 8}; + rt->functions.addModule(0x300000, 0x300200, lowResident, {5, 6}, lowFns, 2, nullptr, 0); + rt->functions.addModule(0x300100, 0x300180, highResident, {7, 8}, highFns, 1, nullptr, 0); + eq("lower module's own part", rt->functions.generated(0x300000) == fnA, true); + eq("higher module over the lower's tail", rt->functions.generated(0x300140) == fnB, true); + highResident[0] = 0; + eq("the lower module again once the higher is gone", rt->functions.generated(0x300140) == fnA, true); + rt->functions.clearModules(); + // ei / di toggle Status.EIE; mfc0 12 reads Status. bozo_set_interrupts(rt->memory.ram(), &ctx, rt.get(), true); eq("ei", bozo_cop0_read(&ctx, rt.get(), 12), 0x10000); diff --git a/tests/runtime/state_tests.cpp b/tests/runtime/state_tests.cpp index 1bd069a..e9e5b70 100644 --- a/tests/runtime/state_tests.cpp +++ b/tests/runtime/state_tests.cpp @@ -148,10 +148,38 @@ namespace state::fields(x, rAfter); x.end(); check(r1 == 1 && r2 == 2 && rAfter == 3 && x.atEnd(), "rewound to the mark, read in the older layout"); + // A mark inside a section: a trial read that takes too few bytes fails at the section's end (the libraries' + // sif section tries its older layout so); the section stays open for the rewind and the read goes on. + { + state::Archive inner(old.data()); + uint32_t a1 = 0, a2 = 0, aAfter = 0; + inner.begin("s"); + const state::Archive::Mark at = inner.mark(); + check(throws([&] { + state::fields(inner, a1); + inner.end(); + }), + "a shorter trial read fails at the section's end"); + inner.rewind(at); + state::fields(inner, a1, a2); + inner.end(); + inner.begin("next"); + state::fields(inner, aAfter); + inner.end(); + check(a1 == 1 && a2 == 2 && aAfter == 3 && inner.atEnd(), "rewound inside the section, read on"); + } state::Archive y(old.data()); check(y.nextIs("s") && !y.nextIs("next") && !y.nextIs("ss"), "nextIs names the coming section"); y.begin("s"); check(!y.nextIs("next"), "nextIs: fields come first"); + uint32_t z1 = 0, z2 = 0; + check(y.sectionLeft() == 8, "sectionLeft: the section's fields"); + state::fields(y, z1); + check(y.sectionLeft() == 4, "sectionLeft: a field is left"); + state::fields(y, z2); + check(y.sectionLeft() == 0 && z2 == 2, "sectionLeft: the section's fields are all read"); + y.end(); + check(y.sectionLeft() == 0, "sectionLeft: no section open"); } }