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