core/PluginSys.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Sat Mar 16 13:31:35 2013 -0400 (2013-03-16)
changeset 3813 bf1faf4a16c9
parent 3790 98b099a406d2
permissions -rw-r--r--
Added repeated field handling to PbRead* natives. Deprecate PbReadRepeated* (bug 5633, r=asherkin).
     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 	m_AllPluginsLoaded = false;
   827 	LoadPluginsFromDir(basedir, NULL);
   828 }
   829 
   830 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   831 {
   832 	char base_path[PLATFORM_MAX_PATH];
   833 
   834 	/* Form the current path to start reading from */
   835 	if (localpath == NULL)
   836 	{
   837 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
   838 	} else {
   839 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   840 	}
   841 
   842 	IDirectory *dir = g_LibSys.OpenDirectory(base_path);
   843 
   844 	if (!dir)
   845 	{
   846 		char error[256];
   847 		g_LibSys.GetPlatformError(error, sizeof(error));
   848 		g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
   849 		g_Logger.LogError("[SM] Platform returned error: %s", error);
   850 		return;
   851 	}
   852 
   853 	while (dir->MoreFiles())
   854 	{
   855 		if (dir->IsEntryDirectory() 
   856 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   857 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   858 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   859 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   860 		{
   861 			char new_local[PLATFORM_MAX_PATH];
   862 			if (localpath == NULL)
   863 			{
   864 				/* If no path yet, don't add a former slash */
   865 				UTIL_Format(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   866 			} else {
   867 				g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   868 			}
   869 			LoadPluginsFromDir(basedir, new_local);
   870 		} else if (dir->IsEntryFile()) {
   871 			const char *name = dir->GetEntryName();
   872 			size_t len = strlen(name);
   873 			if (len >= 4
   874 				&& strcmp(&name[len-4], ".smx") == 0)
   875 			{
   876 				/* If the filename matches, load the plugin */
   877 				char plugin[PLATFORM_MAX_PATH];
   878 				if (localpath == NULL)
   879 				{
   880 					UTIL_Format(plugin, sizeof(plugin), "%s", name);
   881 				} else {
   882 					g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   883 				}
   884 				LoadAutoPlugin(plugin);
   885 			}
   886 		}
   887 		dir->NextEntry();
   888 	}
   889 	g_LibSys.CloseDirectory(dir);
   890 }
   891 
   892 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
   893 {
   894 	if (m_LoadingLocked)
   895 	{
   896 		return LoadRes_NeverLoad;
   897 	}
   898 
   899 	int err;
   900 
   901 	/**
   902 	 * Does this plugin already exist?
   903 	 */
   904 	CPlugin *pPlugin;
   905 	if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
   906 	{
   907 		/* Check to see if we should try reloading it */
   908 		if (pPlugin->GetStatus() == Plugin_BadLoad
   909 			|| pPlugin->GetStatus() == Plugin_Error
   910 			|| pPlugin->GetStatus() == Plugin_Failed)
   911 		{
   912 			UnloadPlugin(pPlugin);
   913 		}
   914 		else
   915 		{
   916 			if (_plugin)
   917 			{
   918 				*_plugin = pPlugin;
   919 			}
   920 			return LoadRes_AlreadyLoaded;
   921 		}
   922 	}
   923 
   924 	pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
   925 
   926 	assert(pPlugin != NULL);
   927 
   928 	pPlugin->m_type = PluginType_MapUpdated;
   929 
   930 	ICompilation *co = NULL;
   931 
   932 	if (pPlugin->m_status == Plugin_Uncompiled)
   933 	{
   934 		co = g_pSourcePawn2->StartCompilation();
   935 	}
   936 
   937 	/* Do the actual compiling */
   938 	if (co != NULL)
   939 	{
   940 		char fullpath[PLATFORM_MAX_PATH];
   941 		g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
   942 
   943 		pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
   944 		if (pPlugin->m_pRuntime == NULL)
   945 		{
   946 			if (error)
   947 			{
   948 				UTIL_Format(error, 
   949 					maxlength, 
   950 					"Unable to load plugin (error %d: %s)", 
   951 					err, 
   952 					g_pSourcePawn2->GetErrorString(err));
   953 			}
   954 			pPlugin->m_status = Plugin_BadLoad;
   955 		}
   956 		else
   957 		{
   958 			if (pPlugin->UpdateInfo())
   959 			{
   960 				pPlugin->m_status = Plugin_Created;
   961 			}
   962 			else
   963 			{
   964 				if (error)
   965 				{
   966 					UTIL_Format(error, maxlength, "%s", pPlugin->m_errormsg);
   967 				}
   968 			}
   969 		}
   970 	}
   971 	
   972 	if (pPlugin->GetStatus() == Plugin_Created)
   973 	{
   974 		unsigned char *pCodeHash = pPlugin->m_pRuntime->GetCodeHash();
   975 		
   976 		char codeHashBuf[40];
   977 		UTIL_Format(codeHashBuf, 40, "plugin_");
   978 		for (int i = 0; i < 16; i++)
   979 			UTIL_Format(codeHashBuf + 7 + (i * 2), 3, "%02x", pCodeHash[i]);
   980 		
   981 		const char *bulletinUrl = g_pGameConf->GetKeyValue(codeHashBuf);
   982 		if (bulletinUrl != NULL)
   983 		{
   984 			if (m_bBlockBadPlugins)
   985 			{
   986 				if (error)
   987 				{
   988 					if (bulletinUrl[0] != '\0')
   989 					{
   990 						UTIL_Format(error, maxlength, "Known malware detected and blocked. See %s for more info", bulletinUrl);
   991 					} else {
   992 						UTIL_Format(error, maxlength, "Possible malware or illegal plugin detected and blocked");
   993 					}
   994 				}
   995 				pPlugin->m_status = Plugin_BadLoad;
   996 			} else {
   997 				if (bulletinUrl[0] != '\0')
   998 				{
   999 					g_Logger.LogMessage("%s: Known malware detected. See %s for more info, blocking disabled in core.cfg", pPlugin->GetFilename(), bulletinUrl);
  1000 				} else {
  1001 					g_Logger.LogMessage("%s: Possible malware or illegal plugin detected, blocking disabled in core.cfg", pPlugin->GetFilename());
  1002 				}
  1003 			}
  1004 		}
  1005 	}
  1006 
  1007 	LoadRes loadFailure = LoadRes_Failure;
  1008 	/* Get the status */
  1009 	if (pPlugin->GetStatus() == Plugin_Created)
  1010 	{
  1011 		/* First native pass - add anything from Core */
  1012 		g_ShareSys.BindNativesToPlugin(pPlugin, true);
  1013 		pPlugin->InitIdentity();
  1014 		APLRes result = pPlugin->Call_AskPluginLoad(error, maxlength);  
  1015 		switch (result)
  1016 		{
  1017 		case APLRes_Success:
  1018 			/* Autoload any modules */
  1019 			LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
  1020 			break;
  1021 		case APLRes_Failure:
  1022 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1023 			loadFailure = LoadRes_Failure;
  1024 			break;
  1025 		case APLRes_SilentFailure:
  1026 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1027 			loadFailure = LoadRes_SilentFailure;
  1028 			pPlugin->SetSilentlyFailed(true);
  1029 			break;
  1030 		default:
  1031 			assert(false);
  1032 		}
  1033 	}
  1034 
  1035 	/* Save the time stamp */
  1036 	time_t t = pPlugin->GetFileTimeStamp();
  1037 	pPlugin->SetTimeStamp(t);
  1038 
  1039 	if (_plugin)
  1040 	{
  1041 		*_plugin = pPlugin;
  1042 	}
  1043 
  1044 	return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : loadFailure;
  1045 }
  1046 
  1047 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
  1048 {
  1049 	CPlugin *pl;
  1050 	LoadRes res;
  1051 
  1052 	*wasloaded = false;
  1053 	if ((res=_LoadPlugin(&pl, path, true, type, error, maxlength)) == LoadRes_Failure)
  1054 	{
  1055 		delete pl;
  1056 		return NULL;
  1057 	}
  1058 
  1059 	if (res == LoadRes_AlreadyLoaded)
  1060 	{
  1061 		*wasloaded = true;
  1062 		return pl;
  1063 	}
  1064 
  1065 	if (res == LoadRes_NeverLoad)
  1066 	{
  1067 		if (error)
  1068 		{
  1069 			if (m_LoadingLocked)
  1070 			{
  1071 				UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
  1072 			}
  1073 			else
  1074 			{
  1075 				UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
  1076 			}
  1077 		}
  1078 		return NULL;
  1079 	}
  1080 
  1081 	AddPlugin(pl);
  1082 
  1083 	/* Run second pass if we need to */
  1084 	if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
  1085 	{
  1086 		if (!RunSecondPass(pl, error, maxlength))
  1087 		{
  1088 			UnloadPlugin(pl);
  1089 			return NULL;
  1090 		}
  1091 		pl->Call_OnAllPluginsLoaded();
  1092 	}
  1093 
  1094 	return pl;
  1095 }
  1096 
  1097 void CPluginManager::LoadAutoPlugin(const char *plugin)
  1098 {
  1099 	CPlugin *pl = NULL;
  1100 	LoadRes res;
  1101 	char error[255] = "Unknown error";
  1102 
  1103 	if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
  1104 	{
  1105 		g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, error);
  1106 		pl->SetErrorState(
  1107 			pl->GetStatus() <= Plugin_Created ? Plugin_BadLoad : pl->GetStatus(), 
  1108 			"%s",
  1109 			error);
  1110 	}
  1111 
  1112 	if (res == LoadRes_Successful || res == LoadRes_Failure || res == LoadRes_SilentFailure)
  1113 	{
  1114 		AddPlugin(pl);
  1115 	}
  1116 }
  1117 
  1118 void CPluginManager::AddPlugin(CPlugin *pPlugin)
  1119 {
  1120 	List<IPluginsListener *>::iterator iter;
  1121 	IPluginsListener *pListener;
  1122 
  1123 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1124 	{
  1125 		pListener = (*iter);
  1126 		pListener->OnPluginCreated(pPlugin);
  1127 	}
  1128 
  1129 	m_plugins.push_back(pPlugin);
  1130 	sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
  1131 }
  1132 
  1133 void CPluginManager::LoadAll_SecondPass()
  1134 {
  1135 	List<CPlugin *>::iterator iter;
  1136 	CPlugin *pPlugin;
  1137 
  1138 	char error[256];
  1139 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1140 	{
  1141 		pPlugin = (*iter);
  1142 		if (pPlugin->GetStatus() == Plugin_Loaded)
  1143 		{
  1144 			error[0] = '\0';
  1145 			if (!RunSecondPass(pPlugin, error, sizeof(error)))
  1146 			{
  1147 				g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
  1148 				pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1149 			}
  1150 		}
  1151 	}
  1152 
  1153 	m_AllPluginsLoaded = true;
  1154 }
  1155 
  1156 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
  1157 {
  1158 	struct _pl
  1159 	{
  1160 		cell_t name;
  1161 		cell_t file;
  1162 		cell_t required;
  1163 	} *pl;
  1164 
  1165 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1166 	uint32_t num = pBase->GetPubVarsNum();
  1167 	sp_pubvar_t *pubvar;
  1168 	char *name, *file;
  1169 	char pathfile[PLATFORM_MAX_PATH];
  1170 
  1171 	for (uint32_t i=0; i<num; i++)
  1172 	{
  1173 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1174 		{
  1175 			continue;
  1176 		}
  1177 		if (strncmp(pubvar->name, "__pl_", 5) == 0)
  1178 		{
  1179 			pl = (_pl *)pubvar->offs;
  1180 			if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
  1181 			{
  1182 				continue;
  1183 			}
  1184 			if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
  1185 			{
  1186 				continue;
  1187 			}
  1188 			g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
  1189 			if (strcmp(pathfile, file) == 0)
  1190 			{
  1191 				continue;
  1192 			}
  1193 			if (pl->required == false)
  1194 			{
  1195 				IPluginFunction *pFunc;
  1196 				char buffer[64];
  1197 				UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
  1198 				if ((pFunc=pBase->GetFunctionByName(buffer)))
  1199 				{
  1200 					cell_t res;
  1201 					pFunc->Execute(&res);
  1202 					if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1203 					{
  1204 						if (error)
  1205 						{
  1206 							UTIL_Format(error, maxlength, "Fatal error during initializing plugin load");
  1207 						}
  1208 						return false;
  1209 					}
  1210 				}
  1211 			}
  1212 			else
  1213 			{
  1214 				/* Check that we aren't registering the same library twice */
  1215 				if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
  1216 				{
  1217 					pPlugin->m_RequiredLibs.push_back(name);
  1218 				}
  1219 				else
  1220 				{
  1221 					continue;
  1222 				}
  1223 				List<CPlugin *>::iterator iter;
  1224 				CPlugin *pl;
  1225 				bool found = false;
  1226 				for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1227 				{
  1228 					pl = (*iter);
  1229 					if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
  1230 					{
  1231 						found = true;
  1232 						break;
  1233 					}
  1234 				}
  1235 				if (!found)
  1236 				{
  1237 					if (error)
  1238 					{
  1239 						UTIL_Format(error, maxlength, "Could not find required plugin \"%s\"", name);
  1240 					}
  1241 					return false;
  1242 				}
  1243 			}
  1244 		}
  1245 	}
  1246 
  1247 	return true;
  1248 }
  1249 
  1250 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
  1251 {
  1252 	/* Find any extensions this plugin needs */
  1253 	struct _ext
  1254 	{
  1255 		cell_t name;
  1256 		cell_t file;
  1257 		cell_t autoload;
  1258 		cell_t required;
  1259 	} *ext;
  1260 
  1261 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1262 	uint32_t num = pBase->GetPubVarsNum();
  1263 	sp_pubvar_t *pubvar;
  1264 	IExtension *pExt;
  1265 	char path[PLATFORM_MAX_PATH];
  1266 	char *file, *name;
  1267 	for (uint32_t i=0; i<num; i++)
  1268 	{
  1269 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1270 		{
  1271 			continue;
  1272 		}
  1273 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
  1274 		{
  1275 			ext = (_ext *)pubvar->offs;
  1276 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
  1277 			{
  1278 				continue;
  1279 			}
  1280 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
  1281 			{
  1282 				continue;
  1283 			}
  1284 			if (pass == 1)
  1285 			{
  1286 				/* Attempt to auto-load if necessary */
  1287 				if (ext->autoload)
  1288 				{
  1289 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1290 					bool bErrorOnMissing = ext->required ? true : false;
  1291 					g_Extensions.LoadAutoExtension(path, bErrorOnMissing);
  1292 				}
  1293 			}
  1294 			else if (pass == 2)
  1295 			{
  1296 				/* Is this required? */
  1297 				if (ext->required)
  1298 				{
  1299 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1300 					if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
  1301 					{
  1302 						pExt = g_Extensions.FindExtensionByName(name);
  1303 					}
  1304 					/* :TODO: should we bind to unloaded extensions?
  1305 					 * Currently the extension manager will ignore this.
  1306 					 */
  1307 					if (!pExt || !pExt->IsRunning(NULL, 0))
  1308 					{
  1309 						if (error)
  1310 						{
  1311 							UTIL_Format(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
  1312 						}
  1313 						return false;
  1314 					}
  1315 					else
  1316 					{
  1317 						g_Extensions.BindChildPlugin(pExt, pPlugin);
  1318 					}
  1319 				}
  1320 				else
  1321 				{
  1322 					IPluginFunction *pFunc;
  1323 					char buffer[64];
  1324 					UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
  1325 
  1326 					if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
  1327 					{
  1328 						cell_t res;
  1329 						pFunc->Execute(&res);
  1330 						if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1331 						{
  1332 							if (error)
  1333 							{
  1334 								UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
  1335 							}
  1336 							return false;
  1337 						}
  1338 					}
  1339 				}
  1340 			}
  1341 		}
  1342 	}
  1343 
  1344 	return true;
  1345 }
  1346 
  1347 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
  1348 {
  1349 	/* Second pass for extension requirements */
  1350 	if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
  1351 	{
  1352 		return false;
  1353 	}
  1354 
  1355 	if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
  1356 	{
  1357 		return false;
  1358 	}
  1359 
  1360 	/* Run another binding pass */
  1361 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1362 
  1363 	/* Find any unbound natives. Right now, these are not allowed. */
  1364 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1365 	uint32_t num = pContext->GetNativesNum();
  1366 	sp_native_t *native;
  1367 	for (unsigned int i=0; i<num; i++)
  1368 	{
  1369 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1370 		{
  1371 			break;
  1372 		}
  1373 		if (native->status == SP_NATIVE_UNBOUND
  1374 			&& native->name[0] != '@'
  1375 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1376 		{
  1377 			if (error)
  1378 			{
  1379 				UTIL_Format(error, maxlength, "Native \"%s\" was not found", native->name);
  1380 			}
  1381 			return false;
  1382 		}
  1383 	}
  1384 
  1385 	/* Finish by telling all listeners */
  1386 	List<IPluginsListener *>::iterator iter;
  1387 	IPluginsListener *pListener;
  1388 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1389 	{
  1390 		pListener = (*iter);
  1391 		pListener->OnPluginLoaded(pPlugin);
  1392 	}
  1393 	
  1394 	/* Tell this plugin to finish initializing itself */
  1395 	pPlugin->Call_OnPluginStart();
  1396 
  1397 	/* Now, if we have fake natives, go through all plugins that might need rebinding */
  1398 	if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
  1399 	{
  1400 		List<CPlugin *>::iterator pl_iter;
  1401 		CPlugin *pOther;
  1402 		for (pl_iter = m_plugins.begin();
  1403 			 pl_iter != m_plugins.end();
  1404 			 pl_iter++)
  1405 		{
  1406 			pOther = (*pl_iter);
  1407 			if ((pOther->GetStatus() == Plugin_Error
  1408 				&& (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
  1409 				|| pOther->m_FakeNativesMissing)
  1410 			{
  1411 				TryRefreshDependencies(pOther);
  1412 			}
  1413 			else if ((pOther->GetStatus() == Plugin_Running
  1414 					  || pOther->GetStatus() == Plugin_Paused)
  1415 					 && pOther != pPlugin)
  1416 			{
  1417 				List<NativeEntry *>::iterator nv_iter;
  1418 				for (nv_iter = pPlugin->m_Natives.begin();
  1419 					 nv_iter != pPlugin->m_Natives.end();
  1420 					 nv_iter++)
  1421 				{
  1422 					g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
  1423 				}
  1424 			}
  1425 		}
  1426 	}
  1427 
  1428 	/* Go through our libraries and tell other plugins they're added */
  1429 	List<String>::iterator s_iter;
  1430 	for (s_iter = pPlugin->m_Libraries.begin();
  1431 		s_iter != pPlugin->m_Libraries.end();
  1432 		s_iter++)
  1433 	{
  1434 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Added);
  1435 	}
  1436 
  1437 	/* :TODO: optimize? does this even matter? */
  1438 	pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
  1439 
  1440 	return true;
  1441 }
  1442 
  1443 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
  1444 {
  1445 	assert(pPlugin->GetBaseContext() != NULL);
  1446 
  1447 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1448 
  1449 	List<String>::iterator lib_iter;
  1450 	List<String>::iterator req_iter;
  1451 	List<CPlugin *>::iterator pl_iter;
  1452 	CPlugin *pl;
  1453 	for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
  1454 	{
  1455 		bool found = false;
  1456 		for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
  1457 		{
  1458 			pl = (*pl_iter);
  1459 			for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
  1460 			{
  1461 				if ((*req_iter) == (*lib_iter))
  1462 				{
  1463 					found = true;
  1464 				}
  1465 			}
  1466 		}
  1467 		if (!found)
  1468 		{
  1469 			pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
  1470 			return;
  1471 		}
  1472 	}
  1473 
  1474 	/* Find any unbound natives
  1475 	 * Right now, these are not allowed
  1476 	 */
  1477 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1478 	uint32_t num = pContext->GetNativesNum();
  1479 	sp_native_t *native;
  1480 	for (unsigned int i=0; i<num; i++)
  1481 	{
  1482 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1483 		{
  1484 			break;
  1485 		}
  1486 		if (native->status == SP_NATIVE_UNBOUND
  1487 			&& native->name[0] != '@'
  1488 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1489 		{
  1490 			pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
  1491 			return;
  1492 		}
  1493 	}
  1494 
  1495 	if (pPlugin->GetStatus() == Plugin_Error)
  1496 	{
  1497 		/* If we got here, all natives are okay again! */
  1498 		pPlugin->m_status = Plugin_Running;
  1499 		if (pPlugin->m_pRuntime->IsPaused())
  1500 		{
  1501 			pPlugin->m_pRuntime->SetPauseState(false);
  1502 			_SetPauseState(pPlugin, false);
  1503 		}
  1504 	}
  1505 }
  1506 
  1507 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
  1508 {
  1509 	CPlugin *pPlugin = (CPlugin *)plugin;
  1510 
  1511 	/* This prevents removal during insertion or anything else weird */
  1512 	if (m_plugins.find(pPlugin) == m_plugins.end())
  1513 	{
  1514 		return false;
  1515 	}
  1516 
  1517 	IPluginContext *pContext = plugin->GetBaseContext();
  1518 	if (pContext != NULL && pContext->IsInExec())
  1519 	{
  1520 		char buffer[255];
  1521 		UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
  1522 		engine->ServerCommand(buffer);
  1523 		return false;
  1524 	}
  1525 
  1526 	/* Remove us from the lookup table and linked list */
  1527 	m_plugins.remove(pPlugin);
  1528 	sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
  1529 
  1530 	/* Go through our libraries and tell other plugins they're gone */
  1531 	List<String>::iterator s_iter;
  1532 	for (s_iter = pPlugin->m_Libraries.begin();
  1533 		 s_iter != pPlugin->m_Libraries.end();
  1534 		 s_iter++)
  1535 	{
  1536 		OnLibraryAction((*s_iter).c_str(), LibraryAction_Removed);
  1537 	}
  1538 
  1539 	List<IPluginsListener *>::iterator iter;
  1540 	IPluginsListener *pListener;
  1541 
  1542 	if (pPlugin->GetStatus() <= Plugin_Error)
  1543 	{
  1544 		/* Notify plugin */
  1545 		pPlugin->Call_OnPluginEnd();
  1546 
  1547 		/* Notify listeners of unloading */
  1548 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1549 		{
  1550 			pListener = (*iter);
  1551 			pListener->OnPluginUnloaded(pPlugin);
  1552 		}
  1553 	}
  1554 
  1555 	pPlugin->DropEverything();
  1556 
  1557 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1558 	{
  1559 		/* Notify listeners of destruction */
  1560 		pListener = (*iter);
  1561 		pListener->OnPluginDestroyed(pPlugin);
  1562 	}
  1563 	
  1564 	/* Tell the plugin to delete itself */
  1565 	delete pPlugin;
  1566 
  1567 	return true;
  1568 }
  1569 
  1570 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
  1571 {
  1572 	IPlugin *pPlugin;
  1573 	IPluginContext *pContext;
  1574 
  1575 	pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
  1576 
  1577 	if (pContext->GetKey(2, (void **)&pPlugin))
  1578 	{
  1579 		return pPlugin;
  1580 	}
  1581 
  1582 	return NULL;
  1583 }
  1584 
  1585 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
  1586 {
  1587 	return (CPlugin *)FindPluginByContext(ctx);
  1588 }
  1589 
  1590 unsigned int CPluginManager::GetPluginCount()
  1591 {
  1592 	return m_plugins.size();
  1593 }
  1594 
  1595 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
  1596 {
  1597 	m_listeners.push_back(listener);
  1598 }
  1599 
  1600 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
  1601 {
  1602 	m_listeners.remove(listener);
  1603 }
  1604 
  1605 IPluginIterator *CPluginManager::GetPluginIterator()
  1606 {
  1607 	if (m_iters.empty())
  1608 	{
  1609 		return new CPluginIterator(&m_plugins);
  1610 	} else {
  1611 		CPluginIterator *iter = m_iters.front();
  1612 		m_iters.pop();
  1613 		iter->Reset();
  1614 		return iter;
  1615 	}
  1616 }
  1617 
  1618 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1619 {
  1620 	m_iters.push(iter);
  1621 }
  1622 
  1623 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1624 {
  1625 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1626 	size_t alias_len = 0;
  1627 	size_t local_len = 0;
  1628 
  1629 	const char *ptr = alias;
  1630 	unsigned int alias_explicit_paths = 0;
  1631 	unsigned int alias_path_end = 0;
  1632 	while (*ptr != '\0')
  1633 	{
  1634 		if (*ptr == '\\' || *ptr == '/')
  1635 		{
  1636 			alias_explicit_paths++;
  1637 			alias_path_end = alias_len;
  1638 		}
  1639 		alias_len++;
  1640 		ptr++;
  1641 	}
  1642 
  1643 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1644 	{
  1645 		/* Trailing slash is totally invalid here */
  1646 		return false;
  1647 	}
  1648 
  1649 	ptr = localpath;
  1650 	unsigned int local_explicit_paths = 0;
  1651 	unsigned int local_path_end = 0;
  1652 	while (*ptr != '\0')
  1653 	{
  1654 		if (*ptr == '\\' || *ptr == '/')
  1655 		{
  1656 			local_explicit_paths++;
  1657 			local_path_end = local_len;
  1658 		}
  1659 		local_len++;
  1660 		ptr++;
  1661 	}
  1662 
  1663 	/* If the alias has more explicit paths than the real path,
  1664 	 * no match will be possible.
  1665 	 */
  1666 	if (alias_explicit_paths > local_explicit_paths)
  1667 	{
  1668 		return false;
  1669 	}
  1670 
  1671 	if (alias_explicit_paths)
  1672 	{
  1673 		/* We need to find if the paths match now.  For example, these should all match:
  1674 		 * csdm     csdm
  1675 		 * csdm     optional/csdm
  1676 		 * csdm/ban optional/crab/csdm/ban
  1677 		*/
  1678 		const char *aliasptr = alias;
  1679 		const char *localptr = localpath;
  1680 		bool match = true;
  1681 		do
  1682 		{
  1683 			if (*aliasptr != *localptr)
  1684 			{
  1685 				/* We have to knock one path off */
  1686 				local_explicit_paths--;
  1687 				if (alias_explicit_paths > local_explicit_paths)
  1688 				{
  1689 					/* Skip out if we're gonna have an impossible match */
  1690 					return false;
  1691 				}
  1692 				/* Eat up localptr tokens until we get a result */
  1693 				while (((localptr - localpath) < (int)local_path_end)
  1694 					&& *localptr != '/'
  1695 					&& *localptr != '\\')
  1696 				{
  1697 					localptr++;
  1698 				}
  1699 				/* Check if we hit the end of our searchable area.
  1700 				 * This probably isn't possible because of the path 
  1701 				 * count check, but it's a good idea anyway.
  1702 				 */
  1703 				if ((localptr - localpath) >= (int)local_path_end)
  1704 				{
  1705 					return false;
  1706 				} else {
  1707 					/* Consume the slash token */
  1708 					localptr++;
  1709 				}
  1710 				/* Reset the alias pointer so we can continue consuming */
  1711 				aliasptr = alias;
  1712 				match = false;
  1713 				continue;
  1714 			}
  1715 			/* Note:
  1716 			 * This is safe because if localptr terminates early, aliasptr will too
  1717 			 */
  1718 			do
  1719 			{
  1720 				/* We should never reach the end of the string because of this check. */
  1721 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1722 				bool localend = (localptr - localpath) > (int)local_path_end;
  1723 				if (aliasend || localend)
  1724 				{
  1725 					if (aliasend && localend)
  1726 					{
  1727 						/* we matched, and we can break out now */
  1728 						match = true;
  1729 						break;
  1730 					}
  1731 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1732 					match = false;
  1733 					break;
  1734 				}
  1735 
  1736 				/* If we got here, it's safe to compare the next two tokens */
  1737 				if (*localptr != *aliasptr)
  1738 				{
  1739 					match = false;
  1740 					break;
  1741 				}
  1742 				localptr++;
  1743 				aliasptr++;
  1744 			} while (true);
  1745 		} while (!match);
  1746 	}
  1747 
  1748 	/* If we got here, it's time to compare filenames */
  1749 	const char *aliasptr = alias;
  1750 	const char *localptr = localpath;
  1751 
  1752 	if (alias_explicit_paths)
  1753 	{
  1754 		aliasptr = &alias[alias_path_end + 1];
  1755 	}
  1756 
  1757 	if (local_explicit_paths)
  1758 	{
  1759 		localptr = &localpath[local_path_end + 1];
  1760 	}
  1761 
  1762 	while (true)
  1763 	{
  1764 		if (*aliasptr == '*')
  1765 		{
  1766 			/* First, see if this is the last character */
  1767 			if ((unsigned)(aliasptr - alias) == alias_len - 1)
  1768 			{
  1769 				/* If so, there's no need to match anything else */
  1770 				return true;
  1771 			}
  1772 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1773 			 * Note that we only need to search up to the next asterisk.
  1774 			 */
  1775 			aliasptr++;
  1776 			bool match = true;
  1777 			const char *local_orig = localptr;
  1778 			do
  1779 			{
  1780 				match = true;
  1781 				while (*aliasptr != '\0' && *aliasptr != '*')
  1782 				{
  1783 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1784 					if (*aliasptr != *localptr)
  1785 					{
  1786 						match = false;
  1787 						break;
  1788 					}
  1789 					aliasptr++;
  1790 					localptr++;
  1791 				}
  1792 				if (!match)
  1793 				{
  1794 					/* If we didn't get a match, we need to advance the search stream.
  1795 					 * This will let us skip tokens while still searching for another match.
  1796 					 */
  1797 					localptr = ++local_orig;
  1798 					/* Make sure we don't go out of bounds */
  1799 					if (*localptr == '\0')
  1800 					{
  1801 						break;
  1802 					}
  1803 				}
  1804 			} while (!match);
  1805 
  1806 			if (!match)
  1807 			{
  1808 				return false;
  1809 			} else {
  1810 				/* If we got a match, move on to the next token */
  1811 				continue;
  1812 			}
  1813 		} else if (*aliasptr == '\0') {
  1814 			if (*localptr == '\0'
  1815 				||
  1816 				strcmp(localptr, ".smx") == 0)
  1817 			{
  1818 				return true;
  1819 			} else {
  1820 				return false;
  1821 			}
  1822 		} else if (*aliasptr != *localptr) {
  1823 			return false;
  1824 		}
  1825 		aliasptr++;
  1826 		localptr++;
  1827 	}
  1828 
  1829 	return true;
  1830 }
  1831 
  1832 bool CPluginManager::IsLateLoadTime() const
  1833 {
  1834 	return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
  1835 }
  1836 
  1837 void CPluginManager::OnSourceModAllInitialized()
  1838 {
  1839 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1840 
  1841 	HandleAccess sec;
  1842 	g_HandleSys.InitAccessDefaults(NULL, &sec);
  1843 
  1844 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1845 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1846 
  1847 	g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1848 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1849 
  1850 	g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
  1851 
  1852 	g_ShareSys.AddInterface(NULL, this);
  1853 	
  1854 	m_pOnLibraryAdded = g_Forwards.CreateForward("OnLibraryAdded", ET_Ignore, 1, NULL, Param_String);
  1855 	m_pOnLibraryRemoved = g_Forwards.CreateForward("OnLibraryRemoved", ET_Ignore, 1, NULL, Param_String);
  1856 }
  1857 
  1858 void CPluginManager::OnSourceModShutdown()
  1859 {
  1860 	g_RootMenu.RemoveRootConsoleCommand("plugins", this);
  1861 
  1862 	UnloadAll();
  1863 
  1864 	g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
  1865 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1866 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1867 	
  1868 	g_Forwards.ReleaseForward(m_pOnLibraryAdded);
  1869 	g_Forwards.ReleaseForward(m_pOnLibraryRemoved);
  1870 }
  1871 
  1872 ConfigResult CPluginManager::OnSourceModConfigChanged(const char *key, 
  1873 												 const char *value, 
  1874 												 ConfigSource source, 
  1875 												 char *error, 
  1876 												 size_t maxlength)
  1877 {
  1878 	if (strcmp(key, "BlockBadPlugins") == 0) {
  1879 		if (strcasecmp(value, "yes") == 0)
  1880 		{
  1881 			m_bBlockBadPlugins = true;
  1882 		} else if (strcasecmp(value, "no") == 0) {
  1883 			m_bBlockBadPlugins = false;
  1884 		} else {
  1885 			UTIL_Format(error, maxlength, "Invalid value: must be \"yes\" or \"no\"");
  1886 			return ConfigResult_Reject;
  1887 		}
  1888 		return ConfigResult_Accept;
  1889 	}
  1890 	return ConfigResult_Ignore;
  1891 }
  1892 
  1893 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1894 {
  1895 	/* We don't care about the internal object, actually */
  1896 }
  1897 
  1898 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
  1899 {
  1900 	*pSize = ((CPlugin *)object)->CalcMemUsage();
  1901 	return true;
  1902 }
  1903 
  1904 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1905 {
  1906 	IPlugin *pPlugin;
  1907 	HandleError _err;
  1908 
  1909 	HandleSecurity sec;
  1910 
  1911 	sec.pOwner = NULL;
  1912 	sec.pIdentity = m_MyIdent;
  1913 
  1914 	if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1915 	{
  1916 		pPlugin = NULL;
  1917 	}
  1918 
  1919 	if (err)
  1920 	{
  1921 		*err = _err;
  1922 	}
  1923 
  1924 	return pPlugin;
  1925 }
  1926 
  1927 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1928 {
  1929 	if (num < 1 || num > (int)GetPluginCount())
  1930 	{
  1931 		return NULL;
  1932 	}
  1933 
  1934 	CPlugin *pl;
  1935 	int id = 1;
  1936 
  1937 	SourceHook::List<CPlugin *>::iterator iter;
  1938 	for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
  1939 
  1940 	pl = *iter;
  1941 
  1942 	return pl;
  1943 }
  1944 
  1945 const char *CPluginManager::GetStatusText(PluginStatus st)
  1946 {
  1947 	switch (st)
  1948 	{
  1949 	case Plugin_Running:
  1950 		return "Running";
  1951 	case Plugin_Paused:
  1952 		return "Paused";
  1953 	case Plugin_Error:
  1954 		return "Error";
  1955 	case Plugin_Uncompiled:
  1956 		return "Uncompiled";
  1957 	case Plugin_BadLoad:
  1958 		return "Bad Load";
  1959 	case Plugin_Failed:
  1960 		return "Failed";
  1961 	default:
  1962 		assert(false);
  1963 		return "-";
  1964 	}
  1965 }
  1966 
  1967 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
  1968 {
  1969 	int argcount = command.ArgC();
  1970 	if (argcount >= 3)
  1971 	{
  1972 		const char *cmd = command.Arg(2);
  1973 		if (strcmp(cmd, "list") == 0)
  1974 		{
  1975 			char buffer[256];
  1976 			unsigned int id = 1;
  1977 			int plnum = GetPluginCount();
  1978 
  1979 			if (!plnum)
  1980 			{
  1981 				g_RootMenu.ConsolePrint("[SM] No plugins loaded");
  1982 				return;
  1983 			}
  1984 			else
  1985 			{
  1986 				g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
  1987 			}
  1988 
  1989 			CPlugin *pl;
  1990 			SourceHook::List<CPlugin *>::iterator iter;
  1991 			SourceHook::List<CPlugin *> m_FailList;
  1992 
  1993 			for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  1994 			{
  1995 				pl = (*iter);
  1996 				assert(pl->GetStatus() != Plugin_Created);
  1997 				int len = 0;
  1998 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  1999 				if (pl->GetStatus() != Plugin_Running && !pl->IsSilentlyFailed())
  2000 				{
  2001 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d <%s>", id, GetStatusText(pl->GetStatus()));
  2002 
  2003 					if (pl->GetStatus() <= Plugin_Error)
  2004 					{
  2005 						/* Plugin has failed to load. */
  2006 						m_FailList.push_back(pl);
  2007 					}
  2008 				}
  2009 				else
  2010 				{
  2011 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d", id);
  2012 				}
  2013 				if (pl->GetStatus() < Plugin_Created)
  2014 				{
  2015 					if (pl->IsSilentlyFailed())
  2016 						len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " Disabled:");
  2017 					len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2018 					if (IS_STR_FILLED(info->version))
  2019 					{
  2020 						len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  2021 					}
  2022 					if (IS_STR_FILLED(info->author))
  2023 					{
  2024 						UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  2025 					}
  2026 				}
  2027 				else
  2028 				{
  2029 					UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
  2030 				}
  2031 				g_RootMenu.ConsolePrint("%s", buffer);
  2032 			}
  2033 
  2034 			if (!m_FailList.empty())
  2035 			{
  2036 				g_RootMenu.ConsolePrint("Load Errors:");
  2037 
  2038 				SourceHook::List<CPlugin *>::iterator _iter;
  2039 
  2040 				CPlugin *pl;
  2041 
  2042 				for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
  2043 				{
  2044 					pl = (CPlugin *)*_iter;
  2045 					g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
  2046 				}
  2047 			}
  2048 
  2049 			return;
  2050 		}
  2051 		else if (strcmp(cmd, "load") == 0)
  2052 		{
  2053 			if (argcount < 4)
  2054 			{
  2055 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
  2056 				return;
  2057 			}
  2058 
  2059 			char error[128];
  2060 			bool wasloaded;
  2061 			const char *filename = command.Arg(3);
  2062 
  2063 			char pluginfile[256];
  2064 			const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
  2065 			g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
  2066 
  2067 			IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
  2068 
  2069 			if (wasloaded)
  2070 			{
  2071 				g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
  2072 				return;
  2073 			}
  2074 
  2075 			if (pl)
  2076 			{
  2077 				g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
  2078 			}
  2079 			else
  2080 			{
  2081 				g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
  2082 			}
  2083 
  2084 			return;
  2085 		}
  2086 		else if (strcmp(cmd, "unload") == 0)
  2087 		{
  2088 			if (argcount < 4)
  2089 			{
  2090 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
  2091 				return;
  2092 			}
  2093 
  2094 			CPlugin *pl;
  2095 			char *end;
  2096 			const char *arg = command.Arg(3);
  2097 			int id = strtol(arg, &end, 10);
  2098 
  2099 			if (*end == '\0')
  2100 			{
  2101 				pl = GetPluginByOrder(id);
  2102 				if (!pl)
  2103 				{
  2104 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2105 					return;
  2106 				}
  2107 			}
  2108 			else
  2109 			{
  2110 				char pluginfile[256];
  2111 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2112 				g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2113 
  2114 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2115 				{
  2116 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2117 					return;
  2118 				}
  2119 			}
  2120 
  2121 			char name[PLATFORM_MAX_PATH];
  2122 
  2123 			if (pl->GetStatus() < Plugin_Created)
  2124 			{
  2125 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  2126 				UTIL_Format(name, sizeof(name), (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2127 			}
  2128 			else
  2129 			{
  2130 				UTIL_Format(name, sizeof(name), "%s", pl->GetFilename());
  2131 			}
  2132 
  2133 			if (UnloadPlugin(pl))
  2134 			{
  2135 				g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
  2136 			}
  2137 			else
  2138 			{
  2139 				g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
  2140 			}
  2141 
  2142 			return;
  2143 		}
  2144 		else if (strcmp(cmd, "unload_all") == 0)
  2145 		{
  2146 			g_PluginSys.UnloadAll();
  2147 			g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
  2148 			return;
  2149 		}
  2150 		else if (strcmp(cmd, "load_lock") == 0)
  2151 		{
  2152 			if (m_LoadingLocked)
  2153 			{
  2154 				g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
  2155 			}
  2156 			else
  2157 			{
  2158 				m_LoadingLocked = true;
  2159 				g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
  2160 			}
  2161 			return;
  2162 		}
  2163 		else if (strcmp(cmd, "load_unlock") == 0)
  2164 		{
  2165 			if (m_LoadingLocked)
  2166 			{
  2167 				m_LoadingLocked = false;
  2168 				g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
  2169 			}
  2170 			else
  2171 			{
  2172 				g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
  2173 			}
  2174 			return;
  2175 		}
  2176 		else if (strcmp(cmd, "info") == 0)
  2177 		{
  2178 			if (argcount < 4)
  2179 			{
  2180 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
  2181 				return;
  2182 			}
  2183 
  2184 			CPlugin *pl;
  2185 			char *end;
  2186 			const char *arg = command.Arg(3);
  2187 			int id = strtol(arg, &end, 10);
  2188 
  2189 			if (*end == '\0')
  2190 			{
  2191 				pl = GetPluginByOrder(id);
  2192 				if (!pl)
  2193 				{
  2194 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2195 					return;
  2196 				}
  2197 			}
  2198 			else
  2199 			{
  2200 				char pluginfile[256];
  2201 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2202 				g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2203 
  2204 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2205 				{
  2206 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2207 					return;
  2208 				}
  2209 			}
  2210 
  2211 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2212 
  2213 			g_RootMenu.ConsolePrint("  Filename: %s", pl->GetFilename());
  2214 			if (pl->GetStatus() <= Plugin_Error)
  2215 			{
  2216 				if (IS_STR_FILLED(info->name))
  2217 				{
  2218 					if (IS_STR_FILLED(info->description))
  2219 					{
  2220 						g_RootMenu.ConsolePrint("  Title: %s (%s)", info->name, info->description);
  2221 					} else {
  2222 						g_RootMenu.ConsolePrint("  Title: %s", info->name);
  2223 					}
  2224 				}
  2225 				if (IS_STR_FILLED(info->author))
  2226 				{
  2227 					g_RootMenu.ConsolePrint("  Author: %s", info->author);
  2228 				}
  2229 				if (IS_STR_FILLED(info->version))
  2230 				{
  2231 					g_RootMenu.ConsolePrint("  Version: %s", info->version);
  2232 				}
  2233 				if (IS_STR_FILLED(info->url))
  2234 				{
  2235 					g_RootMenu.ConsolePrint("  URL: %s", info->url);
  2236 				}
  2237 				if (pl->GetStatus() == Plugin_Error)
  2238 				{
  2239 					g_RootMenu.ConsolePrint("  Error: %s", pl->m_errormsg);
  2240 				}
  2241 				else
  2242 				{
  2243 					if (pl->GetStatus() == Plugin_Running)
  2244 					{
  2245 						g_RootMenu.ConsolePrint("  Status: running");
  2246 					}
  2247 					else
  2248 					{
  2249 						g_RootMenu.ConsolePrint("  Status: not running");
  2250 					}
  2251 
  2252 					const char *typestr = "";
  2253 					switch (pl->GetType())
  2254 					{
  2255 					case PluginType_MapUpdated:
  2256 						typestr = "Map Change if Updated";
  2257 						break;
  2258 					case PluginType_MapOnly:
  2259 						typestr = "Map Change";
  2260 						break;
  2261 					case PluginType_Private:
  2262 					case PluginType_Global:
  2263 						typestr = "Never";
  2264 						break;
  2265 					}
  2266 
  2267 					g_RootMenu.ConsolePrint("  Reloads: %s", typestr);
  2268 				}
  2269 				if (pl->m_FileVersion >= 3)
  2270 				{
  2271 					g_RootMenu.ConsolePrint("  Timestamp: %s", pl->m_DateTime);
  2272 				}
  2273 				
  2274 				unsigned char *pCodeHash = pl->m_pRuntime->GetCodeHash();
  2275 				unsigned char *pDataHash = pl->m_pRuntime->GetDataHash();
  2276 				
  2277 				char combinedHash[33];
  2278 				for (int i = 0; i < 16; i++)
  2279 					UTIL_Format(combinedHash + (i * 2), 3, "%02x", pCodeHash[i] ^ pDataHash[i]);
  2280 				
  2281 				g_RootMenu.ConsolePrint("  Hash: %s", combinedHash);
  2282 			}
  2283 			else
  2284 			{
  2285 				g_RootMenu.ConsolePrint("  Load error: %s", pl->m_errormsg);
  2286 				if (pl->GetStatus() < Plugin_Created)
  2287 				{
  2288 					g_RootMenu.ConsolePrint("  File info: (title \"%s\") (version \"%s\")", 
  2289 											info->name ? info->name : "<none>",
  2290 											info->version ? info->version : "<none>");
  2291 					if (IS_STR_FILLED(info->url))
  2292 					{
  2293 						g_RootMenu.ConsolePrint("  File URL: %s", info->url);
  2294 					}
  2295 				}
  2296 			}
  2297 
  2298 			return;
  2299 		}
  2300 		else if (strcmp(cmd, "refresh") == 0)
  2301 		{
  2302 			g_SourceMod.DoGlobalPluginLoads();
  2303 			g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
  2304 			return;
  2305 		}
  2306 		else if (strcmp(cmd, "reload") == 0)
  2307 		{
  2308 			if (argcount < 4)
  2309 			{
  2310 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
  2311 				return;
  2312 			}
  2313 
  2314 			CPlugin *pl;
  2315 			char *end;
  2316 			const char *arg = command.Arg(3);
  2317 			int id = strtol(arg, &end, 10);
  2318 
  2319 			if (*end == '\0')
  2320 			{
  2321 				pl = GetPluginByOrder(id);
  2322 				if (!pl)
  2323 				{
  2324 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2325 					return;
  2326 				}
  2327 			}
  2328 			else
  2329 			{
  2330 				char pluginfile[256];
  2331 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2332 				g_SourceMod.BuildPath(Path_None, pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2333 
  2334 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2335 				{
  2336 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2337 					return;
  2338 				}
  2339 			}
  2340 
  2341 			char name[PLATFORM_MAX_PATH];
  2342 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2343 			if (pl->GetStatus() <= Plugin_Paused) 
  2344 				strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2345 			else
  2346 				strcpy(name, pl->GetFilename());
  2347 
  2348 			if (ReloadPlugin(pl))
  2349 			{
  2350 				g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
  2351 			}
  2352 			else
  2353 			{
  2354 				g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
  2355 			}
  2356 
  2357 			return;
  2358 		}
  2359 	}
  2360 
  2361 	/* Draw the main menu */
  2362 	g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
  2363 	g_RootMenu.DrawGenericOption("info", "Information about a plugin");
  2364 	g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
  2365 	g_RootMenu.DrawGenericOption("load", "Load a plugin");
  2366 	g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
  2367 	g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
  2368 	g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
  2369 	g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
  2370 	g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
  2371 	g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
  2372 }
  2373 
  2374 bool CPluginManager::ReloadPlugin(CPlugin *pl)
  2375 {
  2376 	List<CPlugin *>::iterator iter;
  2377 	char filename[PLATFORM_MAX_PATH];
  2378 	bool wasloaded;
  2379 	PluginType ptype;
  2380 	IPlugin *newpl;
  2381 	int id = 1;
  2382 
  2383 	strcpy(filename, pl->m_filename);
  2384 	ptype = pl->GetType();
  2385 
  2386 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
  2387 	{
  2388 		if ((*iter) == pl)
  2389 		{
  2390 			break;
  2391 		}
  2392 	}
  2393 
  2394 	if (!UnloadPlugin(pl))
  2395 	{
  2396 		return false;
  2397 	}
  2398 	if (!(newpl=LoadPlugin(filename, true, ptype, NULL, 0, &wasloaded)))
  2399 	{
  2400 		return false;
  2401 	}
  2402 
  2403 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2404 	{
  2405 		if ((*iter) == (CPlugin *)newpl)
  2406 		{
  2407 			m_plugins.erase(iter);
  2408 			break;
  2409 		}
  2410 	}
  2411 
  2412 	int i;
  2413 	for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
  2414 	{
  2415 	}
  2416 	m_plugins.insert(iter, (CPlugin *)newpl);
  2417 
  2418 	return true;
  2419 }
  2420 
  2421 void CPluginManager::ReloadOrUnloadPlugins()
  2422 {
  2423 	/* If we're in a load lock, just skip this whole bit. */
  2424 	if (m_LoadingLocked)
  2425 	{
  2426 		return;
  2427 	}
  2428 
  2429 	List<CPlugin *>::iterator iter;
  2430 	List<CPlugin *> tmp_list = m_plugins;
  2431 	CPlugin *pl;
  2432 	time_t t;
  2433 
  2434 	for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
  2435 	{
  2436 		pl = (*iter);
  2437 		if (pl->GetType() ==  PluginType_MapOnly)
  2438 		{
  2439 			UnloadPlugin((IPlugin *)pl);
  2440 		}
  2441 		else if (pl->GetType() == PluginType_MapUpdated)
  2442 		{
  2443 			t = pl->GetFileTimeStamp();
  2444 			if (!t || t > pl->GetTimeStamp())
  2445 			{
  2446 				pl->SetTimeStamp(t);
  2447 				UnloadPlugin((IPlugin *)pl);
  2448 			}
  2449 		}
  2450 	}
  2451 }
  2452 
  2453 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
  2454 {
  2455 	List<IPluginsListener *>::iterator iter;
  2456 	IPluginsListener *pListener;
  2457 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  2458 	{
  2459 		pListener = (*iter);
  2460 		pListener->OnPluginPauseChange(pl, paused);
  2461 	}	
  2462 }
  2463 
  2464 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
  2465 {
  2466 	List<CPlugin *>::iterator iter;
  2467 	CPlugin *pPlugin;
  2468 	IPluginFunction *pFunction;
  2469 
  2470 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2471 	{
  2472 		pPlugin = (*iter);
  2473 
  2474 		if (pPlugin->GetStatus() <= Plugin_Paused)
  2475 		{
  2476 			pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
  2477 
  2478 			if (pFunction)
  2479 			{
  2480 				pForward->AddFunction(pFunction);
  2481 			}
  2482 		}
  2483 	}
  2484 }
  2485 
  2486 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
  2487 {
  2488 	if (pToken->type != g_PluginIdent)
  2489 	{
  2490 		return NULL;
  2491 	}
  2492 
  2493 	return (CPlugin *)(pToken->ptr);
  2494 }
  2495 
  2496 void CPluginManager::OnLibraryAction(const char *lib, LibraryAction action)
  2497 {
  2498 	switch (action)
  2499 	{
  2500 	case LibraryAction_Removed:
  2501 		m_pOnLibraryRemoved->PushString(lib);
  2502 		m_pOnLibraryRemoved->Execute(NULL);
  2503 		break;
  2504 	case LibraryAction_Added:
  2505 		m_pOnLibraryAdded->PushString(lib);
  2506 		m_pOnLibraryAdded->Execute(NULL);
  2507 		break;
  2508 	}
  2509 }
  2510 
  2511 bool CPluginManager::LibraryExists(const char *lib)
  2512 {
  2513 	List<CPlugin *>::iterator iter;
  2514 
  2515 	for (iter=m_plugins.begin();
  2516 		 iter!=m_plugins.end();
  2517 		 iter++)
  2518 	{
  2519 		CPlugin *pl = (*iter);
  2520 		if (pl->GetStatus() != Plugin_Running)
  2521 		{
  2522 			continue;
  2523 		}
  2524 		List<String>::iterator s_iter;
  2525 		for (s_iter = pl->m_Libraries.begin();
  2526 			 s_iter != pl->m_Libraries.end();
  2527 			 s_iter++)
  2528 		{
  2529 			if ((*s_iter).compare(lib) == 0)
  2530 			{
  2531 				return true;
  2532 			}
  2533 		}
  2534 	}
  2535 
  2536 	return false;
  2537 }
  2538 
  2539 void CPluginManager::AllPluginsLoaded()
  2540 {
  2541 	List<CPlugin *>::iterator iter;
  2542 	CPlugin *pl;
  2543 
  2544 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2545 	{
  2546 		pl = (*iter);
  2547 		pl->Call_OnAllPluginsLoaded();
  2548 	}
  2549 }
  2550 
  2551 void CPluginManager::UnloadAll()
  2552 {
  2553 	List<CPlugin *>::iterator iter;
  2554 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  2555 	{
  2556 		UnloadPlugin((*iter));
  2557 	}
  2558 }
  2559 
  2560 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
  2561 {
  2562 	int id = 1;
  2563 	List<CPlugin *>::iterator iter;
  2564 
  2565 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  2566 	{
  2567 		if ((*iter) == pl)
  2568 		{
  2569 			return id;
  2570 		}
  2571 	}
  2572 
  2573 	return -1;
  2574 }
  2575 
  2576 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
  2577 {
  2578 	int id;
  2579 	char *end;
  2580 	CPlugin *pl;
  2581 	
  2582 	id = strtol(arg, &end, 10);
  2583 
  2584 	if (*end == '\0')
  2585 	{
  2586 		pl = GetPluginByOrder(id);
  2587 		if (!pl)
  2588 		{
  2589 			return NULL;
  2590 		}
  2591 	}
  2592 	else
  2593 	{
  2594 		char pluginfile[256];
  2595 		const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2596 		UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2597 
  2598 		if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2599 		{
  2600 			return NULL;
  2601 		}
  2602 	}
  2603 
  2604 	return pl;
  2605 }
  2606 
  2607 void CPluginManager::OnSourceModMaxPlayersChanged(int newvalue)
  2608 {
  2609 	SyncMaxClients(newvalue);
  2610 }
  2611 
  2612 void CPluginManager::SyncMaxClients(int max_clients)
  2613 {
  2614 	List<CPlugin *>::iterator iter;
  2615 
  2616 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2617 	{
  2618 		(*iter)->SyncMaxClients(max_clients);
  2619 	}
  2620 }
  2621 
  2622 void CPluginManager::ListPluginsToClient(CPlayer *player, const CCommand &args)
  2623 {
  2624 	char buffer[256];
  2625 	unsigned int id = 0;
  2626 	int plnum = GetPluginCount();
  2627 	edict_t *e = player->GetEdict();
  2628 	unsigned int start = 0;
  2629 
  2630 	if (!plnum)
  2631 	{
  2632 		ClientConsolePrint(e, "[SM] No plugins found.");
  2633 		return;
  2634 	}
  2635 
  2636 	if (args.ArgC() > 2)
  2637 	{
  2638 		start = atoi(args.Arg(2));
  2639 	}
  2640 
  2641 	CPlugin *pl;
  2642 	SourceHook::List<CPlugin *>::iterator iter;
  2643 	SourceHook::List<CPlugin *> m_FailList;
  2644 
  2645 	for (iter = m_plugins.begin();
  2646 		 iter != m_plugins.end();
  2647 		 iter++)
  2648 	{
  2649 		pl = (*iter);
  2650 
  2651 		if (pl->GetStatus() != Plugin_Running)
  2652 		{
  2653 			continue;
  2654 		}
  2655 
  2656 		/* Count valid plugins */
  2657 		id++;
  2658 		if (id < start)
  2659 		{
  2660 			continue;
  2661 		}
  2662 
  2663 		if (id - start > 10)
  2664 		{
  2665 			break;
  2666 		}
  2667 
  2668 		size_t len;
  2669 		const sm_plugininfo_t *info = pl->GetPublicInfo();
  2670 		len = UTIL_Format(buffer, sizeof(buffer), " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2671 		if (IS_STR_FILLED(info->version))
  2672 		{
  2673 			len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  2674 		}
  2675 		if (IS_STR_FILLED(info->author))
  2676 		{
  2677 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  2678 		}
  2679 		else
  2680 		{
  2681 			UTIL_Format(&buffer[len], sizeof(buffer)-len, " %s", pl->m_filename);
  2682 		}
  2683 		ClientConsolePrint(e, "%s", buffer);
  2684 	}
  2685 
  2686 	/* See if we can get more plugins */
  2687 	while (iter != m_plugins.end())
  2688 	{
  2689 		if ((*iter)->GetStatus() == Plugin_Running)
  2690 		{
  2691 			break;
  2692 		}
  2693 	}
  2694 
  2695 	/* Do we actually have more plugins? */
  2696 	if (iter != m_plugins.end())
  2697 	{
  2698 		ClientConsolePrint(e, "To see more, type \"sm plugins %d\"", id);
  2699 	}
  2700 }