Написал код для установки 5-и байтового jmp хука. Переводить в библиотеку не вижу…
- User
Написал код для установки 5-и байтового jmp хука. Переводить в библиотеку не вижу смысла, так что нужно просто скопировать его. upd:или вижу... если хочется вариант с либой - https://www.blast.hk/threads/55743/ Хуки при завершении скрипта сами снимутся Lua: --HOOKS local hook = {hooks = {}} addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(hook.hooks) do if hook.status then hook.stop() end end end end) ffi.cdef [[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) --off jit compilation | thx FYP local size = size or 5 local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end --HOOKS Что нужно для использования? Знать FFI Знать прототип функции Знать адрес функции Использование Для примера установим хук на showDialog Его прототип C++: void(__thiscall *)(void *this, uint16_t wID, uint8_t iStyle, char *szCaption, char *szText, char *szButton1, char *szButton2, bool bSend) И его адрес Lua: getModuleHandle('samp.dll') + 0x6B9C0 Это все что нужно, для установки хука используем Lua: tableHook = hook.new(прототип, калбэк, адрес, размер) --Размер по умолчанию = 5 Эта функция устанавливает хук и возвращает таблицу с управлением над ним, ее методы Lua: tableHook.status --статус хука(true/false) tableHook.start() -- устанавливает хук tableHook.stop() -- снимает хук res = tableHook.call(...) --вызывает оригинальную функцию, если не void - возвратит результат res = tableHook(...) --снимает хук, вызывает оригинальную ф-ю и ставит обратно --То есть tableHook(...) = stop() call(...) start() Пишем код Обязательно подключаем библиотеку ffi Lua: local ffi = require 'ffi' Пишем колбэк для хука по прототипу Lua: --void(__thiscall *)(void *this, uint16_t wID, uint8_t iStyle, char *szCaption, char *szText, char *szButton1, char *szButton2, bool bSend) function dialogHook(this, id, style, caption, text, button1, button2, send) print(id, style, ffi.string(caption), ffi.string(text), ffi.string(button1), ffi.string(button2), send) --выводим параметры с которыми была вызвана оригинальная функция end И ставим хук Lua: function main() dialogHook = hook.new('void(__thiscall *)(void *this, uint16_t wID, uint8_t iStyle, char *szCaption, char *szText, char *szButton1, char szButton2, bool bSend)', dialogHook, getModuleHandle('samp.dll') + 0x6B9C0) --Узнать его статус можно так dialogHook.status end Все хук установлен и работает, но диалог не показывается. Чтобы он показался: нужно снять хук, вызвать оригинальную функцию и поставить обратно хук, для этого изменяем калбэк Lua: function dialogHook(this, id, style, caption, text, button1, button2, send) print(id, style, ffi.string(caption), ffi.string(text), ffi.string(button1), ffi.string(button2), send) dialogHook(this, id, style, caption, text, button1, button2, send) --Или --dialogHook.stop() --dialogHook.call(this, id, style, caption, text, button1, button2, send) --dialogHook.start() end Можем подменить заголовок диалога Lua: function dialogHook(this, id, style, caption, text, button1, button2, send) dialogHook(this, id, style, ffi.cast('char', ffi.string(caption)..' | Hooked'), text, button1, button2, send) --К заголовку диалога будет дописываться " | Hooked" end Полный код
Lua: local ffi = require 'ffi' --HOOKS local hook = {hooks = {}} addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(hook.hooks) do if hook.status then hook.stop() end end end end) ffi.cdef [[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) --off jit compilation | thx FYP local size = size or 5 local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end --HOOKS
function main() dialogHook = hook.new('void(__thiscall *)(void *this, uint16_t wID, uint8_t iStyle, char *szCaption, char *szText, char *szButton1, char *szButton2, bool bSend)', dialogHook, getModuleHandle('samp.dll') + 0x6B9C0) end
function dialogHook(this, id, style, caption, text, button1, button2, send) dialogHook(this, id, style, ffi.cast('char*', ffi.string(caption)..' | Hooked'), text, button1, button2, send) end При таком хуке для вызова диалога можно использовать sampShowDialog(...) или dialogHook.call(...) (в этом случае нужно еще передать указатель this первым параметром, т.к. функция thiscall, если что, то это sampDialogInfoPtr)
И еще один пример по хук win api функции Lua: function main() local res, addr = getDynamicLibraryProcedure("MessageBoxA", getModuleHandle('user32.dll')) if not res then return end msgBoxHook = hook.new('int (__stdcall *)(void *w, const char *txt, const char *cap, int type)', msgBoxHook, addr)
--Вызываем для теста msgbox ffi.cdef[[ int MessageBoxA(void *w, const char *txt, const char *cap, int type); ]] ffi.C.MessageBoxA(nil, "Hello world!", "Test", 0) --Или просто msgBoxHook.call(nil, "Hello world!", "Test", 0)end
function msgBoxHook(w, txt, cap, type) print(w, ffi.string(txt), ffi.string(cap), type) return msgBoxHook(w, txt, cap, type) --Т.к. функцию в прототипе указано int, а не void, нужно вернуть результат end
используй этот код поставь хук сюда
// 0x5429F0 void CPhysical::ApplyMoveForce(CVector force) { if (!physicalFlags.bInfiniteMass && !physicalFlags.bDisableMoveForce) { if (physicalFlags.bDisableZ) force.z = 0.0f; m_vecMoveSpeed += force / m_fMass; } }
- Assistant
To hook the function
CPhysical::ApplyMoveForceat the address0x5429F0using the Lua code you provided, you would need to do the following modifications:- Set up the Lua environment with FFI and ensure the hook system is ready.
- Define the callback function in Lua to be triggered when
ApplyMoveForceis called. - Use the hook system to connect your Lua callback to the target function.
Here's how the code would look:
local ffi = require 'ffi' -- Ensure that the necessary Windows API functions are accessible ffi.cdef [[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] -- Define the hook system as outlined in the provided code local hook = {hooks = {}} addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(hook.hooks) do if hook.status then hook.stop() end end end end) function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) local size = size or 5 local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end -- Hooking the CPhysical::ApplyMoveForce function function main() local applyMoveForceAddr = 0x5429F0 -- The address you've indicated local hook_cast = 'void(__thiscall *)(void *this, CVector force)' -- Function prototype applyMoveForceHook = hook.new(hook_cast, applyMoveForceCallback, applyMoveForceAddr) print("Hook set on CPhysical::ApplyMoveForce at address ", string.format("0x%X", applyMoveForceAddr)) end -- Define the callback function for the hook function applyMoveForceCallback(this, force) -- Log the vector force being applied for debugging print("ApplyMoveForce called with force: ", force.x, force.y, force.z) -- Optionally, modify the force or perform additional operations here -- Call the original function to ensure normal execution applyMoveForceHook(this, force) end main()In this setup:
- Replace
CVectorwith the appropriate FFI structure definition if it's not defined elsewhere. Ensure FFI is aware of what aCVectoris. - The
applyMoveForceCallbackfunction can be modified to inspect or modify theforceparameter as needed. - The address
0x5429F0is used directly as specified, and the hook should correctly insert your callback in place of the original function.
This Lua code should hook into the designated function, apply any desired changes via the callback, and allow you to monitor or alter the behavior of
CPhysical::ApplyMoveForce. Just ensure that all data types and addresses are accurate and that you handle any necessary Lua to C data conversions. - User
[ML] (error) (lol).lua: ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:110: declaration specifier expected near 'CVector' stack traceback: [C]: in function 'cast' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:110: in function 'new' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:145: in function 'main' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:160: in main chunk [ML] (error) (lol).lua: Script died due to an error. (4970A124)
- Assistant
The error you are encountering indicates that the FFI does not recognize the
CVectortype used in the prototype cast for the hook. To resolve this issue, you need to define what aCVectoris using the FFI before you try to use it in function prototypes or in any FFI operations.Here's how you can define
CVectorusing FFI:- Define the
CVectorstructure: Add a definition forCVectorin your Lua script before you attempt to use it in any FFI context. You need to understand the definition ofCVectorthat matches the game's internal structure:
local ffi = require 'ffi' -- Define the CVector structure, assuming it has x, y, and z as float members ffi.cdef [[ typedef struct { float x; float y; float z; } CVector; ]] -- Proceed with the rest of the setup -- Ensure that the necessary Windows API functions are accessible ffi.cdef [[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] -- Define the hook system as outlined in the provided code local hook = {hooks = {}} addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(hook.hooks) do if hook.status then hook.stop() end end end end) function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) local size = size or 5 local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end -- Hooking the CPhysical::ApplyMoveForce function function main() local applyMoveForceAddr = 0x5429F0 -- The address you've indicated local hook_cast = 'void(__thiscall *)(void *this, CVector force)' -- Function prototype applyMoveForceHook = hook.new(hook_cast, applyMoveForceCallback, applyMoveForceAddr) print("Hook set on CPhysical::ApplyMoveForce at address ", string.format("0x%X", applyMoveForceAddr)) end -- Define the callback function for the hook function applyMoveForceCallback(this, force) -- Log the vector force being applied for debugging print("ApplyMoveForce called with force: ", force.x, force.y, force.z) -- Optionally, modify the force or perform additional operations here -- Call the original function to ensure normal execution applyMoveForceHook(this, force) end main()Key Adjustments:
- The
CVectortype is defined as a struct that contains three floats:x,y, andz. This matches the likely internal representation of a 3D vector in the game's memory structure. - Ensure that the
CVectorstruct layout precisely matches the game's internal memory struct, as assumptions can lead to improper memory access and undefined behavior. - After defining the structure, you can cast and pass
CVectortypes when using FFI.
If the
CVectordefinition you have in mind differs from the above, adjust thetypedef struct { ... } CVector;portion accordingly. This should resolve the error and allow you to use FFI to interact with the game's functions correctly. - Define the
- User
[ML] (error) (lol).lua: ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:24: declaration specifier expected near 'CVector' stack traceback: [C]: in function 'cast' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:24: in function 'new' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:59: in function 'main' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:74: in main chunk [ML] (error) (lol).lua: Script died due to an error. (0546290C)
кажется у меня нет CVector?
- Assistant
The error message you're seeing suggests that
CVectoris not recognized by the FFI. In order to useCVector, we need to define it within your Lua script using the FFI interface. Let's defineCVectorbased on what a typical 3D vector could be structured like in C++:Here's an outline of how you can define it:
local ffi = require 'ffi' -- Define the CVector structure, typically containing three floats for x, y, and z coordinates ffi.cdef [[ typedef struct { float x; float y; float z; } CVector; ]] -- Make sure you also include necessary Windows API functions ffi.cdef [[ int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] -- Define your hook system as needed local hook = {hooks = {}} addEventHandler('onScriptTerminate', function(scr) if scr == script.this then for i, hook in ipairs(hook.hooks) do if hook.status then hook.stop() end end end end) function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) local size = size or 5 local new_hook = {} local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end -- Hooking the CPhysical::ApplyMoveForce function function main() local applyMoveForceAddr = 0x5429F0 -- The address you've indicated local hook_cast = 'void(__thiscall *)(void *this, CVector force)' -- Function prototype using CVector applyMoveForceHook = hook.new(hook_cast, applyMoveForceCallback, applyMoveForceAddr) print("Hook set on CPhysical::ApplyMoveForce at address ", string.format("0x%X", applyMoveForceAddr)) end -- Define the callback function for the hook function applyMoveForceCallback(this, force) -- Log the vector force being applied for debugging print("ApplyMoveForce called with force: ", force.x, force.y, force.z) -- Optionally, modify the force or perform additional operations here -- Call the original function to ensure normal execution applyMoveForceHook(this, force) end main()Key Points:
-
Defining CVector: In this code,
CVectoris defined as astructwith three members:x,y, andz, which are all of typefloat. This matches a typical 3D vector layout. -
Function Prototype: We're using this C-style definition in the function prototype for your hook. Ensure this matches the actual function signature expected by the game or library you are interfacing with.
-
Debugging Output: Use print statements to verify that data is being passed and handled correctly.
Before running this script, ensure the definition of
CVectoraligns with the actual data structure used by the game. IfCVectorhas a different structure (like additional fields), you'll need to adjust the definition accordingly. If there are further issues, double-check the memory address0x5429F0and other parts of the setup to confirm that they are correct for your use case. -
- Assistant
It seems like your message was cut off. Could you please provide more details or clarify your question? If you're experiencing further issues or have more questions about using FFI, hooking, or defining C structures in Lua, feel free to ask!
- User
[ML] (error) (lol).lua: ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:33: cannot convert 'function' to 'void (*)()' stack traceback: [C]: in function 'cast' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:33: in function 'new' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:68: in function 'main' ...rs\username\Desktop\GTA San Andreas\moonloader(lol).lua:83: in main chunk [ML] (error) (lol).lua: Script died due to an error. (0546290C)
- Assistant
The error message you're encountering suggests that there is an issue with how LuaJIT's FFI is handling the conversion of a Lua function to a C function pointer. Specifically, it seems that the callback function isn't being cast correctly.
To address this issue, ensure that:
- Callback Signature Matches the Prototype: The prototype string you use must match exactly how the function is expected to be called, including calling conventions and parameter types.
- Function Signature in Lua: The Lua callback must match the signature defined in the
hook.newcall.
Let's go through the code to find possible issues:
Ensuring Compatibility
When dealing with C functions and function pointers, it is critical that the types and prototypes match exactly. In your case, the function
CPhysical::ApplyMoveForceuses the__thiscallconvention and takes a reference to aCVector, a structure you defined as:ffi.cdef [[ typedef struct { float x; float y; float z; } CVector; ]]Callback Signature
Here's how you ensure that the callback function's signature matches what is expected:
- Function Definition for Hooking: Double-check that the
hook_castparameter provided is correct forCPhysical::ApplyMoveForce. The Lua function should mimic this signature.
Here’s a code snippet for setting the hook:
-- Lua script using FFI to hook C function local ffi = require 'ffi' -- FFI structure and functions ffi.cdef [[ typedef struct { float x; float y; float z; } CVector; int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect); ]] -- Hook management local hook = {hooks = {}} -- Function to set hooks function hook.new(cast, callback, hook_addr, size) jit.off(callback, true) -- Ensure JIT is off for the callback local size = size or 5 local new_hook = {} -- Cast the Lua function to a C function pointer local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback)))) -- Other necessary operations for hooking local void_addr = ffi.cast('void*', hook_addr) local old_prot = ffi.new('unsigned long[1]') local org_bytes = ffi.new('uint8_t[?]', size) ffi.copy(org_bytes, void_addr, size) local hook_bytes = ffi.new('uint8_t[?]', size, 0x90) hook_bytes[0] = 0xE9 ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5 new_hook.call = ffi.cast(cast, hook_addr) new_hook.status = false local function set_status(bool) new_hook.status = bool ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot) ffi.copy(void_addr, bool and hook_bytes or org_bytes, size) ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot) end new_hook.stop = function() set_status(false) end new_hook.start = function() set_status(true) end new_hook.start() table.insert(hook.hooks, new_hook) return setmetatable(new_hook, { __call = function(self, ...) self.stop() local res = self.call(...) self.start() return res end }) end -- Hook the function function main() local applyMoveForceAddr = 0x5429F0 -- The address you've indicated local hook_cast = 'void(__thiscall *)(void *this, CVector force)' -- Function prototype applyMoveForceHook = hook.new(hook_cast, applyMoveForceCallback, applyMoveForceAddr) print("Hook set on CPhysical::ApplyMoveForce at address ", string.format("0x%X", applyMoveForceAddr)) end -- The hook callback implementation function applyMoveForceCallback(this, force) -- Logging and modifications print("ApplyMoveForce called with force: ", force.x, force.y, force.z) -- Example modification (if needed) -- force.x, force.y, force.z = force.x * 2, force.y * 2, force.z * 2 -- Call the original function applyMoveForceHook(this, force) end main()Key Points:
- Matching Callback: Ensure the Lua function
applyMoveForceCallbackis correctly declared and used inhook.new. - JIT Disabled: Use
jit.off(callback, true)to prevent JIT compilation issues, ensuring the callback matches the C calling convention. - Set up Hooks Correctly: The address, size, and other configuration parameters should be correctly defined and accurately reflect the environment you are working within.
By following these guidelines and adjustments, you should be able to resolve the error and establish the function hook correctly. If further issues arise, confirm that the types and calling conventions are fully compatible with the original function’s signature.