Skip to main content

ghook_sdk/
lib.rs

1// ghook-sdk Copyright (c) 2026 Semyon Tsarev
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// project, You can obtain one at https://mozilla.org/MPL/2.0/.
5
6//! # ghook-sdk
7//!
8//! Core SDK for the **ghook** modding framework.
9//!
10//! This crate provides the runtime infrastructure for native Rust modding:
11//!
12//! - **Hook Manager** -- dispatches prefix, postfix, and replace hooks with panic isolation
13//! - **Mod Loader** -- scans directories, resolves dependencies, loads mods in correct order
14//! - **Dependency Resolver** -- topological sorting, cycle detection, conflict checking
15//! - **Host API** -- extensible interface between game and mods via extension registry
16//! - **Safety** -- segfault handler, panic catching, safe FFI boundaries
17//!
18//! ## Overview
19//!
20//! `ghook` implements an Inversion of Control (IoC) and Aspect-Oriented Programming (AOP)
21//! system for Rust games. The game marks functions as hookable with `#[hookable]`, and
22//! mods intercept them with `#[prefix]`, `#[postfix]`, or `#[replace]`.
23//!
24//! ## Quick Start
25//!
26//! ```rust,no_run
27//! use ghook_sdk::*;
28//!
29//! fn main() {
30//!     let host_api = create_host_api();
31//!     let mut loader = ModLoader::new();
32//!     loader.load_all_mods("./mods", &host_api).unwrap();
33//! }
34//! ```
35//!
36//! ## Feature Flags
37//!
38//! This crate has no feature flags. All functionality is included by default.
39//!
40//! ## Safety
41//!
42//! This crate uses `unsafe` internally for FFI operations. All unsafe blocks are
43//! documented and justified. Public APIs are safe to call.
44//!
45//! ## License
46//!
47//! Licensed under the [Mozilla Public License 2.0](https://opensource.org/licenses/MPL-2.0).
48//!
49//! ## Author
50//!
51//! Semyon Tsarev
52
53#![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
62// Re-export procedural macros
63pub use ghook_macros::{hookable, mod_info, prefix, postfix, replace, mod_init};
64pub use ghook_macros::use_game_hooks;
65
66// =============================================================================
67// SYNTACTIC SUGAR
68// =============================================================================
69
70/// Declares FFI-compatible argument structures for hooks.
71///
72/// This macro generates `#[repr(C)]` structs that match the memory layout expected
73/// by the game's hookable functions. The field names and types must exactly match
74/// what the game generates via `#[hookable]`.
75///
76/// For automatic type generation from the game binary, see [`use_game_hooks!`].
77///
78/// # Example
79///
80/// ```rust
81/// use ghook_sdk::declare_args;
82///
83/// declare_args! {
84///     ApplyDamageArgs { entity: u64, amount: f32 },
85///     GetHealthArgs { entity: u64 },
86/// }
87/// ```
88#[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// =============================================================================
101// CORE TYPES
102// =============================================================================
103
104/// Control flow signal returned by prefix and postfix hooks.
105///
106/// Determines whether the original function should be called, skipped, or aborted.
107#[repr(u8)]
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum HookControl {
110    /// Continue normal execution -- call the original function (or next hook).
111    Continue = 0,
112    /// Skip the original function but still run postfix hooks.
113    SkipOriginal = 1,
114    /// Abort entirely -- return the current result immediately.
115    Abort = 2,
116}
117
118/// Context passed to every hook callback via FFI.
119///
120/// Contains metadata about which mod is currently executing.
121#[repr(C)]
122pub struct HookContext {
123    /// Pointer to the mod ID string (UTF-8, not null-terminated).
124    pub mod_id: *const u8,
125    /// Length of the mod ID string in bytes.
126    pub mod_id_len: usize,
127}
128
129/// Metadata about a mod, stored in a dedicated binary section.
130///
131/// This structure is embedded in the `.mod_info` section of each mod's shared library.
132/// It contains identification, versioning, and dependency information.
133///
134/// # Binary Layout
135///
136/// All string fields are stored as raw UTF-8 byte pointers + lengths (not null-terminated).
137/// Dependency lists are comma-separated strings (e.g., `"mod_a,mod_b"`).
138#[repr(C)]
139pub struct ModInfo {
140    /// Magic bytes: must be `b"RUSTMOD\x00"`.
141    pub magic: [u8; 8],
142    /// API version this mod was compiled against.
143    pub api_version: u32,
144    /// Pointer to mod ID string.
145    pub id_ptr: *const u8,
146    /// Length of mod ID string.
147    pub id_len: usize,
148    /// Pointer to version string.
149    pub version_ptr: *const u8,
150    /// Length of version string.
151    pub version_len: usize,
152    /// Comma-separated list of required mod IDs.
153    pub requires_ptr: *const u8,
154    /// Length of requires string.
155    pub requires_len: usize,
156    /// Comma-separated list of mods that must load before this one.
157    pub load_after_ptr: *const u8,
158    /// Length of load_after string.
159    pub load_after_len: usize,
160    /// Comma-separated list of mods that must load after this one.
161    pub load_before_ptr: *const u8,
162    /// Length of load_before string.
163    pub load_before_len: usize,
164    /// Comma-separated list of incompatible mod IDs.
165    pub incompatible_with_ptr: *const u8,
166    /// Length of incompatible_with string.
167    pub incompatible_with_len: usize,
168}
169
170// SAFETY: ModInfo contains only raw pointers and primitives.
171// The pointed-to data lives in static sections of the shared library
172// and is valid for the lifetime of the loaded library.
173unsafe impl Sync for ModInfo {}
174unsafe impl Send for ModInfo {}
175
176impl ModInfo {
177    /// Reads a UTF-8 string from a raw pointer and length.
178    fn read_str(ptr: *const u8, len: usize) -> String {
179        if ptr.is_null() || len == 0 {
180            return String::new();
181        }
182        // SAFETY: The pointer and length come from static data embedded in the
183        // shared library by the #[mod_info] macro. The data is guaranteed to be
184        // valid UTF-8 and live for the lifetime of the library.
185        unsafe {
186            let slice = std::slice::from_raw_parts(ptr, len);
187            std::str::from_utf8_unchecked(slice).to_string()
188        }
189    }
190
191    /// Returns the mod's unique identifier.
192    pub fn id(&self) -> String {
193        Self::read_str(self.id_ptr, self.id_len)
194    }
195
196    /// Returns the mod's version string.
197    pub fn version(&self) -> String {
198        Self::read_str(self.version_ptr, self.version_len)
199    }
200
201    /// Returns the list of required mod IDs.
202    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    /// Returns the list of mods that must load before this one.
211    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    /// Returns the list of mods that must load after this one.
220    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    /// Returns the list of incompatible mod IDs.
229    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/// Parsed manifest of a mod, derived from [`ModInfo`].
239///
240/// Contains all metadata needed for dependency resolution and load ordering.
241#[derive(Debug, Clone)]
242pub struct ModManifest {
243    /// Unique mod identifier.
244    pub id: String,
245    /// Version string.
246    pub version: String,
247    /// Required mod IDs.
248    pub requires: Vec<String>,
249    /// Mods that must load before this one.
250    pub load_after: Vec<String>,
251    /// Mods that must load after this one.
252    pub load_before: Vec<String>,
253    /// Incompatible mod IDs.
254    pub incompatible_with: Vec<String>,
255    /// Filesystem path to the mod's shared library.
256    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// =============================================================================
274// HOST API WITH EXTENSIONS
275// =============================================================================
276
277/// The interface provided by the game to mods.
278///
279/// Contains core functions for hook registration, logging, and extension access.
280/// Games can extend this API by registering custom extensions via
281/// [`register_extension`].
282///
283/// # ABI Stability
284///
285/// This struct is `#[repr(C)]` and must maintain a stable layout across versions.
286/// New fields should only be added at the end, and `api_version` should be bumped.
287#[repr(C)]
288pub struct HostApi {
289    /// API version number. Mods should check this in `mod_init`.
290    pub api_version: u32,
291    /// Registers a hook callback for a given target function hash.
292    pub register_hook: extern "C" fn(
293        target_hash: u64,
294        kind: u8,
295        priority: i32,
296        callback: *const c_void,
297    ) -> u64,
298    /// Logs a message at the specified level.
299    pub log: extern "C" fn(level: u8, msg_ptr: *const u8, msg_len: usize),
300    /// Retrieves a registered extension by name.
301    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    /// Logs an informational message.
311    pub fn log_info(&self, msg: &str) {
312        self.log_raw(0, msg);
313    }
314
315    /// Logs a warning message.
316    pub fn log_warn(&self, msg: &str) {
317        self.log_raw(1, msg);
318    }
319
320    /// Logs an error message.
321    pub fn log_error(&self, msg: &str) {
322        self.log_raw(2, msg);
323    }
324
325    /// Logs a debug message.
326    pub fn log_debug(&self, msg: &str) {
327        self.log_raw(3, msg);
328    }
329
330    /// Safely retrieves a typed extension by name.
331    ///
332    /// Returns `None` if the extension is not registered or the name doesn't match.
333    ///
334    /// # Safety
335    ///
336    /// The caller must ensure that the type `T` matches the type used when
337    /// registering the extension via [`register_extension`].
338    ///
339    /// # Example
340    ///
341    /// ```rust,no_run
342    /// # use ghook_sdk::HostApi;
343    /// # fn example(api: &HostApi) {
344    /// if let Some(world) = api.get_extension_typed::<GameWorldApi>("game_world") {
345    ///     let entity = (world.spawn_entity)(10.0, 20.0, 1);
346    /// }
347    /// # }
348    /// # #[repr(C)] struct GameWorldApi { spawn_entity: extern "C" fn(f32, f32, u32) -> u64 }
349    /// ```
350    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            // SAFETY: Caller guarantees T matches the registered type.
356            Some(unsafe { &*(ptr as *const T) })
357        }
358    }
359}
360
361// =============================================================================
362// EXTENSION REGISTRY
363// =============================================================================
364
365/// Registry for game-provided API extensions.
366///
367/// Games register extensions (e.g., world API, UI API) that mods can query
368/// at runtime via [`HostApi::get_extension_typed`].
369pub struct ExtensionRegistry {
370    extensions: HashMap<String, *const c_void>,
371}
372
373impl ExtensionRegistry {
374    /// Creates an empty extension registry.
375    pub fn new() -> Self {
376        Self {
377            extensions: HashMap::new(),
378        }
379    }
380
381    /// Registers a named extension.
382    ///
383    /// The `api` reference must be `'static` -- typically a global `static` variable.
384    ///
385    /// # Example
386    ///
387    /// ```rust,no_run
388    /// # use ghook_sdk::ExtensionRegistry;
389    /// # static MY_API: () = ();
390    /// let mut registry = ExtensionRegistry::new();
391    /// registry.register("my_api", &MY_API);
392    /// ```
393    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    /// Retrieves an extension by name.
400    ///
401    /// Returns a null pointer if the extension is not found.
402    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
410// SAFETY: ExtensionRegistry stores only raw pointers to 'static data.
411// Access is synchronized via RwLock in the global instance.
412unsafe impl Send for ExtensionRegistry {}
413unsafe impl Sync for ExtensionRegistry {}
414
415// =============================================================================
416// DEPENDENCY RESOLVER
417// =============================================================================
418
419/// Errors that can occur during dependency resolution.
420#[derive(Debug, Clone)]
421pub enum DependencyError {
422    /// A required mod is not present.
423    MissingMod(String, String),
424    /// A circular dependency was detected.
425    CycleDetected(Vec<String>),
426    /// Two incompatible mods are both present.
427    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
448/// Resolves mod load order based on dependency metadata.
449///
450/// Uses Kahn's algorithm for topological sorting with deterministic tie-breaking.
451pub struct DependencyResolver;
452
453impl DependencyResolver {
454    /// Determines the correct load order for a set of mod manifests.
455    ///
456    /// # Errors
457    ///
458    /// Returns [`DependencyError`] if:
459    /// - A required mod is missing
460    /// - A circular dependency exists
461    /// - Two incompatible mods are both present
462    ///
463    /// # Example
464    ///
465    /// ```rust,no_run
466    /// # use ghook_sdk::{DependencyResolver, ModManifest};
467    /// let manifests: Vec<ModManifest> = vec![];
468    /// let order = DependencyResolver::resolve_load_order(&manifests).unwrap();
469    /// ```
470    pub fn resolve_load_order(manifests: &[ModManifest]) -> Result<Vec<String>, DependencyError> {
471        // 1. Check incompatibilities
472        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        // 2. Check that all required mods exist
484        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        // 3. Build dependency graph
497        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        // 4. Topological sort (Kahn's algorithm)
517        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)| deg == 0)
531            .map(|(&id, _)| id)
532            .collect();
533        queue.sort(); // Deterministic ordering
534
535        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        // 5. Check for cycles
553        if order.len() != manifests.len() {
554            let cycle: Vec<String> = in_degree
555                .iter()
556                .filter(|(_, &deg)| 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// =============================================================================
567// CONST HASHING (FNV-1a)
568// =============================================================================
569
570/// Computes an FNV-1a hash of a string at compile time.
571///
572/// Used by generated code to avoid runtime string hashing in hot paths.
573///
574/// # Example
575///
576/// ```rust
577/// # use ghook_sdk::hash_string_const;
578/// const HASH: u64 = hash_string_const("apply_damage");
579/// assert_ne!(HASH, 0);
580/// ```
581#[inline]
582pub const fn hash_string_const(s: &str) -> u64 {
583    let bytes = s.as_bytes();
584    let mut hash: u64 = 0xcbf29ce484222325; // FNV offset basis
585    let mut i = 0;
586    while i < bytes.len() {
587        hash ^= bytes[i] as u64;
588        hash = hash.wrapping_mul(0x100000001b3); // FNV prime
589        i += 1;
590    }
591    hash
592}
593
594/// Computes an FNV-1a hash of a string at runtime.
595///
596/// Delegates to [`hash_string_const`] for consistency.
597#[inline]
598pub fn hash_string(s: &str) -> u64 {
599    hash_string_const(s)
600}
601
602// =============================================================================
603// SEGFAULT HANDLER
604// =============================================================================
605
606static 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    // SAFETY: write() is async-signal-safe. We avoid allocations and formatting.
614    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
621/// Installs a SIGSEGV/SIGBUS handler that prints a diagnostic and aborts.
622///
623/// Called automatically by [`create_host_api`]. Safe to call multiple times;
624/// the handler is installed only once.
625pub fn install_segfault_handler() {
626    SEGFAULT_HANDLER_INSTALLED.get_or_init(|| {
627        // SAFETY: sigaction is a standard POSIX call. We set up a minimal handler
628        // that only uses async-signal-safe operations.
629        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
641// =============================================================================
642// HOOK MANAGER
643// =============================================================================
644
645type 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,     // 0=prefix, 1=postfix, 2=replace
651    priority: i32,
652    callback: HookCallback,
653}
654
655static HOOK_MANAGER: OnceLock<RwLock<HookManager>> = OnceLock::new();
656
657/// Manages hook registrations and dispatch.
658///
659/// Uses `RwLock` for concurrent read access during hook execution.
660/// Write access is only needed during registration/unregistration.
661pub struct HookManager {
662    hooks: HashMap<u64, Vec<HookRegistration>>,
663}
664
665impl HookManager {
666    /// Creates an empty hook manager.
667    pub fn new() -> Self {
668        Self {
669            hooks: HashMap::new(),
670        }
671    }
672
673    /// Registers a hook callback for a target function.
674    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    /// Removes all hooks registered by a specific mod.
697    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    /// Executes prefix hooks for a target function.
705    #[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    /// Executes postfix hooks for a target function.
760    #[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    /// Executes replace hooks for a target function.
814    ///
815    /// Returns `true` if a replace hook successfully handled the call.
816    #[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
864/// Returns a reference to the global hook manager.
865///
866/// The manager is lazily initialized on first access.
867pub fn get_hook_manager() -> &'static RwLock<HookManager> {
868    HOOK_MANAGER.get_or_init(|| RwLock::new(HookManager::new()))
869}
870
871// =============================================================================
872// HOST API IMPLEMENTATION
873// =============================================================================
874
875extern "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    // SAFETY: The callback pointer comes from a valid Rust function
885    // with the correct signature, cast to *const c_void by the generated code.
886    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    // SAFETY: The pointer and length come from a valid Rust &str
898    // passed through the FFI boundary by the mod.
899    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    // SAFETY: Same as host_log -- valid UTF-8 str from mod.
915    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
921/// Creates the host API that is passed to mods during initialization.
922///
923/// Also installs the segfault handler on first call.
924///
925/// # Example
926///
927/// ```rust,no_run
928/// use ghook_sdk::create_host_api;
929///
930/// let host_api = create_host_api();
931/// ```
932pub 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
943/// Registers a game-provided API extension.
944///
945/// Extensions can be retrieved by mods via [`HostApi::get_extension_typed`].
946///
947/// # Example
948///
949/// ```rust,no_run
950/// # use ghook_sdk::register_extension;
951/// # static MY_API: () = ();
952/// register_extension("my_api", &MY_API);
953/// ```
954pub 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// =============================================================================
960// HOOK INFO EXTRACTION
961// =============================================================================
962
963/// Information about a hookable function, extracted from a game binary.
964#[derive(Debug, Clone)]
965pub struct HookInfo {
966    /// Function name (e.g., `"apply_damage"`).
967    pub name: String,
968    /// FNV-1a hash of the function name.
969    pub hash: u64,
970    /// Argument descriptors: `(name, type_string)` pairs.
971    pub args: Vec<(String, String)>,
972    /// Return type as a string (e.g., `"f32"`, `"String"`).
973    pub result_type: String,
974}
975
976/// Reads hook metadata from a game binary's `.hooks_info.*` sections.
977///
978/// Parses the ELF binary at the given path and extracts all hook descriptors
979/// embedded by the `#[hookable]` macro.
980///
981/// # Errors
982///
983/// Returns an error if the file cannot be read or contains no hook info sections.
984///
985/// # Example
986///
987/// ```rust,no_run
988/// # use ghook_sdk::read_hooks_info;
989/// let hooks = read_hooks_info("/path/to/game-binary").unwrap();
990/// for hook in &hooks {
991///     println!("{}: {:?}", hook.name, hook.args);
992/// }
993/// ```
994pub 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(&section_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
1039/// Validates a game binary and returns the list of available hook names.
1040///
1041/// # Errors
1042///
1043/// Returns an error if the binary cannot be read or contains no hooks.
1044pub 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
1054/// Internal ELF section reader for runtime use.
1055fn 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    // Only support 64-bit ELF
1063    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
1143// =============================================================================
1144// MOD LOADER
1145// =============================================================================
1146
1147/// A loaded mod with its manifest and library handle.
1148pub struct LoadedMod {
1149    /// Parsed mod manifest.
1150    pub manifest: ModManifest,
1151    /// Handle to the loaded shared library.
1152    pub library: libloading::Library,
1153}
1154
1155/// Full-featured mod loader with dependency resolution and lifecycle management.
1156///
1157/// Scans a directory for mod shared libraries, reads their metadata,
1158/// resolves dependencies, and loads them in the correct order.
1159///
1160/// # Example
1161///
1162/// ```rust,no_run
1163/// use ghook_sdk::*;
1164///
1165/// let host_api = create_host_api();
1166/// let mut loader = ModLoader::new();
1167/// loader.load_all_mods("./mods", &host_api).unwrap();
1168/// println!("Loaded: {:?}", loader.loaded_mods());
1169/// ```
1170pub struct ModLoader {
1171    mods: HashMap<String, LoadedMod>,
1172    load_order: Vec<String>,
1173}
1174
1175impl ModLoader {
1176    /// Creates a new, empty mod loader.
1177    pub fn new() -> Self {
1178        Self {
1179            mods: HashMap::new(),
1180            load_order: Vec::new(),
1181        }
1182    }
1183
1184    /// Scans a directory and loads all mods in dependency-resolved order.
1185    ///
1186    /// # Errors
1187    ///
1188    /// Returns an error if the directory doesn't exist or dependency resolution fails.
1189    /// Individual mod load failures are logged but don't stop the process.
1190    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        // 1. Collect all manifests without loading code
1199        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                    // Temporarily load to read metadata
1216                    // SAFETY: We're reading a well-known symbol from a trusted local file.
1217                    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        // 2. Resolve load order
1240        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        // 3. Load mods in resolved order
1246        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        // SAFETY: Loading a shared library from a trusted local path.
1274        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    /// Unloads a mod, checking that no other mods depend on it.
1301    ///
1302    /// # Errors
1303    ///
1304    /// Returns an error if another loaded mod depends on this one,
1305    /// or if the mod is not found.
1306    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    /// Reloads a mod by unloading and re-loading it.
1331    ///
1332    /// # Errors
1333    ///
1334    /// Returns an error if the mod is not found or cannot be unloaded.
1335    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    /// Returns the IDs of all currently loaded mods.
1352    pub fn loaded_mods(&self) -> Vec<&str> {
1353        self.mods.keys().map(|s| s.as_str()).collect()
1354    }
1355
1356    /// Returns the manifest of a loaded mod.
1357    pub fn get_manifest(&self, mod_id: &str) -> Option<&ModManifest> {
1358        self.mods.get(mod_id).map(|m| &m.manifest)
1359    }
1360}