-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathsceKernelModule.cpp
2727 lines (2372 loc) · 91.4 KB
/
sceKernelModule.cpp
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
// Copyright (c) 2012- PPSSPP Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0 or later versions.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include <algorithm>
#include <set>
#include "zlib.h"
#include "Common/Data/Convert/SmallDataConvert.h"
#include "Common/Serialize/Serializer.h"
#include "Common/Serialize/SerializeFuncs.h"
#include "Common/Serialize/SerializeSet.h"
#include "Common/File/FileUtil.h"
#include "Common/StringUtils.h"
#include "Common/System/Request.h"
#include "Common/System/System.h"
#include "Core/Config.h"
#include "Core/Core.h"
#include "Core/HLE/HLE.h"
#include "Core/HLE/FunctionWrappers.h"
#include "Core/HLE/HLETables.h"
#include "Core/HLE/Plugins.h"
#include "Core/HLE/ReplaceTables.h"
#include "Core/HLE/sceDisplay.h"
#include "Core/Reporting.h"
#include "Core/Loaders.h"
#include "Core/MIPS/MIPS.h"
#include "Core/MIPS/MIPSAnalyst.h"
#include "Core/MIPS/MIPSCodeUtils.h"
#include "Core/ELF/ElfReader.h"
#include "Core/ELF/PBPReader.h"
#include "Core/ELF/PrxDecrypter.h"
#include "Core/FileSystems/FileSystem.h"
#include "Core/FileSystems/MetaFileSystem.h"
#include "Core/Util/BlockAllocator.h"
#include "Core/CoreTiming.h"
#include "Core/PSPLoaders.h"
#include "Core/System.h"
#include "Core/MemMapHelpers.h"
#include "Core/Debugger/SymbolMap.h"
#include "Core/MIPS/MIPS.h"
#include "Core/HLE/sceKernel.h"
#include "Core/HLE/sceKernelModule.h"
#include "Core/HLE/sceKernelThread.h"
#include "Core/HLE/sceKernelMemory.h"
#include "Core/HLE/sceMpeg.h"
#include "Core/HLE/scePsmf.h"
#include "Core/HLE/sceIo.h"
#include "Core/HLE/KernelWaitHelpers.h"
#include "Core/ELF/ParamSFO.h"
#include "GPU/Debugger/Playback.h"
#include "GPU/GPU.h"
#include "GPU/GPUInterface.h"
#include "GPU/GPUState.h"
enum {
PSP_THREAD_ATTR_KERNEL = 0x00001000,
PSP_THREAD_ATTR_USER = 0x80000000,
};
enum : u32 {
// Function exports.
NID_MODULE_START = 0xD632ACDB,
NID_MODULE_STOP = 0xCEE8593C,
NID_MODULE_REBOOT_BEFORE = 0x2F064FA6,
NID_MODULE_REBOOT_PHASE = 0xADF12745,
NID_MODULE_BOOTSTART = 0xD3744BE0,
// Variable exports.
NID_MODULE_INFO = 0xF01D73A7,
NID_MODULE_START_THREAD_PARAMETER = 0x0F7C276C,
NID_MODULE_STOP_THREAD_PARAMETER = 0xCF0CC697,
NID_MODULE_REBOOT_BEFORE_THREAD_PARAMETER = 0xF4F4299D,
NID_MODULE_SDK_VERSION = 0x11B97506,
};
// This is a workaround for misbehaving homebrew (like TBL's Suicide Barbie (Final)).
static const char * const lieAboutSuccessModules[] = {
"flash0:/kd/audiocodec.prx",
"flash0:/kd/audiocodec_260.prx",
"flash0:/kd/libatrac3plus.prx",
"disc0:/PSP_GAME/SYSDIR/UPDATE/EBOOT.BIN",
"flash0:/kd/ifhandle.prx",
"flash0:/kd/pspnet.prx",
"flash0:/kd/pspnet_inet.prx",
"flash0:/kd/pspnet_apctl.prx",
"flash0:/kd/pspnet_resolver.prx",
};
// Modules to not load. TODO: Look into loosening this a little (say sceFont).
static const char * const blacklistedModules[] = {
"sceATRAC3plus_Library",
"sceFont_Library",
"SceFont_Library",
"SceHttp_Library",
"sceMpeg_library",
"sceNetAdhocctl_Library",
"sceNetAdhocDownload_Library",
"sceNetAdhocMatching_Library",
"sceNetApDialogDummy_Library",
"sceNetAdhoc_Library",
"sceNetApctl_Library",
"sceNetInet_Library",
"sceNetResolver_Library",
"sceNet_Library",
"sceNetAdhoc_Library",
"sceNetAdhocAuth_Service",
"sceNetAdhocctl_Library",
"sceNetIfhandle_Service",
"sceSsl_Module",
"sceDEFLATE_Library",
"sceMD5_Library",
"sceMemab",
};
struct WriteVarSymbolState;
struct VarSymbolImport {
char moduleName[KERNELOBJECT_MAX_NAME_LENGTH + 1];
u32 nid;
u32 stubAddr;
u8 type;
};
struct VarSymbolExport {
bool Matches(const VarSymbolImport &other) const {
return nid == other.nid && !strncmp(moduleName, other.moduleName, KERNELOBJECT_MAX_NAME_LENGTH);
}
char moduleName[KERNELOBJECT_MAX_NAME_LENGTH + 1];
u32 nid;
u32 symAddr;
};
struct FuncSymbolImport {
char moduleName[KERNELOBJECT_MAX_NAME_LENGTH + 1];
u32 stubAddr;
u32 nid;
};
struct FuncSymbolExport {
bool Matches(const FuncSymbolImport &other) const {
return nid == other.nid && !strncmp(moduleName, other.moduleName, KERNELOBJECT_MAX_NAME_LENGTH);
}
char moduleName[KERNELOBJECT_MAX_NAME_LENGTH + 1];
u32 symAddr;
u32 nid;
};
void ImportVarSymbol(WriteVarSymbolState &state, const VarSymbolImport &var);
void ExportVarSymbol(const VarSymbolExport &var);
void UnexportVarSymbol(const VarSymbolExport &var);
void ImportFuncSymbol(const FuncSymbolImport &func, bool reimporting, const char *importingModule);
void ExportFuncSymbol(const FuncSymbolExport &func);
void UnexportFuncSymbol(const FuncSymbolExport &func);
class PSPModule;
static bool KernelImportModuleFuncs(PSPModule *module, u32 *firstImportStubAddr, bool reimporting = false);
struct NativeModule {
u32_le next;
u16_le attribute;
u8 version[2];
char name[28];
u32_le status;
u32_le unk1;
u32_le modid; // 0x2C
u32_le usermod_thid;
u32_le memid;
u32_le mpidtext;
u32_le mpiddata;
u32_le ent_top;
u32_le ent_size;
u32_le stub_top;
u32_le stub_size;
u32_le module_start_func;
u32_le module_stop_func;
u32_le module_bootstart_func;
u32_le module_reboot_before_func;
u32_le module_reboot_phase_func;
u32_le entry_addr;
u32_le gp_value;
u32_le text_addr;
u32_le text_size;
u32_le data_size;
u32_le bss_size;
u32_le nsegment;
u32_le segmentaddr[4];
u32_le segmentsize[4];
u32_le module_start_thread_priority;
u32_le module_start_thread_stacksize;
u32_le module_start_thread_attr;
u32_le module_stop_thread_priority;
u32_le module_stop_thread_stacksize;
u32_le module_stop_thread_attr;
u32_le module_reboot_before_thread_priority;
u32_le module_reboot_before_thread_stacksize;
u32_le module_reboot_before_thread_attr;
};
// by QueryModuleInfo
struct ModuleInfo {
SceSize_le size;
u32_le nsegment;
u32_le segmentaddr[4];
u32_le segmentsize[4];
u32_le entry_addr;
u32_le gp_value;
u32_le text_addr;
u32_le text_size;
u32_le data_size;
u32_le bss_size;
u16_le attribute;
u8 version[2];
char name[28];
};
struct ModuleWaitingThread {
SceUID threadID;
u32 statusPtr;
};
enum NativeModuleStatus {
MODULE_STATUS_STARTING = 4,
MODULE_STATUS_STARTED = 5,
MODULE_STATUS_STOPPING = 6,
MODULE_STATUS_STOPPED = 7,
MODULE_STATUS_UNLOADING = 8,
};
class PSPModule : public KernelObject {
public:
PSPModule() {
modulePtr.ptr = 0;
}
~PSPModule() {
if (memoryBlockAddr) {
// If it's either below user memory, or using a high kernel bit, it's in kernel.
if (memoryBlockAddr < PSP_GetUserMemoryBase() || memoryBlockAddr > PSP_GetUserMemoryEnd()) {
kernelMemory.Free(memoryBlockAddr);
} else {
userMemory.Free(memoryBlockAddr);
}
g_symbolMap->UnloadModule(memoryBlockAddr, memoryBlockSize);
}
if (modulePtr.ptr) {
//Only alloc at kernel memory.
kernelMemory.Free(modulePtr.ptr);
}
}
const char *GetName() override { return nm.name; }
const char *GetTypeName() override { return GetStaticTypeName(); }
static const char *GetStaticTypeName() { return "Module"; }
void GetQuickInfo(char *ptr, int size) override
{
// ignore size
sprintf(ptr, "%sname=%s gp=%08x entry=%08x",
isFake ? "faked " : "",
nm.name,
nm.gp_value,
nm.entry_addr);
}
static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MODULE; }
static int GetStaticIDType() { return PPSSPP_KERNEL_TMID_Module; }
int GetIDType() const override { return PPSSPP_KERNEL_TMID_Module; }
void DoState(PointerWrap &p) override
{
auto s = p.Section("Module", 1, 6);
if (!s)
return;
if (s >= 5) {
Do(p, nm);
} else {
char temp[192];
NativeModule *pnm = &nm;
char *ptemp = temp;
DoArray(p, ptemp, 0xC0);
memcpy(pnm, ptemp, 0x2C);
pnm->modid = GetUID();
memcpy(((uint8_t *)pnm) + 0x30, ((uint8_t *)ptemp) + 0x2C, 0xC0 - 0x2C);
}
if (s >= 6)
Do(p, crc);
Do(p, memoryBlockAddr);
Do(p, memoryBlockSize);
Do(p, isFake);
if (s < 2) {
bool isStarted = false;
Do(p, isStarted);
if (isStarted)
nm.status = MODULE_STATUS_STARTED;
else
nm.status = MODULE_STATUS_STOPPED;
}
if (s >= 3) {
Do(p, textStart);
Do(p, textEnd);
}
if (s >= 4) {
Do(p, libstub);
Do(p, libstubend);
}
if (s >= 5) {
Do(p, modulePtr.ptr);
}
ModuleWaitingThread mwt = {0};
Do(p, waitingThreads, mwt);
FuncSymbolExport fsx = {{0}};
Do(p, exportedFuncs, fsx);
FuncSymbolImport fsi = {{0}};
Do(p, importedFuncs, fsi);
VarSymbolExport vsx = {{0}};
Do(p, exportedVars, vsx);
VarSymbolImport vsi = {{0}};
Do(p, importedVars, vsi);
if (p.mode == p.MODE_READ) {
// On load state, we re-examine in case our syscall ids changed.
if (libstub != 0) {
importedFuncs.clear();
// Imports reloaded in KernelModuleDoState.
} else {
// Older save state. Let's still reload, but this may not pick up new flags, etc.
bool foundBroken = false;
auto importedFuncsState = importedFuncs;
importedFuncs.clear();
for (auto func : importedFuncsState) {
if (func.moduleName[KERNELOBJECT_MAX_NAME_LENGTH] != '\0' || !Memory::IsValidAddress(func.stubAddr)) {
foundBroken = true;
} else {
ImportFunc(func, true);
}
}
if (foundBroken) {
ERROR_LOG(LOADER, "Broken stub import data while loading state");
}
}
char moduleName[29] = {0};
truncate_cpy(moduleName, nm.name);
if (memoryBlockAddr != 0) {
g_symbolMap->AddModule(moduleName, memoryBlockAddr, memoryBlockSize);
}
}
HLEPlugins::DoState(p);
RebuildImpExpModuleNames();
}
// We don't do this in the destructor to avoid annoying messages on game shutdown.
void Cleanup();
void ImportFunc(const FuncSymbolImport &func, bool reimporting) {
if (!Memory::IsValidAddress(func.stubAddr)) {
WARN_LOG_REPORT(LOADER, "Invalid address for syscall stub %s %08x", func.moduleName, func.nid);
return;
}
DEBUG_LOG(LOADER, "Importing %s : %08x", GetFuncName(func.moduleName, func.nid), func.stubAddr);
// Add the symbol to the symbol map for debugging.
char temp[256];
sprintf(temp,"zz_%s", GetFuncName(func.moduleName, func.nid));
g_symbolMap->AddFunction(temp,func.stubAddr,8);
// Keep track and actually hook it up if possible.
importedFuncs.push_back(func);
impExpModuleNames.insert(func.moduleName);
ImportFuncSymbol(func, reimporting, GetName());
}
void ImportVar(WriteVarSymbolState &state, const VarSymbolImport &var) {
// Keep track and actually hook it up if possible.
importedVars.push_back(var);
impExpModuleNames.insert(var.moduleName);
ImportVarSymbol(state, var);
}
void ExportFunc(const FuncSymbolExport &func) {
if (isFake) {
return;
}
exportedFuncs.push_back(func);
impExpModuleNames.insert(func.moduleName);
ExportFuncSymbol(func);
}
void ExportVar(const VarSymbolExport &var) {
if (isFake) {
return;
}
exportedVars.push_back(var);
impExpModuleNames.insert(var.moduleName);
ExportVarSymbol(var);
}
template <typename T>
void RebuildImpExpList(const std::vector<T> &list) {
for (size_t i = 0; i < list.size(); ++i) {
impExpModuleNames.insert(list[i].moduleName);
}
}
void RebuildImpExpModuleNames() {
impExpModuleNames.clear();
RebuildImpExpList(exportedFuncs);
RebuildImpExpList(importedFuncs);
RebuildImpExpList(exportedVars);
RebuildImpExpList(importedVars);
}
bool ImportsOrExportsModuleName(const std::string &moduleName) {
return impExpModuleNames.find(moduleName) != impExpModuleNames.end();
}
NativeModule nm{};
std::vector<ModuleWaitingThread> waitingThreads;
std::vector<FuncSymbolExport> exportedFuncs;
std::vector<FuncSymbolImport> importedFuncs;
std::vector<VarSymbolExport> exportedVars;
std::vector<VarSymbolImport> importedVars;
std::set<std::string> impExpModuleNames;
// Keep track of the code region so we can throw out analysis results
// when unloaded.
u32 textStart = 0;
u32 textEnd = 0;
// Keep track of the libstub pointers so we can recheck on load state.
u32 libstub = 0;
u32 libstubend = 0;
u32 memoryBlockAddr = 0;
u32 memoryBlockSize = 0;
u32 crc = 0;
PSPPointer<NativeModule> modulePtr;
bool isFake = false;
};
KernelObject *__KernelModuleObject()
{
return new PSPModule;
}
class AfterModuleEntryCall : public PSPAction {
public:
AfterModuleEntryCall() {}
SceUID moduleID_;
u32 retValAddr;
void run(MipsCall &call) override;
void DoState(PointerWrap &p) override {
auto s = p.Section("AfterModuleEntryCall", 1);
if (!s)
return;
Do(p, moduleID_);
Do(p, retValAddr);
}
static PSPAction *Create() {
return new AfterModuleEntryCall;
}
};
void AfterModuleEntryCall::run(MipsCall &call) {
Memory::Write_U32(retValAddr, currentMIPS->r[MIPS_REG_V0]);
}
//////////////////////////////////////////////////////////////////////////
// MODULES
//////////////////////////////////////////////////////////////////////////
struct StartModuleInfo
{
u32_le size;
u32_le mpidtext;
u32_le mpiddata;
u32_le threadpriority;
u32_le threadattributes;
};
struct SceKernelLMOption {
SceSize_le size;
SceUID_le mpidtext;
SceUID_le mpiddata;
u32_le flags;
char position;
char access;
char creserved[2];
};
struct SceKernelSMOption {
SceSize_le size;
SceUID_le mpidstack;
SceSize_le stacksize;
s32_le priority;
u32_le attribute;
};
//////////////////////////////////////////////////////////////////////////
// STATE BEGIN
static int actionAfterModule;
static std::set<SceUID> loadedModules;
// STATE END
//////////////////////////////////////////////////////////////////////////
static void __KernelModuleInit()
{
actionAfterModule = __KernelRegisterActionType(AfterModuleEntryCall::Create);
}
void __KernelModuleDoState(PointerWrap &p)
{
auto s = p.Section("sceKernelModule", 1, 2);
if (!s)
return;
Do(p, actionAfterModule);
__KernelRestoreActionType(actionAfterModule, AfterModuleEntryCall::Create);
if (s >= 2) {
Do(p, loadedModules);
}
if (p.mode == p.MODE_READ) {
u32 error;
// We process these late, since they depend on loadedModules for interlinking.
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (module && module->libstub != 0) {
if (!KernelImportModuleFuncs(module, nullptr, true)) {
ERROR_LOG(LOADER, "Something went wrong loading imports on load state");
}
}
}
}
if (g_Config.bFuncReplacements) {
MIPSAnalyst::ReplaceFunctions();
}
}
void __KernelModuleShutdown()
{
loadedModules.clear();
MIPSAnalyst::Reset();
HLEPlugins::Unload();
}
// Sometimes there are multiple LO16's or HI16's per pair, even though the ABI says nothing of this.
// For multiple LO16's, we need the original (unrelocated) instruction data of the HI16.
// For multiple HI16's, we just need to set each one.
struct HI16RelocInfo {
u32 addr;
u32 data;
};
// We have to post-process the HI16 part, since it might be +1 or not depending on the LO16 value.
// For that purpose, we use this state to track HI16s to adjust.
struct WriteVarSymbolState {
u32 lastHI16ExportAddress = 0;
std::vector<HI16RelocInfo> lastHI16Relocs;
bool lastHI16Processed = true;
};
static void WriteVarSymbol(WriteVarSymbolState &state, u32 exportAddress, u32 relocAddress, u8 type, bool reverse = false) {
u32 relocData = Memory::Read_Instruction(relocAddress, true).encoding;
switch (type) {
case R_MIPS_NONE:
WARN_LOG_REPORT(LOADER, "Var relocation type NONE - %08x => %08x", exportAddress, relocAddress);
break;
case R_MIPS_32:
if (!reverse) {
relocData += exportAddress;
} else {
relocData -= exportAddress;
}
break;
// Not really tested, but should work...
/*
case R_MIPS_26:
if (exportAddress % 4 || (exportAddress >> 28) != ((relocAddress + 4) >> 28)) {
WARN_LOG_REPORT(LOADER, "Bad var relocation addresses for type 26 - %08x => %08x", exportAddress, relocAddress)
} else {
if (!reverse) {
relocData = (relocData & ~0x03ffffff) | ((relocData + (exportAddress >> 2)) & 0x03ffffff);
} else {
relocData = (relocData & ~0x03ffffff) | ((relocData - (exportAddress >> 2)) & 0x03ffffff);
}
}
break;
*/
case R_MIPS_HI16:
if (state.lastHI16ExportAddress != exportAddress) {
if (!state.lastHI16Processed && !state.lastHI16Relocs.empty()) {
WARN_LOG_REPORT(LOADER, "Unsafe unpaired HI16 variable relocation @ %08x / %08x", state.lastHI16Relocs[state.lastHI16Relocs.size() - 1].addr, relocAddress);
}
state.lastHI16ExportAddress = exportAddress;
state.lastHI16Relocs.clear();
}
// After this will be an R_MIPS_LO16. If that addition overflows, we need to account for it in HI16.
// The R_MIPS_LO16 and R_MIPS_HI16 will often be *different* relocAddress values.
HI16RelocInfo reloc;
reloc.addr = relocAddress;
reloc.data = Memory::Read_Instruction(relocAddress, true).encoding;
state.lastHI16Relocs.push_back(reloc);
state.lastHI16Processed = false;
break;
case R_MIPS_LO16:
{
// Sign extend the existing low value (e.g. from addiu.)
const u32 offsetLo = SignExtend16ToU32(relocData);
u32 full = exportAddress;
// This is only used in the error case (no hi/wrong hi.)
if (!reverse) {
full = offsetLo + exportAddress;
} else {
full = offsetLo - exportAddress;
}
// The ABI requires that these come in pairs, at least.
if (state.lastHI16Relocs.empty()) {
ERROR_LOG_REPORT(LOADER, "LO16 without any HI16 variable import at %08x for %08x", relocAddress, exportAddress);
// Try to process at least the low relocation...
} else if (state.lastHI16ExportAddress != exportAddress) {
ERROR_LOG_REPORT(LOADER, "HI16 and LO16 imports do not match at %08x for %08x (should be %08x)", relocAddress, state.lastHI16ExportAddress, exportAddress);
} else {
// Process each of the HI16. Usually there's only one.
for (auto &reloc : state.lastHI16Relocs) {
if (!reverse) {
full = (reloc.data << 16) + offsetLo + exportAddress;
} else {
full = (reloc.data << 16) + offsetLo - exportAddress;
}
// The low instruction will be a signed add, which means (full & 0x8000) will subtract.
// We add 1 in that case so that it ends up the right value.
u16 high = (full >> 16) + ((full & 0x8000) ? 1 : 0);
Memory::Write_U32((reloc.data & ~0xFFFF) | high, reloc.addr);
currentMIPS->InvalidateICache(reloc.addr, 4);
}
state.lastHI16Processed = true;
}
// With full set above (hopefully), now we just need to correct the low instruction.
relocData = (relocData & ~0xFFFF) | (full & 0xFFFF);
}
break;
default:
WARN_LOG_REPORT(LOADER, "Unsupported var relocation type %d - %08x => %08x", type, exportAddress, relocAddress);
}
Memory::Write_U32(relocData, relocAddress);
currentMIPS->InvalidateICache(relocAddress, 4);
}
void ImportVarSymbol(WriteVarSymbolState &state, const VarSymbolImport &var) {
if (var.nid == 0) {
// TODO: What's the right thing for this?
ERROR_LOG_REPORT(LOADER, "Var import with nid = 0, type = %d", var.type);
return;
}
if (!Memory::IsValidAddress(var.stubAddr)) {
ERROR_LOG_REPORT(LOADER, "Invalid address for var import nid = %08x, type = %d, addr = %08x", var.nid, var.type, var.stubAddr);
return;
}
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(var.moduleName)) {
continue;
}
// Look for exports currently loaded modules already have. Maybe it's available?
for (const auto &exported : module->exportedVars) {
if (exported.Matches(var)) {
WriteVarSymbol(state, exported.symAddr, var.stubAddr, var.type);
return;
}
}
}
// It hasn't been exported yet, but hopefully it will later.
INFO_LOG(LOADER, "Variable (%s,%08x) unresolved, storing for later resolving", var.moduleName, var.nid);
}
void ExportVarSymbol(const VarSymbolExport &var) {
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(var.moduleName)) {
continue;
}
// Look for imports currently loaded modules already have, hook it up right away.
WriteVarSymbolState state;
for (auto &imported : module->importedVars) {
if (var.Matches(imported)) {
INFO_LOG(LOADER, "Resolving var %s/%08x", var.moduleName, var.nid);
WriteVarSymbol(state, var.symAddr, imported.stubAddr, imported.type);
}
}
}
}
void UnexportVarSymbol(const VarSymbolExport &var) {
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(var.moduleName)) {
continue;
}
// Look for imports modules that are *still* loaded have, and reverse them.
WriteVarSymbolState state;
for (auto &imported : module->importedVars) {
if (var.Matches(imported)) {
INFO_LOG(LOADER, "Unresolving var %s/%08x", var.moduleName, var.nid);
WriteVarSymbol(state, var.symAddr, imported.stubAddr, imported.type, true);
}
}
}
}
void ImportFuncSymbol(const FuncSymbolImport &func, bool reimporting, const char *importingModule) {
// Prioritize HLE implementations.
// TODO: Or not?
if (FuncImportIsSyscall(func.moduleName, func.nid)) {
if (reimporting && Memory::Read_Instruction(func.stubAddr + 4) != GetSyscallOp(func.moduleName, func.nid)) {
WARN_LOG(LOADER, "Reimporting updated syscall %s", GetFuncName(func.moduleName, func.nid));
}
WriteSyscall(func.moduleName, func.nid, func.stubAddr);
currentMIPS->InvalidateICache(func.stubAddr, 8);
MIPSAnalyst::PrecompileFunction(func.stubAddr, 8);
return;
}
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(func.moduleName)) {
continue;
}
// Look for exports currently loaded modules already have. Maybe it's available?
for (auto it = module->exportedFuncs.begin(), end = module->exportedFuncs.end(); it != end; ++it) {
if (it->Matches(func)) {
if (reimporting && Memory::Read_Instruction(func.stubAddr) != MIPS_MAKE_J(it->symAddr)) {
WARN_LOG_REPORT(LOADER, "Reimporting: func import %s/%08x changed", func.moduleName, func.nid);
}
WriteFuncStub(func.stubAddr, it->symAddr);
currentMIPS->InvalidateICache(func.stubAddr, 8);
MIPSAnalyst::PrecompileFunction(func.stubAddr, 8);
return;
}
}
}
// It hasn't been exported yet, but hopefully it will later.
bool isKnownModule = GetModuleIndex(func.moduleName) != -1;
if (isKnownModule) {
// We used to report this, but I don't think it's very interesting anymore.
WARN_LOG(LOADER, "Unknown syscall from known module '%s': 0x%08x (import for '%s')", func.moduleName, func.nid, importingModule);
} else {
INFO_LOG(LOADER, "Function (%s,%08x) unresolved in '%s', storing for later resolving", func.moduleName, func.nid, importingModule);
}
if (isKnownModule || !reimporting) {
WriteFuncMissingStub(func.stubAddr, func.nid);
currentMIPS->InvalidateICache(func.stubAddr, 8);
}
}
void ExportFuncSymbol(const FuncSymbolExport &func) {
if (FuncImportIsSyscall(func.moduleName, func.nid)) {
// HLE covers this already - let's ignore the function.
WARN_LOG(LOADER, "Ignoring func export %s/%08x, already implemented in HLE.", func.moduleName, func.nid);
return;
}
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(func.moduleName)) {
continue;
}
// Look for imports currently loaded modules already have, hook it up right away.
for (auto it = module->importedFuncs.begin(), end = module->importedFuncs.end(); it != end; ++it) {
if (func.Matches(*it)) {
INFO_LOG(LOADER, "Resolving function %s/%08x", func.moduleName, func.nid);
WriteFuncStub(it->stubAddr, func.symAddr);
currentMIPS->InvalidateICache(it->stubAddr, 8);
MIPSAnalyst::PrecompileFunction(it->stubAddr, 8);
}
}
}
}
void UnexportFuncSymbol(const FuncSymbolExport &func) {
if (FuncImportIsSyscall(func.moduleName, func.nid)) {
// Oops, HLE covers this.
return;
}
u32 error;
for (SceUID moduleId : loadedModules) {
PSPModule *module = kernelObjects.Get<PSPModule>(moduleId, error);
if (!module || !module->ImportsOrExportsModuleName(func.moduleName)) {
continue;
}
// Look for imports modules that are *still* loaded have, and write back stubs.
for (auto it = module->importedFuncs.begin(), end = module->importedFuncs.end(); it != end; ++it) {
if (func.Matches(*it)) {
INFO_LOG(LOADER, "Unresolving function %s/%08x", func.moduleName, func.nid);
WriteFuncMissingStub(it->stubAddr, it->nid);
currentMIPS->InvalidateICache(it->stubAddr, 8);
}
}
}
}
void PSPModule::Cleanup() {
MIPSAnalyst::ForgetFunctions(textStart, textEnd);
loadedModules.erase(GetUID());
for (auto it = exportedVars.begin(), end = exportedVars.end(); it != end; ++it) {
UnexportVarSymbol(*it);
}
for (auto it = exportedFuncs.begin(), end = exportedFuncs.end(); it != end; ++it) {
UnexportFuncSymbol(*it);
}
if (memoryBlockAddr != 0 && nm.text_addr != 0 && memoryBlockSize >= nm.data_size + nm.bss_size + nm.text_size) {
DEBUG_LOG(LOADER, "Zeroing out module %s memory: %08x - %08x", nm.name, memoryBlockAddr, memoryBlockAddr + memoryBlockSize);
u32 clearSize = Memory::ValidSize(nm.text_addr, (u32)nm.text_size + 3);
for (u32 i = 0; i < clearSize; i += 4) {
Memory::WriteUnchecked_U32(MIPS_MAKE_BREAK(1), nm.text_addr + i);
}
NotifyMemInfo(MemBlockFlags::WRITE, nm.text_addr, clearSize, "ModuleClear");
Memory::Memset(nm.text_addr + nm.text_size, -1, nm.data_size + nm.bss_size, "ModuleClear");
// Let's also invalidate, just to make sure it's cleared out for any future data.
currentMIPS->InvalidateICache(memoryBlockAddr, memoryBlockSize);
}
}
static void SaveDecryptedEbootToStorageMedia(const u8 *decryptedEbootDataPtr, const u32 length, const char *name) {
if (!decryptedEbootDataPtr) {
ERROR_LOG(SCEMODULE, "Error saving decrypted EBOOT.BIN: invalid pointer");
return;
}
if (length == 0) {
ERROR_LOG(SCEMODULE, "Error saving decrypted EBOOT.BIN: invalid length");
return;
}
const std::string filenameToDumpTo = StringFromFormat("%s_%s.BIN", g_paramSFO.GetDiscID().c_str(), name);
const Path dumpDirectory = GetSysDirectory(DIRECTORY_DUMP);
const Path fullPath = dumpDirectory / filenameToDumpTo;
// If the file already exists, don't dump it again.
if (File::Exists(fullPath)) {
INFO_LOG(SCEMODULE, "Decrypted EBOOT.BIN already exists for this game, skipping dump.");
return;
}
// Make sure the dump directory exists before continuing.
if (!File::Exists(dumpDirectory)) {
if (!File::CreateDir(dumpDirectory)) {
ERROR_LOG(SCEMODULE, "Unable to create directory for EBOOT dumping, aborting.");
return;
}
}
FILE *decryptedEbootFile = File::OpenCFile(fullPath, "wb");
if (!decryptedEbootFile) {
ERROR_LOG(SCEMODULE, "Unable to write decrypted EBOOT.");
return;
}
const size_t lengthToWrite = length;
fwrite(decryptedEbootDataPtr, sizeof(u8), lengthToWrite, decryptedEbootFile);
fclose(decryptedEbootFile);
INFO_LOG(SCEMODULE, "Successfully wrote decrypted EBOOT to %s", fullPath.c_str());
}
static bool IsHLEVersionedModule(const char *name) {
// TODO: Only some of these are currently known to be versioned.
// Potentially only sceMpeg_library matters.
// For now, we're just reporting version numbers.
for (size_t i = 0; i < ARRAY_SIZE(blacklistedModules); i++) {
if (!strncmp(name, blacklistedModules[i], 28)) {
return true;
}
}
static const char *otherModules[] = {
"sceAvcodec_driver",
"sceAudiocodec_Driver",
"sceAudiocodec",
"sceVideocodec_Driver",
"sceVideocodec",
"sceMpegbase_Driver",
"sceMpegbase",
"scePsmf_library",
"scePsmfP_library",
"scePsmfPlayer",
"sceSAScore",
"sceCcc_Library",
"SceParseHTTPheader_Library",
"SceParseURI_Library",
// Guessing.
"sceJpeg",
"sceJpeg_library",
"sceJpeg_Library",
};
for (size_t i = 0; i < ARRAY_SIZE(otherModules); i++) {
if (!strncmp(name, otherModules[i], 28)) {
return true;
}
}
return false;
}
static bool KernelImportModuleFuncs(PSPModule *module, u32 *firstImportStubAddr, bool reimporting) {
struct PspLibStubEntry {
u32_le name;
u16_le version;
u16_le flags;
u8 size;
u8 numVars;
u16_le numFuncs;
// each symbol has an associated nid; nidData is a pointer
// (in .rodata.sceNid section) to an array of longs, one
// for each function, which identifies the function whose
// address is to be inserted.
//
// The hash is the first 4 bytes of a SHA-1 hash of the function
// name. (Represented as a little-endian long, so the order
// of the bytes is reversed.)
u32_le nidData;
// the address of the function stubs where the function address jumps
// should be filled in
u32_le firstSymAddr;
// Optional, this is where var relocations are.
// They use the format: u32 addr, u32 nid, ...
// WARNING: May have garbage if size < 6.
u32_le varData;
// Not sure what this is yet, assume garbage for now.
// TODO: Tales of the World: Radiant Mythology 2 has something here?
u32_le extra;
};
// Can't run - we didn't keep track of the libstub entry.
if (module->libstub == 0) {
return false;
}
if (!Memory::IsValidRange(module->libstub, module->libstubend - module->libstub)) {
ERROR_LOG_REPORT(LOADER, "Garbage libstub address %08x or end %08x", module->libstub, module->libstubend);