Initial import of core-legacy as a gameinfo provider.
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)
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(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);
144 CPluginEventHandler cpeh;
146 cpeh.event = pListener;
147 cpeh.got_vsp = false;
149 pl->m_Events.push_back(cpeh);
152 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
164 //first check ours... we get first chance!
165 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
171 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
172 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
177 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
180 CPluginManager::CPlugin *pl;
181 SourceHook::List<CPluginEventHandler>::iterator event;
182 IMetamodListener *api;
186 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
189 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
191 api = (*event).event;
193 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
205 *_ret = IFACE_FAILED;
210 //////////////////////////////////////////////////////////////////////////
211 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
212 // (note: you can find the offset by looking for the text //
213 // "Echo text to console", you'll find the callback cmd pushed on the //
215 //////////////////////////////////////////////////////////////////////////
218 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
219 #define ENGINE486_OFFS 40
220 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
221 #define ENGINE686_OFFS 50
222 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
223 #define ENGINEAMD_OFFS 47
224 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
225 #define ENGINEW32_OFFS 38
226 #define IA32_CALL 0xE8
228 //Thanks to fysh for the idea of extracting info from "echo" and for
229 // having the original offsets at hand!
230 bool CSmmAPI::CacheCmds()
232 ICvar *pCvar = g_Engine.icvar;
234 ConCommandBase *pBase = pCvar->GetCommands();
235 unsigned char *ptr = NULL;
236 FnCommandCallback callback = NULL;
241 if ( strcmp(pBase->GetName(), "echo") == 0 )
243 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
244 callback = ((ConCommand *)pBase)->GetCallback();
245 ptr = (unsigned char *)callback;
247 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
249 offs = ENGINE486_OFFS;
251 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
253 offs = ENGINE686_OFFS;
255 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
257 offs = ENGINEAMD_OFFS;
259 #elif defined OS_WIN32 // Only one Windows engine binary so far...
260 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
262 offs = ENGINEW32_OFFS;
266 if (!offs || ptr[offs - 1] != IA32_CALL)
268 m_ConPrintf = (CONPRINTF_FUNC)Msg;
271 //get the relative offset
272 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
273 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
274 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
280 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
283 m_ConPrintf = (CONPRINTF_FUNC)Msg;
288 bool CSmmAPI::CmdCacheSuccessful()
293 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
295 major = SM_VERS_API_MAJOR;
296 minor = SM_VERS_API_MINOR;
297 plvers = PLAPI_VERSION;
298 plmin = PLAPI_MIN_VERSION;
301 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
303 shvers = SH_IFACE_VERSION;
304 shimpl = SH_IMPL_VERSION;
307 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
309 int length = (int)strlen(iface);
313 for (i = length - 1; i >= 0; i--)
315 if (!isdigit(iface[i]))
325 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
331 num = atoi(&(iface[++i]));
335 snprintf(&(iface[i]), 4, "%03d", num);
340 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
342 char _if[256]; /* assume no interface goes beyond this */
343 size_t len = strlen(iface);
350 if (len + 4 > sizeof(_if))
363 if ( (pf = (fn)(_if, ret)) != NULL )
367 } while (( num = FormatIface(_if, len+1) ));
372 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
374 char buffer[256]; /* assume no interface will go beyond this */
375 size_t len = strlen(iface);
376 int ret; /* just in case something doesn't handle NULL properly */
378 if (len > sizeof(buffer) - 4)
383 strcpy(buffer, iface);
387 char *ptr = &buffer[len - 1];
389 while (isdigit(*ptr) && digits <=3)
397 /* for now, assume this is an error */
398 strcpy(buffer, iface);
401 min = (min == 0) ? 1 : min;
402 snprintf(num, sizeof(num), "%03d", min);
407 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
410 const char *CSmmAPI::GetBaseDir()
412 return g_ModPath.c_str();
415 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
419 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
422 for (size_t i = 0; i < mylen; i++)
424 if (buffer[i] == ALT_SEP_CHAR)
426 buffer[i] = PATH_SEP_CHAR;
431 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
434 static char buffer[4096];
437 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
440 g_Engine.engine->ClientPrintf(client, buffer);
443 void CSmmAPI::LoadAsVSP()
446 char engine_file[PATH_SIZE];
447 char rel_path[PATH_SIZE * 2];
449 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
451 /* Chop off the "engine" file part */
452 len = strlen(engine_file);
453 for (size_t i = len - 1; i >= 0 && i < len; i--)
455 if (engine_file[i] == '/'
456 || engine_file[i] == '\\')
458 engine_file[i] = '\0';
463 char our_path[PATH_SIZE];
464 GetFileOfAddress((void*)LoadAsGameDLL, our_path, sizeof(our_path));
466 const char *usepath = our_path;
467 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, our_path))
470 char command[PATH_SIZE * 2];
471 g_VspListener.SetLoadable(true);
472 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
473 g_Engine.engine->ServerCommand(command);
476 void CSmmAPI::EnableVSPListener()
478 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
479 if (g_bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_bIsBridgedAsVsp)
486 int CSmmAPI::GetGameDLLVersion()
488 return g_GameDllVersion;
491 //////////////////////////////////////////////////////////////////////
492 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
493 // Signatures necessary in finding the pointer to the CUtlDict that //
494 // stores user message information. //
495 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
496 // message indices. This is our answer to it. Yuck! <:-( //
497 //////////////////////////////////////////////////////////////////////
499 /* General Windows sig */
500 #define MSGCLASS_SIGLEN 7
501 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
502 #define MSGCLASS_OFFS 2
504 /* Dystopia Wimdows hack */
505 #define MSGCLASS2_SIGLEN 16
506 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
507 #define MSGCLASS2_OFFS 11
509 /* Windows frame pointer sig */
510 #define MSGCLASS3_SIGLEN 18
511 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
512 #define MSGCLASS3_OFFS 13
513 #elif defined OS_LINUX
514 /* No frame pointer sig */
515 #define MSGCLASS_SIGLEN 14
516 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
517 #define MSGCLASS_OFFS 9
519 /* Frame pointer sig */
520 #define MSGCLASS2_SIGLEN 16
521 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
522 #define MSGCLASS2_OFFS 11
525 /* This is the ugliest function in all of SourceMM */
526 /* :TODO: Make this prettier */
527 bool CSmmAPI::CacheUserMessages()
529 UserMsgDict *dict = NULL;
530 char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL, g_GameDllPatch);
537 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
539 /* Get address of CUserMessages instance */
540 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
542 /* Get address of CUserMessages::m_UserMessages */
543 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
544 } else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
546 /* If we get here, the code is possibly inlined like in Dystopia */
548 /* Get the address of the CUtlRBTree */
549 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
551 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
552 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
553 #elif defined OS_LINUX
554 /* Get address of CUserMessages instance */
555 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
557 /* Get address of CUserMessages::m_UserMessages */
558 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
561 } else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
562 /* Get address of CUserMessages instance */
563 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
565 /* Get address of CUserMessages::m_UserMessages */
566 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
572 m_MsgCount = dict->Count();
574 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
575 if (m_MsgCount < 0 || m_MsgCount > 255)
583 /* Cache messages in our CUtlDict */
584 for (int i = 0; i < m_MsgCount; i++)
586 msg = dict->Element(i);
587 m_UserMessages.Insert(msg->name, msg);
596 bool CSmmAPI::MsgCacheSuccessful()
598 return m_MsgCount > -1;
601 int CSmmAPI::GetUserMessageCount()
606 int CSmmAPI::FindUserMessage(const char *name, int *size)
608 int index = m_UserMessages.Find(name);
610 if (size && index > -1)
612 UserMessage *msg = m_UserMessages.Element(index);
619 const char *CSmmAPI::GetUserMessage(int index, int *size)
621 if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
626 UserMessage *msg = m_UserMessages.Element(index);