core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Sun Sep 23 06:51:21 2007 +0000 (2007-09-23)
changeset 1456 69a68787c743
parent 1412 a2ca3d22dd71
child 1568 ecbaee393b0b
permissions -rw-r--r--
fixed a bug where double dependencies could cause a crash on unload
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <stdio.h>
    33 #include "sourcemod.h"
    34 #include "sourcemm_api.h"
    35 #include "systems/LibrarySys.h"
    36 #include "vm/sp_vm_engine.h"
    37 #include <sh_string.h>
    38 #include "PluginSys.h"
    39 #include "ShareSys.h"
    40 #include "CoreConfig.h"
    41 #include "Logger.h"
    42 #include "ExtensionSys.h"
    43 #include "AdminCache.h"
    44 #include "sm_stringutil.h"
    45 #include "PlayerManager.h"
    46 #include "Translator.h"
    47 #include "ForwardSys.h"
    48 #include "TimerSys.h"
    49 #include "GameConfigs.h"
    50 
    51 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    52 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    53 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    54 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
    55 
    56 SourcePawnEngine g_SourcePawn;
    57 SourceModBase g_SourceMod;
    58 
    59 ILibrary *g_pJIT = NULL;
    60 SourceHook::String g_BaseDir;
    61 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    62 IVirtualMachine *g_pVM;
    63 IdentityToken_t *g_pCoreIdent = NULL;
    64 IForward *g_pOnMapEnd = NULL;
    65 bool g_Loaded = false;
    66 
    67 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    68 typedef int (*GIVEENGINEPOINTER2)(ISourcePawnEngine *, unsigned int api_version);
    69 typedef unsigned int (*GETEXPORTCOUNT)();
    70 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    71 typedef void (*NOTIFYSHUTDOWN)();
    72 
    73 void ShutdownJIT()
    74 {
    75 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    76 	if (notify)
    77 	{
    78 		notify();
    79 	}
    80 
    81 	g_pJIT->CloseLibrary();
    82 }
    83 
    84 SourceModBase::SourceModBase()
    85 {
    86 	m_IsMapLoading = false;
    87 	m_ExecPluginReload = false;
    88 	m_ExecOnMapEnd = false;
    89 	m_GotBasePath = false;
    90 }
    91 
    92 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    93 									  const char *value, 
    94 									  ConfigSource source, 
    95 									  char *error, 
    96 									  size_t maxlength)
    97 {
    98 	if (strcasecmp(key, "BasePath") == 0)
    99 	{
   100 		if (source == ConfigSource_Console)
   101 		{
   102 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
   103 			return ConfigResult_Reject;
   104 		}
   105 
   106 		if (!m_GotBasePath)
   107 		{
   108 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
   109 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
   110 
   111 			m_GotBasePath = true;
   112 		}
   113 
   114 		return ConfigResult_Accept;
   115 	}
   116 
   117 	return ConfigResult_Ignore;
   118 }
   119 
   120 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
   121 {
   122 	const char *gamepath = g_SMAPI->GetBaseDir();
   123 
   124 	/* Store full path to game */
   125 	g_BaseDir.assign(gamepath);
   126 
   127 	/* Store name of game directory by itself */
   128 	size_t len = strlen(gamepath);
   129 	for (size_t i = len - 1; i >= 0; i--)
   130 	{
   131 		if (gamepath[i] == PLATFORM_SEP_CHAR)
   132 		{
   133 			strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
   134 			break;
   135 		}
   136 	}
   137 
   138 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   139 	g_CoreConfig.Initialize();
   140 
   141 	/* This shouldn't happen, but can't hurt to be safe */
   142 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   143 	{
   144 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   145 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   146 		m_GotBasePath = true;
   147 	}
   148 
   149 	/* Attempt to load the JIT! */
   150 	char file[PLATFORM_MAX_PATH];
   151 	char myerror[255];
   152 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   153 		GetSourceModPath(),
   154 		PLATFORM_LIB_EXT
   155 		);
   156 
   157 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   158 	if (!g_pJIT)
   159 	{
   160 		if (error && maxlength)
   161 		{
   162 			snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   163 				myerror,
   164 				PLATFORM_LIB_EXT);
   165 		}
   166 		return false;
   167 	}
   168 
   169 	int err;
   170 	
   171 	GIVEENGINEPOINTER2 jit_init2 = (GIVEENGINEPOINTER2)g_pJIT->GetSymbolAddress("GiveEnginePointer2");
   172 	if (!jit_init2)
   173 	{
   174 		GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
   175 		if (!jit_init)
   176 		{
   177 			ShutdownJIT();
   178 			if (error && maxlength)
   179 			{
   180 				snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
   181 			}
   182 			return false;
   183 		}
   184 
   185 		if ((err=jit_init(g_pSourcePawn)) != 0)
   186 		{
   187 			ShutdownJIT();
   188 			if (error && maxlength)
   189 			{
   190 				snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
   191 			}
   192 			return false;
   193 		}
   194 	} else {
   195 		/* On version bumps, we should check for older versions as well, if the new version fails.
   196 		 * We can then check the exports to see if any VM versions will be sufficient.
   197 		 */
   198 		if ((err=jit_init2(g_pSourcePawn, SOURCEPAWN_ENGINE_API_VERSION)) != SP_ERROR_NONE)
   199 		{
   200 			ShutdownJIT();
   201 			if (error && maxlength)
   202 			{
   203 				snprintf(error, maxlength, "JIT incompatible with SourceMod version");
   204 			}
   205 			return false;
   206 		}
   207 	}
   208 
   209 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   210 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   211 	if (!jit_get)
   212 	{
   213 		ShutdownJIT();
   214 		if (error && maxlength)
   215 		{
   216 			snprintf(error, maxlength, "JIT is missing a necessary export!");
   217 		}
   218 		return false;
   219 	}
   220 
   221 	unsigned int num = jit_getnum();
   222 	if (!num)
   223 	{
   224 		ShutdownJIT();
   225 		if (error && maxlength)
   226 		{
   227 			snprintf(error, maxlength, "JIT did not export any virtual machines!");
   228 		}
   229 		return false;
   230 	}
   231 
   232 	unsigned int api_version;
   233 	for (unsigned int i=0; i<num; i++)
   234 	{
   235 		 if ((g_pVM=jit_get(i)) == NULL)
   236 		 {
   237 			 if (error && maxlength)
   238 			 {
   239 				 snprintf(error, maxlength, "JIT did not export any virtual machines!");
   240 			 }
   241 			 continue;
   242 		 }
   243 		/* Refuse any API that we might not be able to deal with.
   244 		 * Also refuse anything < 3 because we need fake natives.
   245 		 */
   246 		 api_version = g_pVM->GetAPIVersion();
   247 		 if (api_version < 3 || api_version > SOURCEPAWN_VM_API_VERSION)
   248 		 {
   249 			 if (error && maxlength)
   250 			 {
   251 				 snprintf(error, maxlength, "JIT is not a compatible version");
   252 			 }
   253 			 g_pVM = NULL;
   254 			 continue;
   255 		 }
   256 		 break;
   257 	}
   258 
   259 	if (!g_pVM)
   260 	{
   261 		ShutdownJIT();
   262 		return false;
   263 	}
   264 
   265 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   266 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   267 
   268 	/* Only load if we're not late */
   269 	if (!late)
   270 	{
   271 		StartSourceMod(false);
   272 	}
   273 
   274 	return true;
   275 }
   276 
   277 void SourceModBase::StartSourceMod(bool late)
   278 {
   279 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   280 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
   281 
   282 	enginePatch = SH_GET_CALLCLASS(engine);
   283 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   284 
   285 	/* Notify! */
   286 	SMGlobalClass *pBase = SMGlobalClass::head;
   287 	while (pBase)
   288 	{
   289 		pBase->OnSourceModStartup(false);
   290 		pBase = pBase->m_pGlobalClassNext;
   291 	}
   292 
   293 	/* Make the global core identity */
   294 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   295 
   296 	/* Notify! */
   297 	pBase = SMGlobalClass::head;
   298 	while (pBase)
   299 	{
   300 		pBase->OnSourceModAllInitialized();
   301 		pBase = pBase->m_pGlobalClassNext;
   302 	}
   303 
   304 	/* Add us now... */
   305 	g_ShareSys.AddInterface(NULL, this);
   306 
   307 	/* We're loaded! */
   308 	g_Loaded = true;
   309 }
   310 
   311 static bool g_LevelEndBarrier = false;
   312 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   313 {
   314 	/* If we're not loaded... */
   315 	if (!g_Loaded)
   316 	{
   317 		/* Do all global initialization now */
   318 		StartSourceMod(true);
   319 	}
   320 
   321 	m_IsMapLoading = true;
   322 	m_ExecPluginReload = true;
   323 	m_ExecOnMapEnd = true;
   324 
   325 	/* Notify! */
   326 	SMGlobalClass *pBase = SMGlobalClass::head;
   327 	while (pBase)
   328 	{
   329 		pBase->OnSourceModLevelChange(pMapName);
   330 		pBase = pBase->m_pGlobalClassNext;
   331 	}
   332 
   333 	DoGlobalPluginLoads();
   334 
   335 	m_IsMapLoading = false;
   336 
   337 	/* Notify! */
   338 	pBase = SMGlobalClass::head;
   339 	while (pBase)
   340 	{
   341 		pBase->OnSourceModPluginsLoaded();
   342 		pBase = pBase->m_pGlobalClassNext;
   343 	}
   344 
   345 	if (!g_pOnMapEnd)
   346 	{
   347 		g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
   348 	}
   349 
   350 	g_LevelEndBarrier = true;
   351 
   352 	RETURN_META_VALUE(MRES_IGNORED, true);
   353 }
   354 
   355 void SourceModBase::LevelShutdown()
   356 {
   357 	if (g_LevelEndBarrier)
   358 	{
   359 		SMGlobalClass *next = SMGlobalClass::head;
   360 		while (next)
   361 		{
   362 			next->OnSourceModLevelEnd();
   363 			next = next->m_pGlobalClassNext;
   364 		}
   365 		g_LevelEndBarrier = false;
   366 	}
   367 
   368 	if (g_pOnMapEnd && m_ExecOnMapEnd)
   369 	{
   370 		g_pOnMapEnd->Execute(NULL);
   371 		m_ExecOnMapEnd = false;
   372 	}
   373 
   374 	g_OnMapStarted = false;
   375 
   376 	if (m_ExecPluginReload)
   377 	{
   378 		g_PluginSys.ReloadOrUnloadPlugins();
   379 		m_ExecPluginReload = false;
   380 	}
   381 }
   382 
   383 bool SourceModBase::IsMapLoading() const
   384 {
   385 	return m_IsMapLoading;
   386 }
   387 
   388 void SourceModBase::DoGlobalPluginLoads()
   389 {
   390 	char config_path[PLATFORM_MAX_PATH];
   391 	char plugins_path[PLATFORM_MAX_PATH];
   392 
   393 	BuildPath(Path_SM, config_path, 
   394 		sizeof(config_path),
   395 		"configs/plugin_settings.cfg");
   396 	BuildPath(Path_SM, plugins_path,
   397 		sizeof(plugins_path),
   398 		"plugins");
   399 
   400 	/* Load any auto extensions */
   401 	g_Extensions.TryAutoload();
   402 
   403 	/* Load any game extension */
   404 	const char *game_ext;
   405 	if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
   406 	{
   407 		char path[PLATFORM_MAX_PATH];
   408 		UTIL_Format(path, sizeof(path), "games/%s.ext." PLATFORM_LIB_EXT, game_ext);
   409 		g_Extensions.LoadAutoExtension(path);
   410 	}
   411 
   412 	/* Run the first pass */
   413 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   414 
   415 	/* Mark any extensions as loaded */
   416 	g_Extensions.MarkAllLoaded();
   417 
   418 	/* No modules yet, it's safe to call this from here */
   419 	g_PluginSys.LoadAll_SecondPass();
   420 
   421 	/* Re-mark any extensions as loaded */
   422 	g_Extensions.MarkAllLoaded();
   423 
   424 	/* Call OnAllPluginsLoaded */
   425 	g_PluginSys.AllPluginsLoaded();
   426 }
   427 
   428 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
   429 {
   430 	char _buffer[PLATFORM_MAX_PATH];
   431 	va_list ap;
   432 
   433 	va_start(ap, format);
   434 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   435 	va_end(ap);
   436 
   437 	const char *base = NULL;
   438 	if (type == Path_Game)
   439 	{
   440 		base = GetGamePath();
   441 	} else if (type == Path_SM) {
   442 		base = GetSourceModPath();
   443 	} else if (type == Path_SM_Rel) {
   444 		base = m_SMRelDir;
   445 	}
   446 
   447 	if (base)
   448 	{
   449 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   450 	} else {
   451 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   452 	}
   453 }
   454 
   455 void SourceModBase::CloseSourceMod()
   456 {
   457 	/* Force a level end */
   458 	LevelShutdown();
   459 
   460 	/* Unload plugins */
   461 	g_PluginSys.Shutdown();
   462 
   463 	/* Unload extensions */
   464 	g_Extensions.Shutdown();
   465 
   466 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   467 
   468 	if (g_Loaded)
   469 	{
   470 		if (g_pOnMapEnd)
   471 		{
   472 			g_Forwards.ReleaseForward(g_pOnMapEnd);
   473 		}
   474 	
   475 		/* Notify! */
   476 		SMGlobalClass *pBase = SMGlobalClass::head;
   477 		while (pBase)
   478 		{
   479 			pBase->OnSourceModShutdown();
   480 			pBase = pBase->m_pGlobalClassNext;
   481 		}
   482 	
   483 		/* Delete all data packs */
   484 		CStack<CDataPack *>::iterator iter;
   485 		CDataPack *pd;
   486 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   487 		{
   488 			pd = (*iter);
   489 			delete pd;
   490 		}
   491 		m_freepacks.popall();
   492 	
   493 		/* Notify! */
   494 		pBase = SMGlobalClass::head;
   495 		while (pBase)
   496 		{
   497 			pBase->OnSourceModAllShutdown();
   498 			pBase = pBase->m_pGlobalClassNext;
   499 		}
   500 	
   501 		if (enginePatch)
   502 		{
   503 			SH_RELEASE_CALLCLASS(enginePatch);
   504 			enginePatch = NULL;
   505 		}
   506 	
   507 		if (gamedllPatch)
   508 		{
   509 			SH_RELEASE_CALLCLASS(gamedllPatch);
   510 			gamedllPatch = NULL;
   511 		}
   512 
   513 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   514 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
   515 	}
   516 
   517 	/* Rest In Peace */
   518 	ShutdownJIT();
   519 }
   520 
   521 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   522 {
   523 	IExtensionInterface *pAPI = pExt->GetAPI();
   524 	const char *tag = pAPI->GetExtensionTag();
   525 	char buffer[2048];
   526 	va_list ap;
   527 
   528 	va_start(ap, format);
   529 	vsnprintf(buffer, sizeof(buffer), format, ap);
   530 	va_end(ap);
   531 
   532 	if (tag)
   533 	{
   534 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   535 	} else {
   536 		g_Logger.LogMessage("%s", buffer);
   537 	}
   538 }
   539 
   540 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   541 {
   542 	IExtensionInterface *pAPI = pExt->GetAPI();
   543 	const char *tag = pAPI->GetExtensionTag();
   544 	char buffer[2048];
   545 	va_list ap;
   546 
   547 	va_start(ap, format);
   548 	vsnprintf(buffer, sizeof(buffer), format, ap);
   549 	va_end(ap);
   550 
   551 	if (tag)
   552 	{
   553 		g_Logger.LogError("[%s] %s", tag, buffer);
   554 	} else {
   555 		g_Logger.LogError("%s", buffer);
   556 	}
   557 }
   558 
   559 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   560 {
   561 	char *fmt;
   562 
   563 	pContext->LocalToString(params[param], &fmt);
   564 
   565 	int lparam = ++param;
   566 
   567 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   568 }
   569 
   570 const char *SourceModBase::GetSourceModPath() const
   571 {
   572 	return m_SMBaseDir;
   573 }
   574 
   575 const char *SourceModBase::GetGamePath() const
   576 {
   577 	return g_BaseDir.c_str();
   578 }
   579 
   580 void SourceModBase::SetGlobalTarget(unsigned int index)
   581 {
   582 	m_target = index;
   583 }
   584 
   585 unsigned int SourceModBase::GetGlobalTarget() const
   586 {
   587 	return m_target;
   588 }
   589 
   590 IDataPack *SourceModBase::CreateDataPack()
   591 {
   592 	CDataPack *pack;
   593 	if (m_freepacks.empty())
   594 	{
   595 		pack = new CDataPack;
   596 	} else {
   597 		pack = m_freepacks.front();
   598 		m_freepacks.pop();
   599 		pack->Initialize();
   600 	}
   601 	return pack;
   602 }
   603 
   604 void SourceModBase::FreeDataPack(IDataPack *pack)
   605 {
   606 	m_freepacks.push(static_cast<CDataPack *>(pack));
   607 }
   608 
   609 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   610 {
   611 	//:TODO:
   612 	return 0;
   613 }
   614 
   615 const char *SourceModBase::GetGameFolderName() const
   616 {
   617 	return m_ModDir;
   618 }
   619 
   620 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
   621 {
   622 	return g_pSourcePawn;
   623 }
   624 
   625 IVirtualMachine *SourceModBase::GetScriptingVM()
   626 {
   627 	return g_pVM;
   628 }
   629 
   630 void SourceModBase::AllPluginsLoaded()
   631 {
   632 	SMGlobalClass *base = SMGlobalClass::head;
   633 	while (base)
   634 	{
   635 		base->OnSourceModGameInitialized();
   636 		base = base->m_pGlobalClassNext;
   637 	}
   638 }
   639 
   640 time_t SourceModBase::GetAdjustedTime()
   641 {
   642 	return GetAdjustedTime();
   643 }
   644 
   645 SMGlobalClass *SMGlobalClass::head = NULL;
   646 
   647 SMGlobalClass::SMGlobalClass()
   648 {
   649 	m_pGlobalClassNext = SMGlobalClass::head;
   650 	SMGlobalClass::head = this;
   651 }