mirror of
https://github.com/alliedmodders/metamod-source.git
synced 2025-12-07 10:28:30 +00:00
Initial import to CVS
--HG-- extra : convert_revision : svn%3Ac2935e3e-5518-0410-8daf-afa5dab7d4e3/trunk%402
This commit is contained in:
parent
8b7cb6fe22
commit
69bc1cf15b
2813
sourcehook/FastDelegate.h
Normal file
2813
sourcehook/FastDelegate.h
Normal file
File diff suppressed because it is too large
Load Diff
992
sourcehook/generate/FastDelegate.hxx
Normal file
992
sourcehook/generate/FastDelegate.hxx
Normal file
@ -0,0 +1,992 @@
|
||||
// FastDelegate.h
|
||||
// Efficient delegates in C++ that generate only two lines of asm code!
|
||||
// Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp
|
||||
//
|
||||
// - Don Clugston, Mar 2004.
|
||||
// Major contributions were made by Jody Hagins.
|
||||
// History:
|
||||
// 24-Apr-04 1.0 Submitted to CodeProject.
|
||||
// 28-Apr-04 1.1 * Prevent most unsafe uses of evil static function hack.
|
||||
// * Improved syntax for horrible_cast (thanks Paul Bludov).
|
||||
// * Tested on Metrowerks MWCC and Intel ICL (IA32)
|
||||
// * Compiled, but not run, on Comeau C++ and Intel Itanium ICL.
|
||||
// 27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5
|
||||
// * Now works on /clr "managed C++" code on VC7, VC7.1
|
||||
// * Comeau C++ now compiles without warnings.
|
||||
// * Prevent the virtual inheritance case from being used on
|
||||
// VC6 and earlier, which generate incorrect code.
|
||||
// * Improved warning and error messages. Non-standard hacks
|
||||
// now have compile-time checks to make them safer.
|
||||
// * implicit_cast used instead of static_cast in many cases.
|
||||
// * If calling a const member function, a const class pointer can be used.
|
||||
// * MakeDelegate() global helper function added to simplify pass-by-value.
|
||||
// * Added fastdelegate.clear()
|
||||
// 16-Jul-04 1.2.1* Workaround for gcc bug (const member function pointers in templates)
|
||||
// 30-Oct-04 1.3 * Support for (non-void) return values.
|
||||
// * No more workarounds in client code!
|
||||
// MSVC and Intel now use a clever hack invented by John Dlugosz:
|
||||
// - The FASTDELEGATEDECLARE workaround is no longer necessary.
|
||||
// - No more warning messages for VC6
|
||||
// * Less use of macros. Error messages should be more comprehensible.
|
||||
// * Added include guards
|
||||
// * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks).
|
||||
// * Now tested on VS 2005 Beta, PGI C++
|
||||
// 24-Dec-04 1.4 * Added DelegateMemento, to allow collections of disparate delegates.
|
||||
// * <,>,<=,>= comparison operators to allow storage in ordered containers.
|
||||
// * Substantial reduction of code size, especially the 'Closure' class.
|
||||
// * Standardised all the compiler-specific workarounds.
|
||||
// * MFP conversion now works for CodePlay (but not yet supported in the full code).
|
||||
// * Now compiles without warnings on _any_ compiler, including BCC 5.5.1
|
||||
// * New syntax: FastDelegate< int (char *, double) >.
|
||||
|
||||
#ifndef FASTDELEGATE_H
|
||||
#define FASTDELEGATE_H
|
||||
#if _MSC_VER > 1000
|
||||
#pragma once
|
||||
#endif // _MSC_VER > 1000
|
||||
|
||||
#include <memory.h> // to allow <,> comparisons
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Configuration options
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Uncomment the following #define for optimally-sized delegates.
|
||||
// In this case, the generated asm code is almost identical to the code you'd get
|
||||
// if the compiler had native support for delegates.
|
||||
// It will not work on systems where sizeof(dataptr) < sizeof(codeptr).
|
||||
// Thus, it will not work for DOS compilers using the medium model.
|
||||
// It will also probably fail on some DSP systems.
|
||||
#define FASTDELEGATE_USESTATICFUNCTIONHACK
|
||||
|
||||
// Uncomment the next line to allow function declarator syntax.
|
||||
// It is automatically enabled for those compilers where it is known to work.
|
||||
//#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Compiler identification for workarounds
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Compiler identification. It's not easy to identify Visual C++ because
|
||||
// many vendors fraudulently define Microsoft's identifiers.
|
||||
#if defined(_MSC_VER) && !defined(__MWERKS__) && !defined(__VECTOR_C) && !defined(__ICL) && !defined(__BORLANDC__)
|
||||
#define FASTDLGT_ISMSVC
|
||||
|
||||
#if (_MSC_VER <1300) // Many workarounds are required for VC6.
|
||||
#define FASTDLGT_VC6
|
||||
#pragma warning(disable:4786) // disable this ridiculous warning
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
// Does the compiler uses Microsoft's member function pointer structure?
|
||||
// If so, it needs special treatment.
|
||||
// Metrowerks CodeWarrior, Intel, and CodePlay fraudulently define Microsoft's
|
||||
// identifier, _MSC_VER. We need to filter Metrowerks out.
|
||||
#if defined(_MSC_VER) && !defined(__MWERKS__)
|
||||
#define FASTDLGT_MICROSOFT_MFP
|
||||
|
||||
#if !defined(__VECTOR_C)
|
||||
// CodePlay doesn't have the __single/multi/virtual_inheritance keywords
|
||||
#define FASTDLGT_HASINHERITANCE_KEYWORDS
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Does it allow function declarator syntax? The following compilers are known to work:
|
||||
#if defined(FASTDLGT_ISMSVC) && (_MSC_VER >=1310) // VC 7.1
|
||||
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
#endif
|
||||
|
||||
// Gcc(2.95+), and versions of Digital Mars, Intel and Comeau in common use.
|
||||
#if defined (__DMC__) || defined(__GNUC__) || defined(__ICL) || defined(__COMO__)
|
||||
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
#endif
|
||||
|
||||
// It works on Metrowerks MWCC 3.2.2. From boost.Config it should work on earlier ones too.
|
||||
#if defined (__MWERKS__)
|
||||
#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
#endif
|
||||
|
||||
#ifdef __GNUC__ // Workaround GCC bug #8271
|
||||
// At present, GCC doesn't recognize constness of MFPs in templates
|
||||
#define FASTDELEGATE_GCC_BUG_8271
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// General tricks used in this code
|
||||
//
|
||||
// (a) Error messages are generated by typdefing an array of negative size to
|
||||
// generate compile-time errors.
|
||||
// (b) Warning messages on MSVC are generated by declaring unused variables, and
|
||||
// enabling the "variable XXX is never used" warning.
|
||||
// (c) Unions are used in a few compiler-specific cases to perform illegal casts.
|
||||
// (d) For Microsoft and Intel, when adjusting the 'this' pointer, it's cast to
|
||||
// (char *) first to ensure that the correct number of *bytes* are added.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Helper templates
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
namespace fastdelegate {
|
||||
namespace detail { // we'll hide the implementation details in a nested namespace.
|
||||
|
||||
// implicit_cast< >
|
||||
// I believe this was originally going to be in the C++ standard but
|
||||
// was left out by accident. It's even milder than static_cast.
|
||||
// I use it instead of static_cast<> to emphasize that I'm not doing
|
||||
// anything nasty.
|
||||
// Usage is identical to static_cast<>
|
||||
template <class OutputClass, class InputClass>
|
||||
inline OutputClass implicit_cast(InputClass input){
|
||||
return input;
|
||||
}
|
||||
|
||||
// horrible_cast< >
|
||||
// This is truly evil. It completely subverts C++'s type system, allowing you
|
||||
// to cast from any class to any other class. Technically, using a union
|
||||
// to perform the cast is undefined behaviour (even in C). But we can see if
|
||||
// it is OK by checking that the union is the same size as each of its members.
|
||||
// horrible_cast<> should only be used for compiler-specific workarounds.
|
||||
// Usage is identical to reinterpret_cast<>.
|
||||
|
||||
// This union is declared outside the horrible_cast because BCC 5.5.1
|
||||
// can't inline a function with a nested class, and gives a warning.
|
||||
template <class OutputClass, class InputClass>
|
||||
union horrible_union{
|
||||
OutputClass out;
|
||||
InputClass in;
|
||||
};
|
||||
|
||||
template <class OutputClass, class InputClass>
|
||||
inline OutputClass horrible_cast(const InputClass input){
|
||||
horrible_union<OutputClass, InputClass> u;
|
||||
// Cause a compile-time error if in, out and u are not the same size.
|
||||
// If the compile fails here, it means the compiler has peculiar
|
||||
// unions which would prevent the cast from working.
|
||||
typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u)
|
||||
&& sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1];
|
||||
u.in = input;
|
||||
return u.out;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Workarounds
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Backwards compatibility: This macro used to be necessary in the virtual inheritance
|
||||
// case for Intel and Microsoft. Now it just forward-declares the class.
|
||||
#define FASTDELEGATEDECLARE(CLASSNAME) class CLASSNAME;
|
||||
|
||||
// Prevent use of the static function hack with the DOS medium model.
|
||||
#ifdef __MEDIUM__
|
||||
#undef FASTDELEGATE_USESTATICFUNCTIONHACK
|
||||
#endif
|
||||
|
||||
// DefaultVoid - a workaround for 'void' templates in VC6.
|
||||
//
|
||||
// (1) VC6 and earlier do not allow 'void' as a default template argument.
|
||||
// (2) They also doesn't allow you to return 'void' from a function.
|
||||
//
|
||||
// Workaround for (1): Declare a dummy type 'DefaultVoid' which we use
|
||||
// when we'd like to use 'void'. We convert it into 'void' and back
|
||||
// using the templates DefaultVoidToVoid<> and VoidToDefaultVoid<>.
|
||||
// Workaround for (2): On VC6, the code for calling a void function is
|
||||
// identical to the code for calling a non-void function in which the
|
||||
// return value is never used, provided the return value is returned
|
||||
// in the EAX register, rather than on the stack.
|
||||
// This is true for most fundamental types such as int, enum, void *.
|
||||
// Const void * is the safest option since it doesn't participate
|
||||
// in any automatic conversions. But on a 16-bit compiler it might
|
||||
// cause extra code to be generated, so we disable it for all compilers
|
||||
// except for VC6 (and VC5).
|
||||
#ifdef FASTDLGT_VC6
|
||||
// VC6 workaround
|
||||
typedef const void * DefaultVoid;
|
||||
#else
|
||||
// On any other compiler, just use a normal void.
|
||||
typedef void DefaultVoid;
|
||||
#endif
|
||||
|
||||
// Translate from 'DefaultVoid' to 'void'.
|
||||
// Everything else is unchanged
|
||||
template <class T>
|
||||
struct DefaultVoidToVoid { typedef T type; };
|
||||
|
||||
template <>
|
||||
struct DefaultVoidToVoid<DefaultVoid> { typedef void type; };
|
||||
|
||||
// Translate from 'void' into 'DefaultVoid'
|
||||
// Everything else is unchanged
|
||||
template <class T>
|
||||
struct VoidToDefaultVoid { typedef T type; };
|
||||
|
||||
template <>
|
||||
struct VoidToDefaultVoid<void> { typedef DefaultVoid type; };
|
||||
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 1:
|
||||
//
|
||||
// Conversion of member function pointer to a standard form
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// GenericClass is a fake class, ONLY used to provide a type.
|
||||
// It is vitally important that it is never defined, so that the compiler doesn't
|
||||
// think it can optimize the invocation. For example, Borland generates simpler
|
||||
// code if it knows the class only uses single inheritance.
|
||||
|
||||
// Compilers using Microsoft's structure need to be treated as a special case.
|
||||
#ifdef FASTDLGT_MICROSOFT_MFP
|
||||
|
||||
#ifdef FASTDLGT_HASINHERITANCE_KEYWORDS
|
||||
// For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP
|
||||
// (4 bytes), even when the /vmg option is used. Declaring an empty class
|
||||
// would give 16 byte pointers in this case....
|
||||
class __single_inheritance GenericClass;
|
||||
#endif
|
||||
// ...but for Codeplay, an empty class *always* gives 4 byte pointers.
|
||||
// If compiled with the /clr option ("managed C++"), the JIT compiler thinks
|
||||
// it needs to load GenericClass before it can call any of its functions,
|
||||
// (compiles OK but crashes at runtime!), so we need to declare an
|
||||
// empty class to make it happy.
|
||||
// Codeplay and VC4 can't cope with the unknown_inheritance case either.
|
||||
class GenericClass {};
|
||||
#else
|
||||
class GenericClass;
|
||||
#endif
|
||||
|
||||
// The size of a single inheritance member function pointer.
|
||||
const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)());
|
||||
|
||||
// SimplifyMemFunc< >::Convert()
|
||||
//
|
||||
// A template function that converts an arbitrary member function pointer into the
|
||||
// simplest possible form of member function pointer, using a supplied 'this' pointer.
|
||||
// According to the standard, this can be done legally with reinterpret_cast<>.
|
||||
// For (non-standard) compilers which use member function pointers which vary in size
|
||||
// depending on the class, we need to use knowledge of the internal structure of a
|
||||
// member function pointer, as used by the compiler. Template specialization is used
|
||||
// to distinguish between the sizes. Because some compilers don't support partial
|
||||
// template specialisation, I use full specialisation of a wrapper struct.
|
||||
|
||||
// general case -- don't know how to convert it. Force a compile failure
|
||||
template <int N>
|
||||
struct SimplifyMemFunc {
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
// Unsupported member function type -- force a compile failure.
|
||||
// (it's illegal to have a array with negative size).
|
||||
typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100];
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// For compilers where all member func ptrs are the same size, everything goes here.
|
||||
// For non-standard compilers, only single_inheritance classes go here.
|
||||
template <>
|
||||
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE> {
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
#if defined __DMC__
|
||||
// Digital Mars doesn't allow you to cast between abitrary PMF's,
|
||||
// even though the standard says you can. The 32-bit compiler lets you
|
||||
// static_cast through an int, but the DOS compiler doesn't.
|
||||
bound_func = horrible_cast<GenericMemFuncType>(function_to_bind);
|
||||
#else
|
||||
bound_func = reinterpret_cast<GenericMemFuncType>(function_to_bind);
|
||||
#endif
|
||||
return reinterpret_cast<GenericClass *>(pthis);
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 1b:
|
||||
//
|
||||
// Workarounds for Microsoft and Intel
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
// Compilers with member function pointers which violate the standard (MSVC, Intel, Codeplay),
|
||||
// need to be treated as a special case.
|
||||
#ifdef FASTDLGT_MICROSOFT_MFP
|
||||
|
||||
// We use unions to perform horrible_casts. I would like to use #pragma pack(push, 1)
|
||||
// at the start of each function for extra safety, but VC6 seems to ICE
|
||||
// intermittently if you do this inside a template.
|
||||
|
||||
// __multiple_inheritance classes go here
|
||||
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
|
||||
template<>
|
||||
struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > {
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
// We need to use a horrible_cast to do this conversion.
|
||||
// In MSVC, a multiple inheritance member pointer is internally defined as:
|
||||
union {
|
||||
XFuncType func;
|
||||
struct {
|
||||
GenericMemFuncType funcaddress; // points to the actual member function
|
||||
int delta; // #BYTES to be added to the 'this' pointer
|
||||
}s;
|
||||
} u;
|
||||
// Check that the horrible_cast will work
|
||||
typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1];
|
||||
u.func = function_to_bind;
|
||||
bound_func = u.s.funcaddress;
|
||||
return reinterpret_cast<GenericClass *>(reinterpret_cast<char *>(pthis) + u.s.delta);
|
||||
}
|
||||
};
|
||||
|
||||
// virtual inheritance is a real nuisance. It's inefficient and complicated.
|
||||
// On MSVC and Intel, there isn't enough information in the pointer itself to
|
||||
// enable conversion to a closure pointer. Earlier versions of this code didn't
|
||||
// work for all cases, and generated a compile-time error instead.
|
||||
// But a very clever hack invented by John M. Dlugosz solves this problem.
|
||||
// My code is somewhat different to his: I have no asm code, and I make no
|
||||
// assumptions about the calling convention that is used.
|
||||
|
||||
// In VC++ and ICL, a virtual_inheritance member pointer
|
||||
// is internally defined as:
|
||||
struct MicrosoftVirtualMFP {
|
||||
void (GenericClass::*codeptr)(); // points to the actual member function
|
||||
int delta; // #bytes to be added to the 'this' pointer
|
||||
int vtable_index; // or 0 if no virtual inheritance
|
||||
};
|
||||
// The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the
|
||||
// m_codeptr member is *always* called, regardless of the values of the other
|
||||
// members. (This is *not* true for other compilers, eg GCC, which obtain the
|
||||
// function address from the vtable if a virtual function is being called).
|
||||
// Dlugosz's trick is to make the codeptr point to a probe function which
|
||||
// returns the 'this' pointer that was used.
|
||||
|
||||
// Define a generic class that uses virtual inheritance.
|
||||
// It has a trival member function that returns the value of the 'this' pointer.
|
||||
struct GenericVirtualClass : virtual public GenericClass
|
||||
{
|
||||
typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)();
|
||||
GenericVirtualClass * GetThis() { return this; }
|
||||
};
|
||||
|
||||
// __virtual_inheritance classes go here
|
||||
template <>
|
||||
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 2*sizeof(int) >
|
||||
{
|
||||
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
union {
|
||||
XFuncType func;
|
||||
GenericClass* (X::*ProbeFunc)();
|
||||
MicrosoftVirtualMFP s;
|
||||
} u;
|
||||
u.func = function_to_bind;
|
||||
bound_func = reinterpret_cast<GenericMemFuncType>(u.s.codeptr);
|
||||
union {
|
||||
GenericVirtualClass::ProbePtrType virtfunc;
|
||||
MicrosoftVirtualMFP s;
|
||||
} u2;
|
||||
// Check that the horrible_cast<>s will work
|
||||
typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)
|
||||
&& sizeof(function_to_bind)==sizeof(u.ProbeFunc)
|
||||
&& sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1];
|
||||
// Unfortunately, taking the address of a MF prevents it from being inlined, so
|
||||
// this next line can't be completely optimised away by the compiler.
|
||||
u2.virtfunc = &GenericVirtualClass::GetThis;
|
||||
u.s.codeptr = u2.s.codeptr;
|
||||
return (pthis->*u.ProbeFunc)();
|
||||
}
|
||||
};
|
||||
|
||||
#if (_MSC_VER <1300)
|
||||
|
||||
// Nasty hack for Microsoft Visual C++ 6.0
|
||||
// unknown_inheritance classes go here
|
||||
// There is a compiler bug in MSVC6 which generates incorrect code in this case!!
|
||||
template <>
|
||||
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
|
||||
{
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
// There is an apalling but obscure compiler bug in MSVC6 and earlier:
|
||||
// vtable_index and 'vtordisp' are always set to 0 in the
|
||||
// unknown_inheritance case!
|
||||
// This means that an incorrect function could be called!!!
|
||||
// Compiling with the /vmg option leads to potentially incorrect code.
|
||||
// This is probably the reason that the IDE has a user interface for specifying
|
||||
// the /vmg option, but it is disabled - you can only specify /vmg on
|
||||
// the command line. In VC1.5 and earlier, the compiler would ICE if it ever
|
||||
// encountered this situation.
|
||||
// It is OK to use the /vmg option if /vmm or /vms is specified.
|
||||
|
||||
// Fortunately, the wrong function is only called in very obscure cases.
|
||||
// It only occurs when a derived class overrides a virtual function declared
|
||||
// in a virtual base class, and the member function
|
||||
// points to the *Derived* version of that function. The problem can be
|
||||
// completely averted in 100% of cases by using the *Base class* for the
|
||||
// member fpointer. Ie, if you use the base class as an interface, you'll
|
||||
// stay out of trouble.
|
||||
// Occasionally, you might want to point directly to a derived class function
|
||||
// that isn't an override of a base class. In this case, both vtable_index
|
||||
// and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated.
|
||||
// We can generate correct code in this case. To prevent an incorrect call from
|
||||
// ever being made, on MSVC6 we generate a warning, and call a function to
|
||||
// make the program crash instantly.
|
||||
typedef char ERROR_VC6CompilerBug[-100];
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
#else
|
||||
|
||||
// Nasty hack for Microsoft and Intel (IA32 and Itanium)
|
||||
// unknown_inheritance classes go here
|
||||
// This is probably the ugliest bit of code I've ever written. Look at the casts!
|
||||
// There is a compiler bug in MSVC6 which prevents it from using this code.
|
||||
template <>
|
||||
struct SimplifyMemFunc<SINGLE_MEMFUNCPTR_SIZE + 3*sizeof(int) >
|
||||
{
|
||||
template <class X, class XFuncType, class GenericMemFuncType>
|
||||
inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind,
|
||||
GenericMemFuncType &bound_func) {
|
||||
// The member function pointer is 16 bytes long. We can't use a normal cast, but
|
||||
// we can use a union to do the conversion.
|
||||
union {
|
||||
XFuncType func;
|
||||
// In VC++ and ICL, an unknown_inheritance member pointer
|
||||
// is internally defined as:
|
||||
struct {
|
||||
GenericMemFuncType m_funcaddress; // points to the actual member function
|
||||
int delta; // #bytes to be added to the 'this' pointer
|
||||
int vtordisp; // #bytes to add to 'this' to find the vtable
|
||||
int vtable_index; // or 0 if no virtual inheritance
|
||||
} s;
|
||||
} u;
|
||||
// Check that the horrible_cast will work
|
||||
typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1];
|
||||
u.func = function_to_bind;
|
||||
bound_func = u.s.funcaddress;
|
||||
int virtual_delta = 0;
|
||||
if (u.s.vtable_index) { // Virtual inheritance is used
|
||||
// First, get to the vtable.
|
||||
// It is 'vtordisp' bytes from the start of the class.
|
||||
const int * vtable = *reinterpret_cast<const int *const*>(
|
||||
reinterpret_cast<const char *>(pthis) + u.s.vtordisp );
|
||||
|
||||
// 'vtable_index' tells us where in the table we should be looking.
|
||||
virtual_delta = u.s.vtordisp + *reinterpret_cast<const int *>(
|
||||
reinterpret_cast<const char *>(vtable) + u.s.vtable_index);
|
||||
}
|
||||
// The int at 'virtual_delta' gives us the amount to add to 'this'.
|
||||
// Finally we can add the three components together. Phew!
|
||||
return reinterpret_cast<GenericClass *>(
|
||||
reinterpret_cast<char *>(pthis) + u.s.delta + virtual_delta);
|
||||
};
|
||||
};
|
||||
#endif // MSVC 7 and greater
|
||||
|
||||
#endif // MS/Intel hacks
|
||||
|
||||
} // namespace detail
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 2:
|
||||
//
|
||||
// Define the delegate storage, and cope with static functions
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// DelegateMemento -- an opaque structure which can hold an arbitary delegate.
|
||||
// It knows nothing about the calling convention or number of arguments used by
|
||||
// the function pointed to.
|
||||
// It supplies comparison operators so that it can be stored in STL collections.
|
||||
// It cannot be set to anything other than null, nor invoked directly:
|
||||
// it must be converted to a specific delegate.
|
||||
|
||||
// Implementation:
|
||||
// There are two possible implementations: the Safe method and the Evil method.
|
||||
// DelegateMemento - Safe version
|
||||
//
|
||||
// This implementation is standard-compliant, but a bit tricky.
|
||||
// A static function pointer is stored inside the class.
|
||||
// Here are the valid values:
|
||||
// +-- Static pointer --+--pThis --+-- pMemFunc-+-- Meaning------+
|
||||
// | 0 | 0 | 0 | Empty |
|
||||
// | !=0 |(dontcare)| Invoker | Static function|
|
||||
// | 0 | !=0 | !=0 | Method call |
|
||||
// +--------------------+----------+------------+----------------+
|
||||
// When stored stored inside a specific delegate, the 'dontcare' entries are replaced
|
||||
// with a reference to the delegate itself. This complicates the = and == operators
|
||||
// for the delegate class.
|
||||
|
||||
// DelegateMemento - Evil version
|
||||
//
|
||||
// For compilers where data pointers are at least as big as code pointers, it is
|
||||
// possible to store the function pointer in the this pointer, using another
|
||||
// horrible_cast. In this case the DelegateMemento implementation is simple:
|
||||
// +--pThis --+-- pMemFunc-+-- Meaning---------------------+
|
||||
// | 0 | 0 | Empty |
|
||||
// | !=0 | !=0 | Static function or method call|
|
||||
// +----------+------------+-------------------------------+
|
||||
// Note that the Sun C++ and MSVC documentation explicitly state that they
|
||||
// support static_cast between void * and function pointers.
|
||||
|
||||
class DelegateMemento {
|
||||
protected:
|
||||
// the data is protected, not private, because many
|
||||
// compilers have problems with template friends.
|
||||
typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP.
|
||||
detail::GenericClass *m_pthis;
|
||||
GenericMemFuncType m_pFunction;
|
||||
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
typedef void (*GenericFuncPtr)(); // arbitrary code pointer
|
||||
GenericFuncPtr m_pStaticFunction;
|
||||
#endif
|
||||
|
||||
public:
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {};
|
||||
void clear() {
|
||||
m_pthis=0; m_pFunction=0; m_pStaticFunction=0;
|
||||
}
|
||||
#else
|
||||
DelegateMemento() : m_pthis(0), m_pFunction(0) {};
|
||||
void clear() {
|
||||
m_pthis=0; m_pFunction=0;
|
||||
}
|
||||
#endif
|
||||
public:
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
inline bool IsEqual (const DelegateMemento &x) const{
|
||||
// We have to cope with the static function pointers as a special case
|
||||
if (m_pFunction!=x.m_pFunction) return false;
|
||||
// the static function ptrs must either both be equal, or both be 0.
|
||||
if (m_pStaticFunction!=x.m_pStaticFunction) return false;
|
||||
if (m_pStaticFunction!=0) return m_pthis==x.m_pthis;
|
||||
else return true;
|
||||
}
|
||||
#else // Evil Method
|
||||
inline bool IsEqual (const DelegateMemento &x) const{
|
||||
return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction;
|
||||
}
|
||||
#endif
|
||||
// Provide a strict weak ordering for DelegateMementos.
|
||||
inline bool IsLess(const DelegateMemento &right) const {
|
||||
// deal with static function pointers first
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0)
|
||||
return m_pStaticFunction < right.m_pStaticFunction;
|
||||
#endif
|
||||
if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis;
|
||||
// There are no ordering operators for member function pointers,
|
||||
// but we can fake one by comparing each byte. The resulting ordering is
|
||||
// arbitrary (and compiler-dependent), but it permits storage in ordered STL containers.
|
||||
return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0;
|
||||
|
||||
}
|
||||
inline bool operator ! () const // Is it bound to anything?
|
||||
{ return m_pFunction==0; }
|
||||
public:
|
||||
DelegateMemento & operator = (const DelegateMemento &right) {
|
||||
SetMementoFrom(right);
|
||||
return *this;
|
||||
}
|
||||
inline bool operator <(const DelegateMemento &right) {
|
||||
return IsLess(right);
|
||||
}
|
||||
inline bool operator >(const DelegateMemento &right) {
|
||||
return right.IsLess(*this);
|
||||
}
|
||||
DelegateMemento (const DelegateMemento &right) :
|
||||
m_pFunction(right.m_pFunction), m_pthis(right.m_pthis)
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
, m_pStaticFunction (right.m_pStaticFunction)
|
||||
#endif
|
||||
{}
|
||||
protected:
|
||||
void SetMementoFrom(const DelegateMemento &right) {
|
||||
m_pFunction = right.m_pFunction;
|
||||
m_pthis = right.m_pthis;
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
m_pStaticFunction = right.m_pStaticFunction;
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// ClosurePtr<>
|
||||
//
|
||||
// A private wrapper class that adds function signatures to DelegateMemento.
|
||||
// It's the class that does most of the actual work.
|
||||
// The signatures are specified by:
|
||||
// GenericMemFunc: must be a type of GenericClass member function pointer.
|
||||
// StaticFuncPtr: must be a type of function pointer with the same signature
|
||||
// as GenericMemFunc.
|
||||
// UnvoidStaticFuncPtr: is the same as StaticFuncPtr, except on VC6
|
||||
// where it never returns void (returns DefaultVoid instead).
|
||||
|
||||
// An outer class, FastDelegateN<>, handles the invoking and creates the
|
||||
// necessary typedefs.
|
||||
// This class does everything else.
|
||||
|
||||
namespace detail {
|
||||
|
||||
template < class GenericMemFunc, class StaticFuncPtr, class UnvoidStaticFuncPtr>
|
||||
class ClosurePtr : public DelegateMemento {
|
||||
public:
|
||||
// These functions are for setting the delegate to a member function.
|
||||
|
||||
// Here's the clever bit: we convert an arbitrary member function into a
|
||||
// standard form. XMemFunc should be a member function of class X, but I can't
|
||||
// enforce that here. It needs to be enforced by the wrapper class.
|
||||
template < class X, class XMemFunc >
|
||||
inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) {
|
||||
m_pthis = SimplifyMemFunc< sizeof(function_to_bind) >
|
||||
::Convert(pthis, function_to_bind, m_pFunction);
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
m_pStaticFunction = 0;
|
||||
#endif
|
||||
}
|
||||
// For const member functions, we only need a const class pointer.
|
||||
// Since we know that the member function is const, it's safe to
|
||||
// remove the const qualifier from the 'this' pointer with a const_cast.
|
||||
// VC6 has problems if we just overload 'bindmemfunc', so we give it a different name.
|
||||
template < class X, class XMemFunc>
|
||||
inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) {
|
||||
m_pthis= SimplifyMemFunc< sizeof(function_to_bind) >
|
||||
::Convert(const_cast<X*>(pthis), function_to_bind, m_pFunction);
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
m_pStaticFunction = 0;
|
||||
#endif
|
||||
}
|
||||
#ifdef FASTDELEGATE_GCC_BUG_8271 // At present, GCC doesn't recognize constness of MFPs in templates
|
||||
template < class X, class XMemFunc>
|
||||
inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) {
|
||||
bindconstmemfunc(pthis, function_to_bind);
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
m_pStaticFunction = 0;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
// These functions are required for invoking the stored function
|
||||
inline GenericClass *GetClosureThis() const { return m_pthis; }
|
||||
inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast<GenericMemFunc>(m_pFunction); }
|
||||
|
||||
// There are a few ways of dealing with static function pointers.
|
||||
// There's a standard-compliant, but tricky method.
|
||||
// There's also a straightforward hack, that won't work on DOS compilers using the
|
||||
// medium memory model. It's so evil that I can't recommend it, but I've
|
||||
// implemented it anyway because it produces very nice asm code.
|
||||
|
||||
#if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
|
||||
// ClosurePtr<> - Safe version
|
||||
//
|
||||
// This implementation is standard-compliant, but a bit tricky.
|
||||
// I store the function pointer inside the class, and the delegate then
|
||||
// points to itself. Whenever the delegate is copied, these self-references
|
||||
// must be transformed, and this complicates the = and == operators.
|
||||
public:
|
||||
// The next two functions are for operator ==, =, and the copy constructor.
|
||||
// We may need to convert the m_pthis pointers, so that
|
||||
// they remain as self-references.
|
||||
template< class DerivedClass >
|
||||
inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) {
|
||||
SetMementoFrom(x);
|
||||
if (m_pStaticFunction!=0) {
|
||||
// transform self references...
|
||||
m_pthis=reinterpret_cast<GenericClass *>(pParent);
|
||||
}
|
||||
}
|
||||
// For static functions, the 'static_function_invoker' class in the parent
|
||||
// will be called. The parent then needs to call GetStaticFunction() to find out
|
||||
// the actual function to invoke.
|
||||
template < class DerivedClass, class ParentInvokerSig >
|
||||
inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
|
||||
StaticFuncPtr function_to_bind ) {
|
||||
bindmemfunc(pParent, static_function_invoker);
|
||||
m_pStaticFunction=reinterpret_cast<GenericFuncPtr>(function_to_bind);
|
||||
}
|
||||
inline UnvoidStaticFuncPtr GetStaticFunction() const {
|
||||
return reinterpret_cast<UnvoidStaticFuncPtr>(m_pStaticFunction);
|
||||
}
|
||||
#else
|
||||
|
||||
// ClosurePtr<> - Evil version
|
||||
//
|
||||
// For compilers where data pointers are at least as big as code pointers, it is
|
||||
// possible to store the function pointer in the this pointer, using another
|
||||
// horrible_cast. Invocation isn't any faster, but it saves 4 bytes, and
|
||||
// speeds up comparison and assignment. If C++ provided direct language support
|
||||
// for delegates, they would produce asm code that was almost identical to this.
|
||||
// Note that the Sun C++ and MSVC documentation explicitly state that they
|
||||
// support static_cast between void * and function pointers.
|
||||
|
||||
template< class DerivedClass >
|
||||
inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) {
|
||||
SetMementoFrom(right);
|
||||
}
|
||||
// For static functions, the 'static_function_invoker' class in the parent
|
||||
// will be called. The parent then needs to call GetStaticFunction() to find out
|
||||
// the actual function to invoke.
|
||||
// ******** EVIL, EVIL CODE! *******
|
||||
template < class DerivedClass, class ParentInvokerSig>
|
||||
inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker,
|
||||
StaticFuncPtr function_to_bind) {
|
||||
// We'll be ignoring the 'this' pointer, but we need to make sure we pass
|
||||
// a valid value to bindmemfunc().
|
||||
bindmemfunc(pParent, static_function_invoker);
|
||||
|
||||
// WARNING! Evil hack. We store the function in the 'this' pointer!
|
||||
// Ensure that there's a compilation failure if function pointers
|
||||
// and data pointers have different sizes.
|
||||
// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
|
||||
typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1];
|
||||
m_pthis = horrible_cast<GenericClass *>(function_to_bind);
|
||||
// MSVC, SunC++ and DMC accept the following (non-standard) code:
|
||||
// m_pthis = static_cast<GenericClass *>(static_cast<void *>(function_to_bind));
|
||||
// BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long
|
||||
// m_pthis = reinterpret_cast<GenericClass *>(reinterpret_cast<long>(function_to_bind));
|
||||
}
|
||||
// ******** EVIL, EVIL CODE! *******
|
||||
// This function will be called with an invalid 'this' pointer!!
|
||||
// We're just returning the 'this' pointer, converted into
|
||||
// a function pointer!
|
||||
inline UnvoidStaticFuncPtr GetStaticFunction() const {
|
||||
// Ensure that there's a compilation failure if function pointers
|
||||
// and data pointers have different sizes.
|
||||
// If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK.
|
||||
typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1];
|
||||
return horrible_cast<UnvoidStaticFuncPtr>(this);
|
||||
}
|
||||
#endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK)
|
||||
|
||||
};
|
||||
|
||||
|
||||
} // namespace detail
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 3:
|
||||
//
|
||||
// Wrapper classes to ensure type safety
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
// Once we have the member function conversion templates, it's easy to make the
|
||||
// wrapper classes. So that they will work with as many compilers as possible,
|
||||
// the classes are of the form
|
||||
// FastDelegate3<int, char *, double>
|
||||
// They can cope with any combination of parameters. The max number of parameters
|
||||
// allowed is 8, but it is trivial to increase this limit.
|
||||
// Note that we need to treat const member functions seperately.
|
||||
// All this class does is to enforce type safety, and invoke the delegate with
|
||||
// the correct list of parameters.
|
||||
|
||||
// Because of the weird rule about the class of derived member function pointers,
|
||||
// you sometimes need to apply a downcast to the 'this' pointer.
|
||||
// This is the reason for the use of "implicit_cast<X*>(pthis)" in the code below.
|
||||
// If CDerivedClass is derived from CBaseClass, but doesn't override SimpleVirtualFunction,
|
||||
// without this trick you'd need to write:
|
||||
// MyDelegate(static_cast<CBaseClass *>(&d), &CDerivedClass::SimpleVirtualFunction);
|
||||
// but with the trick you can write
|
||||
// MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction);
|
||||
|
||||
// RetType is the type the compiler uses in compiling the template. For VC6,
|
||||
// it cannot be void. DesiredRetType is the real type which is returned from
|
||||
// all of the functions. It can be void.
|
||||
|
||||
@VARARGS
|
||||
template<@CLASSARGS, class RetType=detail::DefaultVoid>
|
||||
class FastDelegate@NUM {
|
||||
private:
|
||||
typedef typename detail::DefaultVoidToVoid<RetType>::type DesiredRetType;
|
||||
typedef DesiredRetType (*StaticFunctionPtr)(@FUNCARGS);
|
||||
typedef RetType (*UnvoidStaticFunctionPtr)(@FUNCARGS);
|
||||
typedef RetType (detail::GenericClass::*GenericMemFn)(@FUNCARGS);
|
||||
detail::ClosurePtr<GenericMemFn, StaticFunctionPtr, UnvoidStaticFunctionPtr> m_Closure;
|
||||
public:
|
||||
// Typedefs to aid generic programming
|
||||
typedef FastDelegate@NUM type;
|
||||
|
||||
// Construction and comparison functions
|
||||
FastDelegate@NUM() { clear(); }
|
||||
FastDelegate@NUM(const FastDelegate@NUM &x) {
|
||||
m_Closure.CopyFrom(this, x.m_Closure); }
|
||||
void operator = (const FastDelegate@NUM &x) {
|
||||
m_Closure.CopyFrom(this, x.m_Closure); }
|
||||
bool operator ==(const FastDelegate@NUM &x) const {
|
||||
return m_Closure.IsEqual(x.m_Closure); }
|
||||
bool operator !=(const FastDelegate@NUM &x) const {
|
||||
return !m_Closure.IsEqual(x.m_Closure); }
|
||||
bool operator <(const FastDelegate@NUM &x) const {
|
||||
return m_Closure.IsLess(x.m_Closure); }
|
||||
bool operator >(const FastDelegate@NUM &x) const {
|
||||
return x.m_Closure.IsLess(m_Closure); }
|
||||
// Binding to non-const member functions
|
||||
template < class X, class Y >
|
||||
FastDelegate@NUM(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) ) {
|
||||
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
|
||||
template < class X, class Y >
|
||||
inline void bind(Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS)) {
|
||||
m_Closure.bindmemfunc(detail::implicit_cast<X*>(pthis), function_to_bind); }
|
||||
// Binding to const member functions.
|
||||
template < class X, class Y >
|
||||
FastDelegate@NUM(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
|
||||
m_Closure.bindconstmemfunc(detail::implicit_cast<const X*>(pthis), function_to_bind); }
|
||||
template < class X, class Y >
|
||||
inline void bind(const Y *pthis, DesiredRetType (X::* function_to_bind)(@FUNCARGS) const) {
|
||||
m_Closure.bindconstmemfunc(detail::implicit_cast<const X *>(pthis), function_to_bind); }
|
||||
// Static functions. We convert them into a member function call.
|
||||
// Note that this also provides a conversion from static functions.
|
||||
FastDelegate@NUM(DesiredRetType (*function_to_bind)(@FUNCARGS) ) {
|
||||
bind(function_to_bind); }
|
||||
inline void bind(DesiredRetType (*function_to_bind)(@FUNCARGS)) {
|
||||
m_Closure.bindstaticfunc(this, &FastDelegate@NUM::InvokeStaticFunction,
|
||||
function_to_bind); }
|
||||
RetType operator() (@FUNCARGS) const { // Invoke the delegate
|
||||
// this next line is the only one that violates the standard
|
||||
return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(@INVOKEARGS); }
|
||||
inline bool operator ! () const { // Is it bound to anything?
|
||||
return !m_Closure; }
|
||||
inline bool empty() const {
|
||||
return !m_Closure; }
|
||||
void clear() { m_Closure.clear();}
|
||||
// Conversion to and from the DelegateMemento storage class
|
||||
const DelegateMemento & GetMemento() { return m_Closure; }
|
||||
void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); }
|
||||
|
||||
private: // Invoker for static functions
|
||||
RetType InvokeStaticFunction(@FUNCARGS) const {
|
||||
return (*(m_Closure.GetStaticFunction()))(@INVOKEARGS); }
|
||||
};
|
||||
|
||||
@ENDVAR
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 4:
|
||||
//
|
||||
// FastDelegate<> class (Original author: Jody Hagins)
|
||||
// Allows boost::function style syntax like:
|
||||
// FastDelegate< double (int, long) >
|
||||
// instead of:
|
||||
// FastDelegate2< int, long, double >
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
|
||||
// Declare FastDelegate as a class template. It will be specialized
|
||||
// later for all number of arguments.
|
||||
template <typename Signature>
|
||||
class FastDelegate;
|
||||
|
||||
@VARARGS
|
||||
// Specialization to allow use of
|
||||
// FastDelegate< R ( @SELARGS ) >
|
||||
// instead of
|
||||
// FastDelegate@NUM < @SELARGS, R >
|
||||
template<typename R, @CLASSARGS>
|
||||
class FastDelegate< R ( @SELARGS ) >
|
||||
// Inherit from FastDelegate@NUM so that it can be treated just
|
||||
// like a FastDelegate@NUM
|
||||
: public FastDelegate@NUM < @SELARGS, R >
|
||||
{
|
||||
public:
|
||||
// Make using the base type a bit easier via typedef.
|
||||
typedef FastDelegate@NUM < @SELARGS, R > BaseType;
|
||||
|
||||
// Allow users access to the specific type of this delegate.
|
||||
typedef FastDelegate SelfType;
|
||||
|
||||
// Mimic the base class constructors.
|
||||
FastDelegate() : BaseType() { }
|
||||
|
||||
template < class X, class Y >
|
||||
FastDelegate(Y * pthis,
|
||||
R (X::* function_to_bind)( @FUNCARGS ))
|
||||
: BaseType(pthis, function_to_bind) { }
|
||||
|
||||
template < class X, class Y >
|
||||
FastDelegate(const Y *pthis,
|
||||
R (X::* function_to_bind)( @FUNCARGS ) const)
|
||||
: BaseType(pthis, function_to_bind)
|
||||
{ }
|
||||
|
||||
FastDelegate(R (*function_to_bind)( @FUNCARGS ))
|
||||
: BaseType(function_to_bind) { }
|
||||
void operator = (const BaseType &x) {
|
||||
*static_cast<BaseType*>(this) = x; }
|
||||
};
|
||||
|
||||
@ENDVAR
|
||||
|
||||
#endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Fast Delegates, part 5:
|
||||
//
|
||||
// MakeDelegate() helper function
|
||||
//
|
||||
// MakeDelegate(&x, &X::func) returns a fastdelegate of the type
|
||||
// necessary for calling x.func() with the correct number of arguments.
|
||||
// This makes it possible to eliminate many typedefs from user code.
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Also declare overloads of a MakeDelegate() global function to
|
||||
// reduce the need for typedefs.
|
||||
// We need seperate overloads for const and non-const member functions.
|
||||
// Also, because of the weird rule about the class of derived member function pointers,
|
||||
// implicit downcasts may need to be applied later to the 'this' pointer.
|
||||
// That's why two classes (X and Y) appear in the definitions. Y must be implicitly
|
||||
// castable to X.
|
||||
|
||||
// Workaround for VC6. VC6 needs void return types converted into DefaultVoid.
|
||||
// GCC 3.2 and later won't compile this unless it's preceded by 'typename',
|
||||
// but VC6 doesn't allow 'typename' in this context.
|
||||
// So, I have to use a macro.
|
||||
|
||||
#ifdef FASTDLGT_VC6
|
||||
#define FASTDLGT_RETTYPE detail::VoidToDefaultVoid<RetType>::type
|
||||
#else
|
||||
#define FASTDLGT_RETTYPE RetType
|
||||
#endif
|
||||
|
||||
@VARARGS
|
||||
template <class X, class Y, @CLASSARGS, class RetType>
|
||||
FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS)) {
|
||||
return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
|
||||
}
|
||||
|
||||
template <class X, class Y, @CLASSARGS, class RetType>
|
||||
FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE> MakeDelegate(Y* x, RetType (X::*func)(@FUNCARGS) const) {
|
||||
return FastDelegate@NUM<@SELARGS, FASTDLGT_RETTYPE>(x, func);
|
||||
}
|
||||
|
||||
@ENDVAR
|
||||
|
||||
// clean up after ourselves...
|
||||
#undef FASTDLGT_RETTYPE
|
||||
|
||||
} // namespace fastdelegate
|
||||
|
||||
#endif // !defined(FASTDELEGATE_H)
|
||||
|
||||
7
sourcehook/generate/generate.bat
Normal file
7
sourcehook/generate/generate.bat
Normal file
@ -0,0 +1,7 @@
|
||||
:: Generates everything
|
||||
:: Usage:
|
||||
:: generate.bat <num-of-arguments>
|
||||
|
||||
|
||||
shworker iter %1 sourcehook.hxx sourcehook.h
|
||||
shworker hopter %1 FastDelegate.hxx FastDelegate.h
|
||||
BIN
sourcehook/generate/shworker.exe
Normal file
BIN
sourcehook/generate/shworker.exe
Normal file
Binary file not shown.
15
sourcehook/generate/shworker/Makefile
Normal file
15
sourcehook/generate/shworker/Makefile
Normal file
@ -0,0 +1,15 @@
|
||||
default: shworker
|
||||
|
||||
bin:
|
||||
mkdir bin
|
||||
|
||||
fd_hopter.o: fd_hopter.cpp
|
||||
gcc -fPIC -o bin/$@ -c $<
|
||||
|
||||
main.o: main.cpp
|
||||
gcc -fPIC -o bin/$@ -c $<
|
||||
|
||||
shworker: fd_hopter.o main.o
|
||||
gcc -ldl -lstdc++ bin/fd_hopter.o bin/main.o -o bin/shworker
|
||||
|
||||
|
||||
370
sourcehook/generate/shworker/fd_hopter.cpp
Normal file
370
sourcehook/generate/shworker/fd_hopter.cpp
Normal file
@ -0,0 +1,370 @@
|
||||
// From fastdelegate
|
||||
// http://www.codeproject.com/cpp/FastDelegate.asp
|
||||
|
||||
// Modified to be run from shworker by PM
|
||||
|
||||
|
||||
// HOPTER.EXE -- A simple header generator for vararg templates
|
||||
/* MOTIVATION
|
||||
C++ doesn't have a vararg feature for templates. This can be a
|
||||
nuisance when writing class libraries. There are a few options:
|
||||
(a) manually repeat code. This is tedious and error prone.
|
||||
(b) Use macros. Messy, can't cope with template
|
||||
arguments, and users get hard-to-interpret error messages.
|
||||
(c) Use the boost preprocessor library. This slows compilation,
|
||||
and introduces a dependency on boost.
|
||||
(d) Write a program to automatically generate the code.
|
||||
I've never seen a general program to do this job, so this is
|
||||
a very simple command-line program to do it.
|
||||
|
||||
Why is it called Hopter?
|
||||
I wanted a word that started with h, to be reminiscent of header
|
||||
files. At the time, my 2yo son kept talking about 'Hopter Copters'
|
||||
(he couldn't pronounce 'helicopter').
|
||||
It also reflects the level of sophistication of this program --
|
||||
it was named by a two year old.
|
||||
|
||||
IMPLEMENTATION
|
||||
|
||||
When you analyze the problem, you find that the requirements
|
||||
are very simple.
|
||||
Varargs are needed in two places: templates and functions.
|
||||
You want to use them in two ways: when declaring the template
|
||||
or function, and when invoking the function / selecting the
|
||||
template.
|
||||
|
||||
It's a brain-dead implementation, which just does a search-and-replace
|
||||
of specific strings. It could be done with a few lines using sed on
|
||||
a *NIX platform. Because I use Windows, I've done a quick and dirty
|
||||
implementation using CString.
|
||||
|
||||
In a file, @VARARGS at the start of a line indicates the start of the code
|
||||
to be expanded. @ENDVAR at the start of a line marks the end of the
|
||||
expansion.
|
||||
|
||||
declare template -- template <@CLASSARGS> class SomeClass
|
||||
template<class Param1, class Param2>
|
||||
class SomeClass
|
||||
|
||||
declare function -- somefunc(@FUNCARGS)
|
||||
somefunc(Param1 p1, Param2 p2)
|
||||
|
||||
select template -- SomeClass<@SELARGS>
|
||||
SomeClass<Param1, Param2>
|
||||
|
||||
invoke function -- somefunc(@INVOKEARGS)
|
||||
somefunc(p1, p2)
|
||||
|
||||
I also provide @NUM which is the number of arguments.
|
||||
The case where @NUM is zero is a special case: for template declarations,
|
||||
the entire template<> bit needs to disappear. When other arguments are
|
||||
involved, either at the beginning or end of the list, there a commas
|
||||
which might need to be removed.
|
||||
|
||||
I've used .hxx as the extension for these files. This enables C++
|
||||
I wanted to use an unusual file extension (.HOH) for these files, because they
|
||||
aren't real header files. But I also like to use the C++ syntax highlighting
|
||||
in Visual Studio. I chose .hxx because MSVC treats it as C++, but it
|
||||
seems to very rarely used.
|
||||
|
||||
Installation (for VC6, if you want to use .HOH as the extension instead):
|
||||
Go into the registry and change
|
||||
HKEY_CURRENT_USER\Software\Microsoft\DevStudio\6.0\Text Editor\Tabs/Language Settings\C/C++\FileExtensions from cpp;cxx;c;h;hxx;hpp;inl;tlh;tli;rc;rc2
|
||||
to cpp;cxx;c;h;hxx;hpp;inl;tlh;tli;rc;rc2;hoh by adding “;hoh” to the end.
|
||||
Then add this as a custom build step to the main file of your project:
|
||||
hopter $(InputDir)\*.hoh $(InputDir)\*.h
|
||||
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// This is a quick-n-dirty implementation of a CString replacement.
|
||||
// It promises nothing more than to provide enough functionality to get
|
||||
// this program to run.
|
||||
// Note that I have really never used CString, so the information to
|
||||
// implement the members that are used in this program come from
|
||||
// online documentation at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcmfc98/html/_mfc_cstring.asp
|
||||
// Also, I have only used VC++ a few times, a long time ago, so
|
||||
// I really do not know what all their alphabet soup is suppoed to
|
||||
// mean, so I just made a guess...
|
||||
|
||||
|
||||
class CString
|
||||
{
|
||||
public:
|
||||
enum { MAX_FORMAT_STRING_SIZE = 8 * 1044 };
|
||||
CString()
|
||||
: str_()
|
||||
{
|
||||
}
|
||||
|
||||
CString(
|
||||
CString const & rhs)
|
||||
: str_(rhs.str_)
|
||||
{
|
||||
}
|
||||
|
||||
CString(
|
||||
char ch,
|
||||
int repeat = 1)
|
||||
: str_(repeat, ch)
|
||||
{
|
||||
}
|
||||
|
||||
CString(
|
||||
char const * s)
|
||||
: str_(s)
|
||||
{
|
||||
}
|
||||
|
||||
CString & operator=(
|
||||
CString const & rhs)
|
||||
{
|
||||
str_ = rhs.str_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
CString & operator=(
|
||||
char const * s)
|
||||
{
|
||||
str_ = s;
|
||||
return *this;
|
||||
}
|
||||
|
||||
CString & operator=(
|
||||
char ch)
|
||||
{
|
||||
str_ = ch;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Format(
|
||||
char const * fmt,
|
||||
...)
|
||||
{
|
||||
char buffer[ MAX_FORMAT_STRING_SIZE ];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsprintf(buffer, fmt, ap);
|
||||
va_end(ap);
|
||||
str_ = buffer;
|
||||
}
|
||||
|
||||
char operator[](
|
||||
int x) const
|
||||
{
|
||||
return str_[x];
|
||||
}
|
||||
|
||||
CString & operator+=(
|
||||
CString const & x)
|
||||
{
|
||||
str_ += x.str_; return *this;
|
||||
}
|
||||
|
||||
int Replace(
|
||||
CString const & lhs,
|
||||
CString const & rhs)
|
||||
{
|
||||
int rval = 0;
|
||||
std::string::size_type pos = 0;
|
||||
while (pos < str_.length())
|
||||
{
|
||||
pos = str_.find(lhs.str_, pos);
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
str_.replace(pos, lhs.GetLength(), rhs.str_);
|
||||
pos += rhs.GetLength();
|
||||
++rval;
|
||||
}
|
||||
}
|
||||
return rval;
|
||||
}
|
||||
|
||||
int GetLength() const
|
||||
{
|
||||
return str_.length();
|
||||
}
|
||||
|
||||
operator char const * () const
|
||||
{
|
||||
return str_.c_str();
|
||||
}
|
||||
|
||||
private:
|
||||
std::string str_;
|
||||
};
|
||||
|
||||
|
||||
CString operator+(
|
||||
CString const & x,
|
||||
CString const & y)
|
||||
{
|
||||
CString result(x);
|
||||
result += y;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/* Example: This is an excerpt from boost::function_template.hpp
|
||||
|
||||
#define BOOST_FUNCTION_FUNCTION_INVOKER \
|
||||
BOOST_JOIN(function_invoker,BOOST_FUNCTION_NUM_ARGS)
|
||||
#define BOOST_FUNCTION_VOID_FUNCTION_INVOKER \
|
||||
BOOST_JOIN(void_function_invoker,BOOST_FUNCTION_NUM_ARGS)
|
||||
|
||||
template<
|
||||
typename FunctionPtr,
|
||||
typename R BOOST_FUNCTION_COMMA
|
||||
BOOST_FUNCTION_TEMPLATE_PARMS
|
||||
>
|
||||
struct BOOST_FUNCTION_GET_FUNCTION_INVOKER
|
||||
{
|
||||
typedef typename ct_if<(is_void<R>::value),
|
||||
BOOST_FUNCTION_VOID_FUNCTION_INVOKER<
|
||||
FunctionPtr,
|
||||
R BOOST_FUNCTION_COMMA
|
||||
BOOST_FUNCTION_TEMPLATE_ARGS
|
||||
>,
|
||||
BOOST_FUNCTION_FUNCTION_INVOKER<
|
||||
FunctionPtr,
|
||||
R BOOST_FUNCTION_COMMA
|
||||
BOOST_FUNCTION_TEMPLATE_ARGS
|
||||
>
|
||||
>::type type;
|
||||
};
|
||||
|
||||
Using HOPTER, this can be written as:
|
||||
|
||||
template< typename FunctionPtr, typename R, @CLASSARGS>
|
||||
struct get_function_invoker@NUM
|
||||
{
|
||||
typedef typename ct_if<(is_void<R>::value),
|
||||
void_function_invoker@NUM<FunctionPtr, R, @SELARGS>,
|
||||
function_invoker@NUM<FunctionPtr,R, @SELARGS>
|
||||
>::type type;
|
||||
};
|
||||
*/
|
||||
|
||||
int MaxNumArgs;
|
||||
|
||||
/// Makes the necessary subsititutions in 'bigblock', and writes to fout.
|
||||
void PrintVarArgs(FILE *fout, CString bigblock, int num) {
|
||||
CString numstr;
|
||||
CString invokelist;
|
||||
CString funclist;
|
||||
CString selectlist;
|
||||
CString classlist;
|
||||
CString commastr;
|
||||
numstr.Format("%d", num);
|
||||
if (num==0) {
|
||||
invokelist="";
|
||||
funclist="";
|
||||
selectlist="";
|
||||
commastr="";
|
||||
classlist="";
|
||||
}else {
|
||||
invokelist="p1";
|
||||
funclist="Param1 p1";
|
||||
selectlist = "Param1";
|
||||
classlist = "class Param1";
|
||||
commastr=", ";
|
||||
CString str;
|
||||
for (int k=2; k<=num; k++) {
|
||||
str.Format(", p%d", k);
|
||||
invokelist+=str;
|
||||
str.Format(", Param%d p%d", k, k);
|
||||
funclist+=str;
|
||||
str.Format(", Param%d", k);
|
||||
selectlist += str;
|
||||
str.Format(", class Param%d", k);
|
||||
classlist += str;
|
||||
}
|
||||
}
|
||||
|
||||
// Simple replacement of number of arguments
|
||||
bigblock.Replace("@NUM", numstr);
|
||||
|
||||
// Template declarations
|
||||
if (num==0) bigblock.Replace("template<@CLASSARGS>", "");
|
||||
else bigblock.Replace("template<@CLASSARGS>",
|
||||
(CString)"template<" + classlist+">");
|
||||
if (num==0) bigblock.Replace("template <@CLASSARGS>", "");
|
||||
else bigblock.Replace("template <@CLASSARGS>",
|
||||
(CString)"template<" + classlist+">");
|
||||
bigblock.Replace(",@CLASSARGS", commastr + classlist);
|
||||
bigblock.Replace(", @CLASSARGS", commastr + classlist);
|
||||
bigblock.Replace("@CLASSARGS, ", classlist + commastr);
|
||||
bigblock.Replace("@CLASSARGS,", classlist + commastr);
|
||||
bigblock.Replace("@CLASSARGS", classlist);
|
||||
|
||||
// Template selections
|
||||
CString selargstr;
|
||||
if (num==0) selargstr = "";
|
||||
else selargstr = (CString)"<"+selectlist+">";
|
||||
|
||||
bigblock.Replace("<@SELARGS>", selargstr);
|
||||
bigblock.Replace("< @SELARGS >", selargstr);
|
||||
bigblock.Replace(",@SELARGS", commastr + selectlist);
|
||||
bigblock.Replace(", @SELARGS", commastr + selectlist);
|
||||
bigblock.Replace("@SELARGS, ", selectlist + commastr);
|
||||
bigblock.Replace("@SELARGS,", selectlist + commastr);
|
||||
bigblock.Replace("@SELARGS", selectlist);
|
||||
|
||||
// Function declarations
|
||||
bigblock.Replace(",@FUNCARGS", commastr + funclist);
|
||||
bigblock.Replace(", @FUNCARGS", commastr + funclist);
|
||||
bigblock.Replace("@FUNCARGS, ", funclist + commastr);
|
||||
bigblock.Replace("@FUNCARGS,", funclist + commastr);
|
||||
bigblock.Replace("@FUNCARGS", funclist);
|
||||
|
||||
// Function invocation
|
||||
bigblock.Replace(",@INVOKEARGS", commastr + invokelist);
|
||||
bigblock.Replace(", @INVOKEARGS", commastr + invokelist);
|
||||
bigblock.Replace("@INVOKEARGS, ", invokelist + commastr);
|
||||
bigblock.Replace("@INVOKEARGS,", invokelist + commastr);
|
||||
bigblock.Replace("@INVOKEARGS", invokelist);
|
||||
|
||||
fprintf(fout, bigblock);
|
||||
}
|
||||
|
||||
int hopter(int numargs, const char *filenamein, const char *filenameout)
|
||||
{
|
||||
|
||||
MaxNumArgs = numargs;
|
||||
|
||||
FILE * fin;
|
||||
FILE *fout;
|
||||
|
||||
fin =fopen(filenamein,"rt");
|
||||
if (!fin) { printf("Error, can't open %s\n", filenamein); return 1; };
|
||||
fout = fopen (filenameout, "wt");
|
||||
if (!fout) { printf("Error, can't open %s\n", filenameout); return 1; };
|
||||
char buf[5000];
|
||||
for (;;) {
|
||||
if (!fgets(buf, 5000, fin)) break;
|
||||
if (!strncmp(buf, "@VARARGS", 8)) {
|
||||
// found a match...
|
||||
CString bigblock;
|
||||
for (;;) {
|
||||
if (feof(fin)) { printf("No matching @ENDVAR !!??\n"); return 1; };
|
||||
fgets(buf, 5000, fin);
|
||||
if (!strncmp(buf, "@ENDVAR", 7)) break;
|
||||
bigblock+=buf;
|
||||
}
|
||||
// fprintf(fout, "// Auto-generated code [[[\n");
|
||||
for (int k=0; k<=MaxNumArgs; k++) {
|
||||
fprintf(fout, "//N=%d\n", k);
|
||||
PrintVarArgs(fout, bigblock, k);
|
||||
}
|
||||
// fprintf(fout, "// ]]] End auto-generated code\n");
|
||||
} else {
|
||||
fprintf(fout, "%s", buf);
|
||||
}
|
||||
}
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
return 0;
|
||||
}
|
||||
247
sourcehook/generate/shworker/main.cpp
Normal file
247
sourcehook/generate/shworker/main.cpp
Normal file
@ -0,0 +1,247 @@
|
||||
// SHWorker
|
||||
// Inspired by "Hopter" that comes with FastDelegate (http://www.codeproject.com/cpp/FastDelegate.asp)
|
||||
// Much more powerful (and ugly) though
|
||||
|
||||
// Action: iter
|
||||
// @VARARGS@ begins session
|
||||
// @..@ is replaced by .. if num!=0 and removed if num=0. Any
|
||||
// occurences of %% are replaced by the current iter
|
||||
// @$@ is replaced by the current iter
|
||||
// @ENDARGS@ ends session
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <list>
|
||||
#include "stdio.h"
|
||||
|
||||
#ifdef __linux__
|
||||
# define stricmp strcasecmp
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
|
||||
extern int hopter(int numargs, const char *filenamein, const char *filenameout);
|
||||
|
||||
|
||||
void TrimString(std::string &str)
|
||||
{
|
||||
size_t first = str.find_first_not_of(" \t\v\n\r");
|
||||
if (first == std::string::npos)
|
||||
{
|
||||
str.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
size_t last = str.length();
|
||||
for (std::string::reverse_iterator riter = str.rbegin(); riter != str.rend(); ++riter)
|
||||
{
|
||||
char ch = *riter;
|
||||
if (ch != ' ' &&
|
||||
ch != '\t' &&
|
||||
ch != '\v' &&
|
||||
ch != '\n' &&
|
||||
ch != '\r')
|
||||
break;
|
||||
--last;
|
||||
}
|
||||
str = str.substr(first, last - first);
|
||||
}
|
||||
|
||||
bool ExtractToken(std::string &strin, std::string &strout)
|
||||
{
|
||||
TrimString(strin);
|
||||
if (strin.begin() == strin.end())
|
||||
{
|
||||
strout.clear();
|
||||
return false;
|
||||
}
|
||||
size_t first = strin.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ_0123456789");
|
||||
if (first == 0)
|
||||
{
|
||||
if (strin.size() > 1 && strin.at(0) == '/' && strin.at(1) == '/')
|
||||
{
|
||||
// One-line comment, find its end
|
||||
first = strin.find('\n') + 1;
|
||||
}
|
||||
else if (strin.size() > 1 && strin.at(0) == '/' && strin.at(1) == '*')
|
||||
{
|
||||
// Multi-line comment, find its end
|
||||
first = strin.find("*/") + 2;
|
||||
}
|
||||
strin = strin.substr(1);
|
||||
strout.clear();
|
||||
return true;
|
||||
}
|
||||
strout = strin.substr(0, first);
|
||||
strin = strin.substr(first);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Returns the number of occurencies replaced
|
||||
int DoReplace(string &str, const string &what, const string &with)
|
||||
{
|
||||
int cnt=0;
|
||||
size_t where = str.find(what);
|
||||
|
||||
while (where != string::npos)
|
||||
{
|
||||
str.replace(where, what.size(), with);
|
||||
++cnt;
|
||||
where = str.find(what, where);
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if (argc < 5)
|
||||
{
|
||||
cout << "Usage:" << endl << " shworker [iter/hopter] ..." << endl;
|
||||
cout << " shworker iter [num-of-args] filename.in filename.out" << endl;
|
||||
cout << " shworker hopter [num-of-args] filename.in filename.our" << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *action = argv[1];
|
||||
int argsnum = atoi(argv[2]);
|
||||
const char *filenamein = argv[3];
|
||||
const char *filenameout = argv[4];
|
||||
|
||||
if (stricmp(action, "hopter") == 0)
|
||||
{
|
||||
return hopter(argsnum, filenamein, filenameout);
|
||||
}
|
||||
|
||||
ifstream fin(filenamein);
|
||||
ofstream fout(filenameout);
|
||||
if (!fin)
|
||||
{
|
||||
cout << "Could not open file \"" << filenamein << "\"." << endl;
|
||||
return 1;
|
||||
}
|
||||
if (!fout)
|
||||
{
|
||||
cout << "Could not open file \"" << filenameout << "\"." << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (stricmp(action, "iter") == 0)
|
||||
{
|
||||
// Generate versions of func macros for many parameters
|
||||
string str;
|
||||
string replacebuf;
|
||||
while (!fin.eof())
|
||||
{
|
||||
getline(fin, str);
|
||||
if (str == "@VARARGS@")
|
||||
{
|
||||
replacebuf.clear();
|
||||
|
||||
while (true)
|
||||
{
|
||||
getline(fin, str);
|
||||
if (str == "@ENDARGS@")
|
||||
break;
|
||||
|
||||
replacebuf += str;
|
||||
replacebuf += "\n";
|
||||
if (fin.eof())
|
||||
{
|
||||
cout << "No matching @ENDARGS@ !" << endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i <= argsnum; ++i)
|
||||
{
|
||||
string cur = replacebuf;
|
||||
size_t where = cur.find('@');
|
||||
|
||||
while (where != string::npos)
|
||||
{
|
||||
size_t where2 = cur.find('@', where+1);
|
||||
if (where2 == string::npos)
|
||||
{
|
||||
cout << "No ending @";
|
||||
return 1;
|
||||
}
|
||||
string tmp = cur.substr(where + 1, where2 - where - 1);
|
||||
cur.erase(where, where2 - where + 1);
|
||||
|
||||
if (tmp.size() != 0 && tmp[0] == '$')
|
||||
{
|
||||
int tmp_out = i;
|
||||
if (tmp.size() > 2)
|
||||
{
|
||||
if (tmp[1] == '+')
|
||||
{
|
||||
istringstream istr(tmp.substr(2));
|
||||
int tmp;
|
||||
istr >> tmp;
|
||||
tmp_out += tmp;
|
||||
}
|
||||
else if (tmp[1] == '*')
|
||||
{
|
||||
istringstream istr(tmp.substr(2));
|
||||
int tmp;
|
||||
istr >> tmp;
|
||||
tmp_out *= tmp;
|
||||
}
|
||||
}
|
||||
stringstream istr;
|
||||
istr << tmp_out;
|
||||
cur.insert(where, istr.str());
|
||||
where = cur.find('@', where);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find the |.. part, if any
|
||||
string tmpsep;
|
||||
size_t tmpsepbegin = tmp.rfind('|');
|
||||
if (tmpsepbegin != string::npos)
|
||||
{
|
||||
tmpsep = tmp.substr(tmpsepbegin + 1);
|
||||
tmp.erase(tmpsepbegin);
|
||||
}
|
||||
|
||||
size_t pos = where;
|
||||
if (tmp.find("%%") == string::npos)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
cur.insert(pos, tmp);
|
||||
pos += tmp.size();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int j = 1; j <= i; ++j)
|
||||
{
|
||||
stringstream istr;
|
||||
istr << j;
|
||||
string what = tmp;
|
||||
DoReplace(what, string("%%"), istr.str());
|
||||
cur.insert(pos, what);
|
||||
pos += what.size();
|
||||
if (j != i)
|
||||
{
|
||||
cur.insert(pos, tmpsep);
|
||||
pos += tmpsep.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
where = cur.find('@', where);
|
||||
}
|
||||
fout << cur;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
fout << str << endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
123
sourcehook/generate/shworker/shworker.vcproj
Normal file
123
sourcehook/generate/shworker/shworker.vcproj
Normal file
@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding = "Windows-1252"?>
|
||||
<VisualStudioProject
|
||||
ProjectType="Visual C++"
|
||||
Version="7.00"
|
||||
Name="shworker"
|
||||
ProjectGUID="{7CD76E64-A9DF-47DB-8A68-36297C67E557}"
|
||||
Keyword="Win32Proj">
|
||||
<Platforms>
|
||||
<Platform
|
||||
Name="Win32"/>
|
||||
</Platforms>
|
||||
<Configurations>
|
||||
<Configuration
|
||||
Name="Debug|Win32"
|
||||
OutputDirectory="Debug"
|
||||
IntermediateDirectory="Debug"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="2">
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="0"
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
|
||||
MinimalRebuild="TRUE"
|
||||
BasicRuntimeChecks="3"
|
||||
RuntimeLibrary="5"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="3"
|
||||
Detect64BitPortabilityProblems="TRUE"
|
||||
DebugInformationFormat="4"/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
OutputFile="$(OutDir)/shworker.exe"
|
||||
LinkIncremental="2"
|
||||
GenerateDebugInformation="TRUE"
|
||||
ProgramDatabaseFile="$(OutDir)/shworker.pdb"
|
||||
SubSystem="1"
|
||||
TargetMachine="1"/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCWebDeploymentTool"/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Release|Win32"
|
||||
OutputDirectory="Release"
|
||||
IntermediateDirectory="Release"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="2">
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="2"
|
||||
InlineFunctionExpansion="1"
|
||||
OmitFramePointers="TRUE"
|
||||
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
|
||||
StringPooling="TRUE"
|
||||
RuntimeLibrary="4"
|
||||
EnableFunctionLevelLinking="TRUE"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="3"
|
||||
Detect64BitPortabilityProblems="TRUE"
|
||||
DebugInformationFormat="3"/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
OutputFile="$(OutDir)/shworker.exe"
|
||||
LinkIncremental="1"
|
||||
GenerateDebugInformation="TRUE"
|
||||
SubSystem="1"
|
||||
OptimizeReferences="2"
|
||||
EnableCOMDATFolding="2"
|
||||
TargetMachine="1"/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"/>
|
||||
<Tool
|
||||
Name="VCWebDeploymentTool"/>
|
||||
</Configuration>
|
||||
</Configurations>
|
||||
<Files>
|
||||
<Filter
|
||||
Name="Source Files"
|
||||
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm">
|
||||
<File
|
||||
RelativePath="fd_hopter.cpp">
|
||||
</File>
|
||||
<File
|
||||
RelativePath="main.cpp">
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Header Files"
|
||||
Filter="h;hpp;hxx;hm;inl;inc">
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Resource Files"
|
||||
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
|
||||
</Filter>
|
||||
</Files>
|
||||
<Globals>
|
||||
</Globals>
|
||||
</VisualStudioProject>
|
||||
544
sourcehook/generate/sourcehook.hxx
Executable file
544
sourcehook/generate/sourcehook.hxx
Executable file
@ -0,0 +1,544 @@
|
||||
/* ======== SourceHook ========
|
||||
* By PM
|
||||
* No warranties of any kind
|
||||
* ============================
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file sourcehook.h
|
||||
* @brief Contains the public SourceHook API
|
||||
*/
|
||||
|
||||
#ifndef __SOURCEHOOK_H__
|
||||
#define __SOURCEHOOK_H__
|
||||
|
||||
#define SH_ASSERT(x) if (!(x)) __asm { int 3 }
|
||||
|
||||
// System
|
||||
#define SH_SYS_WIN32 1
|
||||
#define SH_SYS_LINUX 2
|
||||
|
||||
#ifdef _WIN32
|
||||
# define SH_SYS SH_SYS_WIN32
|
||||
#elif defined __linux__
|
||||
# define SH_SYS SH_SYS_LINUX
|
||||
#else
|
||||
# error Unsupported system
|
||||
#endif
|
||||
|
||||
// Compiler
|
||||
#define SH_COMP_GCC 1
|
||||
#define SH_COMP_MSVC 2
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define SH_COMP SH_COMP_MSVC
|
||||
#elif defined __GNUC__
|
||||
# define SH_COMP SH_COMP_GCC
|
||||
#else
|
||||
# error Unsupported compiler
|
||||
#endif
|
||||
|
||||
#if SH_COMP==SH_COMP_MSVC
|
||||
# define vsnprintf _vsnprintf
|
||||
#endif
|
||||
|
||||
#include "FastDelegate.h"
|
||||
#include "sh_memfuncinfo.h"
|
||||
#include "sh_memory.h"
|
||||
#include <list>
|
||||
#include <algorithm>
|
||||
|
||||
// Good old metamod!
|
||||
|
||||
// Flags returned by a plugin's api function.
|
||||
// NOTE: order is crucial, as greater/less comparisons are made.
|
||||
enum META_RES
|
||||
{
|
||||
MRES_IGNORED=0, // plugin didn't take any action
|
||||
MRES_HANDLED, // plugin did something, but real function should still be called
|
||||
MRES_OVERRIDE, // call real function, but use my return value
|
||||
MRES_SUPERCEDE, // skip real function; use my return value
|
||||
};
|
||||
|
||||
|
||||
namespace SourceHook
|
||||
{
|
||||
const int STRBUF_LEN=8192; // In bytes, for "vafmt" functions
|
||||
|
||||
/**
|
||||
* @brief A plugin typedef
|
||||
*
|
||||
* SourceHook doesn't really care what this is. As long as the ==, != and = operators work on it
|
||||
* and every plugin has a unique identifier, everything is ok.
|
||||
*/
|
||||
typedef void* Plugin;
|
||||
|
||||
enum HookerAction
|
||||
{
|
||||
HA_GetInfo = 0, // -> Only store info
|
||||
HA_Register, // -> Save the pointer for future reference
|
||||
HA_Unregister, // -> Clear the saved pointer
|
||||
HA_IfaceAdded, // -> Request call class
|
||||
HA_IfaceRemoved // -> Release call class
|
||||
};
|
||||
|
||||
struct HookerInfo;
|
||||
|
||||
/**
|
||||
* @brief Pointer to hooker type
|
||||
*
|
||||
* A "hooker" is a the only thing that knows the actual protoype of the function at compile time.
|
||||
*
|
||||
* @param hi A pointer to a HookerInfo structure. The hooker should fill it and store it for
|
||||
* future reference (mainly if something should get hooked to its hookfunc)
|
||||
*/
|
||||
typedef int (*Hooker)(HookerAction ha, HookerInfo *hi);
|
||||
|
||||
class ISHDelegate
|
||||
{
|
||||
public:
|
||||
virtual void DeleteThis() = 0; // Ugly, I know
|
||||
virtual bool IsEqual(ISHDelegate *other) = 0;
|
||||
};
|
||||
|
||||
template <class T> class CSHDelegate : public ISHDelegate
|
||||
{
|
||||
T m_Deleg;
|
||||
public:
|
||||
CSHDelegate(T deleg) : m_Deleg(deleg)
|
||||
{
|
||||
}
|
||||
|
||||
void DeleteThis()
|
||||
{
|
||||
delete this;
|
||||
}
|
||||
|
||||
bool IsEqual(ISHDelegate *other)
|
||||
{
|
||||
return static_cast<CSHDelegate<T>* >(other)->GetDeleg() == GetDeleg();
|
||||
}
|
||||
|
||||
T &GetDeleg()
|
||||
{
|
||||
return m_Deleg;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief This structure contains information about a hooker (hook manager)
|
||||
*/
|
||||
struct HookerInfo
|
||||
{
|
||||
struct Iface
|
||||
{
|
||||
struct Hook
|
||||
{
|
||||
ISHDelegate *handler; //!< Pointer to the handler
|
||||
Plugin plug; //!< The owner plugin
|
||||
};
|
||||
void *callclass; //!< Stores a call class for this interface
|
||||
void *ptr; //!< Pointer to the interface instance
|
||||
void *orig_entry; //!< The original vtable entry
|
||||
std::list<Hook> hooks_pre; //!< A list of pre-hooks
|
||||
std::list<Hook> hooks_post; //!< A list of post-hooks
|
||||
bool operator ==(void *other) const
|
||||
{
|
||||
return ptr == other;
|
||||
}
|
||||
};
|
||||
Plugin plug; //!< The owner plugin
|
||||
const char *proto; //!< The prototype of the function the hooker is responsible for
|
||||
int vtbl_idx; //!< The vtable index
|
||||
int vtbl_offs; //!< The vtable offset
|
||||
int thisptr_offs; //!< The this-pointer-adjuster
|
||||
Hooker func; //!< The interface to the hooker
|
||||
|
||||
int hookfunc_vtbl_idx; //!< the vtable index of the hookfunc
|
||||
int hookfunc_vtbl_offs; //!< the vtable offset of the hookfunc
|
||||
void *hookfunc_inst; //!< Instance of the class the hookfunc is in
|
||||
|
||||
std::list<Iface> ifaces; //!< List of hooked interfaces
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure describing a callclass
|
||||
*/
|
||||
struct CallClass
|
||||
{
|
||||
struct VTable
|
||||
{
|
||||
void *ptr;
|
||||
int actsize;
|
||||
std::list<int> patches; //!< Already patched entries
|
||||
bool operator ==(void *other) const
|
||||
{
|
||||
return ptr == other;
|
||||
}
|
||||
};
|
||||
void *iface; //!< The iface pointer this callclass belongs to
|
||||
size_t size; //!< The size of the callclass
|
||||
void *ptr; //!< The actual "object"
|
||||
typedef std::list<VTable> VTableList;
|
||||
VTableList vtables; //!< Already known vtables
|
||||
int refcounter; //!< How many times it was requested
|
||||
|
||||
bool operator ==(void *other) const
|
||||
{
|
||||
return ptr == other;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The main SourceHook interface
|
||||
*/
|
||||
class ISourceHook
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Add a hook.
|
||||
*
|
||||
* @return True if the function succeeded, false otherwise
|
||||
*
|
||||
* @param plug The unique identifier of the plugin that calls this function
|
||||
* @param iface The interface pointer
|
||||
* @param ifacesize The size of the class iface points to
|
||||
* @param myHooker A hooker function that should be capable of handling the function
|
||||
* @param handler A pointer to a FastDelegate containing the hook handler
|
||||
* @param post Set to true if you want a post handler
|
||||
*/
|
||||
virtual bool AddHook(Plugin plug, void *iface, int ifacesize, Hooker myHooker, ISHDelegate *handler, bool post) = 0;
|
||||
|
||||
/**
|
||||
* @brief Removes a hook.
|
||||
*
|
||||
* @return True if the function succeeded, false otherwise
|
||||
*
|
||||
* @param plug The unique identifier of the plugin that calls this function
|
||||
* @param iface The interface pointer
|
||||
* @param myHooker A hooker function that should be capable of handling the function
|
||||
* @param handler A pointer to a FastDelegate containing the hook handler
|
||||
* @param post Set to true if you want a post handler
|
||||
*/
|
||||
virtual bool RemoveHook(Plugin plug, void *iface, Hooker myHooker, ISHDelegate *handler, bool post) = 0;
|
||||
|
||||
/**
|
||||
* @brief Checks whether a plugin has (a) hooker(s) that is/are currently used by other plugins
|
||||
*
|
||||
* @param plug The unique identifier of the plugin in question
|
||||
*/
|
||||
virtual bool IsPluginInUse(Plugin plug) = 0;
|
||||
|
||||
/**
|
||||
* @brief Return a pointer to a callclass. Generate a new one if required.
|
||||
*
|
||||
* @param iface The interface pointer
|
||||
* @param size Size of the class
|
||||
*/
|
||||
virtual void *GetCallClass(void *iface, size_t size) = 0;
|
||||
|
||||
/**
|
||||
* @brief Release a callclass
|
||||
*
|
||||
* @param ptr Pointer to the callclass
|
||||
*/
|
||||
virtual void ReleaseCallClass(void *ptr) = 0;
|
||||
|
||||
virtual void SetRes(META_RES res) = 0; //!< Sets the meta result
|
||||
virtual META_RES GetPrevRes() = 0; //!< Gets the meta result of the previously called handler
|
||||
virtual META_RES GetStatus() = 0; //!< Gets the highest meta result
|
||||
virtual const void *GetOrigRet() = 0; //!< Gets the original result. If not in post function, undefined
|
||||
virtual const void *GetOverrideRet() = 0; //!< Gets the override result. If none is specified, NULL
|
||||
virtual void *GetIfacePtr() = 0; //!< Gets the interface pointer
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// For hookers
|
||||
virtual META_RES &GetCurResRef() = 0; //!< Gets the pointer to the current meta result
|
||||
virtual META_RES &GetPrevResRef() = 0; //!< Gets the pointer to the previous meta result
|
||||
virtual META_RES &GetStatusRef() = 0; //!< Gets the pointer to the status variable
|
||||
virtual void SetOrigRet(const void *ptr) = 0; //!< Sets the original return pointer
|
||||
virtual void SetOverrideRet(const void *ptr) = 0; //!< Sets the override result pointer
|
||||
virtual void SetIfacePtr(void *ptr) = 0; //!< Sets the interface this pointer
|
||||
};
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Macro interface
|
||||
#define SET_META_RESULT(result) g_SHPtr->SetRes(result)
|
||||
#define RETURN_META(result) do { g_SHPtr->SetRes(result); return; } while(0)
|
||||
#define RETURN_META_VALUE(result, value) do { g_SHPtr->SetRes(result); return (value); } while(0)
|
||||
|
||||
#define META_RESULT_STATUS g_SHPtr->GetStatus()
|
||||
#define META_RESULT_PREVIOUS g_SHPtr->GetPrevRes()
|
||||
#define META_RESULT_ORIG_RET(type) *(const type *)g_SHPtr->GetOrigRet()
|
||||
#define META_RESULT_OVERRIDE_RET(type) *(const type *)g_SHPtr->GetOverrideRet()
|
||||
#define META_IFACEPTR g_SHPtr->GetIfacePtr()
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get/generate callclass for an interface pointer
|
||||
*
|
||||
* @param ifacetype The type of the interface
|
||||
* @param ifaceptr The interface pointer
|
||||
*/
|
||||
#define SH_GET_CALLCLASS(ifacetype, ifaceptr) g_SHPtr->GetCallClass(iface, sizeof(ifacetype))
|
||||
|
||||
#define SH_ADD_HOOK(ifacetype, ifacefunc, ifaceptr, handler, post) \
|
||||
SourceHook::SH_FHAdd##ifacetype##ifacefunc((void*)ifaceptr, post, handler)
|
||||
#define SH_ADD_HOOK_STATICFUNC(ifacetype, ifacefunc, ifaceptr, handler, post) \
|
||||
SH_ADD_HOOK(ifacetype, ifacefunc, ifaceptr, handler, post)
|
||||
#define SH_ADD_HOOK_MEMFUNC(ifacetype, ifacefunc, ifaceptr, handler_inst, handler_func, post) \
|
||||
SH_ADD_HOOK(ifacetype, ifacefunc, ifaceptr, fastdelegate::MakeDelegate(handler_inst, handler_func), post)
|
||||
|
||||
#define SH_REMOVE_HOOK(ifacetype, ifacefunc, ifaceptr, handler, post) \
|
||||
SourceHook::SH_FHRemove##ifacetype##ifacefunc((void*)ifaceptr, post, handler)
|
||||
#define SH_REMOVE_HOOK_STATICFUNC(ifacetype, ifacefunc, ifaceptr, handler, post) \
|
||||
SH_REMOVE_HOOK(ifacetype, ifacefunc, ifaceptr, handler, post)
|
||||
#define SH_REMOVE_HOOK_MEMFUNC(ifacetype, ifacefunc, ifaceptr, handler_inst, handler_func, post) \
|
||||
SH_REMOVE_HOOK(ifacetype, ifacefunc, ifaceptr, fastdelegate::MakeDelegate(handler_inst, handler_func), post)
|
||||
|
||||
#define SH_NOATTRIB
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
#define SH_FHCls(ift, iff, ov) FHCls_##ift##iff##ov
|
||||
|
||||
#define SHINT_MAKE_HOOKERPUBFUNC(ifacetype, ifacefunc, overload, funcptr) \
|
||||
static int Hooker(HookerAction action, HookerInfo *param) \
|
||||
{ \
|
||||
if (action == HA_GetInfo) \
|
||||
{ \
|
||||
param->proto = ms_Proto; \
|
||||
MemFuncInfo mfi; \
|
||||
GetFuncInfo(funcptr, mfi); \
|
||||
param->vtbl_idx = mfi.vtblindex; \
|
||||
param->vtbl_offs = mfi.vtbloffs; \
|
||||
param->thisptr_offs = mfi.thisptroffs; \
|
||||
if (param->thisptr_offs) \
|
||||
return 2; /*No virtual inheritance supported*/ \
|
||||
GetFuncInfo(&SH_FHCls(ifacetype,ifacefunc,overload)::Func, mfi); \
|
||||
param->hookfunc_vtbl_idx = mfi.vtblindex; \
|
||||
param->hookfunc_vtbl_offs = mfi.vtbloffs; \
|
||||
param->hookfunc_inst = (void*)&ms_Inst; \
|
||||
return 0; \
|
||||
} \
|
||||
else if (action == HA_Register) \
|
||||
{ \
|
||||
ms_HI = param; \
|
||||
return 0; \
|
||||
} \
|
||||
else if (action == HA_Unregister) \
|
||||
{ \
|
||||
ms_HI = NULL; \
|
||||
return 0; \
|
||||
} \
|
||||
else \
|
||||
return 1; \
|
||||
}
|
||||
|
||||
#define SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload, funcptr) \
|
||||
namespace SourceHook \
|
||||
{ \
|
||||
struct SH_FHCls(ifacetype,ifacefunc,overload) \
|
||||
{ \
|
||||
static SH_FHCls(ifacetype,ifacefunc,overload) ms_Inst; \
|
||||
static HookerInfo *ms_HI; \
|
||||
static const char *ms_Proto; \
|
||||
SHINT_MAKE_HOOKERPUBFUNC(ifacetype, ifacefunc, overload, funcptr)
|
||||
|
||||
#define SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, proto) \
|
||||
}; \
|
||||
const char *SH_FHCls(ifacetype,ifacefunc,overload)::ms_Proto = proto; \
|
||||
SH_FHCls(ifacetype,ifacefunc,overload) SH_FHCls(ifacetype,ifacefunc,overload)::ms_Inst; \
|
||||
HookerInfo *SH_FHCls(ifacetype,ifacefunc,overload)::ms_HI; \
|
||||
bool SH_FHAdd##ifacetype##ifacefunc(void *iface, bool post, \
|
||||
SH_FHCls(ifacetype,ifacefunc,overload)::FD handler) \
|
||||
{ \
|
||||
return g_SHPtr->AddHook(g_Plug, iface, sizeof(ifacetype), \
|
||||
SH_FHCls(ifacetype,ifacefunc,overload)::Hooker, \
|
||||
new CSHDelegate<SH_FHCls(ifacetype,ifacefunc,overload)::FD>(handler), post); \
|
||||
} \
|
||||
bool SH_FHRemove##ifacetype##ifacefunc(void *iface, bool post, \
|
||||
SH_FHCls(ifacetype,ifacefunc,overload)::FD handler) \
|
||||
{ \
|
||||
CSHDelegate<SH_FHCls(ifacetype,ifacefunc,overload)::FD> tmp(handler); \
|
||||
return g_SHPtr->RemoveHook(g_Plug, iface, \
|
||||
SH_FHCls(ifacetype,ifacefunc,overload)::Hooker, &tmp, post); \
|
||||
} \
|
||||
}
|
||||
|
||||
#define SH_SETUPCALLS(rettype) \
|
||||
/* 1) Find the iface ptr */ \
|
||||
/* 1.1) Adjust to original this pointer */ \
|
||||
void *origthis = this - ms_HI->thisptr_offs; \
|
||||
std::list<HookerInfo::Iface>::iterator ifaceiter = std::find(ms_HI->ifaces.begin(), \
|
||||
ms_HI->ifaces.end(), origthis); \
|
||||
SH_ASSERT(ifaceiter != ms_HI->ifaces.end()); \
|
||||
HookerInfo::Iface &ci = *ifaceiter; \
|
||||
/* 2) Declare some vars and set it up */ \
|
||||
std::list<HookerInfo::Iface::Hook> &prelist = ci.hooks_pre; \
|
||||
std::list<HookerInfo::Iface::Hook> &postlist = ci.hooks_post; \
|
||||
rettype orig_ret, override_ret, plugin_ret; \
|
||||
META_RES &cur_res = g_SHPtr->GetCurResRef(); \
|
||||
META_RES &prev_res = g_SHPtr->GetPrevResRef(); \
|
||||
META_RES &status = g_SHPtr->GetStatusRef(); \
|
||||
status = MRES_IGNORED; \
|
||||
g_SHPtr->SetIfacePtr(ci.ptr); \
|
||||
g_SHPtr->SetOrigRet(reinterpret_cast<void*>(&orig_ret)); \
|
||||
g_SHPtr->SetOverrideRet(NULL);
|
||||
|
||||
#define SH_CALL_HOOKS(post, params) \
|
||||
prev_res = MRES_IGNORED; \
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator hiter = post##list.begin(); hiter != post##list.end(); ++hiter) \
|
||||
{ \
|
||||
cur_res = MRES_IGNORED; \
|
||||
plugin_ret = reinterpret_cast<CSHDelegate<FD>*>(hiter->handler)->GetDeleg() params; \
|
||||
prev_res = cur_res; \
|
||||
if (cur_res > status) \
|
||||
status = cur_res; \
|
||||
if (cur_res >= MRES_OVERRIDE) \
|
||||
{ \
|
||||
override_ret = plugin_ret; \
|
||||
g_SHPtr->SetOverrideRet(&override_ret); \
|
||||
} \
|
||||
}
|
||||
|
||||
#define SH_CALL_ORIG(ifacetype, ifacefunc, params) \
|
||||
if (status != MRES_SUPERCEDE) \
|
||||
orig_ret = reinterpret_cast<ifacetype*>(ci.callclass)->ifacefunc params; \
|
||||
else \
|
||||
orig_ret = override_ret;
|
||||
|
||||
#define SH_RETURN() \
|
||||
return status >= MRES_OVERRIDE ? override_ret : orig_ret;
|
||||
|
||||
#define SH_HANDLEFUNC(ifacetype, ifacefunc, params, rettype) \
|
||||
SH_SETUPCALLS(rettype) \
|
||||
SH_CALL_HOOKS(pre, params) \
|
||||
SH_CALL_ORIG(ifacetype, ifacefunc, params) \
|
||||
SH_CALL_HOOKS(post, params) \
|
||||
SH_RETURN()
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
#define SH_SETUPCALLS_void() \
|
||||
/* 1) Find the iface ptr */ \
|
||||
/* 1.1) Adjust to original this pointer */ \
|
||||
void *origthis = this - ms_HI->thisptr_offs; \
|
||||
std::list<HookerInfo::Iface>::iterator ifaceiter = std::find(ms_HI->ifaces.begin(), \
|
||||
ms_HI->ifaces.end(), origthis); \
|
||||
SH_ASSERT(ifaceiter != ms_HI->ifaces.end()); \
|
||||
HookerInfo::Iface &ci = *ifaceiter; \
|
||||
/* 2) Declare some vars and set it up */ \
|
||||
std::list<HookerInfo::Iface::Hook> &prelist = ci.hooks_pre; \
|
||||
std::list<HookerInfo::Iface::Hook> &postlist = ci.hooks_post; \
|
||||
META_RES &cur_res = g_SHPtr->GetCurResRef(); \
|
||||
META_RES &prev_res = g_SHPtr->GetPrevResRef(); \
|
||||
META_RES &status = g_SHPtr->GetStatusRef(); \
|
||||
status = MRES_IGNORED; \
|
||||
g_SHPtr->SetIfacePtr(ci.ptr); \
|
||||
g_SHPtr->SetOverrideRet(NULL);
|
||||
|
||||
#define SH_CALL_HOOKS_void(post, params) \
|
||||
prev_res = MRES_IGNORED; \
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator hiter = post##list.begin(); hiter != post##list.end(); ++hiter) \
|
||||
{ \
|
||||
cur_res = MRES_IGNORED; \
|
||||
reinterpret_cast<CSHDelegate<FD>*>(hiter->handler)->GetDeleg() params; \
|
||||
prev_res = cur_res; \
|
||||
if (cur_res > status) \
|
||||
status = cur_res; \
|
||||
}
|
||||
|
||||
#define SH_CALL_ORIG_void(ifacetype, ifacefunc, params) \
|
||||
if (status != MRES_SUPERCEDE) \
|
||||
reinterpret_cast<ifacetype*>(ci.callclass)->ifacefunc params;
|
||||
|
||||
#define SH_RETURN_void()
|
||||
|
||||
#define SH_HANDLEFUNC_void(ifacetype, ifacefunc, params) \
|
||||
SH_SETUPCALLS_void() \
|
||||
SH_CALL_HOOKS_void(pre, params) \
|
||||
SH_CALL_ORIG_void(ifacetype, ifacefunc, params) \
|
||||
SH_CALL_HOOKS_void(post, params) \
|
||||
SH_RETURN_void()
|
||||
|
||||
|
||||
// Special vafmt handlers
|
||||
#define SH_HANDLEFUNC_vafmt(ifacetype, ifacefunc, params_orig, params_plug, rettype) \
|
||||
SH_SETUPCALLS(rettype) \
|
||||
SH_CALL_HOOKS(pre, params_plug) \
|
||||
SH_CALL_ORIG(ifacetype, ifacefunc, params_orig) \
|
||||
SH_CALL_HOOKS(post, params_plug) \
|
||||
SH_RETURN()
|
||||
|
||||
#define SH_HANDLEFUNC_void_vafmt(ifacetype, ifacefunc, params_orig, params_plug) \
|
||||
SH_SETUPCALLS_void() \
|
||||
SH_CALL_HOOKS_void(pre, params_plug) \
|
||||
SH_CALL_ORIG_void(ifacetype, ifacefunc, params_orig) \
|
||||
SH_CALL_HOOKS_void(post, params_plug) \
|
||||
SH_RETURN_void()
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@VARARGS@
|
||||
// *********
|
||||
#define SH_DECL_HOOK@$@(ifacetype, ifacefunc, attr, overload, rettype@, param%%@) \
|
||||
SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload, (static_cast<rettype (ifacetype::*)(@param%%|, @)> \
|
||||
(&ifacetype::ifacefunc))) \
|
||||
typedef fastdelegate::FastDelegate@$@<@param%%|, @@, @rettype> FD; \
|
||||
virtual rettype Func(@param%% p%%|, @) attr \
|
||||
{ SH_HANDLEFUNC(ifacetype, ifacefunc, (@p%%|, @), rettype); } \
|
||||
SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, #attr "|" #rettype @"|" #param%%| @)
|
||||
|
||||
#define SH_DECL_HOOK@$@_void(ifacetype, ifacefunc, attr, overload@, param%%@) \
|
||||
SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload, (static_cast<void (ifacetype::*)(@param%%|, @)> \
|
||||
(&ifacetype::ifacefunc))) \
|
||||
typedef fastdelegate::FastDelegate@$@<@param%%|, @> FD; \
|
||||
virtual void Func(@param%% p%%|, @) attr \
|
||||
{ SH_HANDLEFUNC_void(ifacetype, ifacefunc, (@p%%|, @)); } \
|
||||
SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, #attr @"|" #param%%| @)
|
||||
|
||||
#define SH_DECL_HOOK@$@_vafmt(ifacetype, ifacefunc, attr, overload, rettype@, param%%@) \
|
||||
SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload, (static_cast<rettype (ifacetype::*)(@param%%|, @@, @const char *, ...)> \
|
||||
(&ifacetype::ifacefunc))) \
|
||||
typedef fastdelegate::FastDelegate@$+1@<@param%%|, @@, @const char *, rettype> FD; \
|
||||
virtual rettype Func(@param%% p%%|, @@, @const char *fmt, ...) attr \
|
||||
{ \
|
||||
char buf[STRBUF_LEN]; \
|
||||
va_list ap; \
|
||||
va_start(ap, fmt); \
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap); \
|
||||
va_end(ap); \
|
||||
SH_HANDLEFUNC_vafmt(ifacetype, ifacefunc, (@p%%|, @@, @"%s", buf), (@p%%|, @@, @buf), rettype); \
|
||||
} \
|
||||
SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, #attr "|" #rettype @"|" #param%%| @ "|const char*|...")
|
||||
|
||||
#define SH_DECL_HOOK@$@_void_vafmt(ifacetype, ifacefunc, attr, overload, rettype@, param%%@) \
|
||||
SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload, (static_cast<void (ifacetype::*)(@param%%|, @@, @const char *, ...)> \
|
||||
(&ifacetype::ifacefunc))) \
|
||||
typedef fastdelegate::FastDelegate@$+1@<@param%%|, @@, @const char *> FD; \
|
||||
virtual void Func(@param%% p%%|, @@, @const char *, ...) attr \
|
||||
{ \
|
||||
char buf[STRBUF_LEN]; \
|
||||
va_list ap; \
|
||||
va_start(ap, fmt); \
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap); \
|
||||
va_end(ap); \
|
||||
SH_HANDLEFUNC_void_vafmt(ifacetype, ifacefunc, (@p%%|, @@, @"%s", buf), (@p%%|, @@, @buf)); \
|
||||
} \
|
||||
SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, #attr @"|" #param%%| @ "|const char*|...")
|
||||
|
||||
@ENDARGS@
|
||||
|
||||
/*
|
||||
#define SH_DECL_HOOK1(ifacetype, ifacefunc, attr, overload, rettype, param1) \
|
||||
SHINT_MAKE_GENERICSTUFF_BEGIN(ifacetype, ifacefunc, overload) \
|
||||
typedef fastdelegate::FastDelegate1<param1, rettype> FD; \
|
||||
virtual rettype Func(param1 p1) \
|
||||
{ SH_HANDLEFUNC(ifacetype, ifacefunc, (p1), rettype); } \
|
||||
SHINT_MAKE_GENERICSTUFF_END(ifacetype, ifacefunc, overload, #attr "|" #rettype "|" #param1)
|
||||
|
||||
|
||||
*/
|
||||
|
||||
#endif
|
||||
// The pope is dead. -> :(
|
||||
257
sourcehook/sh_memfuncinfo.h
Normal file
257
sourcehook/sh_memfuncinfo.h
Normal file
@ -0,0 +1,257 @@
|
||||
/* ======== SourceHook ========
|
||||
* By PM
|
||||
* No warranties of any kind
|
||||
*
|
||||
* This file provides a way for getting information about a member function.
|
||||
* ============================
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#ifndef __SHINT_MEMFUNC_INFO_H__
|
||||
#define __SHINT_MEMFUNC_INFO_H__
|
||||
|
||||
namespace SourceHook
|
||||
{
|
||||
|
||||
// Don Clugston:
|
||||
// implicit_cast< >
|
||||
// I believe this was originally going to be in the C++ standard but
|
||||
// was left out by accident. It's even milder than static_cast.
|
||||
// I use it instead of static_cast<> to emphasize that I'm not doing
|
||||
// anything nasty.
|
||||
// Usage is identical to static_cast<>
|
||||
template <class OutputClass, class InputClass>
|
||||
inline OutputClass implicit_cast(InputClass input){
|
||||
return input;
|
||||
}
|
||||
|
||||
|
||||
struct MemFuncInfo
|
||||
{
|
||||
bool isVirtual; // Is the function virtual?
|
||||
int thisptroffs; // The this pointer the function expects to be called with
|
||||
// If -1, you need to call the GetFuncInfo_GetThisPtr function
|
||||
int vtblindex; // The function's index in the vtable (0-based, 1=second entry, 2=third entry, ...)
|
||||
int vtbloffs; // The vtable pointer
|
||||
};
|
||||
|
||||
// Ideas by Don Clugston.
|
||||
// Check out his excellent paper: http://www.codeproject.com/cpp/FastDelegate.asp
|
||||
|
||||
template<int N> struct MFI_Impl
|
||||
{
|
||||
template<class MFP> static inline void GetFuncInfo(MFP *mfp, MemFuncInfo &out)
|
||||
{
|
||||
static char weird_memfunc_pointer_exclamation_mark_arrow_error[N-1000];
|
||||
}
|
||||
};
|
||||
|
||||
# if SH_COMP == SH_COMP_GCC
|
||||
|
||||
template<> struct MFI_Impl<8> // All of these have size==8
|
||||
{
|
||||
struct GCC_MemFunPtr
|
||||
{
|
||||
union
|
||||
{
|
||||
void *funcadr; // always even
|
||||
int vtable_index_plus1; // = vindex+1, always odd
|
||||
};
|
||||
int delta;
|
||||
};
|
||||
template<class MFP> static inline void GetFuncInfo(MFP *mfp, MemFuncInfo &out)
|
||||
{
|
||||
GCC_MemFunPtr *mfp_detail = (GCC_MemFunPtr*)mfp;
|
||||
out.thisptroffs = mfp_detail->delta;
|
||||
if (mfp_detail->vtable_index_plus1 & 1)
|
||||
{
|
||||
out.vtblindex = (mfp_detail->vtable_index_plus1 - 1) / 4;
|
||||
out.vtbloffs = 0;
|
||||
out.isVirtual = true;
|
||||
}
|
||||
else
|
||||
out.isVirtual = false;
|
||||
}
|
||||
};
|
||||
|
||||
# elif SH_COMP == SH_COMP_MSVC
|
||||
|
||||
namespace
|
||||
{
|
||||
int MFI_GetVtblOffset(void *mfp)
|
||||
{
|
||||
unsigned char *addr = (unsigned char*)mfp;
|
||||
if (*addr == 0xE9) // Jmp
|
||||
{
|
||||
// May or may not be!
|
||||
// Check where it'd jump
|
||||
addr += 5 /*size of the instruction*/ + *(unsigned long*)(addr + 1);
|
||||
}
|
||||
|
||||
// Check whether it's a virtual function call
|
||||
// They look like this:
|
||||
// 004125A0 8B 01 mov eax,dword ptr [ecx]
|
||||
// 004125A2 FF 60 04 jmp dword ptr [eax+4]
|
||||
// ==OR==
|
||||
// 00411B80 8B 01 mov eax,dword ptr [ecx]
|
||||
// 00411B82 FF A0 18 03 00 00 jmp dword ptr [eax+318h]
|
||||
if (*addr++ == 0x8B && *addr++ == 0x01 && *addr++ == 0xFF)
|
||||
{
|
||||
if (*addr == 0x60)
|
||||
{
|
||||
return *++addr / 4;
|
||||
}
|
||||
else if (*addr == 0xA0)
|
||||
{
|
||||
return *((unsigned int*)++addr) / 4;
|
||||
}
|
||||
else if (*addr == 0x20)
|
||||
return 0;
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
template<> struct MFI_Impl<4> // simple ones
|
||||
{
|
||||
template<class MFP> static inline void GetFuncInfo(MFP mfp, MemFuncInfo &out)
|
||||
{
|
||||
out.vtblindex = MFI_GetVtblOffset(*(void**)&mfp);
|
||||
out.isVirtual = out.vtblindex >= 0 ? true : false;
|
||||
out.thisptroffs = 0;
|
||||
out.vtbloffs = 0;
|
||||
}
|
||||
};
|
||||
|
||||
template<> struct MFI_Impl<8> // more complicated ones!
|
||||
{
|
||||
struct MSVC_MemFunPtr2
|
||||
{
|
||||
void *funcadr;
|
||||
int delta;
|
||||
};
|
||||
template<class MFP> static inline void GetFuncInfo(MFP mfp, MemFuncInfo &out)
|
||||
{
|
||||
out.vtblindex = MFI_GetVtblOffset(*(void**)&mfp);
|
||||
out.isVirtual = out.vtblindex >= 0 ? true : false;
|
||||
out.thisptr = reinterpret_cast<MSVC_MemFunPtr2*>(&mfp)->delta;
|
||||
out.vtbloffs = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// By Don Clugston, adapted
|
||||
template<> struct MFI_Impl<12> // WOW IT"S GETTING BIGGER OMGOMOGMG
|
||||
{
|
||||
class __single_inheritance GenericClass;
|
||||
class GenericClass {};
|
||||
|
||||
struct MicrosoftVirtualMFP {
|
||||
void (GenericClass::*codeptr)(); // points to the actual member function
|
||||
int delta; // #bytes to be added to the 'this' pointer
|
||||
int vtable_index; // or 0 if no virtual inheritance
|
||||
};
|
||||
|
||||
struct GenericVirtualClass : virtual public GenericClass
|
||||
{
|
||||
typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)();
|
||||
GenericVirtualClass * GetThis() { return this; }
|
||||
};
|
||||
|
||||
template<class MFP> static inline void GetFuncInfo(MFP mfp, MemFuncInfo &out)
|
||||
{
|
||||
out.vtblindex = MFI_GetVtblOffset(*(void**)&mfp);
|
||||
out.isVirtual = out.vtblindex >= 0 ? true : false;
|
||||
// This pointer
|
||||
union {
|
||||
MFP func;
|
||||
GenericClass* (T::*ProbeFunc)();
|
||||
MicrosoftVirtualMFP s;
|
||||
} u;
|
||||
u.func = mfp;
|
||||
union {
|
||||
GenericVirtualClass::ProbePtrType virtfunc;
|
||||
MicrosoftVirtualMFP s;
|
||||
} u2;
|
||||
|
||||
printf("%d %d", sizeof(mfp), sizeof(u.ProbeFunc));
|
||||
// Check that the horrible_cast<>s will work
|
||||
typedef int ERROR_CantUsehorrible_cast[sizeof(mfp)==sizeof(u.s)
|
||||
&& sizeof(mfp)==sizeof(u.ProbeFunc)
|
||||
&& sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1];
|
||||
// Unfortunately, taking the address of a MF prevents it from being inlined, so
|
||||
// this next line can't be completely optimised away by the compiler.
|
||||
u2.virtfunc = &GenericVirtualClass::GetThis;
|
||||
u.s.codeptr = u2.s.codeptr;
|
||||
out.thisptroffs = (reinterpret_cast<T*>(NULL)->*u.ProbeFunc)();
|
||||
out.vtbloffs = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Don: Nasty hack for Microsoft and Intel (IA32 and Itanium)
|
||||
// unknown_inheritance classes go here
|
||||
// This is probably the ugliest bit of code I've ever written. Look at the casts!
|
||||
// There is a compiler bug in MSVC6 which prevents it from using this code.
|
||||
template<> struct MFI_Impl<16> // THE BIGGEST ONE!!!1GABEN
|
||||
{
|
||||
template<class MFP> static inline void GetFuncInfo(MFP mfp, MemFuncInfo &out)
|
||||
{
|
||||
out.vtblindex = MFI_GetVtblOffset(*(void**)&mfp);
|
||||
out.isVirtual = out.vtblindex >= 0 ? true : false;
|
||||
|
||||
// The member function pointer is 16 bytes long. We can't use a normal cast, but
|
||||
// we can use a union to do the conversion.
|
||||
union {
|
||||
MFP func;
|
||||
// In VC++ and ICL, an unknown_inheritance member pointer
|
||||
// is internally defined as:
|
||||
struct {
|
||||
void *m_funcaddress; // points to the actual member function
|
||||
int delta; // #bytes to be added to the 'this' pointer
|
||||
int vtordisp; // #bytes to add to 'this' to find the vtable
|
||||
int vtable_index; // or 0 if no virtual inheritance
|
||||
} s;
|
||||
} u;
|
||||
// Check that the horrible_cast will work
|
||||
typedef int ERROR_CantUsehorrible_cast[sizeof(u.func)==sizeof(u.s)? 1 : -1];
|
||||
u.func = mfp;
|
||||
int virtual_delta = 0;
|
||||
if (u.s.vtable_index) { // Virtual inheritance is used
|
||||
/*
|
||||
// First, get to the vtable.
|
||||
// It is 'vtordisp' bytes from the start of the class.
|
||||
int * vtable = *reinterpret_cast<int **>(
|
||||
reinterpret_cast<char *>(thisptr) + u.s.vtordisp );
|
||||
|
||||
// 'vtable_index' tells us where in the table we should be looking.
|
||||
virtual_delta = u.s.vtordisp + *reinterpret_cast<const int *>(
|
||||
reinterpret_cast<const char *>(vtable) + u.s.vtable_index);
|
||||
// The int at 'virtual_delta' gives us the amount to add to 'this'.
|
||||
// Finally we can add the three components together. Phew!
|
||||
out.thisptr = reinterpret_cast<void *>(
|
||||
reinterpret_cast<char *>(thisptr) + u.s.delta + virtual_delta);
|
||||
*/
|
||||
out.vtbloffs = u.s.vtordisp;
|
||||
out.thisptroffs = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
out.vtbloffs = out.vtblindex < 0 ? 0 : u.s.delta;
|
||||
out.thisptroffs = u.s.delta;
|
||||
}
|
||||
};
|
||||
};
|
||||
# else
|
||||
# error Unsupported compiler
|
||||
# endif
|
||||
|
||||
template<class X> inline void GetFuncInfo(X mfp, MemFuncInfo &out)
|
||||
{
|
||||
MFI_Impl<sizeof(mfp)>::GetFuncInfo(mfp, out);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
74
sourcehook/sh_memory.h
Normal file
74
sourcehook/sh_memory.h
Normal file
@ -0,0 +1,74 @@
|
||||
/* ======== SourceMod ========
|
||||
* Copyright (C) 2004-2005 SourceMod Development Team
|
||||
* No warranties of any kind
|
||||
*
|
||||
* File: shint_memory.h
|
||||
* Memory unprotection
|
||||
*
|
||||
* License: See LICENSE.txt
|
||||
*
|
||||
* Author(s): PM, Damaged Soul
|
||||
* Contributors: lancevorgin, XAD, theqizmo, Damaged-Soul
|
||||
* ============================
|
||||
*/
|
||||
|
||||
#ifndef __SHINT_MEMORY_H__
|
||||
#define __SHINT_MEMORY_H__
|
||||
|
||||
// Feb 17 / 2005:
|
||||
// Unprotect now sets to readwrite
|
||||
// The vtable doesn't need to be executable anyway
|
||||
|
||||
# if /********/ defined _WIN32
|
||||
# include <windows.h>
|
||||
# define SH_MEM_READ 1
|
||||
# define SH_MEM_WRITE 2
|
||||
# define SH_MEM_EXEC 4
|
||||
# elif /******/ defined __linux__
|
||||
# include <sys/mman.h>
|
||||
// http://www.die.net/doc/linux/man/man2/mprotect.2.html
|
||||
# include <limits.h>
|
||||
# ifndef PAGESIZE
|
||||
# define PAGESIZE 4096
|
||||
# endif
|
||||
# define SH_MEM_READ PROT_READ
|
||||
# define SH_MEM_WRITE PROT_WRITE
|
||||
# define SH_MEM_EXEC PROT_EXEC
|
||||
|
||||
// We need to align addr down to pagesize on linux
|
||||
// We assume PAGESIZE is a power of two
|
||||
# define SH_LALIGN(x) (void*)((int)(x) & ~(PAGESIZE-1))
|
||||
|
||||
# else
|
||||
# error Unsupported OS/Compiler
|
||||
# endif
|
||||
|
||||
|
||||
namespace SourceHook
|
||||
{
|
||||
inline bool SetMemAccess(void *addr, size_t len, int access)
|
||||
{
|
||||
# ifdef __linux__
|
||||
return mprotect(SH_LALIGN(addr), len, access)==0 ? true : false;
|
||||
# else
|
||||
DWORD tmp;
|
||||
DWORD prot;
|
||||
switch (access)
|
||||
{
|
||||
case SH_MEM_READ:
|
||||
prot = PAGE_READONLY; break;
|
||||
case SH_MEM_READ | SH_MEM_WRITE:
|
||||
prot = PAGE_READWRITE; break;
|
||||
case SH_MEM_READ | SH_MEM_EXEC:
|
||||
prot = PAGE_EXECUTE_READ; break;
|
||||
default:
|
||||
case SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC:
|
||||
prot = PAGE_EXECUTE_READWRITE; break;
|
||||
}
|
||||
return VirtualProtect(addr, len, prot, &tmp) ? true : false;
|
||||
# endif
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
553
sourcehook/sourcehook.cpp
Normal file
553
sourcehook/sourcehook.cpp
Normal file
@ -0,0 +1,553 @@
|
||||
/* ======== SourceHook ========
|
||||
* By PM
|
||||
* No warranties of any kind
|
||||
* ============================
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file sourcehook.cpp
|
||||
* @brief Contains the implementation of the SourceHook API
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include "sourcehook_impl.h"
|
||||
|
||||
#if SH_SYS == SH_SYS_WIN32
|
||||
# include <windows.h>
|
||||
#elif SH_SYS == SH_SYS_LINUX
|
||||
# include <sys/mman.h>
|
||||
# include <sys/limits.h>
|
||||
# include <unistd.h>
|
||||
# ifndef PAGESIZE
|
||||
# define PAGESIZE 4096
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if SH_RUNTIME_CODEGEN == 1
|
||||
# if SH_COMP == SH_COMP_GCC
|
||||
# define SH_CCC_CODESIZE 15
|
||||
// :TODO:
|
||||
//void SH_CCC_MakeGate(void *origthisptr, unsigned char* &ptr, void *origvtable, int i)
|
||||
//{
|
||||
//}
|
||||
# elif SH_COMP == SH_COMP_MSVC
|
||||
# define SH_CCC_CODESIZE 19
|
||||
void SH_CCC_MakeGate(void *origthisptr, void *ccthisptr, unsigned char* ptr, void *origfunc)
|
||||
{
|
||||
// --Subtract old this pointer to get the offset
|
||||
// 00417EDF 81 E9 A1 7B 33 01 sub ecx,1337BA1h
|
||||
*ptr++ = 0x81;
|
||||
*ptr++ = 0xE9;
|
||||
*reinterpret_cast<void**>(ptr) = ccthisptr;
|
||||
ptr += sizeof(void*);
|
||||
// --Add it to the new this pointer
|
||||
// 00417EE5 81 C1 37 13 37 13 add ecx,13371337h
|
||||
*ptr++ = 0x81;
|
||||
*ptr++ = 0xC1;
|
||||
*reinterpret_cast<void**>(ptr) = origthisptr;
|
||||
ptr += sizeof(void*);
|
||||
// --Prepare address
|
||||
// 00417EEB B8 EF BE AD DE mov eax,0DEADBEEFh
|
||||
*ptr++ = 0xB8;
|
||||
*reinterpret_cast<void**>(ptr) = origfunc;
|
||||
ptr += sizeof(void*);
|
||||
// -- Do actual jump
|
||||
// 00417EF0 FF E0 jmp eax
|
||||
*ptr++ = 0xFF;
|
||||
*ptr++ = 0xE0;
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
|
||||
|
||||
namespace SourceHook
|
||||
{
|
||||
CSourceHookImpl::CSourceHookImpl()
|
||||
{
|
||||
// Get page size
|
||||
#if SH_SYS == SH_SYS_WIN32
|
||||
SYSTEM_INFO sysinfo;
|
||||
GetSystemInfo(&sysinfo);
|
||||
m_PageSize = sysinfo.dwPageSize;
|
||||
#elif SH_SYS == SH_SYS_LINUX
|
||||
m_PageSize = PAGESIZE;
|
||||
#else
|
||||
# error Unsupported system
|
||||
#endif
|
||||
}
|
||||
|
||||
CSourceHookImpl::~CSourceHookImpl()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool CSourceHookImpl::IsPluginInUse(Plugin plug)
|
||||
{
|
||||
// Iterate through all hookers which are in this plugin
|
||||
// Iterate through their hooks
|
||||
// If a hook from an other plugin is found, return true
|
||||
// Return false otherwise
|
||||
|
||||
for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end(); ++iter)
|
||||
{
|
||||
if (iter->plug == plug && !iter->ifaces.empty())
|
||||
{
|
||||
for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end(); ++iter2)
|
||||
{
|
||||
std::list<HookerInfo::Iface::Hook>::iterator iter3;
|
||||
for (iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end(); ++iter3)
|
||||
if (iter3->plug == plug)
|
||||
return true;
|
||||
for (iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
|
||||
if (iter3->plug == plug)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void CSourceHookImpl::UnloadPlugin(Plugin plug)
|
||||
{
|
||||
// Get a list of hookers that are in this plugin and are used by other plugins
|
||||
|
||||
HookerInfoList tmphookers;
|
||||
bool erase = false;
|
||||
for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end();
|
||||
erase ? iter=m_Hookers.erase(iter) : ++iter)
|
||||
{
|
||||
if (iter->plug == plug && !iter->ifaces.empty())
|
||||
{
|
||||
bool found = false;
|
||||
for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin();
|
||||
iter2 != iter->ifaces.end(); ++iter2)
|
||||
{
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin();
|
||||
iter3 != iter2->hooks_pre.end(); ++iter3)
|
||||
{
|
||||
if (iter3->plug != plug)
|
||||
{
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
|
||||
{
|
||||
if (iter3->plug != plug)
|
||||
{
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found)
|
||||
{
|
||||
tmphookers.push_back(*iter);
|
||||
break;
|
||||
}
|
||||
}
|
||||
erase = true;
|
||||
}
|
||||
else
|
||||
erase = false;
|
||||
}
|
||||
|
||||
// For each hooker:
|
||||
for (HookerInfoList::iterator iter = tmphookers.begin(); iter != tmphookers.end(); ++iter)
|
||||
{
|
||||
// Shutdown all ifaces and remove the hooks from this plugin from their lists
|
||||
for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end();
|
||||
erase ? iter2 = iter->ifaces.erase(iter2) : ++iter2)
|
||||
{
|
||||
*(reinterpret_cast<void**>(reinterpret_cast<char*>(iter2->ptr) + iter->vtbl_offs)
|
||||
+ iter->vtbl_idx) = iter2->orig_entry;
|
||||
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end();
|
||||
iter3->plug == plug ? iter3=iter2->hooks_pre.erase(iter3) : ++iter3) {}
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end();
|
||||
iter3->plug == plug ? iter3=iter2->hooks_post.erase(iter3) : ++iter3) {}
|
||||
|
||||
erase = iter2->hooks_pre.empty() && iter2->hooks_post.empty();
|
||||
}
|
||||
|
||||
if (iter->ifaces.empty())
|
||||
{
|
||||
// Nothing more to do; no more ifaces to re-register
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2) Find a suitable hooker in an other plugin
|
||||
HookerInfoList::iterator newHooker = FindHooker(m_Hookers.begin(), m_Hookers.end(),
|
||||
iter->proto, iter->vtbl_offs, iter->vtbl_idx, iter->thisptr_offs);
|
||||
if (newHooker == m_Hookers.end())
|
||||
{
|
||||
// This should _never_ happen.
|
||||
// If there is a hook from an other plugin, the plugin must have provided a hooker as well.
|
||||
SH_ASSERT(0);
|
||||
}
|
||||
|
||||
// AddHook should make sure that every plugin only has _one_ hooker for _one_ proto/vi/vo
|
||||
SH_ASSERT(newHooker->plug != plug);
|
||||
|
||||
// 3) Register it!
|
||||
newHooker->func(HA_Register, &(*iter));
|
||||
for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end();
|
||||
++iter2)
|
||||
{
|
||||
reinterpret_cast<void**>(reinterpret_cast<char*>(iter2->ptr) + iter->vtbl_offs)[iter->vtbl_idx] =
|
||||
reinterpret_cast<void**>(reinterpret_cast<char*>(iter->hookfunc_inst) + iter->hookfunc_vtbl_offs)[iter->hookfunc_vtbl_idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CSourceHookImpl::CompleteShutdown()
|
||||
{
|
||||
// Go through all hookers and shut down all interfaces
|
||||
for (HookerInfoList::iterator iter = m_Hookers.begin(); iter != m_Hookers.end(); ++iter)
|
||||
{
|
||||
for (std::list<HookerInfo::Iface>::iterator iter2 = iter->ifaces.begin(); iter2 != iter->ifaces.end(); ++iter2)
|
||||
{
|
||||
// Note that we can pass iter->func as "myHooker" because it is only used
|
||||
// to retreive data
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_pre.begin(); iter3 != iter2->hooks_pre.end(); ++iter3)
|
||||
RemoveHook(iter3->plug, iter2->ptr, iter->func, iter3->handler, false);
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator iter3 = iter2->hooks_post.begin(); iter3 != iter2->hooks_post.end(); ++iter3)
|
||||
RemoveHook(iter3->plug, iter2->ptr, iter->func, iter3->handler, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CSourceHookImpl::AddHook(Plugin plug, void *iface, int ifacesize, Hooker myHooker, ISHDelegate *handler, bool post)
|
||||
{
|
||||
// 1) Get info about the hooker
|
||||
HookerInfo tmp;
|
||||
if (myHooker(HA_GetInfo, &tmp) != 0)
|
||||
return false;
|
||||
|
||||
// Add the proposed hooker to the _end_ of the list if the plugin doesn't have a hooker with this proto/vo/vi registered
|
||||
HookerInfoList::iterator hookeriter;
|
||||
for (hookeriter = m_Hookers.begin(); hookeriter != m_Hookers.end(); ++hookeriter)
|
||||
{
|
||||
if (hookeriter->plug == plug && strcmp(hookeriter->proto, tmp.proto) == 0 &&
|
||||
hookeriter->vtbl_offs == tmp.vtbl_offs && hookeriter->vtbl_idx == tmp.vtbl_idx &&
|
||||
hookeriter->thisptr_offs == tmp.thisptr_offs)
|
||||
break;
|
||||
}
|
||||
if (hookeriter == m_Hookers.end())
|
||||
{
|
||||
// No such hooker from this plugin yet, add it!
|
||||
tmp.func = myHooker;
|
||||
tmp.plug = plug;
|
||||
m_Hookers.push_back(tmp);
|
||||
}
|
||||
|
||||
// Then, search for a suitable hooker (from the beginning)
|
||||
HookerInfoList::iterator hooker = FindHooker(m_Hookers.begin(), m_Hookers.end(), tmp.proto, tmp.vtbl_offs, tmp.vtbl_idx, tmp.thisptr_offs);
|
||||
SH_ASSERT(hooker != m_Hookers.end());
|
||||
|
||||
// Tell it to store the pointer if it's not already active
|
||||
if (hooker->ifaces.empty())
|
||||
hooker->func(HA_Register, &(*hooker));
|
||||
|
||||
std::list<HookerInfo::Iface>::iterator ifsiter = std::find(hooker->ifaces.begin(), hooker->ifaces.end(), iface);
|
||||
|
||||
if (ifsiter == hooker->ifaces.end())
|
||||
{
|
||||
HookerInfo::Iface ifs;
|
||||
ifs.ptr = iface;
|
||||
ifs.callclass = GetCallClass(iface, ifacesize);
|
||||
void *vtableptr = *reinterpret_cast<void**>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs);
|
||||
SetMemAccess(vtableptr, sizeof(void*) * hooker->vtbl_idx, SH_MEM_READ | SH_MEM_WRITE);
|
||||
ifs.orig_entry = (*reinterpret_cast<void***>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs))[hooker->vtbl_idx];
|
||||
(*reinterpret_cast<void***>(reinterpret_cast<char*>(iface) + hooker->vtbl_offs))[hooker->vtbl_idx] =
|
||||
(*reinterpret_cast<void***>(reinterpret_cast<char*>(hooker->hookfunc_inst) + hooker->hookfunc_vtbl_offs))[hooker->hookfunc_vtbl_idx];
|
||||
hooker->ifaces.push_back(ifs);
|
||||
ifsiter = hooker->ifaces.end();
|
||||
--ifsiter;
|
||||
}
|
||||
HookerInfo::Iface::Hook hookinfo;
|
||||
hookinfo.handler = handler;
|
||||
hookinfo.plug = plug;
|
||||
if (post)
|
||||
ifsiter->hooks_post.push_back(hookinfo);
|
||||
else
|
||||
ifsiter->hooks_pre.push_back(hookinfo);
|
||||
|
||||
|
||||
// Now that it is done, check whether we have to update any callclasses
|
||||
for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
|
||||
{
|
||||
if (cciter->iface == iface)
|
||||
{
|
||||
ApplyCallClassPatch(*cciter, tmp.vtbl_offs, tmp.vtbl_idx, ifsiter->orig_entry);
|
||||
|
||||
// We can assume that there is no more callclass with the same iface
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CSourceHookImpl::RemoveHook(Plugin plug, void *iface, Hooker myHooker, ISHDelegate *handler, bool post)
|
||||
{
|
||||
HookerInfo tmp;
|
||||
if (myHooker(HA_GetInfo, &tmp) != 0)
|
||||
return false;
|
||||
|
||||
// Find the hooker and the hook
|
||||
HookerInfoList::iterator hooker = FindHooker(m_Hookers.begin(), m_Hookers.end(),
|
||||
tmp.proto, tmp.vtbl_offs, tmp.vtbl_idx, tmp.thisptr_offs);
|
||||
if (hooker == m_Hookers.end())
|
||||
return false;
|
||||
|
||||
for (std::list<HookerInfo::Iface>::iterator ifaceiter = hooker->ifaces.begin(); ifaceiter != hooker->ifaces.end(); ++ifaceiter)
|
||||
{
|
||||
if (ifaceiter->ptr == iface)
|
||||
{
|
||||
std::list<HookerInfo::Iface::Hook> &hooks = post ? ifaceiter->hooks_post : ifaceiter->hooks_pre;
|
||||
bool erase;
|
||||
for (std::list<HookerInfo::Iface::Hook>::iterator hookiter = hooks.begin();
|
||||
hookiter != hooks.end(); erase ? hookiter = hooks.erase(hookiter) : ++hookiter)
|
||||
{
|
||||
erase = hookiter->plug == plug && hookiter->handler->IsEqual(handler);
|
||||
if (erase)
|
||||
hookiter->handler->DeleteThis(); // Make the _plugin_ delete the handler object
|
||||
}
|
||||
if (ifaceiter->hooks_post.empty() && ifaceiter->hooks_pre.empty())
|
||||
{
|
||||
// Deactivate the hook
|
||||
(*reinterpret_cast<void***>(reinterpret_cast<char*>(ifaceiter->ptr) +
|
||||
hooker->vtbl_offs))[hooker->vtbl_idx]= ifaceiter->orig_entry;
|
||||
|
||||
// Release the callclass
|
||||
ReleaseCallClass(ifaceiter->callclass);
|
||||
|
||||
// Remove the iface info
|
||||
hooker->ifaces.erase(ifaceiter);
|
||||
|
||||
if (hooker->ifaces.empty())
|
||||
hooker->func(HA_Unregister, NULL);
|
||||
}
|
||||
// :TODO: Better return value? Or none?
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void *CSourceHookImpl::GetCallClass(void *iface, size_t size)
|
||||
{
|
||||
for (Impl_CallClassList::iterator cciter = m_CallClasses.begin(); cciter != m_CallClasses.end(); ++cciter)
|
||||
{
|
||||
if (cciter->iface == iface)
|
||||
{
|
||||
++cciter->refcounter;
|
||||
return cciter->ptr;
|
||||
}
|
||||
}
|
||||
|
||||
// The layout of callclasses is:
|
||||
// Copy of the class; vtable entries pointing to gates
|
||||
// Pointer to the corresponding CallClass object
|
||||
// Copy of the class; vtable entries pointing to original functions
|
||||
|
||||
CallClass tmp;
|
||||
char *ptr = new char[size * 2 + sizeof(void*)];
|
||||
tmp.ptr = reinterpret_cast<void*>(ptr);
|
||||
memcpy(reinterpret_cast<void*>(ptr), iface, size);
|
||||
memcpy(reinterpret_cast<void*>(ptr + size + sizeof(void*)), iface, size);
|
||||
tmp.iface = iface;
|
||||
tmp.size = size;
|
||||
tmp.refcounter = 1;
|
||||
|
||||
// Go through _all_ hooks and apply any needed patches
|
||||
for (HookerInfoList::iterator hooker = m_Hookers.begin(); hooker != m_Hookers.end(); ++hooker)
|
||||
{
|
||||
for (std::list<HookerInfo::Iface>::iterator ifaceiter = hooker->ifaces.begin(); ifaceiter != hooker->ifaces.end(); ++ifaceiter)
|
||||
{
|
||||
if (ifaceiter->ptr == iface)
|
||||
{
|
||||
if (!ApplyCallClassPatch(tmp, hooker->vtbl_offs, hooker->vtbl_idx, ifaceiter->orig_entry))
|
||||
{
|
||||
FreeCallClass(tmp);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m_CallClasses.push_back(tmp);
|
||||
// The object has to be followed by the pointer to the vtable info object
|
||||
*reinterpret_cast<void**>(ptr + size) = &m_CallClasses.back();
|
||||
return tmp.ptr;
|
||||
}
|
||||
|
||||
void CSourceHookImpl::ReleaseCallClass(void *ptr)
|
||||
{
|
||||
Impl_CallClassList::iterator iter = std::find(m_CallClasses.begin(), m_CallClasses.end(), ptr);
|
||||
if (iter == m_CallClasses.end())
|
||||
return;
|
||||
--iter->refcounter;
|
||||
if (iter->refcounter < 1)
|
||||
{
|
||||
FreeCallClass(*iter);
|
||||
m_CallClasses.erase(iter);
|
||||
}
|
||||
}
|
||||
|
||||
void CSourceHookImpl::FreeCallClass(CallClass &cc)
|
||||
{
|
||||
for (CallClass::VTableList::iterator vtbliter = cc.vtables.begin(); vtbliter != cc.vtables.end(); ++vtbliter)
|
||||
{
|
||||
#if SH_RUNTIME_CODEGEN == 1
|
||||
// Delete generated callgates
|
||||
for (std::list<int>::iterator cgiter = vtbliter->patches.begin(); cgiter != vtbliter->patches.end(); ++cgiter)
|
||||
{
|
||||
char *cgptr = reinterpret_cast<char**>(vtbliter->ptr)[*cgiter];
|
||||
delete [] cgptr;
|
||||
}
|
||||
#endif
|
||||
delete [] reinterpret_cast<char*>(vtbliter->ptr);
|
||||
}
|
||||
delete [] reinterpret_cast<char*>(cc.ptr);
|
||||
}
|
||||
|
||||
bool CSourceHookImpl::ApplyCallClassPatch(CallClass &cc, int vtbl_offs, int vtbl_idx, void *orig_entry)
|
||||
{
|
||||
char *ptr = reinterpret_cast<char*>(cc.ptr);
|
||||
void *vtable = *reinterpret_cast<void**>(ptr + vtbl_offs);
|
||||
|
||||
// Check whether we already know that vtable
|
||||
CallClass::VTableList::iterator vtbliter = std::find(cc.vtables.begin(),
|
||||
cc.vtables.end(), reinterpret_cast<void*>(vtable));
|
||||
int actvtablesize=MAX_VTABLE_LEN;
|
||||
if (vtbliter == cc.vtables.end())
|
||||
{
|
||||
CallClass::VTable newvtableinfo;
|
||||
int pagesnum = (MAX_VTABLE_LEN % m_PageSize == 0) ? MAX_VTABLE_LEN / m_PageSize : MAX_VTABLE_LEN / m_PageSize + 1;
|
||||
// Set all pages in the range to readwrite
|
||||
// :TODO: Fix this!
|
||||
char *pagebegin = reinterpret_cast<char*>(vtable) - (reinterpret_cast<int>(vtable) % m_PageSize);
|
||||
for (int ipage = 0; ipage < pagesnum; ++ipage)
|
||||
{
|
||||
if (!SetMemAccess(reinterpret_cast<void*>(pagebegin + ipage * m_PageSize), 1,
|
||||
SH_MEM_READ | SH_MEM_WRITE))
|
||||
{
|
||||
// We can't go here anymore
|
||||
actvtablesize = static_cast<int>((pagebegin + ipage * m_PageSize) - reinterpret_cast<char*>(vtable));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (actvtablesize < 1)
|
||||
{
|
||||
// We can't access the vtable -> Quit
|
||||
return false;
|
||||
}
|
||||
// Create a new vtable
|
||||
newvtableinfo.ptr = reinterpret_cast<void*>(new char[actvtablesize]);
|
||||
// Fill it with the information from the old vtable
|
||||
memcpy(newvtableinfo.ptr, vtable, actvtablesize);
|
||||
newvtableinfo.actsize = actvtablesize;
|
||||
// Set the pointer in the object and add it to the list of already known vtables
|
||||
*reinterpret_cast<void**>(ptr + vtbl_offs) = newvtableinfo.ptr;
|
||||
cc.vtables.push_back(newvtableinfo);
|
||||
|
||||
vtbliter = cc.vtables.end();
|
||||
--vtbliter;
|
||||
// :TODO: When not codegen, patch the other vtable?
|
||||
}
|
||||
|
||||
// Check whether we already have this patch
|
||||
if (std::find(vtbliter->patches.begin(), vtbliter->patches.end(), vtbl_idx) == vtbliter->patches.end())
|
||||
{
|
||||
// No -> apply it
|
||||
|
||||
// Get a call gate
|
||||
void *callgate = NULL;
|
||||
#if SH_RUNTIME_CODEGEN == 1
|
||||
unsigned char *cggen = new unsigned char[SH_CCC_CODESIZE];
|
||||
SH_CCC_MakeGate(cc.iface, cc.ptr, cggen, orig_entry);
|
||||
callgate = (void*)cggen;
|
||||
SetMemAccess(callgate, SH_CCC_CODESIZE, SH_MEM_READ | SH_MEM_WRITE | SH_MEM_EXEC);
|
||||
#else
|
||||
// :TODO:
|
||||
#error Not supported yet!
|
||||
#endif
|
||||
vtbliter->patches.push_back(vtbl_idx);
|
||||
reinterpret_cast<void**>(vtbliter->ptr)[vtbl_idx] = callgate;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
CSourceHookImpl::HookerInfoList::iterator CSourceHookImpl::FindHooker(HookerInfoList::iterator begin,
|
||||
HookerInfoList::iterator end, const char *proto, int vtblofs, int vtblidx, int thisptrofs)
|
||||
{
|
||||
for (HookerInfoList::iterator hookeriter = m_Hookers.begin(); hookeriter != m_Hookers.end(); ++hookeriter)
|
||||
{
|
||||
if (strcmp(hookeriter->proto, proto) == 0 && hookeriter->vtbl_offs == vtblofs && hookeriter->vtbl_idx == vtblidx &&
|
||||
hookeriter->thisptr_offs == thisptrofs)
|
||||
break;
|
||||
}
|
||||
return hookeriter;
|
||||
}
|
||||
|
||||
|
||||
void CSourceHookImpl::SetRes(META_RES res)
|
||||
{
|
||||
m_CurRes = res;
|
||||
}
|
||||
|
||||
META_RES CSourceHookImpl::GetPrevRes()
|
||||
{
|
||||
return m_PrevRes;
|
||||
}
|
||||
|
||||
META_RES CSourceHookImpl::GetStatus()
|
||||
{
|
||||
return m_Status;
|
||||
}
|
||||
|
||||
const void *CSourceHookImpl::GetOrigRet()
|
||||
{
|
||||
return m_OrigRet;
|
||||
}
|
||||
|
||||
const void *CSourceHookImpl::GetOverrideRet()
|
||||
{
|
||||
return m_OverrideRet;
|
||||
}
|
||||
|
||||
META_RES &CSourceHookImpl::GetCurResRef()
|
||||
{
|
||||
return m_CurRes;
|
||||
}
|
||||
|
||||
META_RES &CSourceHookImpl::GetPrevResRef()
|
||||
{
|
||||
return m_PrevRes;
|
||||
}
|
||||
|
||||
META_RES &CSourceHookImpl::GetStatusRef()
|
||||
{
|
||||
return m_Status;
|
||||
}
|
||||
|
||||
void CSourceHookImpl::SetOrigRet(const void *ptr)
|
||||
{
|
||||
m_OrigRet = ptr;
|
||||
}
|
||||
|
||||
void CSourceHookImpl::SetOverrideRet(const void *ptr)
|
||||
{
|
||||
m_OverrideRet = ptr;
|
||||
}
|
||||
|
||||
void CSourceHookImpl::SetIfacePtr(void *ptr)
|
||||
{
|
||||
m_IfacePtr = ptr;
|
||||
}
|
||||
void *CSourceHookImpl::GetIfacePtr()
|
||||
{
|
||||
return m_IfacePtr;
|
||||
}
|
||||
}
|
||||
1294
sourcehook/sourcehook.h
Normal file
1294
sourcehook/sourcehook.h
Normal file
File diff suppressed because it is too large
Load Diff
136
sourcehook/sourcehook_impl.h
Normal file
136
sourcehook/sourcehook_impl.h
Normal file
@ -0,0 +1,136 @@
|
||||
/* ======== SourceHook ========
|
||||
* By PM
|
||||
* No warranties of any kind
|
||||
*
|
||||
* This file declares necessary stuff for the sourcehook implementation.
|
||||
* ============================
|
||||
*/
|
||||
|
||||
#ifndef __SOURCEHOOK_IMPL_H__
|
||||
#define __SOURCEHOOK_IMPL_H__
|
||||
|
||||
#include "sourcehook.h"
|
||||
|
||||
// Set this to 1 to enable runtime code generation (faster)
|
||||
#define SH_RUNTIME_CODEGEN 1
|
||||
|
||||
namespace SourceHook
|
||||
{
|
||||
/**
|
||||
* @brief The SourceHook implementation class
|
||||
*/
|
||||
class CSourceHookImpl : public ISourceHook
|
||||
{
|
||||
/**
|
||||
* @brief A list of HookerInfo structures
|
||||
*/
|
||||
typedef std::list<HookerInfo> HookerInfoList;
|
||||
|
||||
|
||||
/**
|
||||
* @brief A list of Impl_CallClass structures
|
||||
*/
|
||||
typedef std::list<CallClass> Impl_CallClassList;
|
||||
|
||||
Impl_CallClassList m_CallClasses; //!< A list of already generated callclasses
|
||||
HookerInfoList m_Hookers; //!< A list of hookers
|
||||
|
||||
int m_PageSize; //!< Stores the system's page size
|
||||
|
||||
/**
|
||||
* @brief Finds a hooker for a function based on a text-prototype, a vtable offset and a vtable index
|
||||
*/
|
||||
HookerInfoList::iterator FindHooker(HookerInfoList::iterator begin, HookerInfoList::iterator end,
|
||||
const char *proto, int vtblofs, int vtblidx, int thisptrofs);
|
||||
|
||||
void FreeCallClass(CallClass &cc);
|
||||
bool ApplyCallClassPatch(CallClass &cc, int vtbl_offs, int vtbl_idx, void *orig_entry);
|
||||
|
||||
static const int MAX_VTABLE_LEN = 4096; //!< Maximal vtable length in bytes
|
||||
|
||||
META_RES m_Status, m_PrevRes, m_CurRes;
|
||||
const void *m_OrigRet;
|
||||
const void *m_OverrideRet;
|
||||
void *m_IfacePtr;
|
||||
public:
|
||||
CSourceHookImpl();
|
||||
~CSourceHookImpl();
|
||||
|
||||
/**
|
||||
* @brief Make sure that a plugin is not used by any other plugins anymore, and unregister all its hookers
|
||||
*/
|
||||
void UnloadPlugin(Plugin plug);
|
||||
|
||||
/**
|
||||
* @brief Shut down the whole system, unregister all hookers
|
||||
*/
|
||||
void CompleteShutdown();
|
||||
|
||||
/**
|
||||
* @brief Add a hook.
|
||||
*
|
||||
* @return True if the function succeeded, false otherwise
|
||||
*
|
||||
* @param plug The unique identifier of the plugin that calls this function
|
||||
* @param iface The interface pointer
|
||||
* @param myHooker A hooker (hook manager) function that should be capable of handling the corresponding function
|
||||
* @param handler A pointer to a FastDelegate containing the hook handler
|
||||
* @param post Set to true if you want a post handler
|
||||
*/
|
||||
bool AddHook(Plugin plug, void *iface, int ifacesize, Hooker myHooker, ISHDelegate *handler, bool post);
|
||||
|
||||
/**
|
||||
* @brief Removes a hook.
|
||||
*
|
||||
* @return True if the function succeeded, false otherwise
|
||||
*
|
||||
* @param plug The unique identifier of the plugin that calls this function
|
||||
* @param iface The interface pointer
|
||||
* @param vtableoffset Offset to the vtable, in bytes
|
||||
* @param vtableidx Pointer to the vtable index of the function
|
||||
* @param proto A text version of the function prototype; generated by the macros
|
||||
* @param handler A pointer to a FastDelegate containing the hook handler
|
||||
* @param post Set to true if you want a post handler
|
||||
*/
|
||||
bool RemoveHook(Plugin plug, void *iface, Hooker myHooker, ISHDelegate *handler, bool post);
|
||||
|
||||
/**
|
||||
* @brief Checks whether a plugin has (a) hooker(s) that is/are currently used by other plugins
|
||||
*
|
||||
* @param plug The unique identifier of the plugin in question
|
||||
*/
|
||||
bool IsPluginInUse(Plugin plug);
|
||||
|
||||
/**
|
||||
* @brief Return a pointer to a callclass. Generate a new one if required.
|
||||
*
|
||||
* @param iface The interface pointer
|
||||
*/
|
||||
void *GetCallClass(void *iface, size_t size);
|
||||
|
||||
/**
|
||||
* @brief Release a callclass
|
||||
*
|
||||
* @param ptr Pointer to the callclass
|
||||
*/
|
||||
virtual void ReleaseCallClass(void *ptr);
|
||||
|
||||
virtual void SetRes(META_RES res); //!< Sets the meta result
|
||||
virtual META_RES GetPrevRes(); //!< Gets the meta result of the previously called handler
|
||||
virtual META_RES GetStatus(); //!< Gets the highest meta result
|
||||
virtual const void *GetOrigRet(); //!< Gets the original result. If not in post function, undefined
|
||||
virtual const void *GetOverrideRet(); //!< Gets the override result. If none is specified, NULL
|
||||
virtual void *GetIfacePtr(); //!< Gets the interface pointer
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// For hookers
|
||||
virtual META_RES &GetCurResRef(); //!< Gets the pointer to the current meta result
|
||||
virtual META_RES &GetPrevResRef(); //!< Gets the pointer to the previous meta result
|
||||
virtual META_RES &GetStatusRef(); //!< Gets the pointer to the status variable
|
||||
virtual void SetOrigRet(const void *ptr); //!< Sets the original return pointer
|
||||
virtual void SetOverrideRet(const void *ptr); //!< Sets the override result pointer
|
||||
virtual void SetIfacePtr(void *ptr); //!< Sets the interface this pointer
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
Loading…
Reference in New Issue
Block a user