2 * vim: set ts=4 sw=4 tw=99 noet :
3 * ======================================================
5 * Copyright (C) 2004-2009 AlliedModders LLC and authors.
7 * ======================================================
9 * This software is provided 'as-is', without any express or implied warranty.
10 * In no event will the authors be held liable for any damages arising from
11 * the use of this software.
13 * Permission is granted to anyone to use this software for any purpose,
14 * including commercial applications, and to alter it and redistribute it
15 * freely, subject to the following restrictions:
17 * 1. The origin of this software must not be misrepresented; you must not
18 * claim that you wrote the original software. If you use this software in a
19 * product, an acknowledgment in the product documentation would be
20 * appreciated but is not required.
21 * 2. Altered source versions must be plainly marked as such, and must not be
22 * misrepresented as being the original software.
23 * 3. This notice may not be removed or altered from any source distribution.
27 #include "../metamod_oslink.h"
28 #include <sourcehook.h>
31 #include <tier0/icommandline.h>
32 #include <tier1/utldict.h>
33 #include <sh_vector.h>
34 #include <sh_string.h>
35 #include "../metamod_util.h"
36 #include "provider_ep2.h"
38 #include "metamod_console.h"
39 #include <filesystem.h>
43 typedef void (*CONPRINTF_FUNC)(const char *, ...);
49 UsrMsgInfo(int s, const char *t) : size(s), name(t)
57 #if SOURCE_ENGINE == SE_DARKMESSIAH
59 DLL_IMPORT ICommandLine *CommandLine();
63 bool CacheUserMessages();
64 #if SOURCE_ENGINE >= SE_ORANGEBOX
65 void ClientCommand(edict_t *pEdict, const CCommand &args);
66 void LocalCommand_Meta(const CCommand &args);
68 void ClientCommand(edict_t *pEdict);
69 void LocalCommand_Meta();
72 void _ServerCommand();
74 static bool usermsgs_extracted = false;
75 static CVector<UsrMsgInfo> usermsgs_list;
76 static BaseProvider g_Ep1Provider;
77 static List<ConCommandBase *> conbases_unreg;
80 IFileSystem *baseFs = NULL;
81 IServerGameDLL *server = NULL;
82 IVEngineServer *engine = NULL;
83 IServerGameClients *gameclients = NULL;
84 IMetamodSourceProvider *provider = &g_Ep1Provider;
85 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
87 #if SOURCE_ENGINE >= SE_ORANGEBOX
88 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
90 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
93 bool AssumeUserMessages()
100 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
102 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
109 void BaseProvider::ConsolePrint(const char *str)
111 #if SOURCE_ENGINE >= SE_ORANGEBOX
118 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
119 CreateInterfaceFn serverFactory)
121 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
124 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
127 #if SOURCE_ENGINE >= SE_ORANGEBOX
128 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
130 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
134 DisplayError("Could not find ICvar! Metamod cannot load.");
139 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
142 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
145 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
148 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
152 #if SOURCE_ENGINE >= SE_ORANGEBOX
156 g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
158 if ((usermsgs_extracted = CacheUserMessages()) == false)
160 usermsgs_extracted = AssumeUserMessages();
163 #if SOURCE_ENGINE == SE_DARKMESSIAH
164 if (!g_SMConVarAccessor.InitConCommandBaseList())
166 /* This is very unlikely considering it's old engine */
167 mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
168 mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
174 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
178 void BaseProvider::Notify_DLLShutdown_Pre()
180 g_SMConVarAccessor.RemoveMetamodCommands();
182 #if SOURCE_ENGINE == SE_DARKMESSIAH
183 if (g_Metamod.IsLoadedAsGameDLL())
185 icvar->UnlinkVariables(FCVAR_GAMEDLL);
190 bool BaseProvider::IsRemotePrintingAvailable()
195 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
197 engine->ClientPrintf(client, message);
200 void BaseProvider::ServerCommand(const char *cmd)
202 engine->ServerCommand(cmd);
205 const char *BaseProvider::GetConVarString(ConVar *convar)
212 return convar->GetString();
215 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
217 convar->SetValue(str);
220 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
222 return pCommand->IsCommand();
226 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
228 return (build == SOURCE_ENGINE_ORIGINAL
229 || build == SOURCE_ENGINE_EPISODEONE);
232 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
234 if (key[0] == '-' || key[0] == '+')
236 return CommandLine()->ParmValue(key, defval);
241 if ((val = icvar->GetCommandLineValue(key)) == NULL)
252 int BaseProvider::TryServerGameDLL(const char *iface)
254 if (strncmp(iface, "ServerGameDLL", 13) != 0)
259 return atoi(&iface[13]);
262 bool BaseProvider::LogMessage(const char *buffer)
269 engine->LogPrint(buffer);
274 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
276 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
278 if (hook == ProvidedHook_LevelInit)
280 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
282 else if (hook == ProvidedHook_LevelShutdown)
284 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
286 else if (hook == ProvidedHook_GameInit)
288 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
293 return (mfi.thisptroffs >= 0);
296 void BaseProvider::DisplayError(const char *fmt, ...)
302 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
308 void BaseProvider::DisplayWarning(const char *fmt, ...)
314 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
320 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
322 return &g_SMConVarAccessor;
325 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
327 return g_SMConVarAccessor.Register(pCommand);
330 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
332 return g_SMConVarAccessor.Unregister(pCommand);
335 int BaseProvider::GetUserMessageCount()
337 if (!usermsgs_extracted)
342 return (int)usermsgs_list.size();
345 int BaseProvider::FindUserMessage(const char *name, int *size)
347 for (size_t i = 0; i < usermsgs_list.size(); i++)
349 if (usermsgs_list[i].name.compare(name) == 0)
353 *size = usermsgs_list[i].size;
362 const char *BaseProvider::GetUserMessage(int index, int *size)
364 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
371 *size = usermsgs_list[index].size;
374 return usermsgs_list[index].name.c_str();
377 const char *BaseProvider::GetGameDescription()
379 return server->GetGameDescription();
382 int BaseProvider::DetermineSourceEngine(const char *game)
384 #if SOURCE_ENGINE == SE_LEFT4DEAD2
385 return SOURCE_ENGINE_LEFT4DEAD2;
386 #elif SOURCE_ENGINE == SE_LEFT4DEAD
387 return SOURCE_ENGINE_LEFT4DEAD;
388 #elif SOURCE_ENGINE == SE_ORANGEBOX
389 return SOURCE_ENGINE_ORANGEBOX;
390 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
391 return SOURCE_ENGINE_ORANGEBOXVALVE;
392 #elif SOURCE_ENGINE == SE_DARKMESSIAH
393 return SOURCE_ENGINE_DARKMESSIAH;
395 #error "SOURCE_ENGINE not defined to a known value"
399 ConVar *BaseProvider::CreateConVar(const char *name,
405 if (flags & ConVarFlag_Notify)
407 newflags |= FCVAR_NOTIFY;
409 if (flags & ConVarFlag_SpOnly)
411 newflags |= FCVAR_SPONLY;
414 ConVar *pVar = new ConVar(name, defval, newflags, help);
416 g_SMConVarAccessor.RegisterConCommandBase(pVar);
421 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
429 const char *plugin_file, *p_alias;
431 pValues = new KeyValues("Metamod Plugin");
433 if (!pValues->LoadFromFile(baseFs, file))
435 pValues->deleteThis();
439 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
441 pValues->deleteThis();
445 UTIL_Format(path, path_len, "%s", plugin_file);
447 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
449 UTIL_Format(alias, alias_len, "%s", p_alias);
453 UTIL_Format(alias, alias_len, "");
456 pValues->deleteThis();
461 #if SOURCE_ENGINE >= SE_ORANGEBOX
462 class GlobCommand : public IMetamodSourceCommandInfo
465 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
469 unsigned int GetArgCount()
471 return m_cmd->ArgC() - 1;
474 const char *GetArg(unsigned int num)
476 return m_cmd->Arg(num);
479 const char *GetArgString()
481 return m_cmd->ArgS();
484 const CCommand *m_cmd;
487 class GlobCommand : public IMetamodSourceCommandInfo
490 unsigned int GetArgCount()
492 return engine->Cmd_Argc() - 1;
495 const char *GetArg(unsigned int num)
497 return engine->Cmd_Argv(num);
500 const char *GetArgString()
502 return engine->Cmd_Args();
507 #if SOURCE_ENGINE >= SE_ORANGEBOX
508 void LocalCommand_Meta(const CCommand &args)
510 GlobCommand cmd(&args);
512 void LocalCommand_Meta()
519 #if SOURCE_ENGINE >= SE_ORANGEBOX
520 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
522 GlobCommand cmd(&_cmd);
524 void ClientCommand(edict_t *pEdict)
528 if (strcmp(cmd.GetArg(0), "meta") == 0)
530 Command_ClientMeta(pEdict, &cmd);
531 RETURN_META(MRES_SUPERCEDE);
534 RETURN_META(MRES_IGNORED);
537 //////////////////////////////////////////////////////////////////////
538 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
539 // Signatures necessary in finding the pointer to the CUtlDict that //
540 // stores user message information. //
541 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
542 // message indices. This is our answer to it. Yuck! <:-( //
543 //////////////////////////////////////////////////////////////////////
545 /* General Windows sig */
546 #define MSGCLASS_SIGLEN 7
547 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
548 #define MSGCLASS_OFFS 2
550 /* Dystopia Windows hack */
551 #define MSGCLASS2_SIGLEN 16
552 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
553 #define MSGCLASS2_OFFS 11
555 /* Windows frame pointer sig */
556 #define MSGCLASS3_SIGLEN 18
557 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
558 #define MSGCLASS3_OFFS 13
559 #elif defined OS_LINUX
560 /* No frame pointer sig */
561 #define MSGCLASS_SIGLEN 14
562 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
563 #define MSGCLASS_OFFS 9
565 /* Frame pointer sig */
566 #define MSGCLASS2_SIGLEN 16
567 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
568 #define MSGCLASS2_OFFS 11
577 typedef CUtlDict<UserMessage *, int> UserMsgDict;
579 /* This is the ugliest function in all of MM:S */
580 bool CacheUserMessages()
582 UserMsgDict *dict = NULL;
584 /* Get address of original GetUserMessageInfo() */
585 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
587 /* Oh dear, we have a relative jump on our hands
588 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
590 if (*vfunc == '\xE9')
592 /* Get address from displacement...
594 * Add 5 because it's relative to next instruction:
595 * Opcode <1 byte> + 32-bit displacement <4 bytes>
597 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
600 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
602 /* Get address of CUserMessages instance */
603 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
605 /* Get address of CUserMessages::m_UserMessages */
606 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
608 else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
611 /* If we get here, the code is possibly inlined like in Dystopia */
613 /* Get the address of the CUtlRBTree */
614 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
616 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
617 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
618 #elif defined OS_LINUX
619 /* Get address of CUserMessages instance */
620 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
622 /* Get address of CUserMessages::m_UserMessages */
623 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
627 else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
629 /* Get address of CUserMessages instance */
630 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
632 /* Get address of CUserMessages::m_UserMessages */
633 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
637 #if !defined OS_WIN32
641 if (GetFileOfAddress(vfunc, path, sizeof(path)))
643 void *handle = dlopen(path, RTLD_NOW);
646 void *addr = dlsym(handle, "usermessages");
652 dict = (UserMsgDict *)*(void **)addr;
661 int msg_count = dict->Count();
663 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
664 if (msg_count < 0 || msg_count > 255)
672 /* Cache messages in our CUtlDict */
673 for (int i = 0; i < msg_count; i++)
675 msg = dict->Element(i);
676 u_msg.name = msg->name;
677 u_msg.size = msg->size;
678 usermsgs_list.push_back(u_msg);