sourcemm/episode2/provider_ep2.cpp
author Pavol Marko <pavolmarko@gmail.com>
Fri Jan 18 16:56:03 2008 +0000 (2008-01-18)
changeset 490 0a54fa7a5167
parent 485 d8f0a0416936
child 495 e091f2b5e913
permissions -rw-r--r--
Fixed small new[] / delete mismatch in HookManGen (CGenContext::BuildProtoInfo)
     1 
     2 /**
     3  * vim: set ts=4 :
     4  * ======================================================
     5  * Metamod:Source
     6  * Copyright (C) 2004-2007 AlliedModders LLC and authors.
     7  * All rights reserved.
     8  * ======================================================
     9  *
    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.
    13  * 
    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:
    17  *
    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.
    25  *
    26  * Version: $Id$
    27  */
    28 
    29 #if defined _DEBUG
    30 #define DEBUG2
    31 #undef _DEBUG
    32 #endif
    33 #include "../metamod_oslink.h"
    34 #include <sourcehook.h>
    35 #include <convar.h>
    36 #include <eiface.h>
    37 #include <tier0/icommandline.h>
    38 #include <tier1/utldict.h>
    39 #include <sh_vector.h>
    40 #include <sh_string.h>
    41 #include "../metamod_util.h"
    42 #include "provider_ep2.h"
    43 #include "console.h"
    44 #include "metamod_console.h"
    45 #include "vsp_listener.h"
    46 #include <filesystem.h>
    47 #if defined DEBUG2
    48 #undef DEBUG2
    49 #define _DEBUG
    50 #endif
    51 
    52 /* Types */
    53 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    54 struct UsrMsgInfo
    55 {
    56 	int size;
    57 	String name;
    58 };
    59 /* Imports */
    60 #undef CommandLine
    61 DLL_IMPORT ICommandLine *CommandLine();
    62 /* Functions */
    63 bool CacheUserMessages();
    64 void ClientCommand(edict_t *pEdict, const CCommand &args);
    65 void LocalCommand_Meta(const CCommand &args);
    66 void _ServerCommand();
    67 /* Variables */
    68 bool usermsgs_extracted = false;
    69 CVector<UsrMsgInfo> usermsgs_list;
    70 ICvar *icvar = NULL;
    71 ISmmAPI *metamod_api = NULL;
    72 IVEngineServer *engine = NULL;
    73 IServerGameClients *gameclients = NULL;
    74 VSPListener g_VspListener;
    75 BaseProvider g_Ep1Provider;
    76 IMetamodSourceProvider *provider = &g_Ep1Provider;
    77 List<ConCommandBase *> conbases_unreg;
    78 IFileSystem *baseFs = NULL;
    79 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    80 
    81 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    82 
    83 void BaseProvider::ConsolePrint(const char *str)
    84 {
    85 	ConMsg("%s", str);
    86 }
    87 
    88 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory, 
    89 									  CreateInterfaceFn serverFactory)
    90 {
    91 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
    92 	if (!engine)
    93 	{
    94 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
    95 		return;
    96 	}
    97 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
    98 	if (!icvar)
    99 	{
   100 		DisplayError("Could not find ICvar! Metamod cannot load.");
   101 		return;
   102 	}
   103 	g_pCVar = icvar;
   104 
   105 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
   106 		== NULL)
   107 	{
   108 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   109 	}
   110 
   111 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   112 	if (baseFs == NULL)
   113 	{
   114 		::LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
   115 		return;
   116 	}
   117 
   118 	RegisterConCommandBase(&meta_local_cmd);
   119 	conbases_unreg.push_back(&meta_local_cmd);
   120 
   121 	usermsgs_extracted = CacheUserMessages();
   122 
   123 	if (gameclients)
   124 	{
   125 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   126 	}
   127 }
   128 
   129 void BaseProvider::Notify_DLLShutdown_Pre()
   130 {
   131 	List<ConCommandBase *>::iterator iter;
   132 
   133 	for (iter = conbases_unreg.begin();
   134 		 iter != conbases_unreg.end();
   135 		 iter++)
   136 	{
   137 		UnregisterConCommandBase((*iter));
   138 	}
   139 }
   140 
   141 bool BaseProvider::IsRemotePrintingAvailable()
   142 {
   143 	return true;
   144 }
   145 
   146 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   147 {
   148 	engine->ClientPrintf(client, message);
   149 }
   150 
   151 void BaseProvider::ServerCommand(const char *cmd)
   152 {
   153 	engine->ServerCommand(cmd);
   154 }
   155 
   156 const char *BaseProvider::GetConVarString(ConVar *convar)
   157 {
   158 	if (convar == NULL)
   159 	{
   160 		return NULL;
   161 	}
   162 
   163 	return convar->GetString();
   164 }
   165 
   166 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   167 {
   168 	convar->SetValue(str);
   169 }
   170 
   171 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   172 {
   173 	return pCommand->IsCommand();
   174 }
   175 
   176 
   177 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   178 {
   179 	return (build == SOURCE_ENGINE_ORIGINAL
   180 			|| build == SOURCE_ENGINE_EPISODEONE);
   181 }
   182 
   183 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   184 {
   185 	if (key[0] == '-' || key[0] == '+')
   186 	{
   187 		return CommandLine_Tier0()->ParmValue(key, defval);
   188 	}
   189 	else if (icvar)
   190 	{
   191 		const char *val;
   192 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   193 		{
   194 			return defval;
   195 		}
   196 
   197 		return val;
   198 	}
   199 
   200 	return NULL;
   201 }
   202 
   203 int BaseProvider::TryServerGameDLL(const char *iface)
   204 {
   205 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   206 	{
   207 		return 0;
   208 	}
   209 
   210 	return atoi(&iface[13]);
   211 }
   212 
   213 bool BaseProvider::LogMessage(const char *buffer)
   214 {
   215 	if (!engine)
   216 	{
   217 		return false;
   218 	}
   219 
   220 	engine->LogPrint(buffer);
   221 
   222 	return true;
   223 }
   224 
   225 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   226 {
   227 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   228 
   229 	if (hook == ProvidedHook_LevelInit)
   230 	{
   231 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   232 	}
   233 	else if (hook == ProvidedHook_LevelShutdown)
   234 	{
   235 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   236 	}
   237 	else if (hook == ProvidedHook_GameInit)
   238 	{
   239 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   240 	}
   241 	else if (hook == ProvidedHook_DLLShutdown)
   242 	{
   243 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
   244 	}
   245 	else if (hook == ProvidedHook_DLLInit)
   246 	{
   247 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
   248 	}
   249 
   250 	*pInfo = mfi;
   251 
   252 	return (mfi.thisptroffs >= 0);
   253 }
   254 
   255 void BaseProvider::DisplayError(const char *fmt, ...)
   256 {
   257 	va_list ap;
   258 	char buffer[2048];
   259 
   260 	va_start(ap, fmt);
   261 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   262 	va_end(ap);
   263 
   264 	Error(buffer);
   265 }
   266 
   267 void BaseProvider::DisplayWarning(const char *fmt, ...)
   268 {
   269 	va_list ap;
   270 	char buffer[2048];
   271 
   272 	va_start(ap, fmt);
   273 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   274 	va_end(ap);
   275 
   276 	Warning(buffer);
   277 }
   278 
   279 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   280 {
   281 	return &g_SMConVarAccessor;
   282 }
   283 
   284 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   285 {
   286 	return g_SMConVarAccessor.Register(pCommand);
   287 }
   288 
   289 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   290 {
   291 	return g_SMConVarAccessor.Unregister(pCommand);
   292 }
   293 
   294 int BaseProvider::GetUserMessageCount()
   295 {
   296 	if (!usermsgs_extracted)
   297 	{
   298 		return -1;
   299 	}
   300 
   301 	return (int)usermsgs_list.size();
   302 }
   303 
   304 int BaseProvider::FindUserMessage(const char *name, int *size)
   305 {
   306 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   307 	{
   308 		if (usermsgs_list[i].name.compare(name) == 0)
   309 		{
   310 			if (size)
   311 			{
   312 				*size = usermsgs_list[i].size;
   313 			}
   314 			return (int)i;
   315 		}
   316 	}
   317 	
   318 	return -1;
   319 }
   320 
   321 const char *BaseProvider::GetUserMessage(int index, int *size)
   322 {
   323 	if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
   324 	{
   325 		return NULL;
   326 	}
   327 
   328 	if (size)
   329 	{
   330 		*size = usermsgs_list[index].size;
   331 	}
   332 
   333 	return usermsgs_list[index].name.c_str();
   334 }
   335 
   336 const char *BaseProvider::GetGameDescription()
   337 {
   338 	return server->GetGameDescription();
   339 }
   340 
   341 int BaseProvider::DetermineSourceEngine(const char *game)
   342 {
   343 	return SOURCE_ENGINE_ORANGEBOX;
   344 }
   345 
   346 ConVar *BaseProvider::CreateConVar(const char *name,
   347 								   const char *defval,
   348 								   const char *help,
   349 								   int flags)
   350 {
   351 	int newflags = 0;
   352 	if (flags & ConVarFlag_Notify)
   353 	{
   354 		newflags |= FCVAR_NOTIFY;
   355 	}
   356 	if (flags & ConVarFlag_Replicated)
   357 	{
   358 		newflags |= FCVAR_REPLICATED;
   359 	}
   360 	if (flags & ConVarFlag_SpOnly)
   361 	{
   362 		newflags |= FCVAR_SPONLY;
   363 	}
   364 
   365 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   366 
   367 	RegisterConCommandBase(pVar);
   368 	conbases_unreg.push_back(pVar);
   369 
   370 	return pVar;
   371 }
   372 
   373 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
   374 {
   375 	g_VspListener.SetLoadable(true);
   376 	return &g_VspListener;
   377 }
   378 
   379 bool BaseProvider::IsAlternatelyLoaded()
   380 {
   381 	return g_VspListener.IsRootLoadMethod();
   382 }
   383 
   384 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   385 {
   386 	if (baseFs == NULL)
   387 	{
   388 		return false;
   389 	}
   390 
   391 	KeyValues *pValues;
   392 	const char *plugin_file, *p_alias;
   393 
   394 	pValues = new KeyValues("Metamod Plugin");
   395 
   396 	if (!pValues->LoadFromFile(baseFs, file))
   397 	{
   398 		pValues->deleteThis();
   399 		return false;
   400 	}
   401 
   402 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   403 	{
   404 		pValues->deleteThis();
   405 		return false;
   406 	}
   407 
   408 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   409 	{
   410 		UTIL_Format(alias, alias_len, "%s", p_alias);
   411 	}
   412 	else
   413 	{
   414 		UTIL_Format(alias, alias_len, "");
   415 	}
   416 
   417 	/* Attempt to find a file extension */
   418 	if (UTIL_GetExtension(plugin_file) == NULL)
   419 	{
   420 		g_pMetamod->PathFormat(path, 
   421 			path_len, 
   422 			"%s/%s%s", 
   423 			g_pMetamod->GetBaseDir(), 
   424 			plugin_file, 
   425 #if defined WIN32 || defined _WIN32
   426 			".dll"
   427 #else
   428 			"_i486.so"
   429 #endif
   430 			);
   431 	}
   432 	else
   433 	{
   434 		g_pMetamod->PathFormat(path,
   435 			path_len,
   436 			"%s/%s", 
   437 			g_pMetamod->GetBaseDir(),
   438 			plugin_file);
   439 	}
   440 
   441 	pValues->deleteThis();
   442 
   443 	return true;
   444 }
   445 
   446 class GlobCommand : public IMetamodSourceCommandInfo
   447 {
   448 public:
   449 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   450 	{
   451 	}
   452 public:
   453 	unsigned int GetArgCount()
   454 	{
   455 		return m_cmd->ArgC() - 1;
   456 	}
   457 
   458 	const char *GetArg(unsigned int num)
   459 	{
   460 		return m_cmd->Arg(num);
   461 	}
   462 
   463 	const char *GetArgString()
   464 	{
   465 		return m_cmd->ArgS();
   466 	}
   467 private:
   468 	const CCommand *m_cmd;
   469 };
   470 
   471 void LocalCommand_Meta(const CCommand &args)
   472 {
   473 	GlobCommand cmd(&args);
   474 	Command_Meta(&cmd);
   475 }
   476 
   477 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   478 {
   479 	GlobCommand cmd(&_cmd);
   480 
   481 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   482 	{
   483 		Command_ClientMeta(pEdict, &cmd);
   484 		RETURN_META(MRES_SUPERCEDE);
   485 	}
   486 
   487 	RETURN_META(MRES_IGNORED);
   488 }
   489 
   490 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   491 {
   492 	unsigned char *addr1 = (unsigned char *)_addr1;
   493 	unsigned char *addr2 = (unsigned char *)_addr2;
   494 
   495 	for (size_t i=0; i<len; i++)
   496 	{
   497 		if (addr2[i] == '*')
   498 		{
   499 			continue;
   500 		}
   501 		if (addr1[i] != addr2[i])
   502 		{
   503 			return false;
   504 		}
   505 	}
   506 
   507 	return true;
   508 }
   509 
   510 //////////////////////////////////////////////////////////////////////
   511 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   512 // Signatures necessary in finding the pointer to the CUtlDict that //
   513 //   stores user message information.                               //
   514 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   515 //   message indices. This is our answer to it. Yuck! <:-(          //
   516 //////////////////////////////////////////////////////////////////////
   517 #ifdef OS_WIN32
   518 	/* General Windows sig */
   519 	#define MSGCLASS_SIGLEN		7
   520 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   521 	#define MSGCLASS_OFFS		2
   522 
   523 	/* Dystopia Wimdows hack */
   524 	#define MSGCLASS2_SIGLEN	16
   525 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   526 	#define MSGCLASS2_OFFS		11
   527 
   528 	/* Windows frame pointer sig */
   529 	#define MSGCLASS3_SIGLEN	18
   530 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   531 	#define MSGCLASS3_OFFS		13
   532 #elif defined OS_LINUX
   533 	/* No frame pointer sig */
   534 	#define MSGCLASS_SIGLEN		14
   535 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   536 	#define MSGCLASS_OFFS		9
   537 
   538 	/* Frame pointer sig */
   539 	#define MSGCLASS2_SIGLEN	16
   540 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   541 	#define MSGCLASS2_OFFS		11
   542 #endif
   543 
   544 struct UserMessage
   545 {
   546 	int size;
   547 	const char *name;
   548 };
   549 
   550 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   551 
   552 /* This is the ugliest function in all of SourceMM */
   553 bool CacheUserMessages()
   554 {
   555 	/* Get address of original GetUserMessageInfo() */
   556 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   557 
   558 	/* Oh dear, we have a relative jump on our hands
   559 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   560 	 */
   561 	if (*vfunc == '\xE9')
   562 	{
   563 		/* Get address from displacement...
   564 		 *
   565 		 * Add 5 because it's relative to next instruction:
   566 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   567 		 */
   568 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   569 	}
   570 
   571 	CUtlDict<UserMessage *, int> *dict = NULL;
   572 
   573 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   574 	{
   575 		/* Get address of CUserMessages instance */
   576 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   577 
   578 		/* Get address of CUserMessages::m_UserMessages */
   579 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   580 	} 
   581 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   582 	{
   583 	#ifdef OS_WIN32
   584 		/* If we get here, the code is possibly inlined like in Dystopia */
   585 
   586 		/* Get the address of the CUtlRBTree */
   587 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   588 
   589 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   590 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   591 	#elif defined OS_LINUX
   592 		/* Get address of CUserMessages instance */
   593 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   594 
   595 		/* Get address of CUserMessages::m_UserMessages */
   596 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   597 	#endif
   598 	#ifdef OS_WIN32
   599 	} 
   600 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   601 	{
   602 		/* Get address of CUserMessages instance */
   603 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   604 
   605 		/* Get address of CUserMessages::m_UserMessages */
   606 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   607 	#endif
   608 	}
   609 
   610 	#if !defined OS_WIN32
   611 	if (dict == NULL)
   612 	{
   613 		char path[255];
   614 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   615 		{
   616 			void *handle = dlopen(path, RTLD_NOW);
   617 			if (handle != NULL)
   618 			{
   619 				void *addr = dlsym(handle, "usermessages");
   620 				dict = (UserMsgDict *)*(void **)addr;
   621 				dlclose(handle);
   622 			}
   623 		}
   624 	}
   625 	#endif
   626 
   627 	if (dict != NULL)
   628 	{
   629 		int msg_count = dict->Count();
   630 
   631 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   632 		if (msg_count < 0 || msg_count > 255)
   633 		{
   634 			return false;
   635 		}
   636 
   637 		UserMessage *msg;
   638 		UsrMsgInfo u_msg;
   639 
   640 		/* Cache messages in our CUtlDict */
   641 		for (int i = 0; i < msg_count; i++)
   642 		{
   643 			msg = dict->Element(i);
   644 			u_msg.name = msg->name;
   645 			u_msg.size = msg->size;
   646 			usermsgs_list.push_back(u_msg);
   647 		}
   648 
   649 		return true;
   650 	}
   651 
   652 	return false;
   653 }
   654