Trigger build for hl2sdk-l4d changes.
1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2010 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"
24 * @brief Implementation of main API interface
28 using namespace SourceMM;
29 using namespace SourceHook;
36 UsrMsgInfo(int s, const char *t) : size(s), name(t)
45 static CVector<UsrMsgInfo> usermsgs_list;
46 static jmp_buf usermsg_end;
55 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
58 static char buffer[2048];
61 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
64 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
67 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
71 return g_Engine.engineFactory;
74 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
77 return PhysicsFactory;
78 return g_Engine.physicsFactory;
81 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
84 return FileSystemFactory;
85 return g_Engine.fileSystemFactory;
88 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
92 return g_GameDll.factory;
95 CGlobalVars *CSmmAPI::pGlobals()
97 return g_Engine.pGlobals;
100 void CSmmAPI::SetLastMetaReturn(META_RES res)
105 META_RES CSmmAPI::GetLastMetaReturn()
110 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
112 return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
115 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
117 if (pCommand->IsCommand())
119 g_PluginMngr.AddPluginCmd(plugin, pCommand);
121 g_PluginMngr.AddPluginCvar(plugin, pCommand);
124 return g_SMConVarAccessor.Register(pCommand);
127 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
129 if (pCommand->IsCommand())
131 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
133 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
136 CPluginManager::CPlugin *pPlugin = g_PluginMngr.FindByAPI(plugin);
137 PluginId id = (pPlugin != NULL) ? pPlugin->m_Id : Pl_BadLoad;
139 NotifyConCommandBaseDrop(id, pCommand);
141 g_SMConVarAccessor.Unregister(pCommand);
144 void CSmmAPI::ConPrint(const char *fmt)
146 (m_ConPrintf)("%s", fmt);
149 void CSmmAPI::ConPrintf(const char *fmt, ...)
152 static char buffer[4096];
155 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
158 (m_ConPrintf)("%s", buffer);
161 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
163 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
164 CPluginEventHandler cpeh;
166 cpeh.event = pListener;
167 cpeh.got_vsp = false;
169 pl->m_Events.push_back(cpeh);
172 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
184 //first check ours... we get first chance!
185 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
191 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
192 } else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
197 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
200 CPluginManager::CPlugin *pl;
201 SourceHook::List<CPluginEventHandler>::iterator event;
202 IMetamodListener *api;
206 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
209 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
211 api = (*event).event;
213 if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
225 *_ret = IFACE_FAILED;
230 //////////////////////////////////////////////////////////////////////////
231 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
232 // (note: you can find the offset by looking for the text //
233 // "Echo text to console", you'll find the callback cmd pushed on the //
235 //////////////////////////////////////////////////////////////////////////
238 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
239 #define ENGINE486_OFFS 40
240 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
241 #define ENGINE686_OFFS 50
242 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
243 #define ENGINEAMD_OFFS 47
244 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
245 #define ENGINEW32_OFFS 38
246 #define IA32_CALL 0xE8
248 //Thanks to fysh for the idea of extracting info from "echo" and for
249 // having the original offsets at hand!
250 bool CSmmAPI::CacheCmds()
252 ICvar *pCvar = g_Engine.icvar;
254 ConCommandBase *pBase = pCvar->GetCommands();
255 unsigned char *ptr = NULL;
256 FnCommandCallback callback = NULL;
261 if ( strcmp(pBase->GetName(), "echo") == 0 )
263 //callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
264 callback = ((ConCommand *)pBase)->GetCallback();
265 ptr = (unsigned char *)callback;
267 if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
269 offs = ENGINE486_OFFS;
271 else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
273 offs = ENGINE686_OFFS;
275 else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
277 offs = ENGINEAMD_OFFS;
279 #elif defined OS_WIN32 // Only one Windows engine binary so far...
280 if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
282 offs = ENGINEW32_OFFS;
286 if (!offs || ptr[offs - 1] != IA32_CALL)
288 m_ConPrintf = (CONPRINTF_FUNC)Msg;
291 //get the relative offset
292 m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
293 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
294 m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
300 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
303 m_ConPrintf = (CONPRINTF_FUNC)Msg;
308 bool CSmmAPI::CmdCacheSuccessful()
313 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
315 major = SM_VERS_API_MAJOR;
316 minor = SM_VERS_API_MINOR;
317 plvers = PLAPI_VERSION;
318 plmin = PLAPI_MIN_VERSION;
321 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
323 shvers = SH_IFACE_VERSION;
324 shimpl = SH_IMPL_VERSION;
327 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
329 int length = (int)strlen(iface);
333 for (i = length - 1; i >= 0; i--)
335 if (!isdigit(iface[i]))
345 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
351 num = atoi(&(iface[++i]));
355 snprintf(&(iface[i]), 4, "%03d", num);
360 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
362 char _if[256]; /* assume no interface goes beyond this */
363 size_t len = strlen(iface);
370 if (len + 4 > sizeof(_if))
383 if ( (pf = (fn)(_if, ret)) != NULL )
387 } while (( num = FormatIface(_if, len+1) ));
392 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
394 char buffer[256]; /* assume no interface will go beyond this */
395 size_t len = strlen(iface);
396 int ret; /* just in case something doesn't handle NULL properly */
398 if (len > sizeof(buffer) - 4)
403 strcpy(buffer, iface);
407 char *ptr = &buffer[len - 1];
409 while (isdigit(*ptr) && digits <=3)
417 /* for now, assume this is an error */
418 strcpy(buffer, iface);
421 min = (min == 0) ? 1 : min;
422 snprintf(num, sizeof(num), "%03d", min);
427 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
430 const char *CSmmAPI::GetBaseDir()
432 return g_ModPath.c_str();
435 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
439 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
442 for (size_t i = 0; i < mylen; i++)
444 if (buffer[i] == ALT_SEP_CHAR)
446 buffer[i] = PATH_SEP_CHAR;
451 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
454 static char buffer[4096];
457 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
460 g_Engine.engine->ClientPrintf(client, buffer);
463 void CSmmAPI::LoadAsVSP()
466 char engine_file[PATH_SIZE];
467 char rel_path[PATH_SIZE * 2];
469 GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
471 /* Chop off the "engine" file part */
472 len = strlen(engine_file);
473 for (size_t i = len - 1; i < len; i--)
475 if (engine_file[i] == '/'
476 || engine_file[i] == '\\')
478 engine_file[i] = '\0';
483 const char *usepath = g_MetamodPath.c_str();
484 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, g_MetamodPath.c_str()))
489 char command[PATH_SIZE * 2];
490 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
491 g_Engine.engine->ServerCommand(command);
494 void CSmmAPI::EnableVSPListener()
496 /* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
497 if (g_bGameInit && !m_VSP && !g_bIsBridgedAsVsp)
504 int CSmmAPI::GetGameDLLVersion()
506 return g_GameDllVersion;
509 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
510 void Detour_Error(const tchar *pMsg, ...)
512 /* Jump back to setjmp() in CacheUserMessages() */
513 longjmp(usermsg_end, 1);
516 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
517 * early Orange Box. This is because Error() from tier0 gets called when a bad index is
518 * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
520 * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
521 * to a point before GetUserMessageInfo() is called. The detour is then removed and we
524 void CSmmAPI::CacheUserMessages()
528 unsigned char *target, *detour;
529 unsigned char orig_bytes[5];
531 target = (unsigned char *)&Error;
532 detour = (unsigned char *)&Detour_Error;
534 /* Save bytes from target function */
535 memcpy(orig_bytes, target, sizeof(orig_bytes));
537 /* Patch in relative jump to our Error() detour */
538 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
539 target[0] = IA32_JMP_IMM32;
540 *(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
542 /* This is where longjmp() will end up */
543 if (setjmp(usermsg_end))
545 /* Restore bytes and memory protection */
546 memcpy(target, orig_bytes, sizeof(orig_bytes));
547 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
553 /* If GetUserMessageInfo() calls Error(), we should end up in our detour */
554 while (g_GameDll.pGameDLL->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
556 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
560 /* Jump back to setjmp() */
561 longjmp(usermsg_end, 1);
564 int CSmmAPI::GetUserMessageCount()
566 return (int)usermsgs_list.size();
569 int CSmmAPI::FindUserMessage(const char *name, int *size)
571 for (size_t i = 0; i < usermsgs_list.size(); i++)
573 if (usermsgs_list[i].name.compare(name) == 0)
577 *size = usermsgs_list[i].size;
586 const char *CSmmAPI::GetUserMessage(int index, int *size)
588 if (index < 0 || index >= (int)usermsgs_list.size())
595 *size = usermsgs_list[index].size;
598 return usermsgs_list[index].name.c_str();
601 IServerPluginCallbacks *CSmmAPI::GetVSPInfo(int *pVersion)
603 if (pVersion != NULL)
604 *pVersion = g_vsp_version;
606 return g_pRealVspCallbacks;
609 int CSmmAPI::GetSourceEngineBuild()
611 return g_Engine.original ? SOURCE_ENGINE_ORIGINAL : SOURCE_ENGINE_EPISODEONE;
614 void CSmmAPI::GetFullPluginPath(const char *plugin, char *buffer, size_t len)
616 const char *pext, *ext;
618 /* First find if it's an absolute path or not... */
619 if (plugin[0] == '/' || strncmp(&(plugin[1]), ":\\", 2) == 0)
621 UTIL_Format(buffer, len, plugin);
625 /* Attempt to find a file extension */
626 pext = UTIL_GetExtension(plugin);
627 /* Add an extension if there's none there */
630 #if defined WIN32 || defined _WIN32
641 /* Format the new path */
642 PathFormat(buffer, len, "%s/%s%s", g_ModPath.c_str(), plugin, ext);
644 #if defined __linux__
645 /* If path was passed without extension and it doesn't exist with "_i486.so" try ".so" */
647 if (!pext && stat(buffer, &s) != 0)
649 PathFormat(buffer, len, "%s/%s.so", g_ModPath.c_str(), plugin);