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