ghook-sdk 0.1.0

Core SDK for the ghook modding framework -- hook manager, mod loader, dependency resolver, and host API
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
// ghook-sdk Copyright (c) 2026 Semyon Tsarev
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// project, You can obtain one at https://mozilla.org/MPL/2.0/.

//! # ghook-sdk
//!
//! Core SDK for the **ghook** modding framework.
//!
//! This crate provides the runtime infrastructure for native Rust modding:
//!
//! - **Hook Manager** -- dispatches prefix, postfix, and replace hooks with panic isolation
//! - **Mod Loader** -- scans directories, resolves dependencies, loads mods in correct order
//! - **Dependency Resolver** -- topological sorting, cycle detection, conflict checking
//! - **Host API** -- extensible interface between game and mods via extension registry
//! - **Safety** -- segfault handler, panic catching, safe FFI boundaries
//!
//! ## Overview
//!
//! `ghook` implements an Inversion of Control (IoC) and Aspect-Oriented Programming (AOP)
//! system for Rust games. The game marks functions as hookable with `#[hookable]`, and
//! mods intercept them with `#[prefix]`, `#[postfix]`, or `#[replace]`.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use ghook_sdk::*;
//!
//! fn main() {
//!     let host_api = create_host_api();
//!     let mut loader = ModLoader::new();
//!     loader.load_all_mods("./mods", &host_api).unwrap();
//! }
//! ```
//!
//! ## Feature Flags
//!
//! This crate has no feature flags. All functionality is included by default.
//!
//! ## Safety
//!
//! This crate uses `unsafe` internally for FFI operations. All unsafe blocks are
//! documented and justified. Public APIs are safe to call.
//!
//! ## License
//!
//! Licensed under the [Mozilla Public License 2.0](https://opensource.org/licenses/MPL-2.0).
//!
//! ## Author
//!
//! Semyon Tsarev

#![doc(html_logo_url = "https://github.com/SemyonTs/ghook/raw/main/logo.png")]
#![doc(html_favicon_url = "https://github.com/SemyonTs/ghook/raw/main/favicon.ico")]

use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::{OnceLock, RwLock};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::Path;

// Re-export procedural macros
pub use ghook_macros::{hookable, mod_info, prefix, postfix, replace, mod_init};
pub use ghook_macros::use_game_hooks;

// =============================================================================
// SYNTACTIC SUGAR
// =============================================================================

/// Declares FFI-compatible argument structures for hooks.
///
/// This macro generates `#[repr(C)]` structs that match the memory layout expected
/// by the game's hookable functions. The field names and types must exactly match
/// what the game generates via `#[hookable]`.
///
/// For automatic type generation from the game binary, see [`use_game_hooks!`].
///
/// # Example
///
/// ```rust
/// use ghook_sdk::declare_args;
///
/// declare_args! {
///     ApplyDamageArgs { entity: u64, amount: f32 },
///     GetHealthArgs { entity: u64 },
/// }
/// ```
#[macro_export]
macro_rules! declare_args {
    ($($name:ident { $($field:ident: $ty:ty),* $(,)? }),* $(,)?) => {
        $(
            #[repr(C)]
            pub struct $name {
                $(pub $field: $ty,)*
            }
        )*
    };
}

// =============================================================================
// CORE TYPES
// =============================================================================

/// Control flow signal returned by prefix and postfix hooks.
///
/// Determines whether the original function should be called, skipped, or aborted.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookControl {
    /// Continue normal execution -- call the original function (or next hook).
    Continue = 0,
    /// Skip the original function but still run postfix hooks.
    SkipOriginal = 1,
    /// Abort entirely -- return the current result immediately.
    Abort = 2,
}

/// Context passed to every hook callback via FFI.
///
/// Contains metadata about which mod is currently executing.
#[repr(C)]
pub struct HookContext {
    /// Pointer to the mod ID string (UTF-8, not null-terminated).
    pub mod_id: *const u8,
    /// Length of the mod ID string in bytes.
    pub mod_id_len: usize,
}

/// Metadata about a mod, stored in a dedicated binary section.
///
/// This structure is embedded in the `.mod_info` section of each mod's shared library.
/// It contains identification, versioning, and dependency information.
///
/// # Binary Layout
///
/// All string fields are stored as raw UTF-8 byte pointers + lengths (not null-terminated).
/// Dependency lists are comma-separated strings (e.g., `"mod_a,mod_b"`).
#[repr(C)]
pub struct ModInfo {
    /// Magic bytes: must be `b"RUSTMOD\x00"`.
    pub magic: [u8; 8],
    /// API version this mod was compiled against.
    pub api_version: u32,
    /// Pointer to mod ID string.
    pub id_ptr: *const u8,
    /// Length of mod ID string.
    pub id_len: usize,
    /// Pointer to version string.
    pub version_ptr: *const u8,
    /// Length of version string.
    pub version_len: usize,
    /// Comma-separated list of required mod IDs.
    pub requires_ptr: *const u8,
    /// Length of requires string.
    pub requires_len: usize,
    /// Comma-separated list of mods that must load before this one.
    pub load_after_ptr: *const u8,
    /// Length of load_after string.
    pub load_after_len: usize,
    /// Comma-separated list of mods that must load after this one.
    pub load_before_ptr: *const u8,
    /// Length of load_before string.
    pub load_before_len: usize,
    /// Comma-separated list of incompatible mod IDs.
    pub incompatible_with_ptr: *const u8,
    /// Length of incompatible_with string.
    pub incompatible_with_len: usize,
}

// SAFETY: ModInfo contains only raw pointers and primitives.
// The pointed-to data lives in static sections of the shared library
// and is valid for the lifetime of the loaded library.
unsafe impl Sync for ModInfo {}
unsafe impl Send for ModInfo {}

impl ModInfo {
    /// Reads a UTF-8 string from a raw pointer and length.
    fn read_str(ptr: *const u8, len: usize) -> String {
        if ptr.is_null() || len == 0 {
            return String::new();
        }
        // SAFETY: The pointer and length come from static data embedded in the
        // shared library by the #[mod_info] macro. The data is guaranteed to be
        // valid UTF-8 and live for the lifetime of the library.
        unsafe {
            let slice = std::slice::from_raw_parts(ptr, len);
            std::str::from_utf8_unchecked(slice).to_string()
        }
    }

    /// Returns the mod's unique identifier.
    pub fn id(&self) -> String {
        Self::read_str(self.id_ptr, self.id_len)
    }

    /// Returns the mod's version string.
    pub fn version(&self) -> String {
        Self::read_str(self.version_ptr, self.version_len)
    }

    /// Returns the list of required mod IDs.
    pub fn requires(&self) -> Vec<String> {
        Self::read_str(self.requires_ptr, self.requires_len)
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Returns the list of mods that must load before this one.
    pub fn load_after(&self) -> Vec<String> {
        Self::read_str(self.load_after_ptr, self.load_after_len)
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Returns the list of mods that must load after this one.
    pub fn load_before(&self) -> Vec<String> {
        Self::read_str(self.load_before_ptr, self.load_before_len)
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Returns the list of incompatible mod IDs.
    pub fn incompatible_with(&self) -> Vec<String> {
        Self::read_str(self.incompatible_with_ptr, self.incompatible_with_len)
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect()
    }
}

/// Parsed manifest of a mod, derived from [`ModInfo`].
///
/// Contains all metadata needed for dependency resolution and load ordering.
#[derive(Debug, Clone)]
pub struct ModManifest {
    /// Unique mod identifier.
    pub id: String,
    /// Version string.
    pub version: String,
    /// Required mod IDs.
    pub requires: Vec<String>,
    /// Mods that must load before this one.
    pub load_after: Vec<String>,
    /// Mods that must load after this one.
    pub load_before: Vec<String>,
    /// Incompatible mod IDs.
    pub incompatible_with: Vec<String>,
    /// Filesystem path to the mod's shared library.
    pub path: String,
}

impl From<&ModInfo> for ModManifest {
    fn from(info: &ModInfo) -> Self {
        Self {
            id: info.id(),
            version: info.version(),
            requires: info.requires(),
            load_after: info.load_after(),
            load_before: info.load_before(),
            incompatible_with: info.incompatible_with(),
            path: String::new(),
        }
    }
}

// =============================================================================
// HOST API WITH EXTENSIONS
// =============================================================================

/// The interface provided by the game to mods.
///
/// Contains core functions for hook registration, logging, and extension access.
/// Games can extend this API by registering custom extensions via
/// [`register_extension`].
///
/// # ABI Stability
///
/// This struct is `#[repr(C)]` and must maintain a stable layout across versions.
/// New fields should only be added at the end, and `api_version` should be bumped.
#[repr(C)]
pub struct HostApi {
    /// API version number. Mods should check this in `mod_init`.
    pub api_version: u32,
    /// Registers a hook callback for a given target function hash.
    pub register_hook: extern "C" fn(
        target_hash: u64,
        kind: u8,
        priority: i32,
        callback: *const c_void,
    ) -> u64,
    /// Logs a message at the specified level.
    pub log: extern "C" fn(level: u8, msg_ptr: *const u8, msg_len: usize),
    /// Retrieves a registered extension by name.
    pub get_extension: extern "C" fn(name_ptr: *const u8, name_len: usize) -> *const c_void,
}

impl HostApi {
    #[inline]
    fn log_raw(&self, level: u8, msg: &str) {
        (self.log)(level, msg.as_ptr(), msg.len());
    }

    /// Logs an informational message.
    pub fn log_info(&self, msg: &str) {
        self.log_raw(0, msg);
    }

    /// Logs a warning message.
    pub fn log_warn(&self, msg: &str) {
        self.log_raw(1, msg);
    }

    /// Logs an error message.
    pub fn log_error(&self, msg: &str) {
        self.log_raw(2, msg);
    }

    /// Logs a debug message.
    pub fn log_debug(&self, msg: &str) {
        self.log_raw(3, msg);
    }

    /// Safely retrieves a typed extension by name.
    ///
    /// Returns `None` if the extension is not registered or the name doesn't match.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the type `T` matches the type used when
    /// registering the extension via [`register_extension`].
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use ghook_sdk::HostApi;
    /// # fn example(api: &HostApi) {
    /// if let Some(world) = api.get_extension_typed::<GameWorldApi>("game_world") {
    ///     let entity = (world.spawn_entity)(10.0, 20.0, 1);
    /// }
    /// # }
    /// # #[repr(C)] struct GameWorldApi { spawn_entity: extern "C" fn(f32, f32, u32) -> u64 }
    /// ```
    pub fn get_extension_typed<T>(&self, name: &str) -> Option<&'static T> {
        let ptr = (self.get_extension)(name.as_ptr(), name.len());
        if ptr.is_null() {
            None
        } else {
            // SAFETY: Caller guarantees T matches the registered type.
            Some(unsafe { &*(ptr as *const T) })
        }
    }
}

// =============================================================================
// EXTENSION REGISTRY
// =============================================================================

/// Registry for game-provided API extensions.
///
/// Games register extensions (e.g., world API, UI API) that mods can query
/// at runtime via [`HostApi::get_extension_typed`].
pub struct ExtensionRegistry {
    extensions: HashMap<String, *const c_void>,
}

impl ExtensionRegistry {
    /// Creates an empty extension registry.
    pub fn new() -> Self {
        Self {
            extensions: HashMap::new(),
        }
    }

    /// Registers a named extension.
    ///
    /// The `api` reference must be `'static` -- typically a global `static` variable.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use ghook_sdk::ExtensionRegistry;
    /// # static MY_API: () = ();
    /// let mut registry = ExtensionRegistry::new();
    /// registry.register("my_api", &MY_API);
    /// ```
    pub fn register<T: 'static>(&mut self, name: &str, api: &'static T) {
        self.extensions
            .insert(name.to_string(), api as *const T as *const c_void);
        log::info!("Registered extension: '{}'", name);
    }

    /// Retrieves an extension by name.
    ///
    /// Returns a null pointer if the extension is not found.
    pub fn get(&self, name: &str) -> *const c_void {
        self.extensions
            .get(name)
            .copied()
            .unwrap_or(std::ptr::null())
    }
}

// SAFETY: ExtensionRegistry stores only raw pointers to 'static data.
// Access is synchronized via RwLock in the global instance.
unsafe impl Send for ExtensionRegistry {}
unsafe impl Sync for ExtensionRegistry {}

// =============================================================================
// DEPENDENCY RESOLVER
// =============================================================================

/// Errors that can occur during dependency resolution.
#[derive(Debug, Clone)]
pub enum DependencyError {
    /// A required mod is not present.
    MissingMod(String, String),
    /// A circular dependency was detected.
    CycleDetected(Vec<String>),
    /// Two incompatible mods are both present.
    IncompatibleMods(String, String),
}

impl std::fmt::Display for DependencyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingMod(mod_id, dep) => {
                write!(f, "Mod '{}' requires '{}' which is not loaded", mod_id, dep)
            }
            Self::CycleDetected(cycle) => {
                write!(f, "Circular dependency detected: {}", cycle.join(" -> "))
            }
            Self::IncompatibleMods(a, b) => {
                write!(f, "Mods '{}' and '{}' are incompatible", a, b)
            }
        }
    }
}

impl std::error::Error for DependencyError {}

/// Resolves mod load order based on dependency metadata.
///
/// Uses Kahn's algorithm for topological sorting with deterministic tie-breaking.
pub struct DependencyResolver;

impl DependencyResolver {
    /// Determines the correct load order for a set of mod manifests.
    ///
    /// # Errors
    ///
    /// Returns [`DependencyError`] if:
    /// - A required mod is missing
    /// - A circular dependency exists
    /// - Two incompatible mods are both present
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use ghook_sdk::{DependencyResolver, ModManifest};
    /// let manifests: Vec<ModManifest> = vec![];
    /// let order = DependencyResolver::resolve_load_order(&manifests).unwrap();
    /// ```
    pub fn resolve_load_order(manifests: &[ModManifest]) -> Result<Vec<String>, DependencyError> {
        // 1. Check incompatibilities
        for manifest in manifests {
            for conflict in &manifest.incompatible_with {
                if manifests.iter().any(|m| &m.id == conflict) {
                    return Err(DependencyError::IncompatibleMods(
                        manifest.id.clone(),
                        conflict.clone(),
                    ));
                }
            }
        }

        // 2. Check that all required mods exist
        let ids: Vec<&str> = manifests.iter().map(|m| m.id.as_str()).collect();
        for manifest in manifests {
            for dep in &manifest.requires {
                if !ids.contains(&dep.as_str()) {
                    return Err(DependencyError::MissingMod(
                        manifest.id.clone(),
                        dep.clone(),
                    ));
                }
            }
        }

        // 3. Build dependency graph
        let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
        for manifest in manifests {
            let entry = graph.entry(manifest.id.as_str()).or_default();

            for dep in &manifest.requires {
                entry.push(dep.as_str());
            }
            for after in &manifest.load_after {
                entry.push(after.as_str());
            }
            for before in &manifest.load_before {
                if let Some(other_deps) = graph.get_mut(before.as_str()) {
                    other_deps.push(manifest.id.as_str());
                } else {
                    graph.insert(before.as_str(), vec![manifest.id.as_str()]);
                }
            }
        }

        // 4. Topological sort (Kahn's algorithm)
        let mut in_degree: HashMap<&str, usize> = HashMap::new();
        for manifest in manifests {
            in_degree.insert(manifest.id.as_str(), 0);
        }

        for deps in graph.values() {
            for dep in deps {
                *in_degree.entry(dep).or_insert(0) += 1;
            }
        }

        let mut queue: Vec<&str> = in_degree
            .iter()
            .filter(|(_, &deg)| deg == 0)
            .map(|(&id, _)| id)
            .collect();
        queue.sort(); // Deterministic ordering

        let mut order = Vec::new();

        while let Some(id) = queue.pop() {
            order.push(id.to_string());

            if let Some(deps) = graph.get(id) {
                for dep in deps {
                    if let Some(deg) = in_degree.get_mut(dep) {
                        *deg -= 1;
                        if *deg == 0 {
                            queue.push(dep);
                        }
                    }
                }
            }
        }

        // 5. Check for cycles
        if order.len() != manifests.len() {
            let cycle: Vec<String> = in_degree
                .iter()
                .filter(|(_, &deg)| deg > 0)
                .map(|(&id, _)| id.to_string())
                .collect();
            return Err(DependencyError::CycleDetected(cycle));
        }

        Ok(order)
    }
}

// =============================================================================
// CONST HASHING (FNV-1a)
// =============================================================================

/// Computes an FNV-1a hash of a string at compile time.
///
/// Used by generated code to avoid runtime string hashing in hot paths.
///
/// # Example
///
/// ```rust
/// # use ghook_sdk::hash_string_const;
/// const HASH: u64 = hash_string_const("apply_damage");
/// assert_ne!(HASH, 0);
/// ```
#[inline]
pub const fn hash_string_const(s: &str) -> u64 {
    let bytes = s.as_bytes();
    let mut hash: u64 = 0xcbf29ce484222325; // FNV offset basis
    let mut i = 0;
    while i < bytes.len() {
        hash ^= bytes[i] as u64;
        hash = hash.wrapping_mul(0x100000001b3); // FNV prime
        i += 1;
    }
    hash
}

/// Computes an FNV-1a hash of a string at runtime.
///
/// Delegates to [`hash_string_const`] for consistency.
#[inline]
pub fn hash_string(s: &str) -> u64 {
    hash_string_const(s)
}

// =============================================================================
// SEGFAULT HANDLER
// =============================================================================

static SEGFAULT_HANDLER_INSTALLED: OnceLock<()> = OnceLock::new();

extern "C" fn segfault_handler(
    _sig: libc::c_int,
    _info: *mut libc::siginfo_t,
    _ctx: *mut libc::c_void,
) {
    // SAFETY: write() is async-signal-safe. We avoid allocations and formatting.
    let msg = b"\n[SEGFAULT] A mod accessed invalid memory. Aborting.\n";
    unsafe {
        libc::write(libc::STDERR_FILENO, msg.as_ptr() as *const _, msg.len());
    }
    std::process::abort();
}

/// Installs a SIGSEGV/SIGBUS handler that prints a diagnostic and aborts.
///
/// Called automatically by [`create_host_api`]. Safe to call multiple times;
/// the handler is installed only once.
pub fn install_segfault_handler() {
    SEGFAULT_HANDLER_INSTALLED.get_or_init(|| {
        // SAFETY: sigaction is a standard POSIX call. We set up a minimal handler
        // that only uses async-signal-safe operations.
        unsafe {
            let mut sa: libc::sigaction = std::mem::zeroed();
            sa.sa_sigaction = segfault_handler as *const () as usize;
            sa.sa_flags = libc::SA_SIGINFO;
            libc::sigemptyset(&mut sa.sa_mask);
            libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
            libc::sigaction(libc::SIGBUS, &sa, std::ptr::null_mut());
            log::info!("Segfault handler installed");
        }
    });
}

// =============================================================================
// HOOK MANAGER
// =============================================================================

type HookCallback =
    extern "C" fn(ctx: *mut HookContext, args: *mut c_void, result: *mut c_void) -> u8;

struct HookRegistration {
    mod_id: String,
    kind: u8,     // 0=prefix, 1=postfix, 2=replace
    priority: i32,
    callback: HookCallback,
}

static HOOK_MANAGER: OnceLock<RwLock<HookManager>> = OnceLock::new();

/// Manages hook registrations and dispatch.
///
/// Uses `RwLock` for concurrent read access during hook execution.
/// Write access is only needed during registration/unregistration.
pub struct HookManager {
    hooks: HashMap<u64, Vec<HookRegistration>>,
}

impl HookManager {
    /// Creates an empty hook manager.
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    /// Registers a hook callback for a target function.
    pub fn register_hook(
        &mut self,
        target_hash: u64,
        kind: u8,
        priority: i32,
        callback: HookCallback,
        mod_id: &str,
    ) -> u64 {
        let reg = HookRegistration {
            mod_id: mod_id.to_string(),
            kind,
            priority,
            callback,
        };
        self.hooks.entry(target_hash).or_default().push(reg);
        self.hooks
            .get_mut(&target_hash)
            .unwrap()
            .sort_by_key(|h| h.priority);
        1
    }

    /// Removes all hooks registered by a specific mod.
    pub fn unregister_mod(&mut self, mod_id: &str) {
        for hooks in self.hooks.values_mut() {
            hooks.retain(|h| h.mod_id != mod_id);
        }
        log::info!("Unregistered all hooks for mod '{}'", mod_id);
    }

    /// Executes prefix hooks for a target function.
    #[inline]
    pub fn execute_prefix<A, R>(
        &self,
        target_hash: u64,
        args: &mut A,
        result: &mut R,
    ) -> HookControl {
        let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
            let mut to_remove = Vec::new();
            for (idx, hook) in hooks.iter().enumerate() {
                if hook.kind != 0 {
                    continue;
                }
                let ctx = HookContext {
                    mod_id: hook.mod_id.as_ptr(),
                    mod_id_len: hook.mod_id.len(),
                };

                match catch_unwind(AssertUnwindSafe(|| {
                    (hook.callback)(
                        &ctx as *const _ as *mut _,
                        args as *mut A as *mut _,
                        result as *mut R as *mut _,
                    )
                })) {
                    Ok(1) => return HookControl::SkipOriginal,
                    Ok(2) => return HookControl::Abort,
                    Err(_) => {
                        log::error!(
                            "Mod '{}' panicked in prefix! Disabling.",
                            hook.mod_id
                        );
                        to_remove.push(idx);
                    }
                    _ => {}
                }
            }
            to_remove
        } else {
            Vec::new()
        };

        if !to_remove.is_empty() {
            let mut manager = get_hook_manager().write().unwrap();
            if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
                for idx in to_remove.into_iter().rev() {
                    hooks.remove(idx);
                }
            }
        }

        HookControl::Continue
    }

    /// Executes postfix hooks for a target function.
    #[inline]
    pub fn execute_postfix<A, R>(
        &self,
        target_hash: u64,
        args: &A,
        result: &mut R,
    ) -> HookControl {
        let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
            let mut to_remove = Vec::new();
            for (idx, hook) in hooks.iter().enumerate() {
                if hook.kind != 1 {
                    continue;
                }
                let ctx = HookContext {
                    mod_id: hook.mod_id.as_ptr(),
                    mod_id_len: hook.mod_id.len(),
                };

                match catch_unwind(AssertUnwindSafe(|| {
                    (hook.callback)(
                        &ctx as *const _ as *mut _,
                        args as *const A as *mut _,
                        result as *mut R as *mut _,
                    )
                })) {
                    Ok(2) => return HookControl::Abort,
                    Err(_) => {
                        log::error!(
                            "Mod '{}' panicked in postfix! Disabling.",
                            hook.mod_id
                        );
                        to_remove.push(idx);
                    }
                    _ => {}
                }
            }
            to_remove
        } else {
            Vec::new()
        };

        if !to_remove.is_empty() {
            let mut manager = get_hook_manager().write().unwrap();
            if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
                for idx in to_remove.into_iter().rev() {
                    hooks.remove(idx);
                }
            }
        }

        HookControl::Continue
    }

    /// Executes replace hooks for a target function.
    ///
    /// Returns `true` if a replace hook successfully handled the call.
    #[inline]
    pub fn execute_replace<A, R>(&self, target_hash: u64, args: &mut A, result: &mut R) -> bool {
        let to_remove = if let Some(hooks) = self.hooks.get(&target_hash) {
            let mut to_remove = Vec::new();
            for (idx, hook) in hooks.iter().enumerate() {
                if hook.kind != 2 {
                    continue;
                }
                let ctx = HookContext {
                    mod_id: hook.mod_id.as_ptr(),
                    mod_id_len: hook.mod_id.len(),
                };

                match catch_unwind(AssertUnwindSafe(|| {
                    (hook.callback)(
                        &ctx as *const _ as *mut _,
                        args as *mut A as *mut _,
                        result as *mut R as *mut _,
                    )
                })) {
                    Ok(_) => return true,
                    Err(_) => {
                        log::error!(
                            "Mod '{}' panicked in replace! Disabling.",
                            hook.mod_id
                        );
                        to_remove.push(idx);
                    }
                }
            }
            to_remove
        } else {
            Vec::new()
        };

        if !to_remove.is_empty() {
            let mut manager = get_hook_manager().write().unwrap();
            if let Some(hooks) = manager.hooks.get_mut(&target_hash) {
                for idx in to_remove.into_iter().rev() {
                    hooks.remove(idx);
                }
            }
        }

        false
    }
}

/// Returns a reference to the global hook manager.
///
/// The manager is lazily initialized on first access.
pub fn get_hook_manager() -> &'static RwLock<HookManager> {
    HOOK_MANAGER.get_or_init(|| RwLock::new(HookManager::new()))
}

// =============================================================================
// HOST API IMPLEMENTATION
// =============================================================================

extern "C" fn host_register_hook(
    target_hash: u64,
    kind: u8,
    priority: i32,
    callback: *const c_void,
) -> u64 {
    if callback.is_null() {
        return 0;
    }
    // SAFETY: The callback pointer comes from a valid Rust function
    // with the correct signature, cast to *const c_void by the generated code.
    let callback_fn: HookCallback = unsafe { std::mem::transmute(callback) };
    get_hook_manager()
        .write()
        .unwrap()
        .register_hook(target_hash, kind, priority, callback_fn, "dynamic_mod")
}

extern "C" fn host_log(level: u8, msg_ptr: *const u8, msg_len: usize) {
    if msg_ptr.is_null() {
        return;
    }
    // SAFETY: The pointer and length come from a valid Rust &str
    // passed through the FFI boundary by the mod.
    let msg = unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(msg_ptr, msg_len)) };
    match level {
        0 => log::info!("[MOD] {}", msg),
        1 => log::warn!("[MOD] {}", msg),
        2 => log::error!("[MOD] {}", msg),
        _ => log::debug!("[MOD] {}", msg),
    }
}

static EXTENSION_REGISTRY: OnceLock<RwLock<ExtensionRegistry>> = OnceLock::new();

extern "C" fn host_get_extension(name_ptr: *const u8, name_len: usize) -> *const c_void {
    if name_ptr.is_null() {
        return std::ptr::null();
    }
    // SAFETY: Same as host_log -- valid UTF-8 str from mod.
    let name = unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(name_ptr, name_len)) };

    let registry = EXTENSION_REGISTRY.get_or_init(|| RwLock::new(ExtensionRegistry::new()));
    registry.read().unwrap().get(name)
}

/// Creates the host API that is passed to mods during initialization.
///
/// Also installs the segfault handler on first call.
///
/// # Example
///
/// ```rust,no_run
/// use ghook_sdk::create_host_api;
///
/// let host_api = create_host_api();
/// ```
pub fn create_host_api() -> HostApi {
    install_segfault_handler();

    HostApi {
        api_version: 1,
        register_hook: host_register_hook,
        log: host_log,
        get_extension: host_get_extension,
    }
}

/// Registers a game-provided API extension.
///
/// Extensions can be retrieved by mods via [`HostApi::get_extension_typed`].
///
/// # Example
///
/// ```rust,no_run
/// # use ghook_sdk::register_extension;
/// # static MY_API: () = ();
/// register_extension("my_api", &MY_API);
/// ```
pub fn register_extension<T: 'static>(name: &str, api: &'static T) {
    let registry = EXTENSION_REGISTRY.get_or_init(|| RwLock::new(ExtensionRegistry::new()));
    registry.write().unwrap().register(name, api);
}

// =============================================================================
// HOOK INFO EXTRACTION
// =============================================================================

/// Information about a hookable function, extracted from a game binary.
#[derive(Debug, Clone)]
pub struct HookInfo {
    /// Function name (e.g., `"apply_damage"`).
    pub name: String,
    /// FNV-1a hash of the function name.
    pub hash: u64,
    /// Argument descriptors: `(name, type_string)` pairs.
    pub args: Vec<(String, String)>,
    /// Return type as a string (e.g., `"f32"`, `"String"`).
    pub result_type: String,
}

/// Reads hook metadata from a game binary's `.hooks_info.*` sections.
///
/// Parses the ELF binary at the given path and extracts all hook descriptors
/// embedded by the `#[hookable]` macro.
///
/// # Errors
///
/// Returns an error if the file cannot be read or contains no hook info sections.
///
/// # Example
///
/// ```rust,no_run
/// # use ghook_sdk::read_hooks_info;
/// let hooks = read_hooks_info("/path/to/game-binary").unwrap();
/// for hook in &hooks {
///     println!("{}: {:?}", hook.name, hook.args);
/// }
/// ```
pub fn read_hooks_info(binary_path: &str) -> Result<Vec<HookInfo>, String> {
    let data =
        std::fs::read(binary_path).map_err(|e| format!("Failed to read '{}': {}", binary_path, e))?;

    let sections = read_elf_sections_runtime(&data, ".hooks_info.");

    let mut hooks = Vec::new();

    for (name, section_data) in sections {
        let info_str = String::from_utf8_lossy(&section_data);
        let parts: Vec<&str> = info_str.split('|').collect();

        if parts.len() != 2 {
            continue;
        }

        let args: Vec<(String, String)> = if parts[0].is_empty() {
            Vec::new()
        } else {
            parts[0]
                .split(',')
                .filter_map(|arg| {
                    let p: Vec<&str> = arg.splitn(2, ':').collect();
                    if p.len() == 2 {
                        Some((p[0].trim().to_string(), p[1].trim().to_string()))
                    } else {
                        None
                    }
                })
                .collect()
        };

        let hash = hash_string(&name);

        hooks.push(HookInfo {
            name,
            hash,
            args,
            result_type: parts[1].trim().to_string(),
        });
    }

    Ok(hooks)
}

/// Validates a game binary and returns the list of available hook names.
///
/// # Errors
///
/// Returns an error if the binary cannot be read or contains no hooks.
pub fn validate_game_binary(binary_path: &str) -> Result<Vec<String>, String> {
    let hooks = read_hooks_info(binary_path)?;

    if hooks.is_empty() {
        return Err("No hooks found in game binary".to_string());
    }

    Ok(hooks.iter().map(|h| h.name.clone()).collect())
}

/// Internal ELF section reader for runtime use.
fn read_elf_sections_runtime(data: &[u8], prefix: &str) -> Vec<(String, Vec<u8>)> {
    let mut results = Vec::new();

    if data.len() < 64 || &data[0..4] != b"\x7fELF" {
        return results;
    }

    // Only support 64-bit ELF
    if data[4] != 2 {
        return results;
    }

    let e_shoff = u64::from_le_bytes(data[40..48].try_into().unwrap_or([0; 8])) as usize;
    let e_shentsize = u16::from_le_bytes(data[58..60].try_into().unwrap_or([0; 2])) as usize;
    let e_shnum = u16::from_le_bytes(data[60..62].try_into().unwrap_or([0; 2])) as usize;
    let e_shstrndx = u16::from_le_bytes(data[62..64].try_into().unwrap_or([0; 2])) as usize;

    if e_shoff == 0 || e_shnum == 0 {
        return results;
    }

    let shstr_offset = e_shoff + e_shstrndx * e_shentsize;
    if shstr_offset + e_shentsize > data.len() {
        return results;
    }

    let shstr_sh_offset = u64::from_le_bytes(
        data[shstr_offset + 24..shstr_offset + 32]
            .try_into()
            .unwrap_or([0; 8]),
    ) as usize;
    let shstr_sh_size = u64::from_le_bytes(
        data[shstr_offset + 32..shstr_offset + 40]
            .try_into()
            .unwrap_or([0; 8]),
    ) as usize;

    if shstr_sh_offset + shstr_sh_size > data.len() {
        return results;
    }
    let shstrtab = &data[shstr_sh_offset..shstr_sh_offset + shstr_sh_size];

    for i in 0..e_shnum {
        let sh_offset = e_shoff + i * e_shentsize;
        if sh_offset + e_shentsize > data.len() {
            break;
        }

        let sh_name_idx = u32::from_le_bytes(
            data[sh_offset..sh_offset + 4]
                .try_into()
                .unwrap_or([0; 4]),
        ) as usize;

        if sh_name_idx >= shstrtab.len() {
            continue;
        }

        let name_end = shstrtab[sh_name_idx..]
            .iter()
            .position(|&b| b == 0)
            .unwrap_or(0);
        let section_name =
            std::str::from_utf8(&shstrtab[sh_name_idx..sh_name_idx + name_end]).unwrap_or("");

        if section_name.starts_with(prefix) {
            let sh_offset_val = u64::from_le_bytes(
                data[sh_offset + 24..sh_offset + 32]
                    .try_into()
                    .unwrap_or([0; 8]),
            ) as usize;
            let sh_size = u64::from_le_bytes(
                data[sh_offset + 32..sh_offset + 40]
                    .try_into()
                    .unwrap_or([0; 8]),
            ) as usize;

            if sh_offset_val + sh_size <= data.len() {
                let hook_name = section_name.trim_start_matches(prefix).to_string();
                let section_data = data[sh_offset_val..sh_offset_val + sh_size].to_vec();
                results.push((hook_name, section_data));
            }
        }
    }

    results
}

// =============================================================================
// MOD LOADER
// =============================================================================

/// A loaded mod with its manifest and library handle.
pub struct LoadedMod {
    /// Parsed mod manifest.
    pub manifest: ModManifest,
    /// Handle to the loaded shared library.
    pub library: libloading::Library,
}

/// Full-featured mod loader with dependency resolution and lifecycle management.
///
/// Scans a directory for mod shared libraries, reads their metadata,
/// resolves dependencies, and loads them in the correct order.
///
/// # Example
///
/// ```rust,no_run
/// use ghook_sdk::*;
///
/// let host_api = create_host_api();
/// let mut loader = ModLoader::new();
/// loader.load_all_mods("./mods", &host_api).unwrap();
/// println!("Loaded: {:?}", loader.loaded_mods());
/// ```
pub struct ModLoader {
    mods: HashMap<String, LoadedMod>,
    load_order: Vec<String>,
}

impl ModLoader {
    /// Creates a new, empty mod loader.
    pub fn new() -> Self {
        Self {
            mods: HashMap::new(),
            load_order: Vec::new(),
        }
    }

    /// Scans a directory and loads all mods in dependency-resolved order.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory doesn't exist or dependency resolution fails.
    /// Individual mod load failures are logged but don't stop the process.
    pub fn load_all_mods(&mut self, mods_dir: &str, host_api: &HostApi) -> Result<(), String> {
        log::info!("Scanning mods directory: {}", mods_dir);

        let mods_path = Path::new(mods_dir);
        if !mods_path.exists() {
            return Err(format!("Mods directory not found: {}", mods_dir));
        }

        // 1. Collect all manifests without loading code
        let mut manifests = Vec::new();

        let ext = if cfg!(windows) {
            "dll"
        } else if cfg!(target_os = "macos") {
            "dylib"
        } else {
            "so"
        };

        if let Ok(entries) = std::fs::read_dir(mods_path) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().map_or(false, |e| e == ext) {
                    let path_str = path.to_string_lossy().to_string();

                    // Temporarily load to read metadata
                    // SAFETY: We're reading a well-known symbol from a trusted local file.
                    unsafe {
                        if let Ok(lib) = libloading::Library::new(&path_str) {
                            if let Ok(info_ptr) =
                                lib.get::<*const ModInfo>(b"MOD_INFO_SECTION")
                            {
                                let info_ref = &**info_ptr;
                                let mut manifest = ModManifest::from(info_ref);
                                manifest.path = path_str.clone();
                                manifests.push(manifest);
                            }
                        }
                    }
                }
            }
        }

        log::info!(
            "Found {} mods: {:?}",
            manifests.len(),
            manifests.iter().map(|m| m.id.clone()).collect::<Vec<_>>()
        );

        // 2. Resolve load order
        let order = DependencyResolver::resolve_load_order(&manifests)
            .map_err(|e| format!("Dependency resolution failed: {}", e))?;

        log::info!("Load order: {:?}", order);

        // 3. Load mods in resolved order
        for mod_id in &order {
            let manifest = manifests.iter().find(|m| &m.id == mod_id).unwrap();

            match self.load_mod_internal(&manifest.path, manifest.clone(), host_api) {
                Ok(()) => {
                    log::info!(
                        "Loaded mod: {} (v{})",
                        manifest.id,
                        manifest.version
                    );
                    self.load_order.push(mod_id.clone());
                }
                Err(e) => {
                    log::error!("Failed to load mod '{}': {}", mod_id, e);
                }
            }
        }

        Ok(())
    }

    fn load_mod_internal(
        &mut self,
        path: &str,
        manifest: ModManifest,
        host_api: &HostApi,
    ) -> Result<(), String> {
        // SAFETY: Loading a shared library from a trusted local path.
        unsafe {
            let lib = libloading::Library::new(path)
                .map_err(|e| format!("Failed to load library: {}", e))?;

            let init_sym: libloading::Symbol<extern "C" fn(*const HostApi) -> i32> = lib
                .get(b"mod_init")
                .map_err(|e| format!("No 'mod_init' symbol: {}", e))?;

            match catch_unwind(AssertUnwindSafe(|| init_sym(host_api as *const HostApi))) {
                Ok(0) => {}
                Ok(code) => return Err(format!("mod_init failed with code: {}", code)),
                Err(_) => return Err("mod_init panicked".to_string()),
            }

            self.mods.insert(
                manifest.id.clone(),
                LoadedMod {
                    manifest,
                    library: lib,
                },
            );

            Ok(())
        }
    }

    /// Unloads a mod, checking that no other mods depend on it.
    ///
    /// # Errors
    ///
    /// Returns an error if another loaded mod depends on this one,
    /// or if the mod is not found.
    pub fn unload_mod(&mut self, mod_id: &str) -> Result<(), String> {
        for (id, loaded) in &self.mods {
            if loaded.manifest.requires.contains(&mod_id.to_string()) {
                return Err(format!(
                    "Cannot unload '{}': mod '{}' depends on it",
                    mod_id, id
                ));
            }
        }

        if let Some(loaded) = self.mods.remove(mod_id) {
            get_hook_manager()
                .write()
                .unwrap()
                .unregister_mod(mod_id);
            drop(loaded.library);
            self.load_order.retain(|id| id != mod_id);
            log::info!("Unloaded mod: {}", mod_id);
            Ok(())
        } else {
            Err(format!("Mod '{}' not found", mod_id))
        }
    }

    /// Reloads a mod by unloading and re-loading it.
    ///
    /// # Errors
    ///
    /// Returns an error if the mod is not found or cannot be unloaded.
    pub fn reload_mod(&mut self, mod_id: &str, host_api: &HostApi) -> Result<(), String> {
        let manifest = self
            .mods
            .get(mod_id)
            .map(|m| m.manifest.clone())
            .ok_or_else(|| format!("Mod '{}' not found", mod_id))?;

        let path = manifest.path.clone();

        self.unload_mod(mod_id)?;
        self.load_mod_internal(&path, manifest, host_api)?;

        log::info!("Reloaded mod: {}", mod_id);
        Ok(())
    }

    /// Returns the IDs of all currently loaded mods.
    pub fn loaded_mods(&self) -> Vec<&str> {
        self.mods.keys().map(|s| s.as_str()).collect()
    }

    /// Returns the manifest of a loaded mod.
    pub fn get_manifest(&self, mod_id: &str) -> Option<&ModManifest> {
        self.mods.get(mod_id).map(|m| &m.manifest)
    }
}