core/systems/PluginSys.cpp
author David Anderson <dvander@alliedmods.net>
Sun Jul 15 22:34:30 2007 +0000 (2007-07-15)
changeset 1123 08c06c17de24
parent 1122 f07d8e10433b
child 1124 a397d51fb986
permissions -rw-r--r--
fixed a bug where __pl_*_SetNTVOptional could not be called
     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 bool CPlugin::SetPauseState(bool paused)
   429 {
   430 	if (paused && GetStatus() != Plugin_Paused)
   431 	{
   432 		return false;
   433 	} else if (!paused && GetStatus() != Plugin_Running) {
   434 		return false;
   435 	}
   436 
   437 	IPluginFunction *pFunction = m_ctx.base->GetFunctionByName("OnPluginPauseChange");
   438 	if (pFunction)
   439 	{
   440 		cell_t result;
   441 		pFunction->PushCell(paused ? 1 : 0);
   442 		pFunction->Execute(&result);
   443 	}
   444 
   445 	if (paused)
   446 	{
   447 		m_status = Plugin_Paused;
   448 		m_ctx.ctx->flags |= SPFLAG_PLUGIN_PAUSED;
   449 	} else {
   450 		m_status = Plugin_Running;
   451 		m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
   452 	}
   453 
   454 	g_PluginSys._SetPauseState(this, paused);
   455 
   456 	return true;
   457 }
   458 
   459 IdentityToken_t *CPlugin::GetIdentity()
   460 {
   461 	return m_ident;
   462 }
   463 
   464 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
   465 {
   466 	int err;
   467 
   468 	if (!IsRunnable())
   469 	{
   470 		if (error)
   471 		{
   472 			snprintf(error, maxlength, "Plugin is not runnable.");
   473 		}
   474 		return false;
   475 	}
   476 
   477 	if (debug && IsDebugging())
   478 	{
   479 		if (error)
   480 		{
   481 			snprintf(error, maxlength, "Plugin is already in debug mode.");
   482 		}
   483 		return false;
   484 	} else if (!debug && !IsDebugging()) {
   485 		if (error)
   486 		{
   487 			snprintf(error, maxlength, "Plugins is already in production mode.");
   488 		}
   489 		return false;
   490 	}
   491 
   492 	ICompilation *co = g_pVM->StartCompilation(m_ctx.ctx->plugin);
   493 	if (!g_pVM->SetCompilationOption(co, "debug", (debug) ? "1" : "0"))
   494 	{
   495 		if (error)
   496 		{
   497 			snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
   498 		}
   499 		return false;
   500 	}
   501 
   502 	sp_context_t *new_ctx = g_pVM->CompileToContext(co, &err);
   503 
   504 	if (new_ctx)
   505 	{
   506 		memcpy(new_ctx->memory, m_ctx.ctx->memory, m_ctx.ctx->mem_size);
   507 		new_ctx->hp = m_ctx.ctx->hp;
   508 		new_ctx->sp = m_ctx.ctx->sp;
   509 		new_ctx->frm = m_ctx.ctx->frm;
   510 		new_ctx->dbreak = m_ctx.ctx->dbreak;
   511 		new_ctx->context = m_ctx.ctx->context;
   512 		memcpy(new_ctx->user, m_ctx.ctx->user, sizeof(m_ctx.ctx->user));
   513 
   514 		uint32_t nativeCount = m_plugin->info.natives_num;
   515 		for (uint32_t i=0; i<nativeCount; i++)
   516 		{
   517 			new_ctx->natives[i].pfn = m_ctx.ctx->natives[i].pfn;
   518 			new_ctx->natives[i].status = m_ctx.ctx->natives[i].status;
   519 		}
   520 
   521 		g_pVM->FreeContext(m_ctx.ctx);
   522 		m_ctx.ctx = new_ctx;
   523 		m_ctx.base->SetContext(new_ctx);
   524 
   525 		UpdateInfo();
   526 	} else {
   527 		if (error)
   528 		{
   529 			snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
   530 		}
   531 		return false;
   532 	}
   533 
   534 	return true;
   535 }
   536 
   537 bool CPlugin::IsRunnable()
   538 {
   539 	return (m_status <= Plugin_Paused) ? true : false;
   540 }
   541 
   542 time_t CPlugin::GetFileTimeStamp()
   543 {
   544 	char path[PLATFORM_MAX_PATH];
   545 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
   546 #ifdef PLATFORM_WINDOWS
   547 	struct _stat s;
   548 	if (_stat(path, &s) != 0)
   549 #elif defined PLATFORM_POSIX
   550 	struct stat s;
   551 	if (stat(path, &s) != 0)
   552 #endif
   553 	{
   554 		return 0;
   555 	} else {
   556 		return s.st_mtime;
   557 	}
   558 }
   559 
   560 time_t CPlugin::GetTimeStamp()
   561 {
   562 	return m_LastAccess;
   563 }
   564 
   565 void CPlugin::SetTimeStamp(time_t t)
   566 {
   567 	m_LastAccess = t;
   568 }
   569 
   570 void CPlugin::AddLangFile(unsigned int index)
   571 {
   572 	m_PhraseFiles.push_back(index);
   573 }
   574 
   575 size_t CPlugin::GetLangFileCount()
   576 {
   577 	return m_PhraseFiles.size();
   578 }
   579 
   580 unsigned int CPlugin::GetLangFileByIndex(unsigned int index)
   581 {
   582 	return m_PhraseFiles.at(index);
   583 }
   584 
   585 void CPlugin::DependencyDropped(CPlugin *pOwner)
   586 {
   587 	if (!m_ctx.ctx)
   588 	{
   589 		return;
   590 	}
   591 
   592 	List<String>::iterator reqlib_iter;
   593 	List<String>::iterator lib_iter;
   594 	for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
   595 	{
   596 		for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
   597 		{
   598 			if ((*reqlib_iter) == (*lib_iter))
   599 			{
   600 				m_LibraryMissing = true;
   601 			}
   602 		}	
   603 	}
   604 
   605 	List<FakeNative *>::iterator iter;
   606 	FakeNative *pNative;
   607 	sp_native_t *native;
   608 	uint32_t idx;
   609 	unsigned int unbound = 0;
   610 
   611 	for (iter = pOwner->m_fakeNatives.begin();
   612 		 iter != pOwner->m_fakeNatives.end();
   613 		 iter++)
   614 	{
   615 		pNative = (*iter);
   616 		/* Find this native! */
   617 		if (m_ctx.base->FindNativeByName(pNative->name.c_str(), &idx) != SP_ERROR_NONE)
   618 		{
   619 			continue;
   620 		}
   621 		/* Unbind it */
   622 		m_ctx.base->GetNativeByIndex(idx, &native);
   623 		native->pfn = NULL;
   624 		native->status = SP_NATIVE_UNBOUND;
   625 		unbound++;
   626 	}
   627 
   628 	if (unbound)
   629 	{
   630 		m_FakeNativesMissing = true;
   631 	}
   632 
   633 	/* :IDEA: in the future, add native trapping? */
   634 	if (m_FakeNativesMissing || m_LibraryMissing)
   635 	{
   636 		SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
   637 	}
   638 
   639 	m_dependsOn.remove(pOwner);
   640 }
   641 
   642 unsigned int CPlugin::GetConfigCount()
   643 {
   644 	return (unsigned int)m_configs.size();
   645 }
   646 
   647 AutoConfig *CPlugin::GetConfig(unsigned int i)
   648 {
   649 	if (i >= GetConfigCount())
   650 	{
   651 		return NULL;
   652 	}
   653 
   654 	return m_configs[i];
   655 }
   656 
   657 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
   658 {
   659 	AutoConfig *c = new AutoConfig;
   660 
   661 	c->autocfg = cfg;
   662 	c->folder = folder;
   663 	c->create = autoCreate;
   664 
   665 	m_configs.push_back(c);
   666 }
   667 
   668 /*******************
   669  * PLUGIN ITERATOR *
   670  *******************/
   671 
   672 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
   673 {
   674 	mylist = _mylist;
   675 	Reset();
   676 }
   677 
   678 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
   679 {
   680 	return (*current);
   681 }
   682 
   683 bool CPluginManager::CPluginIterator::MorePlugins()
   684 {
   685 	return (current != mylist->end());
   686 }
   687 
   688 void CPluginManager::CPluginIterator::NextPlugin()
   689 {
   690 	current++;
   691 }
   692 
   693 void CPluginManager::CPluginIterator::Release()
   694 {
   695 	g_PluginSys.ReleaseIterator(this);
   696 }
   697 
   698 CPluginManager::CPluginIterator::~CPluginIterator()
   699 {
   700 }
   701 
   702 void CPluginManager::CPluginIterator::Reset()
   703 {
   704 	current = mylist->begin();
   705 }
   706 
   707 /******************
   708  * PLUGIN MANAGER *
   709  ******************/
   710 
   711 CPluginManager::CPluginManager()
   712 {
   713 	m_LoadLookup = sm_trie_create();
   714 	m_AllPluginsLoaded = false;
   715 	m_MyIdent = NULL;
   716 	m_pNativeLookup = sm_trie_create();
   717 }
   718 
   719 CPluginManager::~CPluginManager()
   720 {
   721 	/* :NOTICE: 
   722 	 * Ignore the fact that there might be plugins in the cache.
   723 	 * This usually means that Core is not being unloaded properly, and everything
   724 	 * will crash anyway.  YAY
   725 	 */
   726 	sm_trie_destroy(m_LoadLookup);
   727 	sm_trie_destroy(m_pNativeLookup);
   728 
   729 	CStack<CPluginManager::CPluginIterator *>::iterator iter;
   730 	for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
   731 	{
   732 		delete (*iter);
   733 	}
   734 	m_iters.popall();
   735 }
   736 
   737 void CPluginManager::Shutdown()
   738 {
   739 	List<CPlugin *>::iterator iter;
   740 
   741 	while ((iter = m_plugins.begin()) != m_plugins.end())
   742 	{
   743 		UnloadPlugin(*iter);
   744 	}
   745 }
   746 
   747 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
   748 {
   749 	/* First read in the database of plugin settings */
   750 	SMCParseError err;
   751 	unsigned int line, col;
   752 	m_AllPluginsLoaded = false;
   753 	if ((err=g_TextParser.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
   754 	{
   755 		g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
   756 		const char *err_msg = g_TextParser.GetSMCErrorString(err);
   757 		if (err_msg)
   758 		{
   759 			g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
   760 		}
   761 	}
   762 
   763 	LoadPluginsFromDir(basedir, NULL);
   764 }
   765 
   766 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   767 {
   768 	char base_path[PLATFORM_MAX_PATH];
   769 
   770 	/* Form the current path to start reading from */
   771 	if (localpath == NULL)
   772 	{
   773 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
   774 	} else {
   775 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   776 	}
   777 
   778 	IDirectory *dir = g_LibSys.OpenDirectory(base_path);
   779 
   780 	if (!dir)
   781 	{
   782 		char error[256];
   783 		g_LibSys.GetPlatformError(error, sizeof(error));
   784 		g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
   785 		g_Logger.LogError("[SM] Platform returned error: %s", error);
   786 		return;
   787 	}
   788 
   789 	while (dir->MoreFiles())
   790 	{
   791 		if (dir->IsEntryDirectory() 
   792 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   793 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   794 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   795 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   796 		{
   797 			char new_local[PLATFORM_MAX_PATH];
   798 			if (localpath == NULL)
   799 			{
   800 				/* If no path yet, don't add a former slash */
   801 				snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   802 			} else {
   803 				g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   804 			}
   805 			LoadPluginsFromDir(basedir, new_local);
   806 		} else if (dir->IsEntryFile()) {
   807 			const char *name = dir->GetEntryName();
   808 			size_t len = strlen(name);
   809 			if (len >= 4
   810 				&& strcmp(&name[len-4], ".smx") == 0)
   811 			{
   812 				/* If the filename matches, load the plugin */
   813 				char plugin[PLATFORM_MAX_PATH];
   814 				if (localpath == NULL)
   815 				{
   816 					snprintf(plugin, sizeof(plugin), "%s", name);
   817 				} else {
   818 					g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   819 				}
   820 				LoadAutoPlugin(plugin);
   821 			}
   822 		}
   823 		dir->NextEntry();
   824 	}
   825 	g_LibSys.CloseDirectory(dir);
   826 }
   827 
   828 //well i have discovered that gabe newell is very fat, so i wrote this comment now
   829 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
   830 {
   831 	/**
   832 	 * Does this plugin already exist?
   833 	 */
   834 	CPlugin *pPlugin;
   835 	if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
   836 	{
   837 		/* Check to see if we should try reloading it */
   838 		if (pPlugin->GetStatus() == Plugin_BadLoad
   839 			|| pPlugin->GetStatus() == Plugin_Error
   840 			|| pPlugin->GetStatus() == Plugin_Failed)
   841 		{
   842 			UnloadPlugin(pPlugin);
   843 		} else {
   844 			if (_plugin)
   845 			{
   846 				*_plugin = pPlugin;
   847 			}
   848 			return LoadRes_AlreadyLoaded;
   849 		}
   850 	}
   851 
   852 	pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
   853 
   854 	assert(pPlugin != NULL);
   855 
   856 	pPlugin->m_type = PluginType_MapUpdated;
   857 
   858 	ICompilation *co = NULL;
   859 
   860 	if (pPlugin->m_status == Plugin_Uncompiled)
   861 	{
   862 		co = pPlugin->StartMyCompile(g_pVM);
   863 	}
   864 
   865 	PluginSettings *pset;
   866 	unsigned int setcount = m_PluginInfo.GetSettingsNum();
   867 	for (unsigned int i=0; i<setcount; i++)
   868 	{
   869 		if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
   870 		{
   871 			continue;
   872 		}
   873 		pPlugin->m_type = pset->type_val;
   874 		if (co)
   875 		{
   876 			for (unsigned int j=0; j<pset->opts_num; j++)
   877 			{
   878 				const char *key, *val;
   879 				m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
   880 				if (!key || !val)
   881 				{
   882 					continue;
   883 				}
   884 				if (!g_pVM->SetCompilationOption(co, key, val))
   885 				{
   886 					if (error)
   887 					{
   888 						snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
   889 					}
   890 					pPlugin->CancelMyCompile();
   891 					co = NULL;
   892 					break;
   893 				}
   894 			}
   895 		}
   896 	}
   897 
   898 	/* Do the actual compiling */
   899 	if (co)
   900 	{
   901 		pPlugin->FinishMyCompile(error, maxlength);
   902 		co = NULL;
   903 	}
   904 
   905 	/* Get the status */
   906 	if (pPlugin->GetStatus() == Plugin_Created)
   907 	{
   908 		AddCoreNativesToPlugin(pPlugin);
   909 		pPlugin->InitIdentity();
   910 		if (pPlugin->Call_AskPluginLoad(error, maxlength))
   911 		{
   912 			/* Autoload any modules */
   913 			LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
   914 		}
   915 	}
   916 
   917 	/* Save the time stamp */
   918 	time_t t = pPlugin->GetFileTimeStamp();
   919 	pPlugin->SetTimeStamp(t);
   920 
   921 	if (_plugin)
   922 	{
   923 		*_plugin = pPlugin;
   924 	}
   925 
   926 	return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
   927 }
   928 
   929 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
   930 {
   931 	CPlugin *pl;
   932 	LoadRes res;
   933 
   934 	*wasloaded = false;
   935 	if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
   936 	{
   937 		delete pl;
   938 		return NULL;
   939 	}
   940 
   941 	if (res == LoadRes_AlreadyLoaded)
   942 	{
   943 		*wasloaded = true;
   944 		return pl;
   945 	}
   946 
   947 	AddPlugin(pl);
   948 
   949 	/* Run second pass if we need to */
   950 	if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
   951 	{
   952 		if (!RunSecondPass(pl, error, maxlength))
   953 		{
   954 			UnloadPlugin(pl);
   955 			return NULL;
   956 		}
   957 	}
   958 
   959 	return pl;
   960 }
   961 
   962 void CPluginManager::LoadAutoPlugin(const char *plugin)
   963 {
   964 	CPlugin *pl;
   965 	LoadRes res;
   966 	char error[255] = "Unknown error";
   967 
   968 	if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
   969 	{
   970 		g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
   971 		pl->SetErrorState(Plugin_Failed, "%s", error);
   972 	}
   973 
   974 	if (res == LoadRes_Successful)
   975 	{
   976 		AddPlugin(pl);
   977 	}
   978 }
   979 
   980 void CPluginManager::AddPlugin(CPlugin *pPlugin)
   981 {
   982 	List<IPluginsListener *>::iterator iter;
   983 	IPluginsListener *pListener;
   984 
   985 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
   986 	{
   987 		pListener = (*iter);
   988 		pListener->OnPluginCreated(pPlugin);
   989 	}
   990 
   991 	m_plugins.push_back(pPlugin);
   992 	sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
   993 }
   994 
   995 void CPluginManager::LoadAll_SecondPass()
   996 {
   997 	List<CPlugin *>::iterator iter;
   998 	CPlugin *pPlugin;
   999 
  1000 	char error[256];
  1001 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1002 	{
  1003 		pPlugin = (*iter);
  1004 		if (pPlugin->GetStatus() == Plugin_Loaded)
  1005 		{
  1006 			error[0] = '\0';
  1007 			if (!RunSecondPass(pPlugin, error, sizeof(error)))
  1008 			{
  1009 				g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
  1010 				pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1011 			}
  1012 		}
  1013 	}
  1014 
  1015 	m_AllPluginsLoaded = true;
  1016 }
  1017 
  1018 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
  1019 {
  1020 	struct _pl
  1021 	{
  1022 		cell_t name;
  1023 		cell_t file;
  1024 		cell_t required;
  1025 	} *pl;
  1026 
  1027 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1028 	uint32_t num = pBase->GetPubVarsNum();
  1029 	sp_pubvar_t *pubvar;
  1030 	char *name, *file;
  1031 	char pathfile[PLATFORM_MAX_PATH];
  1032 
  1033 	for (uint32_t i=0; i<num; i++)
  1034 	{
  1035 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1036 		{
  1037 			continue;
  1038 		}
  1039 		if (strncmp(pubvar->name, "__pl_", 5) == 0)
  1040 		{
  1041 			pl = (_pl *)pubvar->offs;
  1042 			if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
  1043 			{
  1044 				continue;
  1045 			}
  1046 			if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
  1047 			{
  1048 				continue;
  1049 			}
  1050 			g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
  1051 			if (strcmp(pathfile, file) == 0)
  1052 			{
  1053 				continue;
  1054 			}
  1055 			if (pl->required == false)
  1056 			{
  1057 				IPluginFunction *pFunc;
  1058 				char buffer[64];
  1059 				UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
  1060 				if ((pFunc=pBase->GetFunctionByName(buffer)))
  1061 				{
  1062 					cell_t res;
  1063 					pFunc->Execute(&res);
  1064 					if (pPlugin->GetContext()->n_err != SP_ERROR_NONE)
  1065 					{
  1066 						if (error)
  1067 						{
  1068 							snprintf(error, maxlength, "Fatal error during initializing plugin load");
  1069 						}
  1070 						return false;
  1071 					}
  1072 				}
  1073 			} else {
  1074 				/* Check that we aren't registering the same library twice */
  1075 				if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
  1076 				{
  1077 					pPlugin->m_RequiredLibs.push_back(name);
  1078 				} else {
  1079 					continue;
  1080 				}
  1081 				List<CPlugin *>::iterator iter;
  1082 				CPlugin *pl;
  1083 				bool found = false;
  1084 				for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1085 				{
  1086 					pl = (*iter);
  1087 					if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
  1088 					{
  1089 						found = true;
  1090 						break;
  1091 					}
  1092 				}
  1093 				if (!found)
  1094 				{
  1095 					if (error)
  1096 					{
  1097 						snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
  1098 					}
  1099 					return false;
  1100 				}
  1101 			}
  1102 		}
  1103 	}
  1104 
  1105 	return true;
  1106 }
  1107 
  1108 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
  1109 {
  1110 	/* Find any extensions this plugin needs */
  1111 	struct _ext
  1112 	{
  1113 		cell_t name;
  1114 		cell_t file;
  1115 		cell_t autoload;
  1116 		cell_t required;
  1117 	} *ext;
  1118 
  1119 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1120 	uint32_t num = pBase->GetPubVarsNum();
  1121 	sp_pubvar_t *pubvar;
  1122 	IExtension *pExt;
  1123 	char path[PLATFORM_MAX_PATH];
  1124 	char *file, *name;
  1125 	for (uint32_t i=0; i<num; i++)
  1126 	{
  1127 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1128 		{
  1129 			continue;
  1130 		}
  1131 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
  1132 		{
  1133 			ext = (_ext *)pubvar->offs;
  1134 			if (!ext->required && !ext->autoload)
  1135 			{
  1136 				continue;
  1137 			}
  1138 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
  1139 			{
  1140 				continue;
  1141 			}
  1142 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
  1143 			{
  1144 				continue;
  1145 			}
  1146 			if (pass == 1)
  1147 			{
  1148 				/* Attempt to auto-load if necessary */
  1149 				if (ext->autoload)
  1150 				{
  1151 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1152 					g_Extensions.LoadAutoExtension(path);
  1153 				}
  1154 			} else if (pass == 2) {
  1155 				/* Is this required? */
  1156 				if (ext->required)
  1157 				{
  1158 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1159 					if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
  1160 					{
  1161 						pExt = g_Extensions.FindExtensionByName(name);
  1162 					}
  1163 					/* :TODO: should we bind to unloaded extensions?
  1164 					 * Currently the extension manager will ignore this.
  1165 					 */
  1166 					if (!pExt || !pExt->IsRunning(NULL, 0))
  1167 					{
  1168 						if (error)
  1169 						{
  1170 							snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
  1171 						}
  1172 						return false;
  1173 					} else {
  1174 						g_Extensions.BindChildPlugin(pExt, pPlugin);
  1175 					}
  1176 				}
  1177 			}
  1178 		}
  1179 	}
  1180 
  1181 	return true;
  1182 }
  1183 
  1184 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
  1185 {
  1186 	/* Second pass for extension requirements */
  1187 	if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
  1188 	{
  1189 		return false;
  1190 	}
  1191 
  1192 	/* Bind all extra natives */
  1193 	g_Extensions.BindAllNativesToPlugin(pPlugin);
  1194 	AddFakeNativesToPlugin(pPlugin);
  1195 
  1196 	if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
  1197 	{
  1198 		return false;
  1199 	}
  1200 
  1201 	/* Find any unbound natives
  1202 	 * Right now, these are not allowed
  1203 	 */
  1204 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1205 	uint32_t num = pContext->GetNativesNum();
  1206 	sp_native_t *native;
  1207 	for (unsigned int i=0; i<num; i++)
  1208 	{
  1209 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1210 		{
  1211 			break;
  1212 		}
  1213 		if (native->status == SP_NATIVE_UNBOUND
  1214 			&& native->name[0] != '@'
  1215 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1216 		{
  1217 			if (error)
  1218 			{
  1219 				snprintf(error, maxlength, "Native \"%s\" was not found.", native->name);
  1220 			}
  1221 			return false;
  1222 		}
  1223 	}
  1224 
  1225 	/* Finish by telling all listeners */
  1226 	List<IPluginsListener *>::iterator iter;
  1227 	IPluginsListener *pListener;
  1228 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1229 	{
  1230 		pListener = (*iter);
  1231 		pListener->OnPluginLoaded(pPlugin);
  1232 	}
  1233 	
  1234 	/* Tell this plugin to finish initializing itself */
  1235 	pPlugin->Call_OnPluginStart();
  1236 
  1237 	/* Now, if we have fake natives, go through all plugins that might need rebinding */
  1238 	if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_fakeNatives.size())
  1239 	{
  1240 		List<CPlugin *>::iterator pl_iter;
  1241 		CPlugin *pOther;
  1242 		for (pl_iter = m_plugins.begin();
  1243 			 pl_iter != m_plugins.end();
  1244 			 pl_iter++)
  1245 		{
  1246 			pOther = (*pl_iter);
  1247 			if ((pOther->GetStatus() == Plugin_Error
  1248 				&& (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
  1249 				|| pOther->m_FakeNativesMissing)
  1250 			{
  1251 				TryRefreshDependencies(pOther);
  1252 			}
  1253 		}
  1254 	}
  1255 
  1256 	return true;
  1257 }
  1258 
  1259 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
  1260 {
  1261 	List<sp_nativeinfo_t *>::iterator iter;
  1262 
  1263 	for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
  1264 	{
  1265 		sp_nativeinfo_t *natives = (*iter);
  1266 		IPluginContext *ctx = pPlugin->GetBaseContext();
  1267 		unsigned int i=0;
  1268 		/* Attempt to bind every native! */
  1269 		while (natives[i].func != NULL)
  1270 		{
  1271 			ctx->BindNative(&natives[i++]);
  1272 		}
  1273 	}
  1274 }
  1275 
  1276 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
  1277 {
  1278 	assert(pPlugin->GetBaseContext() != NULL);
  1279 
  1280 	AddFakeNativesToPlugin(pPlugin);
  1281 
  1282 	List<String>::iterator lib_iter;
  1283 	List<String>::iterator req_iter;
  1284 	List<CPlugin *>::iterator pl_iter;
  1285 	CPlugin *pl;
  1286 	for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
  1287 	{
  1288 		bool found = false;
  1289 		for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
  1290 		{
  1291 			pl = (*pl_iter);
  1292 			for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
  1293 			{
  1294 				if ((*req_iter) == (*lib_iter))
  1295 				{
  1296 					found = true;
  1297 				}
  1298 			}
  1299 		}
  1300 		if (!found)
  1301 		{
  1302 			pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
  1303 			return;
  1304 		}
  1305 	}
  1306 
  1307 	/* Find any unbound natives
  1308 	 * Right now, these are not allowed
  1309 	 */
  1310 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1311 	uint32_t num = pContext->GetNativesNum();
  1312 	sp_native_t *native;
  1313 	for (unsigned int i=0; i<num; i++)
  1314 	{
  1315 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1316 		{
  1317 			break;
  1318 		}
  1319 		if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
  1320 		{
  1321 			pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
  1322 			return;
  1323 		}
  1324 	}
  1325 
  1326 	if (pPlugin->GetStatus() == Plugin_Error)
  1327 	{
  1328 		/* If we got here, all natives are okay again! */
  1329 		pPlugin->m_status = Plugin_Running;
  1330 		if ((pPlugin->m_ctx.ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
  1331 		{
  1332 			pPlugin->m_ctx.ctx->flags &= ~SPFLAG_PLUGIN_PAUSED;
  1333 			_SetPauseState(pPlugin, false);
  1334 		}
  1335 	}
  1336 }
  1337 
  1338 void CPluginManager::AddFakeNativesToPlugin(CPlugin *pPlugin)
  1339 {
  1340 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1341 	sp_nativeinfo_t native;
  1342 
  1343 	List<FakeNative *>::iterator iter;
  1344 	FakeNative *pNative;
  1345 	sp_context_t *ctx;
  1346 	for (iter = m_Natives.begin(); iter != m_Natives.end(); iter++)
  1347 	{
  1348 		pNative = (*iter);
  1349 		ctx = pNative->ctx->GetContext();
  1350 		if ((ctx->flags & SPFLAG_PLUGIN_PAUSED) == SPFLAG_PLUGIN_PAUSED)
  1351 		{
  1352 			/* Ignore natives in paused plugins */
  1353 			continue;
  1354 		}
  1355 		native.name = pNative->name.c_str();
  1356 		native.func = pNative->func;
  1357 		if (pContext->BindNative(&native) == SP_ERROR_NONE)
  1358 		{
  1359 			uint32_t idx;
  1360 			pContext->FindNativeByName(native.name, &idx);
  1361 			if (pPlugin->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL)
  1362 			{
  1363 				WeakNative wkn(pPlugin, idx);
  1364 				GetPluginByCtx(ctx)->m_WeakNatives.push_back(wkn);
  1365 				continue;
  1366 			}
  1367 			/* Add us as a dependency, but we're careful not to do this circularly! */
  1368 			if (pNative->ctx != pContext)
  1369 			{
  1370 				CPlugin *pOther = GetPluginByCtx(ctx);
  1371 				if (pOther->m_dependents.find(pPlugin) == pOther->m_dependents.end())
  1372 				{
  1373 					pOther->m_dependents.push_back(pPlugin);
  1374 				}
  1375 				if (pPlugin->m_dependsOn.find(pOther) == pPlugin->m_dependsOn.end())
  1376 				{
  1377 					pPlugin->m_dependsOn.push_back(pOther);
  1378 				}
  1379 			}
  1380 		}
  1381 	}
  1382 }
  1383 
  1384 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
  1385 {
  1386 	CPlugin *pPlugin = (CPlugin *)plugin;
  1387 
  1388 	/* This prevents removal during insertion or anything else weird */
  1389 	if (m_plugins.find(pPlugin) == m_plugins.end())
  1390 	{
  1391 		return false;
  1392 	}
  1393 
  1394 	/* Remove us from the lookup table and linked list */
  1395 	m_plugins.remove(pPlugin);
  1396 	sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
  1397 
  1398 	/* Go through all dependent plugins and tell them this plugin is now gone */
  1399 	List<CPlugin *>::iterator pl_iter;
  1400 	CPlugin *pOther;
  1401 	for (pl_iter = pPlugin->m_dependents.begin();
  1402 		 pl_iter != pPlugin->m_dependents.end();
  1403 		 pl_iter++)
  1404 	{
  1405 		pOther = (*pl_iter);
  1406 		pOther->DependencyDropped(pPlugin);
  1407 	}
  1408 
  1409 	/* Tell everyone we depend on that we no longer exist */
  1410 	for (pl_iter = pPlugin->m_dependsOn.begin();
  1411 		 pl_iter != pPlugin->m_dependsOn.end();
  1412 		 pl_iter++)
  1413 	{
  1414 		pOther = (*pl_iter);
  1415 		pOther->m_dependents.remove(pPlugin);
  1416 	}
  1417 
  1418 	/* Remove weak references to us */
  1419 	for (pl_iter = m_plugins.begin();
  1420 		 pl_iter != m_plugins.end();
  1421 		 pl_iter++)
  1422 	{
  1423 		pOther = (*pl_iter);
  1424 		List<WeakNative>::iterator wk_iter = pOther->m_WeakNatives.begin();
  1425 		while (wk_iter != pOther->m_WeakNatives.end())
  1426 		{
  1427 			if ((*wk_iter).pl == pPlugin)
  1428 			{
  1429 				wk_iter = pOther->m_WeakNatives.erase(wk_iter);
  1430 			} else {
  1431 				wk_iter++;
  1432 			}
  1433 		}
  1434 	}
  1435 
  1436 	List<IPluginsListener *>::iterator iter;
  1437 	IPluginsListener *pListener;
  1438 
  1439 	if (pPlugin->GetStatus() <= Plugin_Error)
  1440 	{
  1441 		/* Notify listeners of unloading */
  1442 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1443 		{
  1444 			pListener = (*iter);
  1445 			pListener->OnPluginUnloaded(pPlugin);
  1446 		}
  1447 		/* Notify plugin */
  1448 		pPlugin->Call_OnPluginEnd();
  1449 	}
  1450 
  1451 	/* Unbound weak natives */
  1452 	List<WeakNative>::iterator wk_iter;
  1453 	for (wk_iter=pPlugin->m_WeakNatives.begin(); wk_iter!=pPlugin->m_WeakNatives.end(); wk_iter++)
  1454 	{
  1455 		WeakNative & wkn = (*wk_iter);
  1456 		sp_context_t *ctx = wkn.pl->GetContext();
  1457 		ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
  1458 		wkn.pl->m_FakeNativesMissing = true;
  1459 	}
  1460 
  1461 	/* Remove all of our native functions */
  1462 	List<FakeNative *>::iterator fn_iter;
  1463 	FakeNative *pNative;
  1464 	for (fn_iter = pPlugin->m_fakeNatives.begin();
  1465 		fn_iter != pPlugin->m_fakeNatives.end();
  1466 		fn_iter++)
  1467 	{
  1468 		pNative = (*fn_iter);
  1469 		m_Natives.remove(pNative);
  1470 		sm_trie_delete(m_pNativeLookup, pNative->name.c_str());
  1471 		g_pVM->DestroyFakeNative(pNative->func);
  1472 		delete pNative;
  1473 	}
  1474 
  1475 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1476 	{
  1477 		/* Notify listeners of destruction */
  1478 		pListener = (*iter);
  1479 		pListener->OnPluginDestroyed(pPlugin);
  1480 	}
  1481 	
  1482 	/* Tell the plugin to delete itself */
  1483 	delete pPlugin;
  1484 
  1485 	return true;
  1486 }
  1487 
  1488 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
  1489 {
  1490 	IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
  1491 	return pl;
  1492 }
  1493 
  1494 unsigned int CPluginManager::GetPluginCount()
  1495 {
  1496 	return m_plugins.size();
  1497 }
  1498 
  1499 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
  1500 {
  1501 	m_listeners.push_back(listener);
  1502 }
  1503 
  1504 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
  1505 {
  1506 	m_listeners.remove(listener);
  1507 }
  1508 
  1509 IPluginIterator *CPluginManager::GetPluginIterator()
  1510 {
  1511 	if (m_iters.empty())
  1512 	{
  1513 		return new CPluginIterator(&m_plugins);
  1514 	} else {
  1515 		CPluginIterator *iter = m_iters.front();
  1516 		m_iters.pop();
  1517 		iter->Reset();
  1518 		return iter;
  1519 	}
  1520 }
  1521 
  1522 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1523 {
  1524 	m_iters.push(iter);
  1525 }
  1526 
  1527 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1528 {
  1529 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1530 	size_t alias_len = 0;
  1531 	size_t local_len = 0;
  1532 
  1533 	const char *ptr = alias;
  1534 	unsigned int alias_explicit_paths = 0;
  1535 	unsigned int alias_path_end = 0;
  1536 	while (*ptr != '\0')
  1537 	{
  1538 		if (*ptr == '\\' || *ptr == '/')
  1539 		{
  1540 			alias_explicit_paths++;
  1541 			alias_path_end = alias_len;
  1542 		}
  1543 		alias_len++;
  1544 		ptr++;
  1545 	}
  1546 
  1547 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1548 	{
  1549 		/* Trailing slash is totally invalid here */
  1550 		return false;
  1551 	}
  1552 
  1553 	ptr = localpath;
  1554 	unsigned int local_explicit_paths = 0;
  1555 	unsigned int local_path_end = 0;
  1556 	while (*ptr != '\0')
  1557 	{
  1558 		if (*ptr == '\\' || *ptr == '/')
  1559 		{
  1560 			local_explicit_paths++;
  1561 			local_path_end = local_len;
  1562 		}
  1563 		local_len++;
  1564 		ptr++;
  1565 	}
  1566 
  1567 	/* If the alias has more explicit paths than the real path,
  1568 	 * no match will be possible.
  1569 	 */
  1570 	if (alias_explicit_paths > local_explicit_paths)
  1571 	{
  1572 		return false;
  1573 	}
  1574 
  1575 	if (alias_explicit_paths)
  1576 	{
  1577 		/* We need to find if the paths match now.  For example, these should all match:
  1578 		 * csdm     csdm
  1579 		 * csdm     optional/csdm
  1580 		 * csdm/ban optional/crab/csdm/ban
  1581 		*/
  1582 		const char *aliasptr = alias;
  1583 		const char *localptr = localpath;
  1584 		bool match = true;
  1585 		do
  1586 		{
  1587 			if (*aliasptr != *localptr)
  1588 			{
  1589 				/* We have to knock one path off */
  1590 				local_explicit_paths--;
  1591 				if (alias_explicit_paths > local_explicit_paths)
  1592 				{
  1593 					/* Skip out if we're gonna have an impossible match */
  1594 					return false;
  1595 				}
  1596 				/* Eat up localptr tokens until we get a result */
  1597 				while (((localptr - localpath) < (int)local_path_end)
  1598 					&& *localptr != '/'
  1599 					&& *localptr != '\\')
  1600 				{
  1601 					localptr++;
  1602 				}
  1603 				/* Check if we hit the end of our searchable area.
  1604 				 * This probably isn't possible because of the path 
  1605 				 * count check, but it's a good idea anyway.
  1606 				 */
  1607 				if ((localptr - localpath) >= (int)local_path_end)
  1608 				{
  1609 					return false;
  1610 				} else {
  1611 					/* Consume the slash token */
  1612 					localptr++;
  1613 				}
  1614 				/* Reset the alias pointer so we can continue consuming */
  1615 				aliasptr = alias;
  1616 				match = false;
  1617 				continue;
  1618 			}
  1619 			/* Note:
  1620 			 * This is safe because if localptr terminates early, aliasptr will too
  1621 			 */
  1622 			do
  1623 			{
  1624 				/* We should never reach the end of the string because of this check. */
  1625 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1626 				bool localend = (localptr - localpath) > (int)local_path_end;
  1627 				if (aliasend || localend)
  1628 				{
  1629 					if (aliasend && localend)
  1630 					{
  1631 						/* we matched, and we can break out now */
  1632 						match = true;
  1633 						break;
  1634 					}
  1635 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1636 					match = false;
  1637 					break;
  1638 				}
  1639 
  1640 				/* If we got here, it's safe to compare the next two tokens */
  1641 				if (*localptr != *aliasptr)
  1642 				{
  1643 					match = false;
  1644 					break;
  1645 				}
  1646 				localptr++;
  1647 				aliasptr++;
  1648 			} while (true);
  1649 		} while (!match);
  1650 	}
  1651 
  1652 	/* If we got here, it's time to compare filenames */
  1653 	const char *aliasptr = alias;
  1654 	const char *localptr = localpath;
  1655 
  1656 	if (alias_explicit_paths)
  1657 	{
  1658 		aliasptr = &alias[alias_path_end + 1];
  1659 	}
  1660 
  1661 	if (local_explicit_paths)
  1662 	{
  1663 		localptr = &localpath[local_path_end + 1];
  1664 	}
  1665 
  1666 	while (true)
  1667 	{
  1668 		if (*aliasptr == '*')
  1669 		{
  1670 			/* First, see if this is the last character */
  1671 			if ((unsigned)(aliasptr - alias) == alias_len - 1)
  1672 			{
  1673 				/* If so, there's no need to match anything else */
  1674 				return true;
  1675 			}
  1676 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1677 			 * Note that we only need to search up to the next asterisk.
  1678 			 */
  1679 			aliasptr++;
  1680 			bool match = true;
  1681 			const char *local_orig = localptr;
  1682 			do
  1683 			{
  1684 				match = true;
  1685 				while (*aliasptr != '\0' && *aliasptr != '*')
  1686 				{
  1687 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1688 					if (*aliasptr != *localptr)
  1689 					{
  1690 						match = false;
  1691 						break;
  1692 					}
  1693 					aliasptr++;
  1694 					localptr++;
  1695 				}
  1696 				if (!match)
  1697 				{
  1698 					/* If we didn't get a match, we need to advance the search stream.
  1699 					 * This will let us skip tokens while still searching for another match.
  1700 					 */
  1701 					localptr = ++local_orig;
  1702 					/* Make sure we don't go out of bounds */
  1703 					if (*localptr == '\0')
  1704 					{
  1705 						break;
  1706 					}
  1707 				}
  1708 			} while (!match);
  1709 
  1710 			if (!match)
  1711 			{
  1712 				return false;
  1713 			} else {
  1714 				/* If we got a match, move on to the next token */
  1715 				continue;
  1716 			}
  1717 		} else if (*aliasptr == '\0') {
  1718 			if (*localptr == '\0'
  1719 				||
  1720 				strcmp(localptr, ".smx") == 0)
  1721 			{
  1722 				return true;
  1723 			} else {
  1724 				return false;
  1725 			}
  1726 		} else if (*aliasptr != *localptr) {
  1727 			return false;
  1728 		}
  1729 		aliasptr++;
  1730 		localptr++;
  1731 	}
  1732 
  1733 	return true;
  1734 }
  1735 
  1736 bool CPluginManager::IsLateLoadTime() const
  1737 {
  1738 	return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
  1739 }
  1740 
  1741 void CPluginManager::OnSourceModAllInitialized()
  1742 {
  1743 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1744 
  1745 	HandleAccess sec;
  1746 	g_HandleSys.InitAccessDefaults(NULL, &sec);
  1747 
  1748 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1749 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1750 
  1751 	g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1752 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1753 
  1754 	g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
  1755 
  1756 	g_ShareSys.AddInterface(NULL, this);
  1757 }
  1758 
  1759 void CPluginManager::OnSourceModShutdown()
  1760 {
  1761 	g_RootMenu.RemoveRootConsoleCommand("plugins", this);
  1762 
  1763 	List<CPlugin *>::iterator iter;
  1764 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  1765 	{
  1766 		UnloadPlugin((*iter));
  1767 	}
  1768 
  1769 	g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
  1770 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1771 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1772 }
  1773 
  1774 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1775 {
  1776 	/* We don't care about the internal object, actually */
  1777 }
  1778 
  1779 void CPluginManager::RegisterNativesFromCore(sp_nativeinfo_t *natives)
  1780 {
  1781 	m_natives.push_back(natives);
  1782 }
  1783 
  1784 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1785 {
  1786 	IPlugin *pPlugin;
  1787 	HandleError _err;
  1788 
  1789 	HandleSecurity sec;
  1790 
  1791 	sec.pOwner = NULL;
  1792 	sec.pIdentity = m_MyIdent;
  1793 
  1794 	if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1795 	{
  1796 		pPlugin = NULL;
  1797 	}
  1798 
  1799 	if (err)
  1800 	{
  1801 		*err = _err;
  1802 	}
  1803 
  1804 	return pPlugin;
  1805 }
  1806 
  1807 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1808 {
  1809 	if (num < 1 || num > (int)GetPluginCount())
  1810 	{
  1811 		return NULL;
  1812 	}
  1813 
  1814 	CPlugin *pl;
  1815 	int id = 1;
  1816 
  1817 	IPluginIterator *iter = GetPluginIterator();
  1818 	for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++) {}
  1819 
  1820 	pl = (CPlugin *)(iter->GetPlugin());
  1821 	iter->Release();
  1822 
  1823 	return pl;
  1824 }
  1825 
  1826 const char *CPluginManager::GetStatusText(PluginStatus st)
  1827 {
  1828 	switch (st)
  1829 	{
  1830 	case Plugin_Running:
  1831 		return "Running";
  1832 	case Plugin_Paused:
  1833 		return "Paused";
  1834 	case Plugin_Error:
  1835 		return "Error";
  1836 	case Plugin_Uncompiled:
  1837 		return "Uncompiled";
  1838 	case Plugin_BadLoad:
  1839 		return "Bad Load";
  1840 	case Plugin_Failed:
  1841 		return "Failed";
  1842 	default:
  1843 		assert(false);
  1844 		return "-";
  1845 	}
  1846 }
  1847 
  1848 void CPluginManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
  1849 {
  1850 	if (argcount >= 3)
  1851 	{
  1852 		const char *cmd = g_RootMenu.GetArgument(2);
  1853 		if (strcmp(cmd, "list") == 0)
  1854 		{
  1855 			char buffer[256];
  1856 			unsigned int id = 1;
  1857 			int plnum = GetPluginCount();
  1858 
  1859 			if (!plnum)
  1860 			{
  1861 				g_RootMenu.ConsolePrint("[SM] No plugins loaded");
  1862 				return;
  1863 			} else {
  1864 				g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
  1865 			}
  1866 
  1867 			IPluginIterator *iter = GetPluginIterator();
  1868 			for (; iter->MorePlugins(); iter->NextPlugin(), id++)
  1869 			{
  1870 				IPlugin *pl = iter->GetPlugin();
  1871 				assert(pl->GetStatus() != Plugin_Created);
  1872 				int len = 0;
  1873 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  1874 				if (pl->GetStatus() != Plugin_Running)
  1875 				{
  1876 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d <%s>", id, GetStatusText(pl->GetStatus()));
  1877 				} else {
  1878 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d", id);
  1879 				}
  1880 				len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  1881 				if (IS_STR_FILLED(info->version))
  1882 				{
  1883 					len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  1884 				}
  1885 				if (IS_STR_FILLED(info->author))
  1886 				{
  1887 					UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  1888 				}
  1889 				g_RootMenu.ConsolePrint("%s", buffer);
  1890 			}
  1891 
  1892 			iter->Release();
  1893 			return;
  1894 		} else if (strcmp(cmd, "load") == 0) {
  1895 			if (argcount < 4)
  1896 			{
  1897 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
  1898 				return;
  1899 			}
  1900 
  1901 			char error[128];
  1902 			bool wasloaded;
  1903 			const char *filename = g_RootMenu.GetArgument(3);
  1904 
  1905 			char pluginfile[256];
  1906 			const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
  1907 			UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
  1908 
  1909 			IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
  1910 
  1911 			if (wasloaded)
  1912 			{
  1913 				g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
  1914 				return;
  1915 			}
  1916 
  1917 			if (pl)
  1918 			{
  1919 				g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
  1920 			} else {
  1921 				g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
  1922 			}
  1923 
  1924 			return;
  1925 		} else if (strcmp(cmd, "unload") == 0) {
  1926 			if (argcount < 4)
  1927 			{
  1928 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#>");
  1929 				return;
  1930 			}
  1931 
  1932 			int id = 1;
  1933 			int num = atoi(g_RootMenu.GetArgument(3));
  1934 			if (num < 1 || num > (int)GetPluginCount())
  1935 			{
  1936 				g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", num);
  1937 				return;
  1938 			}
  1939 
  1940 			IPluginIterator *iter = GetPluginIterator();
  1941 			for (; iter->MorePlugins() && id<num; iter->NextPlugin(), id++)
  1942 				;
  1943 			IPlugin *pl = iter->GetPlugin();
  1944 
  1945 			char name[PLATFORM_MAX_PATH];
  1946 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  1947 			strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  1948 
  1949 			if (UnloadPlugin(pl))
  1950 			{
  1951 				g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
  1952 			} else {
  1953 				g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
  1954 			}
  1955 
  1956 			iter->Release();
  1957 			return;
  1958 		} else if (strcmp(cmd, "info") == 0) {
  1959 			if (argcount < 4)
  1960 			{
  1961 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
  1962 				return;
  1963 			}
  1964 
  1965 			int num = atoi(g_RootMenu.GetArgument(3));
  1966 			if (num < 1 || num > (int)GetPluginCount())
  1967 			{
  1968 				g_RootMenu.ConsolePrint("[SM] Plugin index not found.");
  1969 				return;
  1970 			}
  1971 
  1972 			CPlugin *pl = GetPluginByOrder(num);
  1973 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  1974 
  1975 			g_RootMenu.ConsolePrint("  Filename: %s", pl->GetFilename());
  1976 			if (pl->GetStatus() <= Plugin_Error)
  1977 			{
  1978 				if (IS_STR_FILLED(info->name))
  1979 				{
  1980 					if (IS_STR_FILLED(info->description))
  1981 					{
  1982 						g_RootMenu.ConsolePrint("  Title: %s (%s)", info->name, info->description);
  1983 					} else {
  1984 						g_RootMenu.ConsolePrint("  Title: %s", info->name);
  1985 					}
  1986 				}
  1987 				if (IS_STR_FILLED(info->author))
  1988 				{
  1989 					g_RootMenu.ConsolePrint("  Author: %s", info->author);
  1990 				}
  1991 				if (IS_STR_FILLED(info->version))
  1992 				{
  1993 					g_RootMenu.ConsolePrint("  Version: %s", info->version);
  1994 				}
  1995 				if (IS_STR_FILLED(info->url))
  1996 				{
  1997 					g_RootMenu.ConsolePrint("  URL: %s", info->url);
  1998 				}
  1999 				if (pl->GetStatus() == Plugin_Error)
  2000 				{
  2001 					g_RootMenu.ConsolePrint("  Error: %s", pl->m_errormsg);
  2002 				} else {
  2003 					g_RootMenu.ConsolePrint("  Debugging: %s", pl->IsDebugging() ? "Yes" : "No");
  2004 					g_RootMenu.ConsolePrint("  Running: %s", pl->GetStatus() == Plugin_Running ? "Yes" : "No");
  2005 
  2006 					const char *typestr = "";
  2007 					switch (pl->GetType())
  2008 					{
  2009 					case PluginType_MapUpdated:
  2010 						typestr = "Map Change if Updated";
  2011 						break;
  2012 					case PluginType_MapOnly:
  2013 						typestr = "Map Change";
  2014 						break;
  2015 					case PluginType_Private:
  2016 					case PluginType_Global:
  2017 						typestr = "Never";
  2018 						break;
  2019 					}
  2020 
  2021 					g_RootMenu.ConsolePrint("  Reloads: %s", typestr);
  2022 				}
  2023 			} else {
  2024 				g_RootMenu.ConsolePrint("  Load error: %s", pl->m_errormsg);
  2025 				g_RootMenu.ConsolePrint("  File info: (title \"%s\") (version \"%s\")", 
  2026 										info->name ? info->name : "<none>",
  2027 										info->version ? info->version : "<none>");
  2028 				if (IS_STR_FILLED(info->url))
  2029 				{
  2030 					g_RootMenu.ConsolePrint("  File URL: %s", info->url);
  2031 				}
  2032 			}
  2033 
  2034 			return;
  2035 		} else if (strcmp(cmd, "debug") == 0) {
  2036 			if (argcount < 5)
  2037 			{
  2038 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
  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 			int res;
  2050 			const char *mode = g_RootMenu.GetArgument(4);
  2051 			if ((res=strcmp("on", mode)) && strcmp("off", mode))
  2052 			{
  2053 				g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
  2054 				return;
  2055 			}
  2056 
  2057 			bool debug;
  2058 			if (!res)
  2059 			{
  2060 				debug = true;
  2061 			} else {
  2062 				debug = false;
  2063 			}
  2064 
  2065 			CPlugin *pl = GetPluginByOrder(num);
  2066 			if (debug && pl->IsDebugging())
  2067 			{
  2068 				g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
  2069 				return;
  2070 			} else if (!debug && !pl->IsDebugging()) {
  2071 				g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
  2072 				return;
  2073 			}
  2074 
  2075 			char error[256];
  2076 			if (pl->ToggleDebugMode(debug, error, sizeof(error)))
  2077 			{
  2078 				g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
  2079 				return;
  2080 			} else {
  2081 				g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
  2082 				g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
  2083 				return;
  2084 			}
  2085 		}
  2086 	}
  2087 
  2088 	/* Draw the main menu */
  2089 	g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
  2090 	g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
  2091 	g_RootMenu.DrawGenericOption("load", "Load a plugin");
  2092 	g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
  2093 	g_RootMenu.DrawGenericOption("info", "Information about a plugin");
  2094 	g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
  2095 }
  2096 
  2097 void CPluginManager::ReloadOrUnloadPlugins()
  2098 {
  2099 	List<CPlugin *>::iterator iter;
  2100 	List<CPlugin *> tmp_list = m_plugins;
  2101 	CPlugin *pl;
  2102 	time_t t;
  2103 
  2104 	for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
  2105 	{
  2106 		pl = (*iter);
  2107 		if (pl->GetType() ==  PluginType_MapOnly)
  2108 		{
  2109 			UnloadPlugin((IPlugin *)pl);
  2110 		} else if (pl->GetType() == PluginType_MapUpdated) {
  2111 			t = pl->GetFileTimeStamp();
  2112 			if (!t || t > pl->GetTimeStamp())
  2113 			{
  2114 				pl->SetTimeStamp(t);
  2115 				UnloadPlugin((IPlugin *)pl);
  2116 			}
  2117 		}
  2118 	}
  2119 }
  2120 
  2121 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
  2122 {
  2123 	List<IPluginsListener *>::iterator iter;
  2124 	IPluginsListener *pListener;
  2125 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  2126 	{
  2127 		pListener = (*iter);
  2128 		pListener->OnPluginPauseChange(pl, paused);
  2129 	}	
  2130 }
  2131 
  2132 bool CPluginManager::AddFakeNative(IPluginFunction *pFunction, const char *name, SPVM_FAKENATIVE_FUNC func)
  2133 {
  2134 	if (sm_trie_retrieve(m_pNativeLookup, name, NULL))
  2135 	{
  2136 		return false;
  2137 	}
  2138 
  2139 	FakeNative *pNative = new FakeNative;
  2140 
  2141 	pNative->func = g_pVM->CreateFakeNative(func, pNative);
  2142 	if (!pNative->func)
  2143 	{
  2144 		delete pNative;
  2145 		return false;
  2146 	}
  2147 
  2148 	pNative->call = pFunction;
  2149 	pNative->name.assign(name);
  2150 	pNative->ctx = pFunction->GetParentContext();
  2151 
  2152 	m_Natives.push_back(pNative);
  2153 	sm_trie_insert(m_pNativeLookup, name,pNative);
  2154 
  2155 	CPlugin *pPlugin = GetPluginByCtx(pNative->ctx->GetContext());
  2156 	pPlugin->m_fakeNatives.push_back(pNative);
  2157 
  2158 	return true;
  2159 }
  2160 
  2161 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
  2162 {
  2163 	List<CPlugin *>::iterator iter;
  2164 	CPlugin *pPlugin;
  2165 	IPluginFunction *pFunction;
  2166 
  2167 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2168 	{
  2169 		pPlugin = (*iter);
  2170 
  2171 		if (pPlugin->GetStatus() <= Plugin_Paused)
  2172 		{
  2173 			pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
  2174 
  2175 			if (pFunction)
  2176 			{
  2177 				pForward->AddFunction(pFunction);
  2178 			}
  2179 		}
  2180 	}
  2181 }
  2182 
  2183 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
  2184 {
  2185 	if (pToken->type != g_PluginIdent)
  2186 	{
  2187 		return NULL;
  2188 	}
  2189 
  2190 	return (CPlugin *)(pToken->ptr);
  2191 }
  2192 
  2193 void CPluginManager::ExecAndGenPluginConfs()
  2194 {
  2195 	List<CPlugin *>::iterator iter;
  2196 
  2197 	//for (iter = 
  2198 }