Merge.
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"
20 * @brief Implementation of main API interface
24 using namespace SourceMM;
38 m_UserMessages.RemoveAll();
41 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
44 static char buffer[2048];
47 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
50 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
53 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
57 return g_Engine.engineFactory;
60 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
63 return PhysicsFactory;
64 return g_Engine.physicsFactory;
67 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
70 return FileSystemFactory;
71 return g_Engine.fileSystemFactory;
74 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
78 return g_GameDll.factory;
81 CGlobalVars *CSmmAPI::pGlobals()
83 return g_Engine.pGlobals;
86 void CSmmAPI::SetLastMetaReturn(META_RES res)
91 META_RES CSmmAPI::GetLastMetaReturn()
96 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
98 return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
101 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
103 if (pCommand->IsCommand())
105 g_PluginMngr.AddPluginCmd(plugin, pCommand);
107 g_PluginMngr.AddPluginCvar(plugin, pCommand);
110 return g_SMConVarAccessor.Register(pCommand);
113 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
115 if (pCommand->IsCommand())
117 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
119 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
122 CPluginManager::CPlugin *pPlugin = g_PluginMngr.FindByAPI(plugin);
123 PluginId id = (pPlugin != NULL) ? pPlugin->m_Id : Pl_BadLoad;
125 NotifyConCommandBaseDrop(id, pCommand);
127 g_SMConVarAccessor.Unregister(pCommand);
130 void CSmmAPI::ConPrint(const char *fmt)
132 (m_ConPrintf)("%s", fmt);
135 void CSmmAPI::ConPrintf(const char *fmt, ...)
138 static char buffer[4096];
141 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
144 (m_ConPrintf)("%s", buffer);
147 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
149 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
150 CPluginEventHandler cpeh;
152 cpeh.event = pListener;
153 cpeh.got_vsp = false;
155 pl->m_Events.push_back(cpeh);
158 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
170 //first check ours... we get first chance!
171 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
177 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
178 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
183 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
186 CPluginManager::CPlugin *pl;
187 SourceHook::List<CPluginEventHandler>::iterator event;
188 IMetamodListener *api;
192 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
195 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
197 api = (*event).event;
199 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
211 *_ret = IFACE_FAILED;
216 //////////////////////////////////////////////////////////////////////////
217 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
218 // (note: you can find the offset by looking for the text //
219 // "Echo text to console", you'll find the callback cmd pushed on the //
221 //////////////////////////////////////////////////////////////////////////
224 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
225 #define ENGINE486_OFFS 40
226 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
227 #define ENGINE686_OFFS 50
228 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
229 #define ENGINEAMD_OFFS 47
230 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
231 #define ENGINEW32_OFFS 38
232 #define IA32_CALL 0xE8
234 //Thanks to fysh for the idea of extracting info from "echo" and for
235 // having the original offsets at hand!
236 bool CSmmAPI::CacheCmds()
238 ICvar *pCvar = g_Engine.icvar;
240 ConCommandBase *pBase = pCvar->GetCommands();
241 unsigned char *ptr = NULL;
242 FnCommandCallback callback = NULL;
247 if ( strcmp(pBase->GetName(), "echo") == 0 )
249 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
250 callback = ((ConCommand *)pBase)->GetCallback();
251 ptr = (unsigned char *)callback;
253 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
255 offs = ENGINE486_OFFS;
257 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
259 offs = ENGINE686_OFFS;
261 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
263 offs = ENGINEAMD_OFFS;
265 #elif defined OS_WIN32 // Only one Windows engine binary so far...
266 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
268 offs = ENGINEW32_OFFS;
272 if (!offs || ptr[offs - 1] != IA32_CALL)
274 m_ConPrintf = (CONPRINTF_FUNC)Msg;
277 //get the relative offset
278 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
279 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
280 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
286 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
289 m_ConPrintf = (CONPRINTF_FUNC)Msg;
294 bool CSmmAPI::CmdCacheSuccessful()
299 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
301 major = SM_VERS_API_MAJOR;
302 minor = SM_VERS_API_MINOR;
303 plvers = PLAPI_VERSION;
304 plmin = PLAPI_MIN_VERSION;
307 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
309 shvers = SH_IFACE_VERSION;
310 shimpl = SH_IMPL_VERSION;
313 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
315 int length = (int)strlen(iface);
319 for (i = length - 1; i >= 0; i--)
321 if (!isdigit(iface[i]))
331 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
337 num = atoi(&(iface[++i]));
341 snprintf(&(iface[i]), 4, "%03d", num);
346 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
348 char _if[256]; /* assume no interface goes beyond this */
349 size_t len = strlen(iface);
356 if (len + 4 > sizeof(_if))
369 if ( (pf = (fn)(_if, ret)) != NULL )
373 } while (( num = FormatIface(_if, len+1) ));
378 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
380 char buffer[256]; /* assume no interface will go beyond this */
381 size_t len = strlen(iface);
382 int ret; /* just in case something doesn't handle NULL properly */
384 if (len > sizeof(buffer) - 4)
389 strcpy(buffer, iface);
393 char *ptr = &buffer[len - 1];
395 while (isdigit(*ptr) && digits <=3)
403 /* for now, assume this is an error */
404 strcpy(buffer, iface);
407 min = (min == 0) ? 1 : min;
408 snprintf(num, sizeof(num), "%03d", min);
413 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
416 const char *CSmmAPI::GetBaseDir()
418 return g_ModPath.c_str();
421 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
425 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
428 for (size_t i = 0; i < mylen; i++)
430 if (buffer[i] == ALT_SEP_CHAR)
432 buffer[i] = PATH_SEP_CHAR;
437 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
440 static char buffer[4096];
443 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
446 g_Engine.engine->ClientPrintf(client, buffer);
449 void CSmmAPI::LoadAsVSP()
452 char engine_file[PATH_SIZE];
453 char rel_path[PATH_SIZE * 2];
455 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
457 /* Chop off the "engine" file part */
458 len = strlen(engine_file);
459 for (size_t i = len - 1; i >= 0 && i < len; i--)
461 if (engine_file[i] == '/'
462 || engine_file[i] == '\\')
464 engine_file[i] = '\0';
469 char our_path[PATH_SIZE];
470 GetFileOfAddress((void*)LoadAsGameDLL, our_path, sizeof(our_path));
472 const char *usepath = our_path;
473 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, our_path))
476 char command[PATH_SIZE * 2];
477 g_VspListener.SetLoadable(true);
478 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
479 g_Engine.engine->ServerCommand(command);
482 void CSmmAPI::EnableVSPListener()
484 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
485 if (g_bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_bIsBridgedAsVsp)
492 int CSmmAPI::GetGameDLLVersion()
494 return g_GameDllVersion;
497 //////////////////////////////////////////////////////////////////////
498 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
499 // Signatures necessary in finding the pointer to the CUtlDict that //
500 // stores user message information. //
501 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
502 // message indices. This is our answer to it. Yuck! <:-( //
503 //////////////////////////////////////////////////////////////////////
505 /* General Windows sig */
506 #define MSGCLASS_SIGLEN 7
507 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
508 #define MSGCLASS_OFFS 2
510 /* Dystopia Wimdows hack */
511 #define MSGCLASS2_SIGLEN 16
512 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
513 #define MSGCLASS2_OFFS 11
515 /* Windows frame pointer sig */
516 #define MSGCLASS3_SIGLEN 18
517 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
518 #define MSGCLASS3_OFFS 13
519 #elif defined OS_LINUX
520 /* No frame pointer sig */
521 #define MSGCLASS_SIGLEN 14
522 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
523 #define MSGCLASS_OFFS 9
525 /* Frame pointer sig */
526 #define MSGCLASS2_SIGLEN 16
527 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
528 #define MSGCLASS2_OFFS 11
531 /* This is the ugliest function in all of SourceMM */
532 /* :TODO: Make this prettier */
533 bool CSmmAPI::CacheUserMessages()
535 UserMsgDict *dict = NULL;
536 char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL);
543 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
545 /* Get address of CUserMessages instance */
546 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
548 /* Get address of CUserMessages::m_UserMessages */
549 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
550 } else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
552 /* If we get here, the code is possibly inlined like in Dystopia */
554 /* Get the address of the CUtlRBTree */
555 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
557 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
558 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
559 #elif defined OS_LINUX
560 /* Get address of CUserMessages instance */
561 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
563 /* Get address of CUserMessages::m_UserMessages */
564 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
567 } else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
568 /* Get address of CUserMessages instance */
569 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
571 /* Get address of CUserMessages::m_UserMessages */
572 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
578 m_MsgCount = dict->Count();
580 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
581 if (m_MsgCount < 0 || m_MsgCount > 255)
589 /* Cache messages in our CUtlDict */
590 for (int i = 0; i < m_MsgCount; i++)
592 msg = dict->Element(i);
593 m_UserMessages.Insert(msg->name, msg);
602 bool CSmmAPI::MsgCacheSuccessful()
604 return m_MsgCount > -1;
607 int CSmmAPI::GetUserMessageCount()
612 int CSmmAPI::FindUserMessage(const char *name, int *size)
614 int index = m_UserMessages.Find(name);
616 if (size && index > -1)
618 UserMessage *msg = m_UserMessages.Element(index);
625 const char *CSmmAPI::GetUserMessage(int index, int *size)
627 if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
632 UserMessage *msg = m_UserMessages.Element(index);