forked from ran-j/PS2Recomp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathps2_stubs_helpers.inl
More file actions
1935 lines (1731 loc) · 56.1 KB
/
ps2_stubs_helpers.inl
File metadata and controls
1935 lines (1731 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef PS2_CD_REMAP_IDX_TO_AFS
#define PS2_CD_REMAP_IDX_TO_AFS 1
#endif
namespace
{
constexpr uint32_t kCdSectorSize = 2048;
constexpr uint32_t kCdPseudoLbnStart = 0x00100000;
struct CdFileEntry
{
std::filesystem::path hostPath;
uint32_t sizeBytes = 0;
uint32_t baseLbn = 0;
uint32_t sectors = 0;
};
std::unordered_map<std::string, CdFileEntry> g_cdFilesByKey;
std::unordered_map<std::string, std::filesystem::path> g_cdLeafIndex;
std::filesystem::path g_cdLeafIndexRoot;
bool g_cdLeafIndexBuilt = false;
uint32_t g_nextPseudoLbn = kCdPseudoLbnStart;
std::filesystem::path g_cdAutoImagePath;
std::filesystem::path g_cdAutoImageRoot;
bool g_cdAutoImageSearched = false;
std::filesystem::path g_cdImageSizePath;
uint64_t g_cdImageSizeBytes = 0;
bool g_cdImageSizeValid = false;
int32_t g_lastCdError = 0;
uint32_t g_cdMode = 0;
uint32_t g_cdStreamingLbn = 0;
bool g_cdInitialized = false;
constexpr uint32_t kIopHeapBase = 0x01A00000;
constexpr uint32_t kIopHeapLimit = 0x01F00000;
constexpr uint32_t kIopHeapAlign = 64;
uint32_t g_iopHeapNext = kIopHeapBase;
std::string toLowerAscii(std::string value)
{
std::transform(value.begin(), value.end(), value.begin(),
[](unsigned char c)
{ return static_cast<char>(std::tolower(c)); });
return value;
}
std::string stripIsoVersionSuffix(std::string value)
{
const std::size_t semicolon = value.find(';');
if (semicolon == std::string::npos)
{
return value;
}
bool numericSuffix = semicolon + 1 < value.size();
for (std::size_t i = semicolon + 1; i < value.size(); ++i)
{
if (!std::isdigit(static_cast<unsigned char>(value[i])))
{
numericSuffix = false;
break;
}
}
if (numericSuffix)
{
value.erase(semicolon);
}
return value;
}
std::string normalizePathSeparators(std::string value)
{
std::replace(value.begin(), value.end(), '\\', '/');
return value;
}
void trimLeadingSeparators(std::string &value)
{
while (!value.empty() && (value.front() == '/' || value.front() == '\\'))
{
value.erase(value.begin());
}
}
std::string normalizeCdPathNoPrefix(std::string path)
{
path = normalizePathSeparators(std::move(path));
std::string lower = toLowerAscii(path);
if (lower.rfind("cdrom0:", 0) == 0)
{
path = path.substr(7);
}
else if (lower.rfind("cdrom:", 0) == 0)
{
path = path.substr(6);
}
trimLeadingSeparators(path);
while (!path.empty() && std::isspace(static_cast<unsigned char>(path.front())))
{
path.erase(path.begin());
}
while (!path.empty() && std::isspace(static_cast<unsigned char>(path.back())))
{
path.pop_back();
}
path = stripIsoVersionSuffix(std::move(path));
return path;
}
std::filesystem::path getCdRootPath()
{
const PS2Runtime::IoPaths &paths = PS2Runtime::getIoPaths();
if (!paths.cdRoot.empty())
{
return paths.cdRoot;
}
if (!paths.elfDirectory.empty())
{
return paths.elfDirectory;
}
std::error_code ec;
const std::filesystem::path cwd = std::filesystem::current_path(ec);
return ec ? std::filesystem::path(".") : cwd.lexically_normal();
}
bool hasCdImageExtension(const std::filesystem::path &path)
{
const std::string ext = toLowerAscii(path.extension().string());
return ext == ".iso" || ext == ".bin" || ext == ".img" || ext == ".mdf" || ext == ".nrg";
}
bool trySelectBestDiscImageFromDirectory(const std::filesystem::path &dir,
std::filesystem::path &pathOut)
{
std::error_code ec;
if (!std::filesystem::exists(dir, ec) || ec || !std::filesystem::is_directory(dir, ec))
{
return false;
}
std::filesystem::path bestPath;
uint64_t bestSize = 0;
for (const auto &entry : std::filesystem::directory_iterator(
dir, std::filesystem::directory_options::skip_permission_denied, ec))
{
if (ec)
{
break;
}
if (!entry.is_regular_file())
{
continue;
}
if (!hasCdImageExtension(entry.path()))
{
continue;
}
std::error_code sizeEc;
const uint64_t size = static_cast<uint64_t>(entry.file_size(sizeEc));
if (sizeEc || size < (64ull * 1024ull * 1024ull))
{
continue;
}
if (size > bestSize)
{
bestSize = size;
bestPath = entry.path();
}
}
if (bestPath.empty())
{
return false;
}
pathOut = bestPath;
return true;
}
std::filesystem::path autoDetectCdImagePath()
{
const PS2Runtime::IoPaths &paths = PS2Runtime::getIoPaths();
std::vector<std::filesystem::path> roots;
const std::filesystem::path cdRoot = getCdRootPath();
if (!cdRoot.empty())
{
roots.push_back(cdRoot);
std::filesystem::path parent = cdRoot;
for (int i = 0; i < 4; ++i)
{
parent = parent.parent_path();
if (parent.empty())
{
break;
}
roots.push_back(parent);
}
}
if (!paths.hostRoot.empty())
{
roots.push_back(paths.hostRoot);
}
if (!paths.elfDirectory.empty())
{
roots.push_back(paths.elfDirectory);
}
std::filesystem::path bestPath;
uint64_t bestSize = 0;
std::unordered_set<std::string> seenRoots;
for (const std::filesystem::path &root : roots)
{
if (root.empty())
{
continue;
}
const std::string key = toLowerAscii(root.lexically_normal().string());
if (!seenRoots.emplace(key).second)
{
continue;
}
std::filesystem::path candidate;
if (!trySelectBestDiscImageFromDirectory(root, candidate))
{
continue;
}
std::error_code sizeEc;
const uint64_t size = static_cast<uint64_t>(std::filesystem::file_size(candidate, sizeEc));
if (sizeEc || size <= bestSize)
{
continue;
}
bestSize = size;
bestPath = candidate;
}
if (!bestPath.empty())
{
std::cout << "[CD] Auto-detected disc image: " << bestPath.string() << std::endl;
}
return bestPath;
}
std::filesystem::path getCdImagePath()
{
const PS2Runtime::IoPaths &paths = PS2Runtime::getIoPaths();
if (!paths.cdImage.empty())
{
return paths.cdImage;
}
const std::filesystem::path cdRoot = getCdRootPath();
if (!g_cdAutoImageSearched || g_cdAutoImageRoot != cdRoot)
{
g_cdAutoImageRoot = cdRoot;
g_cdAutoImagePath = autoDetectCdImagePath();
g_cdAutoImageSearched = true;
}
return g_cdAutoImagePath;
}
bool tryGetCdImageTotalSectors(uint64_t &totalSectorsOut)
{
const std::filesystem::path imagePath = getCdImagePath();
if (imagePath.empty())
{
return false;
}
if (!g_cdImageSizeValid || g_cdImageSizePath != imagePath)
{
std::error_code ec;
g_cdImageSizeBytes = static_cast<uint64_t>(std::filesystem::file_size(imagePath, ec));
g_cdImageSizePath = imagePath;
g_cdImageSizeValid = !ec;
}
if (!g_cdImageSizeValid)
{
return false;
}
totalSectorsOut = g_cdImageSizeBytes / static_cast<uint64_t>(kCdSectorSize);
return true;
}
uint32_t sectorsForBytes(uint64_t byteCount)
{
const uint64_t sectors = (byteCount + (kCdSectorSize - 1)) / kCdSectorSize;
return sectors > 0 ? static_cast<uint32_t>(sectors) : 1;
}
std::string cdPathKey(const std::string &ps2Path)
{
return toLowerAscii(normalizeCdPathNoPrefix(ps2Path));
}
std::filesystem::path cdHostPath(const std::string &ps2Path)
{
const std::string normalized = normalizeCdPathNoPrefix(ps2Path);
std::filesystem::path resolved = getCdRootPath();
if (!normalized.empty())
{
resolved /= std::filesystem::path(normalized);
}
return resolved.lexically_normal();
}
bool resolveCaseInsensitivePath(const std::filesystem::path &root,
const std::filesystem::path &relative,
std::filesystem::path &resolvedOut)
{
std::filesystem::path current = root;
for (const auto &component : relative)
{
const std::filesystem::path direct = current / component;
std::error_code ec;
if (std::filesystem::exists(direct, ec) && !ec)
{
current = direct;
continue;
}
bool matched = false;
const std::string needle = toLowerAscii(component.string());
std::error_code iterEc;
for (const auto &entry : std::filesystem::directory_iterator(current, iterEc))
{
if (iterEc)
{
break;
}
const std::string candidate = toLowerAscii(entry.path().filename().string());
if (candidate == needle)
{
current = entry.path();
matched = true;
break;
}
}
if (!matched)
{
return false;
}
}
std::error_code fileEc;
if (std::filesystem::is_regular_file(current, fileEc) && !fileEc)
{
resolvedOut = current;
return true;
}
return false;
}
void ensureCdLeafIndex(const std::filesystem::path &root)
{
if (g_cdLeafIndexBuilt && g_cdLeafIndexRoot == root)
{
return;
}
g_cdLeafIndex.clear();
g_cdLeafIndexRoot = root;
g_cdLeafIndexBuilt = true;
std::error_code ec;
if (!std::filesystem::exists(root, ec) || ec)
{
return;
}
for (const auto &entry : std::filesystem::recursive_directory_iterator(
root, std::filesystem::directory_options::skip_permission_denied, ec))
{
if (ec)
{
break;
}
if (!entry.is_regular_file())
{
continue;
}
const std::string leaf = toLowerAscii(entry.path().filename().string());
g_cdLeafIndex.emplace(leaf, entry.path());
}
}
bool registerCdFile(const std::string &ps2Path, CdFileEntry &entryOut)
{
const std::string key = cdPathKey(ps2Path);
if (key.empty())
{
g_lastCdError = -1;
return false;
}
auto existing = g_cdFilesByKey.find(key);
if (existing != g_cdFilesByKey.end())
{
entryOut = existing->second;
g_lastCdError = 0;
return true;
}
const std::filesystem::path root = getCdRootPath();
std::filesystem::path path = cdHostPath(ps2Path);
std::error_code ec;
if (!std::filesystem::exists(path, ec) || ec || !std::filesystem::is_regular_file(path, ec))
{
const std::filesystem::path relative(normalizeCdPathNoPrefix(ps2Path));
std::filesystem::path resolvedCasePath;
if (resolveCaseInsensitivePath(root, relative, resolvedCasePath))
{
path = resolvedCasePath;
ec.clear();
}
else
{
ensureCdLeafIndex(root);
const std::string leaf = toLowerAscii(relative.filename().string());
auto it = g_cdLeafIndex.find(leaf);
if (it != g_cdLeafIndex.end())
{
path = it->second;
ec.clear();
}
else
{
g_lastCdError = -1;
return false;
}
}
}
const uint64_t sizeBytes = std::filesystem::file_size(path, ec);
if (ec)
{
g_lastCdError = -1;
return false;
}
CdFileEntry entry;
entry.hostPath = path;
entry.sizeBytes = static_cast<uint32_t>(std::min<uint64_t>(sizeBytes, 0xFFFFFFFFu));
entry.baseLbn = g_nextPseudoLbn;
entry.sectors = sectorsForBytes(sizeBytes);
g_nextPseudoLbn += entry.sectors + 1;
g_cdFilesByKey.emplace(key, entry);
entryOut = entry;
g_lastCdError = 0;
return true;
}
bool readHostRange(const std::filesystem::path &path, uint64_t offsetBytes, uint8_t *dst, size_t byteCount)
{
if (!dst)
{
g_lastCdError = -1;
return false;
}
if (byteCount == 0)
{
g_lastCdError = 0;
return true;
}
std::memset(dst, 0, byteCount);
std::ifstream file(path, std::ios::binary);
if (!file.is_open())
{
g_lastCdError = -1;
return false;
}
file.seekg(static_cast<std::streamoff>(offsetBytes), std::ios::beg);
if (!file.good())
{
g_lastCdError = -1;
return false;
}
file.read(reinterpret_cast<char *>(dst), static_cast<std::streamsize>(byteCount));
g_lastCdError = 0;
return true;
}
bool readCdSectors(uint32_t lbn, uint32_t sectors, uint8_t *dst, size_t byteCount)
{
for (const auto &[key, entry] : g_cdFilesByKey)
{
const uint32_t endLbn = entry.baseLbn + entry.sectors;
if (lbn < entry.baseLbn || lbn >= endLbn)
{
continue;
}
const uint64_t relativeLbn = static_cast<uint64_t>(lbn - entry.baseLbn);
const uint64_t offset = relativeLbn * kCdSectorSize;
return readHostRange(entry.hostPath, offset, dst, byteCount);
}
const std::filesystem::path cdImage = getCdImagePath();
if (!cdImage.empty())
{
uint64_t totalSectors = 0;
if (tryGetCdImageTotalSectors(totalSectors))
{
const uint64_t start = static_cast<uint64_t>(lbn);
const uint64_t end = start + static_cast<uint64_t>(sectors);
if (start >= totalSectors || end > totalSectors)
{
g_lastCdError = -1;
return false;
}
}
const uint64_t offset = static_cast<uint64_t>(lbn) * kCdSectorSize;
return readHostRange(cdImage, offset, dst, byteCount);
}
std::cerr << "sceCdRead unresolved LBN 0x" << std::hex << lbn
<< " sectors=" << std::dec << sectors
<< " (no mapped file and no configured CD image)" << std::endl;
g_lastCdError = -1;
return false;
}
bool isResolvableCdLbn(uint32_t lbn)
{
for (const auto &[key, entry] : g_cdFilesByKey)
{
const uint32_t endLbn = entry.baseLbn + entry.sectors;
if (lbn >= entry.baseLbn && lbn < endLbn)
{
return true;
}
}
uint64_t totalSectors = 0;
if (tryGetCdImageTotalSectors(totalSectors))
{
return static_cast<uint64_t>(lbn) < totalSectors;
}
return false;
}
bool writeCdSearchResult(uint8_t *rdram, uint32_t fileAddr, const std::string &ps2Path, const CdFileEntry &entry)
{
// sceCdlFILE layout: u32 lsn, u32 size, char name[16], u8 date[8]
uint8_t *fileStruct = getMemPtr(rdram, fileAddr);
if (!fileStruct)
{
return false;
}
std::array<uint8_t, 32> packed{};
std::memcpy(packed.data() + 0, &entry.baseLbn, sizeof(entry.baseLbn));
std::memcpy(packed.data() + 4, &entry.sizeBytes, sizeof(entry.sizeBytes));
std::filesystem::path leafPath(normalizeCdPathNoPrefix(ps2Path));
std::string leaf = leafPath.filename().string();
leaf = stripIsoVersionSuffix(std::move(leaf));
std::strncpy(reinterpret_cast<char *>(packed.data() + 8), leaf.c_str(), 15);
std::memcpy(fileStruct, packed.data(), packed.size());
return true;
}
bool hostFileHasAfsMagic(const std::filesystem::path &path)
{
std::ifstream file(path, std::ios::binary);
if (!file.is_open())
{
return false;
}
char magic[4] = {};
file.read(magic, sizeof(magic));
if (file.gcount() < 3)
{
return false;
}
return magic[0] == 'A' && magic[1] == 'F' && magic[2] == 'S';
}
bool tryRemapGdInitSearchToAfs(const std::string &ps2Path,
uint32_t callerRa,
const CdFileEntry &foundEntry,
CdFileEntry &entryOut,
std::string &resolvedPathOut)
{
#if !PS2_CD_REMAP_IDX_TO_AFS
{
return false;
}
#endif
if (callerRa != 0x2d9444u)
{
return false;
}
std::filesystem::path relative(normalizeCdPathNoPrefix(ps2Path));
const std::string ext = toLowerAscii(relative.extension().string());
const std::string leaf = toLowerAscii(relative.filename().string());
if (ext == ".idx")
{
if (foundEntry.sizeBytes > (kCdSectorSize * 8u))
{
return false;
}
std::filesystem::path afsRelative = relative;
afsRelative.replace_extension(".AFS");
CdFileEntry afsEntry;
if (!registerCdFile(afsRelative.generic_string(), afsEntry))
{
return false;
}
if (!hostFileHasAfsMagic(afsEntry.hostPath))
{
return false;
}
entryOut = afsEntry;
resolvedPathOut = afsRelative.generic_string();
return true;
}
return false;
}
uint8_t toBcd(uint32_t value)
{
const uint32_t clamped = value % 100;
return static_cast<uint8_t>(((clamped / 10) << 4) | (clamped % 10));
}
uint32_t fromBcd(uint8_t value)
{
return static_cast<uint32_t>(((value >> 4) & 0x0F) * 10 + (value & 0x0F));
}
std::unordered_map<uint32_t, FILE *> g_file_map;
uint32_t g_next_file_handle = 1; // Start file handles > 0 (0 is NULL)
std::mutex g_file_mutex;
uint32_t generate_file_handle()
{
uint32_t handle = 0;
do
{
handle = g_next_file_handle++;
if (g_next_file_handle == 0)
g_next_file_handle = 1;
} while (handle == 0 || g_file_map.count(handle));
return handle;
}
FILE *get_file_ptr(uint32_t handle)
{
if (handle == 0)
return nullptr;
std::lock_guard<std::mutex> lock(g_file_mutex);
auto it = g_file_map.find(handle);
return (it != g_file_map.end()) ? it->second : nullptr;
}
}
namespace
{
// convert a host pointer within rdram back to a PS2 address
uint32_t hostPtrToPs2Addr(uint8_t *rdram, const void *hostPtr)
{
if (!hostPtr)
return 0; // Handle NULL pointer case
const uint8_t *ptr_u8 = static_cast<const uint8_t *>(hostPtr);
std::ptrdiff_t offset = ptr_u8 - rdram;
// Check if is in rdram range
if (offset >= 0 && static_cast<size_t>(offset) < PS2_RAM_SIZE)
{
return PS2_RAM_BASE + static_cast<uint32_t>(offset);
}
else
{
std::cerr << "Warning: hostPtrToPs2Addr failed - host pointer " << hostPtr << " is outside rdram range [" << static_cast<void *>(rdram) << ", " << static_cast<void *>(rdram + PS2_RAM_SIZE) << ")" << std::endl;
return 0;
}
}
}
namespace
{
bool tryReadWordFromRdram(uint8_t *rdram, uint32_t addr, uint32_t &outWord)
{
const uint8_t *ptr = getConstMemPtr(rdram, addr);
if (!ptr)
{
return false;
}
std::memcpy(&outWord, ptr, sizeof(outWord));
return true;
}
bool tryReadWordFromGuest(uint8_t *rdram, PS2Runtime *runtime, uint32_t addr, uint32_t &outWord)
{
if (tryReadWordFromRdram(rdram, addr, outWord))
{
return true;
}
if (runtime)
{
try
{
PS2Memory &mem = runtime->memory();
outWord = static_cast<uint32_t>(mem.read8(addr + 0u)) |
(static_cast<uint32_t>(mem.read8(addr + 1u)) << 8u) |
(static_cast<uint32_t>(mem.read8(addr + 2u)) << 16u) |
(static_cast<uint32_t>(mem.read8(addr + 3u)) << 24u);
return true;
}
catch (...)
{
return false;
}
}
return false;
}
bool tryReadByteFromGuest(uint8_t *rdram, PS2Runtime *runtime, uint32_t addr, uint8_t &outByte)
{
const uint8_t *chPtr = getConstMemPtr(rdram, addr);
if (chPtr)
{
outByte = *chPtr;
return true;
}
if (runtime)
{
try
{
outByte = runtime->memory().read8(addr);
return true;
}
catch (...)
{
return false;
}
}
return false;
}
bool writeGuestBytes(uint8_t *rdram, PS2Runtime *runtime, uint32_t addr, const uint8_t *src, size_t len)
{
if (!src || len == 0)
{
return true;
}
bool allViaPtrs = true;
for (size_t i = 0; i < len; ++i)
{
const uint64_t guestAddr = static_cast<uint64_t>(addr) + i;
if (guestAddr > 0xFFFFFFFFull)
{
return false;
}
uint8_t *dst = getMemPtr(rdram, static_cast<uint32_t>(guestAddr));
if (!dst)
{
allViaPtrs = false;
break;
}
*dst = src[i];
}
if (allViaPtrs)
{
return true;
}
if (runtime)
{
try
{
PS2Memory &mem = runtime->memory();
for (size_t i = 0; i < len; ++i)
{
const uint64_t guestAddr = static_cast<uint64_t>(addr) + i;
if (guestAddr > 0xFFFFFFFFull)
{
return false;
}
mem.write8(static_cast<uint32_t>(guestAddr), src[i]);
}
return true;
}
catch (...)
{
return false;
}
}
return false;
}
std::string readPs2CStringBounded(uint8_t *rdram, PS2Runtime *runtime, uint32_t addr, size_t maxLen = 512)
{
std::string out;
if (addr == 0 || maxLen == 0)
{
return out;
}
out.reserve(std::min<size_t>(maxLen, 128));
for (size_t i = 0; i < maxLen; ++i)
{
const uint64_t guestAddr = static_cast<uint64_t>(addr) + i;
if (guestAddr > 0xFFFFFFFFull)
{
break;
}
uint8_t chByte = 0;
if (!tryReadByteFromGuest(rdram, runtime, static_cast<uint32_t>(guestAddr), chByte))
{
break;
}
const char ch = static_cast<char>(chByte);
if (ch == '\0')
{
break;
}
out.push_back(ch);
}
return out;
}
std::string readPs2CStringBounded(uint8_t *rdram, uint32_t addr, size_t maxLen = 512)
{
return readPs2CStringBounded(rdram, nullptr, addr, maxLen);
}
std::string sanitizeForLog(const std::string &value)
{
std::string out;
out.reserve(value.size());
for (unsigned char ch : value)
{
if (ch == '\n' || ch == '\r' || ch == '\t' || (ch >= 0x20 && ch < 0x7F))
{
out.push_back(static_cast<char>(ch));
}
else
{
out.push_back('.');
}
}
return out;
}
class Ps2VarArgCursor
{
public:
Ps2VarArgCursor(uint8_t *rdram, R5900Context *ctx, PS2Runtime *runtime, int fixedArgs)
: m_rdram(rdram),
m_ctx(ctx),
m_runtime(runtime),
m_fixedArgs(fixedArgs),
m_stackBase(getRegU32(ctx, 29) + 0x10)
{
if (m_fixedArgs < 0)
{
m_fixedArgs = 0;
}
m_slotIndex = static_cast<uint32_t>(m_fixedArgs);
}
uint32_t nextU32()
{
const uint32_t value = readWordAtSlot(m_slotIndex);
++m_slotIndex;
return value;
}
uint64_t nextU64()
{
// O32 ABI aligns 64-bit variadic values on even 32-bit slots.
if ((m_slotIndex & 1u) != 0u)
{
++m_slotIndex;
}
const uint64_t low = readWordAtSlot(m_slotIndex);
const uint64_t high = readWordAtSlot(m_slotIndex + 1u);
m_slotIndex += 2u;
return low | (high << 32);
}
private:
uint32_t readWordAtSlot(uint32_t slotIndex) const
{
if (slotIndex < 4u)
{
// slot0..slot3 -> a0..a3 (r4..r7)
return getRegU32(m_ctx, 4 + static_cast<int>(slotIndex));
}
const uint32_t stackIndex = slotIndex - 4u;
const uint32_t stackAddr = m_stackBase + stackIndex * 4u;
uint32_t value = 0;
(void)tryReadWordFromGuest(m_rdram, m_runtime, stackAddr, value);
return value;
}
uint8_t *m_rdram;
R5900Context *m_ctx;
PS2Runtime *m_runtime;
int m_fixedArgs;
uint32_t m_stackBase;
uint32_t m_slotIndex = 0;
};
class Ps2VaListCursor
{
public:
Ps2VaListCursor(uint8_t *rdram, PS2Runtime *runtime, uint32_t vaListAddr)
: m_rdram(rdram), m_runtime(runtime), m_curr(vaListAddr)
{
}
uint32_t nextU32()
{
uint32_t value = 0;
(void)tryReadWordFromGuest(m_rdram, m_runtime, m_curr, value);
m_curr += 4;
return value;
}
uint64_t nextU64()
{
m_curr = (m_curr + 7u) & ~7u;
const uint64_t low = nextU32();
const uint64_t high = nextU32();
return low | (high << 32);
}
private:
uint8_t *m_rdram;
PS2Runtime *m_runtime;
uint32_t m_curr = 0;
};
template <typename NextU32Fn, typename NextU64Fn, typename ReadStringFn>
std::string formatPs2StringCore(uint8_t *rdram, const char *format, NextU32Fn nextU32, NextU64Fn nextU64, ReadStringFn readString)
{
if (!format)
{
return {};
}
std::string out;
out.reserve(std::strlen(format) + 32);
const char *p = format;
while (*p)
{
if (*p != '%')
{
out.push_back(*p++);
continue;
}
const char *specStart = p++;
if (*p == '%')