1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2007 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * ============================
11 #include "convar_smm.h"
14 #include "concommands.h"
16 #include "vsp_listener.h"
19 * @brief Implementation of main API interface
23 using namespace SourceMM;
37 m_UserMessages.RemoveAll();
40 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
43 static char buffer[2048];
46 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
49 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
52 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
56 return g_Engine.engineFactory;
59 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
62 return PhysicsFactory;
63 return g_Engine.physicsFactory;
66 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
69 return FileSystemFactory;
70 return g_Engine.fileSystemFactory;
73 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
76 return CreateInterface;
77 return g_GameDll.factory;
80 CGlobalVars *CSmmAPI::pGlobals()
82 return g_Engine.pGlobals;
85 void CSmmAPI::SetLastMetaReturn(META_RES res)
90 META_RES CSmmAPI::GetLastMetaReturn()
95 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
97 return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
100 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
102 if (pCommand->IsCommand())
104 g_PluginMngr.AddPluginCmd(plugin, pCommand);
106 g_PluginMngr.AddPluginCvar(plugin, pCommand);
109 return g_SMConVarAccessor.Register(pCommand);
112 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
114 if (pCommand->IsCommand())
116 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
118 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
121 g_SMConVarAccessor.Unregister(g_PluginMngr.FindByAPI(plugin)->m_Id, pCommand);
124 void CSmmAPI::ConPrint(const char *fmt)
126 (m_ConPrintf)("%s", fmt);
129 void CSmmAPI::ConPrintf(const char *fmt, ...)
132 static char buffer[4096];
135 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
138 (m_ConPrintf)("%s", buffer);
141 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
143 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
145 pl->m_Events.push_back(pListener);
148 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
160 //first check ours... we get first chance!
161 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
167 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
168 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
173 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
176 CPluginManager::CPlugin *pl;
177 SourceHook::List<IMetamodListener *>::iterator event;
178 IMetamodListener *api;
182 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
185 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
189 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
201 *_ret = IFACE_FAILED;
206 //////////////////////////////////////////////////////////////////////////
207 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
208 // (note: you can find the offset by looking for the text //
209 // "Echo text to console", you'll find the callback cmd pushed on the //
211 //////////////////////////////////////////////////////////////////////////
214 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
215 #define ENGINE486_OFFS 40
216 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
217 #define ENGINE686_OFFS 50
218 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
219 #define ENGINEAMD_OFFS 47
220 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
221 #define ENGINEW32_OFFS 38
222 #define IA32_CALL 0xE8
224 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
226 unsigned char *addr1 = (unsigned char *)_addr1;
227 unsigned char *addr2 = (unsigned char *)_addr2;
229 for (size_t i=0; i<len; i++)
233 if (addr1[i] != addr2[i])
240 //Thanks to fysh for the idea of extracting info from "echo" and for
241 // having the original offsets at hand!
242 bool CSmmAPI::CacheCmds()
244 ICvar *pCvar = g_Engine.icvar;
246 ConCommandBase *pBase = pCvar->GetCommands();
247 unsigned char *ptr = NULL;
248 FnCommandCallback callback = NULL;
253 if ( strcmp(pBase->GetName(), "echo") == 0 )
255 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
256 callback = ((ConCommand *)pBase)->GetCallback();
257 ptr = (unsigned char *)callback;
259 if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
261 offs = ENGINE486_OFFS;
263 else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
265 offs = ENGINE686_OFFS;
267 else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
269 offs = ENGINEAMD_OFFS;
271 #elif defined OS_WIN32 // Only one Windows engine binary so far...
272 if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
274 offs = ENGINEW32_OFFS;
278 if (!offs || ptr[offs - 1] != IA32_CALL)
280 m_ConPrintf = (CONPRINTF_FUNC)Msg;
283 //get the relative offset
284 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
285 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
286 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
292 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
295 m_ConPrintf = (CONPRINTF_FUNC)Msg;
300 bool CSmmAPI::CmdCacheSuccessful()
305 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
307 major = SM_VERS_API_MAJOR;
308 minor = SM_VERS_API_MINOR;
309 plvers = PLAPI_VERSION;
310 plmin = PLAPI_MIN_VERSION;
313 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
315 shvers = SH_IFACE_VERSION;
316 shimpl = SH_IMPL_VERSION;
319 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
321 int length = (int)strlen(iface);
325 for (i = length - 1; i >= 0; i--)
327 if (!isdigit(iface[i]))
337 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
343 num = atoi(&(iface[++i]));
347 snprintf(&(iface[i]), 4, "%03d", num);
352 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
354 char _if[256]; /* assume no interface goes beyond this */
355 size_t len = strlen(iface);
362 if (len + 4 > sizeof(_if))
375 if ( (pf = (fn)(_if, ret)) != NULL )
379 } while (( num = FormatIface(_if, len+1) ));
384 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
386 char buffer[256]; /* assume no interface will go beyond this */
387 size_t len = strlen(iface);
388 int ret; /* just in case something doesn't handle NULL properly */
390 if (len > sizeof(buffer) - 4)
395 strcpy(buffer, iface);
399 char *ptr = &buffer[len - 1];
401 while (isdigit(*ptr) && digits <=3)
409 /* for now, assume this is an error */
410 strcpy(buffer, iface);
413 min = (min == 0) ? 1 : min;
414 snprintf(num, sizeof(num), "%03d", min);
419 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
422 const char *CSmmAPI::GetBaseDir()
424 return g_ModPath.c_str();
427 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
431 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
434 for (size_t i = 0; i < mylen; i++)
436 if (buffer[i] == ALT_SEP_CHAR)
438 buffer[i] = PATH_SEP_CHAR;
443 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
446 static char buffer[4096];
449 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
452 g_Engine.engine->ClientPrintf(client, buffer);
455 void CSmmAPI::LoadAsVSP()
458 char engine_file[PATH_SIZE];
459 char engine_path[PATH_SIZE];
460 char rel_path[PATH_SIZE * 2];
462 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
464 /* Chop off the "engine" file part */
465 len = strlen(engine_file);
466 for (size_t i = len - 1; i >= 0 && i < len; i--)
468 if (engine_file[i] == '/'
469 || engine_file[i] == '\\')
471 engine_file[i] = '\0';
475 abspath(engine_path, engine_file);
477 const char *usepath = g_SmmPath.c_str();
478 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, g_SmmPath.c_str()))
483 char command[PATH_SIZE * 2];
484 g_VspListener.SetLoadable(true);
485 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
486 g_Engine.engine->ServerCommand(command);
489 void CSmmAPI::EnableVSPListener()
491 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
492 if (bGameInit && !m_VSP && !g_VspListener.IsLoaded())
499 int CSmmAPI::GetGameDLLVersion()
501 return g_GameDllVersion;
504 //////////////////////////////////////////////////////////////////////
505 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
506 // Signatures necessary in finding the pointer to the CUtlDict that //
507 // stores user message information. //
508 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
509 // message indices. This is our answer to it. Yuck! <:-( //
510 //////////////////////////////////////////////////////////////////////
512 /* General Windows sig */
513 #define MSGCLASS_SIGLEN 7
514 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
515 #define MSGCLASS_OFFS 2
517 /* Dystopia Wimdows hack */
518 #define MSGCLASS2_SIGLEN 16
519 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
520 #define MSGCLASS2_OFFS 11
522 /* Windows frame pointer sig */
523 #define MSGCLASS3_SIGLEN 18
524 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
525 #define MSGCLASS3_OFFS 13
526 #elif defined OS_LINUX
527 /* No frame pointer sig */
528 #define MSGCLASS_SIGLEN 14
529 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
530 #define MSGCLASS_OFFS 9
532 /* Frame pointer sig */
533 #define MSGCLASS2_SIGLEN 16
534 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
535 #define MSGCLASS2_OFFS 11
538 /* This is the ugliest function in all of SourceMM */
539 /* :TODO: Make this prettier */
540 bool CSmmAPI::CacheUserMessages()
542 SourceHook::MemFuncInfo info = {true, -1, 0, 0};
543 SourceHook::GetFuncInfo(&IServerGameDLL::GetUserMessageInfo, info);
545 /* Get address of original GetUserMessageInfo() */
546 char *vfunc = reinterpret_cast<char *>(g_GameDllPatch->GetOrigFunc(info.vtbloffs, info.vtblindex));
548 /* If we can't get original function, that means there's no hook */
551 /* Get virtual function address 'manually' then */
552 char *adjustedptr = reinterpret_cast<char *>(g_GameDll.pGameDLL) + info.thisptroffs + info.vtbloffs;
553 char **vtable = *reinterpret_cast<char ***>(adjustedptr);
555 vfunc = vtable[info.vtblindex];
558 /* Oh dear, we have a relative jump on our hands
559 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
561 if (*vfunc == '\xE9')
563 /* Get address from displacement...
565 * Add 5 because it's relative to next instruction:
566 * Opcode <1 byte> + 32-bit displacement <4 bytes>
568 vfunc = vfunc + *reinterpret_cast<int *>(vfunc + 1) + 5;
571 UserMsgDict *dict = NULL;
573 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
575 /* Get address of CUserMessages instance */
576 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
578 /* Get address of CUserMessages::m_UserMessages */
579 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
580 } else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
582 /* If we get here, the code is possibly inlined like in Dystopia */
584 /* Get the address of the CUtlRBTree */
585 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
587 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
588 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
589 #elif defined OS_LINUX
590 /* Get address of CUserMessages instance */
591 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
593 /* Get address of CUserMessages::m_UserMessages */
594 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
597 } else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
598 /* Get address of CUserMessages instance */
599 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
601 /* Get address of CUserMessages::m_UserMessages */
602 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
608 m_MsgCount = dict->Count();
610 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
611 if (m_MsgCount < 0 || m_MsgCount > 255)
619 /* Cache messages in our CUtlDict */
620 for (int i = 0; i < m_MsgCount; i++)
622 msg = dict->Element(i);
623 m_UserMessages.Insert(msg->name, msg);
632 bool CSmmAPI::MsgCacheSuccessful()
634 return m_MsgCount > -1;
637 int CSmmAPI::GetUserMessageCount()
642 int CSmmAPI::FindUserMessage(const char *name, int *size)
644 int index = m_UserMessages.Find(name);
646 if (size && index > -1)
648 UserMessage *msg = m_UserMessages.Element(index);
655 const char *CSmmAPI::GetUserMessage(int index, int *size)
657 if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
662 UserMessage *msg = m_UserMessages.Element(index);
671 int CSmmAPI::GetVSPVersion()