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