Skip to content

PS2 games in the browser: static recompilation to WebAssembly with a native runtime

C++

Load ELF segments placed in scratchpad, and use the synchronous FILEIO protocol for FILEIO before 2.0

Samir Nuri8ebb09b15f06
diff --git a/runtime/src/iop/sif.cpp b/runtime/src/iop/sif.cpp
index 555a167..1f56f74 100644
--- a/runtime/src/iop/sif.cpp
+++ b/runtime/src/iop/sif.cpp
@@ -281,6 +281,13 @@ void read_reboot_image(const std::string &image_path) {
if (image.empty() || !disc::read(entry->sector, static_cast<std::uint32_t>(image.size() / disc::kSector), image.data())) return;
for (std::size_t at = 0; at + 16 <= image.size() && image[at]; at += 16)
if (std::memcmp(&image[at], "FILEIO\0", 7) == 0) g_fileio_async = true;
+ static const char kFileio[] = "PsIIfileio ";
+ const auto fileio = std::search(image.begin(), image.end(), kFileio, kFileio + sizeof kFileio - 1);
+ if (image.end() - fileio >= static_cast<std::ptrdiff_t>(sizeof kFileio + 3)) {
+ const std::string version(fileio + sizeof kFileio - 1, fileio + sizeof kFileio + 3);
+ if (version < "2000") g_fileio_async = false;
+ std::fprintf(stderr, "[sif] FILEIO from %s reports %s, %s protocol\n", image_path.c_str(), version.c_str(), g_fileio_async ? "asynchronous" : "synchronous");
+ }
static const char kTag[] = "PsIIloadfile";
const auto it = std::search(image.begin(), image.end(), kTag, kTag + sizeof kTag - 1);
if (image.end() - it < static_cast<std::ptrdiff_t>(sizeof kTag + 3)) return;
diff --git a/runtime/src/system.cpp b/runtime/src/system.cpp
index 47d89be..d91c9b7 100644
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@ -377,8 +377,17 @@ bool load_elf(const std::string &path, std::uint32_t &entry) {
for (std::uint32_t i = 0; i < u16(44); ++i) {
const std::size_t ph = phoff + i * u16(42);
if (u32(ph) != 1) continue;
- const std::uint32_t offset = u32(ph + 4), vaddr = physical(u32(ph + 8)), filesz = u32(ph + 16), memsz = u32(ph + 20);
- if (vaddr + memsz > kRamSize || offset + filesz > data.size()) return false;
+ const std::uint32_t offset = u32(ph + 4), filesz = u32(ph + 16), memsz = u32(ph + 20);
+ if (offset + filesz > data.size() || filesz > memsz) return false;
+ if (const std::uint32_t at = u32(ph + 8); (at >> 14) == (kScratchpadBase >> 14)) {
+ const std::uint32_t start = at & (kScratchpadSize - 1);
+ if (start + memsz > kScratchpadSize) return false;
+ std::memcpy(g_spr + start, data.data() + offset, filesz);
+ std::memset(g_spr + start + filesz, 0, memsz - filesz);
+ continue;
+ }
+ const std::uint32_t vaddr = physical(u32(ph + 8));
+ if (vaddr + memsz > kRamSize) return false;
std::memcpy(g_ram + vaddr, data.data() + offset, filesz);
watch_span(vaddr, filesz, "boot:load_exec");
std::memset(g_ram + vaddr + filesz, 0, memsz - filesz);