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