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