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