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