| 1 | // Copyright 2021 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DiscIO/RiivolutionPatcher.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <string> |
| 8 | #include <string_view> |
| 9 | #include <vector> |
| 10 | |
| 11 | #include <fmt/format.h> |
| 12 | |
| 13 | #include "Common/FileUtil.h" |
| 14 | #include "Common/IOFile.h" |
| 15 | #include "Common/StringUtil.h" |
| 16 | #include "Core/AchievementManager.h" |
| 17 | #include "Core/Core.h" |
| 18 | #include "Core/HLE/HLE.h" |
| 19 | #include "Core/HW/Memmap.h" |
| 20 | #include "Core/PowerPC/MMU.h" |
| 21 | #include "Core/System.h" |
| 22 | #include "DiscIO/DirectoryBlob.h" |
| 23 | #include "DiscIO/RiivolutionParser.h" |
| 24 | |
| 25 | namespace DiscIO::Riivolution |
| 26 | { |
| 27 | FileDataLoader::~FileDataLoader() = default; |
| 28 | |
| 29 | FileDataLoaderHostFS::FileDataLoaderHostFS(std::string sd_root, const std::string& xml_path, |
| 30 | std::string_view patch_root) |
| 31 | : m_sd_root(std::move(sd_root)) |
| 32 | { |
| 33 | // Riivolution treats 'external' file paths as follows: |
| 34 | // - If it starts with a '/', it's an absolute path, ie. relative to the SD card root. |
| 35 | // - Otherwise: |
| 36 | // - If the 'root' parameter of the current patch is not set or is empty, the path is relative |
| 37 | // to the folder the XML file is in. |
| 38 | // - If the 'root' parameter of the current patch starts with a '/', the path is relative to |
| 39 | // that folder on the SD card, starting at the SD card root. |
| 40 | // - If the 'root' parameter of the current patch starts without a '/', the path is relative to |
| 41 | // that folder on the SD card, starting at the folder the XML file is in. |
| 42 | // The following initialization should properly replicate this behavior. |
| 43 | |
| 44 | // First set m_patch_root to the folder the parsed XML file is in. |
| 45 | SplitPath(xml_path, &m_patch_root, nullptr, nullptr); |
| 46 | |
| 47 | // Then try to resolve the given patch_root as if it was a file path, and on success replace the |
| 48 | // m_patch_root with it. |
| 49 | if (!patch_root.empty()) |
| 50 | { |
| 51 | auto r = MakeAbsoluteFromRelative(patch_root); |
| 52 | if (r) |
| 53 | m_patch_root = std::move(*r); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | std::optional<std::string> |
| 58 | FileDataLoaderHostFS::MakeAbsoluteFromRelative(std::string_view external_relative_path) const |
| 59 | { |
| 60 | #ifdef _WIN32 |
| 61 | // Riivolution treats a backslash as just a standard filename character, but we can't replicate |
| 62 | // this properly on Windows. So if a file contains a backslash, immediately error out. |
| 63 | if (external_relative_path.contains("\\")) |
| 64 | return std::nullopt; |
| 65 | #endif |
| 66 | |
| 67 | const std::string& root = external_relative_path.starts_with('/') ? m_sd_root : m_patch_root; |
| 68 | std::string result = root; |
| 69 | std::string_view work = external_relative_path; |
| 70 | |
| 71 | // Strip away all leading and trailing path separators. |
| 72 | while (work.starts_with('/')) |
| 73 | work.remove_prefix(1); |
| 74 | while (work.ends_with('/')) |
| 75 | work.remove_suffix(1); |
| 76 | size_t depth = 0; |
| 77 | while (true) |
| 78 | { |
| 79 | if (work.empty()) |
| 80 | break; |
| 81 | |
| 82 | // Extract a single path element. |
| 83 | size_t separator_position = work.find('/'); |
| 84 | std::string_view element = work.substr(0, separator_position); |
| 85 | |
| 86 | if (element == ".") |
| 87 | { |
| 88 | // This is a harmless element, doesn't change any state. |
| 89 | } |
| 90 | else if (element == "..") |
| 91 | { |
| 92 | // We're going up a level. |
| 93 | // If this isn't possible someone is trying to exit the root directory, prevent that. |
| 94 | if (depth == 0) |
| 95 | return std::nullopt; |
| 96 | --depth; |
| 97 | |
| 98 | // Remove the last path element from the result string. |
| 99 | // This must have been previously attached in the branch below (otherwise depth would have |
| 100 | // been 0), so there's no need to check whether the string is empty or anything like that. |
| 101 | while (result.back() != '/') |
| 102 | result.pop_back(); |
| 103 | result.pop_back(); |
| 104 | } |
| 105 | else if (std::ranges::all_of(element, [](char c) { return c == '.'; })) |
| 106 | { |
| 107 | // This is a triple, quadruple, etc. dot. |
| 108 | // Some file systems treat this as several 'up' path traversals, but Riivolution does not. |
| 109 | // If someone tries this just error out, it wouldn't work sensibly in Riivolution anyway. |
| 110 | return std::nullopt; |
| 111 | } |
| 112 | else |
| 113 | { |
| 114 | // We're going down a level. |
| 115 | ++depth; |
| 116 | |
| 117 | // Append path element to result string. |
| 118 | result += '/'; |
| 119 | result += element; |
| 120 | |
| 121 | // Riivolution assumes a case-insensitive file system, which means it's possible that an XML |
| 122 | // file references a 'file.bin' but the actual file is named 'File.bin' or 'FILE.BIN'. To |
| 123 | // preserve this behavior, we modify the file path to match any existing file in the file |
| 124 | // system, if one exists. |
| 125 | if (!::File::Exists(result)) |
| 126 | { |
| 127 | // Drop path element again so we can search in the directory. |
| 128 | result.erase(result.size() - element.size(), element.size()); |
| 129 | |
| 130 | // Re-attach an element that actually matches the capitalization in the host filesystem. |
| 131 | auto possible_files = ::File::ScanDirectoryTree(result, false); |
| 132 | bool found = false; |
| 133 | for (auto& f : possible_files.children) |
| 134 | { |
| 135 | if (Common::CaseInsensitiveEquals(element, f.virtualName)) |
| 136 | { |
| 137 | result += f.virtualName; |
| 138 | found = true; |
| 139 | break; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // If there isn't any file that matches just use the given element. |
| 144 | if (!found) |
| 145 | result += element; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // If this was the last path element, we're done. |
| 150 | if (separator_position == std::string_view::npos) |
| 151 | break; |
| 152 | |
| 153 | // Remove element from work string. |
| 154 | work = work.substr(separator_position + 1); |
| 155 | |
| 156 | // Remove any potential extra path separators. |
| 157 | while (work.starts_with('/')) |
| 158 | work = work.substr(1); |
| 159 | } |
| 160 | return result; |
| 161 | } |
| 162 | |
| 163 | std::optional<u64> |
| 164 | FileDataLoaderHostFS::GetExternalFileSize(std::string_view external_relative_path) |
| 165 | { |
| 166 | auto path = MakeAbsoluteFromRelative(external_relative_path); |
| 167 | if (!path) |
| 168 | return std::nullopt; |
| 169 | ::File::FileInfo f(*path); |
| 170 | if (!f.IsFile()) |
| 171 | return std::nullopt; |
| 172 | return f.GetSize(); |
| 173 | } |
| 174 | |
| 175 | std::vector<u8> FileDataLoaderHostFS::GetFileContents(std::string_view external_relative_path) |
| 176 | { |
| 177 | auto path = MakeAbsoluteFromRelative(external_relative_path); |
| 178 | if (!path) |
| 179 | return {}; |
| 180 | ::File::IOFile f(*path, "rb"); |
| 181 | if (!f) |
| 182 | return {}; |
| 183 | const u64 length = f.GetSize(); |
| 184 | std::vector<u8> value; |
| 185 | value.resize(length); |
| 186 | if (!f.ReadBytes(value.data(), length)) |
| 187 | return {}; |
| 188 | return value; |
| 189 | } |
| 190 | |
| 191 | std::vector<FileDataLoader::Node> |
| 192 | FileDataLoaderHostFS::GetFolderContents(std::string_view external_relative_path) |
| 193 | { |
| 194 | auto path = MakeAbsoluteFromRelative(external_relative_path); |
| 195 | if (!path) |
| 196 | return {}; |
| 197 | ::File::FSTEntry external_files = ::File::ScanDirectoryTree(*path, false); |
| 198 | std::vector<FileDataLoader::Node> nodes; |
| 199 | nodes.reserve(external_files.children.size()); |
| 200 | for (auto& file : external_files.children) |
| 201 | nodes.emplace_back(FileDataLoader::Node{std::move(file.virtualName), file.isDirectory}); |
| 202 | return nodes; |
| 203 | } |
| 204 | |
| 205 | BuilderContentSource |
| 206 | FileDataLoaderHostFS::MakeContentSource(std::string_view external_relative_path, |
| 207 | u64 external_offset, u64 external_size, u64 disc_offset) |
| 208 | { |
| 209 | auto path = MakeAbsoluteFromRelative(external_relative_path); |
| 210 | if (!path) |
| 211 | return BuilderContentSource{disc_offset, external_size, ContentFixedByte{}}; |
| 212 | return BuilderContentSource{disc_offset, external_size, |
| 213 | ContentFile{std::move(*path), external_offset}}; |
| 214 | } |
| 215 | |
| 216 | std::optional<std::string> |
| 217 | FileDataLoaderHostFS::ResolveSavegameRedirectPath(std::string_view external_relative_path) |
| 218 | { |
| 219 | return MakeAbsoluteFromRelative(external_relative_path); |
| 220 | } |
| 221 | |
| 222 | // 'before' and 'after' should be two copies of the same source |
| 223 | // 'split_at' needs to be between the start and end of the source, may not match either boundary |
| 224 | static void SplitAt(BuilderContentSource* before, BuilderContentSource* after, u64 split_at) |
| 225 | { |
| 226 | const u64 start = before->m_offset; |
| 227 | const u64 size = before->m_size; |
| 228 | const u64 end = start + size; |
| 229 | |
| 230 | // The source before the split point just needs its length reduced. |
| 231 | before->m_size = split_at - start; |
| 232 | |
| 233 | // The source after the split needs its length reduced and its start point adjusted. |
| 234 | after->m_offset += before->m_size; |
| 235 | after->m_size = end - split_at; |
| 236 | if (std::holds_alternative<ContentFile>(after->m_source)) |
| 237 | { |
| 238 | std::get<ContentFile>(after->m_source).m_offset += before->m_size; |
| 239 | } |
| 240 | else if (std::holds_alternative<ContentMemory>(after->m_source)) |
| 241 | { |
| 242 | after->m_source = std::make_shared<std::vector<u8>>( |
| 243 | std::get<ContentMemory>(after->m_source)->begin() + before->m_size, |
| 244 | std::get<ContentMemory>(after->m_source)->end()); |
| 245 | } |
| 246 | else if (std::holds_alternative<ContentPartition>(after->m_source)) |
| 247 | { |
| 248 | std::get<ContentPartition>(after->m_source).m_offset += before->m_size; |
| 249 | } |
| 250 | else if (std::holds_alternative<ContentVolume>(after->m_source)) |
| 251 | { |
| 252 | std::get<ContentVolume>(after->m_source).m_offset += before->m_size; |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | static void ApplyPatchToFile(const Patch& patch, FSTBuilderNode* file_node, |
| 257 | std::string_view external_filename, u64 file_patch_offset, |
| 258 | u64 raw_external_file_offset, u64 file_patch_length, bool resize) |
| 259 | { |
| 260 | const auto f = patch.m_file_data_loader->GetExternalFileSize(external_filename); |
| 261 | if (!f) |
| 262 | return; |
| 263 | |
| 264 | auto& content = std::get<std::vector<BuilderContentSource>>(file_node->m_content); |
| 265 | |
| 266 | const u64 raw_external_filesize = *f; |
| 267 | const u64 external_file_offset = std::min(raw_external_file_offset, raw_external_filesize); |
| 268 | const u64 external_filesize = raw_external_filesize - external_file_offset; |
| 269 | |
| 270 | const u64 patch_start = file_patch_offset; |
| 271 | const u64 patch_size = file_patch_length == 0 ? external_filesize : file_patch_length; |
| 272 | const u64 patch_end = patch_start + patch_size; |
| 273 | |
| 274 | const u64 target_filesize = resize ? patch_end : std::max(file_node->m_size, patch_end); |
| 275 | |
| 276 | size_t insert_where = 0; |
| 277 | if (patch_start >= file_node->m_size) |
| 278 | { |
| 279 | // If the patch is at or past the end of the existing file no existing content needs to be |
| 280 | // touched, just extend the file. |
| 281 | if (patch_start > file_node->m_size) |
| 282 | { |
| 283 | // Insert an padding area between the old file and the patch data. |
| 284 | content.emplace_back(BuilderContentSource{file_node->m_size, patch_start - file_node->m_size, |
| 285 | ContentFixedByte{}}); |
| 286 | } |
| 287 | |
| 288 | insert_where = content.size(); |
| 289 | } |
| 290 | else |
| 291 | { |
| 292 | // Patch is at the start or somewhere in the middle of the existing file. At least one source |
| 293 | // needs to be modified or removed, and a new source with the patch data inserted instead. |
| 294 | // To make this easier, we first split up existing sources at the patch start and patch end |
| 295 | // offsets, then discard all overlapping sources and insert the patch sources there. |
| 296 | for (size_t i = 0; i < content.size(); ++i) |
| 297 | { |
| 298 | const u64 source_start = content[i].m_offset; |
| 299 | const u64 source_end = source_start + content[i].m_size; |
| 300 | if (patch_start > source_start && patch_start < source_end) |
| 301 | { |
| 302 | content.insert(content.begin() + i + 1, content[i]); |
| 303 | SplitAt(&content[i], &content[i + 1], patch_start); |
| 304 | continue; |
| 305 | } |
| 306 | if (patch_end > source_start && patch_end < source_end) |
| 307 | { |
| 308 | content.insert(content.begin() + i + 1, content[i]); |
| 309 | SplitAt(&content[i], &content[i + 1], patch_end); |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // Now discard the overlapping areas and remember where they were so we can insert there. |
| 314 | for (size_t i = 0; i < content.size(); ++i) |
| 315 | { |
| 316 | if (patch_start == content[i].m_offset) |
| 317 | { |
| 318 | insert_where = i; |
| 319 | while (i < content.size() && patch_end >= content[i].m_offset + content[i].m_size) |
| 320 | ++i; |
| 321 | content.erase(content.begin() + insert_where, content.begin() + i); |
| 322 | break; |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // Insert the actual patch data. |
| 328 | if (patch_size > 0 && external_filesize > 0) |
| 329 | { |
| 330 | BuilderContentSource source = patch.m_file_data_loader->MakeContentSource( |
| 331 | external_filename, external_file_offset, std::min(patch_size, external_filesize), |
| 332 | patch_start); |
| 333 | content.emplace(content.begin() + insert_where, std::move(source)); |
| 334 | ++insert_where; |
| 335 | } |
| 336 | |
| 337 | // Pad with zeroes if the patch file is smaller than the patch size. |
| 338 | if (external_filesize < patch_size) |
| 339 | { |
| 340 | BuilderContentSource padding{patch_start + external_filesize, patch_size - external_filesize, |
| 341 | ContentFixedByte{}}; |
| 342 | content.emplace(content.begin() + insert_where, std::move(padding)); |
| 343 | } |
| 344 | |
| 345 | // Update the filesize of the file. |
| 346 | file_node->m_size = target_filesize; |
| 347 | |
| 348 | // Drop any source past the new end of the file -- this can happen on file truncation. |
| 349 | while (!content.empty() && content.back().m_offset >= target_filesize) |
| 350 | content.pop_back(); |
| 351 | } |
| 352 | |
| 353 | static void ApplyPatchToFile(const Patch& patch, const File& file_patch, FSTBuilderNode* file_node) |
| 354 | { |
| 355 | // The last two bits of the offset seem to be ignored by actual Riivolution. |
| 356 | ApplyPatchToFile(patch, file_node, file_patch.m_external, file_patch.m_offset & ~u64(3), |
| 357 | file_patch.m_fileoffset, file_patch.m_length, file_patch.m_resize); |
| 358 | } |
| 359 | |
| 360 | static FSTBuilderNode* FindFileNodeInFST(std::string_view path, std::vector<FSTBuilderNode>* fst, |
| 361 | bool create_if_not_exists) |
| 362 | { |
| 363 | const size_t path_separator = path.find('/'); |
| 364 | const bool is_file = path_separator == std::string_view::npos; |
| 365 | const std::string_view name = is_file ? path : path.substr(0, path_separator); |
| 366 | const auto it = std::ranges::find_if(*fst, [&](const FSTBuilderNode& node) { |
| 367 | return Common::CaseInsensitiveEquals(node.m_filename, name); |
| 368 | }); |
| 369 | |
| 370 | if (it == fst->end()) |
| 371 | { |
| 372 | if (!create_if_not_exists) |
| 373 | return nullptr; |
| 374 | |
| 375 | if (is_file) |
| 376 | { |
| 377 | return &fst->emplace_back( |
| 378 | FSTBuilderNode{std::string(name), 0, std::vector<BuilderContentSource>()}); |
| 379 | } |
| 380 | |
| 381 | auto& new_folder = |
| 382 | fst->emplace_back(FSTBuilderNode{std::string(name), 0, std::vector<FSTBuilderNode>()}); |
| 383 | return FindFileNodeInFST(path.substr(path_separator + 1), |
| 384 | &std::get<std::vector<FSTBuilderNode>>(new_folder.m_content), true); |
| 385 | } |
| 386 | |
| 387 | const bool is_existing_node_file = it->IsFile(); |
| 388 | if (is_file != is_existing_node_file) |
| 389 | return nullptr; |
| 390 | if (is_file) |
| 391 | return &*it; |
| 392 | |
| 393 | return FindFileNodeInFST(path.substr(path_separator + 1), |
| 394 | &std::get<std::vector<FSTBuilderNode>>(it->m_content), |
| 395 | create_if_not_exists); |
| 396 | } |
| 397 | |
| 398 | static FSTBuilderNode* FindFilenameNodeInFST(std::string_view filename, |
| 399 | std::vector<FSTBuilderNode>& fst) |
| 400 | { |
| 401 | for (FSTBuilderNode& node : fst) |
| 402 | { |
| 403 | if (node.IsFolder()) |
| 404 | { |
| 405 | FSTBuilderNode* result = FindFilenameNodeInFST(filename, node.GetFolderContent()); |
| 406 | if (result) |
| 407 | return result; |
| 408 | } |
| 409 | else if (Common::CaseInsensitiveEquals(node.m_filename, filename)) |
| 410 | { |
| 411 | return &node; |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | return nullptr; |
| 416 | } |
| 417 | |
| 418 | static void ApplyFilePatchToFST(const Patch& patch, const File& file, |
| 419 | std::vector<FSTBuilderNode>* fst, FSTBuilderNode* dol_node) |
| 420 | { |
| 421 | if (!file.m_disc.empty() && file.m_disc[0] == '/') |
| 422 | { |
| 423 | // If the disc path starts with a / then we should patch that specific disc path. |
| 424 | FSTBuilderNode* node = |
| 425 | FindFileNodeInFST(std::string_view(file.m_disc).substr(1), fst, file.m_create); |
| 426 | if (node) |
| 427 | ApplyPatchToFile(patch, file, node); |
| 428 | } |
| 429 | else if (dol_node && Common::CaseInsensitiveEquals(file.m_disc, "main.dol")) |
| 430 | { |
| 431 | // Special case: If the filename is "main.dol", we want to patch the main executable. |
| 432 | ApplyPatchToFile(patch, file, dol_node); |
| 433 | } |
| 434 | else |
| 435 | { |
| 436 | // Otherwise we want to patch the first file in the FST that matches that filename. |
| 437 | FSTBuilderNode* node = FindFilenameNodeInFST(file.m_disc, *fst); |
| 438 | if (node) |
| 439 | ApplyPatchToFile(patch, file, node); |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | static void ApplyFolderPatchToFST(const Patch& patch, const Folder& folder, |
| 444 | std::vector<FSTBuilderNode>* fst, FSTBuilderNode* dol_node, |
| 445 | std::string_view disc_path, std::string_view external_path) |
| 446 | { |
| 447 | const auto external_files = patch.m_file_data_loader->GetFolderContents(external_path); |
| 448 | for (const auto& child : external_files) |
| 449 | { |
| 450 | const auto combine_paths = [](std::string_view a, std::string_view b) { |
| 451 | if (a.empty()) |
| 452 | return std::string(b); |
| 453 | if (b.empty()) |
| 454 | return std::string(a); |
| 455 | if (a.ends_with('/')) |
| 456 | a.remove_suffix(1); |
| 457 | if (b.starts_with('/')) |
| 458 | b.remove_prefix(1); |
| 459 | return fmt::format("{}/{}", a, b); |
| 460 | }; |
| 461 | std::string child_disc_path = combine_paths(disc_path, child.m_filename); |
| 462 | std::string child_external_path = combine_paths(external_path, child.m_filename); |
| 463 | |
| 464 | if (child.m_is_directory) |
| 465 | { |
| 466 | if (folder.m_recursive) |
| 467 | ApplyFolderPatchToFST(patch, folder, fst, dol_node, child_disc_path, child_external_path); |
| 468 | } |
| 469 | else |
| 470 | { |
| 471 | File file; |
| 472 | file.m_disc = std::move(child_disc_path); |
| 473 | file.m_external = std::move(child_external_path); |
| 474 | file.m_resize = folder.m_resize; |
| 475 | file.m_create = folder.m_create; |
| 476 | file.m_length = folder.m_length; |
| 477 | ApplyFilePatchToFST(patch, file, fst, dol_node); |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | static void ApplyFolderPatchToFST(const Patch& patch, const Folder& folder, |
| 483 | std::vector<FSTBuilderNode>* fst, FSTBuilderNode* dol_node) |
| 484 | { |
| 485 | ApplyFolderPatchToFST(patch, folder, fst, dol_node, folder.m_disc, folder.m_external); |
| 486 | } |
| 487 | |
| 488 | void ApplyPatchesToFiles(std::span<const Patch> patches, PatchIndex index, |
| 489 | std::vector<FSTBuilderNode>* fst, FSTBuilderNode* dol_node) |
| 490 | { |
| 491 | for (const auto& patch : patches) |
| 492 | { |
| 493 | const auto& file_patches = |
| 494 | index == PatchIndex::DolphinSysFiles ? patch.m_sys_file_patches : patch.m_file_patches; |
| 495 | const auto& folder_patches = |
| 496 | index == PatchIndex::DolphinSysFiles ? patch.m_sys_folder_patches : patch.m_folder_patches; |
| 497 | |
| 498 | for (const auto& file : file_patches) |
| 499 | ApplyFilePatchToFST(patch, file, fst, dol_node); |
| 500 | |
| 501 | for (const auto& folder : folder_patches) |
| 502 | ApplyFolderPatchToFST(patch, folder, fst, dol_node); |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | static bool MemoryMatchesAt(const Core::CPUThreadGuard& guard, u32 offset, |
| 507 | std::span<const u8> value) |
| 508 | { |
| 509 | for (u32 i = 0; i < value.size(); ++i) |
| 510 | { |
| 511 | auto result = PowerPC::MMU::HostTryRead<u8>(guard, offset + i); |
| 512 | if (!result || result->value != value[i]) |
| 513 | return false; |
| 514 | } |
| 515 | return true; |
| 516 | } |
| 517 | |
| 518 | static void ApplyMemoryPatch(const Core::CPUThreadGuard& guard, u32 offset, |
| 519 | std::span<const u8> value, std::span<const u8> original) |
| 520 | { |
| 521 | if (AchievementManager::GetInstance().IsHardcoreModeActive()) |
| 522 | return; |
| 523 | |
| 524 | if (value.empty()) |
| 525 | return; |
| 526 | |
| 527 | if (!original.empty() && !MemoryMatchesAt(guard, offset, original)) |
| 528 | return; |
| 529 | |
| 530 | auto& system = guard.GetSystem(); |
| 531 | const u32 size = static_cast<u32>(value.size()); |
| 532 | for (u32 i = 0; i < size; ++i) |
| 533 | PowerPC::MMU::HostTryWrite<u8>(guard, value[i], offset + i); |
| 534 | const u32 overlapping_hook_count = HLE::UnpatchRange(system, offset, offset + size); |
| 535 | if (overlapping_hook_count != 0) |
| 536 | { |
| 537 | WARN_LOG_FMT(OSHLE, "Riivolution memory patch overlaps {} HLE hook(s) at {:08x} (size: {})", |
| 538 | overlapping_hook_count, offset, value.size()); |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | static std::vector<u8> GetMemoryPatchValue(const Patch& patch, const Memory& memory_patch) |
| 543 | { |
| 544 | if (!memory_patch.m_valuefile.empty()) |
| 545 | return patch.m_file_data_loader->GetFileContents(memory_patch.m_valuefile); |
| 546 | return memory_patch.m_value; |
| 547 | } |
| 548 | |
| 549 | static void ApplyMemoryPatch(const Core::CPUThreadGuard& guard, const Patch& patch, |
| 550 | const Memory& memory_patch) |
| 551 | { |
| 552 | if (memory_patch.m_offset == 0) |
| 553 | return; |
| 554 | |
| 555 | ApplyMemoryPatch(guard, memory_patch.m_offset | 0x80000000, |
| 556 | GetMemoryPatchValue(patch, memory_patch), memory_patch.m_original); |
| 557 | } |
| 558 | |
| 559 | static void ApplySearchMemoryPatch(const Core::CPUThreadGuard& guard, const Patch& patch, |
| 560 | const Memory& memory_patch, u32 ram_start, u32 length) |
| 561 | { |
| 562 | if (memory_patch.m_original.empty() || memory_patch.m_align == 0) |
| 563 | return; |
| 564 | |
| 565 | const u32 stride = memory_patch.m_align; |
| 566 | for (u32 i = 0; i < length - (stride - 1); i += stride) |
| 567 | { |
| 568 | const u32 address = ram_start + i; |
| 569 | if (MemoryMatchesAt(guard, address, memory_patch.m_original)) |
| 570 | { |
| 571 | ApplyMemoryPatch(guard, address, GetMemoryPatchValue(patch, memory_patch), {}); |
| 572 | break; |
| 573 | } |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | static void ApplyOcarinaMemoryPatch(const Core::CPUThreadGuard& guard, const Patch& patch, |
| 578 | const Memory& memory_patch, u32 ram_start, u32 length) |
| 579 | { |
| 580 | if (memory_patch.m_offset == 0) |
| 581 | return; |
| 582 | const std::vector<u8> value = GetMemoryPatchValue(patch, memory_patch); |
| 583 | if (value.empty()) |
| 584 | return; |
| 585 | |
| 586 | auto& system = guard.GetSystem(); |
| 587 | for (u32 i = 0; i < length; i += 4) |
| 588 | { |
| 589 | // first find the pattern |
| 590 | const u32 address = ram_start + i; |
| 591 | if (MemoryMatchesAt(guard, address, value)) |
| 592 | { |
| 593 | for (; i < length; i += 4) |
| 594 | { |
| 595 | // from the pattern find the next blr instruction |
| 596 | const u32 blr_address = ram_start + i; |
| 597 | auto blr = PowerPC::MMU::HostTryRead<u32>(guard, blr_address); |
| 598 | if (blr && blr->value == 0x4e800020) |
| 599 | { |
| 600 | // and replace it with a jump to the given offset |
| 601 | const u32 target = memory_patch.m_offset | 0x80000000; |
| 602 | const u32 jmp = ((target - blr_address) & 0x03fffffc) | 0x48000000; |
| 603 | PowerPC::MMU::HostTryWrite<u32>(guard, jmp, blr_address); |
| 604 | const u32 overlapping_hook_count = |
| 605 | HLE::UnpatchRange(system, blr_address, blr_address + 4); |
| 606 | if (overlapping_hook_count != 0) |
| 607 | { |
| 608 | WARN_LOG_FMT(OSHLE, "Riivolution ocarina patch overlaps HLE hook at {}", blr_address); |
| 609 | } |
| 610 | return; |
| 611 | } |
| 612 | } |
| 613 | return; |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | void ApplyGeneralMemoryPatches(const Core::CPUThreadGuard& guard, std::span<const Patch> patches) |
| 619 | { |
| 620 | const auto& system = guard.GetSystem(); |
| 621 | const auto& system_memory = system.GetMemory(); |
| 622 | |
| 623 | for (const auto& patch : patches) |
| 624 | { |
| 625 | for (const auto& memory : patch.m_memory_patches) |
| 626 | { |
| 627 | if (memory.m_ocarina) |
| 628 | continue; |
| 629 | |
| 630 | if (memory.m_search) |
| 631 | ApplySearchMemoryPatch(guard, patch, memory, 0x80000000, system_memory.GetRamSize()); |
| 632 | else |
| 633 | ApplyMemoryPatch(guard, patch, memory); |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | void ApplyApploaderMemoryPatches(const Core::CPUThreadGuard& guard, std::span<const Patch> patches, |
| 639 | u32 ram_address, u32 ram_length) |
| 640 | { |
| 641 | for (const auto& patch : patches) |
| 642 | { |
| 643 | for (const auto& memory : patch.m_memory_patches) |
| 644 | { |
| 645 | if (!memory.m_ocarina && !memory.m_search) |
| 646 | continue; |
| 647 | |
| 648 | if (memory.m_ocarina) |
| 649 | ApplyOcarinaMemoryPatch(guard, patch, memory, ram_address, ram_length); |
| 650 | else |
| 651 | ApplySearchMemoryPatch(guard, patch, memory, ram_address, ram_length); |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | std::optional<SavegameRedirect> ExtractSavegameRedirect(std::span<const Patch> riivolution_patches) |
| 657 | { |
| 658 | for (const auto& patch : riivolution_patches) |
| 659 | { |
| 660 | if (!patch.m_savegame_patches.empty()) |
| 661 | { |
| 662 | const auto& save_patch = patch.m_savegame_patches[0]; |
| 663 | auto resolved = patch.m_file_data_loader->ResolveSavegameRedirectPath(save_patch.m_external); |
| 664 | if (resolved) |
| 665 | return SavegameRedirect{std::move(*resolved), save_patch.m_clone}; |
| 666 | return std::nullopt; |
| 667 | } |
| 668 | } |
| 669 | return std::nullopt; |
| 670 | } |
| 671 | } // namespace DiscIO::Riivolution |