Difference between revisions of "HamSandwich General Usage (AMX Mod X)"

From AlliedModders Wiki
Jump to: navigation, search
(Config File Requirements)
 
(4 intermediate revisions by 3 users not shown)
Line 1: Line 1:
 
== About Ham Sandwich ==
 
== About Ham Sandwich ==
Ham Sandwich is a module that provides additional hooking and function calling capabilities to [[AMX Mod X]].  It is scheduled to be included with the 1.8 branch of AMX Mod X.
+
Ham Sandwich is a module that provides additional hooking and function calling capabilities to [[AMX Mod X]].
  
 
Instead of hooking and executing Half-Life engine calls, like the modules FakeMeta and Engine do, this hooks and executes virtual function calls.
 
Instead of hooking and executing Half-Life engine calls, like the modules FakeMeta and Engine do, this hooks and executes virtual function calls.
Line 8: Line 8:
  
 
Unlike normal member functions, virtual functions can be changed by class derivatives.  For example, a typical hierarchy of entities in Half-Life game dlls look something like this:
 
Unlike normal member functions, virtual functions can be changed by class derivatives.  For example, a typical hierarchy of entities in Half-Life game dlls look something like this:
 
 
  CBaseEntity
 
  CBaseEntity
 
     CBaseAnimating
 
     CBaseAnimating
Line 17: Line 16:
 
           CBasePlayer
 
           CBasePlayer
 
             CBot
 
             CBot
 +
  
 
Now for example, if CBaseEntity has the virtual function called "FunctionA", and that function does nothing.  But, CBarnacle also declares the function "FunctionA", and instead of doing nothing it causes the barnacle to die.
 
Now for example, if CBaseEntity has the virtual function called "FunctionA", and that function does nothing.  But, CBarnacle also declares the function "FunctionA", and instead of doing nothing it causes the barnacle to die.
Line 22: Line 22:
 
If something like this were to be executed:
 
If something like this were to be executed:
 
  CBaseEntity *ent=GET_PRIVATE(entity);
 
  CBaseEntity *ent=GET_PRIVATE(entity);
ent->FunctionA();
+
  ent->FunctionA();
  
 
And the entity were a barnacle, the barnacle would die.  If the entity was a zombie, nothing would happen.
 
And the entity were a barnacle, the barnacle would die.  If the entity was a zombie, nothing would happen.
Line 35: Line 35:
  
 
For example, say you have a plugin like this:
 
For example, say you have a plugin like this:
 +
<pawn>
 +
#include <amxmodx>
 +
#include <fakemeta>
 +
#include <hamsandwich>
 +
 +
new myStr;
 +
 +
public plugin_init()
 +
{
 +
    myStr = engfunc( EngFunc_AllocString, "info_target" );
  
#include <amxmodx>
+
    register_clcmd( "make_entity", "cmdMakeEntity" );
#include <fakemeta>
 
#include <hamsandwich>
 
 
new myStr;
 
public plugin_init()
 
{
 
  myStr = engfunc( EngFunc_AllocString, "info_target" );
 
 
  register_clcmd( "make_entity", "cmdMakeEntity" );
 
 
  RegisterHam(Ham_TakeDamage, "damageHook", "MyEntityClass"); // Error!
 
}
 
public cmdMakeEntity( id )
 
{
 
  new ent = engfunc( EngFunc_CreateEntity, myStr );
 
  set_pev( ent, pev_classname, "MyEntityClass" );
 
  // ...
 
}
 
  
 +
    RegisterHam(Ham_TakeDamage, "MyEntityClass", "damageHook"); // Error!
 +
}
 +
 +
public cmdMakeEntity( id )
 +
{
 +
    new ent = engfunc( EngFunc_CreateEntity, myStr );
 +
    set_pev( ent, pev_classname, "MyEntityClass" );
 +
    // ...
 +
}
 +
</pawn>
 
That will not work, because the class "MyEntityClass" is not native to the gamedll.  Instead, you would need to hook TakeDamage for "info_target", and do some form of parsing on the entities that get passed to it (such as checking classname), if you want to deal with custom entity hooking.
 
That will not work, because the class "MyEntityClass" is not native to the gamedll.  Instead, you would need to hook TakeDamage for "info_target", and do some form of parsing on the entities that get passed to it (such as checking classname), if you want to deal with custom entity hooking.
  
Line 65: Line 67:
 
* That the entity is not derived any further.
 
* That the entity is not derived any further.
  
An example would be using the hierarchy shown earlier.  If, inside of CBot::TakeDamage a call to the virtual function CBot::Killed is made, most compilers will optimize the virtual function lookup out, so that CBot::TakeDamage would then directly call CBot::Killed.  This means that the hook would never be called.
+
An example would be using the hierarchy shown earlier.  If, inside of <code>CBot::TakeDamage</code> a call to the virtual function <code>CBot::Killed</code> is made, most compilers will optimize the virtual function lookup out, so that <code>CBot::TakeDamage</code> would then directly call <code>CBot::Killed</code>.  This means that the hook would never be called.
  
 
Fortunately, these instances are kind of rare.
 
Fortunately, these instances are kind of rare.
  
 
==== Config File Requirements ====
 
==== Config File Requirements ====
Every hook and every ExecuteHam() call requires an entry for the function which the scripter is attempting to hook or execute.  The function needs to be in the amxmodx/configs/hamdata.ini config file, under the game mod and operating system.
+
Every hook and every <code>ExecuteHam()</code> call requires an entry for the function which the scripter is attempting to hook or execute.  The function needs to be in the amxmodx/configs/hamdata.ini config file, under the game mod and operating system.
  
 
If a function that the script attempts to hook or call is not configured in the hamdata.ini file, then the module will cause the plugin to cease operation, as this is a fatal error.
 
If a function that the script attempts to hook or call is not configured in the hamdata.ini file, then the module will cause the plugin to cease operation, as this is a fatal error.
  
The fatal errors can be filtered out by including a forward in the script called '''HamFilter'''.  This is similar to native/module filters available inside of the core of amxmodx, whenever a fatal error occurs, it will pass along the parameters to HamFilter, and if HamFilter returns '''PLUGIN_HANDLED''', the error will be ignored (but the attempted hook or execution will not take place).  If the forward does not exist, or if it returns something other than PLUGIN_HANDLED, the plugin will fail.
+
The fatal errors can be filtered out by including a forward in the script called <code>HamFilter</code>.  This is similar to native/module filters available inside of the core of amxmodx, whenever a fatal error occurs, it will pass along the parameters to <code>HamFilter</code>, and if <code>HamFilter</code> returns <code>PLUGIN_HANDLED</code>, the error will be ignored (but the attempted hook or execution will not take place).  If the forward does not exist, or if it returns something other than <code>PLUGIN_HANDLED</code>, the plugin will fail.
  
 
An example layout for HamFilter:
 
An example layout for HamFilter:
public HamFilter(Ham:which, HamError:err, const reason[])
+
<pawn>
{
+
public HamFilter(Ham:which, HamError:err, const reason[])
  // Ignore an unconfigured ns_awardkill
+
{
  if (which == Ham_NS_AwardKill && err == HAM_FUNC_NOT_CONFIGURED)(
+
    // Ignore an unconfigured ns_awardkill
  {
+
    if (which == Ham_NS_AwardKill && err == HAM_FUNC_NOT_CONFIGURED)
    return PLUGIN_HANDLED;
+
    {
  }
+
        return PLUGIN_HANDLED;
  // We absolutely need to be able to use cs_roundrespawn!
+
    }
  // If we can't, then the plugin cannot continue.
 
  if (which == Ham_CS_RoundRespawn)
 
  {
 
    return 0;
 
  }
 
}
 
  
Additionally, you can check to see if a function is valid to execute or hook by using the '''IsHamValid()''' native.  The validity of a function is determined when the module is first loaded, and it will never change, so if you want to check it, there is no need to do so before every execute.
+
    // We absolutely need to be able to use cs_roundrespawn!
 +
    // If we can't, then the plugin cannot continue.
 +
    if (which == Ham_CS_RoundRespawn)
 +
    {
 +
        return 0;
 +
    }
 +
}
 +
</pawn>
 +
 
 +
Additionally, you can check to see if a function is valid to execute or hook by using the <code>IsHamValid()</code> native.  The validity of a function is determined when the module is first loaded, and it will never change, so if you want to check it, there is no need to do so before every execute.
  
 
== Supported Mods ==
 
== Supported Mods ==
Line 105: Line 110:
  
 
=== Weakly Supported ===
 
=== Weakly Supported ===
Because these mods do not contain a Linux binary, they are much harder to disassemble.  There is only plans for disassembling two functions for each (TakeDamage and Use).
+
Because these mods do not contain a Linux binary, they are much harder to disassemble.
 
* Sven-Coop
 
* Sven-Coop
 
* Earth's Special Forces
 
* Earth's Special Forces
Line 115: Line 120:
 
Creating a hook is a lot like creating a hook in Fakemeta.
 
Creating a hook is a lot like creating a hook in Fakemeta.
  
#include <amxmodx>
+
<pawn>
#include <hamsandwich>
+
#include <amxmodx>
+
#include <hamsandwich>
public plugin_init()
+
 
{
+
public plugin_init()
  RegisterHam(Ham_TakeDamage, "player_hurt", "player");
+
{
}
+
    RegisterHam(Ham_TakeDamage, "player", "player_hurt");
+
}
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
+
 
{
+
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
  // Stuff...
+
{
}
+
    // Stuff...
 +
}
 +
</pawn>
  
 
This creates a basic hook which is called any time a player takes damage.  Look in '''ham_const.inc''' for forward parameters for each hook.
 
This creates a basic hook which is called any time a player takes damage.  Look in '''ham_const.inc''' for forward parameters for each hook.
  
Like FakeMeta, there is a hidden last parameter (it goes after the classname in this case).  Set it to 1 to do post hooking.
+
Like Fakemeta, there is a hidden last parameter.  Set it to 1 to do post hooking.
  
 
=== Blocking the Hook ===
 
=== Blocking the Hook ===
Line 137: Line 144:
 
Blocking in Ham Sandwich is identical to how it is accomplished in Fakemeta.  In each hook, you return one of four special values:
 
Blocking in Ham Sandwich is identical to how it is accomplished in Fakemeta.  In each hook, you return one of four special values:
  
* HAM_IGNORED - Nothing happened, the call continues.
+
* <code>HAM_IGNORED</code> - Nothing happened, the call continues.
* HAM_HANDLED - You did something, but the call continues.
+
* <code>HAM_HANDLED</code> - You did something, but the call continues.
* HAM_OVERRIDE - The call will still be executed, but instead you will change the return value.
+
* <code>HAM_OVERRIDE</code> - The call will still be executed, but instead you will change the return value.
* HAM_SUPERCEDE - The call is not executed, and you use your return value, if applicable.
+
* <code>HAM_SUPERCEDE</code> - The call is not executed, and you use your return value, if applicable.
  
You can use the native '''GetHamReturnStatus()''' to check the current return status of the hook.
+
You can use the native <code>GetHamReturnStatus()</code> to check the current return status of the hook.
  
 
=== Return Values ===
 
=== Return Values ===
Line 148: Line 155:
  
 
These natives will get any ''modified'' return values.
 
These natives will get any ''modified'' return values.
 +
<tt>
 
* native GetHamReturnInteger(&output);
 
* native GetHamReturnInteger(&output);
 
* native GetHamReturnFloat(&Float:output);
 
* native GetHamReturnFloat(&Float:output);
Line 153: Line 161:
 
* native GetHamReturnEntity(&output);
 
* native GetHamReturnEntity(&output);
 
* native GetHamReturnString(output[], size);
 
* native GetHamReturnString(output[], size);
 +
</tt>
  
 
These natives will get the ''original'' return value from the function.
 
These natives will get the ''original'' return value from the function.
 +
Note that this is '''only''' valid to call in a post hook, it will be undefined to call it at any other time.
 +
<tt>
 
* native GetOrigHamReturnInteger(&output);
 
* native GetOrigHamReturnInteger(&output);
 
* native GetOrigHamReturnFloat(&Float:output);
 
* native GetOrigHamReturnFloat(&Float:output);
 
* native GetOrigHamReturnVector(Float:output[3]);
 
* native GetOrigHamReturnVector(Float:output[3]);
* native GetOrigHamReturnCbase(&output);
+
* native GetOrigHamReturnEntity(&output);
 
* native GetOrigHamReturnString(output[], size);
 
* native GetOrigHamReturnString(output[], size);
 +
</tt>
  
 
These natives will change the return value to whatever you please.
 
These natives will change the return value to whatever you please.
 +
Note that this will have no effect on the actual return value from the function '''unless''' the return status of the hook is <code>HAM_OVERRIDE</code> or <code>HAM_SUPERCEDE</code>.
 +
<tt>
 
* native SetHamReturnInteger(value);
 
* native SetHamReturnInteger(value);
 
* native SetHamReturnFloat(Float:value);
 
* native SetHamReturnFloat(Float:value);
Line 167: Line 181:
 
* native SetHamReturnEntity(value);
 
* native SetHamReturnEntity(value);
 
* native SetHamReturnString(const value[]);
 
* native SetHamReturnString(const value[]);
 +
</tt>
  
 
=== Changing Hook Parameters ===
 
=== Changing Hook Parameters ===
Line 172: Line 187:
  
 
This means that, for example, if you wanted to make a plugin that halved all damage players take, you would do something like this:
 
This means that, for example, if you wanted to make a plugin that halved all damage players take, you would do something like this:
#include <amxmodx>
+
<pawn>
#include <fakemeta>
+
#include <amxmodx>
public plugin_init()
+
#include <hamsandwich>
{
+
 
  RegisterHam(Ham_TakeDamage, "player_hurt", "player");
+
public plugin_init()
}
+
{
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
+
    RegisterHam(Ham_TakeDamage, "player", "player_hurt");
{
+
}
  SetHamParamFloat(4, damage / 2.0);
+
 
  return HAM_HANDLED;
+
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
}
+
{
 +
    // Player will now take half damage
 +
    SetHamParamFloat(4, damage / 2.0);
 +
    return HAM_HANDLED;
 +
}
 +
</pawn>
  
 
All hooks after the one you change them in will see the modified values.  Hooks are executed in the order in which they are registered.
 
All hooks after the one you change them in will see the modified values.  Hooks are executed in the order in which they are registered.
  
 
All available parameter changing natives are:
 
All available parameter changing natives are:
 
+
<tt>
 
* native SetHamParamInteger(which, value);
 
* native SetHamParamInteger(which, value);
 
* native SetHamParamFloat(which, Float:value);
 
* native SetHamParamFloat(which, Float:value);
Line 194: Line 214:
 
* native SetHamParamString(which, const output[]);
 
* native SetHamParamString(which, const output[]);
 
* native SetHamParamTraceResult(which, tr_handle);
 
* native SetHamParamTraceResult(which, tr_handle);
 +
</tt>
  
 
=== Disabling Hooks ===
 
=== Disabling Hooks ===
  
Similar to how FakeMeta allows for unregistering of hooks with unregister_forward, HamSandwich will allow you to disable and enable hooks whenever you want.
+
Similar to how FakeMeta allows for unregistering of hooks with <code>unregister_forward()</code>, HamSandwich will allow you to disable and enable hooks whenever you want.
  
The '''RegisterHam''' function will return a handle (tagged with HamHook).  You can then make subsequent calls to DisableHamHook() and EnableHamHook() with the handle to stop it from forwarding, or enable its forwards again.
+
The <code>RegisterHam()</code> function will return a handle (tagged with <code>HamHook</code>).  You can then make subsequent calls to <code>DisableHamForward()</code> and <code>EnableHamForward()</code> with the handle to stop it from forwarding, or enable its forwards again.
  
 
There is no way to completely unregister the hooks (until map change), as deleting a hook is a delicate process.
 
There is no way to completely unregister the hooks (until map change), as deleting a hook is a delicate process.

Latest revision as of 14:42, 30 August 2017

About Ham Sandwich

Ham Sandwich is a module that provides additional hooking and function calling capabilities to AMX Mod X.

Instead of hooking and executing Half-Life engine calls, like the modules FakeMeta and Engine do, this hooks and executes virtual function calls.

What is a virtual function?

A virtual function is a member function of a class in C++. In the case of Ham Sandwich, the virtual function would be a member function of a game entity. The virtual functions deal with various events in game, such as damage, and using entities.

Unlike normal member functions, virtual functions can be changed by class derivatives. For example, a typical hierarchy of entities in Half-Life game dlls look something like this:

CBaseEntity
   CBaseAnimating
      CBaseMonster
         CZombie
         CHeadCrab
         CBarnacle
         CBasePlayer
            CBot


Now for example, if CBaseEntity has the virtual function called "FunctionA", and that function does nothing. But, CBarnacle also declares the function "FunctionA", and instead of doing nothing it causes the barnacle to die.

If something like this were to be executed:

CBaseEntity *ent=GET_PRIVATE(entity);
 ent->FunctionA();

And the entity were a barnacle, the barnacle would die. If the entity was a zombie, nothing would happen.

What are some limitations?

Dealing with virtual functions have a couple minor drawbacks.

Custom Entities

Hooking virtual functions, such as TakeDamage, that get called on custom entities is a little bit awkward.

Because of the way where classes derive, and they get their own virtual table for each class, the type of class that the game dll allocates will be whatever gets hooked for a particular hook.

For example, say you have a plugin like this:

#include <amxmodx>
#include <fakemeta>
#include <hamsandwich>
 
new myStr;
 
public plugin_init()
{
    myStr = engfunc( EngFunc_AllocString, "info_target" );
 
    register_clcmd( "make_entity", "cmdMakeEntity" );
 
    RegisterHam(Ham_TakeDamage, "MyEntityClass", "damageHook"); // Error!
}
 
public cmdMakeEntity( id )
{
    new ent = engfunc( EngFunc_CreateEntity, myStr );
    set_pev( ent, pev_classname, "MyEntityClass" );
    // ...
}

That will not work, because the class "MyEntityClass" is not native to the gamedll. Instead, you would need to hook TakeDamage for "info_target", and do some form of parsing on the entities that get passed to it (such as checking classname), if you want to deal with custom entity hooking.

End of Chain Derivatives

The normal way virtual functions get called is by a virtual table that resides somewhere in the class. A magical index is assigned to each function, and then it looks up the function pointer inside of the virtual table, and executes the required function.

However, compilers are smart enough to optimize away the virtual function lookup if it knows two things about a call:

  • The exact class type of the entity.
  • That the entity is not derived any further.

An example would be using the hierarchy shown earlier. If, inside of CBot::TakeDamage a call to the virtual function CBot::Killed is made, most compilers will optimize the virtual function lookup out, so that CBot::TakeDamage would then directly call CBot::Killed. This means that the hook would never be called.

Fortunately, these instances are kind of rare.

Config File Requirements

Every hook and every ExecuteHam() call requires an entry for the function which the scripter is attempting to hook or execute. The function needs to be in the amxmodx/configs/hamdata.ini config file, under the game mod and operating system.

If a function that the script attempts to hook or call is not configured in the hamdata.ini file, then the module will cause the plugin to cease operation, as this is a fatal error.

The fatal errors can be filtered out by including a forward in the script called HamFilter. This is similar to native/module filters available inside of the core of amxmodx, whenever a fatal error occurs, it will pass along the parameters to HamFilter, and if HamFilter returns PLUGIN_HANDLED, the error will be ignored (but the attempted hook or execution will not take place). If the forward does not exist, or if it returns something other than PLUGIN_HANDLED, the plugin will fail.

An example layout for HamFilter:

public HamFilter(Ham:which, HamError:err, const reason[])
{
    // Ignore an unconfigured ns_awardkill
    if (which == Ham_NS_AwardKill && err == HAM_FUNC_NOT_CONFIGURED)
    {
        return PLUGIN_HANDLED;
    }
 
    // We absolutely need to be able to use cs_roundrespawn!
    // If we can't, then the plugin cannot continue.
    if (which == Ham_CS_RoundRespawn)
    {
        return 0;
    }
}

Additionally, you can check to see if a function is valid to execute or hook by using the IsHamValid() native. The validity of a function is determined when the module is first loaded, and it will never change, so if you want to check it, there is no need to do so before every execute.

Supported Mods

Mostly Supported

These mods have a very large list of functions that are usable in the module.

  • Counter-Strike 1.6
  • Condition Zero
  • Day of Defeat
  • Team Fortress Classic
  • The Specialists
  • Natural-Selection

Weakly Supported

Because these mods do not contain a Linux binary, they are much harder to disassemble.

  • Sven-Coop
  • Earth's Special Forces

Hooking Functions

The big feature for Ham Sandwich is the ability to hook virtual functions.

Creating the Hook

Creating a hook is a lot like creating a hook in Fakemeta.

#include <amxmodx>
#include <hamsandwich>
 
public plugin_init()
{
    RegisterHam(Ham_TakeDamage, "player", "player_hurt");
}
 
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
{
    // Stuff...
}

This creates a basic hook which is called any time a player takes damage. Look in ham_const.inc for forward parameters for each hook.

Like Fakemeta, there is a hidden last parameter. Set it to 1 to do post hooking.

Blocking the Hook

Like Fakemeta and Engine, it is possible to stop a function from being called. This is called superceding.

Blocking in Ham Sandwich is identical to how it is accomplished in Fakemeta. In each hook, you return one of four special values:

  • HAM_IGNORED - Nothing happened, the call continues.
  • HAM_HANDLED - You did something, but the call continues.
  • HAM_OVERRIDE - The call will still be executed, but instead you will change the return value.
  • HAM_SUPERCEDE - The call is not executed, and you use your return value, if applicable.

You can use the native GetHamReturnStatus() to check the current return status of the hook.

Return Values

You can get or change the return values for all the hooks available in Ham Sandwich. Look in ham_const.inc for a list of all hooks and their return values.

These natives will get any modified return values.

  • native GetHamReturnInteger(&output);
  • native GetHamReturnFloat(&Float:output);
  • native GetHamReturnVector(Float:output[3]);
  • native GetHamReturnEntity(&output);
  • native GetHamReturnString(output[], size);

These natives will get the original return value from the function. Note that this is only valid to call in a post hook, it will be undefined to call it at any other time.

  • native GetOrigHamReturnInteger(&output);
  • native GetOrigHamReturnFloat(&Float:output);
  • native GetOrigHamReturnVector(Float:output[3]);
  • native GetOrigHamReturnEntity(&output);
  • native GetOrigHamReturnString(output[], size);

These natives will change the return value to whatever you please. Note that this will have no effect on the actual return value from the function unless the return status of the hook is HAM_OVERRIDE or HAM_SUPERCEDE.

  • native SetHamReturnInteger(value);
  • native SetHamReturnFloat(Float:value);
  • native SetHamReturnVector(const Float:value[3]);
  • native SetHamReturnEntity(value);
  • native SetHamReturnString(const value[]);

Changing Hook Parameters

One feature available in Ham Sandwich that is not available in FakeMeta is the ability to change all parameters on the fly for each hook.

This means that, for example, if you wanted to make a plugin that halved all damage players take, you would do something like this:

#include <amxmodx>
#include <hamsandwich>
 
public plugin_init()
{
    RegisterHam(Ham_TakeDamage, "player", "player_hurt");
}
 
public player_hurt(this, inflictor, attacker, Float:damage, damagebits)
{
    // Player will now take half damage
    SetHamParamFloat(4, damage / 2.0);
    return HAM_HANDLED;
}

All hooks after the one you change them in will see the modified values. Hooks are executed in the order in which they are registered.

All available parameter changing natives are:

  • native SetHamParamInteger(which, value);
  • native SetHamParamFloat(which, Float:value);
  • native SetHamParamVector(which, const Float:value[3]);
  • native SetHamParamEntity(which, value);
  • native SetHamParamString(which, const output[]);
  • native SetHamParamTraceResult(which, tr_handle);

Disabling Hooks

Similar to how FakeMeta allows for unregistering of hooks with unregister_forward(), HamSandwich will allow you to disable and enable hooks whenever you want.

The RegisterHam() function will return a handle (tagged with HamHook). You can then make subsequent calls to DisableHamForward() and EnableHamForward() with the handle to stop it from forwarding, or enable its forwards again.

There is no way to completely unregister the hooks (until map change), as deleting a hook is a delicate process.