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