-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmods.cpp
More file actions
2580 lines (2199 loc) · 105 KB
/
mods.cpp
File metadata and controls
2580 lines (2199 loc) · 105 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
#include <span>
#include <fstream>
#include <sstream>
#include <functional>
#include "librecomp/files.hpp"
#include "librecomp/mods.hpp"
#include "librecomp/overlays.hpp"
#include "librecomp/game.hpp"
#include "recompiler/context.h"
#include "recompiler/live_recompiler.h"
static bool read_json(std::ifstream input_file, nlohmann::json &json_out) {
if (!input_file.good()) {
return false;
}
try {
input_file >> json_out;
}
catch (nlohmann::json::parse_error &) {
return false;
}
return true;
}
static bool read_json_with_backups(const std::filesystem::path &path, nlohmann::json &json_out) {
// Try reading and parsing the base file.
if (read_json(std::ifstream{ path }, json_out)) {
return true;
}
// Try reading and parsing the backup file.
if (read_json(recomp::open_input_backup_file(path), json_out)) {
return true;
}
// Both reads failed.
return false;
}
template <typename T1, typename T2>
bool get_to_vec(const nlohmann::json& val, std::vector<T2>& out) {
const nlohmann::json::array_t* ptr = val.get_ptr<const nlohmann::json::array_t*>();
if (ptr == nullptr) {
return false;
}
out.clear();
for (const nlohmann::json& cur_val : *ptr) {
const T1* temp_ptr = cur_val.get_ptr<const T1*>();
if (temp_ptr == nullptr) {
out.clear();
return false;
}
out.emplace_back(*temp_ptr);
}
return true;
}
// Architecture detection.
// MSVC x86_64
#if defined (_M_AMD64) && (_M_AMD64 == 100) && !defined (_M_ARM64EC)
# define IS_X86_64
// GCC/Clang x86_64
#elif defined(__x86_64__)
# define IS_X86_64
// MSVC/GCC/Clang ARM64
#elif defined(__ARM_ARCH_ISA_A64)
# define IS_ARM64
#else
# error "Unsupported architecture!"
#endif
#if defined(_WIN32)
#define PATHFMT "%ls"
#else
#define PATHFMT "%s"
#endif
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
#if defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include "Windows.h"
class recomp::mods::DynamicLibrary {
public:
static constexpr std::string_view PlatformExtension = ".dll";
DynamicLibrary() = default;
DynamicLibrary(const std::filesystem::path& path) {
native_handle = LoadLibraryExW(std::filesystem::absolute(path).c_str(), nullptr, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
if (good()) {
uint32_t* recomp_api_version;
if (get_dll_symbol(recomp_api_version, "recomp_api_version")) {
api_version = *recomp_api_version;
}
else {
api_version = (uint32_t)-1;
}
}
}
~DynamicLibrary() {
unload();
}
DynamicLibrary(const DynamicLibrary&) = delete;
DynamicLibrary& operator=(const DynamicLibrary&) = delete;
DynamicLibrary(DynamicLibrary&&) = delete;
DynamicLibrary& operator=(DynamicLibrary&&) = delete;
void unload() {
if (native_handle != nullptr) {
FreeLibrary(native_handle);
}
native_handle = nullptr;
}
bool good() const {
return native_handle != nullptr;
}
template <typename T>
bool get_dll_symbol(T& out, const char* name) const {
out = (T)(void*)GetProcAddress(native_handle, name);
if (out == nullptr) {
return false;
}
return true;
};
uint32_t get_api_version() {
return api_version;
}
private:
HMODULE native_handle;
uint32_t api_version;
};
void unprotect(void* target_func, uint64_t* old_flags) {
DWORD old_flags_dword;
BOOL result = VirtualProtect(target_func,
16,
PAGE_READWRITE,
&old_flags_dword);
*old_flags = old_flags_dword;
(void)result;
}
void protect(void* target_func, uint64_t old_flags) {
DWORD dummy_old_flags;
BOOL result = VirtualProtect(target_func,
16,
static_cast<DWORD>(old_flags),
&dummy_old_flags);
(void)result;
}
#else
# include <unistd.h>
# include <dlfcn.h>
# include <sys/mman.h>
class recomp::mods::DynamicLibrary {
public:
#if defined(__APPLE__)
static constexpr std::string_view PlatformExtension = ".dylib";
#else
static constexpr std::string_view PlatformExtension = ".so";
#endif
DynamicLibrary() = default;
DynamicLibrary(const std::filesystem::path& path) {
native_handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (good()) {
uint32_t* recomp_api_version;
if (get_dll_symbol(recomp_api_version, "recomp_api_version")) {
api_version = *recomp_api_version;
}
else {
api_version = (uint32_t)-1;
}
}
}
~DynamicLibrary() {
unload();
}
DynamicLibrary(const DynamicLibrary&) = delete;
DynamicLibrary& operator=(const DynamicLibrary&) = delete;
DynamicLibrary(DynamicLibrary&&) = delete;
DynamicLibrary& operator=(DynamicLibrary&&) = delete;
void unload() {
if (native_handle != nullptr) {
dlclose(native_handle);
}
native_handle = nullptr;
}
bool good() const {
return native_handle != nullptr;
}
template <typename T>
bool get_dll_symbol(T& out, const char* name) const {
out = (T)dlsym(native_handle, name);
if (out == nullptr) {
return false;
}
return true;
};
uint32_t get_api_version() {
return api_version;
}
private:
void* native_handle;
uint32_t api_version;
};
void unprotect(void* target_func, uint64_t* old_flags) {
// Align the address to a page boundary.
uintptr_t page_start = (uintptr_t)target_func;
int page_size = getpagesize();
page_start = (page_start / page_size) * page_size;
int result = mprotect((void*)page_start, page_size, PROT_READ | PROT_WRITE);
*old_flags = 0;
(void)result;
}
void protect(void* target_func, uint64_t old_flags) {
// Align the address to a page boundary.
uintptr_t page_start = (uintptr_t)target_func;
int page_size = getpagesize();
page_start = (page_start / page_size) * page_size;
int result = mprotect((void*)page_start, page_size, PROT_READ | PROT_EXEC);
(void)result;
}
#endif
namespace modpaths {
constexpr std::string_view default_mod_extension = "nrm";
constexpr std::string_view binary_path = "mod_binary.bin";
constexpr std::string_view binary_syms_path = "mod_syms.bin";
};
recomp::mods::CodeModLoadError recomp::mods::validate_api_version(uint32_t api_version, std::string& error_param) {
switch (api_version) {
case 1:
return CodeModLoadError::Good;
case (uint32_t)-1:
return CodeModLoadError::NoSpecifiedApiVersion;
default:
error_param = std::to_string(api_version);
return CodeModLoadError::UnsupportedApiVersion;
}
}
recomp::mods::ModHandle::ModHandle(const ModContext& context, ModManifest&& manifest, ConfigStorage&& config_storage, std::vector<size_t>&& game_indices, std::vector<ModContentTypeId>&& content_types, std::vector<char>&& thumbnail) :
manifest(std::move(manifest)),
config_storage(std::move(config_storage)),
code_handle(),
recompiler_context{std::make_unique<N64Recomp::Context>()},
content_types{std::move(content_types)},
thumbnail{ std::move(thumbnail) },
game_indices{std::move(game_indices)}
{
runtime_toggleable = true;
for (ModContentTypeId type : this->content_types) {
if (!context.is_content_runtime_toggleable(type)) {
runtime_toggleable = false;
break;
}
}
}
recomp::mods::ModHandle::ModHandle(ModHandle&& rhs) = default;
recomp::mods::ModHandle& recomp::mods::ModHandle::operator=(ModHandle&& rhs) = default;
recomp::mods::ModHandle::~ModHandle() = default;
size_t recomp::mods::ModHandle::num_exports() const {
return recompiler_context->exported_funcs.size();
}
size_t recomp::mods::ModHandle::num_events() const {
return recompiler_context->event_symbols.size();
}
void recomp::mods::ModHandle::populate_exports() {
for (size_t func_index : recompiler_context->exported_funcs) {
const auto& func_handle = recompiler_context->functions[func_index];
exports_by_name.emplace(func_handle.name, func_index);
}
}
recomp::mods::CodeModLoadError recomp::mods::ModHandle::load_native_library(const recomp::mods::NativeLibraryManifest& lib_manifest, std::string& error_param) {
std::string lib_filename = lib_manifest.name + std::string{DynamicLibrary::PlatformExtension};
std::filesystem::path lib_path = manifest.mod_root_path.parent_path() / lib_filename;
std::unique_ptr<DynamicLibrary>& lib = native_libraries.emplace_back(std::make_unique<DynamicLibrary>(lib_path));
if (!lib->good()) {
error_param = lib_filename;
return CodeModLoadError::FailedToLoadNativeLibrary;
}
std::string api_error_param;
CodeModLoadError api_error = validate_api_version(lib->get_api_version(), api_error_param);
if (api_error != CodeModLoadError::Good) {
if (api_error_param.empty()) {
error_param = lib_filename;
}
else {
error_param = lib_filename + ":" + api_error_param;
}
return api_error;
}
native_library_exports.clear();
for (const std::string& export_name : lib_manifest.exports) {
recomp_func_t* cur_func;
if (native_library_exports.contains(export_name)) {
error_param = export_name;
return CodeModLoadError::DuplicateExport;
}
if (!lib->get_dll_symbol(cur_func, export_name.c_str())) {
error_param = lib_manifest.name + ":" + export_name;
return CodeModLoadError::FailedToFindNativeExport;
}
native_library_exports.emplace(export_name, cur_func);
}
return CodeModLoadError::Good;
}
bool recomp::mods::ModHandle::get_export_function(const std::string& export_name, GenericFunction& out) const {
// First, check the code exports.
auto code_find_it = exports_by_name.find(export_name);
if (code_find_it != exports_by_name.end()) {
out = code_handle->get_function_handle(code_find_it->second);
return true;
}
// Next, check the native library exports.
auto native_find_it = native_library_exports.find(export_name);
if (native_find_it != native_library_exports.end()) {
out = native_find_it->second;
return true;
}
// Nothing found.
return false;
}
void recomp::mods::ModHandle::populate_events() {
for (size_t event_index = 0; event_index < recompiler_context->event_symbols.size(); event_index++) {
const N64Recomp::EventSymbol& event = recompiler_context->event_symbols[event_index];
events_by_name.emplace(event.base.name, event_index);
}
}
bool recomp::mods::ModHandle::get_global_event_index(const std::string& event_name, size_t& event_index_out) const {
auto find_it = events_by_name.find(event_name);
if (find_it == events_by_name.end()) {
return false;
}
event_index_out = code_handle->get_base_event_index() + find_it->second;
return true;
}
recomp::mods::DynamicLibraryCodeHandle::DynamicLibraryCodeHandle(const std::filesystem::path& dll_path, const N64Recomp::Context& context, const ModCodeHandleInputs& inputs) {
is_good = true;
// Load the DLL.
dynamic_lib = std::make_unique<DynamicLibrary>(dll_path);
if (!dynamic_lib->good()) {
is_good = false;
return;
}
// Fill out the list of function pointers.
functions.resize(context.functions.size());
for (size_t i = 0; i < functions.size(); i++) {
if(!context.functions[i].name.empty()) {
is_good &= dynamic_lib->get_dll_symbol(functions[i], context.functions[i].name.c_str());
}
else {
std::string func_name = "mod_func_" + std::to_string(i);
is_good &= dynamic_lib->get_dll_symbol(functions[i], func_name.c_str());
}
if (!is_good) {
return;
}
}
// Get the standard exported symbols.
is_good = true;
is_good &= dynamic_lib->get_dll_symbol(imported_funcs, "imported_funcs");
is_good &= dynamic_lib->get_dll_symbol(reference_symbol_funcs, "reference_symbol_funcs");
is_good &= dynamic_lib->get_dll_symbol(base_event_index, "base_event_index");
is_good &= dynamic_lib->get_dll_symbol(recomp_trigger_event, "recomp_trigger_event");
is_good &= dynamic_lib->get_dll_symbol(get_function, "get_function");
is_good &= dynamic_lib->get_dll_symbol(cop0_status_write, "cop0_status_write");
is_good &= dynamic_lib->get_dll_symbol(cop0_status_read, "cop0_status_read");
is_good &= dynamic_lib->get_dll_symbol(switch_error, "switch_error");
is_good &= dynamic_lib->get_dll_symbol(do_break, "do_break");
is_good &= dynamic_lib->get_dll_symbol(reference_section_addresses, "reference_section_addresses");
is_good &= dynamic_lib->get_dll_symbol(section_addresses, "section_addresses");
if (is_good) {
*base_event_index = inputs.base_event_index;
*recomp_trigger_event = inputs.recomp_trigger_event;
*get_function = inputs.get_function;
*cop0_status_write = inputs.cop0_status_write;
*cop0_status_read = inputs.cop0_status_read;
*switch_error = inputs.switch_error;
*do_break = inputs.do_break;
*reference_section_addresses = inputs.reference_section_addresses;
}
}
bool recomp::mods::DynamicLibraryCodeHandle::good() {
return dynamic_lib->good() && is_good;
}
uint32_t recomp::mods::DynamicLibraryCodeHandle::get_api_version() {
return dynamic_lib->get_api_version();
}
void recomp::mods::DynamicLibraryCodeHandle::set_bad() {
dynamic_lib.reset();
is_good = false;
}
void recomp::mods::DynamicLibraryCodeHandle::set_imported_function(size_t import_index, GenericFunction func) {
std::visit(overloaded {
[this, import_index](recomp_func_t* native_func) {
imported_funcs[import_index] = native_func;
}
}, func);
}
recomp::mods::CodeModLoadError recomp::mods::DynamicLibraryCodeHandle::populate_reference_symbols(const N64Recomp::Context& context, std::string& error_param) {
size_t reference_symbol_index = 0;
for (const auto& section : context.sections) {
for (const auto& reloc : section.relocs) {
if (reloc.type == N64Recomp::RelocType::R_MIPS_26 && reloc.reference_symbol && context.is_regular_reference_section(reloc.target_section)) {
recomp_func_t* cur_func = recomp::overlays::get_func_by_section_index_function_offset(reloc.target_section, reloc.target_section_offset);
if (cur_func == nullptr) {
std::stringstream error_param_stream{};
error_param_stream << std::hex <<
"section: " << reloc.target_section <<
" func offset: 0x" << reloc.target_section_offset;
error_param = error_param_stream.str();
return CodeModLoadError::InvalidReferenceSymbol;
}
reference_symbol_funcs[reference_symbol_index] = cur_func;
reference_symbol_index++;
}
}
}
return CodeModLoadError::Good;
}
recomp::mods::LiveRecompilerCodeHandle::LiveRecompilerCodeHandle(
const N64Recomp::Context& context, const ModCodeHandleInputs& inputs,
std::unordered_map<size_t, size_t>&& entry_func_hooks, std::unordered_map<size_t, size_t>&& return_func_hooks, std::vector<size_t>&& original_section_indices, bool regenerated)
{
if (!regenerated) {
section_addresses = std::make_unique<int32_t[]>(context.sections.size());
}
base_event_index = inputs.base_event_index;
N64Recomp::LiveGeneratorInputs recompiler_inputs{
.base_event_index = inputs.base_event_index,
.cop0_status_write = inputs.cop0_status_write,
.cop0_status_read = inputs.cop0_status_read,
.switch_error = inputs.switch_error,
.do_break = inputs.do_break,
.get_function = inputs.get_function,
.syscall_handler = nullptr, // TODO hook this up
.pause_self = pause_self,
.trigger_event = inputs.recomp_trigger_event,
.reference_section_addresses = inputs.reference_section_addresses,
// Use the reference section addresses as the local section addresses if this is regenerated code so that jump tables work correctly.
.local_section_addresses = regenerated ? inputs.reference_section_addresses : section_addresses.get(),
.run_hook = run_hook,
.entry_func_hooks = std::move(entry_func_hooks),
.return_func_hooks = std::move(return_func_hooks),
.original_section_indices = std::move(original_section_indices)
};
N64Recomp::LiveGenerator generator{ context.functions.size(), recompiler_inputs };
std::vector<std::vector<uint32_t>> dummy_static_funcs{};
bool errored = false;
for (size_t func_index = 0; func_index < context.functions.size(); func_index++) {
std::ostringstream dummy_ostream{};
if (!N64Recomp::recompile_function_live(generator, context, func_index, dummy_ostream, dummy_static_funcs, true)) {
errored = true;
break;
}
}
// Generate the code.
recompiler_output = std::make_unique<N64Recomp::LiveGeneratorOutput>(generator.finish());
is_good = !errored && recompiler_output->good;
}
void recomp::mods::LiveRecompilerCodeHandle::set_imported_function(size_t import_index, GenericFunction func) {
std::visit(overloaded {
[this, import_index](recomp_func_t* native_func) {
recompiler_output->populate_import_symbol_jumps(import_index, native_func);
}
}, func);
}
recomp::mods::CodeModLoadError recomp::mods::LiveRecompilerCodeHandle::populate_reference_symbols(const N64Recomp::Context& context, std::string& error_param) {
size_t num_reference_jumps = recompiler_output->num_reference_symbol_jumps();
for (size_t jump_index = 0; jump_index < num_reference_jumps; jump_index++) {
N64Recomp::ReferenceJumpDetails jump_details = recompiler_output->get_reference_symbol_jump_details(jump_index);
recomp_func_t* cur_func = recomp::overlays::get_func_by_section_index_function_offset(jump_details.section, jump_details.section_offset);
if (cur_func == nullptr) {
std::stringstream error_param_stream{};
error_param_stream << std::hex <<
"section: " << jump_details.section <<
" func offset: 0x" << jump_details.section_offset;
error_param = error_param_stream.str();
return CodeModLoadError::InvalidReferenceSymbol;
}
recompiler_output->set_reference_symbol_jump(jump_index, cur_func);
}
return CodeModLoadError::Good;
}
recomp::mods::GenericFunction recomp::mods::LiveRecompilerCodeHandle::get_function_handle(size_t func_index) {
return GenericFunction{ recompiler_output->functions[func_index] };
}
void patch_func(recomp_func_t* target_func, recomp::mods::GenericFunction replacement_func) {
uint8_t* target_func_u8 = reinterpret_cast<uint8_t*>(target_func);
size_t offset = 0;
auto write_bytes = [&](const void* bytes, size_t count) {
memcpy(target_func_u8 + offset, bytes, count);
offset += count;
};
uint64_t old_flags;
unprotect(target_func_u8, &old_flags);
#if defined(IS_X86_64)
static const uint8_t movabs_rax[] = {0x48, 0xB8};
static const uint8_t jmp_rax[] = {0xFF, 0xE0};
std::visit(overloaded {
[&write_bytes](recomp_func_t* native_func) {
write_bytes(movabs_rax, sizeof(movabs_rax));
write_bytes(&native_func, sizeof(&native_func));
write_bytes(jmp_rax, sizeof(jmp_rax));
}
}, replacement_func);
#elif defined(IS_ARM64)
static const uint8_t ldr_x2_8__br_x2[] = {0x42, 0x00, 0x00, 0x58, 0x40, 0x00, 0x1F, 0xD6};
std::visit(overloaded {
[&write_bytes](recomp_func_t* native_func) {
write_bytes(ldr_x2_8__br_x2, sizeof(ldr_x2_8__br_x2));
write_bytes(&native_func, sizeof(&native_func));
}
}, replacement_func);
#else
# error "Unsupported architecture"
#endif
protect(target_func_u8, old_flags);
}
void unpatch_func(void* target_func, const recomp::mods::PatchData& data) {
uint64_t old_flags;
unprotect(target_func, &old_flags);
memcpy(target_func, data.replaced_bytes.data(), data.replaced_bytes.size());
protect(target_func, old_flags);
}
void recomp::mods::ModContext::add_opened_mod(ModManifest&& manifest, ConfigStorage&& config_storage, std::vector<size_t>&& game_indices, std::vector<ModContentTypeId>&& detected_content_types, std::vector<char>&& thumbnail) {
std::unique_lock lock(opened_mods_mutex);
size_t mod_index = opened_mods.size();
opened_mods_by_id.emplace(manifest.mod_id, mod_index);
opened_mods_by_filename.emplace(manifest.mod_root_path.filename().native(), mod_index);
opened_mods.emplace_back(*this, std::move(manifest), std::move(config_storage), std::move(game_indices), std::move(detected_content_types), std::move(thumbnail));
opened_mods_order.emplace_back(mod_index);
}
recomp::mods::ModLoadError recomp::mods::ModContext::load_mod(recomp::mods::ModHandle& mod, std::string& error_param) {
using namespace recomp::mods;
mod.section_load_addresses.clear();
// Check that the mod's minimum recomp version is met.
if (get_project_version() < mod.manifest.minimum_recomp_version) {
error_param = mod.manifest.minimum_recomp_version.to_string();
return ModLoadError::MinimumRecompVersionNotMet;
}
for (ModContentTypeId type_id : mod.content_types) {
content_enabled_callback* callback = content_types[type_id.value].on_enabled;
if (callback) {
callback(*this, mod);
}
}
return ModLoadError::Good;
}
void recomp::mods::ModContext::register_game(const std::string& mod_game_id) {
mod_game_ids.emplace(mod_game_id, mod_game_ids.size());
}
void recomp::mods::ModContext::register_embedded_mod(const std::string &mod_id, std::span<const uint8_t> mod_bytes) {
embedded_mod_bytes.emplace(mod_id, mod_bytes);
}
void recomp::mods::ModContext::close_mods() {
std::unique_lock lock(opened_mods_mutex);
opened_mods_by_id.clear();
opened_mods_by_filename.clear();
opened_mods.clear();
opened_mods_order.clear();
mod_order_lookup.clear();
mod_ids.clear();
enabled_mods.clear();
auto_enabled_mods.clear();
}
bool save_mod_config_storage(const std::filesystem::path &path, const std::string &mod_id, const recomp::Version &mod_version, const recomp::mods::ConfigStorage &config_storage, const recomp::mods::ConfigSchema &config_schema) {
using json = nlohmann::json;
json config_json;
config_json["mod_id"] = mod_id;
config_json["mod_version"] = mod_version.to_string();
config_json["recomp_version"] = recomp::get_project_version().to_string();
json &storage_json = config_json["storage"];
for (auto it : config_storage.value_map) {
auto id_it = config_schema.options_by_id.find(it.first);
if (id_it == config_schema.options_by_id.end()) {
continue;
}
const recomp::mods::ConfigOption &config_option = config_schema.options[id_it->second];
switch (config_option.type) {
case recomp::mods::ConfigOptionType::Enum:
storage_json[it.first] = std::get<recomp::mods::ConfigOptionEnum>(config_option.variant).options[std::get<uint32_t>(it.second)];
break;
case recomp::mods::ConfigOptionType::Number:
storage_json[it.first] = std::get<double>(it.second);
break;
case recomp::mods::ConfigOptionType::String:
storage_json[it.first] = std::get<std::string>(it.second);
break;
default:
assert(false && "Unknown config type.");
break;
}
}
std::ofstream output_file = recomp::open_output_file_with_backup(path);
if (!output_file.good()) {
return false;
}
output_file << std::setw(4) << config_json;
output_file.close();
return recomp::finalize_output_file_with_backup(path);
}
bool parse_mods_config(const std::filesystem::path &path, std::unordered_set<std::string> &enabled_mods, std::vector<std::string> &mod_order) {
using json = nlohmann::json;
json config_json;
if (!read_json_with_backups(path, config_json)) {
return false;
}
auto enabled_mods_json = config_json.find("enabled_mods");
if (enabled_mods_json != config_json.end()) {
std::vector<std::string> enabled_mods_vector;
if (get_to_vec<std::string>(*enabled_mods_json, enabled_mods_vector)) {
for (const std::string &mod_id : enabled_mods_vector) {
enabled_mods.emplace(mod_id);
}
}
}
auto mod_order_json = config_json.find("mod_order");
if (mod_order_json != config_json.end()) {
get_to_vec<std::string>(*mod_order_json, mod_order);
}
return true;
}
bool save_mods_config(const std::filesystem::path &path, const std::unordered_set<std::string> &enabled_mods, const std::vector<std::string> &mod_order) {
nlohmann::json config_json;
config_json["enabled_mods"] = enabled_mods;
config_json["mod_order"] = mod_order;
std::ofstream output_file = recomp::open_output_file_with_backup(path);
if (!output_file.good()) {
return false;
}
output_file << std::setw(4) << config_json;
output_file.close();
return recomp::finalize_output_file_with_backup(path);
}
void recomp::mods::ModContext::dirty_mod_configuration_thread_process() {
using namespace std::chrono_literals;
ModConfigQueueVariant variant;
ModConfigQueueSaveMod save_mod;
std::unordered_set<std::string> pending_mods;
std::unordered_map<std::string, ConfigStorage> pending_mod_storage;
std::unordered_map<std::string, ConfigSchema> pending_mod_schema;
std::unordered_map<std::string, Version> pending_mod_version;
std::unordered_set<std::string> config_enabled_mods;
std::vector<std::string> config_mod_order;
bool pending_config_save = false;
std::filesystem::path config_path;
bool active = true;
auto handle_variant = [&](const ModConfigQueueVariant &variant) {
if (std::get_if<ModConfigQueueEnd>(&variant) != nullptr) {
active = false;
}
else if (std::get_if<ModConfigQueueSave>(&variant) != nullptr) {
pending_config_save = true;
}
else if (const ModConfigQueueSaveMod* queue_save_mod = std::get_if<ModConfigQueueSaveMod>(&variant)) {
pending_mods.emplace(queue_save_mod->mod_id);
}
};
while (active) {
// Wait for at least one mod to require writing.
mod_configuration_thread_queue.wait_dequeue(variant);
handle_variant(variant);
// Clear out the entire queue to coalesce all writes with a timeout.
while (active && mod_configuration_thread_queue.wait_dequeue_timed(variant, 1s)) {
handle_variant(variant);
}
if (active && !pending_mods.empty()) {
{
std::unique_lock opened_mods_lock(opened_mods_mutex);
for (const std::string &id : pending_mods) {
auto it = opened_mods_by_id.find(id);
if (it != opened_mods_by_id.end()) {
const ModHandle &mod = opened_mods[it->second];
std::unique_lock config_storage_lock(mod_config_storage_mutex);
pending_mod_storage[id] = mod.config_storage;
pending_mod_schema[id] = mod.manifest.config_schema;
pending_mod_version[id] = mod.manifest.version;
}
}
}
for (const std::string &id : pending_mods) {
config_path = mod_config_directory / std::string(id + ".json");
save_mod_config_storage(config_path, id, pending_mod_version[id], pending_mod_storage[id], pending_mod_schema[id]);
}
pending_mods.clear();
}
if (active && pending_config_save) {
{
// Store the enabled mods and the order.
std::unique_lock lock(opened_mods_mutex);
config_enabled_mods = enabled_mods;
config_mod_order.clear();
for (size_t mod_index : opened_mods_order) {
config_mod_order.emplace_back(opened_mods[mod_index].manifest.mod_id);
}
}
save_mods_config(mods_config_path, config_enabled_mods, config_mod_order);
pending_config_save = false;
}
}
}
std::vector<recomp::mods::ModOpenErrorDetails> recomp::mods::ModContext::scan_mod_folder(const std::filesystem::path& mod_folder) {
std::vector<recomp::mods::ModOpenErrorDetails> ret{};
std::error_code ec;
close_mods();
static const std::vector<ModContentTypeId> empty_content_types{};
for (const auto& mod_path : std::filesystem::directory_iterator{mod_folder, std::filesystem::directory_options::skip_permission_denied, ec}) {
bool is_mod = false;
bool requires_manifest = true;
std::reference_wrapper<const std::vector<ModContentTypeId>> supported_content_types = std::cref(empty_content_types);
if (mod_path.is_regular_file()) {
auto find_container_it = container_types.find(mod_path.path().extension().string());
if (find_container_it != container_types.end()) {
is_mod = true;
supported_content_types = find_container_it->second.supported_content_types;
requires_manifest = find_container_it->second.requires_manifest;
}
}
else if (mod_path.is_directory()) {
is_mod = true;
}
if (is_mod) {
printf("Opening mod " PATHFMT "\n", mod_path.path().stem().c_str());
std::string open_error_param;
ModOpenError open_error = open_mod_from_path(mod_path, open_error_param, supported_content_types, requires_manifest);
if (open_error != ModOpenError::Good) {
ret.emplace_back(mod_path.path(), open_error, open_error_param);
}
}
else {
printf("Skipping non-mod " PATHFMT PATHFMT "\n", mod_path.path().stem().c_str(), mod_path.path().extension().c_str());
}
}
for (const auto &mod_bytes : embedded_mod_bytes) {
if (opened_mods_by_id.contains(mod_bytes.first)) {
continue;
}
std::string open_error_param;
ModOpenError open_error = open_mod_from_memory(mod_bytes.second, open_error_param, empty_content_types, true);
if (open_error != ModOpenError::Good) {
ret.emplace_back(mod_bytes.first, open_error, open_error_param);
}
}
return ret;
}
void recomp::mods::ModContext::load_mods_config() {
std::unordered_set<std::string> config_enabled_mods;
std::vector<std::string> config_mod_order;
std::vector<bool> opened_mod_is_known;
parse_mods_config(mods_config_path, config_enabled_mods, config_mod_order);
// Fill a vector with the relative order of the mods. Existing mods will get ordered below new mods.
std::vector<size_t> sort_order;
sort_order.resize(opened_mods.size());
opened_mod_is_known.resize(opened_mods.size(), false);
std::iota(sort_order.begin(), sort_order.end(), 0);
for (size_t i = 0; i < config_mod_order.size(); i++) {
auto it = opened_mods_by_id.find(config_mod_order[i]);
if (it != opened_mods_by_id.end()) {
sort_order[it->second] = opened_mods.size() + i;
opened_mod_is_known[it->second] = true;
}
}
// Run the sort using the relative order computed before.
std::iota(opened_mods_order.begin(), opened_mods_order.end(), 0);
std::sort(opened_mods_order.begin(), opened_mods_order.end(), [&](size_t i, size_t j) {
return sort_order[i] < sort_order[j];
});
rebuild_mod_order_lookup();
// Enable mods that are specified in the configuration or mods that are considered new.
for (size_t i = 0; i < opened_mods.size(); i++) {
const ModHandle& mod = opened_mods[i];
const std::string &mod_id = mod.manifest.mod_id;
bool is_default_enabled = !opened_mod_is_known[i] && mod.manifest.enabled_by_default;
bool is_manually_enabled = config_enabled_mods.contains(mod_id);
if (is_default_enabled || is_manually_enabled) {
enable_mod(mod_id, true, false);
}
}
}
void recomp::mods::ModContext::rebuild_mod_order_lookup() {
// Initialize the mod order lookup to all -1 so that mods that aren't enabled have an order index of -1.
mod_order_lookup.resize(opened_mods.size());
std::fill(mod_order_lookup.begin(), mod_order_lookup.end(), static_cast<size_t>(-1));
// Build the lookup of mod index to mod order by inverting the opened mods order list.
for (size_t mod_order_index = 0; mod_order_index < opened_mods_order.size(); mod_order_index++) {
size_t mod_index = opened_mods_order[mod_order_index];
mod_order_lookup[mod_index] = mod_order_index;
}
}
recomp::mods::ModContext::ModContext() {
// Register the code content type.
ModContentType code_content_type {
.content_filename = std::string{modpaths::binary_syms_path},
.allow_runtime_toggle = false,
.on_enabled = ModContext::on_code_mod_enabled,
.on_disabled = nullptr,
.on_reordered = nullptr
};
code_content_type_id = register_content_type(code_content_type);
// Register the default mod container type (.nrm) and allow it to have any content type by passing an empty vector.
register_container_type(std::string{ modpaths::default_mod_extension }, {}, true);
mod_configuration_thread = std::make_unique<std::thread>(&ModContext::dirty_mod_configuration_thread_process, this);
}
void recomp::mods::ModContext::on_code_mod_enabled(ModContext& context, const ModHandle& mod) {
auto find_mod_it = context.loaded_mods_by_id.find(mod.manifest.mod_id);
if (find_mod_it == context.loaded_mods_by_id.end()) {
assert(false && "Failed to find enabled code mod");
}
else {
context.loaded_code_mods.emplace_back(find_mod_it->second);
}
}
recomp::mods::ModContext::~ModContext() {
mod_configuration_thread_queue.enqueue(ModConfigQueueEnd());
mod_configuration_thread->join();
mod_configuration_thread.reset();
}
recomp::mods::ModContentTypeId recomp::mods::ModContext::register_content_type(const ModContentType& type) {
size_t ret = content_types.size();
content_types.emplace_back(type);
return ModContentTypeId{.value = ret};
}
bool recomp::mods::ModContext::register_container_type(const std::string& extension, const std::vector<ModContentTypeId>& container_content_types, bool requires_manifest) {
// Validate the provided content type IDs.
for (ModContentTypeId id : container_content_types) {
if (id.value >= content_types.size()) {
return false;
}
}
// Validate that the extension doesn't contain a dot.
if (extension.find('.') != std::string::npos) {
return false;
}
// Prepend a dot to the extension to get the real extension that will be registered..
std::string true_extension = "." + extension;
// Validate that this extension hasn't been registered already.
if (container_types.contains(true_extension)) {
return false;
}
// Register the container type.
container_types.emplace(true_extension,
ModContainerType {
.supported_content_types = container_content_types,
.requires_manifest = requires_manifest
});
return true;
}
std::string recomp::mods::ModContext::get_mod_display_name(size_t mod_index) const {
return opened_mods[mod_index].manifest.display_name;
}
std::filesystem::path recomp::mods::ModContext::get_mod_path(size_t mod_index) const {
return opened_mods[mod_index].manifest.mod_root_path;
}
std::pair<std::string, std::string> recomp::mods::ModContext::get_mod_import_info(size_t mod_index, size_t import_index) const {
const ModHandle& mod = opened_mods[mod_index];
const N64Recomp::ImportSymbol& imported_func = mod.recompiler_context->import_symbols[import_index];
const std::string& dependency_id = mod.recompiler_context->dependencies[imported_func.dependency_index];
return std::make_pair<std::string, std::string>(std::string{ dependency_id }, std::string{ imported_func.base.name });
}
recomp::mods::DependencyStatus recomp::mods::ModContext::is_dependency_met(size_t mod_index, const std::string& dependency_id) const {
const ModHandle& mod = opened_mods[mod_index];
auto find_dep = mod.manifest.dependencies_by_id.find(dependency_id);
if (find_dep == mod.manifest.dependencies_by_id.end()) {