Skip to main content

ghook_macros/
lib.rs

1// ghook-macros 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-macros
7//!
8//! Procedural macros for the **ghook** modding framework.
9//!
10//! This crate provides the compile-time code generation that powers ghook:
11//!
12//! - [`#[hookable]`](attr.hookable.html) -- marks game functions as interceptable
13//! - [`#[prefix]`](attr.prefix.html) -- defines a hook that runs before the original
14//! - [`#[postfix]`](attr.postfix.html) -- defines a hook that runs after the original
15//! - [`#[replace]`](attr.replace.html) -- defines a hook that replaces the original
16//! - [`#[mod_info]`](attr.mod_info.html) -- embeds mod metadata in the binary
17//! - [`#[mod_init]`](attr.mod_init.html) -- marks the mod's entry point
18//! - [`use_game_hooks!`](macro.use_game_hooks.html) -- auto-generates types from game binary
19//!
20//! ## Note
21//!
22//! This crate is a proc-macro crate and cannot be used directly. Import these
23//! macros through [`ghook-sdk`](https://docs.rs/ghook-sdk) instead:
24//!
25//! ```rust,ignore
26//! use ghook_sdk::*; // Re-exports all macros
27//! ```
28//!
29//! ## License
30//!
31//! Licensed under the [Mozilla Public License 2.0](https://opensource.org/licenses/MPL-2.0).
32//!
33//! ## Author
34//!
35//! Semyon Tsarev
36
37use proc_macro::TokenStream;
38use quote::quote;
39use syn::{parse_macro_input, ItemFn, Expr, ExprLit, Lit, Token, Type, FnArg};
40use syn::punctuated::Punctuated;
41use syn::MetaNameValue;
42use syn::parse::Parse;
43
44// =============================================================================
45// HELPER FUNCTIONS
46// =============================================================================
47
48fn bytes_to_tokens(bytes: &[u8]) -> proc_macro2::TokenStream {
49    let tokens = bytes.iter().map(|b| quote! { #b });
50    quote! { [#(#tokens),*] }
51}
52
53fn to_pascal_case(s: &str) -> String {
54    s.split('_')
55        .map(|word| {
56            let mut chars = word.chars();
57            match chars.next() {
58                None => String::new(),
59                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
60            }
61        })
62        .collect()
63}
64
65/// Converts a `syn::Type` to a compact string representation without extra whitespace.
66///
67/// This is used for serializing type information into `.hooks_info` sections.
68/// Standard `quote!(#ty).to_string()` produces `"std :: string :: String"` with spaces,
69/// which breaks downstream parsing. This function produces `"String"` or `"u64"`.
70fn type_to_compact_string(ty: &syn::Type) -> String {
71    match ty {
72        syn::Type::Path(tp) => tp
73            .path
74            .segments
75            .iter()
76            .map(|seg| seg.ident.to_string())
77            .collect::<Vec<_>>()
78            .join("::"),
79        syn::Type::Reference(tr) => {
80            let inner = type_to_compact_string(&tr.elem);
81            if tr.mutability.is_some() {
82                format!("&mut {}", inner)
83            } else {
84                format!("&{}", inner)
85            }
86        }
87        syn::Type::Tuple(tt) => {
88            let elems: Vec<String> = tt.elems.iter().map(type_to_compact_string).collect();
89            format!("({})", elems.join(", "))
90        }
91        syn::Type::Array(ta) => {
92            let elem = type_to_compact_string(&ta.elem);
93            format!("[{}]", elem)
94        }
95        _ => quote!(#ty).to_string().replace(' ', ""),
96    }
97}
98
99/// Parses a type string (as serialized by `type_to_compact_string`) back into tokens.
100fn parse_type_string(s: &str) -> proc_macro2::TokenStream {
101    let cleaned = s.replace(" :: ", "::");
102
103    syn::parse_str::<syn::Type>(&cleaned)
104        .map(|ty| quote! { #ty })
105        .unwrap_or_else(|_| {
106            cleaned
107                .parse::<proc_macro2::TokenStream>()
108                .unwrap_or(quote! { () })
109        })
110}
111
112// =============================================================================
113// ATTRIBUTE PARSERS
114// =============================================================================
115
116struct ModInfoArgs {
117    id: String,
118    version: String,
119    requires: String,
120    load_after: String,
121    load_before: String,
122    incompatible_with: String,
123}
124
125impl Parse for ModInfoArgs {
126    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
127        let mut id = "unknown_mod".to_string();
128        let mut version = "0.1.0".to_string();
129        let mut requires = String::new();
130        let mut load_after = String::new();
131        let mut load_before = String::new();
132        let mut incompatible_with = String::new();
133
134        if input.is_empty() {
135            return Ok(Self {
136                id,
137                version,
138                requires,
139                load_after,
140                load_before,
141                incompatible_with,
142            });
143        }
144
145        let meta_list = Punctuated::<MetaNameValue, Token![,]>::parse_terminated(input)?;
146        for meta in meta_list {
147            if meta.path.is_ident("id") {
148                if let Expr::Lit(ExprLit {
149                    lit: Lit::Str(s), ..
150                }) = meta.value
151                {
152                    id = s.value();
153                }
154            } else if meta.path.is_ident("version") {
155                if let Expr::Lit(ExprLit {
156                    lit: Lit::Str(s), ..
157                }) = meta.value
158                {
159                    version = s.value();
160                }
161            } else if meta.path.is_ident("requires") {
162                if let Expr::Lit(ExprLit {
163                    lit: Lit::Str(s), ..
164                }) = meta.value
165                {
166                    requires = s.value();
167                }
168            } else if meta.path.is_ident("load_after") {
169                if let Expr::Lit(ExprLit {
170                    lit: Lit::Str(s), ..
171                }) = meta.value
172                {
173                    load_after = s.value();
174                }
175            } else if meta.path.is_ident("load_before") {
176                if let Expr::Lit(ExprLit {
177                    lit: Lit::Str(s), ..
178                }) = meta.value
179                {
180                    load_before = s.value();
181                }
182            } else if meta.path.is_ident("incompatible_with") {
183                if let Expr::Lit(ExprLit {
184                    lit: Lit::Str(s), ..
185                }) = meta.value
186                {
187                    incompatible_with = s.value();
188                }
189            }
190        }
191
192        Ok(Self {
193            id,
194            version,
195            requires,
196            load_after,
197            load_before,
198            incompatible_with,
199        })
200    }
201}
202
203struct HookArgs {
204    target: String,
205}
206
207impl Parse for HookArgs {
208    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
209        let mut target = "unknown".to_string();
210        if input.is_empty() {
211            return Ok(Self { target });
212        }
213        let meta_list = Punctuated::<MetaNameValue, Token![,]>::parse_terminated(input)?;
214        for meta in meta_list {
215            if meta.path.is_ident("target") {
216                if let Expr::Lit(ExprLit {
217                    lit: Lit::Str(s), ..
218                }) = meta.value
219                {
220                    target = s.value();
221                }
222            }
223        }
224        Ok(Self { target })
225    }
226}
227
228// =============================================================================
229// #[hookable]
230// =============================================================================
231
232/// Marks a function as hookable by mods.
233///
234/// Generates:
235/// - `#[repr(C)]` argument and result structures
236/// - A dispatcher that checks replace -> prefix -> original -> postfix
237/// - A `.hooks_info.<name>` binary section with type metadata
238///
239/// # Example
240///
241/// ```rust,ignore
242/// #[hookable]
243/// fn apply_damage(entity: u64, amount: f32) -> f32 {
244///     amount
245/// }
246/// ```
247///
248/// This generates `ApplyDamageArgs { entity: u64, amount: f32 }` and
249/// `ApplyDamageResult { value: f32 }` structures, plus a `.hooks_info.apply_damage`
250/// section containing `"entity:u64,amount:f32|f32"`.
251#[proc_macro_attribute]
252pub fn hookable(_attr: TokenStream, item: TokenStream) -> TokenStream {
253    let input = parse_macro_input!(item as ItemFn);
254    let fn_name = &input.sig.ident;
255
256    let pascal_name = to_pascal_case(&fn_name.to_string());
257    let args_struct = syn::Ident::new(&format!("{}Args", pascal_name), fn_name.span());
258    let res_struct = syn::Ident::new(&format!("{}Result", pascal_name), fn_name.span());
259    let impl_fn = syn::Ident::new(&format!("{}_impl", fn_name), fn_name.span());
260
261    let inputs = &input.sig.inputs;
262    let block = &input.block;
263    let out_ty = match &input.sig.output {
264        syn::ReturnType::Default => quote! { () },
265        syn::ReturnType::Type(_, ty) => quote! { #ty },
266    };
267
268    let fields = inputs.iter().filter_map(|a| {
269        if let syn::FnArg::Typed(p) = a {
270            Some(quote! { pub #p })
271        } else {
272            None
273        }
274    });
275
276    let arg_names: Vec<_> = inputs
277        .iter()
278        .filter_map(|a| {
279            if let syn::FnArg::Typed(p) = a {
280                Some(&p.pat)
281            } else {
282                None
283            }
284        })
285        .collect();
286
287    let arg_access = arg_names.iter().map(|name| quote! { args.#name });
288    let tgt = fn_name.to_string();
289
290    // Generate hook info metadata for .hooks_info section
291    let args_desc: Vec<String> = inputs
292        .iter()
293        .filter_map(|a| {
294            if let syn::FnArg::Typed(p) = a {
295                let name = match &*p.pat {
296                    syn::Pat::Ident(ident) => ident.ident.to_string(),
297                    _ => quote!(#p.pat).to_string(),
298                };
299                let ty = type_to_compact_string(&p.ty);
300                Some(format!("{}:{}", name, ty))
301            } else {
302                None
303            }
304        })
305        .collect();
306
307    let args_desc_str = args_desc.join(",");
308
309    let result_desc_str = match &input.sig.output {
310        syn::ReturnType::Default => "()".to_string(),
311        syn::ReturnType::Type(_, ty) => type_to_compact_string(ty),
312    };
313
314    let hook_info_str = format!("{}|{}", args_desc_str, result_desc_str);
315    let hook_info_bytes = hook_info_str.as_bytes();
316    let hook_info_len = hook_info_bytes.len();
317    let hook_info_tokens = bytes_to_tokens(hook_info_bytes);
318
319    let section_name = format!(".hooks_info.{}", fn_name);
320    let hook_info_static = syn::Ident::new(
321        &format!("__HOOK_INFO_{}", fn_name.to_string().to_uppercase()),
322        fn_name.span(),
323    );
324
325    quote! {
326        #[repr(C)]
327        pub struct #args_struct { #(#fields),* }
328
329        #[repr(C)]
330        pub struct #res_struct { pub value: #out_ty }
331
332        #[inline(never)]
333        fn #impl_fn(#inputs) -> #out_ty #block
334
335        #[used]
336        #[cfg_attr(target_os = "linux", link_section = #section_name)]
337        #[cfg_attr(target_os = "macos", link_section = "__DATA,__hooks_info")]
338        static #hook_info_static: [u8; #hook_info_len] = #hook_info_tokens;
339
340        pub fn #fn_name(#inputs) -> #out_ty {
341            let mut args = #args_struct { #(#arg_names),* };
342            let mut result = #res_struct { value: Default::default() };
343
344            const TARGET_HASH: u64 = ghook_sdk::hash_string_const(#tgt);
345            let mgr = ghook_sdk::get_hook_manager().read().unwrap();
346
347            if mgr.execute_replace(TARGET_HASH, &mut args, &mut result) {
348                return result.value;
349            }
350
351            match mgr.execute_prefix(TARGET_HASH, &mut args, &mut result) {
352                ghook_sdk::HookControl::SkipOriginal => {},
353                ghook_sdk::HookControl::Abort => return result.value,
354                ghook_sdk::HookControl::Continue => {
355                    result.value = #impl_fn(#(#arg_access),*);
356                }
357            }
358
359            mgr.execute_postfix(TARGET_HASH, &args, &mut result);
360            result.value
361        }
362    }
363    .into()
364}
365
366// =============================================================================
367// #[mod_info]
368// =============================================================================
369
370/// Embeds mod metadata into a dedicated binary section.
371///
372/// The metadata is readable by the mod loader without executing any mod code.
373///
374/// # Attributes
375///
376/// - `id` -- unique mod identifier (required)
377/// - `version` -- semantic version string (default: `"0.1.0"`)
378/// - `requires` -- comma-separated required mod IDs
379/// - `load_after` -- comma-separated mods that must load first
380/// - `load_before` -- comma-separated mods that must load after
381/// - `incompatible_with` -- comma-separated conflicting mod IDs
382///
383/// # Example
384///
385/// ```rust,ignore
386/// #[mod_info(
387///     id = "double_damage",
388///     version = "1.0.0",
389///     requires = "base_mod",
390///     incompatible_with = "no_damage_mod"
391/// )]
392/// ```
393#[proc_macro_attribute]
394pub fn mod_info(attr: TokenStream, item: TokenStream) -> TokenStream {
395    let args = parse_macro_input!(attr with ModInfoArgs::parse);
396    let item_tokens: proc_macro2::TokenStream = item.into();
397
398    let id_bytes = args.id.as_bytes();
399    let ver_bytes = args.version.as_bytes();
400    let req_bytes = args.requires.as_bytes();
401    let after_bytes = args.load_after.as_bytes();
402    let before_bytes = args.load_before.as_bytes();
403    let incompat_bytes = args.incompatible_with.as_bytes();
404
405    let id_len = id_bytes.len();
406    let ver_len = ver_bytes.len();
407    let req_len = req_bytes.len();
408    let after_len = after_bytes.len();
409    let before_len = before_bytes.len();
410    let incompat_len = incompat_bytes.len();
411
412    let id_tokens = bytes_to_tokens(id_bytes);
413    let ver_tokens = bytes_to_tokens(ver_bytes);
414    let req_tokens = bytes_to_tokens(req_bytes);
415    let after_tokens = bytes_to_tokens(after_bytes);
416    let before_tokens = bytes_to_tokens(before_bytes);
417    let incompat_tokens = bytes_to_tokens(incompat_bytes);
418
419    quote! {
420        #[allow(unsafe_code)]
421        mod __mod_info_export {
422            use super::*;
423
424            static MOD_ID_BYTES: [u8; #id_len] = #id_tokens;
425            static MOD_VERSION_BYTES: [u8; #ver_len] = #ver_tokens;
426            static MOD_REQUIRES_BYTES: [u8; #req_len] = #req_tokens;
427            static MOD_LOAD_AFTER_BYTES: [u8; #after_len] = #after_tokens;
428            static MOD_LOAD_BEFORE_BYTES: [u8; #before_len] = #before_tokens;
429            static MOD_INCOMPATIBLE_BYTES: [u8; #incompat_len] = #incompat_tokens;
430
431            #[used]
432            #[cfg_attr(target_os = "linux", link_section = ".mod_info")]
433            #[cfg_attr(target_os = "windows", link_section = ".modinfo")]
434            #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_info")]
435            #[no_mangle]
436            pub static MOD_INFO_SECTION: ghook_sdk::ModInfo = ghook_sdk::ModInfo {
437                magic: *b"RUSTMOD\x00",
438                api_version: 1,
439                id_ptr: MOD_ID_BYTES.as_ptr(),
440                id_len: #id_len,
441                version_ptr: MOD_VERSION_BYTES.as_ptr(),
442                version_len: #ver_len,
443                requires_ptr: MOD_REQUIRES_BYTES.as_ptr(),
444                requires_len: #req_len,
445                load_after_ptr: MOD_LOAD_AFTER_BYTES.as_ptr(),
446                load_after_len: #after_len,
447                load_before_ptr: MOD_LOAD_BEFORE_BYTES.as_ptr(),
448                load_before_len: #before_len,
449                incompatible_with_ptr: MOD_INCOMPATIBLE_BYTES.as_ptr(),
450                incompatible_with_len: #incompat_len,
451            };
452        }
453        #item_tokens
454    }
455    .into()
456}
457
458// =============================================================================
459// #[mod_init]
460// =============================================================================
461
462/// Marks a function as the mod's initialization entry point.
463///
464/// The function must take exactly one argument of type `&HostApi` and return `i32`.
465/// Returning `0` indicates success; any other value indicates failure.
466///
467/// # Example
468///
469/// ```rust,ignore
470/// #[mod_init]
471/// fn init(api: &HostApi) -> i32 {
472///     register_my_hooks(api);
473///     api.log_info("Mod loaded!");
474///     0
475/// }
476/// ```
477#[proc_macro_attribute]
478pub fn mod_init(_attr: TokenStream, item: TokenStream) -> TokenStream {
479    let input = parse_macro_input!(item as ItemFn);
480    let fn_name = &input.sig.ident;
481    let block = &input.block;
482    let output = &input.sig.output;
483
484    if input.sig.inputs.len() != 1 {
485        return syn::Error::new_spanned(
486            &input.sig.ident,
487            "mod_init must take exactly one argument: `api: &HostApi`",
488        )
489        .to_compile_error()
490        .into();
491    }
492
493    quote! {
494        fn #fn_name(api: &ghook_sdk::HostApi) #output #block
495
496        #[no_mangle]
497        #[export_name = "mod_init"]
498        pub extern "C" fn __mod_init_ffi_entry(host: *const ghook_sdk::HostApi) -> i32 {
499            if host.is_null() {
500                return -1;
501            }
502            #fn_name(unsafe { &*host })
503        }
504    }
505    .into()
506}
507
508// =============================================================================
509// #[prefix]
510// =============================================================================
511
512/// Defines a prefix hook that runs before the original function.
513///
514/// The hook receives mutable access to the arguments and can modify them
515/// before the original function executes.
516///
517/// # Arguments
518///
519/// - `target` -- name of the hookable function to intercept
520///
521/// # Function Signature
522///
523/// Must be `fn(args: &mut ArgsType) -> HookControl`.
524///
525/// # Example
526///
527/// ```rust,ignore
528/// #[prefix(target = "apply_damage")]
529/// fn double_damage(args: &mut ApplyDamageArgs) -> HookControl {
530///     args.amount *= 2.0;
531///     HookControl::Continue
532/// }
533/// ```
534#[proc_macro_attribute]
535pub fn prefix(attr: TokenStream, item: TokenStream) -> TokenStream {
536    let input = parse_macro_input!(item as ItemFn);
537    let args = parse_macro_input!(attr with HookArgs::parse);
538
539    let fn_name = &input.sig.ident;
540    let ffi_name = syn::Ident::new(&format!("{}_ffi", fn_name), fn_name.span());
541    let reg_name = syn::Ident::new(&format!("register_{}", fn_name), fn_name.span());
542    let target_bytes_name =
543        syn::Ident::new(&format!("__TARGET_BYTES_{}", fn_name), fn_name.span());
544
545    let target_bytes = args.target.as_bytes();
546    let target_len = target_bytes.len();
547    let block = &input.block;
548    let target_tokens = bytes_to_tokens(target_bytes);
549
550    let inner_type = match input.sig.inputs.first() {
551        Some(FnArg::Typed(pat_type)) => {
552            if let Type::Reference(ref type_ref) = *pat_type.ty {
553                &*type_ref.elem
554            } else {
555                &*pat_type.ty
556            }
557        }
558        Some(FnArg::Receiver(recv)) => {
559            return syn::Error::new_spanned(recv, "Prefix hooks cannot be methods.")
560                .to_compile_error()
561                .into();
562        }
563        _ => {
564            return syn::Error::new_spanned(&input.sig, "Prefix requires `args: &mut T`")
565                .to_compile_error()
566                .into();
567        }
568    };
569
570    quote! {
571        fn #fn_name(args: &mut #inner_type) -> ghook_sdk::HookControl #block
572
573        #[no_mangle]
574        pub extern "C" fn #ffi_name(
575            _ctx: *mut ghook_sdk::HookContext,
576            args: *mut std::ffi::c_void,
577            _res: *mut std::ffi::c_void,
578        ) -> u8 {
579            let args = unsafe { &mut *(args as *mut #inner_type) };
580            #fn_name(args) as u8
581        }
582
583        #[allow(non_upper_case_globals)]
584        static #target_bytes_name: [u8; #target_len] = #target_tokens;
585
586        pub fn #reg_name(host: &ghook_sdk::HostApi) {
587            const TARGET_HASH: u64 = ghook_sdk::hash_string_const(
588                unsafe { std::str::from_utf8_unchecked(&#target_bytes_name) }
589            );
590            (host.register_hook)(
591                TARGET_HASH,
592                0,
593                0,
594                #ffi_name as *const std::ffi::c_void,
595            );
596        }
597    }
598    .into()
599}
600
601// =============================================================================
602// #[postfix]
603// =============================================================================
604
605/// Defines a postfix hook that runs after the original function.
606///
607/// The hook receives read-only access to arguments and mutable access
608/// to the result, allowing it to modify the return value.
609///
610/// # Arguments
611///
612/// - `target` -- name of the hookable function to intercept
613///
614/// # Function Signature
615///
616/// Must be `fn(args: &ArgsType, result: &mut ResultType) -> HookControl`.
617///
618/// # Example
619///
620/// ```rust,ignore
621/// #[postfix(target = "get_player_name")]
622/// fn add_suffix(_args: &GetPlayerNameArgs, result: &mut String) -> HookControl {
623///     result.push_str("_GOD");
624///     HookControl::Continue
625/// }
626/// ```
627#[proc_macro_attribute]
628pub fn postfix(attr: TokenStream, item: TokenStream) -> TokenStream {
629    let input = parse_macro_input!(item as ItemFn);
630    let args = parse_macro_input!(attr with HookArgs::parse);
631
632    let fn_name = &input.sig.ident;
633    let ffi_name = syn::Ident::new(&format!("{}_ffi", fn_name), fn_name.span());
634    let reg_name = syn::Ident::new(&format!("register_{}", fn_name), fn_name.span());
635    let target_bytes_name =
636        syn::Ident::new(&format!("__TARGET_BYTES_{}", fn_name), fn_name.span());
637
638    let target_bytes = args.target.as_bytes();
639    let target_len = target_bytes.len();
640    let block = &input.block;
641    let target_tokens = bytes_to_tokens(target_bytes);
642
643    let (args_type, result_type) = match (
644        input.sig.inputs.iter().nth(0),
645        input.sig.inputs.iter().nth(1),
646    ) {
647        (Some(FnArg::Typed(p1)), Some(FnArg::Typed(p2))) => {
648            let t1 = if let Type::Reference(ref r) = *p1.ty {
649                &*r.elem
650            } else {
651                &*p1.ty
652            };
653            let t2 = if let Type::Reference(ref r) = *p2.ty {
654                &*r.elem
655            } else {
656                &*p2.ty
657            };
658            (t1, t2)
659        }
660        _ => {
661            return syn::Error::new_spanned(
662                &input,
663                "Postfix requires: fn(&T, &mut R) -> HookControl",
664            )
665            .to_compile_error()
666            .into();
667        }
668    };
669
670    quote! {
671        fn #fn_name(args: &#args_type, result: &mut #result_type) -> ghook_sdk::HookControl #block
672
673        #[no_mangle]
674        pub extern "C" fn #ffi_name(
675            _ctx: *mut ghook_sdk::HookContext,
676            args: *mut std::ffi::c_void,
677            result: *mut std::ffi::c_void,
678        ) -> u8 {
679            let args = unsafe { &*(args as *const #args_type) };
680            let result = unsafe { &mut *(result as *mut #result_type) };
681            #fn_name(args, result) as u8
682        }
683
684        #[allow(non_upper_case_globals)]
685        static #target_bytes_name: [u8; #target_len] = #target_tokens;
686
687        pub fn #reg_name(host: &ghook_sdk::HostApi) {
688            const TARGET_HASH: u64 = ghook_sdk::hash_string_const(
689                unsafe { std::str::from_utf8_unchecked(&#target_bytes_name) }
690            );
691            (host.register_hook)(
692                TARGET_HASH,
693                1,
694                0,
695                #ffi_name as *const std::ffi::c_void,
696            );
697        }
698    }
699    .into()
700}
701
702// =============================================================================
703// #[replace]
704// =============================================================================
705
706/// Defines a replace hook that completely substitutes the original function.
707///
708/// When a replace hook is registered, the original function is never called.
709/// The hook must return a value of the same type as the original function.
710///
711/// # Arguments
712///
713/// - `target` -- name of the hookable function to replace
714///
715/// # Function Signature
716///
717/// Must be `fn(args: &mut ArgsType) -> ReturnType`.
718///
719/// # Example
720///
721/// ```rust,ignore
722/// #[replace(target = "get_health")]
723/// fn god_mode_health(_args: &mut GetHealthArgs) -> i32 {
724///     999
725/// }
726/// ```
727#[proc_macro_attribute]
728pub fn replace(attr: TokenStream, item: TokenStream) -> TokenStream {
729    let input = parse_macro_input!(item as ItemFn);
730    let args = parse_macro_input!(attr with HookArgs::parse);
731
732    let fn_name = &input.sig.ident;
733    let ffi_name = syn::Ident::new(&format!("{}_ffi", fn_name), fn_name.span());
734    let reg_name = syn::Ident::new(&format!("register_{}", fn_name), fn_name.span());
735    let target_bytes_name =
736        syn::Ident::new(&format!("__TARGET_BYTES_{}", fn_name), fn_name.span());
737
738    let target_bytes = args.target.as_bytes();
739    let target_len = target_bytes.len();
740    let block = &input.block;
741    let target_tokens = bytes_to_tokens(target_bytes);
742
743    let (args_type, result_type) = match (&input.sig.inputs.first(), &input.sig.output) {
744        (Some(FnArg::Typed(p)), syn::ReturnType::Type(_, ty)) => {
745            let t = if let Type::Reference(ref r) = *p.ty {
746                &*r.elem
747            } else {
748                &*p.ty
749            };
750            (t, ty.clone())
751        }
752        _ => {
753            return syn::Error::new_spanned(&input, "Replace requires: fn(&mut T) -> R")
754                .to_compile_error()
755                .into();
756        }
757    };
758
759    quote! {
760        fn #fn_name(args: &mut #args_type) -> #result_type #block
761
762        #[no_mangle]
763        pub extern "C" fn #ffi_name(
764            _ctx: *mut ghook_sdk::HookContext,
765            args: *mut std::ffi::c_void,
766            result: *mut std::ffi::c_void,
767        ) -> u8 {
768            let args = unsafe { &mut *(args as *mut #args_type) };
769            let value = #fn_name(args);
770            unsafe { std::ptr::write(result as *mut #result_type, value); }
771            0
772        }
773
774        #[allow(non_upper_case_globals)]
775        static #target_bytes_name: [u8; #target_len] = #target_tokens;
776
777        pub fn #reg_name(host: &ghook_sdk::HostApi) {
778            const TARGET_HASH: u64 = ghook_sdk::hash_string_const(
779                unsafe { std::str::from_utf8_unchecked(&#target_bytes_name) }
780            );
781            (host.register_hook)(
782                TARGET_HASH,
783                2,
784                0,
785                #ffi_name as *const std::ffi::c_void,
786            );
787        }
788    }
789    .into()
790}
791
792// =============================================================================
793// ELF PARSER FOR use_game_hooks!
794// =============================================================================
795
796/// Reads sections with a given prefix from an ELF64 binary.
797///
798/// Returns a list of `(section_name_without_prefix, section_data)` pairs.
799fn read_elf_sections(data: &[u8], prefix: &str) -> Vec<(String, Vec<u8>)> {
800    let mut results = Vec::new();
801
802    // ELF magic check
803    if data.len() < 64 || &data[0..4] != b"\x7fELF" {
804        return results;
805    }
806
807    // Only support 64-bit ELF
808    if data[4] != 2 {
809        return results;
810    }
811
812    let e_shoff = u64::from_le_bytes(data[40..48].try_into().unwrap_or([0; 8])) as usize;
813    let e_shentsize = u16::from_le_bytes(data[58..60].try_into().unwrap_or([0; 2])) as usize;
814    let e_shnum = u16::from_le_bytes(data[60..62].try_into().unwrap_or([0; 2])) as usize;
815    let e_shstrndx = u16::from_le_bytes(data[62..64].try_into().unwrap_or([0; 2])) as usize;
816
817    if e_shoff == 0 || e_shnum == 0 || e_shentsize == 0 {
818        return results;
819    }
820
821    // Read section header string table
822    let shstr_offset = e_shoff + e_shstrndx * e_shentsize;
823    if shstr_offset + e_shentsize > data.len() {
824        return results;
825    }
826
827    let shstr_sh_offset = u64::from_le_bytes(
828        data[shstr_offset + 24..shstr_offset + 32]
829            .try_into()
830            .unwrap_or([0; 8]),
831    ) as usize;
832    let shstr_sh_size = u64::from_le_bytes(
833        data[shstr_offset + 32..shstr_offset + 40]
834            .try_into()
835            .unwrap_or([0; 8]),
836    ) as usize;
837
838    if shstr_sh_offset + shstr_sh_size > data.len() {
839        return results;
840    }
841    let shstrtab = &data[shstr_sh_offset..shstr_sh_offset + shstr_sh_size];
842
843    // Iterate over section headers
844    for i in 0..e_shnum {
845        let sh_offset = e_shoff + i * e_shentsize;
846        if sh_offset + e_shentsize > data.len() {
847            break;
848        }
849
850        let sh_name_idx = u32::from_le_bytes(
851            data[sh_offset..sh_offset + 4]
852                .try_into()
853                .unwrap_or([0; 4]),
854        ) as usize;
855
856        if sh_name_idx >= shstrtab.len() {
857            continue;
858        }
859
860        let name_end = shstrtab[sh_name_idx..]
861            .iter()
862            .position(|&b| b == 0)
863            .unwrap_or(0);
864        let section_name =
865            std::str::from_utf8(&shstrtab[sh_name_idx..sh_name_idx + name_end]).unwrap_or("");
866
867        if section_name.starts_with(prefix) {
868            let sh_offset_val = u64::from_le_bytes(
869                data[sh_offset + 24..sh_offset + 32]
870                    .try_into()
871                    .unwrap_or([0; 8]),
872            ) as usize;
873            let sh_size = u64::from_le_bytes(
874                data[sh_offset + 32..sh_offset + 40]
875                    .try_into()
876                    .unwrap_or([0; 8]),
877            ) as usize;
878
879            if sh_offset_val + sh_size <= data.len() {
880                let hook_name = section_name.trim_start_matches(prefix).to_string();
881                let section_data = data[sh_offset_val..sh_offset_val + sh_size].to_vec();
882                results.push((hook_name, section_data));
883            }
884        }
885    }
886
887    results
888}
889
890// =============================================================================
891// use_game_hooks! MACRO
892// =============================================================================
893
894/// Reads a game binary and auto-generates hook argument/result types.
895///
896/// This macro parses the `.hooks_info.*` sections embedded in the game binary
897/// by `#[hookable]` and generates matching `#[repr(C)]` structs and hash constants.
898///
899/// If the game changes a function signature, mods using this macro will fail
900/// to compile -- providing compile-time type safety for mod development.
901///
902/// # Arguments
903///
904/// An absolute path to the game binary (string literal).
905///
906/// # Generated Items
907///
908/// For each hookable function `foo_bar`:
909/// - `FooBarArgs` -- `#[repr(C)]` struct with the function's parameters
910/// - `FooBarResult` -- `#[repr(C)]` struct with a `value` field of the return type
911/// - `FOO_BAR_HASH` -- `u64` constant with the FNV-1a hash of the function name
912///
913/// # Example
914///
915/// ```rust,ignore
916/// use ghook_sdk::*;
917///
918/// // Generates ApplyDamageArgs, ApplyDamageResult, APPLY_DAMAGE_HASH, etc.
919/// use_game_hooks!("/home/user/games/my-game/target/release/my-game");
920///
921/// #[prefix(target = "apply_damage")]
922/// fn double_damage(args: &mut ApplyDamageArgs) -> HookControl {
923///     args.amount *= 2.0;
924///     HookControl::Continue
925/// }
926/// ```
927///
928/// # Errors
929///
930/// Produces a compile error if:
931/// - The binary cannot be read
932/// - No `.hooks_info.*` sections are found
933#[proc_macro]
934pub fn use_game_hooks(input: TokenStream) -> TokenStream {
935    let lit = parse_macro_input!(input as syn::LitStr);
936    let binary_path = lit.value();
937
938    let data = match std::fs::read(&binary_path) {
939        Ok(d) => d,
940        Err(e) => {
941            return syn::Error::new(
942                lit.span(),
943                format!("Failed to read game binary '{}': {}", binary_path, e),
944            )
945            .to_compile_error()
946            .into();
947        }
948    };
949
950    let sections = read_elf_sections(&data, ".hooks_info.");
951
952    if sections.is_empty() {
953        return syn::Error::new(
954            lit.span(),
955            format!(
956                "No .hooks_info sections found in '{}'. Is this a ghook-enabled game?",
957                binary_path
958            ),
959        )
960        .to_compile_error()
961        .into();
962    }
963
964    let mut generated = Vec::new();
965
966    for (hook_name, section_data) in &sections {
967        let info_str = String::from_utf8_lossy(section_data);
968        let parts: Vec<&str> = info_str.split('|').collect();
969
970        if parts.len() != 2 {
971            continue;
972        }
973
974        let args_str = parts[0];
975        let result_str = parts[1];
976
977        let pascal_name = to_pascal_case(hook_name);
978        let args_struct_name = syn::Ident::new(&format!("{}Args", pascal_name), lit.span());
979        let result_struct_name = syn::Ident::new(&format!("{}Result", pascal_name), lit.span());
980
981        let mut fields = Vec::new();
982        if !args_str.is_empty() {
983            for arg in args_str.split(',') {
984                let arg_parts: Vec<&str> = arg.splitn(2, ':').collect();
985                if arg_parts.len() == 2 {
986                    let field_name = syn::Ident::new(arg_parts[0].trim(), lit.span());
987                    let field_type = parse_type_string(arg_parts[1].trim());
988                    fields.push(quote! { pub #field_name: #field_type });
989                }
990            }
991        }
992
993        let result_type = parse_type_string(result_str.trim());
994
995        let hash_value = {
996            let mut hash: u64 = 0xcbf29ce484222325;
997            for byte in hook_name.bytes() {
998                hash ^= byte as u64;
999                hash = hash.wrapping_mul(0x100000001b3);
1000            }
1001            hash
1002        };
1003
1004        let hash_const_name =
1005            syn::Ident::new(&format!("{}_HASH", hook_name.to_uppercase()), lit.span());
1006
1007        generated.push(quote! {
1008            #[repr(C)]
1009            #[derive(Debug, Clone)]
1010            pub struct #args_struct_name {
1011                #(#fields),*
1012            }
1013
1014            #[repr(C)]
1015            #[derive(Debug, Clone)]
1016            pub struct #result_struct_name {
1017                pub value: #result_type,
1018            }
1019
1020            pub const #hash_const_name: u64 = #hash_value;
1021        });
1022    }
1023
1024    quote! {
1025        // Auto-generated by ghook from: #binary_path
1026        #(#generated)*
1027    }
1028    .into()
1029}