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