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