Fixed circular dependency between sourcemm.h/util.h (build bustage).
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 g_SMConVarAccessor.Unregister(pCommand);
125 void CSmmAPI::ConPrint(const char *fmt)
127 (m_ConPrintf)("%s", fmt);
130 void CSmmAPI::ConPrintf(const char *fmt, ...)
133 static char buffer[4096];
136 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
139 (m_ConPrintf)("%s", buffer);
142 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
144 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
145 CPluginEventHandler cpeh;
147 cpeh.event = pListener;
148 cpeh.got_vsp = false;
150 pl->m_Events.push_back(cpeh);
153 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
165 //first check ours... we get first chance!
166 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
172 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
173 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
178 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
181 CPluginManager::CPlugin *pl;
182 SourceHook::List<CPluginEventHandler>::iterator event;
183 IMetamodListener *api;
187 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
190 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
192 api = (*event).event;
194 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
206 *_ret = IFACE_FAILED;
211 //////////////////////////////////////////////////////////////////////////
212 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
213 // (note: you can find the offset by looking for the text //
214 // "Echo text to console", you'll find the callback cmd pushed on the //
216 //////////////////////////////////////////////////////////////////////////
219 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
220 #define ENGINE486_OFFS 40
221 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
222 #define ENGINE686_OFFS 50
223 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
224 #define ENGINEAMD_OFFS 47
225 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
226 #define ENGINEW32_OFFS 38
227 #define IA32_CALL 0xE8
229 //Thanks to fysh for the idea of extracting info from "echo" and for
230 // having the original offsets at hand!
231 bool CSmmAPI::CacheCmds()
233 ICvar *pCvar = g_Engine.icvar;
235 ConCommandBase *pBase = pCvar->GetCommands();
236 unsigned char *ptr = NULL;
237 FnCommandCallback callback = NULL;
242 if ( strcmp(pBase->GetName(), "echo") == 0 )
244 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
245 callback = ((ConCommand *)pBase)->GetCallback();
246 ptr = (unsigned char *)callback;
248 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
250 offs = ENGINE486_OFFS;
252 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
254 offs = ENGINE686_OFFS;
256 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
258 offs = ENGINEAMD_OFFS;
260 #elif defined OS_WIN32 // Only one Windows engine binary so far...
261 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
263 offs = ENGINEW32_OFFS;
267 if (!offs || ptr[offs - 1] != IA32_CALL)
269 m_ConPrintf = (CONPRINTF_FUNC)Msg;
272 //get the relative offset
273 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
274 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
275 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
281 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
284 m_ConPrintf = (CONPRINTF_FUNC)Msg;
289 bool CSmmAPI::CmdCacheSuccessful()
294 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
296 major = SM_VERS_API_MAJOR;
297 minor = SM_VERS_API_MINOR;
298 plvers = PLAPI_VERSION;
299 plmin = PLAPI_MIN_VERSION;
302 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
304 shvers = SH_IFACE_VERSION;
305 shimpl = SH_IMPL_VERSION;
308 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
310 int length = (int)strlen(iface);
314 for (i = length - 1; i >= 0; i--)
316 if (!isdigit(iface[i]))
326 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
332 num = atoi(&(iface[++i]));
336 snprintf(&(iface[i]), 4, "%03d", num);
341 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
343 char _if[256]; /* assume no interface goes beyond this */
344 size_t len = strlen(iface);
351 if (len + 4 > sizeof(_if))
364 if ( (pf = (fn)(_if, ret)) != NULL )
368 } while (( num = FormatIface(_if, len+1) ));
373 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
375 char buffer[256]; /* assume no interface will go beyond this */
376 size_t len = strlen(iface);
377 int ret; /* just in case something doesn't handle NULL properly */
379 if (len > sizeof(buffer) - 4)
384 strcpy(buffer, iface);
388 char *ptr = &buffer[len - 1];
390 while (isdigit(*ptr) && digits <=3)
398 /* for now, assume this is an error */
399 strcpy(buffer, iface);
402 min = (min == 0) ? 1 : min;
403 snprintf(num, sizeof(num), "%03d", min);
408 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
411 const char *CSmmAPI::GetBaseDir()
413 return g_ModPath.c_str();
416 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
420 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
423 for (size_t i = 0; i < mylen; i++)
425 if (buffer[i] == ALT_SEP_CHAR)
427 buffer[i] = PATH_SEP_CHAR;
432 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
435 static char buffer[4096];
438 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
441 g_Engine.engine->ClientPrintf(client, buffer);
444 void CSmmAPI::LoadAsVSP()
447 char engine_file[PATH_SIZE];
448 char rel_path[PATH_SIZE * 2];
450 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
452 /* Chop off the "engine" file part */
453 len = strlen(engine_file);
454 for (size_t i = len - 1; i >= 0 && i < len; i--)
456 if (engine_file[i] == '/'
457 || engine_file[i] == '\\')
459 engine_file[i] = '\0';
464 char our_path[PATH_SIZE];
465 GetFileOfAddress((void*)LoadAsGameDLL, our_path, sizeof(our_path));
467 const char *usepath = our_path;
468 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, our_path))
471 char command[PATH_SIZE * 2];
472 g_VspListener.SetLoadable(true);
473 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
474 g_Engine.engine->ServerCommand(command);
477 void CSmmAPI::EnableVSPListener()
479 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
480 if (g_bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_bIsBridgedAsVsp)
487 int CSmmAPI::GetGameDLLVersion()
489 return g_GameDllVersion;
492 //////////////////////////////////////////////////////////////////////
493 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
494 // Signatures necessary in finding the pointer to the CUtlDict that //
495 // stores user message information. //
496 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
497 // message indices. This is our answer to it. Yuck! <:-( //
498 //////////////////////////////////////////////////////////////////////
500 /* General Windows sig */
501 #define MSGCLASS_SIGLEN 7
502 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
503 #define MSGCLASS_OFFS 2
505 /* Dystopia Wimdows hack */
506 #define MSGCLASS2_SIGLEN 16
507 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
508 #define MSGCLASS2_OFFS 11
510 /* Windows frame pointer sig */
511 #define MSGCLASS3_SIGLEN 18
512 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
513 #define MSGCLASS3_OFFS 13
514 #elif defined OS_LINUX
515 /* No frame pointer sig */
516 #define MSGCLASS_SIGLEN 14
517 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
518 #define MSGCLASS_OFFS 9
520 /* Frame pointer sig */
521 #define MSGCLASS2_SIGLEN 16
522 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
523 #define MSGCLASS2_OFFS 11
526 /* This is the ugliest function in all of SourceMM */
527 /* :TODO: Make this prettier */
528 bool CSmmAPI::CacheUserMessages()
530 UserMsgDict *dict = NULL;
531 char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL);
538 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
540 /* Get address of CUserMessages instance */
541 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
543 /* Get address of CUserMessages::m_UserMessages */
544 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
545 } else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
547 /* If we get here, the code is possibly inlined like in Dystopia */
549 /* Get the address of the CUtlRBTree */
550 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
552 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
553 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
554 #elif defined OS_LINUX
555 /* Get address of CUserMessages instance */
556 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
558 /* Get address of CUserMessages::m_UserMessages */
559 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
562 } else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
563 /* Get address of CUserMessages instance */
564 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
566 /* Get address of CUserMessages::m_UserMessages */
567 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
573 m_MsgCount = dict->Count();
575 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
576 if (m_MsgCount < 0 || m_MsgCount > 255)
584 /* Cache messages in our CUtlDict */
585 for (int i = 0; i < m_MsgCount; i++)
587 msg = dict->Element(i);
588 m_UserMessages.Insert(msg->name, msg);
597 bool CSmmAPI::MsgCacheSuccessful()
599 return m_MsgCount > -1;
602 int CSmmAPI::GetUserMessageCount()
607 int CSmmAPI::FindUserMessage(const char *name, int *size)
609 int index = m_UserMessages.Find(name);
611 if (size && index > -1)
613 UserMessage *msg = m_UserMessages.Element(index);
620 const char *CSmmAPI::GetUserMessage(int index, int *size)
622 if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
627 UserMessage *msg = m_UserMessages.Element(index);