core/provider/provider_ep2.cpp
author David Anderson <dvander@alliedmods.net>
Sat Oct 15 22:16:50 2011 -0700 (2011-10-15)
changeset 767 fd3ff8d792ce
parent 763 e5a02b89021c
child 780 35f2a207badf
permissions -rw-r--r--
Fix page protection bug causing a rare startup crash (bug 5133, r=fyren).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2009 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     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.
    12  * 
    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:
    16  *
    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.
    24  */
    25 
    26 #include <stdio.h>
    27 #include <setjmp.h>
    28 #include "../metamod_oslink.h"
    29 #include <sourcehook.h>
    30 #include <convar.h>
    31 #include <eiface.h>
    32 #include <tier0/icommandline.h>
    33 #include <sh_vector.h>
    34 #include <sh_string.h>
    35 #include "../metamod_util.h"
    36 #include "provider_ep2.h"
    37 #include "console.h"
    38 #include "metamod_console.h"
    39 #include <filesystem.h>
    40 #include "metamod.h"
    41 
    42 /* Types */
    43 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    44 struct UsrMsgInfo
    45 {
    46 	UsrMsgInfo()
    47 	{
    48 	}
    49 	UsrMsgInfo(int s, const char *t) : size(s), name(t)
    50 	{
    51 	}
    52 	int size;
    53 	String name;
    54 };
    55 
    56 /* Imports */
    57 #if SOURCE_ENGINE == SE_DARKMESSIAH
    58 #undef CommandLine
    59 DLL_IMPORT ICommandLine *CommandLine();
    60 #endif
    61 
    62 /* Functions */
    63 void CacheUserMessages();
    64 void Detour_Error(const tchar *pMsg, ...);
    65 #if SOURCE_ENGINE >= SE_ORANGEBOX
    66 void ClientCommand(edict_t *pEdict, const CCommand &args);
    67 void LocalCommand_Meta(const CCommand &args);
    68 #else
    69 void ClientCommand(edict_t *pEdict);
    70 void LocalCommand_Meta();
    71 #endif
    72 
    73 void _ServerCommand();
    74 /* Variables */
    75 static BaseProvider g_Ep1Provider;
    76 static List<ConCommandBase *> conbases_unreg;
    77 static CVector<UsrMsgInfo> usermsgs_list;
    78 static jmp_buf usermsg_end;
    79 
    80 ICvar *icvar = NULL;
    81 IFileSystem *baseFs = NULL;
    82 IServerGameDLL *server = NULL;
    83 IVEngineServer *engine = NULL;
    84 IServerGameClients *gameclients = NULL;
    85 IMetamodSourceProvider *provider = &g_Ep1Provider;
    86 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    87 
    88 #if SOURCE_ENGINE >= SE_ORANGEBOX
    89 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    90 #else
    91 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    92 #endif
    93 
    94 void BaseProvider::ConsolePrint(const char *str)
    95 {
    96 #if SOURCE_ENGINE >= SE_ORANGEBOX
    97 	ConMsg("%s", str);
    98 #else
    99 	Msg("%s", str);
   100 #endif
   101 }
   102 
   103 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory, 
   104 									  CreateInterfaceFn serverFactory)
   105 {
   106 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   107 	if (!engine)
   108 	{
   109 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
   110 		return;
   111 	}
   112 #if SOURCE_ENGINE >= SE_ORANGEBOX
   113 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
   114 #else
   115 	icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
   116 #endif
   117 	if (!icvar)
   118 	{
   119 		DisplayError("Could not find ICvar! Metamod cannot load.");
   120 		return;
   121 	}
   122 
   123 
   124 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
   125 		== NULL)
   126 	{
   127 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   128 	}
   129 
   130 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   131 	if (baseFs == NULL)
   132 	{
   133 		mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
   134 	}
   135 
   136 #if SOURCE_ENGINE >= SE_ORANGEBOX
   137 	g_pCVar = icvar;
   138 #endif
   139 
   140 	g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
   141 
   142 	CacheUserMessages();
   143 
   144 #if SOURCE_ENGINE == SE_DARKMESSIAH
   145 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   146 	{
   147 		/* This is very unlikely considering it's old engine */
   148 		mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   149 		mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   150 	}
   151 #endif
   152 
   153 	if (gameclients)
   154 	{
   155 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   156 	}
   157 }
   158 
   159 void BaseProvider::Notify_DLLShutdown_Pre()
   160 {
   161 	g_SMConVarAccessor.RemoveMetamodCommands();
   162 
   163 #if SOURCE_ENGINE == SE_DARKMESSIAH
   164 	if (g_Metamod.IsLoadedAsGameDLL())
   165 	{
   166 		icvar->UnlinkVariables(FCVAR_GAMEDLL);
   167 	}
   168 #endif
   169 }
   170 
   171 bool BaseProvider::IsRemotePrintingAvailable()
   172 {
   173 	return true;
   174 }
   175 
   176 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   177 {
   178 	engine->ClientPrintf(client, message);
   179 }
   180 
   181 void BaseProvider::ServerCommand(const char *cmd)
   182 {
   183 	engine->ServerCommand(cmd);
   184 }
   185 
   186 const char *BaseProvider::GetConVarString(ConVar *convar)
   187 {
   188 	if (convar == NULL)
   189 	{
   190 		return NULL;
   191 	}
   192 
   193 	return convar->GetString();
   194 }
   195 
   196 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   197 {
   198 	convar->SetValue(str);
   199 }
   200 
   201 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   202 {
   203 	return pCommand->IsCommand();
   204 }
   205 
   206 
   207 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   208 {
   209 	return (build == SOURCE_ENGINE_ORIGINAL
   210 			|| build == SOURCE_ENGINE_EPISODEONE);
   211 }
   212 
   213 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   214 {
   215 	if (key[0] == '-' || key[0] == '+')
   216 	{
   217 		return CommandLine()->ParmValue(key, defval);
   218 	}
   219 	else if (icvar)
   220 	{
   221 		const char *val;
   222 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   223 		{
   224 			return defval;
   225 		}
   226 
   227 		return val;
   228 	}
   229 
   230 	return NULL;
   231 }
   232 
   233 int BaseProvider::TryServerGameDLL(const char *iface)
   234 {
   235 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   236 	{
   237 		return 0;
   238 	}
   239 
   240 	return atoi(&iface[13]);
   241 }
   242 
   243 bool BaseProvider::LogMessage(const char *buffer)
   244 {
   245 	if (!engine)
   246 	{
   247 		return false;
   248 	}
   249 
   250 	engine->LogPrint(buffer);
   251 
   252 	return true;
   253 }
   254 
   255 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   256 {
   257 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   258 
   259 	if (hook == ProvidedHook_LevelInit)
   260 	{
   261 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   262 	}
   263 	else if (hook == ProvidedHook_LevelShutdown)
   264 	{
   265 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   266 	}
   267 	else if (hook == ProvidedHook_GameInit)
   268 	{
   269 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   270 	}
   271 
   272 	*pInfo = mfi;
   273 
   274 	return (mfi.thisptroffs >= 0);
   275 }
   276 
   277 void BaseProvider::DisplayError(const char *fmt, ...)
   278 {
   279 	va_list ap;
   280 	char buffer[2048];
   281 
   282 	va_start(ap, fmt);
   283 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   284 	va_end(ap);
   285 
   286 	Error(buffer);
   287 }
   288 
   289 void BaseProvider::DisplayWarning(const char *fmt, ...)
   290 {
   291 	va_list ap;
   292 	char buffer[2048];
   293 
   294 	va_start(ap, fmt);
   295 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   296 	va_end(ap);
   297 
   298 	Warning(buffer);
   299 }
   300 
   301 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   302 {
   303 	return &g_SMConVarAccessor;
   304 }
   305 
   306 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   307 {
   308 	return g_SMConVarAccessor.Register(pCommand);
   309 }
   310 
   311 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   312 {
   313 	return g_SMConVarAccessor.Unregister(pCommand);
   314 }
   315 
   316 int BaseProvider::GetUserMessageCount()
   317 {
   318 	return (int)usermsgs_list.size();
   319 }
   320 
   321 int BaseProvider::FindUserMessage(const char *name, int *size)
   322 {
   323 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   324 	{
   325 		if (usermsgs_list[i].name.compare(name) == 0)
   326 		{
   327 			if (size)
   328 			{
   329 				*size = usermsgs_list[i].size;
   330 			}
   331 			return (int)i;
   332 		}
   333 	}
   334 	
   335 	return -1;
   336 }
   337 
   338 const char *BaseProvider::GetUserMessage(int index, int *size)
   339 {
   340 	if (index < 0 || index >= (int)usermsgs_list.size())
   341 	{
   342 		return NULL;
   343 	}
   344 
   345 	if (size)
   346 	{
   347 		*size = usermsgs_list[index].size;
   348 	}
   349 
   350 	return usermsgs_list[index].name.c_str();
   351 }
   352 
   353 const char *BaseProvider::GetGameDescription()
   354 {
   355 	return server->GetGameDescription();
   356 }
   357 
   358 int BaseProvider::DetermineSourceEngine(const char *game)
   359 {
   360 #if SOURCE_ENGINE == SE_BLOODYGOODTIME
   361 	return SOURCE_ENGINE_BLOODYGOODTIME;
   362 #elif SOURCE_ENGINE == SE_ALIENSWARM
   363 	return SOURCE_ENGINE_ALIENSWARM;
   364 #elif SOURCE_ENGINE == SE_LEFT4DEAD2
   365 	return SOURCE_ENGINE_LEFT4DEAD2;
   366 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   367 	return SOURCE_ENGINE_LEFT4DEAD;
   368 #elif SOURCE_ENGINE == SE_ORANGEBOX
   369 	return SOURCE_ENGINE_ORANGEBOX;
   370 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
   371 	return SOURCE_ENGINE_ORANGEBOXVALVE;
   372 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   373 	return SOURCE_ENGINE_DARKMESSIAH;
   374 #elif SOURCE_ENGINE == SE_EYE
   375 	return SOURCE_ENGINE_EYE;
   376 #else
   377 #error "SOURCE_ENGINE not defined to a known value"
   378 #endif
   379 }
   380 
   381 ConVar *BaseProvider::CreateConVar(const char *name,
   382 								   const char *defval,
   383 								   const char *help,
   384 								   int flags)
   385 {
   386 	int newflags = 0;
   387 	if (flags & ConVarFlag_Notify)
   388 	{
   389 		newflags |= FCVAR_NOTIFY;
   390 	}
   391 	if (flags & ConVarFlag_SpOnly)
   392 	{
   393 		newflags |= FCVAR_SPONLY;
   394 	}
   395 
   396 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   397 
   398 	g_SMConVarAccessor.RegisterConCommandBase(pVar);
   399 
   400 	return pVar;
   401 }
   402 
   403 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   404 {
   405 	if (baseFs == NULL)
   406 	{
   407 		return false;
   408 	}
   409 
   410 	KeyValues *pValues;
   411 	const char *plugin_file, *p_alias;
   412 
   413 	pValues = new KeyValues("Metamod Plugin");
   414 
   415 	if (!pValues->LoadFromFile(baseFs, file))
   416 	{
   417 		pValues->deleteThis();
   418 		return false;
   419 	}
   420 
   421 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   422 	{
   423 		pValues->deleteThis();
   424 		return false;
   425 	}
   426 
   427 	UTIL_Format(path, path_len, "%s", plugin_file);
   428 
   429 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   430 	{
   431 		UTIL_Format(alias, alias_len, "%s", p_alias);
   432 	}
   433 	else
   434 	{
   435 		UTIL_Format(alias, alias_len, "");
   436 	}
   437 
   438 	pValues->deleteThis();
   439 
   440 	return true;
   441 }
   442 
   443 #if SOURCE_ENGINE >= SE_ORANGEBOX
   444 class GlobCommand : public IMetamodSourceCommandInfo
   445 {
   446 public:
   447 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   448 	{
   449 	}
   450 public:
   451 	unsigned int GetArgCount()
   452 	{
   453 		return m_cmd->ArgC() - 1;
   454 	}
   455 
   456 	const char *GetArg(unsigned int num)
   457 	{
   458 		return m_cmd->Arg(num);
   459 	}
   460 
   461 	const char *GetArgString()
   462 	{
   463 		return m_cmd->ArgS();
   464 	}
   465 private:
   466 	const CCommand *m_cmd;
   467 };
   468 #else
   469 class GlobCommand : public IMetamodSourceCommandInfo
   470 {
   471 public:
   472 	unsigned int GetArgCount()
   473 	{
   474 		return engine->Cmd_Argc() - 1;
   475 	}
   476 
   477 	const char *GetArg(unsigned int num)
   478 	{
   479 		return engine->Cmd_Argv(num);
   480 	}
   481 
   482 	const char *GetArgString()
   483 	{
   484 		return engine->Cmd_Args();
   485 	}
   486 };
   487 #endif
   488 
   489 #if SOURCE_ENGINE >= SE_ORANGEBOX
   490 void LocalCommand_Meta(const CCommand &args)
   491 {
   492 	GlobCommand cmd(&args);
   493 #else
   494 void LocalCommand_Meta()
   495 {
   496 	GlobCommand cmd;
   497 #endif
   498 	Command_Meta(&cmd);
   499 }
   500 
   501 #if SOURCE_ENGINE >= SE_ORANGEBOX
   502 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   503 {
   504 	GlobCommand cmd(&_cmd);
   505 #else
   506 void ClientCommand(edict_t *pEdict)
   507 {
   508 	GlobCommand cmd;
   509 #endif
   510 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   511 	{
   512 		Command_ClientMeta(pEdict, &cmd);
   513 		RETURN_META(MRES_SUPERCEDE);
   514 	}
   515 
   516 	RETURN_META(MRES_IGNORED);
   517 }
   518 
   519 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   520 void Detour_Error(const tchar *pMsg, ...)
   521 {
   522 	/* Jump back to setjmp() in CacheUserMessages() */
   523 	longjmp(usermsg_end, 1);
   524 }
   525 
   526 #define IA32_JMP_IMM32 0xE9
   527 
   528 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   529  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   530  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   531  *
   532  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   533  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   534  * exit.
   535  */
   536 void CacheUserMessages()
   537 {
   538 	int q, size;
   539 	char buffer[256];
   540 	unsigned char *target, *detour;
   541 	unsigned char orig_bytes[5];
   542 
   543 	target = (unsigned char *)&Error;
   544 	detour = (unsigned char *)&Detour_Error;
   545 
   546 	/* Save bytes from target function */
   547 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   548 
   549 	/* Patch in relative jump to our Error() detour */
   550 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   551 	target[0] = IA32_JMP_IMM32;
   552 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   553 
   554 	/* This is where longjmp() will end up */
   555 	if (setjmp(usermsg_end))
   556 	{
   557 		/* Restore bytes and memory protection */
   558 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   559 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   560 		return;
   561 	}
   562 
   563 	q = 0;
   564 
   565 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   566 	while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   567 	{
   568 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   569 		q++;
   570 	}
   571 
   572 	/* Jump back to setjmp() */
   573 	longjmp(usermsg_end, 1);
   574 }