Fixed up bugs and linking errors - loads but crashes.
4 * ======================================================
6 * Copyright (C) 2004-2008 AlliedModders LLC and authors.
8 * ======================================================
10 * This software is provided 'as-is', without any express or implied warranty.
11 * In no event will the authors be held liable for any damages arising from
12 * the use of this software.
14 * Permission is granted to anyone to use this software for any purpose,
15 * including commercial applications, and to alter it and redistribute it
16 * freely, subject to the following restrictions:
18 * 1. The origin of this software must not be misrepresented; you must not
19 * claim that you wrote the original software. If you use this software in a
20 * product, an acknowledgment in the product documentation would be
21 * appreciated but is not required.
22 * 2. Altered source versions must be plainly marked as such, and must not be
23 * misrepresented as being the original software.
24 * 3. This notice may not be removed or altered from any source distribution.
30 #include "../metamod_oslink.h"
31 #include <sourcehook.h>
34 #include <tier0/icommandline.h>
35 #include <tier1/utldict.h>
36 #include <sh_vector.h>
37 #include <sh_string.h>
38 #include "../metamod_util.h"
39 #include "provider_ep2.h"
41 #include "metamod_console.h"
42 #include "vsp_listener.h"
43 #include <filesystem.h>
47 typedef void (*CONPRINTF_FUNC)(const char *, ...);
53 UsrMsgInfo(int s, const char *t) : size(s), name(t)
61 DLL_IMPORT ICommandLine *CommandLine();
63 bool CacheUserMessages();
64 void ClientCommand(edict_t *pEdict, const CCommand &args);
65 void LocalCommand_Meta(const CCommand &args);
66 void _ServerCommand();
68 static bool usermsgs_extracted = false;
69 static CVector<UsrMsgInfo> usermsgs_list;
70 static VSPListener g_VspListener;
71 static BaseProvider g_Ep1Provider;
72 static List<ConCommandBase *> conbases_unreg;
75 IFileSystem *baseFs = NULL;
76 IServerGameDLL *server = NULL;
77 IVEngineServer *engine = NULL;
78 IServerGameClients *gameclients = NULL;
79 IMetamodSourceProvider *provider = &g_Ep1Provider;
80 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
82 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
84 bool AssumeUserMessages()
91 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
93 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
100 void BaseProvider::ConsolePrint(const char *str)
105 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
106 CreateInterfaceFn serverFactory)
108 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
111 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
114 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
117 DisplayError("Could not find ICvar! Metamod cannot load.");
122 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
125 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
128 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
131 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
135 RegisterConCommandBase(&meta_local_cmd);
136 conbases_unreg.push_back(&meta_local_cmd);
138 if ((usermsgs_extracted = CacheUserMessages()) == false)
140 usermsgs_extracted = AssumeUserMessages();
145 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
149 void BaseProvider::Notify_DLLShutdown_Pre()
151 List<ConCommandBase *>::iterator iter;
153 for (iter = conbases_unreg.begin();
154 iter != conbases_unreg.end();
157 UnregisterConCommandBase((*iter));
161 bool BaseProvider::IsRemotePrintingAvailable()
166 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
168 engine->ClientPrintf(client, message);
171 void BaseProvider::ServerCommand(const char *cmd)
173 engine->ServerCommand(cmd);
176 const char *BaseProvider::GetConVarString(ConVar *convar)
183 return convar->GetString();
186 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
188 convar->SetValue(str);
191 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
193 return pCommand->IsCommand();
197 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
199 return (build == SOURCE_ENGINE_ORIGINAL
200 || build == SOURCE_ENGINE_EPISODEONE);
203 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
205 if (key[0] == '-' || key[0] == '+')
207 return CommandLine_Tier0()->ParmValue(key, defval);
212 if ((val = icvar->GetCommandLineValue(key)) == NULL)
223 int BaseProvider::TryServerGameDLL(const char *iface)
225 if (strncmp(iface, "ServerGameDLL", 13) != 0)
230 return atoi(&iface[13]);
233 bool BaseProvider::LogMessage(const char *buffer)
240 engine->LogPrint(buffer);
245 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
247 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
249 if (hook == ProvidedHook_LevelInit)
251 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
253 else if (hook == ProvidedHook_LevelShutdown)
255 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
257 else if (hook == ProvidedHook_GameInit)
259 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
261 else if (hook == ProvidedHook_DLLShutdown)
263 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
265 else if (hook == ProvidedHook_DLLInit)
267 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
272 return (mfi.thisptroffs >= 0);
275 void BaseProvider::DisplayError(const char *fmt, ...)
281 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
287 void BaseProvider::DisplayWarning(const char *fmt, ...)
293 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
299 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
301 return &g_SMConVarAccessor;
304 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
306 return g_SMConVarAccessor.Register(pCommand);
309 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
311 return g_SMConVarAccessor.Unregister(pCommand);
314 int BaseProvider::GetUserMessageCount()
316 if (!usermsgs_extracted)
321 return (int)usermsgs_list.size();
324 int BaseProvider::FindUserMessage(const char *name, int *size)
326 for (size_t i = 0; i < usermsgs_list.size(); i++)
328 if (usermsgs_list[i].name.compare(name) == 0)
332 *size = usermsgs_list[i].size;
341 const char *BaseProvider::GetUserMessage(int index, int *size)
343 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
350 *size = usermsgs_list[index].size;
353 return usermsgs_list[index].name.c_str();
356 const char *BaseProvider::GetGameDescription()
358 return server->GetGameDescription();
361 int BaseProvider::DetermineSourceEngine(const char *game)
363 return SOURCE_ENGINE_ORANGEBOX;
366 ConVar *BaseProvider::CreateConVar(const char *name,
372 if (flags & ConVarFlag_Notify)
374 newflags |= FCVAR_NOTIFY;
376 if (flags & ConVarFlag_SpOnly)
378 newflags |= FCVAR_SPONLY;
381 ConVar *pVar = new ConVar(name, defval, newflags, help);
383 RegisterConCommandBase(pVar);
384 conbases_unreg.push_back(pVar);
389 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
396 g_VspListener.SetLoadable(true);
397 return &g_VspListener;
400 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
408 const char *plugin_file, *p_alias;
410 pValues = new KeyValues("Metamod Plugin");
412 if (!pValues->LoadFromFile(baseFs, file))
414 pValues->deleteThis();
418 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
420 pValues->deleteThis();
424 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
426 UTIL_Format(alias, alias_len, "%s", p_alias);
430 UTIL_Format(alias, alias_len, "");
433 /* Attempt to find a file extension */
434 if (UTIL_GetExtension(plugin_file) == NULL)
436 g_pMetamod->PathFormat(path,
439 g_pMetamod->GetBaseDir(),
441 #if defined WIN32 || defined _WIN32
450 g_pMetamod->PathFormat(path,
453 g_pMetamod->GetBaseDir(),
457 pValues->deleteThis();
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 void LocalCommand_Meta(const CCommand &args)
489 GlobCommand cmd(&args);
493 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
495 GlobCommand cmd(&_cmd);
497 if (strcmp(cmd.GetArg(0), "meta") == 0)
499 Command_ClientMeta(pEdict, &cmd);
500 RETURN_META(MRES_SUPERCEDE);
503 RETURN_META(MRES_IGNORED);
506 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
508 unsigned char *addr1 = (unsigned char *)_addr1;
509 unsigned char *addr2 = (unsigned char *)_addr2;
511 for (size_t i=0; i<len; i++)
517 if (addr1[i] != addr2[i])
526 //////////////////////////////////////////////////////////////////////
527 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
528 // Signatures necessary in finding the pointer to the CUtlDict that //
529 // stores user message information. //
530 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
531 // message indices. This is our answer to it. Yuck! <:-( //
532 //////////////////////////////////////////////////////////////////////
534 /* General Windows sig */
535 #define MSGCLASS_SIGLEN 7
536 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
537 #define MSGCLASS_OFFS 2
539 /* Dystopia Wimdows hack */
540 #define MSGCLASS2_SIGLEN 16
541 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
542 #define MSGCLASS2_OFFS 11
544 /* Windows frame pointer sig */
545 #define MSGCLASS3_SIGLEN 18
546 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
547 #define MSGCLASS3_OFFS 13
548 #elif defined OS_LINUX
549 /* No frame pointer sig */
550 #define MSGCLASS_SIGLEN 14
551 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
552 #define MSGCLASS_OFFS 9
554 /* Frame pointer sig */
555 #define MSGCLASS2_SIGLEN 16
556 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
557 #define MSGCLASS2_OFFS 11
566 typedef CUtlDict<UserMessage *, int> UserMsgDict;
568 /* This is the ugliest function in all of SourceMM */
569 bool CacheUserMessages()
571 /* Get address of original GetUserMessageInfo() */
572 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
574 /* Oh dear, we have a relative jump on our hands
575 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
577 if (*vfunc == '\xE9')
579 /* Get address from displacement...
581 * Add 5 because it's relative to next instruction:
582 * Opcode <1 byte> + 32-bit displacement <4 bytes>
584 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
587 CUtlDict<UserMessage *, int> *dict = NULL;
589 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
591 /* Get address of CUserMessages instance */
592 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
594 /* Get address of CUserMessages::m_UserMessages */
595 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
597 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
600 /* If we get here, the code is possibly inlined like in Dystopia */
602 /* Get the address of the CUtlRBTree */
603 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
605 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
606 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
607 #elif defined OS_LINUX
608 /* Get address of CUserMessages instance */
609 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
611 /* Get address of CUserMessages::m_UserMessages */
612 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
616 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
618 /* Get address of CUserMessages instance */
619 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
621 /* Get address of CUserMessages::m_UserMessages */
622 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
626 #if !defined OS_WIN32
630 if (GetFileOfAddress(vfunc, path, sizeof(path)))
632 void *handle = dlopen(path, RTLD_NOW);
635 void *addr = dlsym(handle, "usermessages");
640 dict = (UserMsgDict *)*(void **)addr;
649 int msg_count = dict->Count();
651 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
652 if (msg_count < 0 || msg_count > 255)
660 /* Cache messages in our CUtlDict */
661 for (int i = 0; i < msg_count; i++)
663 msg = dict->Element(i);
664 u_msg.name = msg->name;
665 u_msg.size = msg->size;
666 usermsgs_list.push_back(u_msg);