core/sourcehook/sourcehook_impl_cvfnptr.cpp
author Scott Ehlert <ds@alliedmods.net>
Fri Jun 24 17:18:15 2011 -0500 (2011-06-24)
changeset 760 719dcf97dc1b
parent 733 2365240861a2
child 767 fd3ff8d792ce
permissions -rw-r--r--
Oh, triggering a build.
     1 /* ======== SourceHook ========
     2 * Copyright (C) 2004-2010 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): Pavol "PM OnoTo" Marko
     8 * ============================
     9 */
    10 
    11 #include "sourcehook_impl.h"
    12 
    13 namespace SourceHook
    14 {
    15 	namespace Impl
    16 	{
    17 		CPageAlloc CVfnPtr::ms_AlignedPageAllocator(8);
    18 
    19 		CVfnPtr::CVfnPtr(void *ptr)
    20 			: m_Ptr(ptr), m_OrigEntry(*reinterpret_cast<void**>(m_Ptr)),
    21 			m_OrigCallThunk(NULL)
    22 		{
    23 		}
    24 
    25 		CVfnPtr::~CVfnPtr()
    26 		{
    27 			if (!m_HookMans.empty())
    28 				m_HookMans.front()->DecrRef(this);
    29 		}
    30 
    31 		bool CVfnPtr::Init()
    32 		{
    33 			// Initalize the vfn ptr info object.
    34 
    35 			// If we're running on GCC and the original vtable entry is odd
    36 			// we have a problem.
    37 			// The hook functions use non-virtual member function pointers to
    38 			// call the original function (see sourcehook.hxx, SH_SETUP_MFP and SH_CALL_ORIG)
    39 			// GCC has the same format for virtual and non-virtual MFPs:
    40 			// virtual ones have an odd value as "funcptr" where the offset into the vtable is encoded
    41 			// non-virtual ones have the direct function pointer as "funcptr", assuming that it is even
    42 
    43 			// When m_OrigEntry is odd, GCC's runtime MFP calling code interpretes it as a virtual
    44 			// function call though we want to call the function in a non-virtual way
    45 			// (the original function call mechanism between the pre and post hook loop has to bypass
    46 			// the virtual calling mechanism in order to call the original function).
    47 
    48 #if SH_COMP==SH_COMP_GCC
    49 			if ((((ptrdiff_t)m_OrigEntry) & 1) != 0)
    50 			{
    51 				// Odd orig entry.
    52 				if (SH_PTRSIZE != 4)
    53 				{
    54 					// We only have code for IA32 atm!
    55 					return false;
    56 				}
    57 
    58 				// Generate a new thunk
    59 				m_OrigCallThunk = ms_AlignedPageAllocator.Alloc(5);
    60 				ms_AlignedPageAllocator.SetRW(m_OrigCallThunk);
    61 
    62 				unsigned char* thunkBase = reinterpret_cast<unsigned char*>(m_OrigCallThunk);
    63 				*(thunkBase + 0) = 0xE9;		// offset jump, immediate operand
    64 				ptrdiff_t *offsetAddr = reinterpret_cast<ptrdiff_t*>(thunkBase + 1);
    65 				
    66 				// destination = src + offset + 5
    67 				// <=>  offset = destination - src - 5
    68 				*offsetAddr =
    69 					(reinterpret_cast<unsigned char*>(m_OrigEntry) - thunkBase) - 5;
    70 
    71 				ms_AlignedPageAllocator.SetRE(m_OrigCallThunk);
    72 			}
    73 #endif
    74 			return true;
    75 		}
    76 
    77 		class CVfnPtrOrigThunkCleanup : public ICleanupTask
    78 		{
    79 			CPageAlloc *m_Allocator;
    80 			void *m_AddrToFree;
    81 
    82 		public:
    83 			CVfnPtrOrigThunkCleanup(CPageAlloc *allocator, void *addrToFree) :
    84 				m_Allocator(allocator), m_AddrToFree(addrToFree)
    85 			{
    86 			}
    87 
    88 			virtual void CleanupAndDeleteThis()
    89 			{
    90 				m_Allocator->Free(m_AddrToFree);
    91 				delete this;
    92 			}
    93 		};
    94 
    95 		ICleanupTask* CVfnPtr::GetCleanupTask()
    96 		{
    97 			if (m_OrigCallThunk != NULL)
    98 			{
    99 				return new CVfnPtrOrigThunkCleanup(&ms_AlignedPageAllocator, m_OrigCallThunk);
   100 			}
   101 			else
   102 			{
   103 				return NULL;
   104 			}
   105 		}
   106 
   107 		void* CVfnPtr::GetOrigCallAddr() const
   108 		{
   109 			if (m_OrigCallThunk)
   110 			{
   111 				return m_OrigCallThunk;
   112 			}
   113 			else
   114 			{
   115 				return m_OrigEntry;
   116 			}
   117 		}
   118 
   119 		bool CVfnPtr::Revert()
   120 		{
   121 			// Only patch the vfnptr back if the module is still in memory
   122 			// If it's not, do not remove stuff like we did before
   123 			// First off we did it wrong (shutdown the whole hookman, uh..) and secondly applications may be
   124 			// confused by RemoveHook returning false then (yeah, I know, I made this one up, no one checks for RemoveHook error)
   125 			if (ModuleInMemory(reinterpret_cast<char*>(m_Ptr), SH_PTRSIZE))
   126 			{
   127 				return Patch(m_OrigEntry);
   128 			}
   129 			else
   130 			{
   131 				return true;
   132 			}
   133 		}
   134 
   135 		CIface *CVfnPtr::FindIface(void *iface)
   136 		{
   137 			List<CIface>::iterator iter = m_IfaceList.find(iface);
   138 			if (iter == m_IfaceList.end())
   139 				return NULL;
   140 			else
   141 				return &(*iter);
   142 		}
   143 
   144 		void CVfnPtr::AddHookMan(CHookManager *pHookMan)
   145 		{
   146 			List<CHookManager*>::iterator iter;
   147 
   148 			// Don't accept invalid hook managers
   149 			if (!*pHookMan)
   150 				return;
   151 
   152 			// Check whether this hook manager already exists; if yes, ignore.
   153 			iter = m_HookMans.find(pHookMan);
   154 			if (iter != m_HookMans.end())
   155 				return;
   156 
   157 			// It doesn't -> add it. Add it to the end of its version group.
   158 			for (iter = m_HookMans.begin(); iter != m_HookMans.end(); ++iter)
   159 			{
   160 				if ((*iter)->GetVersion() < pHookMan->GetVersion())
   161 					break;
   162 			}
   163 
   164 			bool isBeginning = iter == m_HookMans.begin();
   165 
   166 			m_HookMans.insert(iter, pHookMan);
   167 
   168 			if (isBeginning)
   169 			{
   170 				pHookMan->IncrRef(this);
   171 				if (m_HookMans.size() > 1)
   172 				{
   173 					// If another hookman was used until now but this one is better
   174 					// (which it is because it's the first -> it has a higher version)
   175 					// -> switch!
   176 
   177 					List<CHookManager*>::iterator second = m_HookMans.begin();
   178 					++second;
   179 
   180 					(*second)->DecrRef(this);
   181 				}
   182 
   183 				// Make sure that this vfnptr points at it
   184 				Patch(pHookMan->GetHookFunc());
   185 			}
   186 		}
   187 
   188 		bool CVfnPtr::HookManRemoved(CHookManager *pHookMan)
   189 		{
   190 			// Don't accept invalid hook managers
   191 			if (!*pHookMan)
   192 				return true;
   193 
   194 			List<CHookManager*>::iterator iter = m_HookMans.find(pHookMan);
   195 			if (iter == m_HookMans.end())
   196 				return true;							// Didn't exist here anyway
   197 
   198 			if (iter == m_HookMans.begin())
   199 			{
   200 				// It is the first one!
   201 				pHookMan->DecrRef(this);
   202 				m_HookMans.erase(iter);
   203 
   204 				if (m_HookMans.empty())
   205 					return false;				// No more hookmans -> let SH delete us
   206 
   207 				// Activate second -> now first hookman
   208 				m_HookMans.front()->IncrRef(this);
   209 				Patch(m_HookMans.front()->GetHookFunc());
   210 			}
   211 			else
   212 			{
   213 				m_HookMans.erase(iter);
   214 			}
   215 			return true;
   216 		}
   217 
   218 		bool CVfnPtr::Patch(void *newValue)
   219 		{
   220 			if (!SetMemAccess(m_Ptr, sizeof(void*), SH_MEM_READ | SH_MEM_WRITE))
   221 			{
   222 				return false;
   223 			}
   224 
   225 			*reinterpret_cast<void**>(m_Ptr) = newValue;
   226 
   227 			return true;
   228 		}
   229 
   230 		CIface &CVfnPtr::GetIface(void *iface)
   231 		{
   232 			List<CIface>::iterator iter = m_IfaceList.find(iface);
   233 			if (iter == m_IfaceList.end())
   234 			{
   235 				CIface newIface(iface);
   236 				if (iface == NULL)
   237 				{
   238 					m_IfaceList.push_front(newIface);
   239 					return m_IfaceList.front();
   240 				}
   241 				else
   242 				{
   243 					m_IfaceList.push_back(newIface);
   244 					return m_IfaceList.back();
   245 				}
   246 			}
   247 			else
   248 			{
   249 				return *iter;
   250 			}
   251 		}
   252 	}
   253 }