Skip to content

Hook virtual functions by offset #617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 30 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
8284e52
feat: `CreateValveFunctionByOffset`
KillStr3aK Oct 9, 2024
679ce6c
feat: overloaded constructor
KillStr3aK Oct 9, 2024
73fe4ff
feat: now inherits from `MemoryFunction*`
KillStr3aK Oct 9, 2024
05fde7c
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 11, 2024
3ddc0ba
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 13, 2024
033d69a
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 17, 2024
0f4b855
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 17, 2024
077d1eb
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 19, 2024
96489f3
Merge branch 'main' into virtual-hooks
KillStr3aK Oct 21, 2024
8d60cf9
Merge branch 'main' into virtual-hooks
KillStr3aK Nov 6, 2024
78639d4
Merge branch 'main' into virtual-hooks
KillStr3aK Nov 13, 2024
e56eb54
Merge branch 'main' into virtual-hooks
KillStr3aK Nov 26, 2024
dc87751
Merge branch 'main' into virtual-hooks
KillStr3aK Dec 3, 2024
d999bf1
Merge branch 'main' into virtual-hooks
KillStr3aK Jan 5, 2025
a385a67
Merge branch 'main' into virtual-hooks
KillStr3aK Jan 16, 2025
3764434
Merge branch 'main' into virtual-hooks
KillStr3aK Jan 25, 2025
21dac44
Merge branch 'main' into virtual-hooks
KillStr3aK Jan 27, 2025
9e09709
Merge branch 'main' into virtual-hooks
KillStr3aK Jan 30, 2025
f1703ec
Merge branch 'roflmuffin:main' into virtual-hooks
KillStr3aK May 10, 2025
d9dcb7e
fix: disambiguate virtual functions by offset
KillStr3aK May 10, 2025
a789b0f
chore: removed unused import
KillStr3aK May 10, 2025
4624aed
feat: CModule::FindVirtualTable
KillStr3aK May 12, 2025
415dace
feat: implemented new natives
KillStr3aK May 12, 2025
106c9cd
feat: vtables can now be accessed without an instance
KillStr3aK May 12, 2025
0006d03
feat: created example plugin
KillStr3aK May 12, 2025
cc16cf3
Merge branch 'main' into virtual-hooks
KillStr3aK May 12, 2025
2c28db9
fix: unhook correct method
KillStr3aK May 13, 2025
81f188b
tweak: removed symbol ctors from VTable<TClass>
KillStr3aK May 13, 2025
ab31593
feat: windows and linux implementation of CModule::FindVirtualTable
KillStr3aK May 15, 2025
048f86c
Merge branch 'virtual-hooks' of https://github.com/KillStr3aK/Counter…
KillStr3aK May 15, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions examples/WithVirtualFunctions/WithVirtualFunctions.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
</ItemGroup>

</Project>
146 changes: 146 additions & 0 deletions examples/WithVirtualFunctions/WithVirtualFunctionsPlugin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using CounterStrikeSharp.API.Modules.Utils;

using Microsoft.Extensions.Logging;

namespace WithVTableHooks;

public class WithVirtualFunctionsPlugin : BasePlugin
{
public override string ModuleName => "Example: With Virtual Functions";
public override string ModuleVersion => "1.0.0";
public override string ModuleAuthor => "CounterStrikeSharp & Contributors";
public override string ModuleDescription => "A simple plugin that hooks virtual functions by signature and offset";

// There are 3 ways to access a virtual function:
// 1 -> By signature
// 2 -> By the vtable offset (index) and an instance of the class
// 3 -> By the vtable offset (index) and without an instance of the class, but you need to know the vtable symbol

// In this example, we are going to cover each method.
// Note: we won't cover RE here.

// 1 -> Working with a signature:

// this example shows that you can just pass the signature of the function
// Note: CS# assumes the server binary by default. there are overloads that allow you to specify a different binary.
// this example will continue inside the "Load" method.
private static VirtualFunctionVoid<CCSPlayerController, CsTeam> CCSPlayerController_SwitchTeam = new(GameData.GetSignature("CCSPlayerController_SwitchTeam"));

// 2 -> Working with a vtable offset and an instance of the class
// Since we need an active instance of the class, we can only declare our virtual function here, and the rest of the code will be inside the "Load" method.
// Declare it as a nullable type, because we only set a value when this is being used.
private static VirtualFunctionVoid<CCSPlayer_ItemServices, string, CEntityInstance>? CCSPlayer_ItemServices_GiveNamedItem;

// 3 -> Working with a vtable offset without an instance:

// this example shows that you can just pass the offset of the function, and CS# will automatically gather the VTable and access the function at the given offset.
// Note: CS# assumes the server binary by default. there are overloads that allow you to specify a different binary.
// Note: here, CS# uses the 'CCSPlayerController' (TArg1) argument type name as the "vtable symbol" and you should only rely on this if you know what you are doing.
// Note: if you need more freedom, there are other variants that supports custom parameters. (Check below)
private static VirtualFunctionVoid<CCSPlayerController, CsTeam> CCSPlayerController_ChangeTeam = new(GameData.GetOffset("CCSPlayerController_ChangeTeam"));

// this example is pretty much the same as above, but you should prefer this method if you are not using explicit types, or the vtable symbol is not the same as a predefined class name. (usually when you use 'nint' instead)
// Note: you can still use the `CCSPlayerController` as TArg1, the main point here is if you explicitly set the vtable symbol name, then that value will be used and CS# will NOT use the TArg1 type name.
private static VirtualFunctionVoid<nint, CsTeam> CCSPlayerController_Respawn = new("CCSPlayerController", GameData.GetOffset("CCSPlayerController_Respawn"));

// this is still the same, the main point here is that you can set the vtable symbol, binary path, and the offset.
// private static VirtualFunctionVoid<nint, int> Random_Function = new("VTABLE_SYMBOL_IN_ENGINE_BINARY", Addresses.EnginePath, 51); // this offset is a random example here

private static VirtualFunctionWithReturn<CCSGameRules, CBasePlayerController, CBaseEntity?>? CCSGameRules_FindPickerEntity;

// Also there are wrapper classes that you can use:
// Note that this class actually holds the vtable ptr. (.Handle)
// VTable CCSGameRules_VTable_Symbol = new VTable("CCSGameRules"); // this will look for "CCSGameRules" vtable symbol, and if found, you can use this class to retrieve the functions.

// this is the same as above, but CS# here will use the `TClass` type name as the vtable symbol, and when you retrieve functions, you don't have to specify the TArg1 each time, just the parameters.
VTable<CCSGameRules> CCSGameRules_VTable = new VTable<CCSGameRules>();

// examples can be found in the load method.

public override void Load(bool hotReload)
{
// 1 -> By signature
// setup a hook on the virtual function that we got using the signature.
CCSPlayerController_SwitchTeam.Hook(OnSwitchTeam, HookMode.Pre);

// 2 -> By the vtable offset (index) and an instance of the class
// so we need to somehow get an instance of `CCSPlayer_ItemServices`, the following code will be a random example and it depends on context.

AddCommand("vfunc_2", "Example way of accessing a virtual function", (controller, info) =>
{
// we don't want to setup the same thing over and over again
if (CCSPlayer_ItemServices_GiveNamedItem != null)
return;

// sanity checks are up to you
if (controller == null || !controller.IsValid || controller.IsBot || controller.PlayerPawn.Value == null)
return;

if (controller.PlayerPawn.Value.ItemServices == null)
return;

// as you can see we used an active instance of the class (controller.PlayerPawn.Value.ItemServices) to access the virtual function.
// if you hook this function, any and every call to it will be intercepted, regardless of the instance.
// in this way, the instance is only needed to access the function through the vtable.
CCSPlayer_ItemServices_GiveNamedItem = new(controller.PlayerPawn.Value.ItemServices, GameData.GetOffset("CCSPlayer_ItemServices_GiveNamedItem"));
CCSPlayer_ItemServices_GiveNamedItem.Hook(OnGiveNamedItem, HookMode.Pre);
});

// 3 -> By the vtable offset (index) and without an instance of the class

// we have already created our virtual function, so we can just use it here.
CCSPlayerController_ChangeTeam.Hook(OnChangeTeam, HookMode.Pre);

// Wrapper examples

// when using the generic variant of the VTable class, you only need to pass the generic parameters of the function, TArg1 is assumed to be `CCSGameRules`
CCSGameRules_FindPickerEntity = CCSGameRules_VTable.GetFunctionWithReturn<CBasePlayerController, CBaseEntity?>(GameData.GetOffset("CCSGameRules_FindPickerEntity"));
CCSGameRules_FindPickerEntity.Hook(OnFindPickerEntity, HookMode.Pre);

// and when you are not using the generic variant, you also need to pass the `CCSGameRules` each time.
// CCSGameRules_VTable_Symbol.GetFunctionWithReturn<CCSGameRules, CBasePlayerController, CBaseEntity?>(GameData.GetOffset("CCSGameRules_FindPickerEntity")).Hook(OnFindPickerEntity, HookMode.Pre);
}

private HookResult OnChangeTeam(DynamicHook hook)
{
Logger.LogInformation("ON CHANGE TEAM");
return HookResult.Continue;
}

private HookResult OnGiveNamedItem(DynamicHook hook)
{
string itemName = hook.GetParam<string>(1);
Logger.LogInformation("ON GIVE NAMED ITEM {0}", itemName);
return HookResult.Continue;
}

private HookResult OnSwitchTeam(DynamicHook hook)
{
Logger.LogInformation("ON SWITCH TEAM");
return HookResult.Continue;
}

private HookResult OnFindPickerEntity(DynamicHook hook)
{
Logger.LogInformation("ON FIND PICKER ENTITY");
return HookResult.Continue;
}

public override void Unload(bool hotReload)
{
// Dont forget to release your hooks

// 1 -> By signature
CCSPlayerController_SwitchTeam.Unhook(OnSwitchTeam, HookMode.Pre);

// 2 -> By the vtable offset (index) and an instance of the class
CCSPlayer_ItemServices_GiveNamedItem?.Unhook(OnGiveNamedItem, HookMode.Pre);

//3 -> By the vtable offset (index) and without an instance of the class
CCSPlayerController_ChangeTeam.Unhook(OnChangeTeam, HookMode.Pre);
CCSGameRules_FindPickerEntity?.Unhook(OnFindPickerEntity, HookMode.Pre);
}
}
49 changes: 49 additions & 0 deletions managed/CounterStrikeSharp.API/Core/API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,43 @@ public static IntPtr CreateVirtualFunctionBySignature(IntPtr pointer, string bin
}
}

public static IntPtr CreateVirtualFunctionBySymbol(string binaryname, string symbolname, int vtableoffset, int numarguments, int returntype, object[] arguments){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(binaryname);
ScriptContext.GlobalScriptContext.Push(symbolname);
ScriptContext.GlobalScriptContext.Push(vtableoffset);
ScriptContext.GlobalScriptContext.Push(numarguments);
ScriptContext.GlobalScriptContext.Push(returntype);
foreach (var obj in arguments)
{
ScriptContext.GlobalScriptContext.Push(obj);
}
ScriptContext.GlobalScriptContext.SetIdentifier(0xF873189F);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
return (IntPtr)ScriptContext.GlobalScriptContext.GetResult(typeof(IntPtr));
}
}

public static IntPtr CreateVirtualFunctionFromVTable(IntPtr pointer, int vtableoffset, int numarguments, int returntype, object[] arguments){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(pointer);
ScriptContext.GlobalScriptContext.Push(vtableoffset);
ScriptContext.GlobalScriptContext.Push(numarguments);
ScriptContext.GlobalScriptContext.Push(returntype);
foreach (var obj in arguments)
{
ScriptContext.GlobalScriptContext.Push(obj);
}
ScriptContext.GlobalScriptContext.SetIdentifier(0xE9D17E63);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
return (IntPtr)ScriptContext.GlobalScriptContext.GetResult(typeof(IntPtr));
}
}

public static void HookFunction(IntPtr function, InputArgument hook, bool post){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
Expand Down Expand Up @@ -1154,6 +1191,18 @@ public static IntPtr FindSignature(string modulepath, string signature){
}
}

public static IntPtr FindVirtualTable(string binarypath, string symbolname){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(binarypath);
ScriptContext.GlobalScriptContext.Push(symbolname);
ScriptContext.GlobalScriptContext.SetIdentifier(0xEA506CFF);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
return (IntPtr)ScriptContext.GlobalScriptContext.GetResult(typeof(IntPtr));
}
}

public static int GetNetworkVectorSize(IntPtr vec){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CounterStrikeSharp.API.Core;

namespace CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
namespace CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;

public abstract class BaseMemoryFunction : NativeObject
{
private static Dictionary<string, IntPtr> _createdFunctions = new();
private static Dictionary<string, IntPtr> _createdFunctions = new();

internal static Dictionary<string, IntPtr> _createdOffsetFunctions = new();

private static IntPtr CreateValveFunctionBySignature(string signature, DataType returnType,
DataType[] argumentTypes)
Expand Down Expand Up @@ -45,6 +42,55 @@ private static IntPtr CreateValveFunctionBySignature(string signature, string bi
}

return function;
}

private static IntPtr CreateValveFunctionByOffset(string symbolName, int offset, DataType returnType,
DataType[] argumentTypes, Func<nint> nativeCaller)
{
string constructKey = $"{symbolName}_{offset}";

if (!_createdOffsetFunctions.TryGetValue(constructKey, out var function))
{
try
{
function = nativeCaller();
_createdOffsetFunctions[constructKey] = function;
} catch (Exception)
{
}
}

return function;
}

private static IntPtr CreateValveFunctionByOffset(IntPtr objectPtr, string symbolName, int offset, DataType returnType,
DataType[] argumentTypes)
{
return CreateValveFunctionByOffset(symbolName, offset, returnType, argumentTypes, () =>
{
return NativeAPI.CreateVirtualFunction(objectPtr, offset, argumentTypes.Length,
(int)returnType, argumentTypes.Cast<object>().ToArray());
});
}

private static IntPtr CreateValveFunctionBySymbol(string symbolName, string binaryPath, int offset, DataType returnType,
DataType[] argumentTypes)
{
return CreateValveFunctionByOffset(symbolName, offset, returnType, argumentTypes, () =>
{
return NativeAPI.CreateVirtualFunctionBySymbol(binaryPath, symbolName, offset, argumentTypes.Length,
(int)returnType, argumentTypes.Cast<object>().ToArray());
});
}

private static IntPtr CreateValveFunctionFromVTable(string symbolName, IntPtr vtable, int offset, DataType returnType,
DataType[] argumentTypes)
{
return CreateValveFunctionByOffset(symbolName, offset, returnType, argumentTypes, () =>
{
return NativeAPI.CreateVirtualFunctionFromVTable(vtable, offset, argumentTypes.Length,
(int)returnType, argumentTypes.Cast<object>().ToArray());
});
}

public BaseMemoryFunction(string signature, DataType returnType, DataType[] parameters) : base(
Expand All @@ -55,6 +101,38 @@ public BaseMemoryFunction(string signature, DataType returnType, DataType[] para
public BaseMemoryFunction(string signature, string binarypath, DataType returnType, DataType[] parameters) : base(
CreateValveFunctionBySignature(signature, binarypath, returnType, parameters))
{
}

/// <summary>
/// <b>WARNING:</b> this is only supposed to be used with <see cref="VirtualFunctionVoid{TArg1}"/> and <see cref="VirtualFunctionWithReturn{TArg1, TResult}"/> variants.
/// </summary>
internal BaseMemoryFunction(IntPtr objectPtr, string symbolName, int offset, DataType returnType, DataType[] parameters) : base(
CreateValveFunctionByOffset(objectPtr, symbolName, offset, returnType, parameters))
{
}

/// <summary>
/// <b>WARNING:</b> this is only supposed to be used with <see cref="VirtualFunctionVoid{TArg1}"/> and <see cref="VirtualFunctionWithReturn{TArg1, TResult}"/> variants.
/// </summary>
internal BaseMemoryFunction(string symbolName, string binaryPath, int offset, DataType returnType, DataType[] parameters) : base(
CreateValveFunctionBySymbol(symbolName, binaryPath, offset, returnType, parameters))
{
}

/// <summary>
/// <b>WARNING:</b> this is only supposed to be used with <see cref="VirtualFunctionVoid{TArg1}"/> and <see cref="VirtualFunctionWithReturn{TArg1, TResult}"/> variants.
/// </summary>
internal BaseMemoryFunction(string symbolName, int offset, DataType returnType, DataType[] parameters) : base(
CreateValveFunctionBySymbol(symbolName, Addresses.ServerPath, offset, returnType, parameters))
{
}

/// <summary>
/// <b>WARNING:</b> this is only supposed to be used with <see cref="VirtualFunctionVoid{TArg1}"/> and <see cref="VirtualFunctionWithReturn{TArg1, TResult}"/> variants.
/// </summary>
internal BaseMemoryFunction(string symbolName, IntPtr vtable, int offset, DataType returnType, DataType[] parameters) : base(
CreateValveFunctionFromVTable(symbolName, vtable, offset, returnType, parameters))
{
}

public void Hook(Func<DynamicHook, HookResult> handler, HookMode mode)
Expand All @@ -76,4 +154,4 @@ protected void InvokeInternalVoid(params object[] args)
{
NativeAPI.ExecuteVirtualFunction<object>(Handle, args);
}
}
}
Loading
Loading