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