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