Difference between revisions of "Metamod:Source Development"
m (added info about 1.3) |
|||
Line 308: | Line 308: | ||
RETURN_META_VALUE_MNEWPARAMS(MRES_SUPERCEDE, true, _M_Function2, (false, 3)); | RETURN_META_VALUE_MNEWPARAMS(MRES_SUPERCEDE, true, _M_Function2, (false, 3)); | ||
}</cpp> | }</cpp> | ||
+ | |||
+ | =1.3 Changes - Returning References= | ||
+ | SourceMM 1.3 integrates SourceHook v4.6, which adds support for functions returning references. Luckily, this change is both backwards compatible and is transparent to the already existing macros. Thus, the code below is now valid. Note that if you don't want to actually return any reference, you can opt to use the new macro <tt>RETURN_META_NOREF</tt> instead. | ||
+ | <cpp>class Interface | ||
+ | { | ||
+ | public: | ||
+ | virtual int &GetMyInt() = 0; | ||
+ | }; | ||
+ | |||
+ | DECL_HOOK0(Interface, GetMyInt, SH_NOATTRIB, false, int &); | ||
+ | |||
+ | int &Hook_GetMyInt() | ||
+ | { | ||
+ | static int gaben = 5; | ||
+ | RETURN_META_VALUE(MRES_SUPERCEDE, gaben); | ||
+ | } | ||
+ | |||
+ | int &Hook_GetMyInt2() | ||
+ | { | ||
+ | RETURN_META_NOREF(MRES_IGNORED, int &); | ||
+ | } | ||
+ | |||
+ | void AddHook(Interface *pFace) | ||
+ | { | ||
+ | SH_ADDHOOK_STATICFUNC(Interface, GetMyInt, pFace, Hook_GetMyInt, false); | ||
+ | SH_ADDHOOK_STATICFUNC(Interface, GetMyInt, pFace, Hook_GetMyInt2, true); | ||
+ | }</cpp> | ||
+ | |||
[[Category:SourceHook]] | [[Category:SourceHook]] | ||
[[Category:Documentation (SourceMM)]] | [[Category:Documentation (SourceMM)]] |
Revision as of 00:40, 14 August 2006
This article is an introduction to SourceMM coding.
Note: The majority of this documentation should be merged or moved into an article about SourceHook.
Note: This article probably needs some better formatting.
Contents
- 1 Requirements
- 2 Plugin API
- 3 SourceHook (Hooking)
- 4 Calling Original Functions
- 5 Other Macros
- 6 Events System
- 7 Global Variables
- 8 Compiling
- 9 1.1 Changes - Late Loading, Events
- 10 1.2 Changes - Changing Parameters, Manual Hooking
- 11 1.2.2 Changes - Manual Callclasses
- 12 1.2.3 Changes - Changing Parameters in Manually Hooked Functions
- 13 1.3 Changes - Returning References
Requirements
You must have the Valve HL2SDK, available from your Steam Menu. For Windows, you must have Microsoft Visual Studio 7.0 or 7.1 (we have not tried 6.0). For Linux, Valve requires you use at least GCC 3.4.1. You should also have a copy of the Metamod:Source source code, available here (sourcemm/sourcehook and sourcemm/sourcemm).
For Microsoft Visual Studio, you should make sure that you have the following HL2SDK paths in your include settings (Tools -> Options -> Projects, VC++ Directories, Include Files), as well as the "sourcehook" and "sourcemm" folders:
- dlls
- public
- public\vstdlib
- public\tier1
- public\tier0
- public\engine
- public\dlls
- tier1
- lib\public (this should be in your Library Paths!)
Plugin API
In order to write a plugin, you must implement the ISmmPlugin interface, similar to IServerPluginCallbacks. Each Metamod:Source release has a minimum required interface version and a current version. The minimum version is guaranteed to be upward compatible to the current, however, it may be lacking some features.
Once you've implemented the interface, you must also have a global singleton of your plugin available. There are a few macros to assist you in properly exposing the interface as a DLL and setting up the API states.
- PLUGIN_GLOBALVARS() - Place in header. Declares the global variables that some API calls require (such as g_SHPtr and g_PLAPI).
- PLUGIN_EXPOSE(class, singleton) - Place in .cpp file. Declares the external CreateInterface function which exposes the API.
- PLUGIN_SAVEVARS() - Use first thing in ISmmPlugin::Load(), saves the global variables sent from SourceMM.
The actual plugin API you must implement as of this writing is version 004. To see a description of each of the functions, you can view the doxygen information here. Note that the Load, Unload, Pause, and Unpause functions allow you to refuse the action and copy an error message (you should check to make sure error is not NULL - it can be).
SourceHook (Hooking)
SourceHook is the engine used to intercept function calls, much like Metamod. The difference with SourceHook is that it can intercept any virtual function in any class that, at compile time, you have the header for. 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 can safely remove it.
For example, let's say you wanted to intercept log messages in VEngineServer. Observe the prototype:
virtual void LogPrint( const char *msg ) = 0;
This is a virtual, public function of a class we have an instance of (let's say in IVEngineServer *m_Engine) and that we have the header for. It can be intercepted.
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 *);
This line must appear outside of a function. It means "Declare a hook prototype for LogPrint in IVEngineServer, which is a void function that has one parameter, which is a const char *".
Next we must actually hook the function. You can do this wherever you want to begin the interception. The two macros for hooking look like this:
- SH_ADD_HOOK_STATICFUNC(class, memberfunction, instance_pointer, handler, post) Hooks a virtual function to a static/global function.
- class - The name of the class
- memberfunction - The name of the member function
- instance - A pointer to an instance of the class
- handler - Your function that will be called on hooking
- post - true for post operation, false for pre operation
- SH_ADD_HOOK_MEMFUNC(class, memberfunction, instance, myinstance, myfunction, post) Hooks a virtual function to a member function of another class.
- class - The name of the class
- memberfunction - The name of the member function
- instance - An pointer to an instance of the class
- myinstance - A pointer to an instance of the class that has the handler member function
- myfunction - The name of the handler member function in your class
- post - true for post operation, false for pre-operation
Let's continue with the example. To hook LogPrint to a function in your class, CMetaHooks (instance, g_MetaHooks), you would use:
SH_ADD_HOOK_MEMFUNC(IVEngineServer, LogPrint, m_Engine, &g_MetaHooks, &CMetaHooks::LogPrint, false);
To remove the hook (either once it will no longer be unused, or at unload time):
SH_REMOVE_HOOK_MEMFUNC(IVEngineServer, LogPrint, m_Engine &g_MetaHooks, &CMetaHooks::LogPrint, false);
Now, your function contents will look something like this:
void CMetaHooks::LogPrint(const char *msg) { //Code here RETURN_META(MRES_IGNORED); }
Note this return statement. This style of returning is similar to Metamod's, where you can set four different flags to indicate how you would like SourceHook to proceed. In Metamod, this return statement was required. In SourceMM, it is only required if you wish to set a return state other than MRES_IGNORED.
- MRES_IGNORED - No states were changed, act as though nothing happened. Original function is still called.
- MRES_HANDLED - Something changed, but the original function was still called. This can be used to tell another plugin that you did something.
- MRES_OVERRIDE - The original function will still be called, but your return value will override whatever it returns.
- MRES_SUPERCEDE - The original function is not called, and your return value will be what is returned to the caller.
Note, that if you need to return a value, there is another macro. For example:
RETURN_META_VALUE(MRES_SUPERCEDE, value);
This is required for non-void functions, athough the return value is ignored using MRES_IGNORED or MRES_HANDLED.
Alternatively, you can hook to static member functions which has a slightly easier syntax. The DECL_HOOK line does not change. To add the hook:
SH_ADD_HOOK_STATICFUNC(IVEngineServer, LogPrint, m_Engine, LogPrint_handler, false);
Removing the hook:
SH_REMOVE_HOOK_STATICFUNC(IVEngineServer, LogPrint, m_Engine, LogPrint_handler, false);
Declaring the handler:
void LogPrint_handler(const char *msg) { //Code here RETURN_META(MRES_IGNORED); }
Note that vafmt functions hooked with SourceHook assume that the vafmt is for a printf style string, and that the vafmt occurs at the end. When setting the parameters, you do not include the '...' notation, and SourceHook will vafmt the input string for you (meaning you also don't specify ... in your hooked function).
Calling Original Functions
Often it will be necessary for you to call a function that's hooked, however, you don't want the hooks to be included in the calling. For example, if you want to entirely supercede a function and call it yourself from within a hook. To do this, you must request a call class. This is similar to MDLL_x() from Metamod for Half-Life 1.
Continuing with the above example, let's say we want to supercede the original call and log a different message. Assume we also have the pointer m_Engine which is a IVEngineServer *.
SourceHook::CallClass<IVEngineServer> *Engine_CC = SH_GET_CALLCLASS(m_Engine); SH_CALL(Engine_CC, &IVEngineServer::LogPrint)("This is a log message!\n"); //When you are done with the pointer.. SH_RELEASE_CALLCLASS(Engine_CC);
Because of the complex nature of inheritance, instance pointers, and vtables, this syntax can be quite daunting. You may wish to make macros for specific functions or classes you use quite often, to reduce the amount of typing. For example:
//Assuming you have a global pointer g_Engine... #define ENGCALL(func) SH_CALL(g_Engine, &IVEngineServer::func) //Then you can do: ENGCALL(LogPrint)("This is a test!");
The syntax of calling class construction is:
- SourceHook::CallClass<class> *ptr = SH_GET_CALLCLASS(instance);
- Returns an object which allows you to call the original function. Class is the name of the class which is the target, instance is an instance of that class.
- SH_CALL(cc_ptr, &class::func)([params])
- Pass the pointer returned from SH_GET_CALLCLASS as cc_ptr. The target function you call must be passed as a pointer-to-member-function, which takes the form &Class::Function as seen in previous examples. You must then complete the function call by adding a parenthetical parameter expression, even for void functions, which would be ().
Other Macros
All of the macros take g_PLAPI as the first parameter. For more information on this, see the global variables section.
- META_CONPRINT(const char *msg)
- META_CONPRINTF(const char *fmt, ...)
- These two functions are recommended over Msg() for printing to the server console. Msg() does not relay commands back through rcon, and as of this writing Valve does not expose the function which does. To be able to display text through the rcon console (much like HL1), you should use these functions. If SourceMM is unable to extract the function properly, it will automatically default to Msg.
- META_LOG(g_PLAPI, const char *msg, ...)
- Logs a message through IVEngineServer::LogPrint(). A newline is automatically added, and msg is formatted as a sprintf() style string. Logging is done by the game server and can be enabled by adding log on to server.cfg or typing it in the console. The log files are found in the logs directory of the particular MOD you are running.
- META_REGCVAR(var)
- Registers a ConCommandBase pointer through SourceMM. The correct way to use this is to create an IConCommandBaseAccessor, and inside RegisterConCommandBase, call the macro on the given ConComandBase. This will ensure that SourceMM correctly detects and unloads your cvars and concommands at the appopriate time. Otherwise, unloading your plugin will cause a crash.
- META_UNREGCVAR(var)
- Unregisters a ConCommandBase pointer. This is not needed if you have set up your IConCommandBaseAccessor correctly (and called ConCommandBaseMngr::OneTimeInit()).
Events System
The Events System is based on IMetamodListener. By implementing the IMetamodListener class and using g_SMAPI->AddListener, you can watch for certain, low-traffic events. These events are split into three categories:
- Plugin Events let you listen for plugin pauses and unloads. This is important if you're relying on information from another plugin, as you can handle cases where a live plugin has become invalid.
- Game Events are simple events that SourceMM is already hooking and makes available. These are LevelShutdown and LevelInit right now.
- Query Events occur when a factory is used. The four main factories (Engine, GameDLL, FileSystem, and Physics) are all overridable. You should simply return a non-NULL result to override, and fill the return code with IFACE_OK if available. There is no way to handle the case of two plugins overriding right now. The final factory is the Metamod Factory, which is the factory that Metamod:Source adds to the runtime space for plugins. By default, it only contains the interfaces for the PluginManager and SourceHook. Plugins can use this to add new interfaces. Other plugins request these interfaces through g_SMAPI->MetaFactory().
Global Variables
These global variables are saved by PLUGIN_EXPOSE and PLUGIN_SAVEVARS. They are declared with PLUGIN_GLOBALVARS.
- g_PLAPI
- ISmmPlugin * pointer to your global class singleton.
- g_PLID
- The internal PluginId of your plugin.
- g_SHPtr
- The SourceHook::ISourceHook * pointer to SourceHook's interface.
- g_SMAPI
- The ISmmAPI * pointer to SourceMM's interface.
Compiling
To see more about compiling, see the Sample Plugin Compiling section.
Modifying the default Makefiles for your own projects:
- OPT_FLAGS - Optimization flags
- DEBUG_FLAGS - Debug flags
- CPP - C++ Compiler
- OBJECTS - List of C++ files to compile
- LINK - Linker Options
- CFLAGS - Base Compiler Flags
- BINARY - Output Binary Name
Makefile commands:
- clean - Cleans all build files
- debug - Builds debug version
1.1 Changes - Late Loading, Events
SourceMM 1.1 changed quite a few things internally, and externally made many breaking changes. These include:
- ISmmPlugin::Load() has removed the factory list parameter (the factory system was replaced with the event system). Also, a boolean parameter was added, specifying whether the plugin was loaded late or not.
- ISmmPlugin::Load() is now called BEFORE DLLInit(), rather than after. This means it might not have all information it needs -- for example, IGameEvents won't be parsed yet. You will need to do things like this in ISmmPlugin:AllPluginsLoaded() instead, as it is guaranteed to occur when all DLLs are initialized.
- ISmmPlugin now has default functions -- you don't have to implement all of them.
- SourceHook was modified to use interfaces rather than straight struct pointers. This breaking changes will ensure that future SourceHook modifications do not break older plugins.
- SourceHook was modified to be re-entrant.
- SourceHook now has a tiny template library with it. This removes the necessity to link against libstdc++.so.*, which harms binary compatibility across linux distributions.
- SourceMM's GameDLL code was completely rewritten. It will now work with newer mods much easier, and issues like the DoD:S release will be much easier to deal with (if at all). It also removes a few important speed bottlenecks.
- An events system was added.
1.2 Changes - Changing Parameters, Manual Hooking
SourceMM 1.2 now supports changing the parameters in a hook chain. For example, say the GameDLL has a function called IGameDLL::PrintString(const char *str). You can hook this, let it continue, but change the "str" parameter passed in to the rest of the hooks and the GameDLL. To do this, use the following macros:
- RETURN_META_NEWPARAMS
- RETURN_META_VALUE_NEWPARAMS
Example:
class ISomething { virtual void Function1(int num) =0; virtual bool Function2(bool what, int hi) =0; } void MyHook1(int num) { //if num is 0, // we will change the num parameter in the rest of the hooks, and the gamedll, to be 1. if (num == 0) RETURN_META_NEWPARAMS(MRES_IGNORED, &ISomething::Function1, (1)) RETURN_META(MRES_SUPERCEDE); } bool MyHook2(bool what, int hi) { //change the "what" and "hi" parameters to be false and 3 respectively //also, return true, but specify that the value is ignored RETURN_META_VALUE_NEWPARAMS(MRES_IGNORED, true, &ISomething::Function2, (false, 3)); }
SourceHook also supports manual hooking of functions. This means you must know the virtual table index, the virtual table offset (for polymorphism), and the "this" pointer offset. Luckily, the polymorphic offsets are usually zero. This type of hook is ideal when supporting different ABI, for example, across different gamedlls. The API is almost identical:
- SH_DECL_MANUALHOOKn[_void|_vafamt] -
- Declares the manual hook. A unique name must be given to each manual hook.
- SH_[ADD|REMOVE]_MANUALHOOK_[STATIC|MEM]FUNC -
- Adds or removes a static or member function hook on a manually declared hook.
- SH_MANUALHOOK_RECONFIGURE -
- Reconfigures the indexes and offsets of a manual hook.
An example is below, using the ISomething class from above.
SH_DECL_MANUALHOOK2(_M_Function1, 1, 0, 0, bool, bool, int); void OnLoad(ISomething *pSomething) { //we reference the static function by its unique handle we gave it //the parameters are otherwise the same - this pointer, hook handler, and post/non-post SH_ADD_MANUALHOOK_STATICFUNC(_M_Function1, pSomething, MyHook1, false); } void OnUnload(ISomething *pSomething) { SH_REMOVE_MANUALHOOK_STATICFUNC(_M_Function1, pSomething, MyHook1, false); }
For more examples of the above features, you can look in SourceHook CVS's test suite, which demonstrates a variety of hooking scenarios.
1.2.2 Changes - Manual Callclasses
SourceMM 1.2.2 adds support for manual callclasses. These can be used to call manually hooked functions without invoking the hook chain. Manual callclasses work just like other callclasses with the exception that the virtual table information must be known when creating them. Here is a quick example of how to create and use them:
// Creating a manual callclass SourceHook::ManualCallClass *mcc = SH_GET_CALLCLASS(interfacePtr, sizeof(void*)); // Assuming we have this manual hook SH_DECL_MANUALHOOK0_void(Some_Hook, 1, 0, 0); // We can call the original function like so SH_MCALL(mcc, Some_Hook)(); // And when you are done with the pointer, you release the callclass like any other SH_RELEASE_CALLCLASS(mcc);
It is also possible to call a function without having a hook declaration first. In order to this, you need a MFP (member function pointer) that corresponds to the function you wish to call. The class does not matter, but SourceHook::EmptyClass can be used for this purpose. For example, if the function takes two parameters (a const char * and and bool) and returns an int, you would do the following:
// Member function pointer typedef typedef int (SourceHook::EmptyClass::*MFP_MyFunc)(const char *, bool); // Now to call the function, you do this int ret = SH_MCALL2(mcc, MFP_MyFunc(), 1, 0, 0)("hello", true);
1.2.3 Changes - Changing Parameters in Manually Hooked Functions
SourceMM 1.2.3 adds support for changing parameters in manually hooked functions with RETURN_META_(VALUE_)MNEWPARAMS. It is mostly the same as its non-manual counterpart except that it takes the unique name given when the manual hook was declared instead of a member function pointer. Here is an example using ISomething from above:
SH_DECL_MANUALHOOK2(_M_Function2, 2, 0, 0, bool, bool, int); void OnLoad(ISomething *pSomething) { SH_ADD_MANUALHOOK_STATICFUNC(_M_Function2, pSomething, MyHook2, false); } bool MyHook2(bool what, int hi) { // Change the "what" and "hi" parameters to be false and 3 respectively RETURN_META_VALUE_MNEWPARAMS(MRES_SUPERCEDE, true, _M_Function2, (false, 3)); }
1.3 Changes - Returning References
SourceMM 1.3 integrates SourceHook v4.6, which adds support for functions returning references. Luckily, this change is both backwards compatible and is transparent to the already existing macros. Thus, the code below is now valid. Note that if you don't want to actually return any reference, you can opt to use the new macro RETURN_META_NOREF instead.
class Interface { public: virtual int &GetMyInt() = 0; }; DECL_HOOK0(Interface, GetMyInt, SH_NOATTRIB, false, int &); int &Hook_GetMyInt() { static int gaben = 5; RETURN_META_VALUE(MRES_SUPERCEDE, gaben); } int &Hook_GetMyInt2() { RETURN_META_NOREF(MRES_IGNORED, int &); } void AddHook(Interface *pFace) { SH_ADDHOOK_STATICFUNC(Interface, GetMyInt, pFace, Hook_GetMyInt, false); SH_ADDHOOK_STATICFUNC(Interface, GetMyInt, pFace, Hook_GetMyInt2, true); }