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