SourceHook Development

From AlliedModders Wiki
Revision as of 21:38, 5 October 2007 by BAILOPAN (talk | contribs) (initial import)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

SourceHook is a powerful API (Application Programming Interface) for detouring virtual functions. Unlike static detours, SourceHook needs only to swap addresses in and out of an object's virtual table. This makes it fast and generally very platform-safe.

SourceHook is coupled with Don Clugston's FastDelegate headers. Virtual hooks can be detoured to any static function of the same prototype, or any member function (of any class) as long as the prototype matches.

All code in SourceHook is part of the SourceHook namespace. Thus, it may be prudent to declare this before using SourceHook structures or types:

using namespace SourceHook;

Simple Hooks

SourceHook has the following steps of operation:

  • Declare the prototype of the function you are going to hook. This generates compile-time code that is able to pinpoint exactly how to go about hooking the function.
  • Hook the function - as a member function of another class or a regular static function.
  • Before the hooked function is called, all of the "pre" hook handlers attached to it are called. Each hook can set a special flag, the highest of which is chosen as a final operation. This flag specifies whether the original function should be called or not.
  • Once all the hooks have been called, SourceHook decides whether to call the original function. Another set of hooks are called directly after, called "post" hook handlers. You can specify whether each hook is a post or pre hook - it simply changes whether it's called before or after the original call is made.
  • After you are done using a hook, you must safely remove it before the object is destroyed (otherwise, memory will be leaked).

Declaration

As an example, take the following class prototype:

class IVEngineServer
{
public:
   /*...*/
   virtual void LogPrint( const char *msg ) = 0;
   virtual bool IsDedicated() = 0;
};
 
extern IVEngineServer *engine;


The first step is to figure out how to declare its prototype to SourceHook. This function is void, and has one parameter. The declaration macro follows these formats:

  • SH_DECL_HOOKn - n is the number of parameters
    • The parameters are: Class name, member function name, attributes, overloaded?, the return type, and a list of the parameter types.
  • SH_DECL_HOOKn_void - n is the number of parameters
    • _void specifies that the function does not return a value. The format is the same as above except the "return type" parameter is missing.
  • Note: Not covered here are the SH_DECL_HOOKn[_void]_vafmt hooks. These can hook string-formattable variable argument lists. You do not pass the string format or ellipses parameter. SourceHook will automatically format the string for your hook.

Our macro will look like this:

SH_DECL_HOOK1_void(IVEngineServer, LogPrint, SH_NOATTRIB, 0, const char *);
SH_DECL_HOOK0(IVEngineServer, IsDedicated, SH_NOATTRIB, 0, bool);

Broken down for the first line:

  • There is 1 parameter.
  • The function has no return value.
  • IVEngineServer is the class containing the function.
  • LogPrint is the function being hooked.
  • The function as no attributes (for example, it is not const).
  • The function is not overloaded.
  • The first (and only) argument is a const char *

The second line is similar, except the parameter immediately after the overload parameter specifies the return type. There are no further parameters since it was declared with 0.

Hook Functions

Hooks can be declared either pre or post. A pre hook will intercept the original function before it is called. Pre-hooks can return one of four hook actions:

  • META_IGNORED - The original function will be called.
  • META_HANDLED - Same as META_IGNORED, except subsequent hooks can assume this means something important was changed.
  • META_OVERRIDE - The original function will be called, but the new return value will be used instead of the one from the original function.
  • META_SUPERCEDE - The original function will not be called. The new return value (if any) will be used instead.

Once all pre-hooks have been processed, SourceHook takes an action based on the "highest" hook action returned (META_IGNORED being lowest, META_SUPERCEDE being highest). Once the action has been processed, all post hooks are called. That is to say, even if the original function is never called, post hooks are still processed. Because a post hook as no chance at true interception, it is important to realize that depending on the information being detoured, the data may be modified or destroyed. Similarly, a post hook's returned action and value is ignored.

A hook's action is signalled via one of two macros:

  • RETURN_META - Only usable from void functions. Signals the action to take, then returns.
  • RETURN_META_VALUE - Only usable from non-void functions. Signals the action to take, then returns the supplied value.

There are two methods of adding or removing hooks. Hooks can be bound to static or member functions. Both have a similar syntax.

It is important to realize that a simple hook will only be invoked when used on the same instance. That is to say, if there are 500 instances of object X, and a hook is added to instance #8 to &X::Y, then the hook will only be invoked from instance #8. Multiple hooks can be declared on the same instance, and multiple instances can be bound to the same hook.

This restriction on simple hooks means that the hook must be removed before the instance is destroyed; otherwise, memory will be leaked with no chance of removal (since the accessing the object is invalid). To have hooks that work across all instances, and thus do not need to be delegated per-instance, see the "Global Hooks" section.

Adding Static Hooks

The static binding macros are SH_ADD_HOOK_STATICFUNC and SH_REMOVE_HOOK_STATICFUNC. The syntax is:

SH_[ADD|REMOVE]_HOOK_STATICFUNC(Interface, Function, Instance, Hook, [post? true,false])

An example of adding a LogPrint hook:

void Hook_LogPrint(const char *msg)
{
   if (strcmp(msg, "If this string matches the function will be blocked") == 0)
   {
      RETURN_META(MRES_SUPERCEDE);
   }
 
   /* Not needed, but good style */
   RETURN_META(MRES_IGNORED);
}
 
void StartHooks()
{
   SH_ADD_HOOK_STATICFUNC(IVEngineServer, LogPrint, engine, Hook_LogPrint, false);
}
 
void StopHooks()
{
   SH_REMOVE_HOOK_STATICFUNC(IVEngineServer, LogPrint, engine, Hook_LogPrint, false);
}

Adding Member Hooks

The member binding macros are SH_ADD_HOOK_MEMFUNC and SH_REMOVE_HOOK_MEMFUNC. The syntax is:

SH_[ADD|REMOVE]_HOOK_MEMFUNC(Interface, Function, Instance, HookInstance, HookFunction, [post? true,false])

Example equivalent to the above:

class MyHooks
{
public:
   void Hook_LogPrint(const char *msg)
   {
      if (strcmp(msg, "If this string matches the function will be blocked") == 0)
      {
         RETURN_META(MRES_SUPERCEDE);
      }
 
      /* Not needed, but good style */
      RETURN_META(MRES_IGNORED);
   }
 
   void StartHooks()
   {
      SH_ADD_HOOK_STATICFUNC(IVEngineServer, LogPrint, engine, this, &MyHooks::Hook_LogPrint, false);
   }
 
   void StopHooks()
   {
      SH_REMOVE_HOOK_STATICFUNC(IVEngineServer, LogPrint, engine, this, &MyHooks::Hook_LogPrint, false);
   }
};


Manual Hooks

In some cases, it may be necessary to support multiple, incompatible ABI branches of an interface. For example, suppose you need to hook an application that may supply either version of these interfaces:

Interface v1:

class Interface
{
public:
   virtual void Function1() =0;
   virtual bool Function2(int clam) =0;
};

Interface v2:

class Interface
{
public:
   virtual bool Function2(int clam) =0;
};

Obviously, these two interfaces are backwards incompatible. Manual hooks allow you to precisely define the structure of the virtual table, bypassing the compiler's rules. These rules can be re-configured at runtime.

Declaration

Declaring a manual hook is similar to declaring a normal/simple hook. The syntax is:

SH_DECL_MANUALHOOK<n>[_void](UniqueName, vtblIndex, vtblOffs, thisOffs, [return and param types])

The UniqueName is a unique identifier for the hook. The vtblIndex is the index into the virtual table at which the function lies. In most compilers, this index starts from 0. The vtblOffs and thisOffs fields are used for multiple inheritance and are almost always 0 in modern compiler single inheritance.

An example of hooking the two functions from the first interface version:

SH_DECL_MANUALHOOK0_void(MHook_Function1, 0, 0, 0);
SH_DECL_MANUALHOOK1(MHook_Function2, 1, 0, 0, bool, int);

Reconfiguring

A manual hook can be reconfigured, which will update its set offsets. Reconfiguration automatically removes all hooks on the manual hook. Let's say we want to reconfigure the Function2 hook in the case of the second version being detected:

void SwitchToNewerHooks()
{
   SH_MANUALHOOK_RECONFIGURE(MHook_Function2, 0, 0, 0);
}

Note that the hook was referenced by its unique identifier.

Adding/Removing Hooks

Adding or removing hook binds is done via four extra macros:

  • SH_ADD_MANUALHOOK_STATICFUNC
  • SH_REMOVE_MANUALHOOK_MEMFUNC
  • SH_ADD_MANUALHOOK_STATICFUNC
  • SH_REMOVE_MANUALHOOK_MEMFUNC

These work similar to the original functions. Example:

extern Interface *iface;
 
bool Hook_Function2(int clam)
{
   RETURN_META_VALUE(MRES_IGNORED, false);
}
 
void StartHooks()
{
   SH_ADD_MANUALHOOK_STATICFUNC(MHook_Function2, iface, Hook_Function2, false);
}
 
void StopHooks()
{
   SH_REMOVE_MANUALHOOK_STATICFUNC(MHook_Function2, iface, Hook_Function2, false);
}

The member function version is similar:

SH_[ADD|REMOVE]_MANUALHOOK_MEMFUNC(UniqueName, Instance, HookInstance, HookFunction, [post? true,false]);


Bypassing Hooks

Often, either to avoid certain functionality or to avoid infinite recursion, it is necessary to bypass all hooks on a hooked function, such that only the original function is called. For example, our example above blocks certain messages sent through LogPrint. In order to send that message, the hook needs to be bypassed.

The method of bypassing hooks changed in SourceHook versions v4.5 and above. The old method is deprecated, but still supported. Both are documented here.

New Method

The new method uses the macro SH_CALL, which has the following prototype:

SH_CALL(Instance, HookFunction)(params)

Example:

SH_CALL(engine, &IVEngineServer::LogPrint)("Secret Message");

Old Method

The old method is optional as of SourceHook v4.5 and represents restrictions that have since been lifted. It is recommended that only the new style be used.

In order to bypass hooks on an interface, a CallClass object must be obtained. Obtaining and releasing such an object should be considered an expensive operation. An example might look like:

CallClass<IVEngineServer> *engine_bypass;
 
void LogPrint_Bypass(const char *msg)
{
  SH_CALL(engine_bypass, &IVEngineServer::LogPrint)(msg);
}
 
void StartHooks()
{
  /* ... */
  engine_bypass = SH_GET_CALLCLASS(engine);
}
 
void StopHooks()
{
  /* ... */
  SH_RELEASE_CALLCLASS(engine_bypass);
}

Note that the syntax is similar to the new method, except the CallClass instance must be used instead of the actual class instance.

Manual Bypasses

Bypasses against manual hooks are possible as well. Re-using the example from earlier:

class Interface
{
public:
   virtual bool Function2(int clam) =0;
};
 
extern Interface *iface;
 
SH_DECL_MANUALHOOK1(MHook_Function2, 1, 0, 0, bool, int);

New Method

Supported in SourceHook v4.5 or higher.

bool Function2_Bypass(int clam)
{
   return SH_MCALL(iface, MHook_Function2)(clam);
}

Old Method

Deprecated in SourceHook v4.5 or higher.

ManualCallClass *iface_bypass = NULL;
 
bool Function2_Bypass(int clam)
{
   return SH_MCALL(iface_bypass, MHook_Function2)(clam);
}
 
void StartHooks()
{
   /* ... */
   iface_bypass = SH_GET_MCALLCLASS(iface, sizeof(void*)); 
}
 
void StopHooks()
{
   /* ... */
   SH_RELEASE_CALLCLASS(iface_bypass);
}