1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2008 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)
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 CPluginManager::CPlugin *pPlugin = g_PluginMngr.FindByAPI(plugin);
122 PluginId id = (pPlugin != NULL) ? pPlugin->m_Id : Pl_BadLoad;
124 NotifyConCommandBaseDrop(id, pCommand);
126 g_SMConVarAccessor.Unregister(pCommand);
129 void CSmmAPI::ConPrint(const char *fmt)
131 (m_ConPrintf)("%s", fmt);
134 void CSmmAPI::ConPrintf(const char *fmt, ...)
137 static char buffer[4096];
140 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
143 (m_ConPrintf)("%s", buffer);
146 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
148 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
149 CPluginEventHandler cpeh;
151 cpeh.event = pListener;
152 cpeh.got_vsp = false;
154 pl->m_Events.push_back(cpeh);
157 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
169 //first check ours... we get first chance!
170 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
176 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
177 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
182 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
185 CPluginManager::CPlugin *pl;
186 SourceHook::List<CPluginEventHandler>::iterator event;
187 IMetamodListener *api;
191 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
194 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
196 api = (*event).event;
198 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
210 *_ret = IFACE_FAILED;
215 //////////////////////////////////////////////////////////////////////////
216 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
217 // (note: you can find the offset by looking for the text //
218 // "Echo text to console", you'll find the callback cmd pushed on the //
220 //////////////////////////////////////////////////////////////////////////
223 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
224 #define ENGINE486_OFFS 40
225 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
226 #define ENGINE686_OFFS 50
227 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
228 #define ENGINEAMD_OFFS 47
229 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
230 #define ENGINEW32_OFFS 38
231 #define IA32_CALL 0xE8
233 //Thanks to fysh for the idea of extracting info from "echo" and for
234 // having the original offsets at hand!
235 bool CSmmAPI::CacheCmds()
237 ICvar *pCvar = g_Engine.icvar;
239 ConCommandBase *pBase = pCvar->GetCommands();
240 unsigned char *ptr = NULL;
241 FnCommandCallback callback = NULL;
246 if ( strcmp(pBase->GetName(), "echo") == 0 )
248 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
249 callback = ((ConCommand *)pBase)->GetCallback();
250 ptr = (unsigned char *)callback;
252 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
254 offs = ENGINE486_OFFS;
256 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
258 offs = ENGINE686_OFFS;
260 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
262 offs = ENGINEAMD_OFFS;
264 #elif defined OS_WIN32 // Only one Windows engine binary so far...
265 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
267 offs = ENGINEW32_OFFS;
271 if (!offs || ptr[offs - 1] != IA32_CALL)
273 m_ConPrintf = (CONPRINTF_FUNC)Msg;
276 //get the relative offset
277 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
278 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
279 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
285 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
288 m_ConPrintf = (CONPRINTF_FUNC)Msg;
293 bool CSmmAPI::CmdCacheSuccessful()
298 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
300 major = SM_VERS_API_MAJOR;
301 minor = SM_VERS_API_MINOR;
302 plvers = PLAPI_VERSION;
303 plmin = PLAPI_MIN_VERSION;
306 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
308 shvers = SH_IFACE_VERSION;
309 shimpl = SH_IMPL_VERSION;
312 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
314 int length = (int)strlen(iface);
318 for (i = length - 1; i >= 0; i--)
320 if (!isdigit(iface[i]))
330 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
336 num = atoi(&(iface[++i]));
340 snprintf(&(iface[i]), 4, "%03d", num);
345 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
347 char _if[256]; /* assume no interface goes beyond this */
348 size_t len = strlen(iface);
355 if (len + 4 > sizeof(_if))
368 if ( (pf = (fn)(_if, ret)) != NULL )
372 } while (( num = FormatIface(_if, len+1) ));
377 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
379 char buffer[256]; /* assume no interface will go beyond this */
380 size_t len = strlen(iface);
381 int ret; /* just in case something doesn't handle NULL properly */
383 if (len > sizeof(buffer) - 4)
388 strcpy(buffer, iface);
392 char *ptr = &buffer[len - 1];
394 while (isdigit(*ptr) && digits <=3)
402 /* for now, assume this is an error */
403 strcpy(buffer, iface);
406 min = (min == 0) ? 1 : min;
407 snprintf(num, sizeof(num), "%03d", min);
412 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
415 const char *CSmmAPI::GetBaseDir()
417 return g_ModPath.c_str();
420 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
424 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
427 for (size_t i = 0; i < mylen; i++)
429 if (buffer[i] == ALT_SEP_CHAR)
431 buffer[i] = PATH_SEP_CHAR;
436 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
439 static char buffer[4096];
442 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
445 g_Engine.engine->ClientPrintf(client, buffer);
448 void CSmmAPI::LoadAsVSP()
451 char engine_file[PATH_SIZE];
452 char rel_path[PATH_SIZE * 2];
454 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
456 /* Chop off the "engine" file part */
457 len = strlen(engine_file);
458 for (size_t i = len - 1; i >= 0 && i < len; i--)
460 if (engine_file[i] == '/'
461 || engine_file[i] == '\\')
463 engine_file[i] = '\0';
468 char our_path[PATH_SIZE];
469 GetFileOfAddress((void*)LoadAsGameDLL, our_path, sizeof(our_path));
471 const char *usepath = our_path;
472 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, our_path))
475 char command[PATH_SIZE * 2];
476 g_VspListener.SetLoadable(true);
477 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
478 g_Engine.engine->ServerCommand(command);
481 void CSmmAPI::EnableVSPListener()
483 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
484 if (g_bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_bIsBridgedAsVsp)
491 int CSmmAPI::GetGameDLLVersion()
493 return g_GameDllVersion;
496 //////////////////////////////////////////////////////////////////////
497 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
498 // Signatures necessary in finding the pointer to the CUtlDict that //
499 // stores user message information. //
500 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
501 // message indices. This is our answer to it. Yuck! <:-( //
502 //////////////////////////////////////////////////////////////////////
504 /* General Windows sig */
505 #define MSGCLASS_SIGLEN 7
506 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
507 #define MSGCLASS_OFFS 2
509 /* Dystopia Wimdows hack */
510 #define MSGCLASS2_SIGLEN 16
511 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
512 #define MSGCLASS2_OFFS 11
514 /* Windows frame pointer sig */
515 #define MSGCLASS3_SIGLEN 18
516 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
517 #define MSGCLASS3_OFFS 13
518 #elif defined OS_LINUX
519 /* No frame pointer sig */
520 #define MSGCLASS_SIGLEN 14
521 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
522 #define MSGCLASS_OFFS 9
524 /* Frame pointer sig */
525 #define MSGCLASS2_SIGLEN 16
526 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
527 #define MSGCLASS2_OFFS 11
530 /* This is the ugliest function in all of SourceMM */
531 /* :TODO: Make this prettier */
532 bool CSmmAPI::CacheUserMessages()
534 UserMsgDict *dict = NULL;
535 char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL);
542 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
544 /* Get address of CUserMessages instance */
545 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
547 /* Get address of CUserMessages::m_UserMessages */
548 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
549 } else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
551 /* If we get here, the code is possibly inlined like in Dystopia */
553 /* Get the address of the CUtlRBTree */
554 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
556 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
557 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
558 #elif defined OS_LINUX
559 /* Get address of CUserMessages instance */
560 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
562 /* Get address of CUserMessages::m_UserMessages */
563 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
566 } else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
567 /* Get address of CUserMessages instance */
568 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
570 /* Get address of CUserMessages::m_UserMessages */
571 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
577 m_MsgCount = dict->Count();
579 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
580 if (m_MsgCount < 0 || m_MsgCount > 255)
588 /* Cache messages in our CUtlDict */
589 for (int i = 0; i < m_MsgCount; i++)
591 msg = dict->Element(i);
592 m_UserMessages.Insert(msg->name, msg);
601 bool CSmmAPI::MsgCacheSuccessful()
603 return m_MsgCount > -1;
606 int CSmmAPI::GetUserMessageCount()
611 int CSmmAPI::FindUserMessage(const char *name, int *size)
613 int index = m_UserMessages.Find(name);
615 if (size && index > -1)
617 UserMessage *msg = m_UserMessages.Element(index);
624 const char *CSmmAPI::GetUserMessage(int index, int *size)
626 if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
631 UserMessage *msg = m_UserMessages.Element(index);