1#![doc(html_logo_url = "https://github.com/SemyonTs/ghook/raw/main/logo.png")]
54#![doc(html_favicon_url = "https://github.com/SemyonTs/ghook/raw/main/favicon.ico")]
55
56use std::collections::HashMap;
57use std::ffi::c_void;
58use std::sync::{OnceLock, RwLock};
59use std::panic::{catch_unwind, AssertUnwindSafe};
60use std::path::Path;
61
62pub use ghook_macros::{hookable, mod_info, prefix, postfix, replace, mod_init};
64pub use ghook_macros::use_game_hooks;
65
66#[macro_export]
89macro_rules! declare_args {
90 ($($name:ident { $($field:ident: $ty:ty),* $(,)? }),* $(,)?) => {
91 $(
92 #[repr(C)]
93 pub struct $name {
94 $(pub $field: $ty,)*
95 }
96 )*
97 };
98}
99
100#[repr(u8)]
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum HookControl {
110 Continue = 0,
112 SkipOriginal = 1,
114 Abort = 2,
116}
117
118#[repr(C)]
122pub struct HookContext {
123 pub mod_id: *const u8,
125 pub mod_id_len: usize,
127}
128
129#[repr(C)]
139pub struct ModInfo {
140 pub magic: [u8; 8],
142 pub api_version: u32,
144 pub id_ptr: *const u8,
146 pub id_len: usize,
148 pub version_ptr: *const u8,
150 pub version_len: usize,
152 pub requires_ptr: *const u8,
154 pub requires_len: usize,
156 pub load_after_ptr: *const u8,
158 pub load_after_len: usize,
160 pub load_before_ptr: *const u8,
162 pub load_before_len: usize,
164 pub incompatible_with_ptr: *const u8,
166 pub incompatible_with_len: usize,
168}
169
170unsafe impl Sync for ModInfo {}
174unsafe impl Send for ModInfo {}
175
176impl ModInfo {
177 fn read_str(ptr: *const u8, len: usize) -> String {
179 if ptr.is_null() || len == 0 {
180 return String::new();
181 }
182 unsafe {
186 let slice = std::slice::from_raw_parts(ptr, len);
187 std::str::from_utf8_unchecked(slice).to_string()
188 }
189 }
190
191 pub fn id(&self) -> String {
193 Self::read_str(self.id_ptr, self.id_len)
194 }
195
196 pub fn version(&self) -> String {
198 Self::read_str(self.version_ptr, self.version_len)
199 }
200
201 pub fn requires(&self) -> Vec<String> {
203 Self::read_str(self.requires_ptr, self.requires_len)
204 .split(',')
205 .map(|s| s.trim().to_string())
206 .filter(|s| !s.is_empty())
207 .collect()
208 }
209
210 pub fn load_after(&self) -> Vec<String> {
212 Self::read_str(self.load_after_ptr, self.load_after_len)
213 .split(',')
214 .map(|s| s.trim().to_string())
215 .filter(|s| !s.is_empty())
216 .collect()
217 }
218
219 pub fn load_before(&self) -> Vec<String> {
221 Self::read_str(self.load_before_ptr, self.load_before_len)
222 .split(',')
223 .map(|s| s.trim().to_string())
224 .filter(|s| !s.is_empty())
225 .collect()
226 }
227
228 pub fn incompatible_with(&self) -> Vec<String> {
230 Self::read_str(self.incompatible_with_ptr, self.incompatible_with_len)
231 .split(',')
232 .map(|s| s.trim().to_string())
233 .filter(|s| !s.is_empty())
234 .collect()
235 }
236}
237
238#[derive(Debug, Clone)]
242pub struct ModManifest {
243 pub id: String,
245 pub version: String,
247 pub requires: Vec<String>,
249 pub load_after: Vec<String>,
251 pub load_before: Vec<String>,
253 pub incompatible_with: Vec<String>,
255 pub path: String,
257}
258
259impl From<&ModInfo> for ModManifest {
260 fn from(info: &ModInfo) -> Self {
261 Self {
262 id: info.id(),
263 version: info.version(),
264 requires: info.requires(),
265 load_after: info.load_after(),
266 load_before: info.load_before(),
267 incompatible_with: info.incompatible_with(),
268 path: String::new(),
269 }
270 }
271}
272
273#[repr(C)]
288pub struct HostApi {
289 pub api_version: u32,
291 pub register_hook: extern "C" fn(
293 target_hash: u64,
294 kind: u8,
295 priority: i32,
296 callback: *const c_void,
297 ) -> u64,
298 pub log: extern "C" fn(level: u8, msg_ptr: *const u8, msg_len: usize),
300 pub get_extension: extern "C" fn(name_ptr: *const u8, name_len: usize) -> *const c_void,
302}
303
304impl HostApi {
305 #[inline]
306 fn log_raw(&self, level: u8, msg: &str) {
307 (self.log)(level, msg.as_ptr(), msg.len());
308 }
309
310 pub fn log_info(&self, msg: &str) {
312 self.log_raw(0, msg);
313 }
314
315 pub fn log_warn(&self, msg: &str) {
317 self.log_raw(1, msg);
318 }
319
320 pub fn log_error(&self, msg: &str) {
322 self.log_raw(2, msg);
323 }
324
325 pub fn log_debug(&self, msg: &str) {
327 self.log_raw(3, msg);
328 }
329
330 pub fn get_extension_typed<T>(&self, name: &str) -> Option<&'static T> {
351 let ptr = (self.get_extension)(name.as_ptr(), name.len());
352 if ptr.is_null() {
353 None
354 } else {
355 Some(unsafe { &*(ptr as *const T) })
357 }
358 }
359}
360
361pub struct ExtensionRegistry {
370 extensions: HashMap<String, *const c_void>,
371}
372
373impl ExtensionRegistry {
374 pub fn new() -> Self {
376 Self {
377 extensions: HashMap::new(),
378 }
379 }
380
381 pub fn register<T: 'static>(&mut self, name: &str, api: &'static T) {
394 self.extensions
395 .insert(name.to_string(), api as *const T as *const c_void);
396 log::info!("Registered extension: '{}'", name);
397 }
398
399 pub fn get(&self, name: &str) -> *const c_void {
403 self.extensions
404 .get(name)
405 .copied()
406 .unwrap_or(std::ptr::null())
407 }
408}
409
410unsafe impl Send for ExtensionRegistry {}
413unsafe impl Sync for ExtensionRegistry {}
414
415#[derive(Debug, Clone)]
421pub enum DependencyError {
422 MissingMod(String, String),
424 CycleDetected(Vec<String>),
426 IncompatibleMods(String, String),
428}
429
430impl std::fmt::Display for DependencyError {
431 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432 match self {
433 Self::MissingMod(mod_id, dep) => {
434 write!(f, "Mod '{}' requires '{}' which is not loaded", mod_id, dep)
435 }
436 Self::CycleDetected(cycle) => {
437 write!(f, "Circular dependency detected: {}", cycle.join(" -> "))
438 }
439 Self::IncompatibleMods(a, b) => {
440 write!(f, "Mods '{}' and '{}' are incompatible", a, b)
441 }
442 }
443 }
444}
445
446impl std::error::Error for DependencyError {}
447
448pub struct DependencyResolver;
452
453impl DependencyResolver {
454 pub fn resolve_load_order(manifests: &[ModManifest]) -> Result<Vec<String>, DependencyError> {
471 for manifest in manifests {
473 for conflict in &manifest.incompatible_with {
474 if manifests.iter().any(|m| &m.id == conflict) {
475 return Err(DependencyError::IncompatibleMods(
476 manifest.id.clone(),
477 conflict.clone(),
478 ));
479 }
480 }
481 }
482
483 let ids: Vec<&str> = manifests.iter().map(|m| m.id.as_str()).collect();
485 for manifest in manifests {
486 for dep in &manifest.requires {
487 if !ids.contains(&dep.as_str()) {
488 return Err(DependencyError::MissingMod(
489 manifest.id.clone(),
490 dep.clone(),
491 ));
492 }
493 }
494 }
495
496 let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
498 for manifest in manifests {
499 let entry = graph.entry(manifest.id.as_str()).or_default();
500
501 for dep in &manifest.requires {
502 entry.push(dep.as_str());
503 }
504 for after in &manifest.load_after {
505 entry.push(after.as_str());
506 }
507 for before in &manifest.load_before {
508 if let Some(other_deps) = graph.get_mut(before.as_str()) {
509 other_deps.push(manifest.id.as_str());
510 } else {
511 graph.insert(before.as_str(), vec![manifest.id.as_str()]);
512 }
513 }
514 }
515
516 let mut in_degree: HashMap<&str, usize> = HashMap::new();
518 for manifest in manifests {
519 in_degree.insert(manifest.id.as_str(), 0);
520 }
521
522 for deps in graph.values() {
523 for dep in deps {
524 *in_degree.entry(dep).or_insert(0) += 1;
525 }
526 }
527
528 let mut queue: Vec<&str> = in_degree
529 .iter()
530 .filter(|(_, °)| deg == 0)
531 .map(|(&id, _)| id)
532 .collect();
533 queue.sort(); let mut order = Vec::new();
536
537 while let Some(id) = queue.pop() {
538 order.push(id.to_string());
539
540 if let Some(deps) = graph.get(id) {
541 for dep in deps {
542 if let Some(deg) = in_degree.get_mut(dep) {
543 *deg -= 1;
544 if *deg == 0 {
545 queue.push(dep);
546 }
547 }
548 }
549 }
550 }
551
552 if order.len() != manifests.len() {
554 let cycle: Vec<String> = in_degree
555 .iter()
556 .filter(|(_, °)| deg > 0)
557 .map(|(&id, _)| id.to_string())
558 .collect();
559 return Err(DependencyError::CycleDetected(cycle));
560 }
561
562 Ok(order)
563 }
564}
565
566#[inline]
582pub const fn hash_string_const(s: &str) -> u64 {
583 let bytes = s.as_bytes();
584 let mut hash: u64 = 0xcbf29ce484222325; let mut i = 0;
586 while i < bytes.len() {
587 hash ^= bytes[i] as u64;
588 hash = hash.wrapping_mul(0x100000001b3); i += 1;
590 }
591 hash
592}
593
594#[inline]
598pub fn hash_string(s: &str) -> u64 {
599 hash_string_const(s)
600}
601
602static SEGFAULT_HANDLER_INSTALLED: OnceLock<()> = OnceLock::new();
607
608extern "C" fn segfault_handler(
609 _sig: libc::c_int,
610 _info: *mut libc::siginfo_t,
611 _ctx: *mut libc::c_void,
612) {
613 let msg = b"\n[SEGFAULT] A mod accessed invalid memory. Aborting.\n";
615 unsafe {
616 libc::write(libc::STDERR_FILENO, msg.as_ptr() as *const _, msg.len());
617 }
618 std::process::abort();
619}
620
621pub fn install_segfault_handler() {
626 SEGFAULT_HANDLER_INSTALLED.get_or_init(|| {
627 unsafe {
630 let mut sa: libc::sigaction = std::mem::zeroed();
631 sa.sa_sigaction = segfault_handler as *const () as usize;
632 sa.sa_flags = libc::SA_SIGINFO;
633 libc::sigemptyset(&mut sa.sa_mask);
634 libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
635 libc::sigaction(libc::SIGBUS, &sa, std::ptr::null_mut());
636 log::info!("Segfault handler installed");
637 }
638 });
639}
640
641type HookCallback =
646 extern "C" fn(ctx: *mut HookContext, args: *mut c_void, result: *mut c_void) -> u8;
647
648struct HookRegistration {
649 mod_id: String,
650 kind: u8, priority: i32,
652 callback: HookCallback,
653}
654
655static HOOK_MANAGER: OnceLock<RwLock<HookManager>> = OnceLock::new();
656
657pub struct HookManager {
662 hooks: HashMap<u64, Vec<HookRegistration>>,
663}
664
665impl HookManager {
666 pub fn new() -> Self {
668 Self {
669 hooks: HashMap::new(),
670 }
671 }
672
673 pub fn register_hook(
675 &mut self,
676 target_hash: u64,
677 kind: u8,
678 priority: i32,
679 callback: HookCallback,
680 mod_id: &str,
681 ) -> u64 {
682 let reg = HookRegistration {
683 mod_id: mod_id.to_string(),
684 kind,
685 priority,
686 callback,
687 };
688 self.hooks.entry(target_hash).or_default().push(reg);
689 self.hooks
690 .get_mut(&target_hash)
691 .unwrap()
692 .sort_by_key(|h| h.priority);
693 1
694 }
695
696 pub fn unregister_mod(&mut self, mod_id: &str) {
698 for hooks in self.hooks.values_mut() {
699 hooks.retain(|h| h.mod_id != mod_id);
700 }
701 log::info!("Unregistered all hooks for mod '{}'", mod_id);
702 }
703
704 #[inline]
706 pub fn execute_prefix<A, R>(
707 &self,
708 target_hash: u64,
709 args: &mut A,
710 result: &mut R,
711 ) -> HookControl {
712 let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
713 let mut to_remove = Vec::new();
714 for (idx, hook) in hooks.iter().enumerate() {
715 if hook.kind != 0 {
716 continue;
717 }
718 let ctx = HookContext {
719 mod_id: hook.mod_id.as_ptr(),
720 mod_id_len: hook.mod_id.len(),
721 };
722
723 match catch_unwind(AssertUnwindSafe(|| {
724 (hook.callback)(
725 &ctx as *const _ as *mut _,
726 args as *mut A as *mut _,
727 result as *mut R as *mut _,
728 )
729 })) {
730 Ok(1) => return HookControl::SkipOriginal,
731 Ok(2) => return HookControl::Abort,
732 Err(_) => {
733 log::error!(
734 "Mod '{}' panicked in prefix! Disabling.",
735 hook.mod_id
736 );
737 to_remove.push(idx);
738 }
739 _ => {}
740 }
741 }
742 to_remove
743 } else {
744 Vec::new()
745 };
746
747 if !to_remove.is_empty() {
748 let mut manager = get_hook_manager().write().unwrap();
749 if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
750 for idx in to_remove.into_iter().rev() {
751 hooks.remove(idx);
752 }
753 }
754 }
755
756 HookControl::Continue
757 }
758
759 #[inline]
761 pub fn execute_postfix<A, R>(
762 &self,
763 target_hash: u64,
764 args: &A,
765 result: &mut R,
766 ) -> HookControl {
767 let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
768 let mut to_remove = Vec::new();
769 for (idx, hook) in hooks.iter().enumerate() {
770 if hook.kind != 1 {
771 continue;
772 }
773 let ctx = HookContext {
774 mod_id: hook.mod_id.as_ptr(),
775 mod_id_len: hook.mod_id.len(),
776 };
777
778 match catch_unwind(AssertUnwindSafe(|| {
779 (hook.callback)(
780 &ctx as *const _ as *mut _,
781 args as *const A as *mut _,
782 result as *mut R as *mut _,
783 )
784 })) {
785 Ok(2) => return HookControl::Abort,
786 Err(_) => {
787 log::error!(
788 "Mod '{}' panicked in postfix! Disabling.",
789 hook.mod_id
790 );
791 to_remove.push(idx);
792 }
793 _ => {}
794 }
795 }
796 to_remove
797 } else {
798 Vec::new()
799 };
800
801 if !to_remove.is_empty() {
802 let mut manager = get_hook_manager().write().unwrap();
803 if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
804 for idx in to_remove.into_iter().rev() {
805 hooks.remove(idx);
806 }
807 }
808 }
809
810 HookControl::Continue
811 }
812
813 #[inline]
817 pub fn execute_replace<A, R>(&self, target_hash: u64, args: &mut A, result: &mut R) -> bool {
818 let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
819 let mut to_remove = Vec::new();
820 for (idx, hook) in hooks.iter().enumerate() {
821 if hook.kind != 2 {
822 continue;
823 }
824 let ctx = HookContext {
825 mod_id: hook.mod_id.as_ptr(),
826 mod_id_len: hook.mod_id.len(),
827 };
828
829 match catch_unwind(AssertUnwindSafe(|| {
830 (hook.callback)(
831 &ctx as *const _ as *mut _,
832 args as *mut A as *mut _,
833 result as *mut R as *mut _,
834 )
835 })) {
836 Ok(_) => return true,
837 Err(_) => {
838 log::error!(
839 "Mod '{}' panicked in replace! Disabling.",
840 hook.mod_id
841 );
842 to_remove.push(idx);
843 }
844 }
845 }
846 to_remove
847 } else {
848 Vec::new()
849 };
850
851 if !to_remove.is_empty() {
852 let mut manager = get_hook_manager().write().unwrap();
853 if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
854 for idx in to_remove.into_iter().rev() {
855 hooks.remove(idx);
856 }
857 }
858 }
859
860 false
861 }
862}
863
864pub fn get_hook_manager() -> &'static RwLock<HookManager> {
868 HOOK_MANAGER.get_or_init(|| RwLock::new(HookManager::new()))
869}
870
871extern "C" fn host_register_hook(
876 target_hash: u64,
877 kind: u8,
878 priority: i32,
879 callback: *const c_void,
880) -> u64 {
881 if callback.is_null() {
882 return 0;
883 }
884 let callback_fn: HookCallback = unsafe { std::mem::transmute(callback) };
887 get_hook_manager()
888 .write()
889 .unwrap()
890 .register_hook(target_hash, kind, priority, callback_fn, "dynamic_mod")
891}
892
893extern "C" fn host_log(level: u8, msg_ptr: *const u8, msg_len: usize) {
894 if msg_ptr.is_null() {
895 return;
896 }
897 let msg = unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(msg_ptr, msg_len)) };
900 match level {
901 0 => log::info!("[MOD] {}", msg),
902 1 => log::warn!("[MOD] {}", msg),
903 2 => log::error!("[MOD] {}", msg),
904 _ => log::debug!("[MOD] {}", msg),
905 }
906}
907
908static EXTENSION_REGISTRY: OnceLock<RwLock<ExtensionRegistry>> = OnceLock::new();
909
910extern "C" fn host_get_extension(name_ptr: *const u8, name_len: usize) -> *const c_void {
911 if name_ptr.is_null() {
912 return std::ptr::null();
913 }
914 let name = unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(name_ptr, name_len)) };
916
917 let registry = EXTENSION_REGISTRY.get_or_init(|| RwLock::new(ExtensionRegistry::new()));
918 registry.read().unwrap().get(name)
919}
920
921pub fn create_host_api() -> HostApi {
933 install_segfault_handler();
934
935 HostApi {
936 api_version: 1,
937 register_hook: host_register_hook,
938 log: host_log,
939 get_extension: host_get_extension,
940 }
941}
942
943pub fn register_extension<T: 'static>(name: &str, api: &'static T) {
955 let registry = EXTENSION_REGISTRY.get_or_init(|| RwLock::new(ExtensionRegistry::new()));
956 registry.write().unwrap().register(name, api);
957}
958
959#[derive(Debug, Clone)]
965pub struct HookInfo {
966 pub name: String,
968 pub hash: u64,
970 pub args: Vec<(String, String)>,
972 pub result_type: String,
974}
975
976pub fn read_hooks_info(binary_path: &str) -> Result<Vec<HookInfo>, String> {
995 let data =
996 std::fs::read(binary_path).map_err(|e| format!("Failed to read '{}': {}", binary_path, e))?;
997
998 let sections = read_elf_sections_runtime(&data, ".hooks_info.");
999
1000 let mut hooks = Vec::new();
1001
1002 for (name, section_data) in sections {
1003 let info_str = String::from_utf8_lossy(§ion_data);
1004 let parts: Vec<&str> = info_str.split('|').collect();
1005
1006 if parts.len() != 2 {
1007 continue;
1008 }
1009
1010 let args: Vec<(String, String)> = if parts[0].is_empty() {
1011 Vec::new()
1012 } else {
1013 parts[0]
1014 .split(',')
1015 .filter_map(|arg| {
1016 let p: Vec<&str> = arg.splitn(2, ':').collect();
1017 if p.len() == 2 {
1018 Some((p[0].trim().to_string(), p[1].trim().to_string()))
1019 } else {
1020 None
1021 }
1022 })
1023 .collect()
1024 };
1025
1026 let hash = hash_string(&name);
1027
1028 hooks.push(HookInfo {
1029 name,
1030 hash,
1031 args,
1032 result_type: parts[1].trim().to_string(),
1033 });
1034 }
1035
1036 Ok(hooks)
1037}
1038
1039pub fn validate_game_binary(binary_path: &str) -> Result<Vec<String>, String> {
1045 let hooks = read_hooks_info(binary_path)?;
1046
1047 if hooks.is_empty() {
1048 return Err("No hooks found in game binary".to_string());
1049 }
1050
1051 Ok(hooks.iter().map(|h| h.name.clone()).collect())
1052}
1053
1054fn read_elf_sections_runtime(data: &[u8], prefix: &str) -> Vec<(String, Vec<u8>)> {
1056 let mut results = Vec::new();
1057
1058 if data.len() < 64 || &data[0..4] != b"\x7fELF" {
1059 return results;
1060 }
1061
1062 if data[4] != 2 {
1064 return results;
1065 }
1066
1067 let e_shoff = u64::from_le_bytes(data[40..48].try_into().unwrap_or([0; 8])) as usize;
1068 let e_shentsize = u16::from_le_bytes(data[58..60].try_into().unwrap_or([0; 2])) as usize;
1069 let e_shnum = u16::from_le_bytes(data[60..62].try_into().unwrap_or([0; 2])) as usize;
1070 let e_shstrndx = u16::from_le_bytes(data[62..64].try_into().unwrap_or([0; 2])) as usize;
1071
1072 if e_shoff == 0 || e_shnum == 0 {
1073 return results;
1074 }
1075
1076 let shstr_offset = e_shoff + e_shstrndx * e_shentsize;
1077 if shstr_offset + e_shentsize > data.len() {
1078 return results;
1079 }
1080
1081 let shstr_sh_offset = u64::from_le_bytes(
1082 data[shstr_offset + 24..shstr_offset + 32]
1083 .try_into()
1084 .unwrap_or([0; 8]),
1085 ) as usize;
1086 let shstr_sh_size = u64::from_le_bytes(
1087 data[shstr_offset + 32..shstr_offset + 40]
1088 .try_into()
1089 .unwrap_or([0; 8]),
1090 ) as usize;
1091
1092 if shstr_sh_offset + shstr_sh_size > data.len() {
1093 return results;
1094 }
1095 let shstrtab = &data[shstr_sh_offset..shstr_sh_offset + shstr_sh_size];
1096
1097 for i in 0..e_shnum {
1098 let sh_offset = e_shoff + i * e_shentsize;
1099 if sh_offset + e_shentsize > data.len() {
1100 break;
1101 }
1102
1103 let sh_name_idx = u32::from_le_bytes(
1104 data[sh_offset..sh_offset + 4]
1105 .try_into()
1106 .unwrap_or([0; 4]),
1107 ) as usize;
1108
1109 if sh_name_idx >= shstrtab.len() {
1110 continue;
1111 }
1112
1113 let name_end = shstrtab[sh_name_idx..]
1114 .iter()
1115 .position(|&b| b == 0)
1116 .unwrap_or(0);
1117 let section_name =
1118 std::str::from_utf8(&shstrtab[sh_name_idx..sh_name_idx + name_end]).unwrap_or("");
1119
1120 if section_name.starts_with(prefix) {
1121 let sh_offset_val = u64::from_le_bytes(
1122 data[sh_offset + 24..sh_offset + 32]
1123 .try_into()
1124 .unwrap_or([0; 8]),
1125 ) as usize;
1126 let sh_size = u64::from_le_bytes(
1127 data[sh_offset + 32..sh_offset + 40]
1128 .try_into()
1129 .unwrap_or([0; 8]),
1130 ) as usize;
1131
1132 if sh_offset_val + sh_size <= data.len() {
1133 let hook_name = section_name.trim_start_matches(prefix).to_string();
1134 let section_data = data[sh_offset_val..sh_offset_val + sh_size].to_vec();
1135 results.push((hook_name, section_data));
1136 }
1137 }
1138 }
1139
1140 results
1141}
1142
1143pub struct LoadedMod {
1149 pub manifest: ModManifest,
1151 pub library: libloading::Library,
1153}
1154
1155pub struct ModLoader {
1171 mods: HashMap<String, LoadedMod>,
1172 load_order: Vec<String>,
1173}
1174
1175impl ModLoader {
1176 pub fn new() -> Self {
1178 Self {
1179 mods: HashMap::new(),
1180 load_order: Vec::new(),
1181 }
1182 }
1183
1184 pub fn load_all_mods(&mut self, mods_dir: &str, host_api: &HostApi) -> Result<(), String> {
1191 log::info!("Scanning mods directory: {}", mods_dir);
1192
1193 let mods_path = Path::new(mods_dir);
1194 if !mods_path.exists() {
1195 return Err(format!("Mods directory not found: {}", mods_dir));
1196 }
1197
1198 let mut manifests = Vec::new();
1200
1201 let ext = if cfg!(windows) {
1202 "dll"
1203 } else if cfg!(target_os = "macos") {
1204 "dylib"
1205 } else {
1206 "so"
1207 };
1208
1209 if let Ok(entries) = std::fs::read_dir(mods_path) {
1210 for entry in entries.flatten() {
1211 let path = entry.path();
1212 if path.extension().map_or(false, |e| e == ext) {
1213 let path_str = path.to_string_lossy().to_string();
1214
1215 unsafe {
1218 if let Ok(lib) = libloading::Library::new(&path_str) {
1219 if let Ok(info_ptr) =
1220 lib.get::<*const ModInfo>(b"MOD_INFO_SECTION")
1221 {
1222 let info_ref = &**info_ptr;
1223 let mut manifest = ModManifest::from(info_ref);
1224 manifest.path = path_str.clone();
1225 manifests.push(manifest);
1226 }
1227 }
1228 }
1229 }
1230 }
1231 }
1232
1233 log::info!(
1234 "Found {} mods: {:?}",
1235 manifests.len(),
1236 manifests.iter().map(|m| m.id.clone()).collect::<Vec<_>>()
1237 );
1238
1239 let order = DependencyResolver::resolve_load_order(&manifests)
1241 .map_err(|e| format!("Dependency resolution failed: {}", e))?;
1242
1243 log::info!("Load order: {:?}", order);
1244
1245 for mod_id in &order {
1247 let manifest = manifests.iter().find(|m| &m.id == mod_id).unwrap();
1248
1249 match self.load_mod_internal(&manifest.path, manifest.clone(), host_api) {
1250 Ok(()) => {
1251 log::info!(
1252 "Loaded mod: {} (v{})",
1253 manifest.id,
1254 manifest.version
1255 );
1256 self.load_order.push(mod_id.clone());
1257 }
1258 Err(e) => {
1259 log::error!("Failed to load mod '{}': {}", mod_id, e);
1260 }
1261 }
1262 }
1263
1264 Ok(())
1265 }
1266
1267 fn load_mod_internal(
1268 &mut self,
1269 path: &str,
1270 manifest: ModManifest,
1271 host_api: &HostApi,
1272 ) -> Result<(), String> {
1273 unsafe {
1275 let lib = libloading::Library::new(path)
1276 .map_err(|e| format!("Failed to load library: {}", e))?;
1277
1278 let init_sym: libloading::Symbol<extern "C" fn(*const HostApi) -> i32> = lib
1279 .get(b"mod_init")
1280 .map_err(|e| format!("No 'mod_init' symbol: {}", e))?;
1281
1282 match catch_unwind(AssertUnwindSafe(|| init_sym(host_api as *const HostApi))) {
1283 Ok(0) => {}
1284 Ok(code) => return Err(format!("mod_init failed with code: {}", code)),
1285 Err(_) => return Err("mod_init panicked".to_string()),
1286 }
1287
1288 self.mods.insert(
1289 manifest.id.clone(),
1290 LoadedMod {
1291 manifest,
1292 library: lib,
1293 },
1294 );
1295
1296 Ok(())
1297 }
1298 }
1299
1300 pub fn unload_mod(&mut self, mod_id: &str) -> Result<(), String> {
1307 for (id, loaded) in &self.mods {
1308 if loaded.manifest.requires.contains(&mod_id.to_string()) {
1309 return Err(format!(
1310 "Cannot unload '{}': mod '{}' depends on it",
1311 mod_id, id
1312 ));
1313 }
1314 }
1315
1316 if let Some(loaded) = self.mods.remove(mod_id) {
1317 get_hook_manager()
1318 .write()
1319 .unwrap()
1320 .unregister_mod(mod_id);
1321 drop(loaded.library);
1322 self.load_order.retain(|id| id != mod_id);
1323 log::info!("Unloaded mod: {}", mod_id);
1324 Ok(())
1325 } else {
1326 Err(format!("Mod '{}' not found", mod_id))
1327 }
1328 }
1329
1330 pub fn reload_mod(&mut self, mod_id: &str, host_api: &HostApi) -> Result<(), String> {
1336 let manifest = self
1337 .mods
1338 .get(mod_id)
1339 .map(|m| m.manifest.clone())
1340 .ok_or_else(|| format!("Mod '{}' not found", mod_id))?;
1341
1342 let path = manifest.path.clone();
1343
1344 self.unload_mod(mod_id)?;
1345 self.load_mod_internal(&path, manifest, host_api)?;
1346
1347 log::info!("Reloaded mod: {}", mod_id);
1348 Ok(())
1349 }
1350
1351 pub fn loaded_mods(&self) -> Vec<&str> {
1353 self.mods.keys().map(|s| s.as_str()).collect()
1354 }
1355
1356 pub fn get_manifest(&self, mod_id: &str) -> Option<&ModManifest> {
1358 self.mods.get(mod_id).map(|m| &m.manifest)
1359 }
1360}