core/logic/PluginSys.cpp
author Ruben Gonzalez <drifter01620@gmail.com>
Thu May 22 09:49:27 2014 -0400 (2014-05-22)
changeset 4378 568f4497ef4a
parent 4109 10eb68d668af
permissions -rw-r--r--
Update CS:GO team score gamedata.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 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 <stdarg.h>
    34 #include "PluginSys.h"
    35 #include "ShareSys.h"
    36 #include <ILibrarySys.h>
    37 #include <ISourceMod.h>
    38 #include <IHandleSys.h>
    39 #include <IForwardSys.h>
    40 #include <IPlayerHelpers.h>
    41 #include "ExtensionSys.h"
    42 #include "GameConfigs.h"
    43 #include "common_logic.h"
    44 #include "Translator.h"
    45 
    46 CPluginManager g_PluginSys;
    47 HandleType_t g_PluginType = 0;
    48 IdentityType_t g_PluginIdent = 0;
    49 
    50 CPlugin::CPlugin(const char *file)
    51 {
    52 	static int MySerial = 0;
    53 
    54 	m_type = PluginType_Private;
    55 	m_status = Plugin_Uncompiled;
    56 	m_bSilentlyFailed = false;
    57 	m_serial = ++MySerial;
    58 	m_pRuntime = NULL;
    59 	m_errormsg[sizeof(m_errormsg) - 1] = '\0';
    60 	smcore.Format(m_filename, sizeof(m_filename), "%s", file);
    61 	m_handle = 0;
    62 	m_ident = NULL;
    63 	m_FakeNativesMissing = false;
    64 	m_LibraryMissing = false;
    65 	m_bGotAllLoaded = false;
    66 	m_pPhrases = g_Translator.CreatePhraseCollection();
    67 	m_MaxClientsVar = NULL;
    68 }
    69 
    70 CPlugin::~CPlugin()
    71 {
    72 	if (m_handle)
    73 	{
    74 		HandleSecurity sec;
    75 		sec.pOwner = g_PluginSys.GetIdentity();
    76 		sec.pIdentity = sec.pOwner;
    77 
    78 		handlesys->FreeHandle(m_handle, &sec);
    79 		g_ShareSys.DestroyIdentity(m_ident);
    80 	}
    81 
    82 	if (m_pRuntime != NULL)
    83 	{
    84 		delete m_pRuntime;
    85 		m_pRuntime = NULL;
    86 	}
    87 
    88 	for (size_t i=0; i<m_configs.size(); i++)
    89 	{
    90 		delete m_configs[i];
    91 	}
    92 	m_configs.clear();
    93 	if (m_pPhrases != NULL)
    94 	{
    95 		m_pPhrases->Destroy();
    96 		m_pPhrases = NULL;
    97 	}
    98 }
    99 
   100 void CPlugin::InitIdentity()
   101 {
   102 	if (!m_handle)
   103 	{
   104 		m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
   105 		m_handle = handlesys->CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
   106 		m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
   107 		m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
   108 	}
   109 }
   110 
   111 unsigned int CPlugin::CalcMemUsage()
   112 {
   113 	unsigned int base_size = 
   114 		sizeof(CPlugin) 
   115 		+ sizeof(IdentityToken_t)
   116 		+ (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
   117 		+ m_Props.mem_usage();
   118 
   119 	for (unsigned int i = 0; i < m_configs.size(); i++)
   120 	{
   121 		base_size += m_configs[i]->autocfg.size();
   122 		base_size += m_configs[i]->folder.size();
   123 	}
   124 
   125 	for (List<String>::iterator i = m_Libraries.begin();
   126 		 i != m_Libraries.end();
   127 		 i++)
   128 	{
   129 		base_size += (*i).size();
   130 	}
   131 
   132 	for (List<String>::iterator i = m_RequiredLibs.begin();
   133 		 i != m_RequiredLibs.end();
   134 		 i++)
   135 	{
   136 		base_size += (*i).size();
   137 	}
   138 
   139 	return base_size;
   140 }
   141 
   142 Handle_t CPlugin::GetMyHandle()
   143 {
   144 	return m_handle;
   145 }
   146 
   147 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
   148 {
   149 	char fullpath[PLATFORM_MAX_PATH];
   150 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
   151 	FILE *fp = fopen(fullpath, "rb");
   152 
   153 	CPlugin *pPlugin = new CPlugin(file);
   154 
   155 	if (!fp)
   156 	{
   157 		if (error)
   158 		{
   159 			smcore.Format(error, maxlength, "Unable to open file");
   160 		}
   161 		pPlugin->m_status = Plugin_BadLoad;
   162 		return pPlugin;
   163 	}
   164 
   165 	fclose(fp);
   166 
   167 	return pPlugin;
   168 }
   169 
   170 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
   171 {
   172 	StringHashMap<void *>::Result r = m_Props.find(prop);
   173 	if (!r.found())
   174 		return false;
   175 
   176 	if (ptr)
   177 		*ptr = r->value;
   178 
   179 	if (remove)
   180 		m_Props.remove(r);
   181 
   182 	return true;
   183 }
   184 
   185 bool CPlugin::SetProperty(const char *prop, void *ptr)
   186 {
   187 	 return m_Props.insert(prop, ptr);
   188 }
   189 
   190 IPluginRuntime *CPlugin::GetRuntime()
   191 {
   192 	return m_pRuntime;
   193 }
   194 
   195 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
   196 {
   197 	PluginStatus old_status = m_status;
   198 	m_status = status;
   199 
   200 	if (old_status == Plugin_Running)
   201 	{
   202 		/* Tell everyone we're now paused */
   203 		g_PluginSys._SetPauseState(this, true);
   204 	}
   205 
   206 	va_list ap;
   207 	va_start(ap, error_fmt);
   208 	smcore.FormatArgs(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
   209 	va_end(ap);
   210 
   211 	if (m_pRuntime != NULL)
   212 	{
   213 		m_pRuntime->SetPauseState(true);
   214 	}
   215 }
   216 
   217 bool CPlugin::UpdateInfo()
   218 {
   219 	/* Now grab the info */
   220 	uint32_t idx;
   221 	IPluginContext *base = GetBaseContext();
   222 	int err = base->FindPubvarByName("myinfo", &idx);
   223 
   224 	memset(&m_info, 0, sizeof(m_info));
   225 
   226 	if (err == SP_ERROR_NONE)
   227 	{
   228 		struct sm_plugininfo_c_t
   229 		{
   230 			cell_t name;
   231 			cell_t description;
   232 			cell_t author;
   233 			cell_t version;
   234 			cell_t url;
   235 		};
   236 		sm_plugininfo_c_t *cinfo;
   237 		cell_t local_addr;
   238 
   239 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
   240 		base->LocalToString(cinfo->name, (char **)&m_info.name);
   241 		base->LocalToString(cinfo->description, (char **)&m_info.description);
   242 		base->LocalToString(cinfo->author, (char **)&m_info.author);
   243 		base->LocalToString(cinfo->url, (char **)&m_info.url);
   244 		base->LocalToString(cinfo->version, (char **)&m_info.version);
   245 	}
   246 
   247 	m_info.author = m_info.author ? m_info.author : "";
   248 	m_info.description = m_info.description ? m_info.description : "";
   249 	m_info.name = m_info.name ? m_info.name : "";
   250 	m_info.url = m_info.url ? m_info.url : "";
   251 	m_info.version = m_info.version ? m_info.version : "";
   252 
   253 	if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
   254 	{
   255 		struct __version_info
   256 		{
   257 			cell_t version;
   258 			cell_t filevers;
   259 			cell_t date;
   260 			cell_t time;
   261 		};
   262 		__version_info *info;
   263 		cell_t local_addr;
   264 		const char *pDate, *pTime, *pFileVers;
   265 
   266 		pDate = "";
   267 		pTime = "";
   268 
   269 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
   270 		m_FileVersion = info->version;
   271 		if (m_FileVersion >= 4)
   272 		{
   273 			base->LocalToString(info->date, (char **)&pDate);
   274 			base->LocalToString(info->time, (char **)&pTime);
   275 			smcore.Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
   276 		}
   277 		if (m_FileVersion > 5)
   278 		{
   279 			base->LocalToString(info->filevers, (char **)&pFileVers);
   280 			SetErrorState(Plugin_Failed, "Newer SourceMod required (%s or higher)", pFileVers);
   281 			return false;
   282 		}
   283 	}
   284 	else
   285 	{
   286 		m_FileVersion = 0;
   287 	}
   288 
   289 	if ((err = base->FindPubvarByName("MaxClients", &idx)) == SP_ERROR_NONE)
   290 	{
   291 		base->GetPubvarByIndex(idx, &m_MaxClientsVar);
   292 	}
   293 
   294 	return true;
   295 }
   296 
   297 void CPlugin::SyncMaxClients(int max_clients)
   298 {
   299 	if (m_MaxClientsVar == NULL)
   300 	{
   301 		return;
   302 	}
   303 
   304 	*m_MaxClientsVar->offs = max_clients;
   305 }
   306 
   307 void CPlugin::Call_OnPluginStart()
   308 {
   309 	if (m_status != Plugin_Loaded)
   310 	{
   311 		return;
   312 	}
   313 
   314 	m_status = Plugin_Running;
   315 
   316 	SyncMaxClients(playerhelpers->GetMaxClients());
   317 
   318 	cell_t result;
   319 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
   320 	if (!pFunction)
   321 	{
   322 		return;
   323 	}
   324 
   325 	int err;
   326 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   327 	{
   328 		SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
   329 	}
   330 }
   331 
   332 void CPlugin::Call_OnPluginEnd()
   333 {
   334 	if (m_status > Plugin_Paused)
   335 	{
   336 		return;
   337 	}
   338 
   339 	cell_t result;
   340 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
   341 	if (!pFunction)
   342 	{
   343 		return;
   344 	}
   345 
   346 	pFunction->Execute(&result);
   347 }
   348 
   349 void CPlugin::Call_OnAllPluginsLoaded()
   350 {
   351 	if (m_status > Plugin_Paused)
   352 	{
   353 		return;
   354 	}
   355 
   356 	if (m_bGotAllLoaded)
   357 	{
   358 		return;
   359 	}
   360 
   361 	m_bGotAllLoaded = true;
   362 
   363 	cell_t result;
   364 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
   365 	if (pFunction != NULL)
   366 	{
   367 		pFunction->Execute(&result);
   368 	}
   369 
   370 	if (smcore.IsMapRunning())
   371 	{
   372 		if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
   373 		{
   374 			pFunction->Execute(NULL);
   375 		}
   376 	}
   377 
   378 	if (smcore.AreConfigsExecuted())
   379 	{
   380 		smcore.ExecuteConfigs(GetBaseContext());
   381 	}
   382 }
   383 
   384 APLRes CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
   385 {
   386 	if (m_status != Plugin_Created)
   387 	{
   388 		return APLRes_Failure;
   389 	}
   390 
   391 	m_status = Plugin_Loaded;
   392 
   393 	int err;
   394 	cell_t result;
   395 	bool haveNewAPL = false;
   396 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad2");
   397 
   398 	if (pFunction) 
   399 	{
   400 		haveNewAPL = true;
   401 	}
   402 	else if (!(pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad")))
   403 	{
   404 		return APLRes_Success;
   405 	}
   406 
   407 	pFunction->PushCell(m_handle);
   408 	pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
   409 	pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
   410 	pFunction->PushCell(maxlength);
   411 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   412 	{
   413 		return APLRes_Failure;
   414 	}
   415 
   416 	if (haveNewAPL) 
   417 	{
   418 		return (APLRes)result;
   419 	}
   420 	else if (result)
   421 	{
   422 		return APLRes_Success;
   423 	}
   424 	else
   425 	{
   426 		return APLRes_Failure;
   427 	}
   428 }
   429 
   430 void *CPlugin::GetPluginStructure()
   431 {
   432 	return NULL;
   433 }
   434 
   435 IPluginContext *CPlugin::GetBaseContext()
   436 {
   437 	if (m_pRuntime == NULL)
   438 	{
   439 		return NULL;
   440 	}
   441 
   442 	return m_pRuntime->GetDefaultContext();
   443 }
   444 
   445 sp_context_t *CPlugin::GetContext()
   446 {
   447 	return NULL;
   448 }
   449 
   450 const char *CPlugin::GetFilename()
   451 {
   452 	return m_filename;
   453 }
   454 
   455 PluginType CPlugin::GetType()
   456 {
   457 	return m_type;
   458 }
   459 
   460 const sm_plugininfo_t *CPlugin::GetPublicInfo()
   461 {
   462 	if (GetStatus() >= Plugin_Created)
   463 	{
   464 		return NULL;
   465 	}
   466 	return &m_info;
   467 }
   468 
   469 unsigned int CPlugin::GetSerial()
   470 {
   471 	return m_serial;
   472 }
   473 
   474 PluginStatus CPlugin::GetStatus()
   475 {
   476 	return m_status;
   477 }
   478 
   479 bool CPlugin::IsSilentlyFailed()
   480 {
   481 	return m_bSilentlyFailed;
   482 }
   483 
   484 bool CPlugin::IsDebugging()
   485 {
   486 	if (m_pRuntime == NULL)
   487 	{
   488 		return false;
   489 	}
   490 
   491 	return true;
   492 }
   493 
   494 void CPlugin::SetSilentlyFailed(bool sf)
   495 {
   496 	m_bSilentlyFailed = sf;
   497 }
   498 
   499 void CPlugin::LibraryActions(LibraryAction action)
   500 {
   501 	List<String>::iterator iter;
   502 	for (iter = m_Libraries.begin();
   503 		iter != m_Libraries.end();
   504 		iter++)
   505 	{
   506 		g_PluginSys.OnLibraryAction((*iter).c_str(), action);
   507 	}
   508 }
   509 
   510 bool CPlugin::SetPauseState(bool paused)
   511 {
   512 	if (paused && GetStatus() != Plugin_Running)
   513 	{
   514 		return false;
   515 	} else if (!paused && GetStatus() != Plugin_Paused) {
   516 		return false;
   517 	}
   518 
   519 	if (paused)
   520 	{
   521 		LibraryActions(LibraryAction_Removed);
   522 	}
   523 
   524 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
   525 	if (pFunction)
   526 	{
   527 		cell_t result;
   528 		pFunction->PushCell(paused ? 1 : 0);
   529 		pFunction->Execute(&result);
   530 	}
   531 
   532 	if (paused)
   533 	{
   534 		m_status = Plugin_Paused;
   535 		m_pRuntime->SetPauseState(true);
   536 	} else {
   537 		m_status = Plugin_Running;
   538 		m_pRuntime->SetPauseState(false);
   539 	}
   540 
   541 	g_PluginSys._SetPauseState(this, paused);
   542 
   543 	if (!paused)
   544 	{
   545 		LibraryActions(LibraryAction_Added);
   546 	}
   547 
   548 	return true;
   549 }
   550 
   551 IdentityToken_t *CPlugin::GetIdentity()
   552 {
   553 	return m_ident;
   554 }
   555 
   556 bool CPlugin::IsRunnable()
   557 {
   558 	return (m_status <= Plugin_Paused) ? true : false;
   559 }
   560 
   561 time_t CPlugin::GetFileTimeStamp()
   562 {
   563 	char path[PLATFORM_MAX_PATH];
   564 	g_pSM->BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
   565 #ifdef PLATFORM_WINDOWS
   566 	struct _stat s;
   567 	if (_stat(path, &s) != 0)
   568 #elif defined PLATFORM_POSIX
   569 	struct stat s;
   570 	if (stat(path, &s) != 0)
   571 #endif
   572 	{
   573 		return 0;
   574 	}
   575 	else
   576 	{
   577 		return s.st_mtime;
   578 	}
   579 }
   580 
   581 time_t CPlugin::GetTimeStamp()
   582 {
   583 	return m_LastAccess;
   584 }
   585 
   586 void CPlugin::SetTimeStamp(time_t t)
   587 {
   588 	m_LastAccess = t;
   589 }
   590 
   591 IPhraseCollection *CPlugin::GetPhrases()
   592 {
   593 	return m_pPhrases;
   594 }
   595 
   596 void CPlugin::DependencyDropped(CPlugin *pOwner)
   597 {
   598 	if (!m_pRuntime)
   599 		return;
   600 
   601 	List<String>::iterator reqlib_iter;
   602 	List<String>::iterator lib_iter;
   603 	for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
   604 	{
   605 		for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
   606 		{
   607 			if ((*reqlib_iter) == (*lib_iter))
   608 				m_LibraryMissing = true;
   609 		}	
   610 	}
   611 
   612 	unsigned int unbound = 0;
   613 	for (size_t i = 0; i < pOwner->m_fakes.length(); i++)
   614 	{
   615 		ke::Ref<Native> entry(pOwner->m_fakes[i]);
   616 
   617 		uint32_t idx;
   618 		if (m_pRuntime->FindNativeByName(entry->name(), &idx) != SP_ERROR_NONE)
   619 			continue;
   620 
   621 		sp_native_t *native;
   622 		m_pRuntime->GetNativeByIndex(idx, &native);
   623 
   624 		native->pfn = NULL;
   625 		native->status = SP_NATIVE_UNBOUND;
   626 		unbound++;
   627 	}
   628 
   629 	if (unbound)
   630 	{
   631 		m_FakeNativesMissing = true;
   632 	}
   633 
   634 	/* :IDEA: in the future, add native trapping? */
   635 	if (m_FakeNativesMissing || m_LibraryMissing)
   636 	{
   637 		SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
   638 	}
   639 }
   640 
   641 size_t CPlugin::GetConfigCount()
   642 {
   643 	return (unsigned int)m_configs.size();
   644 }
   645 
   646 AutoConfig *CPlugin::GetConfig(size_t i)
   647 {
   648 	if (i >= GetConfigCount())
   649 	{
   650 		return NULL;
   651 	}
   652 
   653 	return m_configs[i];
   654 }
   655 
   656 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
   657 {
   658 	/* Do a check for duplicates to prevent double-execution */
   659 	for (size_t i = 0; i < m_configs.size(); i++)
   660 	{
   661 		if (m_configs[i]->autocfg.compare(cfg) == 0
   662 			&& m_configs[i]->folder.compare(folder) == 0
   663 			&& m_configs[i]->create == autoCreate)
   664 		{
   665 			return;
   666 		}
   667 	}
   668 
   669 	AutoConfig *c = new AutoConfig;
   670 
   671 	c->autocfg = cfg;
   672 	c->folder = folder;
   673 	c->create = autoCreate;
   674 
   675 	m_configs.push_back(c);
   676 }
   677 
   678 void CPlugin::DropEverything()
   679 {
   680 	CPlugin *pOther;
   681 	List<WeakNative>::iterator wk_iter;
   682 
   683 	/* Tell everyone that depends on us that we're about to drop */
   684 	for (List<CPlugin *>::iterator iter = m_Dependents.begin();
   685 		 iter != m_Dependents.end(); 
   686 		 iter++)
   687 	{
   688 		pOther = static_cast<CPlugin *>(*iter);
   689 		pOther->DependencyDropped(this);
   690 	}
   691 
   692 	/* Note: we don't care about things we depend on. 
   693 	 * The reason is that extensions have their own cleanup 
   694 	 * code for plugins.  Although the "right" design would be 
   695 	 * to centralize that here, i'm omitting it for now.  Thus, 
   696 	 * the code below to walk the plugins list will suffice.
   697 	 */
   698 	
   699 	/* Other plugins could be holding weak references that were 
   700 	 * added by us.  We need to clean all of those up now.
   701 	 */
   702 	for (List<CPlugin *>::iterator iter = g_PluginSys.m_plugins.begin();
   703 		 iter != g_PluginSys.m_plugins.end();
   704 		 iter++)
   705 	{
   706 		(*iter)->ToNativeOwner()->DropRefsTo(this);
   707 	}
   708 
   709 	/* Proceed with the rest of the necessities. */
   710 	CNativeOwner::DropEverything();
   711 }
   712 
   713 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
   714 {
   715 	ke::Ref<Native> entry = g_ShareSys.AddFakeNative(pFunc, name, func);
   716 	if (!entry)
   717 		return false;
   718 
   719 	m_fakes.append(entry);
   720 	return true;
   721 }
   722 
   723 /*******************
   724  * PLUGIN ITERATOR *
   725  *******************/
   726 
   727 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
   728 {
   729 	mylist = _mylist;
   730 	Reset();
   731 }
   732 
   733 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
   734 {
   735 	return (*current);
   736 }
   737 
   738 bool CPluginManager::CPluginIterator::MorePlugins()
   739 {
   740 	return (current != mylist->end());
   741 }
   742 
   743 void CPluginManager::CPluginIterator::NextPlugin()
   744 {
   745 	current++;
   746 }
   747 
   748 void CPluginManager::CPluginIterator::Release()
   749 {
   750 	g_PluginSys.ReleaseIterator(this);
   751 }
   752 
   753 CPluginManager::CPluginIterator::~CPluginIterator()
   754 {
   755 }
   756 
   757 void CPluginManager::CPluginIterator::Reset()
   758 {
   759 	current = mylist->begin();
   760 }
   761 
   762 /******************
   763  * PLUGIN MANAGER *
   764  ******************/
   765 
   766 CPluginManager::CPluginManager()
   767 {
   768 	m_AllPluginsLoaded = false;
   769 	m_MyIdent = NULL;
   770 	m_LoadingLocked = false;
   771 	
   772 	m_bBlockBadPlugins = true;
   773 }
   774 
   775 CPluginManager::~CPluginManager()
   776 {
   777 	CStack<CPluginManager::CPluginIterator *>::iterator iter;
   778 	for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
   779 	{
   780 		delete (*iter);
   781 	}
   782 	m_iters.popall();
   783 }
   784 
   785 void CPluginManager::Shutdown()
   786 {
   787 	List<CPlugin *>::iterator iter;
   788 
   789 	while ((iter = m_plugins.begin()) != m_plugins.end())
   790 	{
   791 		UnloadPlugin(*iter);
   792 	}
   793 }
   794 
   795 void CPluginManager::LoadAll(const char *config_path, const char *plugins_path)
   796 {
   797 	LoadAll_FirstPass(config_path, plugins_path);
   798 	g_Extensions.MarkAllLoaded();
   799 	LoadAll_SecondPass();
   800 	g_Extensions.MarkAllLoaded();
   801 	AllPluginsLoaded();
   802 }
   803 
   804 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
   805 {
   806 	/* First read in the database of plugin settings */
   807 	m_AllPluginsLoaded = false;
   808 	LoadPluginsFromDir(basedir, NULL);
   809 }
   810 
   811 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   812 {
   813 	char base_path[PLATFORM_MAX_PATH];
   814 
   815 	/* Form the current path to start reading from */
   816 	if (localpath == NULL)
   817 	{
   818 		libsys->PathFormat(base_path, sizeof(base_path), "%s", basedir);
   819 	} else {
   820 		libsys->PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   821 	}
   822 
   823 	IDirectory *dir = libsys->OpenDirectory(base_path);
   824 
   825 	if (!dir)
   826 	{
   827 		char error[256];
   828 		libsys->GetPlatformError(error, sizeof(error));
   829 		smcore.LogError("[SM] Failure reading from plugins path: %s", localpath);
   830 		smcore.LogError("[SM] Platform returned error: %s", error);
   831 		return;
   832 	}
   833 
   834 	while (dir->MoreFiles())
   835 	{
   836 		if (dir->IsEntryDirectory() 
   837 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   838 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   839 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   840 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   841 		{
   842 			char new_local[PLATFORM_MAX_PATH];
   843 			if (localpath == NULL)
   844 			{
   845 				/* If no path yet, don't add a former slash */
   846 				smcore.Format(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   847 			} else {
   848 				libsys->PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   849 			}
   850 			LoadPluginsFromDir(basedir, new_local);
   851 		} else if (dir->IsEntryFile()) {
   852 			const char *name = dir->GetEntryName();
   853 			size_t len = strlen(name);
   854 			if (len >= 4
   855 				&& strcmp(&name[len-4], ".smx") == 0)
   856 			{
   857 				/* If the filename matches, load the plugin */
   858 				char plugin[PLATFORM_MAX_PATH];
   859 				if (localpath == NULL)
   860 				{
   861 					smcore.Format(plugin, sizeof(plugin), "%s", name);
   862 				} else {
   863 					libsys->PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   864 				}
   865 				LoadAutoPlugin(plugin);
   866 			}
   867 		}
   868 		dir->NextEntry();
   869 	}
   870 	libsys->CloseDirectory(dir);
   871 }
   872 
   873 LoadRes CPluginManager::_LoadPlugin(CPlugin **aResult, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
   874 {
   875 	if (m_LoadingLocked)
   876 		return LoadRes_NeverLoad;
   877 
   878 	int err;
   879 
   880 	/**
   881 	 * Does this plugin already exist?
   882 	 */
   883 	CPlugin *pPlugin;
   884 	if (m_LoadLookup.retrieve(path, &pPlugin))
   885 	{
   886 		/* Check to see if we should try reloading it */
   887 		if (pPlugin->GetStatus() == Plugin_BadLoad
   888 			|| pPlugin->GetStatus() == Plugin_Error
   889 			|| pPlugin->GetStatus() == Plugin_Failed)
   890 		{
   891 			UnloadPlugin(pPlugin);
   892 		}
   893 		else
   894 		{
   895 			if (aResult)
   896 				*aResult = pPlugin;
   897 			return LoadRes_AlreadyLoaded;
   898 		}
   899 	}
   900 
   901 	pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
   902 	assert(pPlugin != NULL);
   903 
   904 	pPlugin->m_type = PluginType_MapUpdated;
   905 
   906 	ICompilation *co = NULL;
   907 
   908 	if (pPlugin->m_status == Plugin_Uncompiled)
   909 	{
   910 		co = g_pSourcePawn2->StartCompilation();
   911 	}
   912 
   913 	/* Do the actual compiling */
   914 	if (co != NULL)
   915 	{
   916 		char fullpath[PLATFORM_MAX_PATH];
   917 		g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
   918 
   919 		pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
   920 		if (pPlugin->m_pRuntime == NULL)
   921 		{
   922 			if (error)
   923 			{
   924 				smcore.Format(error, 
   925 					maxlength, 
   926 					"Unable to load plugin (error %d: %s)", 
   927 					err, 
   928 					g_pSourcePawn2->GetErrorString(err));
   929 			}
   930 			pPlugin->m_status = Plugin_BadLoad;
   931 		}
   932 		else
   933 		{
   934 			if (pPlugin->UpdateInfo())
   935 			{
   936 				pPlugin->m_status = Plugin_Created;
   937 			}
   938 			else
   939 			{
   940 				if (error)
   941 				{
   942 					smcore.Format(error, maxlength, "%s", pPlugin->m_errormsg);
   943 				}
   944 			}
   945 		}
   946 	}
   947 	
   948 	if (pPlugin->GetStatus() == Plugin_Created)
   949 	{
   950 		unsigned char *pCodeHash = pPlugin->m_pRuntime->GetCodeHash();
   951 		
   952 		char codeHashBuf[40];
   953 		smcore.Format(codeHashBuf, 40, "plugin_");
   954 		for (int i = 0; i < 16; i++)
   955 			smcore.Format(codeHashBuf + 7 + (i * 2), 3, "%02x", pCodeHash[i]);
   956 		
   957 		const char *bulletinUrl = g_pGameConf->GetKeyValue(codeHashBuf);
   958 		if (bulletinUrl != NULL)
   959 		{
   960 			if (m_bBlockBadPlugins)
   961 			{
   962 				if (error)
   963 				{
   964 					if (bulletinUrl[0] != '\0')
   965 					{
   966 						smcore.Format(error, maxlength, "Known malware detected and blocked. See %s for more info", bulletinUrl);
   967 					} else {
   968 						smcore.Format(error, maxlength, "Possible malware or illegal plugin detected and blocked");
   969 					}
   970 				}
   971 				pPlugin->m_status = Plugin_BadLoad;
   972 			} else {
   973 				if (bulletinUrl[0] != '\0')
   974 				{
   975 					smcore.Log("%s: Known malware detected. See %s for more info, blocking disabled in core.cfg", pPlugin->GetFilename(), bulletinUrl);
   976 				} else {
   977 					smcore.Log("%s: Possible malware or illegal plugin detected, blocking disabled in core.cfg", pPlugin->GetFilename());
   978 				}
   979 			}
   980 		}
   981 	}
   982 
   983 	LoadRes loadFailure = LoadRes_Failure;
   984 	/* Get the status */
   985 	if (pPlugin->GetStatus() == Plugin_Created)
   986 	{
   987 		/* First native pass - add anything from Core */
   988 		g_ShareSys.BindNativesToPlugin(pPlugin, true);
   989 		pPlugin->InitIdentity();
   990 		APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);  
   991 		switch (result)
   992 		{
   993 		case APLRes_Success:
   994 			/* Autoload any modules */
   995 			LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
   996 			break;
   997 		case APLRes_Failure:
   998 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
   999 			loadFailure = LoadRes_Failure;
  1000 			break;
  1001 		case APLRes_SilentFailure:
  1002 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1003 			loadFailure = LoadRes_SilentFailure;
  1004 			pPlugin->SetSilentlyFailed(true);
  1005 			break;
  1006 		default:
  1007 			assert(false);
  1008 		}
  1009 	}
  1010 
  1011 	/* Save the time stamp */
  1012 	time_t t = pPlugin->GetFileTimeStamp();
  1013 	pPlugin->SetTimeStamp(t);
  1014 
  1015 	if (aResult)
  1016 		*aResult = pPlugin;
  1017 
  1018 	return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
  1019 }
  1020 
  1021 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
  1022 {
  1023 	CPlugin *pl;
  1024 	LoadRes res;
  1025 
  1026 	*wasloaded = false;
  1027 	if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
  1028 	{
  1029 		delete pl;
  1030 		return NULL;
  1031 	}
  1032 
  1033 	if (res == LoadRes_AlreadyLoaded)
  1034 	{
  1035 		*wasloaded = true;
  1036 		return pl;
  1037 	}
  1038 
  1039 	if (res == LoadRes_NeverLoad)
  1040 	{
  1041 		if (error)
  1042 		{
  1043 			if (m_LoadingLocked)
  1044 			{
  1045 				smcore.Format(error, maxlength, "There is a global plugin loading lock in effect");
  1046 			}
  1047 			else
  1048 			{
  1049 				smcore.Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
  1050 			}
  1051 		}
  1052 		return NULL;
  1053 	}
  1054 
  1055 	AddPlugin(pl);
  1056 
  1057 	/* Run second pass if we need to */
  1058 	if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
  1059 	{
  1060 		if (!RunSecondPass(pl, error, maxlength))
  1061 		{
  1062 			UnloadPlugin(pl);
  1063 			return NULL;
  1064 		}
  1065 		pl->Call_OnAllPluginsLoaded();
  1066 	}
  1067 
  1068 	return pl;
  1069 }
  1070 
  1071 void CPluginManager::LoadAutoPlugin(const char *plugin)
  1072 {
  1073 	CPlugin *pl = NULL;
  1074 	LoadRes res;
  1075 	char error[255] = "Unknown error";
  1076 
  1077 	if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
  1078 	{
  1079 		smcore.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, error);
  1080 		pl->SetErrorState(
  1081 			pl->GetStatus() <= Plugin_Created ? Plugin_BadLoad : pl->GetStatus(), 
  1082 			"%s",
  1083 			error);
  1084 	}
  1085 
  1086 	if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
  1087 	{
  1088 		AddPlugin(pl);
  1089 	}
  1090 }
  1091 
  1092 void CPluginManager::AddPlugin(CPlugin *pPlugin)
  1093 {
  1094 	List<IPluginsListener *>::iterator iter;
  1095 	IPluginsListener *pListener;
  1096 
  1097 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1098 	{
  1099 		pListener = (*iter);
  1100 		pListener->OnPluginCreated(pPlugin);
  1101 	}
  1102 
  1103 	m_plugins.push_back(pPlugin);
  1104 	m_LoadLookup.insert(pPlugin->m_filename, pPlugin);
  1105 }
  1106 
  1107 void CPluginManager::LoadAll_SecondPass()
  1108 {
  1109 	List<CPlugin *>::iterator iter;
  1110 	CPlugin *pPlugin;
  1111 
  1112 	char error[256];
  1113 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1114 	{
  1115 		pPlugin = (*iter);
  1116 		if (pPlugin->GetStatus() == Plugin_Loaded)
  1117 		{
  1118 			error[0] = '\0';
  1119 			if (!RunSecondPass(pPlugin, error, sizeof(error)))
  1120 			{
  1121 				smcore.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
  1122 				pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1123 			}
  1124 		}
  1125 	}
  1126 
  1127 	m_AllPluginsLoaded = true;
  1128 }
  1129 
  1130 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
  1131 {
  1132 	struct _pl
  1133 	{
  1134 		cell_t name;
  1135 		cell_t file;
  1136 		cell_t required;
  1137 	} *pl;
  1138 
  1139 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1140 	uint32_t num = pBase->GetPubVarsNum();
  1141 	sp_pubvar_t *pubvar;
  1142 	char *name, *file;
  1143 	char pathfile[PLATFORM_MAX_PATH];
  1144 
  1145 	for (uint32_t i=0; i<num; i++)
  1146 	{
  1147 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1148 		{
  1149 			continue;
  1150 		}
  1151 		if (strncmp(pubvar->name, "__pl_", 5) == 0)
  1152 		{
  1153 			pl = (_pl *)pubvar->offs;
  1154 			if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
  1155 			{
  1156 				continue;
  1157 			}
  1158 			if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
  1159 			{
  1160 				continue;
  1161 			}
  1162 			libsys->GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
  1163 			if (strcmp(pathfile, file) == 0)
  1164 			{
  1165 				continue;
  1166 			}
  1167 			if (pl->required == false)
  1168 			{
  1169 				IPluginFunction *pFunc;
  1170 				char buffer[64];
  1171 				smcore.Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
  1172 				if ((pFunc=pBase->GetFunctionByName(buffer)))
  1173 				{
  1174 					cell_t res;
  1175 					pFunc->Execute(&res);
  1176 					if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1177 					{
  1178 						if (error)
  1179 						{
  1180 							smcore.Format(error, maxlength, "Fatal error during initializing plugin load");
  1181 						}
  1182 						return false;
  1183 					}
  1184 				}
  1185 			}
  1186 			else
  1187 			{
  1188 				/* Check that we aren't registering the same library twice */
  1189 				if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
  1190 				{
  1191 					pPlugin->m_RequiredLibs.push_back(name);
  1192 				}
  1193 				else
  1194 				{
  1195 					continue;
  1196 				}
  1197 				List<CPlugin *>::iterator iter;
  1198 				CPlugin *pl;
  1199 				bool found = false;
  1200 				for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1201 				{
  1202 					pl = (*iter);
  1203 					if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
  1204 					{
  1205 						found = true;
  1206 						break;
  1207 					}
  1208 				}
  1209 				if (!found)
  1210 				{
  1211 					if (error)
  1212 					{
  1213 						smcore.Format(error, maxlength, "Could not find required plugin \"%s\"", name);
  1214 					}
  1215 					return false;
  1216 				}
  1217 			}
  1218 		}
  1219 	}
  1220 
  1221 	return true;
  1222 }
  1223 
  1224 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
  1225 {
  1226 	/* Find any extensions this plugin needs */
  1227 	struct _ext
  1228 	{
  1229 		cell_t name;
  1230 		cell_t file;
  1231 		cell_t autoload;
  1232 		cell_t required;
  1233 	} *ext;
  1234 
  1235 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1236 	uint32_t num = pBase->GetPubVarsNum();
  1237 	sp_pubvar_t *pubvar;
  1238 	IExtension *pExt;
  1239 	char path[PLATFORM_MAX_PATH];
  1240 	char *file, *name;
  1241 	for (uint32_t i=0; i<num; i++)
  1242 	{
  1243 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1244 		{
  1245 			continue;
  1246 		}
  1247 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
  1248 		{
  1249 			ext = (_ext *)pubvar->offs;
  1250 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
  1251 			{
  1252 				continue;
  1253 			}
  1254 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
  1255 			{
  1256 				continue;
  1257 			}
  1258 			if (pass == 1)
  1259 			{
  1260 				/* Attempt to auto-load if necessary */
  1261 				if (ext->autoload)
  1262 				{
  1263 					libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1264 					bool bErrorOnMissing = ext->required ? true : false;
  1265 					g_Extensions.LoadAutoExtension(path, bErrorOnMissing);
  1266 				}
  1267 			}
  1268 			else if (pass == 2)
  1269 			{
  1270 				/* Is this required? */
  1271 				if (ext->required)
  1272 				{
  1273 					libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1274 					if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
  1275 					{
  1276 						pExt = g_Extensions.FindExtensionByName(name);
  1277 					}
  1278 					/* :TODO: should we bind to unloaded extensions?
  1279 					 * Currently the extension manager will ignore this.
  1280 					 */
  1281 					if (!pExt || !pExt->IsRunning(NULL, 0))
  1282 					{
  1283 						if (error)
  1284 						{
  1285 							smcore.Format(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
  1286 						}
  1287 						return false;
  1288 					}
  1289 					else
  1290 					{
  1291 						g_Extensions.BindChildPlugin(pExt, pPlugin);
  1292 					}
  1293 				}
  1294 				else
  1295 				{
  1296 					IPluginFunction *pFunc;
  1297 					char buffer[64];
  1298 					smcore.Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
  1299 
  1300 					if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
  1301 					{
  1302 						cell_t res;
  1303 						pFunc->Execute(&res);
  1304 						if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1305 						{
  1306 							if (error)
  1307 							{
  1308 								smcore.Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
  1309 							}
  1310 							return false;
  1311 						}
  1312 					}
  1313 				}
  1314 			}
  1315 		}
  1316 	}
  1317 
  1318 	return true;
  1319 }
  1320 
  1321 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
  1322 {
  1323 	/* Second pass for extension requirements */
  1324 	if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
  1325 	{
  1326 		return false;
  1327 	}
  1328 
  1329 	if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
  1330 	{
  1331 		return false;
  1332 	}
  1333 
  1334 	/* Run another binding pass */
  1335 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1336 
  1337 	/* Find any unbound natives. Right now, these are not allowed. */
  1338 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1339 	uint32_t num = pContext->GetNativesNum();
  1340 	sp_native_t *native;
  1341 	for (unsigned int i=0; i<num; i++)
  1342 	{
  1343 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1344 		{
  1345 			break;
  1346 		}
  1347 		if (native->status == SP_NATIVE_UNBOUND
  1348 			&& native->name[0] != '@'
  1349 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1350 		{
  1351 			if (error)
  1352 			{
  1353 				smcore.Format(error, maxlength, "Native \"%s\" was not found", native->name);
  1354 			}
  1355 			return false;
  1356 		}
  1357 	}
  1358 
  1359 	/* Finish by telling all listeners */
  1360 	List<IPluginsListener *>::iterator iter;
  1361 	IPluginsListener *pListener;
  1362 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1363 	{
  1364 		pListener = (*iter);
  1365 		pListener->OnPluginLoaded(pPlugin);
  1366 	}
  1367 	
  1368 	/* Tell this plugin to finish initializing itself */
  1369 	pPlugin->Call_OnPluginStart();
  1370 
  1371 	/* Now, if we have fake natives, go through all plugins that might need rebinding */
  1372 	if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakes.length())
  1373 	{
  1374 		List<CPlugin *>::iterator pl_iter;
  1375 		for (pl_iter = m_plugins.begin();
  1376 			 pl_iter != m_plugins.end();
  1377 			 pl_iter++)
  1378 		{
  1379 			CPlugin *pOther = (*pl_iter);
  1380 			if ((pOther->GetStatus() == Plugin_Error
  1381 				&& (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
  1382 				|| pOther->m_FakeNativesMissing)
  1383 			{
  1384 				TryRefreshDependencies(pOther);
  1385 			}
  1386 			else if ((pOther->GetStatus() == Plugin_Running
  1387 					  || pOther->GetStatus() == Plugin_Paused)
  1388 					 && pOther != pPlugin)
  1389 			{
  1390 				for (size_t i = 0; i < pPlugin->m_fakes.length(); i++)
  1391 					g_ShareSys.BindNativeToPlugin(pOther, pPlugin->m_fakes[i]);
  1392 			}
  1393 		}
  1394 	}
  1395 
  1396 	/* Go through our libraries and tell other plugins they're added */
  1397 	List<String>::iterator s_iter;
  1398 	for (s_iter = pPlugin->m_Libraries.begin();
  1399 		s_iter != pPlugin->m_Libraries.end();
  1400 		s_iter++)
  1401 	{
  1402 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Added);
  1403 	}
  1404 
  1405 	/* :TODO: optimize? does this even matter? */
  1406 	pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
  1407 
  1408 	return true;
  1409 }
  1410 
  1411 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
  1412 {
  1413 	assert(pPlugin->GetBaseContext() != NULL);
  1414 
  1415 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1416 
  1417 	List<String>::iterator lib_iter;
  1418 	List<String>::iterator req_iter;
  1419 	List<CPlugin *>::iterator pl_iter;
  1420 	CPlugin *pl;
  1421 	for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
  1422 	{
  1423 		bool found = false;
  1424 		for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
  1425 		{
  1426 			pl = (*pl_iter);
  1427 			for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
  1428 			{
  1429 				if ((*req_iter) == (*lib_iter))
  1430 				{
  1431 					found = true;
  1432 				}
  1433 			}
  1434 		}
  1435 		if (!found)
  1436 		{
  1437 			pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
  1438 			return;
  1439 		}
  1440 	}
  1441 
  1442 	/* Find any unbound natives
  1443 	 * Right now, these are not allowed
  1444 	 */
  1445 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1446 	uint32_t num = pContext->GetNativesNum();
  1447 	sp_native_t *native;
  1448 	for (unsigned int i=0; i<num; i++)
  1449 	{
  1450 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1451 		{
  1452 			break;
  1453 		}
  1454 		if (native->status == SP_NATIVE_UNBOUND
  1455 			&& native->name[0] != '@'
  1456 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1457 		{
  1458 			pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
  1459 			return;
  1460 		}
  1461 	}
  1462 
  1463 	if (pPlugin->GetStatus() == Plugin_Error)
  1464 	{
  1465 		/* If we got here, all natives are okay again! */
  1466 		pPlugin->m_status = Plugin_Running;
  1467 		if (pPlugin->m_pRuntime->IsPaused())
  1468 		{
  1469 			pPlugin->m_pRuntime->SetPauseState(false);
  1470 			_SetPauseState(pPlugin, false);
  1471 		}
  1472 	}
  1473 }
  1474 
  1475 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
  1476 {
  1477 	CPlugin *pPlugin = (CPlugin *)plugin;
  1478 
  1479 	/* This prevents removal during insertion or anything else weird */
  1480 	if (m_plugins.find(pPlugin) == m_plugins.end())
  1481 	{
  1482 		return false;
  1483 	}
  1484 
  1485 	IPluginContext *pContext = plugin->GetBaseContext();
  1486 	if (pContext != NULL && pContext->IsInExec())
  1487 	{
  1488 		char buffer[255];
  1489 		smcore.Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
  1490 		engine->ServerCommand(buffer);
  1491 		return false;
  1492 	}
  1493 
  1494 	/* Remove us from the lookup table and linked list */
  1495 	m_plugins.remove(pPlugin);
  1496 	m_LoadLookup.remove(pPlugin->m_filename);
  1497 
  1498 	/* Go through our libraries and tell other plugins they're gone */
  1499 	List<String>::iterator s_iter;
  1500 	for (s_iter = pPlugin->m_Libraries.begin();
  1501 		 s_iter != pPlugin->m_Libraries.end();
  1502 		 s_iter++)
  1503 	{
  1504 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Removed);
  1505 	}
  1506 
  1507 	List<IPluginsListener *>::iterator iter;
  1508 	IPluginsListener *pListener;
  1509 
  1510 	if (pPlugin->GetStatus() <= Plugin_Error)
  1511 	{
  1512 		/* Notify plugin */
  1513 		pPlugin->Call_OnPluginEnd();
  1514 
  1515 		/* Notify listeners of unloading */
  1516 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1517 		{
  1518 			pListener = (*iter);
  1519 			pListener->OnPluginUnloaded(pPlugin);
  1520 		}
  1521 	}
  1522 
  1523 	pPlugin->DropEverything();
  1524 
  1525 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1526 	{
  1527 		/* Notify listeners of destruction */
  1528 		pListener = (*iter);
  1529 		pListener->OnPluginDestroyed(pPlugin);
  1530 	}
  1531 	
  1532 	/* Tell the plugin to delete itself */
  1533 	delete pPlugin;
  1534 
  1535 	return true;
  1536 }
  1537 
  1538 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
  1539 {
  1540 	IPlugin *pPlugin;
  1541 	IPluginContext *pContext;
  1542 
  1543 	pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
  1544 
  1545 	if (pContext->GetKey(2, (void **)&pPlugin))
  1546 	{
  1547 		return pPlugin;
  1548 	}
  1549 
  1550 	return NULL;
  1551 }
  1552 
  1553 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
  1554 {
  1555 	return (CPlugin *)FindPluginByContext(ctx);
  1556 }
  1557 
  1558 unsigned int CPluginManager::GetPluginCount()
  1559 {
  1560 	return m_plugins.size();
  1561 }
  1562 
  1563 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
  1564 {
  1565 	m_listeners.push_back(listener);
  1566 }
  1567 
  1568 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
  1569 {
  1570 	m_listeners.remove(listener);
  1571 }
  1572 
  1573 IPluginIterator *CPluginManager::GetPluginIterator()
  1574 {
  1575 	if (m_iters.empty())
  1576 	{
  1577 		return new CPluginIterator(&m_plugins);
  1578 	} else {
  1579 		CPluginIterator *iter = m_iters.front();
  1580 		m_iters.pop();
  1581 		iter->Reset();
  1582 		return iter;
  1583 	}
  1584 }
  1585 
  1586 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1587 {
  1588 	m_iters.push(iter);
  1589 }
  1590 
  1591 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1592 {
  1593 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1594 	size_t alias_len = 0;
  1595 	size_t local_len = 0;
  1596 
  1597 	const char *ptr = alias;
  1598 	unsigned int alias_explicit_paths = 0;
  1599 	unsigned int alias_path_end = 0;
  1600 	while (*ptr != '\0')
  1601 	{
  1602 		if (*ptr == '\\' || *ptr == '/')
  1603 		{
  1604 			alias_explicit_paths++;
  1605 			alias_path_end = alias_len;
  1606 		}
  1607 		alias_len++;
  1608 		ptr++;
  1609 	}
  1610 
  1611 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1612 	{
  1613 		/* Trailing slash is totally invalid here */
  1614 		return false;
  1615 	}
  1616 
  1617 	ptr = localpath;
  1618 	unsigned int local_explicit_paths = 0;
  1619 	unsigned int local_path_end = 0;
  1620 	while (*ptr != '\0')
  1621 	{
  1622 		if (*ptr == '\\' || *ptr == '/')
  1623 		{
  1624 			local_explicit_paths++;
  1625 			local_path_end = local_len;
  1626 		}
  1627 		local_len++;
  1628 		ptr++;
  1629 	}
  1630 
  1631 	/* If the alias has more explicit paths than the real path,
  1632 	 * no match will be possible.
  1633 	 */
  1634 	if (alias_explicit_paths > local_explicit_paths)
  1635 	{
  1636 		return false;
  1637 	}
  1638 
  1639 	if (alias_explicit_paths)
  1640 	{
  1641 		/* We need to find if the paths match now.  For example, these should all match:
  1642 		 * csdm     csdm
  1643 		 * csdm     optional/csdm
  1644 		 * csdm/ban optional/crab/csdm/ban
  1645 		*/
  1646 		const char *aliasptr = alias;
  1647 		const char *localptr = localpath;
  1648 		bool match = true;
  1649 		do
  1650 		{
  1651 			if (*aliasptr != *localptr)
  1652 			{
  1653 				/* We have to knock one path off */
  1654 				local_explicit_paths--;
  1655 				if (alias_explicit_paths > local_explicit_paths)
  1656 				{
  1657 					/* Skip out if we're gonna have an impossible match */
  1658 					return false;
  1659 				}
  1660 				/* Eat up localptr tokens until we get a result */
  1661 				while (((localptr - localpath) < (int)local_path_end)
  1662 					&& *localptr != '/'
  1663 					&& *localptr != '\\')
  1664 				{
  1665 					localptr++;
  1666 				}
  1667 				/* Check if we hit the end of our searchable area.
  1668 				 * This probably isn't possible because of the path 
  1669 				 * count check, but it's a good idea anyway.
  1670 				 */
  1671 				if ((localptr - localpath) >= (int)local_path_end)
  1672 				{
  1673 					return false;
  1674 				} else {
  1675 					/* Consume the slash token */
  1676 					localptr++;
  1677 				}
  1678 				/* Reset the alias pointer so we can continue consuming */
  1679 				aliasptr = alias;
  1680 				match = false;
  1681 				continue;
  1682 			}
  1683 			/* Note:
  1684 			 * This is safe because if localptr terminates early, aliasptr will too
  1685 			 */
  1686 			do
  1687 			{
  1688 				/* We should never reach the end of the string because of this check. */
  1689 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1690 				bool localend = (localptr - localpath) > (int)local_path_end;
  1691 				if (aliasend || localend)
  1692 				{
  1693 					if (aliasend && localend)
  1694 					{
  1695 						/* we matched, and we can break out now */
  1696 						match = true;
  1697 						break;
  1698 					}
  1699 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1700 					match = false;
  1701 					break;
  1702 				}
  1703 
  1704 				/* If we got here, it's safe to compare the next two tokens */
  1705 				if (*localptr != *aliasptr)
  1706 				{
  1707 					match = false;
  1708 					break;
  1709 				}
  1710 				localptr++;
  1711 				aliasptr++;
  1712 			} while (true);
  1713 		} while (!match);
  1714 	}
  1715 
  1716 	/* If we got here, it's time to compare filenames */
  1717 	const char *aliasptr = alias;
  1718 	const char *localptr = localpath;
  1719 
  1720 	if (alias_explicit_paths)
  1721 	{
  1722 		aliasptr = &alias[alias_path_end + 1];
  1723 	}
  1724 
  1725 	if (local_explicit_paths)
  1726 	{
  1727 		localptr = &localpath[local_path_end + 1];
  1728 	}
  1729 
  1730 	while (true)
  1731 	{
  1732 		if (*aliasptr == '*')
  1733 		{
  1734 			/* First, see if this is the last character */
  1735 			if ((unsigned)(aliasptr - alias) == alias_len - 1)
  1736 			{
  1737 				/* If so, there's no need to match anything else */
  1738 				return true;
  1739 			}
  1740 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1741 			 * Note that we only need to search up to the next asterisk.
  1742 			 */
  1743 			aliasptr++;
  1744 			bool match = true;
  1745 			const char *local_orig = localptr;
  1746 			do
  1747 			{
  1748 				match = true;
  1749 				while (*aliasptr != '\0' && *aliasptr != '*')
  1750 				{
  1751 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1752 					if (*aliasptr != *localptr)
  1753 					{
  1754 						match = false;
  1755 						break;
  1756 					}
  1757 					aliasptr++;
  1758 					localptr++;
  1759 				}
  1760 				if (!match)
  1761 				{
  1762 					/* If we didn't get a match, we need to advance the search stream.
  1763 					 * This will let us skip tokens while still searching for another match.
  1764 					 */
  1765 					localptr = ++local_orig;
  1766 					/* Make sure we don't go out of bounds */
  1767 					if (*localptr == '\0')
  1768 					{
  1769 						break;
  1770 					}
  1771 				}
  1772 			} while (!match);
  1773 
  1774 			if (!match)
  1775 			{
  1776 				return false;
  1777 			} else {
  1778 				/* If we got a match, move on to the next token */
  1779 				continue;
  1780 			}
  1781 		} else if (*aliasptr == '\0') {
  1782 			if (*localptr == '\0'
  1783 				||
  1784 				strcmp(localptr, ".smx") == 0)
  1785 			{
  1786 				return true;
  1787 			} else {
  1788 				return false;
  1789 			}
  1790 		} else if (*aliasptr != *localptr) {
  1791 			return false;
  1792 		}
  1793 		aliasptr++;
  1794 		localptr++;
  1795 	}
  1796 
  1797 	return true;
  1798 }
  1799 
  1800 bool CPluginManager::IsLateLoadTime() const
  1801 {
  1802 	return (m_AllPluginsLoaded || !smcore.IsMapLoading());
  1803 }
  1804 
  1805 void CPluginManager::OnSourceModAllInitialized()
  1806 {
  1807 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1808 
  1809 	HandleAccess sec;
  1810 	handlesys->InitAccessDefaults(NULL, &sec);
  1811 
  1812 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1813 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1814 
  1815 	g_PluginType = handlesys->CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1816 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1817 
  1818 	rootmenu->AddRootConsoleCommand("plugins", "Manage Plugins", this);
  1819 
  1820 	g_ShareSys.AddInterface(NULL, GetOldAPI());
  1821 	
  1822 	m_pOnLibraryAdded = forwardsys->CreateForward("OnLibraryAdded", ET_Ignore, 1, NULL, Param_String);
  1823 	m_pOnLibraryRemoved = forwardsys->CreateForward("OnLibraryRemoved", ET_Ignore, 1, NULL, Param_String);
  1824 }
  1825 
  1826 void CPluginManager::OnSourceModShutdown()
  1827 {
  1828 	rootmenu->RemoveRootConsoleCommand("plugins", this);
  1829 
  1830 	UnloadAll();
  1831 
  1832 	handlesys->RemoveType(g_PluginType, m_MyIdent);
  1833 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1834 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1835 	
  1836 	forwardsys->ReleaseForward(m_pOnLibraryAdded);
  1837 	forwardsys->ReleaseForward(m_pOnLibraryRemoved);
  1838 }
  1839 
  1840 ConfigResult CPluginManager::OnSourceModConfigChanged(const char *key, 
  1841 												 const char *value, 
  1842 												 ConfigSource source, 
  1843 												 char *error, 
  1844 												 size_t maxlength)
  1845 {
  1846 	if (strcmp(key, "BlockBadPlugins") == 0) {
  1847 		if (strcasecmp(value, "yes") == 0)
  1848 		{
  1849 			m_bBlockBadPlugins = true;
  1850 		} else if (strcasecmp(value, "no") == 0) {
  1851 			m_bBlockBadPlugins = false;
  1852 		} else {
  1853 			smcore.Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
  1854 			return ConfigResult_Reject;
  1855 		}
  1856 		return ConfigResult_Accept;
  1857 	}
  1858 	return ConfigResult_Ignore;
  1859 }
  1860 
  1861 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1862 {
  1863 	/* We don't care about the internal object, actually */
  1864 }
  1865 
  1866 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
  1867 {
  1868 	*pSize = ((CPlugin *)object)->CalcMemUsage();
  1869 	return true;
  1870 }
  1871 
  1872 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1873 {
  1874 	IPlugin *pPlugin;
  1875 	HandleError _err;
  1876 
  1877 	HandleSecurity sec;
  1878 
  1879 	sec.pOwner = NULL;
  1880 	sec.pIdentity = m_MyIdent;
  1881 
  1882 	if ((_err=handlesys->ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1883 	{
  1884 		pPlugin = NULL;
  1885 	}
  1886 
  1887 	if (err)
  1888 	{
  1889 		*err = _err;
  1890 	}
  1891 
  1892 	return pPlugin;
  1893 }
  1894 
  1895 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1896 {
  1897 	if (num < 1 || num > (int)GetPluginCount())
  1898 	{
  1899 		return NULL;
  1900 	}
  1901 
  1902 	CPlugin *pl;
  1903 	int id = 1;
  1904 
  1905 	SourceHook::List<CPlugin *>::iterator iter;
  1906 	for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
  1907 
  1908 	pl = *iter;
  1909 
  1910 	return pl;
  1911 }
  1912 
  1913 const char *CPluginManager::GetStatusText(PluginStatus st)
  1914 {
  1915 	switch (st)
  1916 	{
  1917 	case Plugin_Running:
  1918 		return "Running";
  1919 	case Plugin_Paused:
  1920 		return "Paused";
  1921 	case Plugin_Error:
  1922 		return "Error";
  1923 	case Plugin_Uncompiled:
  1924 		return "Uncompiled";
  1925 	case Plugin_BadLoad:
  1926 		return "Bad Load";
  1927 	case Plugin_Failed:
  1928 		return "Failed";
  1929 	default:
  1930 		assert(false);
  1931 		return "-";
  1932 	}
  1933 }
  1934 
  1935 static inline bool IS_STR_FILLED(const char *text)
  1936 {
  1937 	return text[0] != '\0';
  1938 }
  1939 
  1940 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
  1941 {
  1942 	int argcount = smcore.Argc(command);
  1943 	if (argcount >= 3)
  1944 	{
  1945 		const char *cmd = smcore.Arg(command, 2);
  1946 		if (strcmp(cmd, "list") == 0)
  1947 		{
  1948 			char buffer[256];
  1949 			unsigned int id = 1;
  1950 			int plnum = GetPluginCount();
  1951 
  1952 			if (!plnum)
  1953 			{
  1954 				rootmenu->ConsolePrint("[SM] No plugins loaded");
  1955 				return;
  1956 			}
  1957 			else
  1958 			{
  1959 				rootmenu->ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
  1960 			}
  1961 
  1962 			CPlugin *pl;
  1963 			SourceHook::List<CPlugin *>::iterator iter;
  1964 			SourceHook::List<CPlugin *> m_FailList;
  1965 
  1966 			for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  1967 			{
  1968 				pl = (*iter);
  1969 				assert(pl->GetStatus() != Plugin_Created);
  1970 				int len = 0;
  1971 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  1972 				if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
  1973 				{
  1974 					len += smcore.Format(buffer, sizeof(buffer), "  %02d <%s>", id, GetStatusText(pl->GetStatus()));
  1975 
  1976 					if (pl->GetStatus() <= Plugin_Error)
  1977 					{
  1978 						/* Plugin has failed to load. */
  1979 						m_FailList.push_back(pl);
  1980 					}
  1981 				}
  1982 				else
  1983 				{
  1984 					len += smcore.Format(buffer, sizeof(buffer), "  %02d", id);
  1985 				}
  1986 				if (pl->GetStatus() < Plugin_Created)
  1987 				{
  1988 					if (pl->IsSilentlyFailed())
  1989 						len += smcore.Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
  1990 					len += smcore.Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  1991 					if (IS_STR_FILLED(info->version))
  1992 					{
  1993 						len += smcore.Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  1994 					}
  1995 					if (IS_STR_FILLED(info->author))
  1996 					{
  1997 						smcore.Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  1998 					}
  1999 				}
  2000 				else
  2001 				{
  2002 					smcore.Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
  2003 				}
  2004 				rootmenu->ConsolePrint("%s", buffer);
  2005 			}
  2006 
  2007 			if (!m_FailList.empty())
  2008 			{
  2009 				rootmenu->ConsolePrint("Load Errors:");
  2010 
  2011 				SourceHook::List<CPlugin *>::iterator _iter;
  2012 
  2013 				CPlugin *pl;
  2014 
  2015 				for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
  2016 				{
  2017 					pl = (CPlugin *)*_iter;
  2018 					rootmenu->ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
  2019 				}
  2020 			}
  2021 
  2022 			return;
  2023 		}
  2024 		else if (strcmp(cmd, "load") == 0)
  2025 		{
  2026 			if (argcount < 4)
  2027 			{
  2028 				rootmenu->ConsolePrint("[SM] Usage: sm plugins load <file>");
  2029 				return;
  2030 			}
  2031 
  2032 			char error[128];
  2033 			bool wasloaded;
  2034 			const char *filename = smcore.Arg(command, 3);
  2035 
  2036 			char pluginfile[256];
  2037 			const char *ext = libsys->GetFileExtension(filename) ? "" : ".smx";
  2038 			g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
  2039 
  2040 			IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
  2041 
  2042 			if (wasloaded)
  2043 			{
  2044 				rootmenu->ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
  2045 				return;
  2046 			}
  2047 
  2048 			if (pl)
  2049 			{
  2050 				rootmenu->ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
  2051 			}
  2052 			else
  2053 			{
  2054 				rootmenu->ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
  2055 			}
  2056 
  2057 			return;
  2058 		}
  2059 		else if (strcmp(cmd, "unload") == 0)
  2060 		{
  2061 			if (argcount < 4)
  2062 			{
  2063 				rootmenu->ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
  2064 				return;
  2065 			}
  2066 
  2067 			CPlugin *pl;
  2068 			char *end;
  2069 			const char *arg = smcore.Arg(command, 3);
  2070 			int id = strtol(arg, &end, 10);
  2071 
  2072 			if (*end == '\0')
  2073 			{
  2074 				pl = GetPluginByOrder(id);
  2075 				if (!pl)
  2076 				{
  2077 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2078 					return;
  2079 				}
  2080 			}
  2081 			else
  2082 			{
  2083 				char pluginfile[256];
  2084 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2085 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2086 
  2087 				if (!m_LoadLookup.retrieve(pluginfile, &pl))
  2088 				{
  2089 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2090 					return;
  2091 				}
  2092 			}
  2093 
  2094 			char name[PLATFORM_MAX_PATH];
  2095 
  2096 			if (pl->GetStatus() < Plugin_Created)
  2097 			{
  2098 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  2099 				smcore.Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2100 			}
  2101 			else
  2102 			{
  2103 				smcore.Format(name, sizeof(name), "%s", pl->GetFilename());
  2104 			}
  2105 
  2106 			if (UnloadPlugin(pl))
  2107 			{
  2108 				rootmenu->ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
  2109 			}
  2110 			else
  2111 			{
  2112 				rootmenu->ConsolePrint("[SM] Failed to unload plugin %s.", name);
  2113 			}
  2114 
  2115 			return;
  2116 		}
  2117 		else if (strcmp(cmd, "unload_all") == 0)
  2118 		{
  2119 			g_PluginSys.UnloadAll();
  2120 			rootmenu->ConsolePrint("[SM] All plugins have been unloaded.");
  2121 			return;
  2122 		}
  2123 		else if (strcmp(cmd, "load_lock") == 0)
  2124 		{
  2125 			if (m_LoadingLocked)
  2126 			{
  2127 				rootmenu->ConsolePrint("[SM] There is already a loading lock in effect.");
  2128 			}
  2129 			else
  2130 			{
  2131 				m_LoadingLocked = true;
  2132 				rootmenu->ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
  2133 			}
  2134 			return;
  2135 		}
  2136 		else if (strcmp(cmd, "load_unlock") == 0)
  2137 		{
  2138 			if (m_LoadingLocked)
  2139 			{
  2140 				m_LoadingLocked = false;
  2141 				rootmenu->ConsolePrint("[SM] The loading lock is no longer in effect.");
  2142 			}
  2143 			else
  2144 			{
  2145 				rootmenu->ConsolePrint("[SM] There was no loading lock in effect.");
  2146 			}
  2147 			return;
  2148 		}
  2149 		else if (strcmp(cmd, "info") == 0)
  2150 		{
  2151 			if (argcount < 4)
  2152 			{
  2153 				rootmenu->ConsolePrint("[SM] Usage: sm plugins info <#>");
  2154 				return;
  2155 			}
  2156 
  2157 			CPlugin *pl;
  2158 			char *end;
  2159 			const char *arg = smcore.Arg(command, 3);
  2160 			int id = strtol(arg, &end, 10);
  2161 
  2162 			if (*end == '\0')
  2163 			{
  2164 				pl = GetPluginByOrder(id);
  2165 				if (!pl)
  2166 				{
  2167 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2168 					return;
  2169 				}
  2170 			}
  2171 			else
  2172 			{
  2173 				char pluginfile[256];
  2174 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2175 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2176 
  2177 				if (!m_LoadLookup.retrieve(pluginfile, &pl))
  2178 				{
  2179 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2180 					return;
  2181 				}
  2182 			}
  2183 
  2184 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2185 
  2186 			rootmenu->ConsolePrint("  Filename: %s", pl->GetFilename());
  2187 			if (pl->GetStatus() <= Plugin_Error)
  2188 			{
  2189 				if (IS_STR_FILLED(info->name))
  2190 				{
  2191 					if (IS_STR_FILLED(info->description))
  2192 					{
  2193 						rootmenu->ConsolePrint("  Title: %s (%s)", info->name, info->description);
  2194 					} else {
  2195 						rootmenu->ConsolePrint("  Title: %s", info->name);
  2196 					}
  2197 				}
  2198 				if (IS_STR_FILLED(info->author))
  2199 				{
  2200 					rootmenu->ConsolePrint("  Author: %s", info->author);
  2201 				}
  2202 				if (IS_STR_FILLED(info->version))
  2203 				{
  2204 					rootmenu->ConsolePrint("  Version: %s", info->version);
  2205 				}
  2206 				if (IS_STR_FILLED(info->url))
  2207 				{
  2208 					rootmenu->ConsolePrint("  URL: %s", info->url);
  2209 				}
  2210 				if (pl->GetStatus() == Plugin_Error)
  2211 				{
  2212 					rootmenu->ConsolePrint("  Error: %s", pl->m_errormsg);
  2213 				}
  2214 				else
  2215 				{
  2216 					if (pl->GetStatus() == Plugin_Running)
  2217 					{
  2218 						rootmenu->ConsolePrint("  Status: running");
  2219 					}
  2220 					else
  2221 					{
  2222 						rootmenu->ConsolePrint("  Status: not running");
  2223 					}
  2224 
  2225 					const char *typestr = "";
  2226 					switch (pl->GetType())
  2227 					{
  2228 					case PluginType_MapUpdated:
  2229 						typestr = "Map Change if Updated";
  2230 						break;
  2231 					case PluginType_MapOnly:
  2232 						typestr = "Map Change";
  2233 						break;
  2234 					case PluginType_Private:
  2235 					case PluginType_Global:
  2236 						typestr = "Never";
  2237 						break;
  2238 					}
  2239 
  2240 					rootmenu->ConsolePrint("  Reloads: %s", typestr);
  2241 				}
  2242 				if (pl->m_FileVersion >= 3)
  2243 				{
  2244 					rootmenu->ConsolePrint("  Timestamp: %s", pl->m_DateTime);
  2245 				}
  2246 				
  2247 				unsigned char *pCodeHash = pl->m_pRuntime->GetCodeHash();
  2248 				unsigned char *pDataHash = pl->m_pRuntime->GetDataHash();
  2249 				
  2250 				char combinedHash[33];
  2251 				for (int i = 0; i < 16; i++)
  2252 					smcore.Format(combinedHash + (i * 2), 3, "%02x", pCodeHash[i] ^ pDataHash[i]);
  2253 				
  2254 				rootmenu->ConsolePrint("  Hash: %s", combinedHash);
  2255 			}
  2256 			else
  2257 			{
  2258 				rootmenu->ConsolePrint("  Load error: %s", pl->m_errormsg);
  2259 				if (pl->GetStatus() < Plugin_Created)
  2260 				{
  2261 					rootmenu->ConsolePrint("  File info: (title \"%s\") (version \"%s\")", 
  2262 											info->name ? info->name : "<none>",
  2263 											info->version ? info->version : "<none>");
  2264 					if (IS_STR_FILLED(info->url))
  2265 					{
  2266 						rootmenu->ConsolePrint("  File URL: %s", info->url);
  2267 					}
  2268 				}
  2269 			}
  2270 
  2271 			return;
  2272 		}
  2273 		else if (strcmp(cmd, "refresh") == 0)
  2274 		{
  2275 			smcore.DoGlobalPluginLoads();
  2276 			rootmenu->ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
  2277 			return;
  2278 		}
  2279 		else if (strcmp(cmd, "reload") == 0)
  2280 		{
  2281 			if (argcount < 4)
  2282 			{
  2283 				rootmenu->ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
  2284 				return;
  2285 			}
  2286 
  2287 			CPlugin *pl;
  2288 			char *end;
  2289 			const char *arg = smcore.Arg(command, 3);
  2290 			int id = strtol(arg, &end, 10);
  2291 
  2292 			if (*end == '\0')
  2293 			{
  2294 				pl = GetPluginByOrder(id);
  2295 				if (!pl)
  2296 				{
  2297 					rootmenu->ConsolePrint("[SM] Plugin index %d not found.", id);
  2298 					return;
  2299 				}
  2300 			}
  2301 			else
  2302 			{
  2303 				char pluginfile[256];
  2304 				const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2305 				g_pSM->BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2306 
  2307 				if (!m_LoadLookup.retrieve(pluginfile, &pl))
  2308 				{
  2309 					rootmenu->ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2310 					return;
  2311 				}
  2312 			}
  2313 
  2314 			char name[PLATFORM_MAX_PATH];
  2315 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2316 			if (pl->GetStatus() <= Plugin_Paused) 
  2317 				strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2318 			else
  2319 				strcpy(name, pl->GetFilename());
  2320 
  2321 			if (ReloadPlugin(pl))
  2322 			{
  2323 				rootmenu->ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
  2324 			}
  2325 			else
  2326 			{
  2327 				rootmenu->ConsolePrint("[SM] Failed to reload plugin %s.", name);
  2328 			}
  2329 
  2330 			return;
  2331 		}
  2332 	}
  2333 
  2334 	/* Draw the main menu */
  2335 	rootmenu->ConsolePrint("SourceMod Plugins Menu:");
  2336 	rootmenu->DrawGenericOption("info", "Information about a plugin");
  2337 	rootmenu->DrawGenericOption("list", "Show loaded plugins");
  2338 	rootmenu->DrawGenericOption("load", "Load a plugin");
  2339 	rootmenu->DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
  2340 	rootmenu->DrawGenericOption("load_unlock", "Re-enables plugin loading");
  2341 	rootmenu->DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
  2342 	rootmenu->DrawGenericOption("reload", "Reloads a plugin");
  2343 	rootmenu->DrawGenericOption("unload", "Unload a plugin");
  2344 	rootmenu->DrawGenericOption("unload_all", "Unloads all plugins");
  2345 }
  2346 
  2347 bool CPluginManager::ReloadPlugin(CPlugin *pl)
  2348 {
  2349 	List<CPlugin *>::iterator iter;
  2350 	char filename[PLATFORM_MAX_PATH];
  2351 	bool wasloaded;
  2352 	PluginType ptype;
  2353 	IPlugin *newpl;
  2354 	int id = 1;
  2355 
  2356 	strcpy(filename, pl->m_filename);
  2357 	ptype = pl->GetType();
  2358 
  2359 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
  2360 	{
  2361 		if ((*iter) == pl)
  2362 		{
  2363 			break;
  2364 		}
  2365 	}
  2366 
  2367 	if (!UnloadPlugin(pl))
  2368 	{
  2369 		return false;
  2370 	}
  2371 	if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
  2372 	{
  2373 		return false;
  2374 	}
  2375 
  2376 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2377 	{
  2378 		if ((*iter) == (CPlugin *)newpl)
  2379 		{
  2380 			m_plugins.erase(iter);
  2381 			break;
  2382 		}
  2383 	}
  2384 
  2385 	int i;
  2386 	for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
  2387 	{
  2388 	}
  2389 	m_plugins.insert(iter, (CPlugin *)newpl);
  2390 
  2391 	return true;
  2392 }
  2393 
  2394 void CPluginManager::RefreshAll()
  2395 {
  2396 	/* If we're in a load lock, just skip this whole bit. */
  2397 	if (m_LoadingLocked)
  2398 	{
  2399 		return;
  2400 	}
  2401 
  2402 	List<CPlugin *>::iterator iter;
  2403 	List<CPlugin *> tmp_list = m_plugins;
  2404 	CPlugin *pl;
  2405 	time_t t;
  2406 
  2407 	for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
  2408 	{
  2409 		pl = (*iter);
  2410 		if (pl->GetType() ==  PluginType_MapOnly)
  2411 		{
  2412 			UnloadPlugin((IPlugin *)pl);
  2413 		}
  2414 		else if (pl->GetType() == PluginType_MapUpdated)
  2415 		{
  2416 			t = pl->GetFileTimeStamp();
  2417 			if (!t || t > pl->GetTimeStamp())
  2418 			{
  2419 				pl->SetTimeStamp(t);
  2420 				UnloadPlugin((IPlugin *)pl);
  2421 			}
  2422 		}
  2423 	}
  2424 }
  2425 
  2426 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
  2427 {
  2428 	List<IPluginsListener *>::iterator iter;
  2429 	IPluginsListener *pListener;
  2430 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  2431 	{
  2432 		pListener = (*iter);
  2433 		pListener->OnPluginPauseChange(pl, paused);
  2434 	}	
  2435 }
  2436 
  2437 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
  2438 {
  2439 	List<CPlugin *>::iterator iter;
  2440 	CPlugin *pPlugin;
  2441 	IPluginFunction *pFunction;
  2442 
  2443 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2444 	{
  2445 		pPlugin = (*iter);
  2446 
  2447 		if (pPlugin->GetStatus() <= Plugin_Paused)
  2448 		{
  2449 			pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
  2450 
  2451 			if (pFunction)
  2452 			{
  2453 				pForward->AddFunction(pFunction);
  2454 			}
  2455 		}
  2456 	}
  2457 }
  2458 
  2459 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
  2460 {
  2461 	if (pToken->type != g_PluginIdent)
  2462 	{
  2463 		return NULL;
  2464 	}
  2465 
  2466 	return (CPlugin *)(pToken->ptr);
  2467 }
  2468 
  2469 void CPluginManager::OnLibraryAction(const char *lib, LibraryAction action)
  2470 {
  2471 	switch (action)
  2472 	{
  2473 	case LibraryAction_Removed:
  2474 		m_pOnLibraryRemoved->PushString(lib);
  2475 		m_pOnLibraryRemoved->Execute(NULL);
  2476 		break;
  2477 	case LibraryAction_Added:
  2478 		m_pOnLibraryAdded->PushString(lib);
  2479 		m_pOnLibraryAdded->Execute(NULL);
  2480 		break;
  2481 	}
  2482 }
  2483 
  2484 bool CPluginManager::LibraryExists(const char *lib)
  2485 {
  2486 	List<CPlugin *>::iterator iter;
  2487 
  2488 	for (iter=m_plugins.begin();
  2489 		 iter!=m_plugins.end();
  2490 		 iter++)
  2491 	{
  2492 		CPlugin *pl = (*iter);
  2493 		if (pl->GetStatus() != Plugin_Running)
  2494 		{
  2495 			continue;
  2496 		}
  2497 		List<String>::iterator s_iter;
  2498 		for (s_iter = pl->m_Libraries.begin();
  2499 			 s_iter != pl->m_Libraries.end();
  2500 			 s_iter++)
  2501 		{
  2502 			if ((*s_iter).compare(lib) == 0)
  2503 			{
  2504 				return true;
  2505 			}
  2506 		}
  2507 	}
  2508 
  2509 	return false;
  2510 }
  2511 
  2512 void CPluginManager::AllPluginsLoaded()
  2513 {
  2514 	List<CPlugin *>::iterator iter;
  2515 	CPlugin *pl;
  2516 
  2517 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2518 	{
  2519 		pl = (*iter);
  2520 		pl->Call_OnAllPluginsLoaded();
  2521 	}
  2522 }
  2523 
  2524 void CPluginManager::UnloadAll()
  2525 {
  2526 	List<CPlugin *>::iterator iter;
  2527 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  2528 	{
  2529 		UnloadPlugin((*iter));
  2530 	}
  2531 }
  2532 
  2533 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
  2534 {
  2535 	int id = 1;
  2536 	List<CPlugin *>::iterator iter;
  2537 
  2538 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  2539 	{
  2540 		if ((*iter) == pl)
  2541 		{
  2542 			return id;
  2543 		}
  2544 	}
  2545 
  2546 	return -1;
  2547 }
  2548 
  2549 SMPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
  2550 {
  2551 	int id;
  2552 	char *end;
  2553 	CPlugin *pl;
  2554 	
  2555 	id = strtol(arg, &end, 10);
  2556 
  2557 	if (*end == '\0')
  2558 	{
  2559 		pl = GetPluginByOrder(id);
  2560 		if (!pl)
  2561 		{
  2562 			return NULL;
  2563 		}
  2564 	}
  2565 	else
  2566 	{
  2567 		char pluginfile[256];
  2568 		const char *ext = libsys->GetFileExtension(arg) ? "" : ".smx";
  2569 		smcore.Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2570 
  2571 		if (!m_LoadLookup.retrieve(pluginfile, &pl))
  2572 			return NULL;
  2573 	}
  2574 
  2575 	return pl;
  2576 }
  2577 
  2578 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
  2579 {
  2580 	SyncMaxClients(newvalue);
  2581 }
  2582 
  2583 void CPluginManager::SyncMaxClients(int max_clients)
  2584 {
  2585 	List<CPlugin *>::iterator iter;
  2586 
  2587 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2588 	{
  2589 		(*iter)->SyncMaxClients(max_clients);
  2590 	}
  2591 }
  2592 
  2593 const CVector<SMPlugin *> *CPluginManager::ListPlugins()
  2594 {
  2595 	CVector<SMPlugin *> *list = new CVector<SMPlugin *>();
  2596 
  2597 	for (List<CPlugin *>::iterator iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2598 		list->push_back((*iter));
  2599 
  2600 	return list;
  2601 }
  2602 
  2603 void CPluginManager::FreePluginList(const CVector<SMPlugin *> *list)
  2604 {
  2605 	delete const_cast<CVector<SMPlugin *> *>(list);
  2606 }
  2607 
  2608 class OldPluginAPI : public IPluginManager
  2609 {
  2610 public:
  2611 	IPlugin *LoadPlugin(const char *path, 
  2612 						bool debug,
  2613 						PluginType type,
  2614 						char error[],
  2615 						size_t maxlength,
  2616 						bool *wasloaded)
  2617 	{
  2618 		return g_PluginSys.LoadPlugin(path, debug, type, error, maxlength, wasloaded);
  2619 	}
  2620 
  2621 	bool UnloadPlugin(IPlugin *plugin)
  2622 	{
  2623 		return g_PluginSys.UnloadPlugin(plugin);
  2624 	}
  2625 
  2626 	IPlugin *FindPluginByContext(const sp_context_t *ctx)
  2627 	{
  2628 		return g_PluginSys.FindPluginByContext(ctx);
  2629 	}
  2630 
  2631 	unsigned int GetPluginCount()
  2632 	{
  2633 		return g_PluginSys.GetPluginCount();
  2634 	}
  2635 
  2636 	IPluginIterator *GetPluginIterator()
  2637 	{
  2638 		return g_PluginSys.GetPluginIterator();
  2639 	}
  2640 
  2641 	void AddPluginsListener(IPluginsListener *listener)
  2642 	{
  2643 		g_PluginSys.AddPluginsListener(listener);
  2644 	}
  2645 
  2646 	void RemovePluginsListener(IPluginsListener *listener)
  2647 	{
  2648 		g_PluginSys.RemovePluginsListener(listener);
  2649 	}
  2650 
  2651 	IPlugin *PluginFromHandle(Handle_t handle, HandleError *err)
  2652 	{
  2653 		return g_PluginSys.PluginFromHandle(handle, err);
  2654 	}
  2655 };
  2656 
  2657 static OldPluginAPI sOldPluginAPI;
  2658 
  2659 IPluginManager *CPluginManager::GetOldAPI()
  2660 {
  2661 	return &sOldPluginAPI;
  2662 }