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