1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2009 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"
17 #include "sh_memory.h"
21 * @brief Implementation of main API interface
25 using namespace SourceMM;
26 using namespace SourceHook;
33 UsrMsgInfo(int s, const char *t) : size(s), name(t)
42 static CVector<UsrMsgInfo> usermsgs_list;
43 static jmp_buf usermsg_end;
52 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
55 static char buffer[2048];
58 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
61 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
64 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
68 return g_Engine.engineFactory;
71 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
74 return PhysicsFactory;
75 return g_Engine.physicsFactory;
78 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
81 return FileSystemFactory;
82 return g_Engine.fileSystemFactory;
85 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
89 return g_GameDll.factory;
92 CGlobalVars *CSmmAPI::pGlobals()
94 return g_Engine.pGlobals;
97 void CSmmAPI::SetLastMetaReturn(META_RES res)
102 META_RES CSmmAPI::GetLastMetaReturn()
107 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
109 return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
112 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
114 if (pCommand->IsCommand())
116 g_PluginMngr.AddPluginCmd(plugin, pCommand);
118 g_PluginMngr.AddPluginCvar(plugin, pCommand);
121 return g_SMConVarAccessor.Register(pCommand);
124 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
126 if (pCommand->IsCommand())
128 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
130 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
133 CPluginManager::CPlugin *pPlugin = g_PluginMngr.FindByAPI(plugin);
134 PluginId id = (pPlugin != NULL) ? pPlugin->m_Id : Pl_BadLoad;
136 NotifyConCommandBaseDrop(id, pCommand);
138 g_SMConVarAccessor.Unregister(pCommand);
141 void CSmmAPI::ConPrint(const char *fmt)
143 (m_ConPrintf)("%s", fmt);
146 void CSmmAPI::ConPrintf(const char *fmt, ...)
149 static char buffer[4096];
152 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
155 (m_ConPrintf)("%s", buffer);
158 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
160 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
161 CPluginEventHandler cpeh;
163 cpeh.event = pListener;
164 cpeh.got_vsp = false;
166 pl->m_Events.push_back(cpeh);
169 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
181 //first check ours... we get first chance!
182 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
188 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
189 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
194 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
197 CPluginManager::CPlugin *pl;
198 SourceHook::List<CPluginEventHandler>::iterator event;
199 IMetamodListener *api;
203 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
206 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
208 api = (*event).event;
210 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
222 *_ret = IFACE_FAILED;
227 //////////////////////////////////////////////////////////////////////////
228 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
229 // (note: you can find the offset by looking for the text //
230 // "Echo text to console", you'll find the callback cmd pushed on the //
232 //////////////////////////////////////////////////////////////////////////
235 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
236 #define ENGINE486_OFFS 40
237 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
238 #define ENGINE686_OFFS 50
239 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
240 #define ENGINEAMD_OFFS 47
241 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
242 #define ENGINEW32_OFFS 38
243 #define IA32_CALL 0xE8
245 //Thanks to fysh for the idea of extracting info from "echo" and for
246 // having the original offsets at hand!
247 bool CSmmAPI::CacheCmds()
249 ICvar *pCvar = g_Engine.icvar;
251 ConCommandBase *pBase = pCvar->GetCommands();
252 unsigned char *ptr = NULL;
253 FnCommandCallback callback = NULL;
258 if ( strcmp(pBase->GetName(), "echo") == 0 )
260 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
261 callback = ((ConCommand *)pBase)->GetCallback();
262 ptr = (unsigned char *)callback;
264 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
266 offs = ENGINE486_OFFS;
268 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
270 offs = ENGINE686_OFFS;
272 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
274 offs = ENGINEAMD_OFFS;
276 #elif defined OS_WIN32 // Only one Windows engine binary so far...
277 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
279 offs = ENGINEW32_OFFS;
283 if (!offs || ptr[offs - 1] != IA32_CALL)
285 m_ConPrintf = (CONPRINTF_FUNC)Msg;
288 //get the relative offset
289 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
290 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
291 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
297 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
300 m_ConPrintf = (CONPRINTF_FUNC)Msg;
305 bool CSmmAPI::CmdCacheSuccessful()
310 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
312 major = SM_VERS_API_MAJOR;
313 minor = SM_VERS_API_MINOR;
314 plvers = PLAPI_VERSION;
315 plmin = PLAPI_MIN_VERSION;
318 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
320 shvers = SH_IFACE_VERSION;
321 shimpl = SH_IMPL_VERSION;
324 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
326 int length = (int)strlen(iface);
330 for (i = length - 1; i >= 0; i--)
332 if (!isdigit(iface[i]))
342 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
348 num = atoi(&(iface[++i]));
352 snprintf(&(iface[i]), 4, "%03d", num);
357 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
359 char _if[256]; /* assume no interface goes beyond this */
360 size_t len = strlen(iface);
367 if (len + 4 > sizeof(_if))
380 if ( (pf = (fn)(_if, ret)) != NULL )
384 } while (( num = FormatIface(_if, len+1) ));
389 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
391 char buffer[256]; /* assume no interface will go beyond this */
392 size_t len = strlen(iface);
393 int ret; /* just in case something doesn't handle NULL properly */
395 if (len > sizeof(buffer) - 4)
400 strcpy(buffer, iface);
404 char *ptr = &buffer[len - 1];
406 while (isdigit(*ptr) && digits <=3)
414 /* for now, assume this is an error */
415 strcpy(buffer, iface);
418 min = (min == 0) ? 1 : min;
419 snprintf(num, sizeof(num), "%03d", min);
424 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
427 const char *CSmmAPI::GetBaseDir()
429 return g_ModPath.c_str();
432 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
436 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
439 for (size_t i = 0; i < mylen; i++)
441 if (buffer[i] == ALT_SEP_CHAR)
443 buffer[i] = PATH_SEP_CHAR;
448 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
451 static char buffer[4096];
454 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
457 g_Engine.engine->ClientPrintf(client, buffer);
460 void CSmmAPI::LoadAsVSP()
463 char engine_file[PATH_SIZE];
464 char rel_path[PATH_SIZE * 2];
466 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
468 /* Chop off the "engine" file part */
469 len = strlen(engine_file);
470 for (size_t i = len - 1; i >= 0 && i < len; i--)
472 if (engine_file[i] == '/'
473 || engine_file[i] == '\\')
475 engine_file[i] = '\0';
480 const char *usepath = g_MetamodPath.c_str();
481 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, g_MetamodPath.c_str()))
486 char command[PATH_SIZE * 2];
487 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
488 g_Engine.engine->ServerCommand(command);
491 void CSmmAPI::EnableVSPListener()
493 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
494 if (g_bGameInit && !m_VSP && !g_bIsBridgedAsVsp)
501 int CSmmAPI::GetGameDLLVersion()
503 return g_GameDllVersion;
506 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
507 void Detour_Error(const tchar *pMsg, ...)
509 /* Jump back to setjmp() in CacheUserMessages() */
510 longjmp(usermsg_end, 1);
513 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
514 * early Orange Box. This is because Error() from tier0 gets called when a bad index is
515 * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
517 * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
518 * to a point before GetUserMessageInfo() is called. The detour is then removed and we
521 void CSmmAPI::CacheUserMessages()
525 unsigned char *target, *detour;
526 unsigned char orig_bytes[5];
528 target = (unsigned char *)&Error;
529 detour = (unsigned char *)&Detour_Error;
531 /* Save bytes from target function */
532 memcpy(orig_bytes, target, sizeof(orig_bytes));
534 /* Patch in relative jump to our Error() detour */
535 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
536 target[0] = IA32_JMP_IMM32;
537 *(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
539 /* This is where longjmp() will end up */
540 if (setjmp(usermsg_end))
542 /* Restore bytes and memory protection */
543 memcpy(target, orig_bytes, sizeof(orig_bytes));
544 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
550 /* If GetUserMessageInfo() calls Error(), we should end up in our detour */
551 while (g_GameDll.pGameDLL->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
553 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
557 /* Jump back to setjmp() */
558 longjmp(usermsg_end, 1);
561 int CSmmAPI::GetUserMessageCount()
563 return (int)usermsgs_list.size();
566 int CSmmAPI::FindUserMessage(const char *name, int *size)
568 for (size_t i = 0; i < usermsgs_list.size(); i++)
570 if (usermsgs_list[i].name.compare(name) == 0)
574 *size = usermsgs_list[i].size;
583 const char *CSmmAPI::GetUserMessage(int index, int *size)
585 if (index < 0 || index >= (int)usermsgs_list.size())
592 *size = usermsgs_list[index].size;
595 return usermsgs_list[index].name.c_str();
598 IServerPluginCallbacks *CSmmAPI::GetVSPInfo(int *pVersion)
600 if (pVersion != NULL)
601 *pVersion = g_vsp_version;
603 return g_pRealVspCallbacks;
606 int CSmmAPI::GetSourceEngineBuild()
608 return g_Engine.original ? SOURCE_ENGINE_ORIGINAL : SOURCE_ENGINE_EPISODEONE;